Raw
1 #define DISABLE_SIGN_COMPARE_WARNINGS
2
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"
16
17 void free_worktree(struct worktree *worktree)
18 {
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);
27 }
28
29 void free_worktrees(struct worktree **worktrees)
30 {
31 int i = 0;
32 for (i = 0; worktrees[i]; i++)
33 free_worktree(worktrees[i]);
34 free (worktrees);
35 }
36
37 /**
38 * Update head_oid, head_ref and is_detached of the given worktree
39 */
40 static void add_head_info(struct worktree *wt)
41 {
42 int flags;
43 const char *target;
44
45 target = refs_resolve_ref_unsafe(get_worktree_ref_store(wt),
46 "HEAD",
47 0,
48 &wt->head_oid, &flags);
49 if (!target)
50 return;
51
52 if (flags & REF_ISSYMREF)
53 wt->head_ref = xstrdup(target);
54 else
55 wt->is_detached = 1;
56 }
57
58 static int is_current_worktree(struct worktree *wt)
59 {
60 char *git_dir = absolute_pathdup(repo_get_git_dir(wt->repo));
61 char *wt_git_dir = get_worktree_git_dir(wt);
62 int is_current = !fspathcmp(git_dir, absolute_path(wt_git_dir));
63 free(wt_git_dir);
64 free(git_dir);
65 return is_current;
66 }
67
68 struct worktree *get_current_worktree(struct repository *repo)
69 {
70 struct worktree *wt = xcalloc(1, sizeof(*wt));
71 char *gitdir = absolute_pathdup(repo->gitdir);
72 char *commondir = absolute_pathdup(repo->commondir);
73
74 wt->repo = repo;
75 wt->path = absolute_pathdup(repo->worktree ? repo->worktree
76 : repo->gitdir);
77 wt->is_bare = !repo->worktree;
78 if (fspathcmp(gitdir, commondir))
79 wt->id = xstrdup(find_last_dir_sep(gitdir) + 1);
80 wt->is_current = true;
81 add_head_info(wt);
82
83 free(gitdir);
84 free(commondir);
85 return wt;
86 }
87
88 /*
89 * When in a secondary worktree, and when extensions.worktreeConfig
90 * is true, only $commondir/config and $commondir/worktrees/<id>/
91 * config.worktree are consulted, hence any core.bare=true setting in
92 * $commondir/config.worktree gets overlooked. Thus, check it manually
93 * to determine if the repository is bare.
94 */
95 static int is_main_worktree_bare(struct repository *repo)
96 {
97 int bare = 0;
98 struct config_set cs = {0};
99 char *worktree_config = xstrfmt("%s/config.worktree", repo_get_common_dir(repo));
100
101 git_configset_init(&cs);
102 git_configset_add_file(&cs, worktree_config);
103 git_configset_get_bool(&cs, "core.bare", &bare);
104
105 git_configset_clear(&cs);
106 free(worktree_config);
107 return bare;
108 }
109
110 /**
111 * get the main worktree
112 */
113 static struct worktree *get_main_worktree(struct repository *repo,
114 int skip_reading_head)
115 {
116 struct worktree *worktree = NULL;
117 struct strbuf worktree_path = STRBUF_INIT;
118
119 strbuf_add_real_path(&worktree_path, repo_get_common_dir(repo));
120 strbuf_strip_suffix(&worktree_path, "/.git");
121
122 CALLOC_ARRAY(worktree, 1);
123 worktree->repo = repo;
124 worktree->path = strbuf_detach(&worktree_path, NULL);
125 worktree->is_current = is_current_worktree(worktree);
126 worktree->is_bare = (repo->bare_cfg == 1) ||
127 is_bare_repository(repo) ||
128 /*
129 * When in a secondary worktree we have to also verify if the main
130 * worktree is bare in $commondir/config.worktree.
131 * This check is unnecessary if we're currently in the main worktree,
132 * as prior checks already consulted all configs of the current worktree.
133 */
134 (!worktree->is_current && is_main_worktree_bare(repo));
135
136 if (!skip_reading_head)
137 add_head_info(worktree);
138 return worktree;
139 }
140
141 struct worktree *get_linked_worktree(struct repository *repo,
142 const char *id,
143 int skip_reading_head)
144 {
145 struct worktree *worktree = NULL;
146 struct strbuf path = STRBUF_INIT;
147 struct strbuf worktree_path = STRBUF_INIT;
148
149 if (!id)
150 die("Missing linked worktree name");
151
152 repo_common_path_append(repo, &path, "worktrees/%s/gitdir", id);
153 if (strbuf_read_file(&worktree_path, path.buf, 0) <= 0)
154 /* invalid gitdir file */
155 goto done;
156 strbuf_rtrim(&worktree_path);
157 strbuf_strip_suffix(&worktree_path, "/.git");
158
159 if (!is_absolute_path(worktree_path.buf)) {
160 strbuf_strip_suffix(&path, "gitdir");
161 strbuf_addbuf(&path, &worktree_path);
162 strbuf_realpath_forgiving(&worktree_path, path.buf, 0);
163 }
164
165 CALLOC_ARRAY(worktree, 1);
166 worktree->repo = repo;
167 worktree->path = strbuf_detach(&worktree_path, NULL);
168 worktree->id = xstrdup(id);
169 worktree->is_current = is_current_worktree(worktree);
170 if (!skip_reading_head)
171 add_head_info(worktree);
172
173 done:
174 strbuf_release(&path);
175 strbuf_release(&worktree_path);
176 return worktree;
177 }
178
179 /*
180 * NEEDSWORK: This function exists so that we can look up metadata of a
181 * worktree without trying to access any of its internals like the refdb. It
182 * would be preferable to instead have a corruption-tolerant function for
183 * retrieving worktree metadata that could be used when the worktree is known
184 * to not be in a healthy state, e.g. when creating or repairing it.
185 */
186 static struct worktree **get_worktrees_internal(struct repository *repo,
187 int skip_reading_head)
188 {
189 struct worktree **list = NULL;
190 struct strbuf path = STRBUF_INIT;
191 DIR *dir;
192 struct dirent *d;
193 int counter = 0, alloc = 2;
194
195 ALLOC_ARRAY(list, alloc);
196
197 list[counter++] = get_main_worktree(repo, skip_reading_head);
198
199 strbuf_addf(&path, "%s/worktrees", repo_get_common_dir(repo));
200 dir = opendir(path.buf);
201 strbuf_release(&path);
202 if (dir) {
203 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
204 struct worktree *linked = NULL;
205
206 if ((linked = get_linked_worktree(repo, d->d_name, skip_reading_head))) {
207 ALLOC_GROW(list, counter + 1, alloc);
208 list[counter++] = linked;
209 }
210 }
211 closedir(dir);
212 }
213 ALLOC_GROW(list, counter + 1, alloc);
214 list[counter] = NULL;
215
216 return list;
217 }
218
219 struct worktree **get_worktrees(struct repository *repo)
220 {
221 return get_worktrees_internal(repo, 0);
222 }
223
224 struct worktree **get_worktrees_without_reading_head(struct repository *repo)
225 {
226 return get_worktrees_internal(repo, 1);
227 }
228
229 char *get_worktree_git_dir(const struct worktree *wt)
230 {
231 if (!wt)
232 BUG("%s() called with NULL worktree", __func__);
233 else if (!wt->id)
234 return xstrdup(repo_get_common_dir(wt->repo));
235 else
236 return repo_common_path(wt->repo, "worktrees/%s", wt->id);
237 }
238
239 static struct worktree *find_worktree_by_suffix(struct worktree **list,
240 const char *suffix)
241 {
242 struct worktree *found = NULL;
243 int nr_found = 0, suffixlen;
244
245 suffixlen = strlen(suffix);
246 if (!suffixlen)
247 return NULL;
248
249 for (; *list && nr_found < 2; list++) {
250 const char *path = (*list)->path;
251 int pathlen = strlen(path);
252 int start = pathlen - suffixlen;
253
254 /* suffix must start at directory boundary */
255 if ((!start || (start > 0 && is_dir_sep(path[start - 1]))) &&
256 !fspathcmp(suffix, path + start)) {
257 found = *list;
258 nr_found++;
259 }
260 }
261 return nr_found == 1 ? found : NULL;
262 }
263
264 struct worktree *find_worktree(struct worktree **list,
265 const char *prefix,
266 const char *arg)
267 {
268 struct worktree *wt;
269 char *to_free = NULL;
270
271 if ((wt = find_worktree_by_suffix(list, arg)))
272 return wt;
273
274 if (prefix)
275 arg = to_free = prefix_filename(prefix, arg);
276 wt = find_worktree_by_path(list, arg);
277 free(to_free);
278 return wt;
279 }
280
281 struct worktree *find_worktree_by_path(struct worktree **list, const char *p)
282 {
283 struct strbuf wt_path = STRBUF_INIT;
284 char *path = real_pathdup(p, 0);
285
286 if (!path)
287 return NULL;
288 for (; *list; list++) {
289 if (!strbuf_realpath(&wt_path, (*list)->path, 0))
290 continue;
291
292 if (!fspathcmp(path, wt_path.buf))
293 break;
294 }
295 free(path);
296 strbuf_release(&wt_path);
297 return *list;
298 }
299
300 int is_main_worktree(const struct worktree *wt)
301 {
302 return !wt->id;
303 }
304
305 const char *worktree_lock_reason(struct worktree *wt)
306 {
307 if (is_main_worktree(wt))
308 return NULL;
309
310 if (!wt->lock_reason_valid) {
311 struct strbuf path = STRBUF_INIT;
312
313 strbuf_addstr(&path, worktree_git_path(wt, "locked"));
314 if (file_exists(path.buf)) {
315 struct strbuf lock_reason = STRBUF_INIT;
316 if (strbuf_read_file(&lock_reason, path.buf, 0) < 0)
317 die_errno(_("failed to read '%s'"), path.buf);
318 strbuf_trim(&lock_reason);
319 wt->lock_reason = strbuf_detach(&lock_reason, NULL);
320 } else
321 wt->lock_reason = NULL;
322 wt->lock_reason_valid = 1;
323 strbuf_release(&path);
324 }
325
326 return wt->lock_reason;
327 }
328
329 const char *worktree_prune_reason(struct worktree *wt, timestamp_t expire)
330 {
331 struct strbuf reason = STRBUF_INIT;
332 char *path = NULL;
333
334 if (is_main_worktree(wt))
335 return NULL;
336 if (wt->prune_reason_valid)
337 return wt->prune_reason;
338
339 if (should_prune_worktree(wt->repo, wt->id, &reason, &path, expire))
340 wt->prune_reason = strbuf_detach(&reason, NULL);
341 wt->prune_reason_valid = 1;
342
343 strbuf_release(&reason);
344 free(path);
345 return wt->prune_reason;
346 }
347
348 /* convenient wrapper to deal with NULL strbuf */
349 __attribute__((format (printf, 2, 3)))
350 static void strbuf_addf_gently(struct strbuf *buf, const char *fmt, ...)
351 {
352 va_list params;
353
354 if (!buf)
355 return;
356
357 va_start(params, fmt);
358 strbuf_vaddf(buf, fmt, params);
359 va_end(params);
360 }
361
362 int validate_worktree(const struct worktree *wt, struct strbuf *errmsg,
363 unsigned flags)
364 {
365 struct strbuf wt_path = STRBUF_INIT;
366 struct strbuf realpath = STRBUF_INIT;
367 struct strbuf buf = STRBUF_INIT;
368 char *path = NULL;
369 int err, ret = -1;
370
371 strbuf_addf(&wt_path, "%s/.git", wt->path);
372
373 if (is_main_worktree(wt)) {
374 if (is_directory(wt_path.buf)) {
375 ret = 0;
376 goto done;
377 }
378 /*
379 * Main worktree using .git file to point to the
380 * repository would make it impossible to know where
381 * the actual worktree is if this function is executed
382 * from another worktree. No .git file support for now.
383 */
384 strbuf_addf_gently(errmsg,
385 _("'%s' at main working tree is not the repository directory"),
386 wt_path.buf);
387 goto done;
388 }
389
390 /*
391 * Make sure "gitdir" file points to a real .git file and that
392 * file points back here.
393 */
394 if (!is_absolute_path(wt->path)) {
395 strbuf_addf_gently(errmsg,
396 _("'%s' file does not contain absolute path to the working tree location"),
397 repo_common_path_replace(wt->repo, &buf, "worktrees/%s/gitdir", wt->id));
398 goto done;
399 }
400
401 if (flags & WT_VALIDATE_WORKTREE_MISSING_OK &&
402 !file_exists(wt->path)) {
403 ret = 0;
404 goto done;
405 }
406
407 if (!file_exists(wt_path.buf)) {
408 strbuf_addf_gently(errmsg, _("'%s' does not exist"), wt_path.buf);
409 goto done;
410 }
411
412 path = xstrdup_or_null(read_gitfile_gently(wt_path.buf, &err));
413 if (!path) {
414 strbuf_addf_gently(errmsg, _("'%s' is not a .git file, error code %d"),
415 wt_path.buf, err);
416 goto done;
417 }
418
419 strbuf_realpath(&realpath, repo_common_path_replace(wt->repo, &buf, "worktrees/%s", wt->id), 1);
420 ret = fspathcmp(path, realpath.buf);
421
422 if (ret)
423 strbuf_addf_gently(errmsg, _("'%s' does not point back to '%s'"),
424 wt->path, repo_common_path_replace(wt->repo, &buf,
425 "worktrees/%s", wt->id));
426 done:
427 free(path);
428 strbuf_release(&buf);
429 strbuf_release(&wt_path);
430 strbuf_release(&realpath);
431 return ret;
432 }
433
434 void update_worktree_location(struct worktree *wt, const char *path_,
435 int use_relative_paths)
436 {
437 struct strbuf path = STRBUF_INIT;
438 struct strbuf dotgit = STRBUF_INIT;
439 struct strbuf gitdir = STRBUF_INIT;
440 char *wt_gitdir;
441
442 if (is_main_worktree(wt))
443 BUG("can't relocate main worktree");
444
445 wt_gitdir = repo_common_path(wt->repo, "worktrees/%s/gitdir", wt->id);
446 strbuf_realpath(&gitdir, wt_gitdir, 1);
447 strbuf_realpath(&path, path_, 1);
448 strbuf_addf(&dotgit, "%s/.git", path.buf);
449 if (fspathcmp(wt->path, path.buf)) {
450 write_worktree_linking_files(wt->repo, dotgit.buf,
451 gitdir.buf, use_relative_paths);
452
453 free(wt->path);
454 wt->path = strbuf_detach(&path, NULL);
455 }
456 strbuf_release(&path);
457 strbuf_release(&dotgit);
458 strbuf_release(&gitdir);
459 free(wt_gitdir);
460 }
461
462 int is_worktree_being_rebased(const struct worktree *wt,
463 const char *target)
464 {
465 struct wt_status_state state;
466 int found_rebase;
467
468 memset(&state, 0, sizeof(state));
469 found_rebase = wt_status_check_rebase(wt, &state) &&
470 (state.rebase_in_progress ||
471 state.rebase_interactive_in_progress) &&
472 state.branch &&
473 skip_prefix(target, "refs/heads/", &target) &&
474 !strcmp(state.branch, target);
475 wt_status_state_free_buffers(&state);
476 return found_rebase;
477 }
478
479 int is_worktree_being_bisected(const struct worktree *wt,
480 const char *target)
481 {
482 struct wt_status_state state;
483 int found_bisect;
484
485 memset(&state, 0, sizeof(state));
486 found_bisect = wt_status_check_bisect(wt, &state) &&
487 state.bisecting_from &&
488 skip_prefix(target, "refs/heads/", &target) &&
489 !strcmp(state.bisecting_from, target);
490 wt_status_state_free_buffers(&state);
491 return found_bisect;
492 }
493
494 /*
495 * note: this function should be able to detect shared symref even if
496 * HEAD is temporarily detached (e.g. in the middle of rebase or
497 * bisect). New commands that do similar things should update this
498 * function as well.
499 */
500 int is_shared_symref(const struct worktree *wt, const char *symref,
501 const char *target)
502 {
503 const char *symref_target;
504 struct ref_store *refs;
505 int flags;
506
507 if (wt->is_bare)
508 return 0;
509
510 if (wt->is_detached && !strcmp(symref, "HEAD")) {
511 if (is_worktree_being_rebased(wt, target))
512 return 1;
513 if (is_worktree_being_bisected(wt, target))
514 return 1;
515 }
516
517 refs = get_worktree_ref_store(wt);
518 symref_target = refs_resolve_ref_unsafe(refs, symref, 0,
519 NULL, &flags);
520 if ((flags & REF_ISSYMREF) &&
521 symref_target && !strcmp(symref_target, target))
522 return 1;
523
524 return 0;
525 }
526
527 const struct worktree *find_shared_symref(struct worktree **worktrees,
528 const char *symref,
529 const char *target)
530 {
531
532 for (int i = 0; worktrees[i]; i++)
533 if (is_shared_symref(worktrees[i], symref, target))
534 return worktrees[i];
535
536 return NULL;
537 }
538
539 int submodule_uses_worktrees(struct repository *repo,
540 const char *path)
541 {
542 char *submodule_gitdir;
543 struct strbuf sb = STRBUF_INIT, err = STRBUF_INIT;
544 DIR *dir;
545 struct dirent *d;
546 int ret = 0;
547 struct repository_format format = REPOSITORY_FORMAT_INIT;
548
549 submodule_gitdir = repo_submodule_path(repo,
550 path, "%s", "");
551 if (!submodule_gitdir)
552 return 0;
553
554 /* The env would be set for the superproject. */
555 get_common_dir_noenv(&sb, submodule_gitdir);
556 free(submodule_gitdir);
557
558 strbuf_addstr(&sb, "/config");
559 read_repository_format(&format, sb.buf);
560 if (verify_repository_format(&format, &err)) {
561 strbuf_release(&err);
562 strbuf_release(&sb);
563 clear_repository_format(&format);
564 return 1;
565 }
566 clear_repository_format(&format);
567 strbuf_release(&err);
568
569 /* Replace config by worktrees. */
570 strbuf_setlen(&sb, sb.len - strlen("config"));
571 strbuf_addstr(&sb, "worktrees");
572
573 /* See if there is any file inside the worktrees directory. */
574 dir = opendir(sb.buf);
575 strbuf_release(&sb);
576
577 if (!dir)
578 return 0;
579
580 d = readdir_skip_dot_and_dotdot(dir);
581 if (d)
582 ret = 1;
583 closedir(dir);
584 return ret;
585 }
586
587 void strbuf_worktree_ref(const struct worktree *wt,
588 struct strbuf *sb,
589 const char *refname)
590 {
591 if (parse_worktree_ref(refname, NULL, NULL, NULL) ==
592 REF_WORKTREE_CURRENT &&
593 wt && !wt->is_current) {
594 if (is_main_worktree(wt))
595 strbuf_addstr(sb, "main-worktree/");
596 else
597 strbuf_addf(sb, "worktrees/%s/", wt->id);
598 }
599 strbuf_addstr(sb, refname);
600 }
601
602 int other_head_refs(struct repository *repo,
603 refs_for_each_cb fn, void *cb_data)
604 {
605 struct worktree **worktrees, **p;
606 struct strbuf refname = STRBUF_INIT;
607 int ret = 0;
608
609 worktrees = get_worktrees(repo);
610 for (p = worktrees; *p; p++) {
611 struct worktree *wt = *p;
612 struct object_id oid;
613 int flag;
614
615 if (wt->is_current)
616 continue;
617
618 strbuf_reset(&refname);
619 strbuf_worktree_ref(wt, &refname, "HEAD");
620 if (refs_resolve_ref_unsafe(get_main_ref_store(repo),
621 refname.buf,
622 RESOLVE_REF_READING,
623 &oid, &flag)) {
624 struct reference ref = {
625 .name = refname.buf,
626 .oid = &oid,
627 .flags = flag,
628 };
629
630 ret = fn(&ref, cb_data);
631 }
632 if (ret)
633 break;
634 }
635 free_worktrees(worktrees);
636 strbuf_release(&refname);
637 return ret;
638 }
639
640 /*
641 * Repair worktree's /path/to/worktree/.git file if missing, corrupt, or not
642 * pointing at <repo>/worktrees/<id>.
643 */
644 static void repair_gitfile(struct worktree *wt,
645 worktree_repair_fn fn, void *cb_data,
646 int use_relative_paths)
647 {
648 struct strbuf dotgit = STRBUF_INIT;
649 struct strbuf gitdir = STRBUF_INIT;
650 struct strbuf repo = STRBUF_INIT;
651 struct strbuf backlink = STRBUF_INIT;
652 char *dotgit_contents = NULL;
653 const char *repair = NULL;
654 char *path = NULL;
655 int err;
656
657 /* missing worktree can't be repaired */
658 if (!file_exists(wt->path))
659 goto done;
660
661 if (!is_directory(wt->path)) {
662 fn(1, wt->path, _("not a directory"), cb_data);
663 goto done;
664 }
665
666 path = repo_common_path(wt->repo, "worktrees/%s", wt->id);
667 strbuf_realpath(&repo, path, 1);
668 strbuf_addf(&dotgit, "%s/.git", wt->path);
669 strbuf_addf(&gitdir, "%s/gitdir", repo.buf);
670 dotgit_contents = xstrdup_or_null(read_gitfile_gently(dotgit.buf, &err));
671
672 if (dotgit_contents) {
673 if (is_absolute_path(dotgit_contents)) {
674 strbuf_addstr(&backlink, dotgit_contents);
675 } else {
676 strbuf_addf(&backlink, "%s/%s", wt->path, dotgit_contents);
677 strbuf_realpath_forgiving(&backlink, backlink.buf, 0);
678 }
679 }
680
681 if (err == READ_GITFILE_ERR_NOT_A_FILE ||
682 err == READ_GITFILE_ERR_IS_A_DIR)
683 fn(1, wt->path, _(".git is not a file"), cb_data);
684 else if (err)
685 repair = _(".git file broken");
686 else if (fspathcmp(backlink.buf, repo.buf))
687 repair = _(".git file incorrect");
688 else if (use_relative_paths == is_absolute_path(dotgit_contents))
689 repair = _(".git file absolute/relative path mismatch");
690
691 if (repair) {
692 fn(0, wt->path, repair, cb_data);
693 write_worktree_linking_files(wt->repo, dotgit.buf,
694 gitdir.buf, use_relative_paths);
695 }
696
697 done:
698 free(dotgit_contents);
699 free(path);
700 strbuf_release(&repo);
701 strbuf_release(&dotgit);
702 strbuf_release(&gitdir);
703 strbuf_release(&backlink);
704 }
705
706 static void repair_noop(int iserr UNUSED,
707 const char *path UNUSED,
708 const char *msg UNUSED,
709 void *cb_data UNUSED)
710 {
711 /* nothing */
712 }
713
714 void repair_worktrees(struct repository *repo, worktree_repair_fn fn,
715 void *cb_data, int use_relative_paths)
716 {
717 struct worktree **worktrees = get_worktrees_internal(repo, 1);
718 struct worktree **wt = worktrees + 1; /* +1 skips main worktree */
719
720 if (!fn)
721 fn = repair_noop;
722 for (; *wt; wt++)
723 repair_gitfile(*wt, fn, cb_data, use_relative_paths);
724 free_worktrees(worktrees);
725 }
726
727 void repair_worktree_after_gitdir_move(struct worktree *wt, const char *old_path)
728 {
729 struct strbuf gitdir = STRBUF_INIT;
730 struct strbuf dotgit = STRBUF_INIT;
731 int is_relative_path;
732 char *path = NULL;
733
734 if (is_main_worktree(wt))
735 goto done;
736
737 path = repo_common_path(wt->repo, "worktrees/%s/gitdir", wt->id);
738 strbuf_realpath(&gitdir, path, 1);
739
740 if (strbuf_read_file(&dotgit, gitdir.buf, 0) < 0)
741 goto done;
742
743 strbuf_rtrim(&dotgit);
744 is_relative_path = ! is_absolute_path(dotgit.buf);
745 if (is_relative_path) {
746 strbuf_insertf(&dotgit, 0, "%s/worktrees/%s/", old_path, wt->id);
747 strbuf_realpath_forgiving(&dotgit, dotgit.buf, 0);
748 }
749
750 if (!file_exists(dotgit.buf))
751 goto done;
752
753 write_worktree_linking_files(wt->repo, dotgit.buf,
754 gitdir.buf, is_relative_path);
755 done:
756 strbuf_release(&gitdir);
757 strbuf_release(&dotgit);
758 free(path);
759 }
760
761 void repair_worktrees_after_gitdir_move(struct repository *repo, const char *old_path)
762 {
763 struct worktree **worktrees = get_worktrees_internal(repo, 1);
764 struct worktree **wt = worktrees + 1; /* +1 skips main worktree */
765
766 for (; *wt; wt++)
767 repair_worktree_after_gitdir_move(*wt, old_path);
768 free_worktrees(worktrees);
769 }
770
771 static int is_main_worktree_path(struct repository *repo, const char *path)
772 {
773 struct strbuf target = STRBUF_INIT;
774 struct strbuf maindir = STRBUF_INIT;
775 int cmp;
776
777 strbuf_add_real_path(&target, path);
778 strbuf_strip_suffix(&target, "/.git");
779 strbuf_add_real_path(&maindir, repo_get_common_dir(repo));
780 strbuf_strip_suffix(&maindir, "/.git");
781 cmp = fspathcmp(maindir.buf, target.buf);
782
783 strbuf_release(&maindir);
784 strbuf_release(&target);
785 return !cmp;
786 }
787
788 /*
789 * If both the main worktree and linked worktree have been moved, then the
790 * gitfile /path/to/worktree/.git won't point into the repository, thus we
791 * won't know which <repo>/worktrees/<id>/gitdir to repair. However, we may
792 * be able to infer the gitdir by manually reading /path/to/worktree/.git,
793 * extracting the <id>, and checking if <repo>/worktrees/<id> exists.
794 *
795 * Returns -1 on failure and strbuf.len on success.
796 */
797 static ssize_t infer_backlink(struct repository *repo,
798 const char *gitfile,
799 struct strbuf *inferred)
800 {
801 struct strbuf actual = STRBUF_INIT;
802 const char *id;
803
804 if (strbuf_read_file(&actual, gitfile, 0) < 0)
805 goto error;
806 if (!starts_with(actual.buf, "gitdir:"))
807 goto error;
808 if (!(id = find_last_dir_sep(actual.buf)))
809 goto error;
810 strbuf_trim(&actual);
811 id++; /* advance past '/' to point at <id> */
812 if (!*id)
813 goto error;
814 repo_common_path_replace(repo, inferred, "worktrees/%s", id);
815 if (!is_directory(inferred->buf))
816 goto error;
817
818 strbuf_release(&actual);
819 return inferred->len;
820 error:
821 strbuf_release(&actual);
822 strbuf_reset(inferred); /* clear invalid path */
823 return -1;
824 }
825
826 /*
827 * Repair <repo>/worktrees/<id>/gitdir if missing, corrupt, or not pointing at
828 * the worktree's path.
829 */
830 void repair_worktree_at_path(struct repository *repo,
831 const char *path,
832 worktree_repair_fn fn, void *cb_data,
833 int use_relative_paths)
834 {
835 struct strbuf dotgit = STRBUF_INIT;
836 struct strbuf backlink = STRBUF_INIT;
837 struct strbuf inferred_backlink = STRBUF_INIT;
838 struct strbuf gitdir = STRBUF_INIT;
839 struct strbuf olddotgit = STRBUF_INIT;
840 char *dotgit_contents = NULL;
841 const char *repair = NULL;
842 int err;
843
844 if (!fn)
845 fn = repair_noop;
846
847 if (is_main_worktree_path(repo, path))
848 goto done;
849
850 strbuf_addf(&dotgit, "%s/.git", path);
851 if (!strbuf_realpath(&dotgit, dotgit.buf, 0)) {
852 fn(1, path, _("not a valid path"), cb_data);
853 goto done;
854 }
855
856 infer_backlink(repo, dotgit.buf, &inferred_backlink);
857 strbuf_realpath_forgiving(&inferred_backlink, inferred_backlink.buf, 0);
858 dotgit_contents = xstrdup_or_null(read_gitfile_gently(dotgit.buf, &err));
859 if (dotgit_contents) {
860 if (is_absolute_path(dotgit_contents)) {
861 strbuf_addstr(&backlink, dotgit_contents);
862 } else {
863 strbuf_addbuf(&backlink, &dotgit);
864 strbuf_strip_suffix(&backlink, ".git");
865 strbuf_addstr(&backlink, dotgit_contents);
866 strbuf_realpath_forgiving(&backlink, backlink.buf, 0);
867 }
868 } else if (err == READ_GITFILE_ERR_NOT_A_FILE ||
869 err == READ_GITFILE_ERR_IS_A_DIR) {
870 fn(1, dotgit.buf, _("unable to locate repository; .git is not a file"), cb_data);
871 goto done;
872 } else if (err == READ_GITFILE_ERR_NOT_A_REPO) {
873 if (inferred_backlink.len) {
874 /*
875 * Worktree's .git file does not point at a repository
876 * but we found a .git/worktrees/<id> in this
877 * repository with the same <id> as recorded in the
878 * worktree's .git file so make the worktree point at
879 * the discovered .git/worktrees/<id>.
880 */
881 strbuf_swap(&backlink, &inferred_backlink);
882 } else {
883 fn(1, dotgit.buf, _("unable to locate repository; .git file does not reference a repository"), cb_data);
884 goto done;
885 }
886 } else {
887 fn(1, dotgit.buf, _("unable to locate repository; .git file broken"), cb_data);
888 goto done;
889 }
890
891 /*
892 * If we got this far, either the worktree's .git file pointed at a
893 * valid repository (i.e. read_gitfile_gently() returned success) or
894 * the .git file did not point at a repository but we were able to
895 * infer a suitable new value for the .git file by locating a
896 * .git/worktrees/<id> in *this* repository corresponding to the <id>
897 * recorded in the worktree's .git file.
898 *
899 * However, if, at this point, inferred_backlink is non-NULL (i.e. we
900 * found a suitable .git/worktrees/<id> in *this* repository) *and* the
901 * worktree's .git file points at a valid repository *and* those two
902 * paths differ, then that indicates that the user probably *copied*
903 * the main and linked worktrees to a new location as a unit rather
904 * than *moving* them. Thus, the copied worktree's .git file actually
905 * points at the .git/worktrees/<id> in the *original* repository, not
906 * in the "copy" repository. In this case, point the "copy" worktree's
907 * .git file at the "copy" repository.
908 */
909 if (inferred_backlink.len && fspathcmp(backlink.buf, inferred_backlink.buf))
910 strbuf_swap(&backlink, &inferred_backlink);
911
912 strbuf_addf(&gitdir, "%s/gitdir", backlink.buf);
913 if (strbuf_read_file(&olddotgit, gitdir.buf, 0) < 0)
914 repair = _("gitdir unreadable");
915 else if (use_relative_paths == is_absolute_path(olddotgit.buf))
916 repair = _("gitdir absolute/relative path mismatch");
917 else {
918 strbuf_rtrim(&olddotgit);
919 if (!is_absolute_path(olddotgit.buf)) {
920 strbuf_insertf(&olddotgit, 0, "%s/", backlink.buf);
921 strbuf_realpath_forgiving(&olddotgit, olddotgit.buf, 0);
922 }
923 if (fspathcmp(olddotgit.buf, dotgit.buf))
924 repair = _("gitdir incorrect");
925 }
926
927 if (repair) {
928 fn(0, gitdir.buf, repair, cb_data);
929 write_worktree_linking_files(repo, dotgit.buf,
930 gitdir.buf, use_relative_paths);
931 }
932 done:
933 free(dotgit_contents);
934 strbuf_release(&olddotgit);
935 strbuf_release(&backlink);
936 strbuf_release(&inferred_backlink);
937 strbuf_release(&gitdir);
938 strbuf_release(&dotgit);
939 }
940
941 int should_prune_worktree(struct repository *repo,
942 const char *id,
943 struct strbuf *reason,
944 char **wtpath,
945 timestamp_t expire)
946 {
947 struct stat st;
948 struct strbuf dotgit = STRBUF_INIT;
949 struct strbuf gitdir = STRBUF_INIT;
950 struct strbuf repo_path = STRBUF_INIT;
951 struct strbuf file = STRBUF_INIT;
952 char *path = NULL;
953 int rc = 0;
954 int fd;
955 size_t len;
956 ssize_t read_result;
957
958 *wtpath = NULL;
959
960 path = repo_common_path(repo, "worktrees/%s", id);
961 strbuf_realpath(&repo_path, path, 1);
962 FREE_AND_NULL(path);
963
964 strbuf_addf(&gitdir, "%s/gitdir", repo_path.buf);
965 if (!is_directory(repo_path.buf)) {
966 strbuf_addstr(reason, _("not a valid directory"));
967 rc = 1;
968 goto done;
969 }
970 strbuf_addf(&file, "%s/locked", repo_path.buf);
971 if (file_exists(file.buf)) {
972 goto done;
973 }
974 if (stat(gitdir.buf, &st)) {
975 strbuf_addstr(reason, _("gitdir file does not exist"));
976 rc = 1;
977 goto done;
978 }
979 fd = open(gitdir.buf, O_RDONLY);
980 if (fd < 0) {
981 strbuf_addf(reason, _("unable to read gitdir file (%s)"),
982 strerror(errno));
983 rc = 1;
984 goto done;
985 }
986 len = xsize_t(st.st_size);
987 path = xmallocz(len);
988
989 read_result = read_in_full(fd, path, len);
990 close(fd);
991 if (read_result < 0) {
992 strbuf_addf(reason, _("unable to read gitdir file (%s)"),
993 strerror(errno));
994 rc = 1;
995 goto done;
996 } else if (read_result != len) {
997 strbuf_addf(reason,
998 _("short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
999 (uintmax_t)len, (uintmax_t)read_result);
1000 rc = 1;
1001 goto done;
1002 }
1003 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
1004 len--;
1005 if (!len) {
1006 strbuf_addstr(reason, _("invalid gitdir file"));
1007 rc = 1;
1008 goto done;
1009 }
1010 path[len] = '\0';
1011 if (is_absolute_path(path)) {
1012 strbuf_addstr(&dotgit, path);
1013 } else {
1014 strbuf_addf(&dotgit, "%s/%s", repo_path.buf, path);
1015 strbuf_realpath_forgiving(&dotgit, dotgit.buf, 0);
1016 }
1017 if (!file_exists(dotgit.buf)) {
1018 strbuf_reset(&file);
1019 strbuf_addf(&file, "%s/index", repo_path.buf);
1020 if (stat(file.buf, &st) || st.st_mtime <= expire) {
1021 strbuf_addstr(reason, _("gitdir file points to non-existent location"));
1022 rc = 1;
1023 goto done;
1024 }
1025 }
1026 *wtpath = strbuf_detach(&dotgit, NULL);
1027 done:
1028 free(path);
1029 strbuf_release(&dotgit);
1030 strbuf_release(&gitdir);
1031 strbuf_release(&repo_path);
1032 strbuf_release(&file);
1033 return rc;
1034 }
1035
1036 static int move_config_setting(struct repository *repo,
1037 const char *key, const char *value,
1038 const char *from_file, const char *to_file)
1039 {
1040 if (repo_config_set_in_file_gently(repo, to_file, key, NULL, value))
1041 return error(_("unable to set %s in '%s'"), key, to_file);
1042 if (repo_config_set_in_file_gently(repo, from_file, key, NULL, NULL))
1043 return error(_("unable to unset %s in '%s'"), key, from_file);
1044 return 0;
1045 }
1046
1047 int init_worktree_config(struct repository *r)
1048 {
1049 int res = 0;
1050 int bare = 0;
1051 struct config_set cs = { { 0 } };
1052 const char *core_worktree;
1053 char *common_config_file;
1054 char *main_worktree_file;
1055
1056 /*
1057 * If the extension is already enabled, then we can skip the
1058 * upgrade process.
1059 */
1060 if (r->repository_format_worktree_config)
1061 return 0;
1062 if ((res = repo_config_set_gently(r, "extensions.worktreeConfig", "true")))
1063 return error(_("failed to set extensions.worktreeConfig setting"));
1064
1065 common_config_file = xstrfmt("%s/config", r->commondir);
1066 main_worktree_file = xstrfmt("%s/config.worktree", r->commondir);
1067
1068 git_configset_init(&cs);
1069 git_configset_add_file(&cs, common_config_file);
1070
1071 /*
1072 * If core.bare is true in the common config file, then we need to
1073 * move it to the main worktree's config file or it will break all
1074 * worktrees. If it is false, then leave it in place because it
1075 * _could_ be negating a global core.bare=true.
1076 */
1077 if (!git_configset_get_bool(&cs, "core.bare", &bare) && bare) {
1078 if ((res = move_config_setting(r, "core.bare", "true",
1079 common_config_file,
1080 main_worktree_file)))
1081 goto cleanup;
1082 }
1083 /*
1084 * If core.worktree is set, then the main worktree is located
1085 * somewhere different than the parent of the common Git dir.
1086 * Relocate that value to avoid breaking all worktrees with this
1087 * upgrade to worktree config.
1088 */
1089 if (!git_configset_get_value(&cs, "core.worktree", &core_worktree, NULL)) {
1090 if ((res = move_config_setting(r, "core.worktree", core_worktree,
1091 common_config_file,
1092 main_worktree_file)))
1093 goto cleanup;
1094 }
1095
1096 /*
1097 * Ensure that we use worktree config for the remaining lifetime
1098 * of the current process.
1099 */
1100 r->repository_format_worktree_config = 1;
1101
1102 cleanup:
1103 git_configset_clear(&cs);
1104 free(common_config_file);
1105 free(main_worktree_file);
1106 return res;
1107 }
1108
1109 void write_worktree_linking_files(struct repository *repo,
1110 const char *dotgit, const char *gitdir,
1111 int use_relative_paths)
1112 {
1113 struct strbuf path = STRBUF_INIT;
1114 struct strbuf repo_path = STRBUF_INIT;
1115 struct strbuf tmp = STRBUF_INIT;
1116
1117 strbuf_addstr(&path, dotgit);
1118 strbuf_strip_suffix(&path, "/.git");
1119 strbuf_realpath(&path, path.buf, 1);
1120 strbuf_addstr(&repo_path, gitdir);
1121 strbuf_strip_suffix(&repo_path, "/gitdir");
1122 strbuf_realpath(&repo_path, repo_path.buf, 1);
1123
1124 if (use_relative_paths && !repo->repository_format_relative_worktrees) {
1125 if (upgrade_repository_format(repo, 1) < 0)
1126 die(_("unable to upgrade repository format to support relative worktrees"));
1127 if (repo_config_set_gently(repo, "extensions.relativeWorktrees", "true"))
1128 die(_("unable to set extensions.relativeWorktrees setting"));
1129 repo->repository_format_relative_worktrees = 1;
1130 }
1131
1132 if (use_relative_paths) {
1133 write_file(gitdir, "%s/.git", relative_path(path.buf, repo_path.buf, &tmp));
1134 write_file(dotgit, "gitdir: %s", relative_path(repo_path.buf, path.buf, &tmp));
1135 } else {
1136 write_file(gitdir, "%s/.git", path.buf);
1137 write_file(dotgit, "gitdir: %s", repo_path.buf);
1138 }
1139
1140 strbuf_release(&path);
1141 strbuf_release(&repo_path);
1142 strbuf_release(&tmp);
1143 }