Coverage Report

Created: 2025-12-31 07:01

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