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