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 prune [<options>]"),
21 N_("git worktree unlock <path>"),
30 const char *new_branch;
36 static timestamp_t expire;
38 static int prune_worktree(const char *id, struct strbuf *reason)
46 if (!is_directory(git_path("worktrees/%s", id))) {
47 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
50 if (file_exists(git_path("worktrees/%s/locked", id)))
52 if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
53 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
56 fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
58 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
62 len = xsize_t(st.st_size);
65 read_result = read_in_full(fd, path, len);
66 if (read_result < 0) {
67 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
75 if (read_result != len) {
77 _("Removing worktrees/%s: short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
78 id, (uintmax_t)len, (uintmax_t)read_result);
82 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
85 strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
90 if (!file_exists(path)) {
94 * the repo is moved manually and has not been
97 if (!stat(git_path("worktrees/%s/link", id), &st_link) &&
100 if (st.st_mtime <= expire) {
101 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
111 static void prune_worktrees(void)
113 struct strbuf reason = STRBUF_INIT;
114 struct strbuf path = STRBUF_INIT;
115 DIR *dir = opendir(git_path("worktrees"));
120 while ((d = readdir(dir)) != NULL) {
121 if (is_dot_or_dotdot(d->d_name))
123 strbuf_reset(&reason);
124 if (!prune_worktree(d->d_name, &reason))
126 if (show_only || verbose)
127 printf("%s\n", reason.buf);
130 git_path_buf(&path, "worktrees/%s", d->d_name);
131 ret = remove_dir_recursively(&path, 0);
132 if (ret < 0 && errno == ENOTDIR)
133 ret = unlink(path.buf);
135 error_errno(_("failed to remove '%s'"), path.buf);
139 rmdir(git_path("worktrees"));
140 strbuf_release(&reason);
141 strbuf_release(&path);
144 static int prune(int ac, const char **av, const char *prefix)
146 struct option options[] = {
147 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
148 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
149 OPT_EXPIRY_DATE(0, "expire", &expire,
150 N_("expire working trees older than <time>")),
155 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
157 usage_with_options(worktree_usage, options);
162 static char *junk_work_tree;
163 static char *junk_git_dir;
165 static pid_t junk_pid;
167 static void remove_junk(void)
169 struct strbuf sb = STRBUF_INIT;
170 if (!is_junk || getpid() != junk_pid)
173 strbuf_addstr(&sb, junk_git_dir);
174 remove_dir_recursively(&sb, 0);
177 if (junk_work_tree) {
178 strbuf_addstr(&sb, junk_work_tree);
179 remove_dir_recursively(&sb, 0);
184 static void remove_junk_on_signal(int signo)
191 static const char *worktree_basename(const char *path, int *olen)
197 while (len && is_dir_sep(path[len - 1]))
200 for (name = path + len - 1; name > path; name--)
201 if (is_dir_sep(*name)) {
210 static int add_worktree(const char *path, const char *refname,
211 const struct add_opts *opts)
213 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
214 struct strbuf sb = STRBUF_INIT;
217 struct child_process cp = CHILD_PROCESS_INIT;
218 struct argv_array child_env = ARGV_ARRAY_INIT;
219 int counter = 0, len, ret;
220 struct strbuf symref = STRBUF_INIT;
221 struct commit *commit = NULL;
223 if (file_exists(path) && !is_empty_dir(path))
224 die(_("'%s' already exists"), path);
226 /* is 'refname' a branch or commit? */
227 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
228 ref_exists(symref.buf)) { /* it's a branch */
230 die_if_checked_out(symref.buf, 0);
231 } else { /* must be a commit */
232 commit = lookup_commit_reference_by_name(refname);
234 die(_("invalid reference: %s"), refname);
237 name = worktree_basename(path, &len);
238 git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
240 if (safe_create_leading_directories_const(sb_repo.buf))
241 die_errno(_("could not create leading directories of '%s'"),
243 while (!stat(sb_repo.buf, &st)) {
245 strbuf_setlen(&sb_repo, len);
246 strbuf_addf(&sb_repo, "%d", counter);
248 name = strrchr(sb_repo.buf, '/') + 1;
252 sigchain_push_common(remove_junk_on_signal);
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);
260 * lock the incomplete repo so prune won't delete it, unlock
261 * after the preparation is over.
263 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
264 if (!opts->keep_locked)
265 write_file(sb.buf, "initializing");
267 write_file(sb.buf, "added with --lock");
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'"),
273 junk_work_tree = xstrdup(path);
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);
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
288 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
289 write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
291 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
292 write_file(sb.buf, "../..");
294 fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
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);
301 argv_array_pushl(&cp.args, "update-ref", "HEAD",
302 oid_to_hex(&commit->object.oid), NULL);
304 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
306 cp.env = child_env.argv;
307 ret = run_command(&cp);
311 if (opts->checkout) {
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);
322 FREE_AND_NULL(junk_work_tree);
323 FREE_AND_NULL(junk_git_dir);
326 if (ret || !opts->keep_locked) {
328 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
329 unlink_or_warn(sb.buf);
331 argv_array_clear(&child_env);
333 strbuf_release(&symref);
334 strbuf_release(&sb_repo);
335 strbuf_release(&sb_git);
339 static int add(int ac, const char **av, const char *prefix)
341 struct add_opts opts;
342 const char *new_branch_force = NULL;
345 const char *opt_track = NULL;
346 struct option options[] = {
347 OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
348 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
349 N_("create a new branch")),
350 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
351 N_("create or reset a branch")),
352 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
353 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
354 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
355 OPT_PASSTHRU(0, "track", &opt_track, NULL,
356 N_("set up tracking mode (see git-branch(1))"),
357 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
361 memset(&opts, 0, sizeof(opts));
363 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
364 if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
365 die(_("-b, -B, and --detach are mutually exclusive"));
366 if (ac < 1 || ac > 2)
367 usage_with_options(worktree_usage, options);
369 path = prefix_filename(prefix, av[0]);
370 branch = ac < 2 ? "HEAD" : av[1];
372 if (!strcmp(branch, "-"))
375 opts.force_new_branch = !!new_branch_force;
376 if (opts.force_new_branch) {
377 struct strbuf symref = STRBUF_INIT;
379 opts.new_branch = new_branch_force;
382 !strbuf_check_branch_ref(&symref, opts.new_branch) &&
383 ref_exists(symref.buf))
384 die_if_checked_out(symref.buf, 0);
385 strbuf_release(&symref);
388 if (ac < 2 && !opts.new_branch && !opts.detach) {
390 const char *s = worktree_basename(path, &n);
391 opts.new_branch = xstrndup(s, n);
394 if (ac == 2 && !opts.new_branch && !opts.detach) {
395 struct object_id oid;
396 struct commit *commit;
399 commit = lookup_commit_reference_by_name(branch);
401 remote = unique_tracking_name(branch, &oid);
403 opts.new_branch = branch;
409 if (opts.new_branch) {
410 struct child_process cp = CHILD_PROCESS_INIT;
412 argv_array_push(&cp.args, "branch");
413 if (opts.force_new_branch)
414 argv_array_push(&cp.args, "--force");
415 argv_array_push(&cp.args, opts.new_branch);
416 argv_array_push(&cp.args, branch);
418 argv_array_push(&cp.args, opt_track);
419 if (run_command(&cp))
421 branch = opts.new_branch;
422 } else if (opt_track) {
423 die(_("--[no-]track can only be used if a new branch is created"));
428 return add_worktree(path, branch, &opts);
431 static void show_worktree_porcelain(struct worktree *wt)
433 printf("worktree %s\n", wt->path);
437 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
439 printf("detached\n");
440 else if (wt->head_ref)
441 printf("branch %s\n", wt->head_ref);
446 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
448 struct strbuf sb = STRBUF_INIT;
449 int cur_path_len = strlen(wt->path);
450 int path_adj = cur_path_len - utf8_strwidth(wt->path);
452 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
454 strbuf_addstr(&sb, "(bare)");
456 strbuf_addf(&sb, "%-*s ", abbrev_len,
457 find_unique_abbrev(wt->head_oid.hash, DEFAULT_ABBREV));
459 strbuf_addstr(&sb, "(detached HEAD)");
460 else if (wt->head_ref) {
461 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
462 strbuf_addf(&sb, "[%s]", ref);
465 strbuf_addstr(&sb, "(error)");
467 printf("%s\n", sb.buf);
472 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
476 for (i = 0; wt[i]; i++) {
478 int path_len = strlen(wt[i]->path);
480 if (path_len > *maxlen)
482 sha1_len = strlen(find_unique_abbrev(wt[i]->head_oid.hash, *abbrev));
483 if (sha1_len > *abbrev)
488 static int list(int ac, const char **av, const char *prefix)
492 struct option options[] = {
493 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
497 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
499 usage_with_options(worktree_usage, options);
501 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
502 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
505 measure_widths(worktrees, &abbrev, &path_maxlen);
507 for (i = 0; worktrees[i]; i++) {
509 show_worktree_porcelain(worktrees[i]);
511 show_worktree(worktrees[i], path_maxlen, abbrev);
513 free_worktrees(worktrees);
518 static int lock_worktree(int ac, const char **av, const char *prefix)
520 const char *reason = "", *old_reason;
521 struct option options[] = {
522 OPT_STRING(0, "reason", &reason, N_("string"),
523 N_("reason for locking")),
526 struct worktree **worktrees, *wt;
528 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
530 usage_with_options(worktree_usage, options);
532 worktrees = get_worktrees(0);
533 wt = find_worktree(worktrees, prefix, av[0]);
535 die(_("'%s' is not a working tree"), av[0]);
536 if (is_main_worktree(wt))
537 die(_("The main working tree cannot be locked or unlocked"));
539 old_reason = is_worktree_locked(wt);
542 die(_("'%s' is already locked, reason: %s"),
544 die(_("'%s' is already locked"), av[0]);
547 write_file(git_common_path("worktrees/%s/locked", wt->id),
549 free_worktrees(worktrees);
553 static int unlock_worktree(int ac, const char **av, const char *prefix)
555 struct option options[] = {
558 struct worktree **worktrees, *wt;
561 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
563 usage_with_options(worktree_usage, options);
565 worktrees = get_worktrees(0);
566 wt = find_worktree(worktrees, prefix, av[0]);
568 die(_("'%s' is not a working tree"), av[0]);
569 if (is_main_worktree(wt))
570 die(_("The main working tree cannot be locked or unlocked"));
571 if (!is_worktree_locked(wt))
572 die(_("'%s' is not locked"), av[0]);
573 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
574 free_worktrees(worktrees);
578 int cmd_worktree(int ac, const char **av, const char *prefix)
580 struct option options[] = {
584 git_config(git_default_config, NULL);
587 usage_with_options(worktree_usage, options);
590 if (!strcmp(av[1], "add"))
591 return add(ac - 1, av + 1, prefix);
592 if (!strcmp(av[1], "prune"))
593 return prune(ac - 1, av + 1, prefix);
594 if (!strcmp(av[1], "list"))
595 return list(ac - 1, av + 1, prefix);
596 if (!strcmp(av[1], "lock"))
597 return lock_worktree(ac - 1, av + 1, prefix);
598 if (!strcmp(av[1], "unlock"))
599 return unlock_worktree(ac - 1, av + 1, prefix);
600 usage_with_options(worktree_usage, options);