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