worktree: add "unlock" command
[git/debian.git] / builtin / worktree.c
blob48774211189b939591428e2d28d9e3d59ed3c1a5
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 const char *new_branch;
28 int force_new_branch;
31 static int show_only;
32 static int verbose;
33 static unsigned long expire;
35 static int prune_worktree(const char *id, struct strbuf *reason)
37 struct stat st;
38 char *path;
39 int fd, len;
41 if (!is_directory(git_path("worktrees/%s", id))) {
42 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
43 return 1;
45 if (file_exists(git_path("worktrees/%s/locked", id)))
46 return 0;
47 if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
48 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file does not exist"), id);
49 return 1;
51 fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
52 if (fd < 0) {
53 strbuf_addf(reason, _("Removing worktrees/%s: unable to read gitdir file (%s)"),
54 id, strerror(errno));
55 return 1;
57 len = st.st_size;
58 path = xmallocz(len);
59 read_in_full(fd, path, len);
60 close(fd);
61 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
62 len--;
63 if (!len) {
64 strbuf_addf(reason, _("Removing worktrees/%s: invalid gitdir file"), id);
65 free(path);
66 return 1;
68 path[len] = '\0';
69 if (!file_exists(path)) {
70 struct stat st_link;
71 free(path);
73 * the repo is moved manually and has not been
74 * accessed since?
76 if (!stat(git_path("worktrees/%s/link", id), &st_link) &&
77 st_link.st_nlink > 1)
78 return 0;
79 if (st.st_mtime <= expire) {
80 strbuf_addf(reason, _("Removing worktrees/%s: gitdir file points to non-existent location"), id);
81 return 1;
82 } else {
83 return 0;
86 free(path);
87 return 0;
90 static void prune_worktrees(void)
92 struct strbuf reason = STRBUF_INIT;
93 struct strbuf path = STRBUF_INIT;
94 DIR *dir = opendir(git_path("worktrees"));
95 struct dirent *d;
96 int ret;
97 if (!dir)
98 return;
99 while ((d = readdir(dir)) != NULL) {
100 if (is_dot_or_dotdot(d->d_name))
101 continue;
102 strbuf_reset(&reason);
103 if (!prune_worktree(d->d_name, &reason))
104 continue;
105 if (show_only || verbose)
106 printf("%s\n", reason.buf);
107 if (show_only)
108 continue;
109 strbuf_reset(&path);
110 strbuf_addstr(&path, git_path("worktrees/%s", d->d_name));
111 ret = remove_dir_recursively(&path, 0);
112 if (ret < 0 && errno == ENOTDIR)
113 ret = unlink(path.buf);
114 if (ret)
115 error(_("failed to remove: %s"), strerror(errno));
117 closedir(dir);
118 if (!show_only)
119 rmdir(git_path("worktrees"));
120 strbuf_release(&reason);
121 strbuf_release(&path);
124 static int prune(int ac, const char **av, const char *prefix)
126 struct option options[] = {
127 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
128 OPT__VERBOSE(&verbose, N_("report pruned objects")),
129 OPT_EXPIRY_DATE(0, "expire", &expire,
130 N_("expire objects older than <time>")),
131 OPT_END()
134 expire = ULONG_MAX;
135 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
136 if (ac)
137 usage_with_options(worktree_usage, options);
138 prune_worktrees();
139 return 0;
142 static char *junk_work_tree;
143 static char *junk_git_dir;
144 static int is_junk;
145 static pid_t junk_pid;
147 static void remove_junk(void)
149 struct strbuf sb = STRBUF_INIT;
150 if (!is_junk || getpid() != junk_pid)
151 return;
152 if (junk_git_dir) {
153 strbuf_addstr(&sb, junk_git_dir);
154 remove_dir_recursively(&sb, 0);
155 strbuf_reset(&sb);
157 if (junk_work_tree) {
158 strbuf_addstr(&sb, junk_work_tree);
159 remove_dir_recursively(&sb, 0);
161 strbuf_release(&sb);
164 static void remove_junk_on_signal(int signo)
166 remove_junk();
167 sigchain_pop(signo);
168 raise(signo);
171 static const char *worktree_basename(const char *path, int *olen)
173 const char *name;
174 int len;
176 len = strlen(path);
177 while (len && is_dir_sep(path[len - 1]))
178 len--;
180 for (name = path + len - 1; name > path; name--)
181 if (is_dir_sep(*name)) {
182 name++;
183 break;
186 *olen = len;
187 return name;
190 static int add_worktree(const char *path, const char *refname,
191 const struct add_opts *opts)
193 struct strbuf sb_git = STRBUF_INIT, sb_repo = STRBUF_INIT;
194 struct strbuf sb = STRBUF_INIT;
195 const char *name;
196 struct stat st;
197 struct child_process cp;
198 struct argv_array child_env = ARGV_ARRAY_INIT;
199 int counter = 0, len, ret;
200 struct strbuf symref = STRBUF_INIT;
201 struct commit *commit = NULL;
203 if (file_exists(path) && !is_empty_dir(path))
204 die(_("'%s' already exists"), path);
206 /* is 'refname' a branch or commit? */
207 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
208 ref_exists(symref.buf)) { /* it's a branch */
209 if (!opts->force)
210 die_if_checked_out(symref.buf, 0);
211 } else { /* must be a commit */
212 commit = lookup_commit_reference_by_name(refname);
213 if (!commit)
214 die(_("invalid reference: %s"), refname);
217 name = worktree_basename(path, &len);
218 strbuf_addstr(&sb_repo,
219 git_path("worktrees/%.*s", (int)(path + len - name), name));
220 len = sb_repo.len;
221 if (safe_create_leading_directories_const(sb_repo.buf))
222 die_errno(_("could not create leading directories of '%s'"),
223 sb_repo.buf);
224 while (!stat(sb_repo.buf, &st)) {
225 counter++;
226 strbuf_setlen(&sb_repo, len);
227 strbuf_addf(&sb_repo, "%d", counter);
229 name = strrchr(sb_repo.buf, '/') + 1;
231 junk_pid = getpid();
232 atexit(remove_junk);
233 sigchain_push_common(remove_junk_on_signal);
235 if (mkdir(sb_repo.buf, 0777))
236 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
237 junk_git_dir = xstrdup(sb_repo.buf);
238 is_junk = 1;
241 * lock the incomplete repo so prune won't delete it, unlock
242 * after the preparation is over.
244 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
245 write_file(sb.buf, "initializing");
247 strbuf_addf(&sb_git, "%s/.git", path);
248 if (safe_create_leading_directories_const(sb_git.buf))
249 die_errno(_("could not create leading directories of '%s'"),
250 sb_git.buf);
251 junk_work_tree = xstrdup(path);
253 strbuf_reset(&sb);
254 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
255 write_file(sb.buf, "%s", real_path(sb_git.buf));
256 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
257 real_path(get_git_common_dir()), name);
259 * This is to keep resolve_ref() happy. We need a valid HEAD
260 * or is_git_directory() will reject the directory. Any value which
261 * looks like an object ID will do since it will be immediately
262 * replaced by the symbolic-ref or update-ref invocation in the new
263 * worktree.
265 strbuf_reset(&sb);
266 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
267 write_file(sb.buf, sha1_to_hex(null_sha1));
268 strbuf_reset(&sb);
269 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
270 write_file(sb.buf, "../..");
272 fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
274 argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
275 argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
276 memset(&cp, 0, sizeof(cp));
277 cp.git_cmd = 1;
279 if (commit)
280 argv_array_pushl(&cp.args, "update-ref", "HEAD",
281 oid_to_hex(&commit->object.oid), NULL);
282 else
283 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
284 symref.buf, NULL);
285 cp.env = child_env.argv;
286 ret = run_command(&cp);
287 if (ret)
288 goto done;
290 if (opts->checkout) {
291 cp.argv = NULL;
292 argv_array_clear(&cp.args);
293 argv_array_pushl(&cp.args, "reset", "--hard", NULL);
294 cp.env = child_env.argv;
295 ret = run_command(&cp);
296 if (ret)
297 goto done;
300 is_junk = 0;
301 free(junk_work_tree);
302 free(junk_git_dir);
303 junk_work_tree = NULL;
304 junk_git_dir = NULL;
306 done:
307 strbuf_reset(&sb);
308 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
309 unlink_or_warn(sb.buf);
310 argv_array_clear(&child_env);
311 strbuf_release(&sb);
312 strbuf_release(&symref);
313 strbuf_release(&sb_repo);
314 strbuf_release(&sb_git);
315 return ret;
318 static int add(int ac, const char **av, const char *prefix)
320 struct add_opts opts;
321 const char *new_branch_force = NULL;
322 const char *path, *branch;
323 struct option options[] = {
324 OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
325 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
326 N_("create a new branch")),
327 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
328 N_("create or reset a branch")),
329 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
330 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
331 OPT_END()
334 memset(&opts, 0, sizeof(opts));
335 opts.checkout = 1;
336 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
337 if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
338 die(_("-b, -B, and --detach are mutually exclusive"));
339 if (ac < 1 || ac > 2)
340 usage_with_options(worktree_usage, options);
342 path = prefix_filename(prefix, strlen(prefix), av[0]);
343 branch = ac < 2 ? "HEAD" : av[1];
345 opts.force_new_branch = !!new_branch_force;
346 if (opts.force_new_branch) {
347 struct strbuf symref = STRBUF_INIT;
349 opts.new_branch = new_branch_force;
351 if (!opts.force &&
352 !strbuf_check_branch_ref(&symref, opts.new_branch) &&
353 ref_exists(symref.buf))
354 die_if_checked_out(symref.buf, 0);
355 strbuf_release(&symref);
358 if (ac < 2 && !opts.new_branch && !opts.detach) {
359 int n;
360 const char *s = worktree_basename(path, &n);
361 opts.new_branch = xstrndup(s, n);
364 if (opts.new_branch) {
365 struct child_process cp;
366 memset(&cp, 0, sizeof(cp));
367 cp.git_cmd = 1;
368 argv_array_push(&cp.args, "branch");
369 if (opts.force_new_branch)
370 argv_array_push(&cp.args, "--force");
371 argv_array_push(&cp.args, opts.new_branch);
372 argv_array_push(&cp.args, branch);
373 if (run_command(&cp))
374 return -1;
375 branch = opts.new_branch;
378 return add_worktree(path, branch, &opts);
381 static void show_worktree_porcelain(struct worktree *wt)
383 printf("worktree %s\n", wt->path);
384 if (wt->is_bare)
385 printf("bare\n");
386 else {
387 printf("HEAD %s\n", sha1_to_hex(wt->head_sha1));
388 if (wt->is_detached)
389 printf("detached\n");
390 else
391 printf("branch %s\n", wt->head_ref);
393 printf("\n");
396 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
398 struct strbuf sb = STRBUF_INIT;
399 int cur_path_len = strlen(wt->path);
400 int path_adj = cur_path_len - utf8_strwidth(wt->path);
402 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
403 if (wt->is_bare)
404 strbuf_addstr(&sb, "(bare)");
405 else {
406 strbuf_addf(&sb, "%-*s ", abbrev_len,
407 find_unique_abbrev(wt->head_sha1, DEFAULT_ABBREV));
408 if (!wt->is_detached)
409 strbuf_addf(&sb, "[%s]", shorten_unambiguous_ref(wt->head_ref, 0));
410 else
411 strbuf_addstr(&sb, "(detached HEAD)");
413 printf("%s\n", sb.buf);
415 strbuf_release(&sb);
418 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
420 int i;
422 for (i = 0; wt[i]; i++) {
423 int sha1_len;
424 int path_len = strlen(wt[i]->path);
426 if (path_len > *maxlen)
427 *maxlen = path_len;
428 sha1_len = strlen(find_unique_abbrev(wt[i]->head_sha1, *abbrev));
429 if (sha1_len > *abbrev)
430 *abbrev = sha1_len;
434 static int list(int ac, const char **av, const char *prefix)
436 int porcelain = 0;
438 struct option options[] = {
439 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
440 OPT_END()
443 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
444 if (ac)
445 usage_with_options(worktree_usage, options);
446 else {
447 struct worktree **worktrees = get_worktrees();
448 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
450 if (!porcelain)
451 measure_widths(worktrees, &abbrev, &path_maxlen);
453 for (i = 0; worktrees[i]; i++) {
454 if (porcelain)
455 show_worktree_porcelain(worktrees[i]);
456 else
457 show_worktree(worktrees[i], path_maxlen, abbrev);
459 free_worktrees(worktrees);
461 return 0;
464 static int lock_worktree(int ac, const char **av, const char *prefix)
466 const char *reason = "", *old_reason;
467 struct option options[] = {
468 OPT_STRING(0, "reason", &reason, N_("string"),
469 N_("reason for locking")),
470 OPT_END()
472 struct worktree **worktrees, *wt;
474 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
475 if (ac != 1)
476 usage_with_options(worktree_usage, options);
478 worktrees = get_worktrees();
479 wt = find_worktree(worktrees, prefix, av[0]);
480 if (!wt)
481 die(_("'%s' is not a working tree"), av[0]);
482 if (is_main_worktree(wt))
483 die(_("The main working tree cannot be locked or unlocked"));
485 old_reason = is_worktree_locked(wt);
486 if (old_reason) {
487 if (*old_reason)
488 die(_("'%s' is already locked, reason: %s"),
489 av[0], old_reason);
490 die(_("'%s' is already locked"), av[0]);
493 write_file(git_common_path("worktrees/%s/locked", wt->id),
494 "%s", reason);
495 free_worktrees(worktrees);
496 return 0;
499 static int unlock_worktree(int ac, const char **av, const char *prefix)
501 struct option options[] = {
502 OPT_END()
504 struct worktree **worktrees, *wt;
505 int ret;
507 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
508 if (ac != 1)
509 usage_with_options(worktree_usage, options);
511 worktrees = get_worktrees();
512 wt = find_worktree(worktrees, prefix, av[0]);
513 if (!wt)
514 die(_("'%s' is not a working tree"), av[0]);
515 if (is_main_worktree(wt))
516 die(_("The main working tree cannot be locked or unlocked"));
517 if (!is_worktree_locked(wt))
518 die(_("'%s' is not locked"), av[0]);
519 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
520 free_worktrees(worktrees);
521 return ret;
524 int cmd_worktree(int ac, const char **av, const char *prefix)
526 struct option options[] = {
527 OPT_END()
530 if (ac < 2)
531 usage_with_options(worktree_usage, options);
532 if (!prefix)
533 prefix = "";
534 if (!strcmp(av[1], "add"))
535 return add(ac - 1, av + 1, prefix);
536 if (!strcmp(av[1], "prune"))
537 return prune(ac - 1, av + 1, prefix);
538 if (!strcmp(av[1], "list"))
539 return list(ac - 1, av + 1, prefix);
540 if (!strcmp(av[1], "lock"))
541 return lock_worktree(ac - 1, av + 1, prefix);
542 if (!strcmp(av[1], "unlock"))
543 return unlock_worktree(ac - 1, av + 1, prefix);
544 usage_with_options(worktree_usage, options);