1#include "cache.h"
2#include "checkout.h"
3#include "config.h"
4#include "builtin.h"
5#include "dir.h"
6#include "parse-options.h"
7#include "argv-array.h"
8#include "branch.h"
9#include "refs.h"
10#include "run-command.h"
11#include "sigchain.h"
12#include "refs.h"
13#include "utf8.h"
14#include "worktree.h"
15
16static const char * const worktree_usage[] = {
17 N_("git worktree add [<options>] <path> [<branch>]"),
18 N_("git worktree list [<options>]"),
19 N_("git worktree lock [<options>] <path>"),
20 N_("git worktree move <worktree> <new-path>"),
21 N_("git worktree prune [<options>]"),
22 N_("git worktree unlock <path>"),
23 NULL
24};
25
26struct add_opts {
27 int force;
28 int detach;
29 int checkout;
30 int keep_locked;
31 const char *new_branch;
32 int force_new_branch;
33};
34
35static int show_only;
36static int verbose;
37static int guess_remote;
38static timestamp_t expire;
39
40static int git_worktree_config(const char *var, const char *value, void *cb)
41{
42 if (!strcmp(var, "worktree.guessremote")) {
43 guess_remote = git_config_bool(var, value);
44 return 0;
45 }
46
47 return git_default_config(var, value, cb);
48}
49
50static int prune_worktree(const char *id, struct strbuf *reason)
51{
52 struct stat st;
53 char *path;
54 int fd;
55 size_t len;
56 ssize_t read_result;
57
58 if (!is_directory(git_path("worktrees/%s", id))) {
59 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
60 return 1;
61 }
62 if (file_exists(git_path("worktrees/%s/locked", id)))
63 return 0;
64 if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
65 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
66 return 1;
67 }
68 fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
69 if (fd < 0) {
70 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
71 id, strerror(errno));
72 return 1;
73 }
74 len = xsize_t(st.st_size);
75 path = xmallocz(len);
76
77 read_result = read_in_full(fd, path, len);
78 if (read_result < 0) {
79 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
80 id, strerror(errno));
81 close(fd);
82 free(path);
83 return 1;
84 }
85 close(fd);
86
87 if (read_result != len) {
88 strbuf_addf(reason,
89 _("Removing worktrees/%s: short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
90 id, (uintmax_t)len, (uintmax_t)read_result);
91 free(path);
92 return 1;
93 }
94 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
95 len--;
96 if (!len) {
97 strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
98 free(path);
99 return 1;
100 }
101 path[len] = '\0';
102 if (!file_exists(path)) {
103 struct stat st_link;
104 free(path);
105 /*
106 * the repo is moved manually and has not been
107 * accessed since?
108 */
109 if (!stat(git_path("worktrees/%s/link", id), &st_link) &&
110 st_link.st_nlink > 1)
111 return 0;
112 if (st.st_mtime <= expire) {
113 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
114 return 1;
115 } else {
116 return 0;
117 }
118 }
119 free(path);
120 return 0;
121}
122
123static void prune_worktrees(void)
124{
125 struct strbuf reason = STRBUF_INIT;
126 struct strbuf path = STRBUF_INIT;
127 DIR *dir = opendir(git_path("worktrees"));
128 struct dirent *d;
129 int ret;
130 if (!dir)
131 return;
132 while ((d = readdir(dir)) != NULL) {
133 if (is_dot_or_dotdot(d->d_name))
134 continue;
135 strbuf_reset(&reason);
136 if (!prune_worktree(d->d_name, &reason))
137 continue;
138 if (show_only || verbose)
139 printf("%s\n", reason.buf);
140 if (show_only)
141 continue;
142 git_path_buf(&path, "worktrees/%s", d->d_name);
143 ret = remove_dir_recursively(&path, 0);
144 if (ret < 0 && errno == ENOTDIR)
145 ret = unlink(path.buf);
146 if (ret)
147 error_errno(_("failed to remove '%s'"), path.buf);
148 }
149 closedir(dir);
150 if (!show_only)
151 rmdir(git_path("worktrees"));
152 strbuf_release(&reason);
153 strbuf_release(&path);
154}
155
156static int prune(int ac, const char **av, const char *prefix)
157{
158 struct option options[] = {
159 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
160 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
161 OPT_EXPIRY_DATE(0, "expire", &expire,
162 N_("expire working trees older than <time>")),
163 OPT_END()
164 };
165
166 expire = TIME_MAX;
167 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
168 if (ac)
169 usage_with_options(worktree_usage, options);
170 prune_worktrees();
171 return 0;
172}
173
174static char *junk_work_tree;
175static char *junk_git_dir;
176static int is_junk;
177static pid_t junk_pid;
178
179static void remove_junk(void)
180{
181 struct strbuf sb = STRBUF_INIT;
182 if (!is_junk || getpid() != junk_pid)
183 return;
184 if (junk_git_dir) {
185 strbuf_addstr(&sb, junk_git_dir);
186 remove_dir_recursively(&sb, 0);
187 strbuf_reset(&sb);
188 }
189 if (junk_work_tree) {
190 strbuf_addstr(&sb, junk_work_tree);
191 remove_dir_recursively(&sb, 0);
192 }
193 strbuf_release(&sb);
194}
195
196static void remove_junk_on_signal(int signo)
197{
198 remove_junk();
199 sigchain_pop(signo);
200 raise(signo);
201}
202
203static const char *worktree_basename(const char *path, int *olen)
204{
205 const char *name;
206 int len;
207
208 len = strlen(path);
209 while (len && is_dir_sep(path[len - 1]))
210 len--;
211
212 for (name = path + len - 1; name > path; name--)
213 if (is_dir_sep(*name)) {
214 name++;
215 break;
216 }
217
218 *olen = len;
219 return name;
220}
221
222static int add_worktree(const char *path, const char *refname,
223 const struct add_opts *opts)
224{
225 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
226 struct strbuf sb = STRBUF_INIT;
227 const char *name;
228 struct stat st;
229 struct child_process cp = CHILD_PROCESS_INIT;
230 struct argv_array child_env = ARGV_ARRAY_INIT;
231 int counter = 0, len, ret;
232 struct strbuf symref = STRBUF_INIT;
233 struct commit *commit = NULL;
234 int is_branch = 0;
235
236 if (file_exists(path) && !is_empty_dir(path))
237 die(_("'%s' already exists"), path);
238
239 /* is 'refname' a branch or commit? */
240 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
241 ref_exists(symref.buf)) {
242 is_branch = 1;
243 if (!opts->force)
244 die_if_checked_out(symref.buf, 0);
245 }
246 commit = lookup_commit_reference_by_name(refname);
247 if (!commit)
248 die(_("invalid reference: %s"), refname);
249
250 name = worktree_basename(path, &len);
251 git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
252 len = sb_repo.len;
253 if (safe_create_leading_directories_const(sb_repo.buf))
254 die_errno(_("could not create leading directories of '%s'"),
255 sb_repo.buf);
256 while (!stat(sb_repo.buf, &st)) {
257 counter++;
258 strbuf_setlen(&sb_repo, len);
259 strbuf_addf(&sb_repo, "%d", counter);
260 }
261 name = strrchr(sb_repo.buf, '/') + 1;
262
263 junk_pid = getpid();
264 atexit(remove_junk);
265 sigchain_push_common(remove_junk_on_signal);
266
267 if (mkdir(sb_repo.buf, 0777))
268 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
269 junk_git_dir = xstrdup(sb_repo.buf);
270 is_junk = 1;
271
272 /*
273 * lock the incomplete repo so prune won't delete it, unlock
274 * after the preparation is over.
275 */
276 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
277 if (!opts->keep_locked)
278 write_file(sb.buf, "initializing");
279 else
280 write_file(sb.buf, "added with --lock");
281
282 strbuf_addf(&sb_git, "%s/.git", path);
283 if (safe_create_leading_directories_const(sb_git.buf))
284 die_errno(_("could not create leading directories of '%s'"),
285 sb_git.buf);
286 junk_work_tree = xstrdup(path);
287
288 strbuf_reset(&sb);
289 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
290 write_file(sb.buf, "%s", real_path(sb_git.buf));
291 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
292 real_path(get_git_common_dir()), name);
293 /*
294 * This is to keep resolve_ref() happy. We need a valid HEAD
295 * or is_git_directory() will reject the directory. Any value which
296 * looks like an object ID will do since it will be immediately
297 * replaced by the symbolic-ref or update-ref invocation in the new
298 * worktree.
299 */
300 strbuf_reset(&sb);
301 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
302 write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
303 strbuf_reset(&sb);
304 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
305 write_file(sb.buf, "../..");
306
307 fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
308
309 argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
310 argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
311 cp.git_cmd = 1;
312
313 if (!is_branch)
314 argv_array_pushl(&cp.args, "update-ref", "HEAD",
315 oid_to_hex(&commit->object.oid), NULL);
316 else
317 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
318 symref.buf, NULL);
319 cp.env = child_env.argv;
320 ret = run_command(&cp);
321 if (ret)
322 goto done;
323
324 if (opts->checkout) {
325 cp.argv = NULL;
326 argv_array_clear(&cp.args);
327 argv_array_pushl(&cp.args, "reset", "--hard", NULL);
328 cp.env = child_env.argv;
329 ret = run_command(&cp);
330 if (ret)
331 goto done;
332 }
333
334 is_junk = 0;
335 FREE_AND_NULL(junk_work_tree);
336 FREE_AND_NULL(junk_git_dir);
337
338done:
339 if (ret || !opts->keep_locked) {
340 strbuf_reset(&sb);
341 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
342 unlink_or_warn(sb.buf);
343 }
344
345 /*
346 * Hook failure does not warrant worktree deletion, so run hook after
347 * is_junk is cleared, but do return appropriate code when hook fails.
348 */
349 if (!ret && opts->checkout)
350 ret = run_hook_le(NULL, "post-checkout", oid_to_hex(&null_oid),
351 oid_to_hex(&commit->object.oid), "1", NULL);
352
353 argv_array_clear(&child_env);
354 strbuf_release(&sb);
355 strbuf_release(&symref);
356 strbuf_release(&sb_repo);
357 strbuf_release(&sb_git);
358 return ret;
359}
360
361static int add(int ac, const char **av, const char *prefix)
362{
363 struct add_opts opts;
364 const char *new_branch_force = NULL;
365 char *path;
366 const char *branch;
367 const char *opt_track = NULL;
368 struct option options[] = {
369 OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
370 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
371 N_("create a new branch")),
372 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
373 N_("create or reset a branch")),
374 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
375 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
376 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
377 OPT_PASSTHRU(0, "track", &opt_track, NULL,
378 N_("set up tracking mode (see git-branch(1))"),
379 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
380 OPT_BOOL(0, "guess-remote", &guess_remote,
381 N_("try to match the new branch name with a remote-tracking branch")),
382 OPT_END()
383 };
384
385 memset(&opts, 0, sizeof(opts));
386 opts.checkout = 1;
387 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
388 if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
389 die(_("-b, -B, and --detach are mutually exclusive"));
390 if (ac < 1 || ac > 2)
391 usage_with_options(worktree_usage, options);
392
393 path = prefix_filename(prefix, av[0]);
394 branch = ac < 2 ? "HEAD" : av[1];
395
396 if (!strcmp(branch, "-"))
397 branch = "@{-1}";
398
399 opts.force_new_branch = !!new_branch_force;
400 if (opts.force_new_branch) {
401 struct strbuf symref = STRBUF_INIT;
402
403 opts.new_branch = new_branch_force;
404
405 if (!opts.force &&
406 !strbuf_check_branch_ref(&symref, opts.new_branch) &&
407 ref_exists(symref.buf))
408 die_if_checked_out(symref.buf, 0);
409 strbuf_release(&symref);
410 }
411
412 if (ac < 2 && !opts.new_branch && !opts.detach) {
413 int n;
414 const char *s = worktree_basename(path, &n);
415 opts.new_branch = xstrndup(s, n);
416 if (guess_remote) {
417 struct object_id oid;
418 const char *remote =
419 unique_tracking_name(opts.new_branch, &oid);
420 if (remote)
421 branch = remote;
422 }
423 }
424
425 if (ac == 2 && !opts.new_branch && !opts.detach) {
426 struct object_id oid;
427 struct commit *commit;
428 const char *remote;
429
430 commit = lookup_commit_reference_by_name(branch);
431 if (!commit) {
432 remote = unique_tracking_name(branch, &oid);
433 if (remote) {
434 opts.new_branch = branch;
435 branch = remote;
436 }
437 }
438 }
439
440 if (opts.new_branch) {
441 struct child_process cp = CHILD_PROCESS_INIT;
442 cp.git_cmd = 1;
443 argv_array_push(&cp.args, "branch");
444 if (opts.force_new_branch)
445 argv_array_push(&cp.args, "--force");
446 argv_array_push(&cp.args, opts.new_branch);
447 argv_array_push(&cp.args, branch);
448 if (opt_track)
449 argv_array_push(&cp.args, opt_track);
450 if (run_command(&cp))
451 return -1;
452 branch = opts.new_branch;
453 } else if (opt_track) {
454 die(_("--[no-]track can only be used if a new branch is created"));
455 }
456
457 UNLEAK(path);
458 UNLEAK(opts);
459 return add_worktree(path, branch, &opts);
460}
461
462static void show_worktree_porcelain(struct worktree *wt)
463{
464 printf("worktree %s\n", wt->path);
465 if (wt->is_bare)
466 printf("bare\n");
467 else {
468 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
469 if (wt->is_detached)
470 printf("detached\n");
471 else if (wt->head_ref)
472 printf("branch %s\n", wt->head_ref);
473 }
474 printf("\n");
475}
476
477static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
478{
479 struct strbuf sb = STRBUF_INIT;
480 int cur_path_len = strlen(wt->path);
481 int path_adj = cur_path_len - utf8_strwidth(wt->path);
482
483 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
484 if (wt->is_bare)
485 strbuf_addstr(&sb, "(bare)");
486 else {
487 strbuf_addf(&sb, "%-*s ", abbrev_len,
488 find_unique_abbrev(wt->head_oid.hash, DEFAULT_ABBREV));
489 if (wt->is_detached)
490 strbuf_addstr(&sb, "(detached HEAD)");
491 else if (wt->head_ref) {
492 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
493 strbuf_addf(&sb, "[%s]", ref);
494 free(ref);
495 } else
496 strbuf_addstr(&sb, "(error)");
497 }
498 printf("%s\n", sb.buf);
499
500 strbuf_release(&sb);
501}
502
503static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
504{
505 int i;
506
507 for (i = 0; wt[i]; i++) {
508 int sha1_len;
509 int path_len = strlen(wt[i]->path);
510
511 if (path_len > *maxlen)
512 *maxlen = path_len;
513 sha1_len = strlen(find_unique_abbrev(wt[i]->head_oid.hash, *abbrev));
514 if (sha1_len > *abbrev)
515 *abbrev = sha1_len;
516 }
517}
518
519static int list(int ac, const char **av, const char *prefix)
520{
521 int porcelain = 0;
522
523 struct option options[] = {
524 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
525 OPT_END()
526 };
527
528 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
529 if (ac)
530 usage_with_options(worktree_usage, options);
531 else {
532 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
533 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
534
535 if (!porcelain)
536 measure_widths(worktrees, &abbrev, &path_maxlen);
537
538 for (i = 0; worktrees[i]; i++) {
539 if (porcelain)
540 show_worktree_porcelain(worktrees[i]);
541 else
542 show_worktree(worktrees[i], path_maxlen, abbrev);
543 }
544 free_worktrees(worktrees);
545 }
546 return 0;
547}
548
549static int lock_worktree(int ac, const char **av, const char *prefix)
550{
551 const char *reason = "", *old_reason;
552 struct option options[] = {
553 OPT_STRING(0, "reason", &reason, N_("string"),
554 N_("reason for locking")),
555 OPT_END()
556 };
557 struct worktree **worktrees, *wt;
558
559 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
560 if (ac != 1)
561 usage_with_options(worktree_usage, options);
562
563 worktrees = get_worktrees(0);
564 wt = find_worktree(worktrees, prefix, av[0]);
565 if (!wt)
566 die(_("'%s' is not a working tree"), av[0]);
567 if (is_main_worktree(wt))
568 die(_("The main working tree cannot be locked or unlocked"));
569
570 old_reason = is_worktree_locked(wt);
571 if (old_reason) {
572 if (*old_reason)
573 die(_("'%s' is already locked, reason: %s"),
574 av[0], old_reason);
575 die(_("'%s' is already locked"), av[0]);
576 }
577
578 write_file(git_common_path("worktrees/%s/locked", wt->id),
579 "%s", reason);
580 free_worktrees(worktrees);
581 return 0;
582}
583
584static int unlock_worktree(int ac, const char **av, const char *prefix)
585{
586 struct option options[] = {
587 OPT_END()
588 };
589 struct worktree **worktrees, *wt;
590 int ret;
591
592 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
593 if (ac != 1)
594 usage_with_options(worktree_usage, options);
595
596 worktrees = get_worktrees(0);
597 wt = find_worktree(worktrees, prefix, av[0]);
598 if (!wt)
599 die(_("'%s' is not a working tree"), av[0]);
600 if (is_main_worktree(wt))
601 die(_("The main working tree cannot be locked or unlocked"));
602 if (!is_worktree_locked(wt))
603 die(_("'%s' is not locked"), av[0]);
604 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
605 free_worktrees(worktrees);
606 return ret;
607}
608
609static void validate_no_submodules(const struct worktree *wt)
610{
611 struct index_state istate = { NULL };
612 int i, found_submodules = 0;
613
614 if (read_index_from(&istate, worktree_git_path(wt, "index")) > 0) {
615 for (i = 0; i < istate.cache_nr; i++) {
616 struct cache_entry *ce = istate.cache[i];
617
618 if (S_ISGITLINK(ce->ce_mode)) {
619 found_submodules = 1;
620 break;
621 }
622 }
623 }
624 discard_index(&istate);
625
626 if (found_submodules)
627 die(_("working trees containing submodules cannot be moved"));
628}
629
630static int move_worktree(int ac, const char **av, const char *prefix)
631{
632 struct option options[] = {
633 OPT_END()
634 };
635 struct worktree **worktrees, *wt;
636 struct strbuf dst = STRBUF_INIT;
637 struct strbuf errmsg = STRBUF_INIT;
638 const char *reason;
639 char *path;
640
641 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
642 if (ac != 2)
643 usage_with_options(worktree_usage, options);
644
645 path = prefix_filename(prefix, av[1]);
646 strbuf_addstr(&dst, path);
647 free(path);
648
649 worktrees = get_worktrees(0);
650 wt = find_worktree(worktrees, prefix, av[0]);
651 if (!wt)
652 die(_("'%s' is not a working tree"), av[0]);
653 if (is_main_worktree(wt))
654 die(_("'%s' is a main working tree"), av[0]);
655 if (is_directory(dst.buf)) {
656 const char *sep = find_last_dir_sep(wt->path);
657
658 if (!sep)
659 die(_("could not figure out destination name from '%s'"),
660 wt->path);
661 strbuf_trim_trailing_dir_sep(&dst);
662 strbuf_addstr(&dst, sep);
663 }
664 if (file_exists(dst.buf))
665 die(_("target '%s' already exists"), dst.buf);
666
667 validate_no_submodules(wt);
668
669 reason = is_worktree_locked(wt);
670 if (reason) {
671 if (*reason)
672 die(_("cannot move a locked working tree, lock reason: %s"),
673 reason);
674 die(_("cannot move a locked working tree"));
675 }
676 if (validate_worktree(wt, &errmsg))
677 die(_("validation failed, cannot move working tree: %s"),
678 errmsg.buf);
679 strbuf_release(&errmsg);
680
681 if (rename(wt->path, dst.buf) == -1)
682 die_errno(_("failed to move '%s' to '%s'"), wt->path, dst.buf);
683
684 update_worktree_location(wt, dst.buf);
685
686 strbuf_release(&dst);
687 free_worktrees(worktrees);
688 return 0;
689}
690
691int cmd_worktree(int ac, const char **av, const char *prefix)
692{
693 struct option options[] = {
694 OPT_END()
695 };
696
697 git_config(git_worktree_config, NULL);
698
699 if (ac < 2)
700 usage_with_options(worktree_usage, options);
701 if (!prefix)
702 prefix = "";
703 if (!strcmp(av[1], "add"))
704 return add(ac - 1, av + 1, prefix);
705 if (!strcmp(av[1], "prune"))
706 return prune(ac - 1, av + 1, prefix);
707 if (!strcmp(av[1], "list"))
708 return list(ac - 1, av + 1, prefix);
709 if (!strcmp(av[1], "lock"))
710 return lock_worktree(ac - 1, av + 1, prefix);
711 if (!strcmp(av[1], "unlock"))
712 return unlock_worktree(ac - 1, av + 1, prefix);
713 if (!strcmp(av[1], "move"))
714 return move_worktree(ac - 1, av + 1, prefix);
715 usage_with_options(worktree_usage, options);
716}