worktree move: refuse to move worktrees with submodules
[alt-git.git] / builtin / worktree.c
blob4789cebe110112cd953a6beee31f678cafea4b77
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"
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>"),
23 NULL
26 struct 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;
35 static int show_only;
36 static int verbose;
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);
44 return 0;
47 return git_default_config(var, value, cb);
50 static int prune_worktree(const char *id, struct strbuf *reason)
52 struct stat st;
53 char *path;
54 int fd;
55 size_t len;
56 ssize_t read_result;
58 if (!is_directory(git_path("worktrees/%s", id))) {
59 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
60 return 1;
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;
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;
74 len = xsize_t(st.st_size);
75 path = xmallocz(len);
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;
85 close(fd);
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;
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;
101 path[len] = '\0';
102 if (!file_exists(path)) {
103 struct stat st_link;
104 free(path);
106 * the repo is moved manually and has not been
107 * accessed since?
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;
119 free(path);
120 return 0;
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"));
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);
149 closedir(dir);
150 if (!show_only)
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>")),
163 OPT_END()
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;
174 static char *junk_work_tree;
175 static char *junk_git_dir;
176 static int is_junk;
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)
183 return;
184 if (junk_git_dir) {
185 strbuf_addstr(&sb, junk_git_dir);
186 remove_dir_recursively(&sb, 0);
187 strbuf_reset(&sb);
189 if (junk_work_tree) {
190 strbuf_addstr(&sb, junk_work_tree);
191 remove_dir_recursively(&sb, 0);
193 strbuf_release(&sb);
196 static void remove_junk_on_signal(int signo)
198 remove_junk();
199 sigchain_pop(signo);
200 raise(signo);
203 static const char *worktree_basename(const char *path, int *olen)
205 const char *name;
206 int len;
208 len = strlen(path);
209 while (len && is_dir_sep(path[len - 1]))
210 len--;
212 for (name = path + len - 1; name > path; name--)
213 if (is_dir_sep(*name)) {
214 name++;
215 break;
218 *olen = len;
219 return 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;
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;
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)) {
242 is_branch = 1;
243 if (!opts->force)
244 die_if_checked_out(symref.buf, 0);
246 commit = lookup_commit_reference_by_name(refname);
247 if (!commit)
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);
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);
261 name = strrchr(sb_repo.buf, '/') + 1;
263 junk_pid = getpid();
264 atexit(remove_junk);
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);
270 is_junk = 1;
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");
279 else
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'"),
285 sb_git.buf);
286 junk_work_tree = xstrdup(path);
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);
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.
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, "../..");
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);
311 cp.git_cmd = 1;
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;
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;
334 is_junk = 0;
335 FREE_AND_NULL(junk_work_tree);
336 FREE_AND_NULL(junk_git_dir);
338 done:
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);
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);
354 strbuf_release(&sb);
355 strbuf_release(&symref);
356 strbuf_release(&sb_repo);
357 strbuf_release(&sb_git);
358 return ret;
361 static int add(int ac, const char **av, const char *prefix)
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()
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);
393 path = prefix_filename(prefix, av[0]);
394 branch = ac < 2 ? "HEAD" : av[1];
396 if (!strcmp(branch, "-"))
397 branch = "@{-1}";
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;
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);
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;
425 if (ac == 2 && !opts.new_branch && !opts.detach) {
426 struct object_id oid;
427 struct commit *commit;
428 const char *remote;
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;
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"));
457 UNLEAK(path);
458 UNLEAK(opts);
459 return add_worktree(path, branch, &opts);
462 static void show_worktree_porcelain(struct worktree *wt)
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);
474 printf("\n");
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);
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)");
498 printf("%s\n", sb.buf);
500 strbuf_release(&sb);
503 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
505 int i;
507 for (i = 0; wt[i]; i++) {
508 int sha1_len;
509 int path_len = strlen(wt[i]->path);
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;
519 static int list(int ac, const char **av, const char *prefix)
521 int porcelain = 0;
523 struct option options[] = {
524 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
525 OPT_END()
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;
535 if (!porcelain)
536 measure_widths(worktrees, &abbrev, &path_maxlen);
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);
544 free_worktrees(worktrees);
546 return 0;
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")),
555 OPT_END()
557 struct worktree **worktrees, *wt;
559 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
560 if (ac != 1)
561 usage_with_options(worktree_usage, options);
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"));
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]);
578 write_file(git_common_path("worktrees/%s/locked", wt->id),
579 "%s", reason);
580 free_worktrees(worktrees);
581 return 0;
584 static int unlock_worktree(int ac, const char **av, const char *prefix)
586 struct option options[] = {
587 OPT_END()
589 struct worktree **worktrees, *wt;
590 int ret;
592 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
593 if (ac != 1)
594 usage_with_options(worktree_usage, options);
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;
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;
620 break;
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[] = {
633 OPT_END()
635 struct worktree **worktrees, *wt;
636 struct strbuf dst = STRBUF_INIT;
637 struct strbuf errmsg = STRBUF_INIT;
638 const char *reason;
639 char *path;
641 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
642 if (ac != 2)
643 usage_with_options(worktree_usage, options);
645 path = prefix_filename(prefix, av[1]);
646 strbuf_addstr(&dst, path);
647 free(path);
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);
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);
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);
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"));
676 if (validate_worktree(wt, &errmsg))
677 die(_("validation failed, cannot move working tree: %s"),
678 errmsg.buf);
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);
688 return 0;
691 int cmd_worktree(int ac, const char **av, const char *prefix)
693 struct option options[] = {
694 OPT_END()
697 git_config(git_worktree_config, NULL);
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);