]> git.ipfire.org Git - thirdparty/git.git/blob - worktree.c
Merge branch 'ps/commit-graph-write-leakfix'
[thirdparty/git.git] / worktree.c
1 #include "git-compat-util.h"
2 #include "abspath.h"
3 #include "environment.h"
4 #include "gettext.h"
5 #include "path.h"
6 #include "repository.h"
7 #include "refs.h"
8 #include "setup.h"
9 #include "strbuf.h"
10 #include "worktree.h"
11 #include "dir.h"
12 #include "wt-status.h"
13 #include "config.h"
14
15 void free_worktrees(struct worktree **worktrees)
16 {
17 int i = 0;
18
19 for (i = 0; worktrees[i]; i++) {
20 free(worktrees[i]->path);
21 free(worktrees[i]->id);
22 free(worktrees[i]->head_ref);
23 free(worktrees[i]->lock_reason);
24 free(worktrees[i]->prune_reason);
25 free(worktrees[i]);
26 }
27 free (worktrees);
28 }
29
30 /**
31 * Update head_oid, head_ref and is_detached of the given worktree
32 */
33 static void add_head_info(struct worktree *wt)
34 {
35 int flags;
36 const char *target;
37
38 target = refs_resolve_ref_unsafe(get_worktree_ref_store(wt),
39 "HEAD",
40 0,
41 &wt->head_oid, &flags);
42 if (!target)
43 return;
44
45 if (flags & REF_ISSYMREF)
46 wt->head_ref = xstrdup(target);
47 else
48 wt->is_detached = 1;
49 }
50
51 /**
52 * get the main worktree
53 */
54 static struct worktree *get_main_worktree(int skip_reading_head)
55 {
56 struct worktree *worktree = NULL;
57 struct strbuf worktree_path = STRBUF_INIT;
58
59 strbuf_add_real_path(&worktree_path, get_git_common_dir());
60 strbuf_strip_suffix(&worktree_path, "/.git");
61
62 CALLOC_ARRAY(worktree, 1);
63 worktree->path = strbuf_detach(&worktree_path, NULL);
64 /*
65 * NEEDSWORK: If this function is called from a secondary worktree and
66 * config.worktree is present, is_bare_repository_cfg will reflect the
67 * contents of config.worktree, not the contents of the main worktree.
68 * This means that worktree->is_bare may be set to 0 even if the main
69 * worktree is configured to be bare.
70 */
71 worktree->is_bare = (is_bare_repository_cfg == 1) ||
72 is_bare_repository();
73 if (!skip_reading_head)
74 add_head_info(worktree);
75 return worktree;
76 }
77
78 static struct worktree *get_linked_worktree(const char *id,
79 int skip_reading_head)
80 {
81 struct worktree *worktree = NULL;
82 struct strbuf path = STRBUF_INIT;
83 struct strbuf worktree_path = STRBUF_INIT;
84
85 if (!id)
86 die("Missing linked worktree name");
87
88 strbuf_git_common_path(&path, the_repository, "worktrees/%s/gitdir", id);
89 if (strbuf_read_file(&worktree_path, path.buf, 0) <= 0)
90 /* invalid gitdir file */
91 goto done;
92 strbuf_rtrim(&worktree_path);
93 strbuf_strip_suffix(&worktree_path, "/.git");
94
95 CALLOC_ARRAY(worktree, 1);
96 worktree->path = strbuf_detach(&worktree_path, NULL);
97 worktree->id = xstrdup(id);
98 if (!skip_reading_head)
99 add_head_info(worktree);
100
101 done:
102 strbuf_release(&path);
103 strbuf_release(&worktree_path);
104 return worktree;
105 }
106
107 static void mark_current_worktree(struct worktree **worktrees)
108 {
109 char *git_dir = absolute_pathdup(get_git_dir());
110 int i;
111
112 for (i = 0; worktrees[i]; i++) {
113 struct worktree *wt = worktrees[i];
114 const char *wt_git_dir = get_worktree_git_dir(wt);
115
116 if (!fspathcmp(git_dir, absolute_path(wt_git_dir))) {
117 wt->is_current = 1;
118 break;
119 }
120 }
121 free(git_dir);
122 }
123
124 /*
125 * NEEDSWORK: This function exists so that we can look up metadata of a
126 * worktree without trying to access any of its internals like the refdb. It
127 * would be preferable to instead have a corruption-tolerant function for
128 * retrieving worktree metadata that could be used when the worktree is known
129 * to not be in a healthy state, e.g. when creating or repairing it.
130 */
131 static struct worktree **get_worktrees_internal(int skip_reading_head)
132 {
133 struct worktree **list = NULL;
134 struct strbuf path = STRBUF_INIT;
135 DIR *dir;
136 struct dirent *d;
137 int counter = 0, alloc = 2;
138
139 ALLOC_ARRAY(list, alloc);
140
141 list[counter++] = get_main_worktree(skip_reading_head);
142
143 strbuf_addf(&path, "%s/worktrees", get_git_common_dir());
144 dir = opendir(path.buf);
145 strbuf_release(&path);
146 if (dir) {
147 while ((d = readdir_skip_dot_and_dotdot(dir)) != NULL) {
148 struct worktree *linked = NULL;
149
150 if ((linked = get_linked_worktree(d->d_name, skip_reading_head))) {
151 ALLOC_GROW(list, counter + 1, alloc);
152 list[counter++] = linked;
153 }
154 }
155 closedir(dir);
156 }
157 ALLOC_GROW(list, counter + 1, alloc);
158 list[counter] = NULL;
159
160 mark_current_worktree(list);
161 return list;
162 }
163
164 struct worktree **get_worktrees(void)
165 {
166 return get_worktrees_internal(0);
167 }
168
169 const char *get_worktree_git_dir(const struct worktree *wt)
170 {
171 if (!wt)
172 return get_git_dir();
173 else if (!wt->id)
174 return get_git_common_dir();
175 else
176 return git_common_path("worktrees/%s", wt->id);
177 }
178
179 static struct worktree *find_worktree_by_suffix(struct worktree **list,
180 const char *suffix)
181 {
182 struct worktree *found = NULL;
183 int nr_found = 0, suffixlen;
184
185 suffixlen = strlen(suffix);
186 if (!suffixlen)
187 return NULL;
188
189 for (; *list && nr_found < 2; list++) {
190 const char *path = (*list)->path;
191 int pathlen = strlen(path);
192 int start = pathlen - suffixlen;
193
194 /* suffix must start at directory boundary */
195 if ((!start || (start > 0 && is_dir_sep(path[start - 1]))) &&
196 !fspathcmp(suffix, path + start)) {
197 found = *list;
198 nr_found++;
199 }
200 }
201 return nr_found == 1 ? found : NULL;
202 }
203
204 struct worktree *find_worktree(struct worktree **list,
205 const char *prefix,
206 const char *arg)
207 {
208 struct worktree *wt;
209 char *to_free = NULL;
210
211 if ((wt = find_worktree_by_suffix(list, arg)))
212 return wt;
213
214 if (prefix)
215 arg = to_free = prefix_filename(prefix, arg);
216 wt = find_worktree_by_path(list, arg);
217 free(to_free);
218 return wt;
219 }
220
221 struct worktree *find_worktree_by_path(struct worktree **list, const char *p)
222 {
223 struct strbuf wt_path = STRBUF_INIT;
224 char *path = real_pathdup(p, 0);
225
226 if (!path)
227 return NULL;
228 for (; *list; list++) {
229 if (!strbuf_realpath(&wt_path, (*list)->path, 0))
230 continue;
231
232 if (!fspathcmp(path, wt_path.buf))
233 break;
234 }
235 free(path);
236 strbuf_release(&wt_path);
237 return *list;
238 }
239
240 int is_main_worktree(const struct worktree *wt)
241 {
242 return !wt->id;
243 }
244
245 const char *worktree_lock_reason(struct worktree *wt)
246 {
247 if (is_main_worktree(wt))
248 return NULL;
249
250 if (!wt->lock_reason_valid) {
251 struct strbuf path = STRBUF_INIT;
252
253 strbuf_addstr(&path, worktree_git_path(wt, "locked"));
254 if (file_exists(path.buf)) {
255 struct strbuf lock_reason = STRBUF_INIT;
256 if (strbuf_read_file(&lock_reason, path.buf, 0) < 0)
257 die_errno(_("failed to read '%s'"), path.buf);
258 strbuf_trim(&lock_reason);
259 wt->lock_reason = strbuf_detach(&lock_reason, NULL);
260 } else
261 wt->lock_reason = NULL;
262 wt->lock_reason_valid = 1;
263 strbuf_release(&path);
264 }
265
266 return wt->lock_reason;
267 }
268
269 const char *worktree_prune_reason(struct worktree *wt, timestamp_t expire)
270 {
271 struct strbuf reason = STRBUF_INIT;
272 char *path = NULL;
273
274 if (is_main_worktree(wt))
275 return NULL;
276 if (wt->prune_reason_valid)
277 return wt->prune_reason;
278
279 if (should_prune_worktree(wt->id, &reason, &path, expire))
280 wt->prune_reason = strbuf_detach(&reason, NULL);
281 wt->prune_reason_valid = 1;
282
283 strbuf_release(&reason);
284 free(path);
285 return wt->prune_reason;
286 }
287
288 /* convenient wrapper to deal with NULL strbuf */
289 __attribute__((format (printf, 2, 3)))
290 static void strbuf_addf_gently(struct strbuf *buf, const char *fmt, ...)
291 {
292 va_list params;
293
294 if (!buf)
295 return;
296
297 va_start(params, fmt);
298 strbuf_vaddf(buf, fmt, params);
299 va_end(params);
300 }
301
302 int validate_worktree(const struct worktree *wt, struct strbuf *errmsg,
303 unsigned flags)
304 {
305 struct strbuf wt_path = STRBUF_INIT;
306 struct strbuf realpath = STRBUF_INIT;
307 char *path = NULL;
308 int err, ret = -1;
309
310 strbuf_addf(&wt_path, "%s/.git", wt->path);
311
312 if (is_main_worktree(wt)) {
313 if (is_directory(wt_path.buf)) {
314 ret = 0;
315 goto done;
316 }
317 /*
318 * Main worktree using .git file to point to the
319 * repository would make it impossible to know where
320 * the actual worktree is if this function is executed
321 * from another worktree. No .git file support for now.
322 */
323 strbuf_addf_gently(errmsg,
324 _("'%s' at main working tree is not the repository directory"),
325 wt_path.buf);
326 goto done;
327 }
328
329 /*
330 * Make sure "gitdir" file points to a real .git file and that
331 * file points back here.
332 */
333 if (!is_absolute_path(wt->path)) {
334 strbuf_addf_gently(errmsg,
335 _("'%s' file does not contain absolute path to the working tree location"),
336 git_common_path("worktrees/%s/gitdir", wt->id));
337 goto done;
338 }
339
340 if (flags & WT_VALIDATE_WORKTREE_MISSING_OK &&
341 !file_exists(wt->path)) {
342 ret = 0;
343 goto done;
344 }
345
346 if (!file_exists(wt_path.buf)) {
347 strbuf_addf_gently(errmsg, _("'%s' does not exist"), wt_path.buf);
348 goto done;
349 }
350
351 path = xstrdup_or_null(read_gitfile_gently(wt_path.buf, &err));
352 if (!path) {
353 strbuf_addf_gently(errmsg, _("'%s' is not a .git file, error code %d"),
354 wt_path.buf, err);
355 goto done;
356 }
357
358 strbuf_realpath(&realpath, git_common_path("worktrees/%s", wt->id), 1);
359 ret = fspathcmp(path, realpath.buf);
360
361 if (ret)
362 strbuf_addf_gently(errmsg, _("'%s' does not point back to '%s'"),
363 wt->path, git_common_path("worktrees/%s", wt->id));
364 done:
365 free(path);
366 strbuf_release(&wt_path);
367 strbuf_release(&realpath);
368 return ret;
369 }
370
371 void update_worktree_location(struct worktree *wt, const char *path_)
372 {
373 struct strbuf path = STRBUF_INIT;
374
375 if (is_main_worktree(wt))
376 BUG("can't relocate main worktree");
377
378 strbuf_realpath(&path, path_, 1);
379 if (fspathcmp(wt->path, path.buf)) {
380 write_file(git_common_path("worktrees/%s/gitdir", wt->id),
381 "%s/.git", path.buf);
382 free(wt->path);
383 wt->path = strbuf_detach(&path, NULL);
384 }
385 strbuf_release(&path);
386 }
387
388 int is_worktree_being_rebased(const struct worktree *wt,
389 const char *target)
390 {
391 struct wt_status_state state;
392 int found_rebase;
393
394 memset(&state, 0, sizeof(state));
395 found_rebase = wt_status_check_rebase(wt, &state) &&
396 (state.rebase_in_progress ||
397 state.rebase_interactive_in_progress) &&
398 state.branch &&
399 skip_prefix(target, "refs/heads/", &target) &&
400 !strcmp(state.branch, target);
401 wt_status_state_free_buffers(&state);
402 return found_rebase;
403 }
404
405 int is_worktree_being_bisected(const struct worktree *wt,
406 const char *target)
407 {
408 struct wt_status_state state;
409 int found_bisect;
410
411 memset(&state, 0, sizeof(state));
412 found_bisect = wt_status_check_bisect(wt, &state) &&
413 state.bisecting_from &&
414 skip_prefix(target, "refs/heads/", &target) &&
415 !strcmp(state.bisecting_from, target);
416 wt_status_state_free_buffers(&state);
417 return found_bisect;
418 }
419
420 /*
421 * note: this function should be able to detect shared symref even if
422 * HEAD is temporarily detached (e.g. in the middle of rebase or
423 * bisect). New commands that do similar things should update this
424 * function as well.
425 */
426 int is_shared_symref(const struct worktree *wt, const char *symref,
427 const char *target)
428 {
429 const char *symref_target;
430 struct ref_store *refs;
431 int flags;
432
433 if (wt->is_bare)
434 return 0;
435
436 if (wt->is_detached && !strcmp(symref, "HEAD")) {
437 if (is_worktree_being_rebased(wt, target))
438 return 1;
439 if (is_worktree_being_bisected(wt, target))
440 return 1;
441 }
442
443 refs = get_worktree_ref_store(wt);
444 symref_target = refs_resolve_ref_unsafe(refs, symref, 0,
445 NULL, &flags);
446 if ((flags & REF_ISSYMREF) &&
447 symref_target && !strcmp(symref_target, target))
448 return 1;
449
450 return 0;
451 }
452
453 const struct worktree *find_shared_symref(struct worktree **worktrees,
454 const char *symref,
455 const char *target)
456 {
457
458 for (int i = 0; worktrees[i]; i++)
459 if (is_shared_symref(worktrees[i], symref, target))
460 return worktrees[i];
461
462 return NULL;
463 }
464
465 int submodule_uses_worktrees(const char *path)
466 {
467 char *submodule_gitdir;
468 struct strbuf sb = STRBUF_INIT, err = STRBUF_INIT;
469 DIR *dir;
470 struct dirent *d;
471 int ret = 0;
472 struct repository_format format = REPOSITORY_FORMAT_INIT;
473
474 submodule_gitdir = git_pathdup_submodule(path, "%s", "");
475 if (!submodule_gitdir)
476 return 0;
477
478 /* The env would be set for the superproject. */
479 get_common_dir_noenv(&sb, submodule_gitdir);
480 free(submodule_gitdir);
481
482 strbuf_addstr(&sb, "/config");
483 read_repository_format(&format, sb.buf);
484 if (verify_repository_format(&format, &err)) {
485 strbuf_release(&err);
486 strbuf_release(&sb);
487 clear_repository_format(&format);
488 return 1;
489 }
490 clear_repository_format(&format);
491 strbuf_release(&err);
492
493 /* Replace config by worktrees. */
494 strbuf_setlen(&sb, sb.len - strlen("config"));
495 strbuf_addstr(&sb, "worktrees");
496
497 /* See if there is any file inside the worktrees directory. */
498 dir = opendir(sb.buf);
499 strbuf_release(&sb);
500
501 if (!dir)
502 return 0;
503
504 d = readdir_skip_dot_and_dotdot(dir);
505 if (d)
506 ret = 1;
507 closedir(dir);
508 return ret;
509 }
510
511 void strbuf_worktree_ref(const struct worktree *wt,
512 struct strbuf *sb,
513 const char *refname)
514 {
515 if (parse_worktree_ref(refname, NULL, NULL, NULL) ==
516 REF_WORKTREE_CURRENT &&
517 wt && !wt->is_current) {
518 if (is_main_worktree(wt))
519 strbuf_addstr(sb, "main-worktree/");
520 else
521 strbuf_addf(sb, "worktrees/%s/", wt->id);
522 }
523 strbuf_addstr(sb, refname);
524 }
525
526 int other_head_refs(each_ref_fn fn, void *cb_data)
527 {
528 struct worktree **worktrees, **p;
529 struct strbuf refname = STRBUF_INIT;
530 int ret = 0;
531
532 worktrees = get_worktrees();
533 for (p = worktrees; *p; p++) {
534 struct worktree *wt = *p;
535 struct object_id oid;
536 int flag;
537
538 if (wt->is_current)
539 continue;
540
541 strbuf_reset(&refname);
542 strbuf_worktree_ref(wt, &refname, "HEAD");
543 if (refs_resolve_ref_unsafe(get_main_ref_store(the_repository),
544 refname.buf,
545 RESOLVE_REF_READING,
546 &oid, &flag))
547 ret = fn(refname.buf, &oid, flag, cb_data);
548 if (ret)
549 break;
550 }
551 free_worktrees(worktrees);
552 strbuf_release(&refname);
553 return ret;
554 }
555
556 /*
557 * Repair worktree's /path/to/worktree/.git file if missing, corrupt, or not
558 * pointing at <repo>/worktrees/<id>.
559 */
560 static void repair_gitfile(struct worktree *wt,
561 worktree_repair_fn fn, void *cb_data)
562 {
563 struct strbuf dotgit = STRBUF_INIT;
564 struct strbuf repo = STRBUF_INIT;
565 char *backlink;
566 const char *repair = NULL;
567 int err;
568
569 /* missing worktree can't be repaired */
570 if (!file_exists(wt->path))
571 return;
572
573 if (!is_directory(wt->path)) {
574 fn(1, wt->path, _("not a directory"), cb_data);
575 return;
576 }
577
578 strbuf_realpath(&repo, git_common_path("worktrees/%s", wt->id), 1);
579 strbuf_addf(&dotgit, "%s/.git", wt->path);
580 backlink = xstrdup_or_null(read_gitfile_gently(dotgit.buf, &err));
581
582 if (err == READ_GITFILE_ERR_NOT_A_FILE)
583 fn(1, wt->path, _(".git is not a file"), cb_data);
584 else if (err)
585 repair = _(".git file broken");
586 else if (fspathcmp(backlink, repo.buf))
587 repair = _(".git file incorrect");
588
589 if (repair) {
590 fn(0, wt->path, repair, cb_data);
591 write_file(dotgit.buf, "gitdir: %s", repo.buf);
592 }
593
594 free(backlink);
595 strbuf_release(&repo);
596 strbuf_release(&dotgit);
597 }
598
599 static void repair_noop(int iserr UNUSED,
600 const char *path UNUSED,
601 const char *msg UNUSED,
602 void *cb_data UNUSED)
603 {
604 /* nothing */
605 }
606
607 void repair_worktrees(worktree_repair_fn fn, void *cb_data)
608 {
609 struct worktree **worktrees = get_worktrees_internal(1);
610 struct worktree **wt = worktrees + 1; /* +1 skips main worktree */
611
612 if (!fn)
613 fn = repair_noop;
614 for (; *wt; wt++)
615 repair_gitfile(*wt, fn, cb_data);
616 free_worktrees(worktrees);
617 }
618
619 static int is_main_worktree_path(const char *path)
620 {
621 struct strbuf target = STRBUF_INIT;
622 struct strbuf maindir = STRBUF_INIT;
623 int cmp;
624
625 strbuf_add_real_path(&target, path);
626 strbuf_strip_suffix(&target, "/.git");
627 strbuf_add_real_path(&maindir, get_git_common_dir());
628 strbuf_strip_suffix(&maindir, "/.git");
629 cmp = fspathcmp(maindir.buf, target.buf);
630
631 strbuf_release(&maindir);
632 strbuf_release(&target);
633 return !cmp;
634 }
635
636 /*
637 * If both the main worktree and linked worktree have been moved, then the
638 * gitfile /path/to/worktree/.git won't point into the repository, thus we
639 * won't know which <repo>/worktrees/<id>/gitdir to repair. However, we may
640 * be able to infer the gitdir by manually reading /path/to/worktree/.git,
641 * extracting the <id>, and checking if <repo>/worktrees/<id> exists.
642 */
643 static char *infer_backlink(const char *gitfile)
644 {
645 struct strbuf actual = STRBUF_INIT;
646 struct strbuf inferred = STRBUF_INIT;
647 const char *id;
648
649 if (strbuf_read_file(&actual, gitfile, 0) < 0)
650 goto error;
651 if (!starts_with(actual.buf, "gitdir:"))
652 goto error;
653 if (!(id = find_last_dir_sep(actual.buf)))
654 goto error;
655 strbuf_trim(&actual);
656 id++; /* advance past '/' to point at <id> */
657 if (!*id)
658 goto error;
659 strbuf_git_common_path(&inferred, the_repository, "worktrees/%s", id);
660 if (!is_directory(inferred.buf))
661 goto error;
662
663 strbuf_release(&actual);
664 return strbuf_detach(&inferred, NULL);
665
666 error:
667 strbuf_release(&actual);
668 strbuf_release(&inferred);
669 return NULL;
670 }
671
672 /*
673 * Repair <repo>/worktrees/<id>/gitdir if missing, corrupt, or not pointing at
674 * the worktree's path.
675 */
676 void repair_worktree_at_path(const char *path,
677 worktree_repair_fn fn, void *cb_data)
678 {
679 struct strbuf dotgit = STRBUF_INIT;
680 struct strbuf realdotgit = STRBUF_INIT;
681 struct strbuf gitdir = STRBUF_INIT;
682 struct strbuf olddotgit = STRBUF_INIT;
683 char *backlink = NULL;
684 const char *repair = NULL;
685 int err;
686
687 if (!fn)
688 fn = repair_noop;
689
690 if (is_main_worktree_path(path))
691 goto done;
692
693 strbuf_addf(&dotgit, "%s/.git", path);
694 if (!strbuf_realpath(&realdotgit, dotgit.buf, 0)) {
695 fn(1, path, _("not a valid path"), cb_data);
696 goto done;
697 }
698
699 backlink = xstrdup_or_null(read_gitfile_gently(realdotgit.buf, &err));
700 if (err == READ_GITFILE_ERR_NOT_A_FILE) {
701 fn(1, realdotgit.buf, _("unable to locate repository; .git is not a file"), cb_data);
702 goto done;
703 } else if (err == READ_GITFILE_ERR_NOT_A_REPO) {
704 if (!(backlink = infer_backlink(realdotgit.buf))) {
705 fn(1, realdotgit.buf, _("unable to locate repository; .git file does not reference a repository"), cb_data);
706 goto done;
707 }
708 } else if (err) {
709 fn(1, realdotgit.buf, _("unable to locate repository; .git file broken"), cb_data);
710 goto done;
711 }
712
713 strbuf_addf(&gitdir, "%s/gitdir", backlink);
714 if (strbuf_read_file(&olddotgit, gitdir.buf, 0) < 0)
715 repair = _("gitdir unreadable");
716 else {
717 strbuf_rtrim(&olddotgit);
718 if (fspathcmp(olddotgit.buf, realdotgit.buf))
719 repair = _("gitdir incorrect");
720 }
721
722 if (repair) {
723 fn(0, gitdir.buf, repair, cb_data);
724 write_file(gitdir.buf, "%s", realdotgit.buf);
725 }
726 done:
727 free(backlink);
728 strbuf_release(&olddotgit);
729 strbuf_release(&gitdir);
730 strbuf_release(&realdotgit);
731 strbuf_release(&dotgit);
732 }
733
734 int should_prune_worktree(const char *id, struct strbuf *reason, char **wtpath, timestamp_t expire)
735 {
736 struct stat st;
737 char *path;
738 int fd;
739 size_t len;
740 ssize_t read_result;
741
742 *wtpath = NULL;
743 if (!is_directory(git_path("worktrees/%s", id))) {
744 strbuf_addstr(reason, _("not a valid directory"));
745 return 1;
746 }
747 if (file_exists(git_path("worktrees/%s/locked", id)))
748 return 0;
749 if (stat(git_path("worktrees/%s/gitdir", id), &st)) {
750 strbuf_addstr(reason, _("gitdir file does not exist"));
751 return 1;
752 }
753 fd = open(git_path("worktrees/%s/gitdir", id), O_RDONLY);
754 if (fd < 0) {
755 strbuf_addf(reason, _("unable to read gitdir file (%s)"),
756 strerror(errno));
757 return 1;
758 }
759 len = xsize_t(st.st_size);
760 path = xmallocz(len);
761
762 read_result = read_in_full(fd, path, len);
763 if (read_result < 0) {
764 strbuf_addf(reason, _("unable to read gitdir file (%s)"),
765 strerror(errno));
766 close(fd);
767 free(path);
768 return 1;
769 }
770 close(fd);
771
772 if (read_result != len) {
773 strbuf_addf(reason,
774 _("short read (expected %"PRIuMAX" bytes, read %"PRIuMAX")"),
775 (uintmax_t)len, (uintmax_t)read_result);
776 free(path);
777 return 1;
778 }
779 while (len && (path[len - 1] == '\n' || path[len - 1] == '\r'))
780 len--;
781 if (!len) {
782 strbuf_addstr(reason, _("invalid gitdir file"));
783 free(path);
784 return 1;
785 }
786 path[len] = '\0';
787 if (!file_exists(path)) {
788 if (stat(git_path("worktrees/%s/index", id), &st) ||
789 st.st_mtime <= expire) {
790 strbuf_addstr(reason, _("gitdir file points to non-existent location"));
791 free(path);
792 return 1;
793 } else {
794 *wtpath = path;
795 return 0;
796 }
797 }
798 *wtpath = path;
799 return 0;
800 }
801
802 static int move_config_setting(const char *key, const char *value,
803 const char *from_file, const char *to_file)
804 {
805 if (git_config_set_in_file_gently(to_file, key, value))
806 return error(_("unable to set %s in '%s'"), key, to_file);
807 if (git_config_set_in_file_gently(from_file, key, NULL))
808 return error(_("unable to unset %s in '%s'"), key, from_file);
809 return 0;
810 }
811
812 int init_worktree_config(struct repository *r)
813 {
814 int res = 0;
815 int bare = 0;
816 struct config_set cs = { { 0 } };
817 const char *core_worktree;
818 char *common_config_file;
819 char *main_worktree_file;
820
821 /*
822 * If the extension is already enabled, then we can skip the
823 * upgrade process.
824 */
825 if (r->repository_format_worktree_config)
826 return 0;
827 if ((res = git_config_set_gently("extensions.worktreeConfig", "true")))
828 return error(_("failed to set extensions.worktreeConfig setting"));
829
830 common_config_file = xstrfmt("%s/config", r->commondir);
831 main_worktree_file = xstrfmt("%s/config.worktree", r->commondir);
832
833 git_configset_init(&cs);
834 git_configset_add_file(&cs, common_config_file);
835
836 /*
837 * If core.bare is true in the common config file, then we need to
838 * move it to the main worktree's config file or it will break all
839 * worktrees. If it is false, then leave it in place because it
840 * _could_ be negating a global core.bare=true.
841 */
842 if (!git_configset_get_bool(&cs, "core.bare", &bare) && bare) {
843 if ((res = move_config_setting("core.bare", "true",
844 common_config_file,
845 main_worktree_file)))
846 goto cleanup;
847 }
848 /*
849 * If core.worktree is set, then the main worktree is located
850 * somewhere different than the parent of the common Git dir.
851 * Relocate that value to avoid breaking all worktrees with this
852 * upgrade to worktree config.
853 */
854 if (!git_configset_get_value(&cs, "core.worktree", &core_worktree, NULL)) {
855 if ((res = move_config_setting("core.worktree", core_worktree,
856 common_config_file,
857 main_worktree_file)))
858 goto cleanup;
859 }
860
861 /*
862 * Ensure that we use worktree config for the remaining lifetime
863 * of the current process.
864 */
865 r->repository_format_worktree_config = 1;
866
867 cleanup:
868 git_configset_clear(&cs);
869 free(common_config_file);
870 free(main_worktree_file);
871 return res;
872 }