6 #include "parse-options.h"
7 #include "argv-array.h"
10 #include "run-command.h"
16 static 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>"),
31 const char *new_branch
;
37 static int guess_remote
;
38 static timestamp_t expire
;
40 static int git_worktree_config(const char *var
, const char *value
, void *cb
)
42 if (!strcmp(var
, "worktree.guessremote")) {
43 guess_remote
= git_config_bool(var
, value
);
47 return git_default_config(var
, value
, cb
);
50 static int prune_worktree(const char *id
, struct strbuf
*reason
)
58 if (!is_directory(git_path("worktrees/%s", id
))) {
59 strbuf_addf(reason
, _("Removing worktrees/%s: not a valid directory"), id
);
62 if (file_exists(git_path("worktrees/%s/locked", id
)))
64 if (stat(git_path("worktrees/%s/gitdir", id
), &st
)) {
65 strbuf_addf(reason
, _("Removing worktrees/%s: gitdir file does not exist"), id
);
68 fd
= open(git_path("worktrees/%s/gitdir", id
), O_RDONLY
);
70 strbuf_addf(reason
, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
74 len
= xsize_t(st
.st_size
);
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)"),
87 if (read_result
!= len
) {
89 _("Removing worktrees/%s: short read (expected %"PRIuMAX
" bytes, read %"PRIuMAX
")"),
90 id
, (uintmax_t)len
, (uintmax_t)read_result
);
94 while (len
&& (path
[len
- 1] == '\n' || path
[len
- 1] == '\r'))
97 strbuf_addf(reason
, _("Removing worktrees/%s: invalid gitdir file"), id
);
102 if (!file_exists(path
)) {
106 * the repo is moved manually and has not been
109 if (!stat(git_path("worktrees/%s/link", id
), &st_link
) &&
110 st_link
.st_nlink
> 1)
112 if (st
.st_mtime
<= expire
) {
113 strbuf_addf(reason
, _("Removing worktrees/%s: gitdir file points to non-existent location"), id
);
123 static void prune_worktrees(void)
125 struct strbuf reason
= STRBUF_INIT
;
126 struct strbuf path
= STRBUF_INIT
;
127 DIR *dir
= opendir(git_path("worktrees"));
132 while ((d
= readdir(dir
)) != NULL
) {
133 if (is_dot_or_dotdot(d
->d_name
))
135 strbuf_reset(&reason
);
136 if (!prune_worktree(d
->d_name
, &reason
))
138 if (show_only
|| verbose
)
139 printf("%s\n", reason
.buf
);
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
);
147 error_errno(_("failed to remove '%s'"), path
.buf
);
151 rmdir(git_path("worktrees"));
152 strbuf_release(&reason
);
153 strbuf_release(&path
);
156 static int prune(int ac
, const char **av
, const char *prefix
)
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>")),
167 ac
= parse_options(ac
, av
, prefix
, options
, worktree_usage
, 0);
169 usage_with_options(worktree_usage
, options
);
174 static char *junk_work_tree
;
175 static char *junk_git_dir
;
177 static pid_t junk_pid
;
179 static void remove_junk(void)
181 struct strbuf sb
= STRBUF_INIT
;
182 if (!is_junk
|| getpid() != junk_pid
)
185 strbuf_addstr(&sb
, junk_git_dir
);
186 remove_dir_recursively(&sb
, 0);
189 if (junk_work_tree
) {
190 strbuf_addstr(&sb
, junk_work_tree
);
191 remove_dir_recursively(&sb
, 0);
196 static void remove_junk_on_signal(int signo
)
203 static const char *worktree_basename(const char *path
, int *olen
)
209 while (len
&& is_dir_sep(path
[len
- 1]))
212 for (name
= path
+ len
- 1; name
> path
; name
--)
213 if (is_dir_sep(*name
)) {
222 static int add_worktree(const char *path
, const char *refname
,
223 const struct add_opts
*opts
)
225 struct strbuf sb_git
= STRBUF_INIT
, sb_repo
= STRBUF_INIT
;
226 struct strbuf sb
= STRBUF_INIT
;
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
;
236 if (file_exists(path
) && !is_empty_dir(path
))
237 die(_("'%s' already exists"), path
);
239 /* is 'refname' a branch or commit? */
240 if (!opts
->detach
&& !strbuf_check_branch_ref(&symref
, refname
) &&
241 ref_exists(symref
.buf
)) {
244 die_if_checked_out(symref
.buf
, 0);
246 commit
= lookup_commit_reference_by_name(refname
);
248 die(_("invalid reference: %s"), refname
);
250 name
= worktree_basename(path
, &len
);
251 git_path_buf(&sb_repo
, "worktrees/%.*s", (int)(path
+ len
- name
), name
);
253 if (safe_create_leading_directories_const(sb_repo
.buf
))
254 die_errno(_("could not create leading directories of '%s'"),
256 while (!stat(sb_repo
.buf
, &st
)) {
258 strbuf_setlen(&sb_repo
, len
);
259 strbuf_addf(&sb_repo
, "%d", counter
);
261 name
= strrchr(sb_repo
.buf
, '/') + 1;
265 sigchain_push_common(remove_junk_on_signal
);
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
);
273 * lock the incomplete repo so prune won't delete it, unlock
274 * after the preparation is over.
276 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
277 if (!opts
->keep_locked
)
278 write_file(sb
.buf
, "initializing");
280 write_file(sb
.buf
, "added with --lock");
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'"),
286 junk_work_tree
= xstrdup(path
);
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
);
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
301 strbuf_addf(&sb
, "%s/HEAD", sb_repo
.buf
);
302 write_file(sb
.buf
, "%s", sha1_to_hex(null_sha1
));
304 strbuf_addf(&sb
, "%s/commondir", sb_repo
.buf
);
305 write_file(sb
.buf
, "../..");
307 fprintf_ln(stderr
, _("Preparing %s (identifier %s)"), path
, name
);
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
);
314 argv_array_pushl(&cp
.args
, "update-ref", "HEAD",
315 oid_to_hex(&commit
->object
.oid
), NULL
);
317 argv_array_pushl(&cp
.args
, "symbolic-ref", "HEAD",
319 cp
.env
= child_env
.argv
;
320 ret
= run_command(&cp
);
324 if (opts
->checkout
) {
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
);
335 FREE_AND_NULL(junk_work_tree
);
336 FREE_AND_NULL(junk_git_dir
);
339 if (ret
|| !opts
->keep_locked
) {
341 strbuf_addf(&sb
, "%s/locked", sb_repo
.buf
);
342 unlink_or_warn(sb
.buf
);
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.
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
);
353 argv_array_clear(&child_env
);
355 strbuf_release(&symref
);
356 strbuf_release(&sb_repo
);
357 strbuf_release(&sb_git
);
361 static int add(int ac
, const char **av
, const char *prefix
)
363 struct add_opts opts
;
364 const char *new_branch_force
= NULL
;
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")),
385 memset(&opts
, 0, sizeof(opts
));
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
);
393 path
= prefix_filename(prefix
, av
[0]);
394 branch
= ac
< 2 ? "HEAD" : av
[1];
396 if (!strcmp(branch
, "-"))
399 opts
.force_new_branch
= !!new_branch_force
;
400 if (opts
.force_new_branch
) {
401 struct strbuf symref
= STRBUF_INIT
;
403 opts
.new_branch
= new_branch_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
);
412 if (ac
< 2 && !opts
.new_branch
&& !opts
.detach
) {
414 const char *s
= worktree_basename(path
, &n
);
415 opts
.new_branch
= xstrndup(s
, n
);
417 struct object_id oid
;
419 unique_tracking_name(opts
.new_branch
, &oid
);
425 if (ac
== 2 && !opts
.new_branch
&& !opts
.detach
) {
426 struct object_id oid
;
427 struct commit
*commit
;
430 commit
= lookup_commit_reference_by_name(branch
);
432 remote
= unique_tracking_name(branch
, &oid
);
434 opts
.new_branch
= branch
;
440 if (opts
.new_branch
) {
441 struct child_process cp
= CHILD_PROCESS_INIT
;
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
);
449 argv_array_push(&cp
.args
, opt_track
);
450 if (run_command(&cp
))
452 branch
= opts
.new_branch
;
453 } else if (opt_track
) {
454 die(_("--[no-]track can only be used if a new branch is created"));
459 return add_worktree(path
, branch
, &opts
);
462 static void show_worktree_porcelain(struct worktree
*wt
)
464 printf("worktree %s\n", wt
->path
);
468 printf("HEAD %s\n", oid_to_hex(&wt
->head_oid
));
470 printf("detached\n");
471 else if (wt
->head_ref
)
472 printf("branch %s\n", wt
->head_ref
);
477 static void show_worktree(struct worktree
*wt
, int path_maxlen
, int abbrev_len
)
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
);
483 strbuf_addf(&sb
, "%-*s ", 1 + path_maxlen
+ path_adj
, wt
->path
);
485 strbuf_addstr(&sb
, "(bare)");
487 strbuf_addf(&sb
, "%-*s ", abbrev_len
,
488 find_unique_abbrev(wt
->head_oid
.hash
, DEFAULT_ABBREV
));
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
);
496 strbuf_addstr(&sb
, "(error)");
498 printf("%s\n", sb
.buf
);
503 static void measure_widths(struct worktree
**wt
, int *abbrev
, int *maxlen
)
507 for (i
= 0; wt
[i
]; i
++) {
509 int path_len
= strlen(wt
[i
]->path
);
511 if (path_len
> *maxlen
)
513 sha1_len
= strlen(find_unique_abbrev(wt
[i
]->head_oid
.hash
, *abbrev
));
514 if (sha1_len
> *abbrev
)
519 static int list(int ac
, const char **av
, const char *prefix
)
523 struct option options
[] = {
524 OPT_BOOL(0, "porcelain", &porcelain
, N_("machine-readable output")),
528 ac
= parse_options(ac
, av
, prefix
, options
, worktree_usage
, 0);
530 usage_with_options(worktree_usage
, options
);
532 struct worktree
**worktrees
= get_worktrees(GWT_SORT_LINKED
);
533 int path_maxlen
= 0, abbrev
= DEFAULT_ABBREV
, i
;
536 measure_widths(worktrees
, &abbrev
, &path_maxlen
);
538 for (i
= 0; worktrees
[i
]; i
++) {
540 show_worktree_porcelain(worktrees
[i
]);
542 show_worktree(worktrees
[i
], path_maxlen
, abbrev
);
544 free_worktrees(worktrees
);
549 static int lock_worktree(int ac
, const char **av
, const char *prefix
)
551 const char *reason
= "", *old_reason
;
552 struct option options
[] = {
553 OPT_STRING(0, "reason", &reason
, N_("string"),
554 N_("reason for locking")),
557 struct worktree
**worktrees
, *wt
;
559 ac
= parse_options(ac
, av
, prefix
, options
, worktree_usage
, 0);
561 usage_with_options(worktree_usage
, options
);
563 worktrees
= get_worktrees(0);
564 wt
= find_worktree(worktrees
, prefix
, av
[0]);
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"));
570 old_reason
= is_worktree_locked(wt
);
573 die(_("'%s' is already locked, reason: %s"),
575 die(_("'%s' is already locked"), av
[0]);
578 write_file(git_common_path("worktrees/%s/locked", wt
->id
),
580 free_worktrees(worktrees
);
584 static int unlock_worktree(int ac
, const char **av
, const char *prefix
)
586 struct option options
[] = {
589 struct worktree
**worktrees
, *wt
;
592 ac
= parse_options(ac
, av
, prefix
, options
, worktree_usage
, 0);
594 usage_with_options(worktree_usage
, options
);
596 worktrees
= get_worktrees(0);
597 wt
= find_worktree(worktrees
, prefix
, av
[0]);
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
);
609 static void validate_no_submodules(const struct worktree
*wt
)
611 struct index_state istate
= { NULL
};
612 int i
, found_submodules
= 0;
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
];
618 if (S_ISGITLINK(ce
->ce_mode
)) {
619 found_submodules
= 1;
624 discard_index(&istate
);
626 if (found_submodules
)
627 die(_("working trees containing submodules cannot be moved"));
630 static int move_worktree(int ac
, const char **av
, const char *prefix
)
632 struct option options
[] = {
635 struct worktree
**worktrees
, *wt
;
636 struct strbuf dst
= STRBUF_INIT
;
637 struct strbuf errmsg
= STRBUF_INIT
;
641 ac
= parse_options(ac
, av
, prefix
, options
, worktree_usage
, 0);
643 usage_with_options(worktree_usage
, options
);
645 path
= prefix_filename(prefix
, av
[1]);
646 strbuf_addstr(&dst
, path
);
649 worktrees
= get_worktrees(0);
650 wt
= find_worktree(worktrees
, prefix
, av
[0]);
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
);
659 die(_("could not figure out destination name from '%s'"),
661 strbuf_trim_trailing_dir_sep(&dst
);
662 strbuf_addstr(&dst
, sep
);
664 if (file_exists(dst
.buf
))
665 die(_("target '%s' already exists"), dst
.buf
);
667 validate_no_submodules(wt
);
669 reason
= is_worktree_locked(wt
);
672 die(_("cannot move a locked working tree, lock reason: %s"),
674 die(_("cannot move a locked working tree"));
676 if (validate_worktree(wt
, &errmsg
))
677 die(_("validation failed, cannot move working tree: %s"),
679 strbuf_release(&errmsg
);
681 if (rename(wt
->path
, dst
.buf
) == -1)
682 die_errno(_("failed to move '%s' to '%s'"), wt
->path
, dst
.buf
);
684 update_worktree_location(wt
, dst
.buf
);
686 strbuf_release(&dst
);
687 free_worktrees(worktrees
);
691 int cmd_worktree(int ac
, const char **av
, const char *prefix
)
693 struct option options
[] = {
697 git_config(git_worktree_config
, NULL
);
700 usage_with_options(worktree_usage
, options
);
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
);