remote-mediawiki: support fetching from (Main) namespace
[git.git] / builtin / worktree.c
blob7b9307aa588a70a47de4c53a380e165f90924ab9
1 #include "cache.h"
2 #include "config.h"
3 #include "builtin.h"
4 #include "dir.h"
5 #include "parse-options.h"
6 #include "argv-array.h"
7 #include "branch.h"
8 #include "refs.h"
9 #include "run-command.h"
10 #include "sigchain.h"
11 #include "refs.h"
12 #include "utf8.h"
13 #include "worktree.h"
15 static const char * const worktree_usage[] = {
16 N_("git worktree add [<options>] <path> [<branch>]"),
17 N_("git worktree list [<options>]"),
18 N_("git worktree lock [<options>] <path>"),
19 N_("git worktree prune [<options>]"),
20 N_("git worktree unlock <path>"),
21 NULL
24 struct add_opts {
25 int force;
26 int detach;
27 int checkout;
28 int keep_locked;
29 const char *new_branch;
30 int force_new_branch;
33 static int show_only;
34 static int verbose;
35 static timestamp_t expire;
37 static int prune_worktree(const char *id, struct strbuf *reason)
39 struct stat st;
40 char *path;
41 int fd;
42 size_t len;
43 ssize_t read_result;
45 if (!is_directory(git_path("worktrees/%s", id))) {
46 strbuf_addf(reason, _("Removing worktrees/%s: not a valid directory"), id);
47 return 1;
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;
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;
61 len = xsize_t(st.st_size);
62 path = xmallocz(len);
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;
72 close(fd);
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;
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;
88 path[len] = '\0';
89 if (!file_exists(path)) {
90 struct stat st_link;
91 free(path);
93 * the repo is moved manually and has not been
94 * accessed since?
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;
106 free(path);
107 return 0;
110 static void prune_worktrees(void)
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) {
120 if (is_dot_or_dotdot(d->d_name))
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;
129 git_path_buf(&path, "worktrees/%s", d->d_name);
130 ret = remove_dir_recursively(&path, 0);
131 if (ret < 0 && errno == ENOTDIR)
132 ret = unlink(path.buf);
133 if (ret)
134 error_errno(_("failed to remove '%s'"), path.buf);
136 closedir(dir);
137 if (!show_only)
138 rmdir(git_path("worktrees"));
139 strbuf_release(&reason);
140 strbuf_release(&path);
143 static int prune(int ac, const char **av, const char *prefix)
145 struct option options[] = {
146 OPT__DRY_RUN(&show_only, N_("do not remove, show only")),
147 OPT__VERBOSE(&verbose, N_("report pruned working trees")),
148 OPT_EXPIRY_DATE(0, "expire", &expire,
149 N_("expire working trees older than <time>")),
150 OPT_END()
153 expire = TIME_MAX;
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;
161 static char *junk_work_tree;
162 static char *junk_git_dir;
163 static int is_junk;
164 static pid_t junk_pid;
166 static void remove_junk(void)
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);
176 if (junk_work_tree) {
177 strbuf_addstr(&sb, junk_work_tree);
178 remove_dir_recursively(&sb, 0);
180 strbuf_release(&sb);
183 static void remove_junk_on_signal(int signo)
185 remove_junk();
186 sigchain_pop(signo);
187 raise(signo);
190 static const char *worktree_basename(const char *path, int *olen)
192 const char *name;
193 int len;
195 len = strlen(path);
196 while (len && is_dir_sep(path[len - 1]))
197 len--;
199 for (name = path + len - 1; name > path; name--)
200 if (is_dir_sep(*name)) {
201 name++;
202 break;
205 *olen = len;
206 return name;
209 static int add_worktree(const char *path, const char *refname,
210 const struct add_opts *opts)
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;
216 struct child_process cp = CHILD_PROCESS_INIT;
217 struct argv_array child_env = ARGV_ARRAY_INIT;
218 int counter = 0, len, ret;
219 struct strbuf symref = STRBUF_INIT;
220 struct commit *commit = NULL;
222 if (file_exists(path) && !is_empty_dir(path))
223 die(_("'%s' already exists"), path);
225 /* is 'refname' a branch or commit? */
226 if (!opts->detach && !strbuf_check_branch_ref(&symref, refname) &&
227 ref_exists(symref.buf)) { /* it's a branch */
228 if (!opts->force)
229 die_if_checked_out(symref.buf, 0);
230 } else { /* must be a commit */
231 commit = lookup_commit_reference_by_name(refname);
232 if (!commit)
233 die(_("invalid reference: %s"), refname);
236 name = worktree_basename(path, &len);
237 git_path_buf(&sb_repo, "worktrees/%.*s", (int)(path + len - name), name);
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);
247 name = strrchr(sb_repo.buf, '/') + 1;
249 junk_pid = getpid();
250 atexit(remove_junk);
251 sigchain_push_common(remove_junk_on_signal);
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;
259 * lock the incomplete repo so prune won't delete it, unlock
260 * after the preparation is over.
262 strbuf_addf(&sb, "%s/locked", sb_repo.buf);
263 if (!opts->keep_locked)
264 write_file(sb.buf, "initializing");
265 else
266 write_file(sb.buf, "added with --lock");
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);
274 strbuf_reset(&sb);
275 strbuf_addf(&sb, "%s/gitdir", sb_repo.buf);
276 write_file(sb.buf, "%s", real_path(sb_git.buf));
277 write_file(sb_git.buf, "gitdir: %s/worktrees/%s",
278 real_path(get_git_common_dir()), name);
280 * This is to keep resolve_ref() happy. We need a valid HEAD
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.
286 strbuf_reset(&sb);
287 strbuf_addf(&sb, "%s/HEAD", sb_repo.buf);
288 write_file(sb.buf, "%s", sha1_to_hex(null_sha1));
289 strbuf_reset(&sb);
290 strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
291 write_file(sb.buf, "../..");
293 fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
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);
297 cp.git_cmd = 1;
299 if (commit)
300 argv_array_pushl(&cp.args, "update-ref", "HEAD",
301 oid_to_hex(&commit->object.oid), NULL);
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;
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;
320 is_junk = 0;
321 FREE_AND_NULL(junk_work_tree);
322 FREE_AND_NULL(junk_git_dir);
324 done:
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);
330 argv_array_clear(&child_env);
331 strbuf_release(&sb);
332 strbuf_release(&symref);
333 strbuf_release(&sb_repo);
334 strbuf_release(&sb_git);
335 return ret;
338 static int add(int ac, const char **av, const char *prefix)
340 struct add_opts opts;
341 const char *new_branch_force = NULL;
342 char *path;
343 const char *branch;
344 struct option options[] = {
345 OPT__FORCE(&opts.force, N_("checkout <branch> even if already checked out in other worktree")),
346 OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
347 N_("create a new branch")),
348 OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
349 N_("create or reset a branch")),
350 OPT_BOOL(0, "detach", &opts.detach, N_("detach HEAD at named commit")),
351 OPT_BOOL(0, "checkout", &opts.checkout, N_("populate the new working tree")),
352 OPT_BOOL(0, "lock", &opts.keep_locked, N_("keep the new working tree locked")),
353 OPT_END()
356 memset(&opts, 0, sizeof(opts));
357 opts.checkout = 1;
358 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
359 if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
360 die(_("-b, -B, and --detach are mutually exclusive"));
361 if (ac < 1 || ac > 2)
362 usage_with_options(worktree_usage, options);
364 path = prefix_filename(prefix, av[0]);
365 branch = ac < 2 ? "HEAD" : av[1];
367 if (!strcmp(branch, "-"))
368 branch = "@{-1}";
370 opts.force_new_branch = !!new_branch_force;
371 if (opts.force_new_branch) {
372 struct strbuf symref = STRBUF_INIT;
374 opts.new_branch = new_branch_force;
376 if (!opts.force &&
377 !strbuf_check_branch_ref(&symref, opts.new_branch) &&
378 ref_exists(symref.buf))
379 die_if_checked_out(symref.buf, 0);
380 strbuf_release(&symref);
383 if (ac < 2 && !opts.new_branch && !opts.detach) {
384 int n;
385 const char *s = worktree_basename(path, &n);
386 opts.new_branch = xstrndup(s, n);
389 if (opts.new_branch) {
390 struct child_process cp = CHILD_PROCESS_INIT;
391 cp.git_cmd = 1;
392 argv_array_push(&cp.args, "branch");
393 if (opts.force_new_branch)
394 argv_array_push(&cp.args, "--force");
395 argv_array_push(&cp.args, opts.new_branch);
396 argv_array_push(&cp.args, branch);
397 if (run_command(&cp))
398 return -1;
399 branch = opts.new_branch;
402 UNLEAK(path);
403 UNLEAK(opts);
404 return add_worktree(path, branch, &opts);
407 static void show_worktree_porcelain(struct worktree *wt)
409 printf("worktree %s\n", wt->path);
410 if (wt->is_bare)
411 printf("bare\n");
412 else {
413 printf("HEAD %s\n", sha1_to_hex(wt->head_sha1));
414 if (wt->is_detached)
415 printf("detached\n");
416 else if (wt->head_ref)
417 printf("branch %s\n", wt->head_ref);
419 printf("\n");
422 static void show_worktree(struct worktree *wt, int path_maxlen, int abbrev_len)
424 struct strbuf sb = STRBUF_INIT;
425 int cur_path_len = strlen(wt->path);
426 int path_adj = cur_path_len - utf8_strwidth(wt->path);
428 strbuf_addf(&sb, "%-*s ", 1 + path_maxlen + path_adj, wt->path);
429 if (wt->is_bare)
430 strbuf_addstr(&sb, "(bare)");
431 else {
432 strbuf_addf(&sb, "%-*s ", abbrev_len,
433 find_unique_abbrev(wt->head_sha1, DEFAULT_ABBREV));
434 if (wt->is_detached)
435 strbuf_addstr(&sb, "(detached HEAD)");
436 else if (wt->head_ref) {
437 char *ref = shorten_unambiguous_ref(wt->head_ref, 0);
438 strbuf_addf(&sb, "[%s]", ref);
439 free(ref);
440 } else
441 strbuf_addstr(&sb, "(error)");
443 printf("%s\n", sb.buf);
445 strbuf_release(&sb);
448 static void measure_widths(struct worktree **wt, int *abbrev, int *maxlen)
450 int i;
452 for (i = 0; wt[i]; i++) {
453 int sha1_len;
454 int path_len = strlen(wt[i]->path);
456 if (path_len > *maxlen)
457 *maxlen = path_len;
458 sha1_len = strlen(find_unique_abbrev(wt[i]->head_sha1, *abbrev));
459 if (sha1_len > *abbrev)
460 *abbrev = sha1_len;
464 static int list(int ac, const char **av, const char *prefix)
466 int porcelain = 0;
468 struct option options[] = {
469 OPT_BOOL(0, "porcelain", &porcelain, N_("machine-readable output")),
470 OPT_END()
473 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
474 if (ac)
475 usage_with_options(worktree_usage, options);
476 else {
477 struct worktree **worktrees = get_worktrees(GWT_SORT_LINKED);
478 int path_maxlen = 0, abbrev = DEFAULT_ABBREV, i;
480 if (!porcelain)
481 measure_widths(worktrees, &abbrev, &path_maxlen);
483 for (i = 0; worktrees[i]; i++) {
484 if (porcelain)
485 show_worktree_porcelain(worktrees[i]);
486 else
487 show_worktree(worktrees[i], path_maxlen, abbrev);
489 free_worktrees(worktrees);
491 return 0;
494 static int lock_worktree(int ac, const char **av, const char *prefix)
496 const char *reason = "", *old_reason;
497 struct option options[] = {
498 OPT_STRING(0, "reason", &reason, N_("string"),
499 N_("reason for locking")),
500 OPT_END()
502 struct worktree **worktrees, *wt;
504 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
505 if (ac != 1)
506 usage_with_options(worktree_usage, options);
508 worktrees = get_worktrees(0);
509 wt = find_worktree(worktrees, prefix, av[0]);
510 if (!wt)
511 die(_("'%s' is not a working tree"), av[0]);
512 if (is_main_worktree(wt))
513 die(_("The main working tree cannot be locked or unlocked"));
515 old_reason = is_worktree_locked(wt);
516 if (old_reason) {
517 if (*old_reason)
518 die(_("'%s' is already locked, reason: %s"),
519 av[0], old_reason);
520 die(_("'%s' is already locked"), av[0]);
523 write_file(git_common_path("worktrees/%s/locked", wt->id),
524 "%s", reason);
525 free_worktrees(worktrees);
526 return 0;
529 static int unlock_worktree(int ac, const char **av, const char *prefix)
531 struct option options[] = {
532 OPT_END()
534 struct worktree **worktrees, *wt;
535 int ret;
537 ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
538 if (ac != 1)
539 usage_with_options(worktree_usage, options);
541 worktrees = get_worktrees(0);
542 wt = find_worktree(worktrees, prefix, av[0]);
543 if (!wt)
544 die(_("'%s' is not a working tree"), av[0]);
545 if (is_main_worktree(wt))
546 die(_("The main working tree cannot be locked or unlocked"));
547 if (!is_worktree_locked(wt))
548 die(_("'%s' is not locked"), av[0]);
549 ret = unlink_or_warn(git_common_path("worktrees/%s/locked", wt->id));
550 free_worktrees(worktrees);
551 return ret;
554 int cmd_worktree(int ac, const char **av, const char *prefix)
556 struct option options[] = {
557 OPT_END()
560 git_config(git_default_config, NULL);
562 if (ac < 2)
563 usage_with_options(worktree_usage, options);
564 if (!prefix)
565 prefix = "";
566 if (!strcmp(av[1], "add"))
567 return add(ac - 1, av + 1, prefix);
568 if (!strcmp(av[1], "prune"))
569 return prune(ac - 1, av + 1, prefix);
570 if (!strcmp(av[1], "list"))
571 return list(ac - 1, av + 1, prefix);
572 if (!strcmp(av[1], "lock"))
573 return lock_worktree(ac - 1, av + 1, prefix);
574 if (!strcmp(av[1], "unlock"))
575 return unlock_worktree(ac - 1, av + 1, prefix);
576 usage_with_options(worktree_usage, options);