Sync with 'maint'
[git/gitster.git] / worktree.c
blob77ff484d3ec48c547ee4e3d958dfa28a52c1eaa7
1 #define USE_THE_REPOSITORY_VARIABLE
3 #include "git-compat-util.h"
4 #include "abspath.h"
5 #include "environment.h"
6 #include "gettext.h"
7 #include "path.h"
8 #include "repository.h"
9 #include "refs.h"
10 #include "setup.h"
11 #include "strbuf.h"
12 #include "worktree.h"
13 #include "dir.h"
14 #include "wt-status.h"
15 #include "config.h"
17 void free_worktree(struct worktree *worktree)
19 if (!worktree)
20 return;
21 free(worktree->path);
22 free(worktree->id);
23 free(worktree->head_ref);
24 free(worktree->lock_reason);
25 free(worktree->prune_reason);
26 free(worktree);
29 void free_worktrees(struct worktree **worktrees)
31 int i = 0;
32 for (i = 0; worktrees[i]; i++)
33 free_worktree(worktrees[i]);
34 free (worktrees);
37 /**
38 * Update head_oid, head_ref and is_detached of the given worktree
40 static void add_head_info(struct worktree *wt)
42 int flags;
43 const char *target;
45 target = refs_resolve_ref_unsafe(get_worktree_ref_store(wt),
46 "HEAD",
48 &wt->head_oid, &flags);
49 if (!target)
50 return;
52 if (flags & REF_ISSYMREF)
53 wt->head_ref = xstrdup(target);
54 else
55 wt->is_detached = 1;
58 static int is_current_worktree(struct worktree *wt)
60 char *git_dir = absolute_pathdup(repo_get_git_dir(the_repository));
61 const char *wt_git_dir = get_worktree_git_dir(wt);
62 int is_current = !fspathcmp(git_dir, absolute_path(wt_git_dir));
63 free(git_dir);
64 return is_current;
67 /**
68 * get the main worktree
70 static struct worktree *get_main_worktree(int skip_reading_head)
72 struct worktree *worktree = NULL;
73 struct strbuf worktree_path = STRBUF_INIT;
75 strbuf_add_real_path(&worktree_path, repo_get_common_dir(the_repository));
76 strbuf_strip_suffix(&worktree_path, "/.git");
78 CALLOC_ARRAY(worktree, 1);
79 worktree->repo = the_repository;
80 worktree->path = strbuf_detach(&worktree_path, NULL);
82 * NEEDSWORK: If this function is called from a secondary worktree and
83 * config.worktree is present, is_bare_repository_cfg will reflect the
84 * contents of config.worktree, not the contents of the main worktree.
85 * This means that worktree->is_bare may be set to 0 even if the main
86 * worktree is configured to be bare.
88 worktree->is_bare = (is_bare_repository_cfg == 1) ||
89 is_bare_repository();
90 worktree->is_current = is_current_worktree(worktree);
91 if (!skip_reading_head)
92 add_head_info(worktree);
93 return worktree;
96 struct worktree *get_linked_worktree(const char *id,
97 int skip_reading_head)
99 struct worktree *worktree = NULL;
100 struct strbuf path = STRBUF_INIT;
101 struct strbuf worktree_path = STRBUF_INIT;
103 if (!id)
104 die("Missing linked worktree name");
106 strbuf_git_common_path(&path, the_repository, "worktrees/%s/gitdir", id);
107 if (strbuf_read_file(&worktree_path, path.buf, 0) <= 0)
108 /* invalid gitdir file */
109 goto done;
110 strbuf_rtrim(&worktree_path);
111 strbuf_strip_suffix(&worktree_path, "/.git");
113 if (!is_absolute_path(worktree_path.buf)) {
114 strbuf_strip_suffix(&path, "gitdir");
115 strbuf_addbuf(&path, &worktree_path);
116 strbuf_realpath_forgiving(&worktree_path, path.buf, 0);
119 CALLOC_ARRAY(worktree, 1);
120 worktree->repo = the_repository;
121 worktree->path = strbuf_detach(&worktree_path, NULL);
122 worktree->id = xstrdup(id);
123 worktree->is_current = is_current_worktree(worktree);
124 if (!skip_reading_head)
125 add_head_info(worktree);
127 done:
128 strbuf_release(&path);
129 strbuf_release(&worktree_path);
130 return worktree;
134 * NEEDSWORK: This function exists so that we can look up metadata of a
135 * worktree without trying to access any of its internals like the refdb. It
136 * would be preferable to instead have a corruption-tolerant function for
137 * retrieving worktree metadata that could be used when the worktree is known
138 * to not be in a healthy state, e.g. when creating or repairing it.
140 static struct worktree **get_worktrees_internal(int skip_reading_head)
142 struct worktree **list = NULL;
143 struct strbuf path = STRBUF_INIT;
144 DIR *dir;
145 struct dirent *d;
146 int counter = 0, alloc = 2;
148 ALLOC_ARRAY(list, alloc);
150 list[counter++] = get_main_worktree(skip_reading_head);
152 strbuf_addf(&path, "%s/worktrees", repo_get_common_dir(the_repository));
153 dir = opendir(path.buf);
154 strbuf_release(&path);
155 if (dir) {
156 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
157 struct worktree *linked = NULL;
159 if ((linked = get_linked_worktree(d->d_name, skip_reading_head))) {
160 ALLOC_GROW(list, counter + 1, alloc);
161 list[counter++] = linked;
164 closedir(dir);
166 ALLOC_GROW(list, counter + 1, alloc);
167 list[counter] = NULL;
169 return list;
172 struct worktree **get_worktrees(void)
174 return get_worktrees_internal(0);
177 const char *get_worktree_git_dir(const struct worktree *wt)
179 if (!wt)
180 return repo_get_git_dir(the_repository);
181 else if (!wt->id)
182 return repo_get_common_dir(the_repository);
183 else
184 return git_common_path("worktrees/%s", wt->id);
187 static struct worktree *find_worktree_by_suffix(struct worktree **list,
188 const char *suffix)
190 struct worktree *found = NULL;
191 int nr_found = 0, suffixlen;
193 suffixlen = strlen(suffix);
194 if (!suffixlen)
195 return NULL;
197 for (; *list && nr_found < 2; list++) {
198 const char *path = (*list)->path;
199 int pathlen = strlen(path);
200 int start = pathlen - suffixlen;
202 /* suffix must start at directory boundary */
203 if ((!start || (start > 0 && is_dir_sep(path[start - 1]))) &&
204 !fspathcmp(suffix, path + start)) {
205 found = *list;
206 nr_found++;
209 return nr_found == 1 ? found : NULL;
212 struct worktree *find_worktree(struct worktree **list,
213 const char *prefix,
214 const char *arg)
216 struct worktree *wt;
217 char *to_free = NULL;
219 if ((wt = find_worktree_by_suffix(list, arg)))
220 return wt;
222 if (prefix)
223 arg = to_free = prefix_filename(prefix, arg);
224 wt = find_worktree_by_path(list, arg);
225 free(to_free);
226 return wt;
229 struct worktree *find_worktree_by_path(struct worktree **list, const char *p)
231 struct strbuf wt_path = STRBUF_INIT;
232 char *path = real_pathdup(p, 0);
234 if (!path)
235 return NULL;
236 for (; *list; list++) {
237 if (!strbuf_realpath(&wt_path, (*list)->path, 0))
238 continue;
240 if (!fspathcmp(path, wt_path.buf))
241 break;
243 free(path);
244 strbuf_release(&wt_path);
245 return *list;
248 int is_main_worktree(const struct worktree *wt)
250 return !wt->id;
253 const char *worktree_lock_reason(struct worktree *wt)
255 if (is_main_worktree(wt))
256 return NULL;
258 if (!wt->lock_reason_valid) {
259 struct strbuf path = STRBUF_INIT;
261 strbuf_addstr(&path, worktree_git_path(the_repository, wt, "locked"));
262 if (file_exists(path.buf)) {
263 struct strbuf lock_reason = STRBUF_INIT;
264 if (strbuf_read_file(&lock_reason, path.buf, 0) < 0)
265 die_errno(_("failed to read '%s'"), path.buf);
266 strbuf_trim(&lock_reason);
267 wt->lock_reason = strbuf_detach(&lock_reason, NULL);
268 } else
269 wt->lock_reason = NULL;
270 wt->lock_reason_valid = 1;
271 strbuf_release(&path);
274 return wt->lock_reason;
277 const char *worktree_prune_reason(struct worktree *wt, timestamp_t expire)
279 struct strbuf reason = STRBUF_INIT;
280 char *path = NULL;
282 if (is_main_worktree(wt))
283 return NULL;
284 if (wt->prune_reason_valid)
285 return wt->prune_reason;
287 if (should_prune_worktree(wt->id, &reason, &path, expire))
288 wt->prune_reason = strbuf_detach(&reason, NULL);
289 wt->prune_reason_valid = 1;
291 strbuf_release(&reason);
292 free(path);
293 return wt->prune_reason;
296 /* convenient wrapper to deal with NULL strbuf */
297 __attribute__((format (printf, 2, 3)))
298 static void strbuf_addf_gently(struct strbuf *buf, const char *fmt, ...)
300 va_list params;
302 if (!buf)
303 return;
305 va_start(params, fmt);
306 strbuf_vaddf(buf, fmt, params);
307 va_end(params);
310 int validate_worktree(const struct worktree *wt, struct strbuf *errmsg,
311 unsigned flags)
313 struct strbuf wt_path = STRBUF_INIT;
314 struct strbuf realpath = STRBUF_INIT;
315 char *path = NULL;
316 int err, ret = -1;
318 strbuf_addf(&wt_path, "%s/.git", wt->path);
320 if (is_main_worktree(wt)) {
321 if (is_directory(wt_path.buf)) {
322 ret = 0;
323 goto done;
326 * Main worktree using .git file to point to the
327 * repository would make it impossible to know where
328 * the actual worktree is if this function is executed
329 * from another worktree. No .git file support for now.
331 strbuf_addf_gently(errmsg,
332 _("'%s' at main working tree is not the repository directory"),
333 wt_path.buf);
334 goto done;
338 * Make sure "gitdir" file points to a real .git file and that
339 * file points back here.
341 if (!is_absolute_path(wt->path)) {
342 strbuf_addf_gently(errmsg,
343 _("'%s' file does not contain absolute path to the working tree location"),
344 git_common_path("worktrees/%s/gitdir", wt->id));
345 goto done;
348 if (flags & WT_VALIDATE_WORKTREE_MISSING_OK &&
349 !file_exists(wt->path)) {
350 ret = 0;
351 goto done;
354 if (!file_exists(wt_path.buf)) {
355 strbuf_addf_gently(errmsg, _("'%s' does not exist"), wt_path.buf);
356 goto done;
359 path = xstrdup_or_null(read_gitfile_gently(wt_path.buf, &err));
360 if (!path) {
361 strbuf_addf_gently(errmsg, _("'%s' is not a .git file, error code %d"),
362 wt_path.buf, err);
363 goto done;
366 strbuf_realpath(&realpath, git_common_path("worktrees/%s", wt->id), 1);
367 ret = fspathcmp(path, realpath.buf);
369 if (ret)
370 strbuf_addf_gently(errmsg, _("'%s' does not point back to '%s'"),
371 wt->path, git_common_path("worktrees/%s", wt->id));
372 done:
373 free(path);
374 strbuf_release(&wt_path);
375 strbuf_release(&realpath);
376 return ret;
379 void update_worktree_location(struct worktree *wt, const char *path_)
381 struct strbuf path = STRBUF_INIT;
382 struct strbuf repo = STRBUF_INIT;
383 struct strbuf file = STRBUF_INIT;
384 struct strbuf tmp = STRBUF_INIT;
386 if (is_main_worktree(wt))
387 BUG("can't relocate main worktree");
389 strbuf_realpath(&repo, git_common_path("worktrees/%s", wt->id), 1);
390 strbuf_realpath(&path, path_, 1);
391 if (fspathcmp(wt->path, path.buf)) {
392 strbuf_addf(&file, "%s/gitdir", repo.buf);
393 write_file(file.buf, "%s/.git", relative_path(path.buf, repo.buf, &tmp));
394 strbuf_reset(&file);
395 strbuf_addf(&file, "%s/.git", path.buf);
396 write_file(file.buf, "gitdir: %s", relative_path(repo.buf, path.buf, &tmp));
398 free(wt->path);
399 wt->path = strbuf_detach(&path, NULL);
401 strbuf_release(&path);
402 strbuf_release(&repo);
403 strbuf_release(&file);
404 strbuf_release(&tmp);
407 int is_worktree_being_rebased(const struct worktree *wt,
408 const char *target)
410 struct wt_status_state state;
411 int found_rebase;
413 memset(&state, 0, sizeof(state));
414 found_rebase = wt_status_check_rebase(wt, &state) &&
415 (state.rebase_in_progress ||
416 state.rebase_interactive_in_progress) &&
417 state.branch &&
418 skip_prefix(target, "refs/heads/", &target) &&
419 !strcmp(state.branch, target);
420 wt_status_state_free_buffers(&state);
421 return found_rebase;
424 int is_worktree_being_bisected(const struct worktree *wt,
425 const char *target)
427 struct wt_status_state state;
428 int found_bisect;
430 memset(&state, 0, sizeof(state));
431 found_bisect = wt_status_check_bisect(wt, &state) &&
432 state.bisecting_from &&
433 skip_prefix(target, "refs/heads/", &target) &&
434 !strcmp(state.bisecting_from, target);
435 wt_status_state_free_buffers(&state);
436 return found_bisect;
440 * note: this function should be able to detect shared symref even if
441 * HEAD is temporarily detached (e.g. in the middle of rebase or
442 * bisect). New commands that do similar things should update this
443 * function as well.
445 int is_shared_symref(const struct worktree *wt, const char *symref,
446 const char *target)
448 const char *symref_target;
449 struct ref_store *refs;
450 int flags;
452 if (wt->is_bare)
453 return 0;
455 if (wt->is_detached && !strcmp(symref, "HEAD")) {
456 if (is_worktree_being_rebased(wt, target))
457 return 1;
458 if (is_worktree_being_bisected(wt, target))
459 return 1;
462 refs = get_worktree_ref_store(wt);
463 symref_target = refs_resolve_ref_unsafe(refs, symref, 0,
464 NULL, &flags);
465 if ((flags & REF_ISSYMREF) &&
466 symref_target && !strcmp(symref_target, target))
467 return 1;
469 return 0;
472 const struct worktree *find_shared_symref(struct worktree **worktrees,
473 const char *symref,
474 const char *target)
477 for (int i = 0; worktrees[i]; i++)
478 if (is_shared_symref(worktrees[i], symref, target))
479 return worktrees[i];
481 return NULL;
484 int submodule_uses_worktrees(const char *path)
486 char *submodule_gitdir;
487 struct strbuf sb = STRBUF_INIT, err = STRBUF_INIT;
488 DIR *dir;
489 struct dirent *d;
490 int ret = 0;
491 struct repository_format format = REPOSITORY_FORMAT_INIT;
493 submodule_gitdir = git_pathdup_submodule(path, "%s", "");
494 if (!submodule_gitdir)
495 return 0;
497 /* The env would be set for the superproject. */
498 get_common_dir_noenv(&sb, submodule_gitdir);
499 free(submodule_gitdir);
501 strbuf_addstr(&sb, "/config");
502 read_repository_format(&format, sb.buf);
503 if (verify_repository_format(&format, &err)) {
504 strbuf_release(&err);
505 strbuf_release(&sb);
506 clear_repository_format(&format);
507 return 1;
509 clear_repository_format(&format);
510 strbuf_release(&err);
512 /* Replace config by worktrees. */
513 strbuf_setlen(&sb, sb.len - strlen("config"));
514 strbuf_addstr(&sb, "worktrees");
516 /* See if there is any file inside the worktrees directory. */
517 dir = opendir(sb.buf);
518 strbuf_release(&sb);
520 if (!dir)
521 return 0;
523 d = readdir_skip_dot_and_dotdot(dir);
524 if (d)
525 ret = 1;
526 closedir(dir);
527 return ret;
530 void strbuf_worktree_ref(const struct worktree *wt,
531 struct strbuf *sb,
532 const char *refname)
534 if (parse_worktree_ref(refname, NULL, NULL, NULL) ==
535 REF_WORKTREE_CURRENT &&
536 wt && !wt->is_current) {
537 if (is_main_worktree(wt))
538 strbuf_addstr(sb, "main-worktree/");
539 else
540 strbuf_addf(sb, "worktrees/%s/", wt->id);
542 strbuf_addstr(sb, refname);
545 int other_head_refs(each_ref_fn fn, void *cb_data)
547 struct worktree **worktrees, **p;
548 struct strbuf refname = STRBUF_INIT;
549 int ret = 0;
551 worktrees = get_worktrees();
552 for (p = worktrees; *p; p++) {
553 struct worktree *wt = *p;
554 struct object_id oid;
555 int flag;
557 if (wt->is_current)
558 continue;
560 strbuf_reset(&refname);
561 strbuf_worktree_ref(wt, &refname, "HEAD");
562 if (refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
563 refname.buf,
564 RESOLVE_REF_READING,
565 &oid, &flag))
566 ret = fn(refname.buf, NULL, &oid, flag, cb_data);
567 if (ret)
568 break;
570 free_worktrees(worktrees);
571 strbuf_release(&refname);
572 return ret;
576 * Repair worktree's /path/to/worktree/.git file if missing, corrupt, or not
577 * pointing at <repo>/worktrees/<id>.
579 static void repair_gitfile(struct worktree *wt,
580 worktree_repair_fn fn, void *cb_data)
582 struct strbuf dotgit = STRBUF_INIT;
583 struct strbuf repo = STRBUF_INIT;
584 struct strbuf backlink = STRBUF_INIT;
585 struct strbuf tmp = STRBUF_INIT;
586 char *dotgit_contents = NULL;
587 const char *repair = NULL;
588 int err;
590 /* missing worktree can't be repaired */
591 if (!file_exists(wt->path))
592 goto done;
594 if (!is_directory(wt->path)) {
595 fn(1, wt->path, _("not a directory"), cb_data);
596 goto done;
599 strbuf_realpath(&repo, git_common_path("worktrees/%s", wt->id), 1);
600 strbuf_addf(&dotgit, "%s/.git", wt->path);
601 dotgit_contents = xstrdup_or_null(read_gitfile_gently(dotgit.buf, &err));
603 if (dotgit_contents) {
604 if (is_absolute_path(dotgit_contents)) {
605 strbuf_addstr(&backlink, dotgit_contents);
606 } else {
607 strbuf_addf(&backlink, "%s/%s", wt->path, dotgit_contents);
608 strbuf_realpath_forgiving(&backlink, backlink.buf, 0);
612 if (err == READ_GITFILE_ERR_NOT_A_FILE)
613 fn(1, wt->path, _(".git is not a file"), cb_data);
614 else if (err)
615 repair = _(".git file broken");
616 else if (fspathcmp(backlink.buf, repo.buf))
617 repair = _(".git file incorrect");
619 if (repair) {
620 fn(0, wt->path, repair, cb_data);
621 write_file(dotgit.buf, "gitdir: %s", relative_path(repo.buf, wt->path, &tmp));
624 done:
625 free(dotgit_contents);
626 strbuf_release(&repo);
627 strbuf_release(&dotgit);
628 strbuf_release(&backlink);
629 strbuf_release(&tmp);
632 static void repair_noop(int iserr UNUSED,
633 const char *path UNUSED,
634 const char *msg UNUSED,
635 void *cb_data UNUSED)
637 /* nothing */
640 void repair_worktrees(worktree_repair_fn fn, void *cb_data)
642 struct worktree **worktrees = get_worktrees_internal(1);
643 struct worktree **wt = worktrees + 1; /* +1 skips main worktree */
645 if (!fn)
646 fn = repair_noop;
647 for (; *wt; wt++)
648 repair_gitfile(*wt, fn, cb_data);
649 free_worktrees(worktrees);
652 void repair_worktree_after_gitdir_move(struct worktree *wt, const char *old_path)
654 struct strbuf path = STRBUF_INIT;
655 struct strbuf repo = STRBUF_INIT;
656 struct strbuf gitdir = STRBUF_INIT;
657 struct strbuf dotgit = STRBUF_INIT;
658 struct strbuf olddotgit = STRBUF_INIT;
659 struct strbuf tmp = STRBUF_INIT;
661 if (is_main_worktree(wt))
662 goto done;
664 strbuf_realpath(&repo, git_common_path("worktrees/%s", wt->id), 1);
665 strbuf_addf(&gitdir, "%s/gitdir", repo.buf);
667 if (strbuf_read_file(&olddotgit, gitdir.buf, 0) < 0)
668 goto done;
670 strbuf_rtrim(&olddotgit);
671 if (is_absolute_path(olddotgit.buf)) {
672 strbuf_addbuf(&dotgit, &olddotgit);
673 } else {
674 strbuf_addf(&dotgit, "%s/worktrees/%s/%s", old_path, wt->id, olddotgit.buf);
675 strbuf_realpath_forgiving(&dotgit, dotgit.buf, 0);
678 if (!file_exists(dotgit.buf))
679 goto done;
681 strbuf_addbuf(&path, &dotgit);
682 strbuf_strip_suffix(&path, "/.git");
684 write_file(dotgit.buf, "gitdir: %s", relative_path(repo.buf, path.buf, &tmp));
685 write_file(gitdir.buf, "%s", relative_path(dotgit.buf, repo.buf, &tmp));
686 done:
687 strbuf_release(&path);
688 strbuf_release(&repo);
689 strbuf_release(&gitdir);
690 strbuf_release(&dotgit);
691 strbuf_release(&olddotgit);
692 strbuf_release(&tmp);
695 void repair_worktrees_after_gitdir_move(const char *old_path)
697 struct worktree **worktrees = get_worktrees_internal(1);
698 struct worktree **wt = worktrees + 1; /* +1 skips main worktree */
700 for (; *wt; wt++)
701 repair_worktree_after_gitdir_move(*wt, old_path);
702 free_worktrees(worktrees);
705 static int is_main_worktree_path(const char *path)
707 struct strbuf target = STRBUF_INIT;
708 struct strbuf maindir = STRBUF_INIT;
709 int cmp;
711 strbuf_add_real_path(&target, path);
712 strbuf_strip_suffix(&target, "/.git");
713 strbuf_add_real_path(&maindir, repo_get_common_dir(the_repository));
714 strbuf_strip_suffix(&maindir, "/.git");
715 cmp = fspathcmp(maindir.buf, target.buf);
717 strbuf_release(&maindir);
718 strbuf_release(&target);
719 return !cmp;
723 * If both the main worktree and linked worktree have been moved, then the
724 * gitfile /path/to/worktree/.git won't point into the repository, thus we
725 * won't know which <repo>/worktrees/<id>/gitdir to repair. However, we may
726 * be able to infer the gitdir by manually reading /path/to/worktree/.git,
727 * extracting the <id>, and checking if <repo>/worktrees/<id> exists.
729 static int infer_backlink(const char *gitfile, struct strbuf *inferred)
731 struct strbuf actual = STRBUF_INIT;
732 const char *id;
734 if (strbuf_read_file(&actual, gitfile, 0) < 0)
735 goto error;
736 if (!starts_with(actual.buf, "gitdir:"))
737 goto error;
738 if (!(id = find_last_dir_sep(actual.buf)))
739 goto error;
740 strbuf_trim(&actual);
741 id++; /* advance past '/' to point at <id> */
742 if (!*id)
743 goto error;
744 strbuf_reset(inferred);
745 strbuf_git_common_path(inferred, the_repository, "worktrees/%s", id);
746 if (!is_directory(inferred->buf))
747 goto error;
749 strbuf_release(&actual);
750 return 1;
752 error:
753 strbuf_release(&actual);
754 strbuf_reset(inferred); /* clear invalid path */
755 return 0;
759 * Repair <repo>/worktrees/<id>/gitdir if missing, corrupt, or not pointing at
760 * the worktree's path.
762 void repair_worktree_at_path(const char *path,
763 worktree_repair_fn fn, void *cb_data)
765 struct strbuf dotgit = STRBUF_INIT;
766 struct strbuf realdotgit = STRBUF_INIT;
767 struct strbuf backlink = STRBUF_INIT;
768 struct strbuf inferred_backlink = STRBUF_INIT;
769 struct strbuf gitdir = STRBUF_INIT;
770 struct strbuf olddotgit = STRBUF_INIT;
771 struct strbuf realolddotgit = STRBUF_INIT;
772 struct strbuf tmp = STRBUF_INIT;
773 char *dotgit_contents = NULL;
774 const char *repair = NULL;
775 int err;
777 if (!fn)
778 fn = repair_noop;
780 if (is_main_worktree_path(path))
781 goto done;
783 strbuf_addf(&dotgit, "%s/.git", path);
784 if (!strbuf_realpath(&realdotgit, dotgit.buf, 0)) {
785 fn(1, path, _("not a valid path"), cb_data);
786 goto done;
789 infer_backlink(realdotgit.buf, &inferred_backlink);
790 strbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);
791 dotgit_contents = xstrdup_or_null(read_gitfile_gently(realdotgit.buf, &err));
792 if (dotgit_contents) {
793 if (is_absolute_path(dotgit_contents)) {
794 strbuf_addstr(&backlink, dotgit_contents);
795 } else {
796 strbuf_addbuf(&backlink, &realdotgit);
797 strbuf_strip_suffix(&backlink, ".git");
798 strbuf_addstr(&backlink, dotgit_contents);
799 strbuf_realpath_forgiving(&backlink, backlink.buf, 0);
801 } else if (err == READ_GITFILE_ERR_NOT_A_FILE) {
802 fn(1, realdotgit.buf, _("unable to locate repository; .git is not a file"), cb_data);
803 goto done;
804 } else if (err == READ_GITFILE_ERR_NOT_A_REPO) {
805 if (inferred_backlink.len) {
807 * Worktree's .git file does not point at a repository
808 * but we found a .git/worktrees/<id> in this
809 * repository with the same <id> as recorded in the
810 * worktree's .git file so make the worktree point at
811 * the discovered .git/worktrees/<id>.
813 strbuf_swap(&backlink, &inferred_backlink);
814 } else {
815 fn(1, realdotgit.buf, _("unable to locate repository; .git file does not reference a repository"), cb_data);
816 goto done;
818 } else {
819 fn(1, realdotgit.buf, _("unable to locate repository; .git file broken"), cb_data);
820 goto done;
824 * If we got this far, either the worktree's .git file pointed at a
825 * valid repository (i.e. read_gitfile_gently() returned success) or
826 * the .git file did not point at a repository but we were able to
827 * infer a suitable new value for the .git file by locating a
828 * .git/worktrees/<id> in *this* repository corresponding to the <id>
829 * recorded in the worktree's .git file.
831 * However, if, at this point, inferred_backlink is non-NULL (i.e. we
832 * found a suitable .git/worktrees/<id> in *this* repository) *and* the
833 * worktree's .git file points at a valid repository *and* those two
834 * paths differ, then that indicates that the user probably *copied*
835 * the main and linked worktrees to a new location as a unit rather
836 * than *moving* them. Thus, the copied worktree's .git file actually
837 * points at the .git/worktrees/<id> in the *original* repository, not
838 * in the "copy" repository. In this case, point the "copy" worktree's
839 * .git file at the "copy" repository.
841 if (inferred_backlink.len && fspathcmp(backlink.buf, inferred_backlink.buf)) {
842 strbuf_swap(&backlink, &inferred_backlink);
845 strbuf_addf(&gitdir, "%s/gitdir", backlink.buf);
846 if (strbuf_read_file(&olddotgit, gitdir.buf, 0) < 0)
847 repair = _("gitdir unreadable");
848 else {
849 strbuf_rtrim(&olddotgit);
850 if (is_absolute_path(olddotgit.buf)) {
851 strbuf_addbuf(&realolddotgit, &olddotgit);
852 } else {
853 strbuf_addf(&realolddotgit, "%s/%s", backlink.buf, olddotgit.buf);
854 strbuf_realpath_forgiving(&realolddotgit, realolddotgit.buf, 0);
856 if (fspathcmp(realolddotgit.buf, realdotgit.buf))
857 repair = _("gitdir incorrect");
860 if (repair) {
861 fn(0, gitdir.buf, repair, cb_data);
862 write_file(gitdir.buf, "%s", relative_path(realdotgit.buf, backlink.buf, &tmp));
864 done:
865 free(dotgit_contents);
866 strbuf_release(&olddotgit);
867 strbuf_release(&realolddotgit);
868 strbuf_release(&backlink);
869 strbuf_release(&inferred_backlink);
870 strbuf_release(&gitdir);
871 strbuf_release(&realdotgit);
872 strbuf_release(&dotgit);
873 strbuf_release(&tmp);
876 int should_prune_worktree(const char *id, struct strbuf *reason, char **wtpath, timestamp_t expire)
878 struct stat st;
879 struct strbuf dotgit = STRBUF_INIT;
880 struct strbuf gitdir = STRBUF_INIT;
881 struct strbuf repo = STRBUF_INIT;
882 struct strbuf file = STRBUF_INIT;
883 char *path = NULL;
884 int rc = 0;
885 int fd;
886 size_t len;
887 ssize_t read_result;
889 *wtpath = NULL;
890 strbuf_realpath(&repo, git_common_path("worktrees/%s", id), 1);
891 strbuf_addf(&gitdir, "%s/gitdir", repo.buf);
892 if (!is_directory(repo.buf)) {
893 strbuf_addstr(reason, _("not a valid directory"));
894 rc = 1;
895 goto done;
897 strbuf_addf(&file, "%s/locked", repo.buf);
898 if (file_exists(file.buf)) {
899 goto done;
901 if (stat(gitdir.buf, &st)) {
902 strbuf_addstr(reason, _("gitdir file does not exist"));
903 rc = 1;
904 goto done;
906 fd = open(gitdir.buf, O_RDONLY);
907 if (fd < 0) {
908 strbuf_addf(reason, _("unable to read gitdir file (%s)"),
909 strerror(errno));
910 rc = 1;
911 goto done;
913 len = xsize_t(st.st_size);
914 path = xmallocz(len);
916 read_result = read_in_full(fd, path, len);
917 close(fd);
918 if (read_result < 0) {
919 strbuf_addf(reason, _("unable to read gitdir file (%s)"),
920 strerror(errno));
921 rc = 1;
922 goto done;
923 } else if (read_result != len) {
924 strbuf_addf(reason,
925 _("short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
926 (uintmax_t)len, (uintmax_t)read_result);
927 rc = 1;
928 goto done;
930 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
931 len--;
932 if (!len) {
933 strbuf_addstr(reason, _("invalid gitdir file"));
934 rc = 1;
935 goto done;
937 path[len] = '\0';
938 if (is_absolute_path(path)) {
939 strbuf_addstr(&dotgit, path);
940 } else {
941 strbuf_addf(&dotgit, "%s/%s", repo.buf, path);
942 strbuf_realpath_forgiving(&dotgit, dotgit.buf, 0);
944 if (!file_exists(dotgit.buf)) {
945 strbuf_reset(&file);
946 strbuf_addf(&file, "%s/index", repo.buf);
947 if (stat(file.buf, &st) || st.st_mtime <= expire) {
948 strbuf_addstr(reason, _("gitdir file points to non-existent location"));
949 rc = 1;
950 goto done;
953 *wtpath = strbuf_detach(&dotgit, NULL);
954 done:
955 free(path);
956 strbuf_release(&dotgit);
957 strbuf_release(&gitdir);
958 strbuf_release(&repo);
959 strbuf_release(&file);
960 return rc;
963 static int move_config_setting(const char *key, const char *value,
964 const char *from_file, const char *to_file)
966 if (git_config_set_in_file_gently(to_file, key, NULL, value))
967 return error(_("unable to set %s in '%s'"), key, to_file);
968 if (git_config_set_in_file_gently(from_file, key, NULL, NULL))
969 return error(_("unable to unset %s in '%s'"), key, from_file);
970 return 0;
973 int init_worktree_config(struct repository *r)
975 int res = 0;
976 int bare = 0;
977 struct config_set cs = { { 0 } };
978 const char *core_worktree;
979 char *common_config_file;
980 char *main_worktree_file;
983 * If the extension is already enabled, then we can skip the
984 * upgrade process.
986 if (r->repository_format_worktree_config)
987 return 0;
988 if ((res = git_config_set_gently("extensions.worktreeConfig", "true")))
989 return error(_("failed to set extensions.worktreeConfig setting"));
991 common_config_file = xstrfmt("%s/config", r->commondir);
992 main_worktree_file = xstrfmt("%s/config.worktree", r->commondir);
994 git_configset_init(&cs);
995 git_configset_add_file(&cs, common_config_file);
998 * If core.bare is true in the common config file, then we need to
999 * move it to the main worktree's config file or it will break all
1000 * worktrees. If it is false, then leave it in place because it
1001 * _could_ be negating a global core.bare=true.
1003 if (!git_configset_get_bool(&cs, "core.bare", &bare) && bare) {
1004 if ((res = move_config_setting("core.bare", "true",
1005 common_config_file,
1006 main_worktree_file)))
1007 goto cleanup;
1010 * If core.worktree is set, then the main worktree is located
1011 * somewhere different than the parent of the common Git dir.
1012 * Relocate that value to avoid breaking all worktrees with this
1013 * upgrade to worktree config.
1015 if (!git_configset_get_value(&cs, "core.worktree", &core_worktree, NULL)) {
1016 if ((res = move_config_setting("core.worktree", core_worktree,
1017 common_config_file,
1018 main_worktree_file)))
1019 goto cleanup;
1023 * Ensure that we use worktree config for the remaining lifetime
1024 * of the current process.
1026 r->repository_format_worktree_config = 1;
1028 cleanup:
1029 git_configset_clear(&cs);
1030 free(common_config_file);
1031 free(main_worktree_file);
1032 return res;