worktree.c: get_worktrees() takes a new flag argument
[git/git.git] / builtin / worktree.c
CommitLineData
df0b6cfb
NTND
1#include "cache.h"
2#include "builtin.h"
3#include "dir.h"
4#include "parse-options.h"
fc56361f 5#include "argv-array.h"
f7c9dac1
ES
6#include "branch.h"
7#include "refs.h"
fc56361f 8#include "run-command.h"
b979d950 9#include "sigchain.h"
799767cc 10#include "refs.h"
bb9c03b8
MR
11#include "utf8.h"
12#include "worktree.h"
df0b6cfb
NTND
13
14static const char * const worktree_usage[] = {
ae9f2745 15 N_("git worktree add [<options>] <path> [<branch>]"),
bb9c03b8 16 N_("git worktree list [<options>]"),
58142c09 17 N_("git worktree lock [<options>] <path>"),
7b722d90 18 N_("git worktree prune [<options>]"),
6d308627 19 N_("git worktree unlock <path>"),
df0b6cfb
NTND
20 NULL
21};
22
5dd6e234
ES
23struct add_opts {
24 int force;
25 int detach;
ef2a0ac9 26 int checkout;
5dd6e234
ES
27 const char *new_branch;
28 int force_new_branch;
29};
30
df0b6cfb
NTND
31static int show_only;
32static int verbose;
33static unsigned long expire;
34
35static int prune_worktree(const char *id, struct strbuf *reason)
36{
37 struct stat st;
38 char *path;
39 int fd, len;
40
41 if (!is_directory(git_path("worktrees/%s", id))) {
42 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
43 return 1;
44 }
45 if (file_exists(git_path("worktrees/%s/locked", id)))
46 return 0;
47 if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
48 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
49 return 1;
50 }
51 fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
52 if (fd < 0) {
53 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
54 id, strerror(errno));
55 return 1;
56 }
57 len = st.st_size;
3733e694 58 path = xmallocz(len);
df0b6cfb
NTND
59 read_in_full(fd, path, len);
60 close(fd);
61 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
62 len--;
63 if (!len) {
64 strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
65 free(path);
66 return 1;
67 }
68 path[len] = '\0';
69 if (!file_exists(path)) {
70 struct stat st_link;
71 free(path);
72 /*
73 * the repo is moved manually and has not been
74 * accessed since?
75 */
76 if (!stat(git_path("worktrees/%s/link", id), &st_link) &&
77 st_link.st_nlink > 1)
78 return 0;
79 if (st.st_mtime <= expire) {
80 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
81 return 1;
82 } else {
83 return 0;
84 }
85 }
86 free(path);
87 return 0;
88}
89
90static void prune_worktrees(void)
91{
92 struct strbuf reason = STRBUF_INIT;
93 struct strbuf path = STRBUF_INIT;
94 DIR *dir = opendir(git_path("worktrees"));
95 struct dirent *d;
96 int ret;
97 if (!dir)
98 return;
99 while ((d = readdir(dir)) != NULL) {
afb9e30b 100 if (is_dot_or_dotdot(d->d_name))
df0b6cfb
NTND
101 continue;
102 strbuf_reset(&reason);
103 if (!prune_worktree(d->d_name, &reason))
104 continue;
105 if (show_only || verbose)
106 printf("%s\n", reason.buf);
107 if (show_only)
108 continue;
109 strbuf_reset(&path);
110 strbuf_addstr(&path, git_path("worktrees/%s", d->d_name));
111 ret = remove_dir_recursively(&path, 0);
112 if (ret < 0 && errno == ENOTDIR)
113 ret = unlink(path.buf);
114 if (ret)
8d19e930 115 error_errno(_("failed to remove '%s'"), path.buf);
df0b6cfb
NTND
116 }
117 closedir(dir);
118 if (!show_only)
119 rmdir(git_path("worktrees"));
120 strbuf_release(&reason);
121 strbuf_release(&path);
122}
123
124static int prune(int ac, const char **av, const char *prefix)
125{
126 struct option options[] = {
127 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
128 OPT__VERBOSE(&verbose, N_("report pruned objects")),
129 OPT_EXPIRY_DATE(0, "expire", &expire,
130 N_("expire objects older than <time>")),
131 OPT_END()
132 };
133
134 expire = ULONG_MAX;
135 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
136 if (ac)
137 usage_with_options(worktree_usage, options);
138 prune_worktrees();
139 return 0;
140}
141
b979d950
ES
142static char *junk_work_tree;
143static char *junk_git_dir;
144static int is_junk;
145static pid_t junk_pid;
146
147static void remove_junk(void)
148{
149 struct strbuf sb = STRBUF_INIT;
150 if (!is_junk || getpid() != junk_pid)
151 return;
152 if (junk_git_dir) {
153 strbuf_addstr(&sb, junk_git_dir);
154 remove_dir_recursively(&sb, 0);
155 strbuf_reset(&sb);
156 }
157 if (junk_work_tree) {
158 strbuf_addstr(&sb, junk_work_tree);
159 remove_dir_recursively(&sb, 0);
160 }
161 strbuf_release(&sb);
162}
163
164static void remove_junk_on_signal(int signo)
165{
166 remove_junk();
167 sigchain_pop(signo);
168 raise(signo);
169}
170
f5682b2a
ES
171static const char *worktree_basename(const char *path, int *olen)
172{
173 const char *name;
174 int len;
175
176 len = strlen(path);
177 while (len && is_dir_sep(path[len - 1]))
178 len--;
179
180 for (name = path + len - 1; name > path; name--)
181 if (is_dir_sep(*name)) {
182 name++;
183 break;
184 }
185
186 *olen = len;
187 return name;
188}
189
80a0548f 190static int add_worktree(const char *path, const char *refname,
5dd6e234 191 const struct add_opts *opts)
b979d950
ES
192{
193 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
194 struct strbuf sb = STRBUF_INIT;
195 const char *name;
196 struct stat st;
542aa25d 197 struct child_process cp = CHILD_PROCESS_INIT;
ae2a3827 198 struct argv_array child_env = ARGV_ARRAY_INIT;
b979d950 199 int counter = 0, len, ret;
f7c9dac1
ES
200 struct strbuf symref = STRBUF_INIT;
201 struct commit *commit = NULL;
b979d950
ES
202
203 if (file_exists(path) && !is_empty_dir(path))
204 die(_("'%s' already exists"), path);
205
f7c9dac1 206 /* is 'refname' a branch or commit? */
0ebf4a2a 207 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
f7c9dac1
ES
208 ref_exists(symref.buf)) { /* it's a branch */
209 if (!opts->force)
8d9fdd70 210 die_if_checked_out(symref.buf, 0);
f7c9dac1
ES
211 } else { /* must be a commit */
212 commit = lookup_commit_reference_by_name(refname);
213 if (!commit)
214 die(_("invalid reference: %s"), refname);
215 }
216
f5682b2a 217 name = worktree_basename(path, &len);
b979d950
ES
218 strbuf_addstr(&sb_repo,
219 git_path("worktrees/%.*s", (int)(path + len - name), name));
220 len = sb_repo.len;
221 if (safe_create_leading_directories_const(sb_repo.buf))
222 die_errno(_("could not create leading directories of '%s'"),
223 sb_repo.buf);
224 while (!stat(sb_repo.buf, &st)) {
225 counter++;
226 strbuf_setlen(&sb_repo, len);
227 strbuf_addf(&sb_repo, "%d", counter);
228 }
229 name = strrchr(sb_repo.buf, '/') + 1;
230
231 junk_pid = getpid();
232 atexit(remove_junk);
233 sigchain_push_common(remove_junk_on_signal);
234
235 if (mkdir(sb_repo.buf, 0777))
236 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
237 junk_git_dir = xstrdup(sb_repo.buf);
238 is_junk = 1;
239
240 /*
241 * lock the incomplete repo so prune won't delete it, unlock
242 * after the preparation is over.
243 */
244 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
1f76a10b 245 write_file(sb.buf, "initializing");
b979d950
ES
246
247 strbuf_addf(&sb_git, "%s/.git", path);
248 if (safe_create_leading_directories_const(sb_git.buf))
249 die_errno(_("could not create leading directories of '%s'"),
250 sb_git.buf);
251 junk_work_tree = xstrdup(path);
252
253 strbuf_reset(&sb);
254 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
1f76a10b
JH
255 write_file(sb.buf, "%s", real_path(sb_git.buf));
256 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
b979d950
ES
257 real_path(get_git_common_dir()), name);
258 /*
259 * This is to keep resolve_ref() happy. We need a valid HEAD
ed197a6a
ES
260 * or is_git_directory() will reject the directory. Any value which
261 * looks like an object ID will do since it will be immediately
262 * replaced by the symbolic-ref or update-ref invocation in the new
263 * worktree.
b979d950 264 */
b979d950
ES
265 strbuf_reset(&sb);
266 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
dabd35f4 267 write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
b979d950
ES
268 strbuf_reset(&sb);
269 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
1f76a10b 270 write_file(sb.buf, "../..");
b979d950 271
cd2f4713 272 fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
b979d950 273
ae2a3827
ES
274 argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
275 argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
b979d950 276 cp.git_cmd = 1;
7f44e3d1
ES
277
278 if (commit)
279 argv_array_pushl(&cp.args, "update-ref", "HEAD",
f2fd0760 280 oid_to_hex(&commit->object.oid), NULL);
7f44e3d1
ES
281 else
282 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
283 symref.buf, NULL);
284 cp.env = child_env.argv;
285 ret = run_command(&cp);
286 if (ret)
287 goto done;
288
ef2a0ac9
RZ
289 if (opts->checkout) {
290 cp.argv = NULL;
291 argv_array_clear(&cp.args);
292 argv_array_pushl(&cp.args, "reset", "--hard", NULL);
293 cp.env = child_env.argv;
294 ret = run_command(&cp);
295 if (ret)
296 goto done;
b979d950 297 }
ef2a0ac9
RZ
298
299 is_junk = 0;
300 free(junk_work_tree);
301 free(junk_git_dir);
302 junk_work_tree = NULL;
303 junk_git_dir = NULL;
304
7f44e3d1 305done:
b979d950
ES
306 strbuf_reset(&sb);
307 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
308 unlink_or_warn(sb.buf);
ae2a3827 309 argv_array_clear(&child_env);
b979d950 310 strbuf_release(&sb);
f7c9dac1 311 strbuf_release(&symref);
b979d950
ES
312 strbuf_release(&sb_repo);
313 strbuf_release(&sb_git);
314 return ret;
315}
316
fc56361f
ES
317static int add(int ac, const char **av, const char *prefix)
318{
5dd6e234
ES
319 struct add_opts opts;
320 const char *new_branch_force = NULL;
fc56361f 321 const char *path, *branch;
fc56361f 322 struct option options[] = {
5dd6e234
ES
323 OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
324 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
cbdf60fa
ES
325 N_("create a new branch")),
326 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
327 N_("create or reset a branch")),
5dd6e234 328 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
ef2a0ac9 329 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
fc56361f
ES
330 OPT_END()
331 };
332
5dd6e234 333 memset(&opts, 0, sizeof(opts));
ef2a0ac9 334 opts.checkout = 1;
fc56361f 335 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
ab0b2c53
ES
336 if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
337 die(_("-b, -B, and --detach are mutually exclusive"));
0f4af3b9
ES
338 if (ac < 1 || ac > 2)
339 usage_with_options(worktree_usage, options);
fc56361f 340
0409e0b6 341 path = prefix_filename(prefix, strlen(prefix), av[0]);
0f4af3b9 342 branch = ac < 2 ? "HEAD" : av[1];
fc56361f 343
1a450e2f
JDG
344 if (!strcmp(branch, "-"))
345 branch = "@{-1}";
346
5dd6e234 347 opts.force_new_branch = !!new_branch_force;
beb6f24b
NTND
348 if (opts.force_new_branch) {
349 struct strbuf symref = STRBUF_INIT;
350
5dd6e234 351 opts.new_branch = new_branch_force;
eef005dc 352
beb6f24b
NTND
353 if (!opts.force &&
354 !strbuf_check_branch_ref(&symref, opts.new_branch) &&
355 ref_exists(symref.buf))
8d9fdd70 356 die_if_checked_out(symref.buf, 0);
beb6f24b
NTND
357 strbuf_release(&symref);
358 }
359
5c942570 360 if (ac < 2 && !opts.new_branch && !opts.detach) {
1eb07d82
ES
361 int n;
362 const char *s = worktree_basename(path, &n);
5dd6e234 363 opts.new_branch = xstrndup(s, n);
1eb07d82
ES
364 }
365
c2842439 366 if (opts.new_branch) {
542aa25d 367 struct child_process cp = CHILD_PROCESS_INIT;
c2842439
ES
368 cp.git_cmd = 1;
369 argv_array_push(&cp.args, "branch");
370 if (opts.force_new_branch)
371 argv_array_push(&cp.args, "--force");
372 argv_array_push(&cp.args, opts.new_branch);
373 argv_array_push(&cp.args, branch);
374 if (run_command(&cp))
375 return -1;
376 branch = opts.new_branch;
1eb07d82
ES
377 }
378
80a0548f 379 return add_worktree(path, branch, &opts);
fc56361f
ES
380}
381
bb9c03b8
MR
382static void show_worktree_porcelain(struct worktree *wt)
383{
384 printf("worktree %s\n", wt->path);
385 if (wt->is_bare)
386 printf("bare\n");
387 else {
388 printf("HEAD %s\n", sha1_to_hex(wt->head_sha1));
389 if (wt->is_detached)
390 printf("detached\n");
a234563a 391 else if (wt->head_ref)
bb9c03b8
MR
392 printf("branch %s\n", wt->head_ref);
393 }
394 printf("\n");
395}
396
397static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
398{
399 struct strbuf sb = STRBUF_INIT;
400 int cur_path_len = strlen(wt->path);
401 int path_adj = cur_path_len - utf8_strwidth(wt->path);
402
403 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
404 if (wt->is_bare)
405 strbuf_addstr(&sb, "(bare)");
406 else {
407 strbuf_addf(&sb, "%-*s ", abbrev_len,
408 find_unique_abbrev(wt->head_sha1, DEFAULT_ABBREV));
96f09e2a 409 if (wt->is_detached)
bb9c03b8 410 strbuf_addstr(&sb, "(detached HEAD)");
a234563a 411 else if (wt->head_ref)
96f09e2a 412 strbuf_addf(&sb, "[%s]", shorten_unambiguous_ref(wt->head_ref, 0));
a234563a
NTND
413 else
414 strbuf_addstr(&sb, "(error)");
bb9c03b8
MR
415 }
416 printf("%s\n", sb.buf);
417
418 strbuf_release(&sb);
419}
420
421static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
422{
423 int i;
424
425 for (i = 0; wt[i]; i++) {
426 int sha1_len;
427 int path_len = strlen(wt[i]->path);
428
429 if (path_len > *maxlen)
430 *maxlen = path_len;
431 sha1_len = strlen(find_unique_abbrev(wt[i]->head_sha1, *abbrev));
432 if (sha1_len > *abbrev)
433 *abbrev = sha1_len;
434 }
435}
436
437static int list(int ac, const char **av, const char *prefix)
438{
439 int porcelain = 0;
440
441 struct option options[] = {
442 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
443 OPT_END()
444 };
445
446 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
447 if (ac)
448 usage_with_options(worktree_usage, options);
449 else {
4fff1ef7 450 struct worktree **worktrees = get_worktrees(0);
bb9c03b8
MR
451 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
452
453 if (!porcelain)
454 measure_widths(worktrees, &abbrev, &path_maxlen);
455
456 for (i = 0; worktrees[i]; i++) {
457 if (porcelain)
458 show_worktree_porcelain(worktrees[i]);
459 else
460 show_worktree(worktrees[i], path_maxlen, abbrev);
461 }
462 free_worktrees(worktrees);
463 }
464 return 0;
465}
466
58142c09
NTND
467static int lock_worktree(int ac, const char **av, const char *prefix)
468{
469 const char *reason = "", *old_reason;
470 struct option options[] = {
471 OPT_STRING(0, "reason", &reason, N_("string"),
472 N_("reason for locking")),
473 OPT_END()
474 };
475 struct worktree **worktrees, *wt;
476
477 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
478 if (ac != 1)
479 usage_with_options(worktree_usage, options);
480
4fff1ef7 481 worktrees = get_worktrees(0);
58142c09
NTND
482 wt = find_worktree(worktrees, prefix, av[0]);
483 if (!wt)
484 die(_("'%s' is not a working tree"), av[0]);
485 if (is_main_worktree(wt))
486 die(_("The main working tree cannot be locked or unlocked"));
487
488 old_reason = is_worktree_locked(wt);
489 if (old_reason) {
490 if (*old_reason)
491 die(_("'%s' is already locked, reason: %s"),
492 av[0], old_reason);
493 die(_("'%s' is already locked"), av[0]);
494 }
495
496 write_file(git_common_path("worktrees/%s/locked", wt->id),
497 "%s", reason);
498 free_worktrees(worktrees);
499 return 0;
500}
501
6d308627
NTND
502static int unlock_worktree(int ac, const char **av, const char *prefix)
503{
504 struct option options[] = {
505 OPT_END()
506 };
507 struct worktree **worktrees, *wt;
508 int ret;
509
510 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
511 if (ac != 1)
512 usage_with_options(worktree_usage, options);
513
4fff1ef7 514 worktrees = get_worktrees(0);
6d308627
NTND
515 wt = find_worktree(worktrees, prefix, av[0]);
516 if (!wt)
517 die(_("'%s' is not a working tree"), av[0]);
518 if (is_main_worktree(wt))
519 die(_("The main working tree cannot be locked or unlocked"));
520 if (!is_worktree_locked(wt))
521 die(_("'%s' is not locked"), av[0]);
522 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
523 free_worktrees(worktrees);
524 return ret;
525}
526
df0b6cfb
NTND
527int cmd_worktree(int ac, const char **av, const char *prefix)
528{
529 struct option options[] = {
530 OPT_END()
531 };
532
d49028e6
JH
533 git_config(git_default_config, NULL);
534
df0b6cfb
NTND
535 if (ac < 2)
536 usage_with_options(worktree_usage, options);
0409e0b6
NTND
537 if (!prefix)
538 prefix = "";
fc56361f
ES
539 if (!strcmp(av[1], "add"))
540 return add(ac - 1, av + 1, prefix);
df0b6cfb
NTND
541 if (!strcmp(av[1], "prune"))
542 return prune(ac - 1, av + 1, prefix);
bb9c03b8
MR
543 if (!strcmp(av[1], "list"))
544 return list(ac - 1, av + 1, prefix);
58142c09
NTND
545 if (!strcmp(av[1], "lock"))
546 return lock_worktree(ac - 1, av + 1, prefix);
6d308627
NTND
547 if (!strcmp(av[1], "unlock"))
548 return unlock_worktree(ac - 1, av + 1, prefix);
df0b6cfb
NTND
549 usage_with_options(worktree_usage, options);
550}