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