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