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