The sixteenth batch
[git/gitster.git] / worktree.c
blobc34b9eb74e595af949d2c5ea8abf9687e90bbf0c
1 #define USE_THE_REPOSITORY_VARIABLE
2 #define DISABLE_SIGN_COMPARE_WARNINGS
4 #include "git-compat-util.h"
5 #include "abspath.h"
6 #include "environment.h"
7 #include "gettext.h"
8 #include "path.h"
9 #include "repository.h"
10 #include "refs.h"
11 #include "setup.h"
12 #include "strbuf.h"
13 #include "worktree.h"
14 #include "dir.h"
15 #include "wt-status.h"
16 #include "config.h"
18 void free_worktree(struct worktree *worktree)
20 if (!worktree)
21 return;
22 free(worktree->path);
23 free(worktree->id);
24 free(worktree->head_ref);
25 free(worktree->lock_reason);
26 free(worktree->prune_reason);
27 free(worktree);
30 void free_worktrees(struct worktree **worktrees)
32 int i = 0;
33 for (i = 0; worktrees[i]; i++)
34 free_worktree(worktrees[i]);
35 free (worktrees);
38 /**
39 * Update head_oid, head_ref and is_detached of the given worktree
41 static void add_head_info(struct worktree *wt)
43 int flags;
44 const char *target;
46 target = refs_resolve_ref_unsafe(get_worktree_ref_store(wt),
47 "HEAD",
49 &wt->head_oid, &flags);
50 if (!target)
51 return;
53 if (flags & REF_ISSYMREF)
54 wt->head_ref = xstrdup(target);
55 else
56 wt->is_detached = 1;
59 static int is_current_worktree(struct worktree *wt)
61 char *git_dir = absolute_pathdup(repo_get_git_dir(the_repository));
62 char *wt_git_dir = get_worktree_git_dir(wt);
63 int is_current = !fspathcmp(git_dir, absolute_path(wt_git_dir));
64 free(wt_git_dir);
65 free(git_dir);
66 return is_current;
70 * When in a secondary worktree, and when extensions.worktreeConfig
71 * is true, only $commondir/config and $commondir/worktrees/<id>/
72 * config.worktree are consulted, hence any core.bare=true setting in
73 * $commondir/config.worktree gets overlooked. Thus, check it manually
74 * to determine if the repository is bare.
76 static int is_main_worktree_bare(struct repository *repo)
78 int bare = 0;
79 struct config_set cs = {0};
80 char *worktree_config = xstrfmt("%s/config.worktree", repo_get_common_dir(repo));
82 git_configset_init(&cs);
83 git_configset_add_file(&cs, worktree_config);
84 git_configset_get_bool(&cs, "core.bare", &bare);
86 git_configset_clear(&cs);
87 free(worktree_config);
88 return bare;
91 /**
92 * get the main worktree
94 static struct worktree *get_main_worktree(int skip_reading_head)
96 struct worktree *worktree = NULL;
97 struct strbuf worktree_path = STRBUF_INIT;
99 strbuf_add_real_path(&worktree_path, repo_get_common_dir(the_repository));
100 strbuf_strip_suffix(&worktree_path, "/.git");
102 CALLOC_ARRAY(worktree, 1);
103 worktree->repo = the_repository;
104 worktree->path = strbuf_detach(&worktree_path, NULL);
105 worktree->is_current = is_current_worktree(worktree);
106 worktree->is_bare = (is_bare_repository_cfg == 1) ||
107 is_bare_repository() ||
109 * When in a secondary worktree we have to also verify if the main
110 * worktree is bare in $commondir/config.worktree.
111 * This check is unnecessary if we're currently in the main worktree,
112 * as prior checks already consulted all configs of the current worktree.
114 (!worktree->is_current && is_main_worktree_bare(the_repository));
116 if (!skip_reading_head)
117 add_head_info(worktree);
118 return worktree;
121 struct worktree *get_linked_worktree(const char *id,
122 int skip_reading_head)
124 struct worktree *worktree = NULL;
125 struct strbuf path = STRBUF_INIT;
126 struct strbuf worktree_path = STRBUF_INIT;
128 if (!id)
129 die("Missing linked worktree name");
131 repo_common_path_append(the_repository, &path, "worktrees/%s/gitdir", id);
132 if (strbuf_read_file(&worktree_path, path.buf, 0) <= 0)
133 /* invalid gitdir file */
134 goto done;
135 strbuf_rtrim(&worktree_path);
136 strbuf_strip_suffix(&worktree_path, "/.git");
138 if (!is_absolute_path(worktree_path.buf)) {
139 strbuf_strip_suffix(&path, "gitdir");
140 strbuf_addbuf(&path, &worktree_path);
141 strbuf_realpath_forgiving(&worktree_path, path.buf, 0);
144 CALLOC_ARRAY(worktree, 1);
145 worktree->repo = the_repository;
146 worktree->path = strbuf_detach(&worktree_path, NULL);
147 worktree->id = xstrdup(id);
148 worktree->is_current = is_current_worktree(worktree);
149 if (!skip_reading_head)
150 add_head_info(worktree);
152 done:
153 strbuf_release(&path);
154 strbuf_release(&worktree_path);
155 return worktree;
159 * NEEDSWORK: This function exists so that we can look up metadata of a
160 * worktree without trying to access any of its internals like the refdb. It
161 * would be preferable to instead have a corruption-tolerant function for
162 * retrieving worktree metadata that could be used when the worktree is known
163 * to not be in a healthy state, e.g. when creating or repairing it.
165 static struct worktree **get_worktrees_internal(int skip_reading_head)
167 struct worktree **list = NULL;
168 struct strbuf path = STRBUF_INIT;
169 DIR *dir;
170 struct dirent *d;
171 int counter = 0, alloc = 2;
173 ALLOC_ARRAY(list, alloc);
175 list[counter++] = get_main_worktree(skip_reading_head);
177 strbuf_addf(&path, "%s/worktrees", repo_get_common_dir(the_repository));
178 dir = opendir(path.buf);
179 strbuf_release(&path);
180 if (dir) {
181 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
182 struct worktree *linked = NULL;
184 if ((linked = get_linked_worktree(d->d_name, skip_reading_head))) {
185 ALLOC_GROW(list, counter + 1, alloc);
186 list[counter++] = linked;
189 closedir(dir);
191 ALLOC_GROW(list, counter + 1, alloc);
192 list[counter] = NULL;
194 return list;
197 struct worktree **get_worktrees(void)
199 return get_worktrees_internal(0);
202 struct worktree **get_worktrees_without_reading_head(void)
204 return get_worktrees_internal(1);
207 char *get_worktree_git_dir(const struct worktree *wt)
209 if (!wt)
210 return xstrdup(repo_get_git_dir(the_repository));
211 else if (!wt->id)
212 return xstrdup(repo_get_common_dir(the_repository));
213 else
214 return repo_common_path(the_repository, "worktrees/%s", wt->id);
217 static struct worktree *find_worktree_by_suffix(struct worktree **list,
218 const char *suffix)
220 struct worktree *found = NULL;
221 int nr_found = 0, suffixlen;
223 suffixlen = strlen(suffix);
224 if (!suffixlen)
225 return NULL;
227 for (; *list && nr_found < 2; list++) {
228 const char *path = (*list)->path;
229 int pathlen = strlen(path);
230 int start = pathlen - suffixlen;
232 /* suffix must start at directory boundary */
233 if ((!start || (start > 0 && is_dir_sep(path[start - 1]))) &&
234 !fspathcmp(suffix, path + start)) {
235 found = *list;
236 nr_found++;
239 return nr_found == 1 ? found : NULL;
242 struct worktree *find_worktree(struct worktree **list,
243 const char *prefix,
244 const char *arg)
246 struct worktree *wt;
247 char *to_free = NULL;
249 if ((wt = find_worktree_by_suffix(list, arg)))
250 return wt;
252 if (prefix)
253 arg = to_free = prefix_filename(prefix, arg);
254 wt = find_worktree_by_path(list, arg);
255 free(to_free);
256 return wt;
259 struct worktree *find_worktree_by_path(struct worktree **list, const char *p)
261 struct strbuf wt_path = STRBUF_INIT;
262 char *path = real_pathdup(p, 0);
264 if (!path)
265 return NULL;
266 for (; *list; list++) {
267 if (!strbuf_realpath(&wt_path, (*list)->path, 0))
268 continue;
270 if (!fspathcmp(path, wt_path.buf))
271 break;
273 free(path);
274 strbuf_release(&wt_path);
275 return *list;
278 int is_main_worktree(const struct worktree *wt)
280 return !wt->id;
283 const char *worktree_lock_reason(struct worktree *wt)
285 if (is_main_worktree(wt))
286 return NULL;
288 if (!wt->lock_reason_valid) {
289 struct strbuf path = STRBUF_INIT;
291 strbuf_addstr(&path, worktree_git_path(the_repository, wt, "locked"));
292 if (file_exists(path.buf)) {
293 struct strbuf lock_reason = STRBUF_INIT;
294 if (strbuf_read_file(&lock_reason, path.buf, 0) < 0)
295 die_errno(_("failed to read '%s'"), path.buf);
296 strbuf_trim(&lock_reason);
297 wt->lock_reason = strbuf_detach(&lock_reason, NULL);
298 } else
299 wt->lock_reason = NULL;
300 wt->lock_reason_valid = 1;
301 strbuf_release(&path);
304 return wt->lock_reason;
307 const char *worktree_prune_reason(struct worktree *wt, timestamp_t expire)
309 struct strbuf reason = STRBUF_INIT;
310 char *path = NULL;
312 if (is_main_worktree(wt))
313 return NULL;
314 if (wt->prune_reason_valid)
315 return wt->prune_reason;
317 if (should_prune_worktree(wt->id, &reason, &path, expire))
318 wt->prune_reason = strbuf_detach(&reason, NULL);
319 wt->prune_reason_valid = 1;
321 strbuf_release(&reason);
322 free(path);
323 return wt->prune_reason;
326 /* convenient wrapper to deal with NULL strbuf */
327 __attribute__((format (printf, 2, 3)))
328 static void strbuf_addf_gently(struct strbuf *buf, const char *fmt, ...)
330 va_list params;
332 if (!buf)
333 return;
335 va_start(params, fmt);
336 strbuf_vaddf(buf, fmt, params);
337 va_end(params);
340 int validate_worktree(const struct worktree *wt, struct strbuf *errmsg,
341 unsigned flags)
343 struct strbuf wt_path = STRBUF_INIT;
344 struct strbuf realpath = STRBUF_INIT;
345 struct strbuf buf = STRBUF_INIT;
346 char *path = NULL;
347 int err, ret = -1;
349 strbuf_addf(&wt_path, "%s/.git", wt->path);
351 if (is_main_worktree(wt)) {
352 if (is_directory(wt_path.buf)) {
353 ret = 0;
354 goto done;
357 * Main worktree using .git file to point to the
358 * repository would make it impossible to know where
359 * the actual worktree is if this function is executed
360 * from another worktree. No .git file support for now.
362 strbuf_addf_gently(errmsg,
363 _("'%s' at main working tree is not the repository directory"),
364 wt_path.buf);
365 goto done;
369 * Make sure "gitdir" file points to a real .git file and that
370 * file points back here.
372 if (!is_absolute_path(wt->path)) {
373 strbuf_addf_gently(errmsg,
374 _("'%s' file does not contain absolute path to the working tree location"),
375 repo_common_path_replace(the_repository, &buf, "worktrees/%s/gitdir", wt->id));
376 goto done;
379 if (flags & WT_VALIDATE_WORKTREE_MISSING_OK &&
380 !file_exists(wt->path)) {
381 ret = 0;
382 goto done;
385 if (!file_exists(wt_path.buf)) {
386 strbuf_addf_gently(errmsg, _("'%s' does not exist"), wt_path.buf);
387 goto done;
390 path = xstrdup_or_null(read_gitfile_gently(wt_path.buf, &err));
391 if (!path) {
392 strbuf_addf_gently(errmsg, _("'%s' is not a .git file, error code %d"),
393 wt_path.buf, err);
394 goto done;
397 strbuf_realpath(&realpath, repo_common_path_replace(the_repository, &buf, "worktrees/%s", wt->id), 1);
398 ret = fspathcmp(path, realpath.buf);
400 if (ret)
401 strbuf_addf_gently(errmsg, _("'%s' does not point back to '%s'"),
402 wt->path, repo_common_path_replace(the_repository, &buf,
403 "worktrees/%s", wt->id));
404 done:
405 free(path);
406 strbuf_release(&buf);
407 strbuf_release(&wt_path);
408 strbuf_release(&realpath);
409 return ret;
412 void update_worktree_location(struct worktree *wt, const char *path_,
413 int use_relative_paths)
415 struct strbuf path = STRBUF_INIT;
416 struct strbuf dotgit = STRBUF_INIT;
417 struct strbuf gitdir = STRBUF_INIT;
418 char *wt_gitdir;
420 if (is_main_worktree(wt))
421 BUG("can't relocate main worktree");
423 wt_gitdir = repo_common_path(the_repository, "worktrees/%s/gitdir", wt->id);
424 strbuf_realpath(&gitdir, wt_gitdir, 1);
425 strbuf_realpath(&path, path_, 1);
426 strbuf_addf(&dotgit, "%s/.git", path.buf);
427 if (fspathcmp(wt->path, path.buf)) {
428 write_worktree_linking_files(dotgit, gitdir, use_relative_paths);
430 free(wt->path);
431 wt->path = strbuf_detach(&path, NULL);
433 strbuf_release(&path);
434 strbuf_release(&dotgit);
435 strbuf_release(&gitdir);
436 free(wt_gitdir);
439 int is_worktree_being_rebased(const struct worktree *wt,
440 const char *target)
442 struct wt_status_state state;
443 int found_rebase;
445 memset(&state, 0, sizeof(state));
446 found_rebase = wt_status_check_rebase(wt, &state) &&
447 (state.rebase_in_progress ||
448 state.rebase_interactive_in_progress) &&
449 state.branch &&
450 skip_prefix(target, "refs/heads/", &target) &&
451 !strcmp(state.branch, target);
452 wt_status_state_free_buffers(&state);
453 return found_rebase;
456 int is_worktree_being_bisected(const struct worktree *wt,
457 const char *target)
459 struct wt_status_state state;
460 int found_bisect;
462 memset(&state, 0, sizeof(state));
463 found_bisect = wt_status_check_bisect(wt, &state) &&
464 state.bisecting_from &&
465 skip_prefix(target, "refs/heads/", &target) &&
466 !strcmp(state.bisecting_from, target);
467 wt_status_state_free_buffers(&state);
468 return found_bisect;
472 * note: this function should be able to detect shared symref even if
473 * HEAD is temporarily detached (e.g. in the middle of rebase or
474 * bisect). New commands that do similar things should update this
475 * function as well.
477 int is_shared_symref(const struct worktree *wt, const char *symref,
478 const char *target)
480 const char *symref_target;
481 struct ref_store *refs;
482 int flags;
484 if (wt->is_bare)
485 return 0;
487 if (wt->is_detached && !strcmp(symref, "HEAD")) {
488 if (is_worktree_being_rebased(wt, target))
489 return 1;
490 if (is_worktree_being_bisected(wt, target))
491 return 1;
494 refs = get_worktree_ref_store(wt);
495 symref_target = refs_resolve_ref_unsafe(refs, symref, 0,
496 NULL, &flags);
497 if ((flags & REF_ISSYMREF) &&
498 symref_target && !strcmp(symref_target, target))
499 return 1;
501 return 0;
504 const struct worktree *find_shared_symref(struct worktree **worktrees,
505 const char *symref,
506 const char *target)
509 for (int i = 0; worktrees[i]; i++)
510 if (is_shared_symref(worktrees[i], symref, target))
511 return worktrees[i];
513 return NULL;
516 int submodule_uses_worktrees(const char *path)
518 char *submodule_gitdir;
519 struct strbuf sb = STRBUF_INIT, err = STRBUF_INIT;
520 DIR *dir;
521 struct dirent *d;
522 int ret = 0;
523 struct repository_format format = REPOSITORY_FORMAT_INIT;
525 submodule_gitdir = repo_submodule_path(the_repository,
526 path, "%s", "");
527 if (!submodule_gitdir)
528 return 0;
530 /* The env would be set for the superproject. */
531 get_common_dir_noenv(&sb, submodule_gitdir);
532 free(submodule_gitdir);
534 strbuf_addstr(&sb, "/config");
535 read_repository_format(&format, sb.buf);
536 if (verify_repository_format(&format, &err)) {
537 strbuf_release(&err);
538 strbuf_release(&sb);
539 clear_repository_format(&format);
540 return 1;
542 clear_repository_format(&format);
543 strbuf_release(&err);
545 /* Replace config by worktrees. */
546 strbuf_setlen(&sb, sb.len - strlen("config"));
547 strbuf_addstr(&sb, "worktrees");
549 /* See if there is any file inside the worktrees directory. */
550 dir = opendir(sb.buf);
551 strbuf_release(&sb);
553 if (!dir)
554 return 0;
556 d = readdir_skip_dot_and_dotdot(dir);
557 if (d)
558 ret = 1;
559 closedir(dir);
560 return ret;
563 void strbuf_worktree_ref(const struct worktree *wt,
564 struct strbuf *sb,
565 const char *refname)
567 if (parse_worktree_ref(refname, NULL, NULL, NULL) ==
568 REF_WORKTREE_CURRENT &&
569 wt && !wt->is_current) {
570 if (is_main_worktree(wt))
571 strbuf_addstr(sb, "main-worktree/");
572 else
573 strbuf_addf(sb, "worktrees/%s/", wt->id);
575 strbuf_addstr(sb, refname);
578 int other_head_refs(each_ref_fn fn, void *cb_data)
580 struct worktree **worktrees, **p;
581 struct strbuf refname = STRBUF_INIT;
582 int ret = 0;
584 worktrees = get_worktrees();
585 for (p = worktrees; *p; p++) {
586 struct worktree *wt = *p;
587 struct object_id oid;
588 int flag;
590 if (wt->is_current)
591 continue;
593 strbuf_reset(&refname);
594 strbuf_worktree_ref(wt, &refname, "HEAD");
595 if (refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
596 refname.buf,
597 RESOLVE_REF_READING,
598 &oid, &flag))
599 ret = fn(refname.buf, NULL, &oid, flag, cb_data);
600 if (ret)
601 break;
603 free_worktrees(worktrees);
604 strbuf_release(&refname);
605 return ret;
609 * Repair worktree's /path/to/worktree/.git file if missing, corrupt, or not
610 * pointing at <repo>/worktrees/<id>.
612 static void repair_gitfile(struct worktree *wt,
613 worktree_repair_fn fn, void *cb_data,
614 int use_relative_paths)
616 struct strbuf dotgit = STRBUF_INIT;
617 struct strbuf gitdir = STRBUF_INIT;
618 struct strbuf repo = STRBUF_INIT;
619 struct strbuf backlink = STRBUF_INIT;
620 char *dotgit_contents = NULL;
621 const char *repair = NULL;
622 char *path = NULL;
623 int err;
625 /* missing worktree can't be repaired */
626 if (!file_exists(wt->path))
627 goto done;
629 if (!is_directory(wt->path)) {
630 fn(1, wt->path, _("not a directory"), cb_data);
631 goto done;
634 path = repo_common_path(the_repository, "worktrees/%s", wt->id);
635 strbuf_realpath(&repo, path, 1);
636 strbuf_addf(&dotgit, "%s/.git", wt->path);
637 strbuf_addf(&gitdir, "%s/gitdir", repo.buf);
638 dotgit_contents = xstrdup_or_null(read_gitfile_gently(dotgit.buf, &err));
640 if (dotgit_contents) {
641 if (is_absolute_path(dotgit_contents)) {
642 strbuf_addstr(&backlink, dotgit_contents);
643 } else {
644 strbuf_addf(&backlink, "%s/%s", wt->path, dotgit_contents);
645 strbuf_realpath_forgiving(&backlink, backlink.buf, 0);
649 if (err == READ_GITFILE_ERR_NOT_A_FILE)
650 fn(1, wt->path, _(".git is not a file"), cb_data);
651 else if (err)
652 repair = _(".git file broken");
653 else if (fspathcmp(backlink.buf, repo.buf))
654 repair = _(".git file incorrect");
655 else if (use_relative_paths == is_absolute_path(dotgit_contents))
656 repair = _(".git file absolute/relative path mismatch");
658 if (repair) {
659 fn(0, wt->path, repair, cb_data);
660 write_worktree_linking_files(dotgit, gitdir, use_relative_paths);
663 done:
664 free(dotgit_contents);
665 free(path);
666 strbuf_release(&repo);
667 strbuf_release(&dotgit);
668 strbuf_release(&gitdir);
669 strbuf_release(&backlink);
672 static void repair_noop(int iserr UNUSED,
673 const char *path UNUSED,
674 const char *msg UNUSED,
675 void *cb_data UNUSED)
677 /* nothing */
680 void repair_worktrees(worktree_repair_fn fn, void *cb_data, int use_relative_paths)
682 struct worktree **worktrees = get_worktrees_internal(1);
683 struct worktree **wt = worktrees + 1; /* +1 skips main worktree */
685 if (!fn)
686 fn = repair_noop;
687 for (; *wt; wt++)
688 repair_gitfile(*wt, fn, cb_data, use_relative_paths);
689 free_worktrees(worktrees);
692 void repair_worktree_after_gitdir_move(struct worktree *wt, const char *old_path)
694 struct strbuf gitdir = STRBUF_INIT;
695 struct strbuf dotgit = STRBUF_INIT;
696 int is_relative_path;
697 char *path = NULL;
699 if (is_main_worktree(wt))
700 goto done;
702 path = repo_common_path(the_repository, "worktrees/%s/gitdir", wt->id);
703 strbuf_realpath(&gitdir, path, 1);
705 if (strbuf_read_file(&dotgit, gitdir.buf, 0) < 0)
706 goto done;
708 strbuf_rtrim(&dotgit);
709 is_relative_path = ! is_absolute_path(dotgit.buf);
710 if (is_relative_path) {
711 strbuf_insertf(&dotgit, 0, "%s/worktrees/%s/", old_path, wt->id);
712 strbuf_realpath_forgiving(&dotgit, dotgit.buf, 0);
715 if (!file_exists(dotgit.buf))
716 goto done;
718 write_worktree_linking_files(dotgit, gitdir, is_relative_path);
719 done:
720 strbuf_release(&gitdir);
721 strbuf_release(&dotgit);
722 free(path);
725 void repair_worktrees_after_gitdir_move(const char *old_path)
727 struct worktree **worktrees = get_worktrees_internal(1);
728 struct worktree **wt = worktrees + 1; /* +1 skips main worktree */
730 for (; *wt; wt++)
731 repair_worktree_after_gitdir_move(*wt, old_path);
732 free_worktrees(worktrees);
735 static int is_main_worktree_path(const char *path)
737 struct strbuf target = STRBUF_INIT;
738 struct strbuf maindir = STRBUF_INIT;
739 int cmp;
741 strbuf_add_real_path(&target, path);
742 strbuf_strip_suffix(&target, "/.git");
743 strbuf_add_real_path(&maindir, repo_get_common_dir(the_repository));
744 strbuf_strip_suffix(&maindir, "/.git");
745 cmp = fspathcmp(maindir.buf, target.buf);
747 strbuf_release(&maindir);
748 strbuf_release(&target);
749 return !cmp;
753 * If both the main worktree and linked worktree have been moved, then the
754 * gitfile /path/to/worktree/.git won't point into the repository, thus we
755 * won't know which <repo>/worktrees/<id>/gitdir to repair. However, we may
756 * be able to infer the gitdir by manually reading /path/to/worktree/.git,
757 * extracting the <id>, and checking if <repo>/worktrees/<id> exists.
759 * Returns -1 on failure and strbuf.len on success.
761 static ssize_t infer_backlink(const char *gitfile, struct strbuf *inferred)
763 struct strbuf actual = STRBUF_INIT;
764 const char *id;
766 if (strbuf_read_file(&actual, gitfile, 0) < 0)
767 goto error;
768 if (!starts_with(actual.buf, "gitdir:"))
769 goto error;
770 if (!(id = find_last_dir_sep(actual.buf)))
771 goto error;
772 strbuf_trim(&actual);
773 id++; /* advance past '/' to point at <id> */
774 if (!*id)
775 goto error;
776 repo_common_path_replace(the_repository, inferred, "worktrees/%s", id);
777 if (!is_directory(inferred->buf))
778 goto error;
780 strbuf_release(&actual);
781 return inferred->len;
782 error:
783 strbuf_release(&actual);
784 strbuf_reset(inferred); /* clear invalid path */
785 return -1;
789 * Repair <repo>/worktrees/<id>/gitdir if missing, corrupt, or not pointing at
790 * the worktree's path.
792 void repair_worktree_at_path(const char *path,
793 worktree_repair_fn fn, void *cb_data,
794 int use_relative_paths)
796 struct strbuf dotgit = STRBUF_INIT;
797 struct strbuf backlink = STRBUF_INIT;
798 struct strbuf inferred_backlink = STRBUF_INIT;
799 struct strbuf gitdir = STRBUF_INIT;
800 struct strbuf olddotgit = STRBUF_INIT;
801 char *dotgit_contents = NULL;
802 const char *repair = NULL;
803 int err;
805 if (!fn)
806 fn = repair_noop;
808 if (is_main_worktree_path(path))
809 goto done;
811 strbuf_addf(&dotgit, "%s/.git", path);
812 if (!strbuf_realpath(&dotgit, dotgit.buf, 0)) {
813 fn(1, path, _("not a valid path"), cb_data);
814 goto done;
817 infer_backlink(dotgit.buf, &inferred_backlink);
818 strbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);
819 dotgit_contents = xstrdup_or_null(read_gitfile_gently(dotgit.buf, &err));
820 if (dotgit_contents) {
821 if (is_absolute_path(dotgit_contents)) {
822 strbuf_addstr(&backlink, dotgit_contents);
823 } else {
824 strbuf_addbuf(&backlink, &dotgit);
825 strbuf_strip_suffix(&backlink, ".git");
826 strbuf_addstr(&backlink, dotgit_contents);
827 strbuf_realpath_forgiving(&backlink, backlink.buf, 0);
829 } else if (err == READ_GITFILE_ERR_NOT_A_FILE) {
830 fn(1, dotgit.buf, _("unable to locate repository; .git is not a file"), cb_data);
831 goto done;
832 } else if (err == READ_GITFILE_ERR_NOT_A_REPO) {
833 if (inferred_backlink.len) {
835 * Worktree's .git file does not point at a repository
836 * but we found a .git/worktrees/<id> in this
837 * repository with the same <id> as recorded in the
838 * worktree's .git file so make the worktree point at
839 * the discovered .git/worktrees/<id>.
841 strbuf_swap(&backlink, &inferred_backlink);
842 } else {
843 fn(1, dotgit.buf, _("unable to locate repository; .git file does not reference a repository"), cb_data);
844 goto done;
846 } else {
847 fn(1, dotgit.buf, _("unable to locate repository; .git file broken"), cb_data);
848 goto done;
852 * If we got this far, either the worktree's .git file pointed at a
853 * valid repository (i.e. read_gitfile_gently() returned success) or
854 * the .git file did not point at a repository but we were able to
855 * infer a suitable new value for the .git file by locating a
856 * .git/worktrees/<id> in *this* repository corresponding to the <id>
857 * recorded in the worktree's .git file.
859 * However, if, at this point, inferred_backlink is non-NULL (i.e. we
860 * found a suitable .git/worktrees/<id> in *this* repository) *and* the
861 * worktree's .git file points at a valid repository *and* those two
862 * paths differ, then that indicates that the user probably *copied*
863 * the main and linked worktrees to a new location as a unit rather
864 * than *moving* them. Thus, the copied worktree's .git file actually
865 * points at the .git/worktrees/<id> in the *original* repository, not
866 * in the "copy" repository. In this case, point the "copy" worktree's
867 * .git file at the "copy" repository.
869 if (inferred_backlink.len && fspathcmp(backlink.buf, inferred_backlink.buf))
870 strbuf_swap(&backlink, &inferred_backlink);
872 strbuf_addf(&gitdir, "%s/gitdir", backlink.buf);
873 if (strbuf_read_file(&olddotgit, gitdir.buf, 0) < 0)
874 repair = _("gitdir unreadable");
875 else if (use_relative_paths == is_absolute_path(olddotgit.buf))
876 repair = _("gitdir absolute/relative path mismatch");
877 else {
878 strbuf_rtrim(&olddotgit);
879 if (!is_absolute_path(olddotgit.buf)) {
880 strbuf_insertf(&olddotgit, 0, "%s/", backlink.buf);
881 strbuf_realpath_forgiving(&olddotgit, olddotgit.buf, 0);
883 if (fspathcmp(olddotgit.buf, dotgit.buf))
884 repair = _("gitdir incorrect");
887 if (repair) {
888 fn(0, gitdir.buf, repair, cb_data);
889 write_worktree_linking_files(dotgit, gitdir, use_relative_paths);
891 done:
892 free(dotgit_contents);
893 strbuf_release(&olddotgit);
894 strbuf_release(&backlink);
895 strbuf_release(&inferred_backlink);
896 strbuf_release(&gitdir);
897 strbuf_release(&dotgit);
900 int should_prune_worktree(const char *id, struct strbuf *reason, char **wtpath, timestamp_t expire)
902 struct stat st;
903 struct strbuf dotgit = STRBUF_INIT;
904 struct strbuf gitdir = STRBUF_INIT;
905 struct strbuf repo = STRBUF_INIT;
906 struct strbuf file = STRBUF_INIT;
907 char *path = NULL;
908 int rc = 0;
909 int fd;
910 size_t len;
911 ssize_t read_result;
913 *wtpath = NULL;
915 path = repo_common_path(the_repository, "worktrees/%s", id);
916 strbuf_realpath(&repo, path, 1);
917 FREE_AND_NULL(path);
919 strbuf_addf(&gitdir, "%s/gitdir", repo.buf);
920 if (!is_directory(repo.buf)) {
921 strbuf_addstr(reason, _("not a valid directory"));
922 rc = 1;
923 goto done;
925 strbuf_addf(&file, "%s/locked", repo.buf);
926 if (file_exists(file.buf)) {
927 goto done;
929 if (stat(gitdir.buf, &st)) {
930 strbuf_addstr(reason, _("gitdir file does not exist"));
931 rc = 1;
932 goto done;
934 fd = open(gitdir.buf, O_RDONLY);
935 if (fd < 0) {
936 strbuf_addf(reason, _("unable to read gitdir file (%s)"),
937 strerror(errno));
938 rc = 1;
939 goto done;
941 len = xsize_t(st.st_size);
942 path = xmallocz(len);
944 read_result = read_in_full(fd, path, len);
945 close(fd);
946 if (read_result < 0) {
947 strbuf_addf(reason, _("unable to read gitdir file (%s)"),
948 strerror(errno));
949 rc = 1;
950 goto done;
951 } else if (read_result != len) {
952 strbuf_addf(reason,
953 _("short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
954 (uintmax_t)len, (uintmax_t)read_result);
955 rc = 1;
956 goto done;
958 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
959 len--;
960 if (!len) {
961 strbuf_addstr(reason, _("invalid gitdir file"));
962 rc = 1;
963 goto done;
965 path[len] = '\0';
966 if (is_absolute_path(path)) {
967 strbuf_addstr(&dotgit, path);
968 } else {
969 strbuf_addf(&dotgit, "%s/%s", repo.buf, path);
970 strbuf_realpath_forgiving(&dotgit, dotgit.buf, 0);
972 if (!file_exists(dotgit.buf)) {
973 strbuf_reset(&file);
974 strbuf_addf(&file, "%s/index", repo.buf);
975 if (stat(file.buf, &st) || st.st_mtime <= expire) {
976 strbuf_addstr(reason, _("gitdir file points to non-existent location"));
977 rc = 1;
978 goto done;
981 *wtpath = strbuf_detach(&dotgit, NULL);
982 done:
983 free(path);
984 strbuf_release(&dotgit);
985 strbuf_release(&gitdir);
986 strbuf_release(&repo);
987 strbuf_release(&file);
988 return rc;
991 static int move_config_setting(const char *key, const char *value,
992 const char *from_file, const char *to_file)
994 if (git_config_set_in_file_gently(to_file, key, NULL, value))
995 return error(_("unable to set %s in '%s'"), key, to_file);
996 if (git_config_set_in_file_gently(from_file, key, NULL, NULL))
997 return error(_("unable to unset %s in '%s'"), key, from_file);
998 return 0;
1001 int init_worktree_config(struct repository *r)
1003 int res = 0;
1004 int bare = 0;
1005 struct config_set cs = { { 0 } };
1006 const char *core_worktree;
1007 char *common_config_file;
1008 char *main_worktree_file;
1011 * If the extension is already enabled, then we can skip the
1012 * upgrade process.
1014 if (r->repository_format_worktree_config)
1015 return 0;
1016 if ((res = git_config_set_gently("extensions.worktreeConfig", "true")))
1017 return error(_("failed to set extensions.worktreeConfig setting"));
1019 common_config_file = xstrfmt("%s/config", r->commondir);
1020 main_worktree_file = xstrfmt("%s/config.worktree", r->commondir);
1022 git_configset_init(&cs);
1023 git_configset_add_file(&cs, common_config_file);
1026 * If core.bare is true in the common config file, then we need to
1027 * move it to the main worktree's config file or it will break all
1028 * worktrees. If it is false, then leave it in place because it
1029 * _could_ be negating a global core.bare=true.
1031 if (!git_configset_get_bool(&cs, "core.bare", &bare) && bare) {
1032 if ((res = move_config_setting("core.bare", "true",
1033 common_config_file,
1034 main_worktree_file)))
1035 goto cleanup;
1038 * If core.worktree is set, then the main worktree is located
1039 * somewhere different than the parent of the common Git dir.
1040 * Relocate that value to avoid breaking all worktrees with this
1041 * upgrade to worktree config.
1043 if (!git_configset_get_value(&cs, "core.worktree", &core_worktree, NULL)) {
1044 if ((res = move_config_setting("core.worktree", core_worktree,
1045 common_config_file,
1046 main_worktree_file)))
1047 goto cleanup;
1051 * Ensure that we use worktree config for the remaining lifetime
1052 * of the current process.
1054 r->repository_format_worktree_config = 1;
1056 cleanup:
1057 git_configset_clear(&cs);
1058 free(common_config_file);
1059 free(main_worktree_file);
1060 return res;
1063 void write_worktree_linking_files(struct strbuf dotgit, struct strbuf gitdir,
1064 int use_relative_paths)
1066 struct strbuf path = STRBUF_INIT;
1067 struct strbuf repo = STRBUF_INIT;
1068 struct strbuf tmp = STRBUF_INIT;
1070 strbuf_addbuf(&path, &dotgit);
1071 strbuf_strip_suffix(&path, "/.git");
1072 strbuf_realpath(&path, path.buf, 1);
1073 strbuf_addbuf(&repo, &gitdir);
1074 strbuf_strip_suffix(&repo, "/gitdir");
1075 strbuf_realpath(&repo, repo.buf, 1);
1077 if (use_relative_paths && !the_repository->repository_format_relative_worktrees) {
1078 if (upgrade_repository_format(1) < 0)
1079 die(_("unable to upgrade repository format to support relative worktrees"));
1080 if (git_config_set_gently("extensions.relativeWorktrees", "true"))
1081 die(_("unable to set extensions.relativeWorktrees setting"));
1082 the_repository->repository_format_relative_worktrees = 1;
1085 if (use_relative_paths) {
1086 write_file(gitdir.buf, "%s/.git", relative_path(path.buf, repo.buf, &tmp));
1087 write_file(dotgit.buf, "gitdir: %s", relative_path(repo.buf, path.buf, &tmp));
1088 } else {
1089 write_file(gitdir.buf, "%s/.git", path.buf);
1090 write_file(dotgit.buf, "gitdir: %s", repo.buf);
1093 strbuf_release(&path);
1094 strbuf_release(&repo);
1095 strbuf_release(&tmp);