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