worktree add: add --lock option
[git.git] / builtin / worktree.c
blob05ade547cada4c7ede7f76fc8e15c26956a216e5
1 #include "cache.h"
2 #include "builtin.h"
3 #include "dir.h"
4 #include "parse-options.h"
5 #include "argv-array.h"
6 #include "branch.h"
7 #include "refs.h"
8 #include "run-command.h"
9 #include "sigchain.h"
10 #include "refs.h"
11 #include "utf8.h"
12 #include "worktree.h"
14 static const char * const worktree_usage[] = {
15 N_("git worktree add [<options>] <path> [<branch>]"),
16 N_("git worktree list [<options>]"),
17 N_("git worktree lock [<options>] <path>"),
18 N_("git worktree prune [<options>]"),
19 N_("git worktree unlock <path>"),
20 NULL
23 struct add_opts {
24 int force;
25 int detach;
26 int checkout;
27 int keep_locked;
28 const char *new_branch;
29 int force_new_branch;
32 static int show_only;
33 static int verbose;
34 static unsigned long expire;
36 static int prune_worktree(const char *id, struct strbuf *reason)
38 struct stat st;
39 char *path;
40 int fd, len;
42 if (!is_directory(git_path("worktrees/%s", id))) {
43 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
44 return 1;
46 if (file_exists(git_path("worktrees/%s/locked", id)))
47 return 0;
48 if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
49 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
50 return 1;
52 fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
53 if (fd < 0) {
54 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
55 id, strerror(errno));
56 return 1;
58 len = st.st_size;
59 path = xmallocz(len);
60 read_in_full(fd, path, len);
61 close(fd);
62 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
63 len--;
64 if (!len) {
65 strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
66 free(path);
67 return 1;
69 path[len] = '\0';
70 if (!file_exists(path)) {
71 struct stat st_link;
72 free(path);
74 * the repo is moved manually and has not been
75 * accessed since?
77 if (!stat(git_path("worktrees/%s/link", id), &st_link) &&
78 st_link.st_nlink > 1)
79 return 0;
80 if (st.st_mtime <= expire) {
81 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
82 return 1;
83 } else {
84 return 0;
87 free(path);
88 return 0;
91 static void prune_worktrees(void)
93 struct strbuf reason = STRBUF_INIT;
94 struct strbuf path = STRBUF_INIT;
95 DIR *dir = opendir(git_path("worktrees"));
96 struct dirent *d;
97 int ret;
98 if (!dir)
99 return;
100 while ((d = readdir(dir)) != NULL) {
101 if (is_dot_or_dotdot(d->d_name))
102 continue;
103 strbuf_reset(&reason);
104 if (!prune_worktree(d->d_name, &reason))
105 continue;
106 if (show_only || verbose)
107 printf("%s\n", reason.buf);
108 if (show_only)
109 continue;
110 strbuf_reset(&path);
111 strbuf_addstr(&path, git_path("worktrees/%s", d->d_name));
112 ret = remove_dir_recursively(&path, 0);
113 if (ret < 0 && errno == ENOTDIR)
114 ret = unlink(path.buf);
115 if (ret)
116 error_errno(_("failed to remove '%s'"), path.buf);
118 closedir(dir);
119 if (!show_only)
120 rmdir(git_path("worktrees"));
121 strbuf_release(&reason);
122 strbuf_release(&path);
125 static int prune(int ac, const char **av, const char *prefix)
127 struct option options[] = {
128 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
129 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
130 OPT_EXPIRY_DATE(0, "expire", &expire,
131 N_("expire working trees older than <time>")),
132 OPT_END()
135 expire = ULONG_MAX;
136 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
137 if (ac)
138 usage_with_options(worktree_usage, options);
139 prune_worktrees();
140 return 0;
143 static char *junk_work_tree;
144 static char *junk_git_dir;
145 static int is_junk;
146 static pid_t junk_pid;
148 static void remove_junk(void)
150 struct strbuf sb = STRBUF_INIT;
151 if (!is_junk || getpid() != junk_pid)
152 return;
153 if (junk_git_dir) {
154 strbuf_addstr(&sb, junk_git_dir);
155 remove_dir_recursively(&sb, 0);
156 strbuf_reset(&sb);
158 if (junk_work_tree) {
159 strbuf_addstr(&sb, junk_work_tree);
160 remove_dir_recursively(&sb, 0);
162 strbuf_release(&sb);
165 static void remove_junk_on_signal(int signo)
167 remove_junk();
168 sigchain_pop(signo);
169 raise(signo);
172 static const char *worktree_basename(const char *path, int *olen)
174 const char *name;
175 int len;
177 len = strlen(path);
178 while (len && is_dir_sep(path[len - 1]))
179 len--;
181 for (name = path + len - 1; name > path; name--)
182 if (is_dir_sep(*name)) {
183 name++;
184 break;
187 *olen = len;
188 return name;
191 static int add_worktree(const char *path, const char *refname,
192 const struct add_opts *opts)
194 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
195 struct strbuf sb = STRBUF_INIT;
196 const char *name;
197 struct stat st;
198 struct child_process cp = CHILD_PROCESS_INIT;
199 struct argv_array child_env = ARGV_ARRAY_INIT;
200 int counter = 0, len, ret;
201 struct strbuf symref = STRBUF_INIT;
202 struct commit *commit = NULL;
204 if (file_exists(path) && !is_empty_dir(path))
205 die(_("'%s' already exists"), path);
207 /* is 'refname' a branch or commit? */
208 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
209 ref_exists(symref.buf)) { /* it's a branch */
210 if (!opts->force)
211 die_if_checked_out(symref.buf, 0);
212 } else { /* must be a commit */
213 commit = lookup_commit_reference_by_name(refname);
214 if (!commit)
215 die(_("invalid reference: %s"), refname);
218 name = worktree_basename(path, &len);
219 strbuf_addstr(&sb_repo,
220 git_path("worktrees/%.*s", (int)(path + len - name), name));
221 len = sb_repo.len;
222 if (safe_create_leading_directories_const(sb_repo.buf))
223 die_errno(_("could not create leading directories of '%s'"),
224 sb_repo.buf);
225 while (!stat(sb_repo.buf, &st)) {
226 counter++;
227 strbuf_setlen(&sb_repo, len);
228 strbuf_addf(&sb_repo, "%d", counter);
230 name = strrchr(sb_repo.buf, '/') + 1;
232 junk_pid = getpid();
233 atexit(remove_junk);
234 sigchain_push_common(remove_junk_on_signal);
236 if (mkdir(sb_repo.buf, 0777))
237 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
238 junk_git_dir = xstrdup(sb_repo.buf);
239 is_junk = 1;
242 * lock the incomplete repo so prune won't delete it, unlock
243 * after the preparation is over.
245 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
246 if (!opts->keep_locked)
247 write_file(sb.buf, "initializing");
248 else
249 write_file(sb.buf, "added with --lock");
251 strbuf_addf(&sb_git, "%s/.git", path);
252 if (safe_create_leading_directories_const(sb_git.buf))
253 die_errno(_("could not create leading directories of '%s'"),
254 sb_git.buf);
255 junk_work_tree = xstrdup(path);
257 strbuf_reset(&sb);
258 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
259 write_file(sb.buf, "%s", real_path(sb_git.buf));
260 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
261 real_path(get_git_common_dir()), name);
263 * This is to keep resolve_ref() happy. We need a valid HEAD
264 * or is_git_directory() will reject the directory. Any value which
265 * looks like an object ID will do since it will be immediately
266 * replaced by the symbolic-ref or update-ref invocation in the new
267 * worktree.
269 strbuf_reset(&sb);
270 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
271 write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
272 strbuf_reset(&sb);
273 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
274 write_file(sb.buf, "../..");
276 fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
278 argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
279 argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
280 cp.git_cmd = 1;
282 if (commit)
283 argv_array_pushl(&cp.args, "update-ref", "HEAD",
284 oid_to_hex(&commit->object.oid), NULL);
285 else
286 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
287 symref.buf, NULL);
288 cp.env = child_env.argv;
289 ret = run_command(&cp);
290 if (ret)
291 goto done;
293 if (opts->checkout) {
294 cp.argv = NULL;
295 argv_array_clear(&cp.args);
296 argv_array_pushl(&cp.args, "reset", "--hard", NULL);
297 cp.env = child_env.argv;
298 ret = run_command(&cp);
299 if (ret)
300 goto done;
303 is_junk = 0;
304 free(junk_work_tree);
305 free(junk_git_dir);
306 junk_work_tree = NULL;
307 junk_git_dir = NULL;
309 done:
310 if (ret || !opts->keep_locked) {
311 strbuf_reset(&sb);
312 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
313 unlink_or_warn(sb.buf);
315 argv_array_clear(&child_env);
316 strbuf_release(&sb);
317 strbuf_release(&symref);
318 strbuf_release(&sb_repo);
319 strbuf_release(&sb_git);
320 return ret;
323 static int add(int ac, const char **av, const char *prefix)
325 struct add_opts opts;
326 const char *new_branch_force = NULL;
327 char *path;
328 const char *branch;
329 struct option options[] = {
330 OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
331 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
332 N_("create a new branch")),
333 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
334 N_("create or reset a branch")),
335 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
336 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
337 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
338 OPT_END()
341 memset(&opts, 0, sizeof(opts));
342 opts.checkout = 1;
343 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
344 if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
345 die(_("-b, -B, and --detach are mutually exclusive"));
346 if (ac < 1 || ac > 2)
347 usage_with_options(worktree_usage, options);
349 path = prefix_filename(prefix, av[0]);
350 branch = ac < 2 ? "HEAD" : av[1];
352 if (!strcmp(branch, "-"))
353 branch = "@{-1}";
355 opts.force_new_branch = !!new_branch_force;
356 if (opts.force_new_branch) {
357 struct strbuf symref = STRBUF_INIT;
359 opts.new_branch = new_branch_force;
361 if (!opts.force &&
362 !strbuf_check_branch_ref(&symref, opts.new_branch) &&
363 ref_exists(symref.buf))
364 die_if_checked_out(symref.buf, 0);
365 strbuf_release(&symref);
368 if (ac < 2 && !opts.new_branch && !opts.detach) {
369 int n;
370 const char *s = worktree_basename(path, &n);
371 opts.new_branch = xstrndup(s, n);
374 if (opts.new_branch) {
375 struct child_process cp = CHILD_PROCESS_INIT;
376 cp.git_cmd = 1;
377 argv_array_push(&cp.args, "branch");
378 if (opts.force_new_branch)
379 argv_array_push(&cp.args, "--force");
380 argv_array_push(&cp.args, opts.new_branch);
381 argv_array_push(&cp.args, branch);
382 if (run_command(&cp))
383 return -1;
384 branch = opts.new_branch;
387 return add_worktree(path, branch, &opts);
390 static void show_worktree_porcelain(struct worktree *wt)
392 printf("worktree %s\n", wt->path);
393 if (wt->is_bare)
394 printf("bare\n");
395 else {
396 printf("HEAD %s\n", sha1_to_hex(wt->head_sha1));
397 if (wt->is_detached)
398 printf("detached\n");
399 else if (wt->head_ref)
400 printf("branch %s\n", wt->head_ref);
402 printf("\n");
405 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
407 struct strbuf sb = STRBUF_INIT;
408 int cur_path_len = strlen(wt->path);
409 int path_adj = cur_path_len - utf8_strwidth(wt->path);
411 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
412 if (wt->is_bare)
413 strbuf_addstr(&sb, "(bare)");
414 else {
415 strbuf_addf(&sb, "%-*s ", abbrev_len,
416 find_unique_abbrev(wt->head_sha1, DEFAULT_ABBREV));
417 if (wt->is_detached)
418 strbuf_addstr(&sb, "(detached HEAD)");
419 else if (wt->head_ref)
420 strbuf_addf(&sb, "[%s]", shorten_unambiguous_ref(wt->head_ref, 0));
421 else
422 strbuf_addstr(&sb, "(error)");
424 printf("%s\n", sb.buf);
426 strbuf_release(&sb);
429 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
431 int i;
433 for (i = 0; wt[i]; i++) {
434 int sha1_len;
435 int path_len = strlen(wt[i]->path);
437 if (path_len > *maxlen)
438 *maxlen = path_len;
439 sha1_len = strlen(find_unique_abbrev(wt[i]->head_sha1, *abbrev));
440 if (sha1_len > *abbrev)
441 *abbrev = sha1_len;
445 static int list(int ac, const char **av, const char *prefix)
447 int porcelain = 0;
449 struct option options[] = {
450 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
451 OPT_END()
454 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
455 if (ac)
456 usage_with_options(worktree_usage, options);
457 else {
458 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
459 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
461 if (!porcelain)
462 measure_widths(worktrees, &abbrev, &path_maxlen);
464 for (i = 0; worktrees[i]; i++) {
465 if (porcelain)
466 show_worktree_porcelain(worktrees[i]);
467 else
468 show_worktree(worktrees[i], path_maxlen, abbrev);
470 free_worktrees(worktrees);
472 return 0;
475 static int lock_worktree(int ac, const char **av, const char *prefix)
477 const char *reason = "", *old_reason;
478 struct option options[] = {
479 OPT_STRING(0, "reason", &reason, N_("string"),
480 N_("reason for locking")),
481 OPT_END()
483 struct worktree **worktrees, *wt;
485 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
486 if (ac != 1)
487 usage_with_options(worktree_usage, options);
489 worktrees = get_worktrees(0);
490 wt = find_worktree(worktrees, prefix, av[0]);
491 if (!wt)
492 die(_("'%s' is not a working tree"), av[0]);
493 if (is_main_worktree(wt))
494 die(_("The main working tree cannot be locked or unlocked"));
496 old_reason = is_worktree_locked(wt);
497 if (old_reason) {
498 if (*old_reason)
499 die(_("'%s' is already locked, reason: %s"),
500 av[0], old_reason);
501 die(_("'%s' is already locked"), av[0]);
504 write_file(git_common_path("worktrees/%s/locked", wt->id),
505 "%s", reason);
506 free_worktrees(worktrees);
507 return 0;
510 static int unlock_worktree(int ac, const char **av, const char *prefix)
512 struct option options[] = {
513 OPT_END()
515 struct worktree **worktrees, *wt;
516 int ret;
518 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
519 if (ac != 1)
520 usage_with_options(worktree_usage, options);
522 worktrees = get_worktrees(0);
523 wt = find_worktree(worktrees, prefix, av[0]);
524 if (!wt)
525 die(_("'%s' is not a working tree"), av[0]);
526 if (is_main_worktree(wt))
527 die(_("The main working tree cannot be locked or unlocked"));
528 if (!is_worktree_locked(wt))
529 die(_("'%s' is not locked"), av[0]);
530 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
531 free_worktrees(worktrees);
532 return ret;
535 int cmd_worktree(int ac, const char **av, const char *prefix)
537 struct option options[] = {
538 OPT_END()
541 git_config(git_default_config, NULL);
543 if (ac < 2)
544 usage_with_options(worktree_usage, options);
545 if (!prefix)
546 prefix = "";
547 if (!strcmp(av[1], "add"))
548 return add(ac - 1, av + 1, prefix);
549 if (!strcmp(av[1], "prune"))
550 return prune(ac - 1, av + 1, prefix);
551 if (!strcmp(av[1], "list"))
552 return list(ac - 1, av + 1, prefix);
553 if (!strcmp(av[1], "lock"))
554 return lock_worktree(ac - 1, av + 1, prefix);
555 if (!strcmp(av[1], "unlock"))
556 return unlock_worktree(ac - 1, av + 1, prefix);
557 usage_with_options(worktree_usage, options);