worktree: add --[no-]track option to the add subcommand
[git/git.git] / builtin / worktree.c
CommitLineData
df0b6cfb 1#include "cache.h"
b2141fc1 2#include "config.h"
df0b6cfb
NTND
3#include "builtin.h"
4#include "dir.h"
5#include "parse-options.h"
fc56361f 6#include "argv-array.h"
f7c9dac1
ES
7#include "branch.h"
8#include "refs.h"
fc56361f 9#include "run-command.h"
b979d950 10#include "sigchain.h"
799767cc 11#include "refs.h"
bb9c03b8
MR
12#include "utf8.h"
13#include "worktree.h"
df0b6cfb
NTND
14
15static const char * const worktree_usage[] = {
ae9f2745 16 N_("git worktree add [<options>] <path> [<branch>]"),
bb9c03b8 17 N_("git worktree list [<options>]"),
58142c09 18 N_("git worktree lock [<options>] <path>"),
7b722d90 19 N_("git worktree prune [<options>]"),
6d308627 20 N_("git worktree unlock <path>"),
df0b6cfb
NTND
21 NULL
22};
23
5dd6e234
ES
24struct add_opts {
25 int force;
26 int detach;
ef2a0ac9 27 int checkout;
507e6e9e 28 int keep_locked;
5dd6e234
ES
29 const char *new_branch;
30 int force_new_branch;
31};
32
df0b6cfb
NTND
33static int show_only;
34static int verbose;
dddbad72 35static timestamp_t expire;
df0b6cfb
NTND
36
37static int prune_worktree(const char *id, struct strbuf *reason)
38{
39 struct stat st;
40 char *path;
228740b6
JK
41 int fd;
42 size_t len;
8a1a8d2a 43 ssize_t read_result;
df0b6cfb
NTND
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 }
228740b6 61 len = xsize_t(st.st_size);
3733e694 62 path = xmallocz(len);
8a1a8d2a
JK
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 }
df0b6cfb 72 close(fd);
8a1a8d2a
JK
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 }
df0b6cfb
NTND
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) {
afb9e30b 120 if (is_dot_or_dotdot(d->d_name))
df0b6cfb
NTND
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;
8c2ca3a6 129 git_path_buf(&path, "worktrees/%s", d->d_name);
df0b6cfb
NTND
130 ret = remove_dir_recursively(&path, 0);
131 if (ret < 0 && errno == ENOTDIR)
132 ret = unlink(path.buf);
133 if (ret)
8d19e930 134 error_errno(_("failed to remove '%s'"), path.buf);
df0b6cfb
NTND
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")),
2488dcab 147 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
df0b6cfb 148 OPT_EXPIRY_DATE(0, "expire", &expire,
2488dcab 149 N_("expire working trees older than <time>")),
df0b6cfb
NTND
150 OPT_END()
151 };
152
dddbad72 153 expire = TIME_MAX;
df0b6cfb
NTND
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
b979d950
ES
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
f5682b2a
ES
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
80a0548f 209static int add_worktree(const char *path, const char *refname,
5dd6e234 210 const struct add_opts *opts)
b979d950
ES
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;
542aa25d 216 struct child_process cp = CHILD_PROCESS_INIT;
ae2a3827 217 struct argv_array child_env = ARGV_ARRAY_INIT;
b979d950 218 int counter = 0, len, ret;
f7c9dac1
ES
219 struct strbuf symref = STRBUF_INIT;
220 struct commit *commit = NULL;
b979d950
ES
221
222 if (file_exists(path) && !is_empty_dir(path))
223 die(_("'%s' already exists"), path);
224
f7c9dac1 225 /* is 'refname' a branch or commit? */
0ebf4a2a 226 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
f7c9dac1
ES
227 ref_exists(symref.buf)) { /* it's a branch */
228 if (!opts->force)
8d9fdd70 229 die_if_checked_out(symref.buf, 0);
f7c9dac1
ES
230 } else { /* must be a commit */
231 commit = lookup_commit_reference_by_name(refname);
232 if (!commit)
233 die(_("invalid reference: %s"), refname);
234 }
235
f5682b2a 236 name = worktree_basename(path, &len);
8c2ca3a6 237 git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
b979d950
ES
238 len = sb_repo.len;
239 if (safe_create_leading_directories_const(sb_repo.buf))
240 die_errno(_("could not create leading directories of '%s'"),
241 sb_repo.buf);
242 while (!stat(sb_repo.buf, &st)) {
243 counter++;
244 strbuf_setlen(&sb_repo, len);
245 strbuf_addf(&sb_repo, "%d", counter);
246 }
247 name = strrchr(sb_repo.buf, '/') + 1;
248
249 junk_pid = getpid();
250 atexit(remove_junk);
251 sigchain_push_common(remove_junk_on_signal);
252
253 if (mkdir(sb_repo.buf, 0777))
254 die_errno(_("could not create directory of '%s'"), sb_repo.buf);
255 junk_git_dir = xstrdup(sb_repo.buf);
256 is_junk = 1;
257
258 /*
259 * lock the incomplete repo so prune won't delete it, unlock
260 * after the preparation is over.
261 */
262 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
507e6e9e
NTND
263 if (!opts->keep_locked)
264 write_file(sb.buf, "initializing");
265 else
266 write_file(sb.buf, "added with --lock");
b979d950
ES
267
268 strbuf_addf(&sb_git, "%s/.git", path);
269 if (safe_create_leading_directories_const(sb_git.buf))
270 die_errno(_("could not create leading directories of '%s'"),
271 sb_git.buf);
272 junk_work_tree = xstrdup(path);
273
274 strbuf_reset(&sb);
275 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
1f76a10b
JH
276 write_file(sb.buf, "%s", real_path(sb_git.buf));
277 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
b979d950
ES
278 real_path(get_git_common_dir()), name);
279 /*
280 * This is to keep resolve_ref() happy. We need a valid HEAD
ed197a6a
ES
281 * or is_git_directory() will reject the directory. Any value which
282 * looks like an object ID will do since it will be immediately
283 * replaced by the symbolic-ref or update-ref invocation in the new
284 * worktree.
b979d950 285 */
b979d950
ES
286 strbuf_reset(&sb);
287 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
dabd35f4 288 write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
b979d950
ES
289 strbuf_reset(&sb);
290 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
1f76a10b 291 write_file(sb.buf, "../..");
b979d950 292
cd2f4713 293 fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
b979d950 294
ae2a3827
ES
295 argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
296 argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
b979d950 297 cp.git_cmd = 1;
7f44e3d1
ES
298
299 if (commit)
300 argv_array_pushl(&cp.args, "update-ref", "HEAD",
f2fd0760 301 oid_to_hex(&commit->object.oid), NULL);
7f44e3d1
ES
302 else
303 argv_array_pushl(&cp.args, "symbolic-ref", "HEAD",
304 symref.buf, NULL);
305 cp.env = child_env.argv;
306 ret = run_command(&cp);
307 if (ret)
308 goto done;
309
ef2a0ac9
RZ
310 if (opts->checkout) {
311 cp.argv = NULL;
312 argv_array_clear(&cp.args);
313 argv_array_pushl(&cp.args, "reset", "--hard", NULL);
314 cp.env = child_env.argv;
315 ret = run_command(&cp);
316 if (ret)
317 goto done;
b979d950 318 }
ef2a0ac9
RZ
319
320 is_junk = 0;
88ce3ef6
ÆAB
321 FREE_AND_NULL(junk_work_tree);
322 FREE_AND_NULL(junk_git_dir);
ef2a0ac9 323
7f44e3d1 324done:
507e6e9e
NTND
325 if (ret || !opts->keep_locked) {
326 strbuf_reset(&sb);
327 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
328 unlink_or_warn(sb.buf);
329 }
ae2a3827 330 argv_array_clear(&child_env);
b979d950 331 strbuf_release(&sb);
f7c9dac1 332 strbuf_release(&symref);
b979d950
ES
333 strbuf_release(&sb_repo);
334 strbuf_release(&sb_git);
335 return ret;
336}
337
fc56361f
ES
338static int add(int ac, const char **av, const char *prefix)
339{
5dd6e234
ES
340 struct add_opts opts;
341 const char *new_branch_force = NULL;
e4da43b1
JK
342 char *path;
343 const char *branch;
e284e892 344 const char *opt_track = NULL;
fc56361f 345 struct option options[] = {
5dd6e234
ES
346 OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
347 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
cbdf60fa
ES
348 N_("create a new branch")),
349 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
350 N_("create or reset a branch")),
5dd6e234 351 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
ef2a0ac9 352 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
507e6e9e 353 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
e284e892
TG
354 OPT_PASSTHRU(0, "track", &opt_track, NULL,
355 N_("set up tracking mode (see git-branch(1))"),
356 PARSE_OPT_NOARG | PARSE_OPT_OPTARG),
fc56361f
ES
357 OPT_END()
358 };
359
5dd6e234 360 memset(&opts, 0, sizeof(opts));
ef2a0ac9 361 opts.checkout = 1;
fc56361f 362 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
ab0b2c53
ES
363 if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
364 die(_("-b, -B, and --detach are mutually exclusive"));
0f4af3b9
ES
365 if (ac < 1 || ac > 2)
366 usage_with_options(worktree_usage, options);
fc56361f 367
116fb64e 368 path = prefix_filename(prefix, av[0]);
0f4af3b9 369 branch = ac < 2 ? "HEAD" : av[1];
fc56361f 370
1a450e2f
JDG
371 if (!strcmp(branch, "-"))
372 branch = "@{-1}";
373
5dd6e234 374 opts.force_new_branch = !!new_branch_force;
beb6f24b
NTND
375 if (opts.force_new_branch) {
376 struct strbuf symref = STRBUF_INIT;
377
5dd6e234 378 opts.new_branch = new_branch_force;
eef005dc 379
beb6f24b
NTND
380 if (!opts.force &&
381 !strbuf_check_branch_ref(&symref, opts.new_branch) &&
382 ref_exists(symref.buf))
8d9fdd70 383 die_if_checked_out(symref.buf, 0);
beb6f24b
NTND
384 strbuf_release(&symref);
385 }
386
5c942570 387 if (ac < 2 && !opts.new_branch && !opts.detach) {
1eb07d82
ES
388 int n;
389 const char *s = worktree_basename(path, &n);
5dd6e234 390 opts.new_branch = xstrndup(s, n);
1eb07d82
ES
391 }
392
c2842439 393 if (opts.new_branch) {
542aa25d 394 struct child_process cp = CHILD_PROCESS_INIT;
c2842439
ES
395 cp.git_cmd = 1;
396 argv_array_push(&cp.args, "branch");
397 if (opts.force_new_branch)
398 argv_array_push(&cp.args, "--force");
399 argv_array_push(&cp.args, opts.new_branch);
400 argv_array_push(&cp.args, branch);
e284e892
TG
401 if (opt_track)
402 argv_array_push(&cp.args, opt_track);
c2842439
ES
403 if (run_command(&cp))
404 return -1;
405 branch = opts.new_branch;
e284e892
TG
406 } else if (opt_track) {
407 die(_("--[no-]track can only be used if a new branch is created"));
1eb07d82
ES
408 }
409
0e5bba53
JK
410 UNLEAK(path);
411 UNLEAK(opts);
80a0548f 412 return add_worktree(path, branch, &opts);
fc56361f
ES
413}
414
bb9c03b8
MR
415static void show_worktree_porcelain(struct worktree *wt)
416{
417 printf("worktree %s\n", wt->path);
418 if (wt->is_bare)
419 printf("bare\n");
420 else {
0f05154c 421 printf("HEAD %s\n", oid_to_hex(&wt->head_oid));
bb9c03b8
MR
422 if (wt->is_detached)
423 printf("detached\n");
a234563a 424 else if (wt->head_ref)
bb9c03b8
MR
425 printf("branch %s\n", wt->head_ref);
426 }
427 printf("\n");
428}
429
430static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
431{
432 struct strbuf sb = STRBUF_INIT;
433 int cur_path_len = strlen(wt->path);
434 int path_adj = cur_path_len - utf8_strwidth(wt->path);
435
436 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
437 if (wt->is_bare)
438 strbuf_addstr(&sb, "(bare)");
439 else {
440 strbuf_addf(&sb, "%-*s ", abbrev_len,
0f05154c 441 find_unique_abbrev(wt->head_oid.hash, DEFAULT_ABBREV));
96f09e2a 442 if (wt->is_detached)
bb9c03b8 443 strbuf_addstr(&sb, "(detached HEAD)");
2e11f58f
JS
444 else if (wt->head_ref) {
445 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
446 strbuf_addf(&sb, "[%s]", ref);
447 free(ref);
448 } else
a234563a 449 strbuf_addstr(&sb, "(error)");
bb9c03b8
MR
450 }
451 printf("%s\n", sb.buf);
452
453 strbuf_release(&sb);
454}
455
456static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
457{
458 int i;
459
460 for (i = 0; wt[i]; i++) {
461 int sha1_len;
462 int path_len = strlen(wt[i]->path);
463
464 if (path_len > *maxlen)
465 *maxlen = path_len;
0f05154c 466 sha1_len = strlen(find_unique_abbrev(wt[i]->head_oid.hash, *abbrev));
bb9c03b8
MR
467 if (sha1_len > *abbrev)
468 *abbrev = sha1_len;
469 }
470}
471
472static int list(int ac, const char **av, const char *prefix)
473{
474 int porcelain = 0;
475
476 struct option options[] = {
477 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
478 OPT_END()
479 };
480
481 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
482 if (ac)
483 usage_with_options(worktree_usage, options);
484 else {
4df1d4d4 485 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
bb9c03b8
MR
486 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
487
488 if (!porcelain)
489 measure_widths(worktrees, &abbrev, &path_maxlen);
490
491 for (i = 0; worktrees[i]; i++) {
492 if (porcelain)
493 show_worktree_porcelain(worktrees[i]);
494 else
495 show_worktree(worktrees[i], path_maxlen, abbrev);
496 }
497 free_worktrees(worktrees);
498 }
499 return 0;
500}
501
58142c09
NTND
502static int lock_worktree(int ac, const char **av, const char *prefix)
503{
504 const char *reason = "", *old_reason;
505 struct option options[] = {
506 OPT_STRING(0, "reason", &reason, N_("string"),
507 N_("reason for locking")),
508 OPT_END()
509 };
510 struct worktree **worktrees, *wt;
511
512 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
513 if (ac != 1)
514 usage_with_options(worktree_usage, options);
515
4fff1ef7 516 worktrees = get_worktrees(0);
58142c09
NTND
517 wt = find_worktree(worktrees, prefix, av[0]);
518 if (!wt)
519 die(_("'%s' is not a working tree"), av[0]);
520 if (is_main_worktree(wt))
521 die(_("The main working tree cannot be locked or unlocked"));
522
523 old_reason = is_worktree_locked(wt);
524 if (old_reason) {
525 if (*old_reason)
526 die(_("'%s' is already locked, reason: %s"),
527 av[0], old_reason);
528 die(_("'%s' is already locked"), av[0]);
529 }
530
531 write_file(git_common_path("worktrees/%s/locked", wt->id),
532 "%s", reason);
533 free_worktrees(worktrees);
534 return 0;
535}
536
6d308627
NTND
537static int unlock_worktree(int ac, const char **av, const char *prefix)
538{
539 struct option options[] = {
540 OPT_END()
541 };
542 struct worktree **worktrees, *wt;
543 int ret;
544
545 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
546 if (ac != 1)
547 usage_with_options(worktree_usage, options);
548
4fff1ef7 549 worktrees = get_worktrees(0);
6d308627
NTND
550 wt = find_worktree(worktrees, prefix, av[0]);
551 if (!wt)
552 die(_("'%s' is not a working tree"), av[0]);
553 if (is_main_worktree(wt))
554 die(_("The main working tree cannot be locked or unlocked"));
555 if (!is_worktree_locked(wt))
556 die(_("'%s' is not locked"), av[0]);
557 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
558 free_worktrees(worktrees);
559 return ret;
560}
561
df0b6cfb
NTND
562int cmd_worktree(int ac, const char **av, const char *prefix)
563{
564 struct option options[] = {
565 OPT_END()
566 };
567
d49028e6
JH
568 git_config(git_default_config, NULL);
569
df0b6cfb
NTND
570 if (ac < 2)
571 usage_with_options(worktree_usage, options);
0409e0b6
NTND
572 if (!prefix)
573 prefix = "";
fc56361f
ES
574 if (!strcmp(av[1], "add"))
575 return add(ac - 1, av + 1, prefix);
df0b6cfb
NTND
576 if (!strcmp(av[1], "prune"))
577 return prune(ac - 1, av + 1, prefix);
bb9c03b8
MR
578 if (!strcmp(av[1], "list"))
579 return list(ac - 1, av + 1, prefix);
58142c09
NTND
580 if (!strcmp(av[1], "lock"))
581 return lock_worktree(ac - 1, av + 1, prefix);
6d308627
NTND
582 if (!strcmp(av[1], "unlock"))
583 return unlock_worktree(ac - 1, av + 1, prefix);
df0b6cfb
NTND
584 usage_with_options(worktree_usage, options);
585}