worktree: add utility to find worktree by pathname
[git] / worktree.c
1 #include "cache.h"
2 #include "repository.h"
3 #include "refs.h"
4 #include "strbuf.h"
5 #include "worktree.h"
6 #include "dir.h"
7 #include "wt-status.h"
8
9 void free_worktrees(struct worktree **worktrees)
10 {
11         int i = 0;
12
13         for (i = 0; worktrees[i]; i++) {
14                 free(worktrees[i]->path);
15                 free(worktrees[i]->id);
16                 free(worktrees[i]->head_ref);
17                 free(worktrees[i]->lock_reason);
18                 free(worktrees[i]);
19         }
20         free (worktrees);
21 }
22
23 /**
24  * Update head_sha1, head_ref and is_detached of the given worktree
25  */
26 static void add_head_info(struct worktree *wt)
27 {
28         int flags;
29         const char *target;
30
31         target = refs_resolve_ref_unsafe(get_worktree_ref_store(wt),
32                                          "HEAD",
33                                          0,
34                                          &wt->head_oid, &flags);
35         if (!target)
36                 return;
37
38         if (flags & REF_ISSYMREF)
39                 wt->head_ref = xstrdup(target);
40         else
41                 wt->is_detached = 1;
42 }
43
44 /**
45  * get the main worktree
46  */
47 static struct worktree *get_main_worktree(void)
48 {
49         struct worktree *worktree = NULL;
50         struct strbuf path = STRBUF_INIT;
51         struct strbuf worktree_path = STRBUF_INIT;
52
53         strbuf_add_absolute_path(&worktree_path, get_git_common_dir());
54         if (!strbuf_strip_suffix(&worktree_path, "/.git"))
55                 strbuf_strip_suffix(&worktree_path, "/.");
56
57         strbuf_addf(&path, "%s/HEAD", get_git_common_dir());
58
59         worktree = xcalloc(1, sizeof(*worktree));
60         worktree->path = strbuf_detach(&worktree_path, NULL);
61         /*
62          * NEEDSWORK: If this function is called from a secondary worktree and
63          * config.worktree is present, is_bare_repository_cfg will reflect the
64          * contents of config.worktree, not the contents of the main worktree.
65          * This means that worktree->is_bare may be set to 0 even if the main
66          * worktree is configured to be bare.
67          */
68         worktree->is_bare = (is_bare_repository_cfg == 1) ||
69                 is_bare_repository();
70         add_head_info(worktree);
71
72         strbuf_release(&path);
73         strbuf_release(&worktree_path);
74         return worktree;
75 }
76
77 static struct worktree *get_linked_worktree(const char *id)
78 {
79         struct worktree *worktree = NULL;
80         struct strbuf path = STRBUF_INIT;
81         struct strbuf worktree_path = STRBUF_INIT;
82
83         if (!id)
84                 die("Missing linked worktree name");
85
86         strbuf_git_common_path(&path, the_repository, "worktrees/%s/gitdir", id);
87         if (strbuf_read_file(&worktree_path, path.buf, 0) <= 0)
88                 /* invalid gitdir file */
89                 goto done;
90
91         strbuf_rtrim(&worktree_path);
92         if (!strbuf_strip_suffix(&worktree_path, "/.git")) {
93                 strbuf_reset(&worktree_path);
94                 strbuf_add_absolute_path(&worktree_path, ".");
95                 strbuf_strip_suffix(&worktree_path, "/.");
96         }
97
98         strbuf_reset(&path);
99         strbuf_addf(&path, "%s/worktrees/%s/HEAD", get_git_common_dir(), id);
100
101         worktree = xcalloc(1, sizeof(*worktree));
102         worktree->path = strbuf_detach(&worktree_path, NULL);
103         worktree->id = xstrdup(id);
104         add_head_info(worktree);
105
106 done:
107         strbuf_release(&path);
108         strbuf_release(&worktree_path);
109         return worktree;
110 }
111
112 static void mark_current_worktree(struct worktree **worktrees)
113 {
114         char *git_dir = absolute_pathdup(get_git_dir());
115         int i;
116
117         for (i = 0; worktrees[i]; i++) {
118                 struct worktree *wt = worktrees[i];
119                 const char *wt_git_dir = get_worktree_git_dir(wt);
120
121                 if (!fspathcmp(git_dir, absolute_path(wt_git_dir))) {
122                         wt->is_current = 1;
123                         break;
124                 }
125         }
126         free(git_dir);
127 }
128
129 static int compare_worktree(const void *a_, const void *b_)
130 {
131         const struct worktree *const *a = a_;
132         const struct worktree *const *b = b_;
133         return fspathcmp((*a)->path, (*b)->path);
134 }
135
136 struct worktree **get_worktrees(unsigned flags)
137 {
138         struct worktree **list = NULL;
139         struct strbuf path = STRBUF_INIT;
140         DIR *dir;
141         struct dirent *d;
142         int counter = 0, alloc = 2;
143
144         ALLOC_ARRAY(list, alloc);
145
146         list[counter++] = get_main_worktree();
147
148         strbuf_addf(&path, "%s/worktrees", get_git_common_dir());
149         dir = opendir(path.buf);
150         strbuf_release(&path);
151         if (dir) {
152                 while ((d = readdir(dir)) != NULL) {
153                         struct worktree *linked = NULL;
154                         if (is_dot_or_dotdot(d->d_name))
155                                 continue;
156
157                         if ((linked = get_linked_worktree(d->d_name))) {
158                                 ALLOC_GROW(list, counter + 1, alloc);
159                                 list[counter++] = linked;
160                         }
161                 }
162                 closedir(dir);
163         }
164         ALLOC_GROW(list, counter + 1, alloc);
165         list[counter] = NULL;
166
167         if (flags & GWT_SORT_LINKED)
168                 /*
169                  * don't sort the first item (main worktree), which will
170                  * always be the first
171                  */
172                 QSORT(list + 1, counter - 1, compare_worktree);
173
174         mark_current_worktree(list);
175         return list;
176 }
177
178 const char *get_worktree_git_dir(const struct worktree *wt)
179 {
180         if (!wt)
181                 return get_git_dir();
182         else if (!wt->id)
183                 return get_git_common_dir();
184         else
185                 return git_common_path("worktrees/%s", wt->id);
186 }
187
188 static struct worktree *find_worktree_by_suffix(struct worktree **list,
189                                                 const char *suffix)
190 {
191         struct worktree *found = NULL;
192         int nr_found = 0, suffixlen;
193
194         suffixlen = strlen(suffix);
195         if (!suffixlen)
196                 return NULL;
197
198         for (; *list && nr_found < 2; list++) {
199                 const char      *path    = (*list)->path;
200                 int              pathlen = strlen(path);
201                 int              start   = pathlen - suffixlen;
202
203                 /* suffix must start at directory boundary */
204                 if ((!start || (start > 0 && is_dir_sep(path[start - 1]))) &&
205                     !fspathcmp(suffix, path + start)) {
206                         found = *list;
207                         nr_found++;
208                 }
209         }
210         return nr_found == 1 ? found : NULL;
211 }
212
213 struct worktree *find_worktree(struct worktree **list,
214                                const char *prefix,
215                                const char *arg)
216 {
217         struct worktree *wt;
218         char *to_free = NULL;
219
220         if ((wt = find_worktree_by_suffix(list, arg)))
221                 return wt;
222
223         if (prefix)
224                 arg = to_free = prefix_filename(prefix, arg);
225         wt = find_worktree_by_path(list, arg);
226         free(to_free);
227         return wt;
228 }
229
230 struct worktree *find_worktree_by_path(struct worktree **list, const char *p)
231 {
232         char *path = real_pathdup(p, 0);
233
234         if (!path)
235                 return NULL;
236         for (; *list; list++) {
237                 const char *wt_path = real_path_if_valid((*list)->path);
238
239                 if (wt_path && !fspathcmp(path, wt_path))
240                         break;
241         }
242         free(path);
243         return *list;
244 }
245
246 int is_main_worktree(const struct worktree *wt)
247 {
248         return !wt->id;
249 }
250
251 const char *worktree_lock_reason(struct worktree *wt)
252 {
253         assert(!is_main_worktree(wt));
254
255         if (!wt->lock_reason_valid) {
256                 struct strbuf path = STRBUF_INIT;
257
258                 strbuf_addstr(&path, worktree_git_path(wt, "locked"));
259                 if (file_exists(path.buf)) {
260                         struct strbuf lock_reason = STRBUF_INIT;
261                         if (strbuf_read_file(&lock_reason, path.buf, 0) < 0)
262                                 die_errno(_("failed to read '%s'"), path.buf);
263                         strbuf_trim(&lock_reason);
264                         wt->lock_reason = strbuf_detach(&lock_reason, NULL);
265                 } else
266                         wt->lock_reason = NULL;
267                 wt->lock_reason_valid = 1;
268                 strbuf_release(&path);
269         }
270
271         return wt->lock_reason;
272 }
273
274 /* convenient wrapper to deal with NULL strbuf */
275 static void strbuf_addf_gently(struct strbuf *buf, const char *fmt, ...)
276 {
277         va_list params;
278
279         if (!buf)
280                 return;
281
282         va_start(params, fmt);
283         strbuf_vaddf(buf, fmt, params);
284         va_end(params);
285 }
286
287 int validate_worktree(const struct worktree *wt, struct strbuf *errmsg,
288                       unsigned flags)
289 {
290         struct strbuf wt_path = STRBUF_INIT;
291         char *path = NULL;
292         int err, ret = -1;
293
294         strbuf_addf(&wt_path, "%s/.git", wt->path);
295
296         if (is_main_worktree(wt)) {
297                 if (is_directory(wt_path.buf)) {
298                         ret = 0;
299                         goto done;
300                 }
301                 /*
302                  * Main worktree using .git file to point to the
303                  * repository would make it impossible to know where
304                  * the actual worktree is if this function is executed
305                  * from another worktree. No .git file support for now.
306                  */
307                 strbuf_addf_gently(errmsg,
308                                    _("'%s' at main working tree is not the repository directory"),
309                                    wt_path.buf);
310                 goto done;
311         }
312
313         /*
314          * Make sure "gitdir" file points to a real .git file and that
315          * file points back here.
316          */
317         if (!is_absolute_path(wt->path)) {
318                 strbuf_addf_gently(errmsg,
319                                    _("'%s' file does not contain absolute path to the working tree location"),
320                                    git_common_path("worktrees/%s/gitdir", wt->id));
321                 goto done;
322         }
323
324         if (flags & WT_VALIDATE_WORKTREE_MISSING_OK &&
325             !file_exists(wt->path)) {
326                 ret = 0;
327                 goto done;
328         }
329
330         if (!file_exists(wt_path.buf)) {
331                 strbuf_addf_gently(errmsg, _("'%s' does not exist"), wt_path.buf);
332                 goto done;
333         }
334
335         path = xstrdup_or_null(read_gitfile_gently(wt_path.buf, &err));
336         if (!path) {
337                 strbuf_addf_gently(errmsg, _("'%s' is not a .git file, error code %d"),
338                                    wt_path.buf, err);
339                 goto done;
340         }
341
342         ret = fspathcmp(path, real_path(git_common_path("worktrees/%s", wt->id)));
343
344         if (ret)
345                 strbuf_addf_gently(errmsg, _("'%s' does not point back to '%s'"),
346                                    wt->path, git_common_path("worktrees/%s", wt->id));
347 done:
348         free(path);
349         strbuf_release(&wt_path);
350         return ret;
351 }
352
353 void update_worktree_location(struct worktree *wt, const char *path_)
354 {
355         struct strbuf path = STRBUF_INIT;
356
357         if (is_main_worktree(wt))
358                 BUG("can't relocate main worktree");
359
360         strbuf_realpath(&path, path_, 1);
361         if (fspathcmp(wt->path, path.buf)) {
362                 write_file(git_common_path("worktrees/%s/gitdir", wt->id),
363                            "%s/.git", path.buf);
364                 free(wt->path);
365                 wt->path = strbuf_detach(&path, NULL);
366         }
367         strbuf_release(&path);
368 }
369
370 int is_worktree_being_rebased(const struct worktree *wt,
371                               const char *target)
372 {
373         struct wt_status_state state;
374         int found_rebase;
375
376         memset(&state, 0, sizeof(state));
377         found_rebase = wt_status_check_rebase(wt, &state) &&
378                 ((state.rebase_in_progress ||
379                   state.rebase_interactive_in_progress) &&
380                  state.branch &&
381                  starts_with(target, "refs/heads/") &&
382                  !strcmp(state.branch, target + strlen("refs/heads/")));
383         free(state.branch);
384         free(state.onto);
385         return found_rebase;
386 }
387
388 int is_worktree_being_bisected(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_bisect(wt, &state) &&
396                 state.branch &&
397                 starts_with(target, "refs/heads/") &&
398                 !strcmp(state.branch, target + strlen("refs/heads/"));
399         free(state.branch);
400         return found_rebase;
401 }
402
403 /*
404  * note: this function should be able to detect shared symref even if
405  * HEAD is temporarily detached (e.g. in the middle of rebase or
406  * bisect). New commands that do similar things should update this
407  * function as well.
408  */
409 const struct worktree *find_shared_symref(const char *symref,
410                                           const char *target)
411 {
412         const struct worktree *existing = NULL;
413         static struct worktree **worktrees;
414         int i = 0;
415
416         if (worktrees)
417                 free_worktrees(worktrees);
418         worktrees = get_worktrees(0);
419
420         for (i = 0; worktrees[i]; i++) {
421                 struct worktree *wt = worktrees[i];
422                 const char *symref_target;
423                 struct ref_store *refs;
424                 int flags;
425
426                 if (wt->is_bare)
427                         continue;
428
429                 if (wt->is_detached && !strcmp(symref, "HEAD")) {
430                         if (is_worktree_being_rebased(wt, target)) {
431                                 existing = wt;
432                                 break;
433                         }
434                         if (is_worktree_being_bisected(wt, target)) {
435                                 existing = wt;
436                                 break;
437                         }
438                 }
439
440                 refs = get_worktree_ref_store(wt);
441                 symref_target = refs_resolve_ref_unsafe(refs, symref, 0,
442                                                         NULL, &flags);
443                 if ((flags & REF_ISSYMREF) &&
444                     symref_target && !strcmp(symref_target, target)) {
445                         existing = wt;
446                         break;
447                 }
448         }
449
450         return existing;
451 }
452
453 int submodule_uses_worktrees(const char *path)
454 {
455         char *submodule_gitdir;
456         struct strbuf sb = STRBUF_INIT;
457         DIR *dir;
458         struct dirent *d;
459         int ret = 0;
460         struct repository_format format = REPOSITORY_FORMAT_INIT;
461
462         submodule_gitdir = git_pathdup_submodule(path, "%s", "");
463         if (!submodule_gitdir)
464                 return 0;
465
466         /* The env would be set for the superproject. */
467         get_common_dir_noenv(&sb, submodule_gitdir);
468         free(submodule_gitdir);
469
470         /*
471          * The check below is only known to be good for repository format
472          * version 0 at the time of writing this code.
473          */
474         strbuf_addstr(&sb, "/config");
475         read_repository_format(&format, sb.buf);
476         if (format.version != 0) {
477                 strbuf_release(&sb);
478                 clear_repository_format(&format);
479                 return 1;
480         }
481         clear_repository_format(&format);
482
483         /* Replace config by worktrees. */
484         strbuf_setlen(&sb, sb.len - strlen("config"));
485         strbuf_addstr(&sb, "worktrees");
486
487         /* See if there is any file inside the worktrees directory. */
488         dir = opendir(sb.buf);
489         strbuf_release(&sb);
490
491         if (!dir)
492                 return 0;
493
494         while ((d = readdir(dir)) != NULL) {
495                 if (is_dot_or_dotdot(d->d_name))
496                         continue;
497
498                 ret = 1;
499                 break;
500         }
501         closedir(dir);
502         return ret;
503 }
504
505 int parse_worktree_ref(const char *worktree_ref, const char **name,
506                        int *name_length, const char **ref)
507 {
508         if (skip_prefix(worktree_ref, "main-worktree/", &worktree_ref)) {
509                 if (!*worktree_ref)
510                         return -1;
511                 if (name)
512                         *name = NULL;
513                 if (name_length)
514                         *name_length = 0;
515                 if (ref)
516                         *ref = worktree_ref;
517                 return 0;
518         }
519         if (skip_prefix(worktree_ref, "worktrees/", &worktree_ref)) {
520                 const char *slash = strchr(worktree_ref, '/');
521
522                 if (!slash || slash == worktree_ref || !slash[1])
523                         return -1;
524                 if (name)
525                         *name = worktree_ref;
526                 if (name_length)
527                         *name_length = slash - worktree_ref;
528                 if (ref)
529                         *ref = slash + 1;
530                 return 0;
531         }
532         return -1;
533 }
534
535 void strbuf_worktree_ref(const struct worktree *wt,
536                          struct strbuf *sb,
537                          const char *refname)
538 {
539         switch (ref_type(refname)) {
540         case REF_TYPE_PSEUDOREF:
541         case REF_TYPE_PER_WORKTREE:
542                 if (wt && !wt->is_current) {
543                         if (is_main_worktree(wt))
544                                 strbuf_addstr(sb, "main-worktree/");
545                         else
546                                 strbuf_addf(sb, "worktrees/%s/", wt->id);
547                 }
548                 break;
549
550         case REF_TYPE_MAIN_PSEUDOREF:
551         case REF_TYPE_OTHER_PSEUDOREF:
552                 break;
553
554         case REF_TYPE_NORMAL:
555                 /*
556                  * For shared refs, don't prefix worktrees/ or
557                  * main-worktree/. It's not necessary and
558                  * files-backend.c can't handle it anyway.
559                  */
560                 break;
561         }
562         strbuf_addstr(sb, refname);
563 }
564
565 const char *worktree_ref(const struct worktree *wt, const char *refname)
566 {
567         static struct strbuf sb = STRBUF_INIT;
568
569         strbuf_reset(&sb);
570         strbuf_worktree_ref(wt, &sb, refname);
571         return sb.buf;
572 }
573
574 int other_head_refs(each_ref_fn fn, void *cb_data)
575 {
576         struct worktree **worktrees, **p;
577         int ret = 0;
578
579         worktrees = get_worktrees(0);
580         for (p = worktrees; *p; p++) {
581                 struct worktree *wt = *p;
582                 struct object_id oid;
583                 int flag;
584
585                 if (wt->is_current)
586                         continue;
587
588                 if (!refs_read_ref_full(get_main_ref_store(the_repository),
589                                         worktree_ref(wt, "HEAD"),
590                                         RESOLVE_REF_READING,
591                                         &oid, &flag))
592                         ret = fn(worktree_ref(wt, "HEAD"), &oid, flag, cb_data);
593                 if (ret)
594                         break;
595         }
596         free_worktrees(worktrees);
597         return ret;
598 }