worktree: expose interface to look up worktree by name

Our worktree interfaces do not provide a way to look up a worktree by its name. Expose `get_linked_worktree()` to allow for this usecase. As callers are responsible for freeing this worktree, introduce a new function `free_worktree()` that does so. Signed-off-by: Patrick Steinhardt <ps@pks.im> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Patrick Steinhardt committed Jan 8, 2024 at 11:05 UTC b8a846b2e03610e6f550d364c75e514532ef7adf
2 files changed +28 -11
worktree.c
+16 -11
@@ -12,18 +12,23 @@
12 #include "wt-status.h"
13 #include "config.h"
14
15 +void free_worktree(struct worktree *worktree)
16 +{
17 + if (!worktree)
18 + return;
19 + free(worktree->path);
20 + free(worktree->id);
21 + free(worktree->head_ref);
22 + free(worktree->lock_reason);
23 + free(worktree->prune_reason);
24 + free(worktree);
25 +}
26 +
27 void free_worktrees(struct worktree **worktrees)
28 {
29 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 - }
30 + for (i = 0; worktrees[i]; i++)
31 + free_worktree(worktrees[i]);
32 free (worktrees);
33 }
34
@@ -75,8 +80,8 @@ static struct worktree *get_main_worktree(int skip_reading_head)
80 return worktree;
81 }
82
78 -static struct worktree *get_linked_worktree(const char *id,
79 - int skip_reading_head)
83 +struct worktree *get_linked_worktree(const char *id,
84 + int skip_reading_head)
85 {
86 struct worktree *worktree = NULL;
87 struct strbuf path = STRBUF_INIT;
worktree.h
+12
@@ -57,6 +57,13 @@ struct worktree *find_worktree(struct worktree **list,
57 const char *prefix,
58 const char *arg);
59
60 +/*
61 + * Look up the worktree corresponding to `id`, or NULL of no such worktree
62 + * exists.
63 + */
64 +struct worktree *get_linked_worktree(const char *id,
65 + int skip_reading_head);
66 +
67 /*
68 * Return the worktree corresponding to `path`, or NULL if no such worktree
69 * exists.
@@ -134,6 +141,11 @@ void repair_worktrees(worktree_repair_fn, void *cb_data);
141 */
142 void repair_worktree_at_path(const char *, worktree_repair_fn, void *cb_data);
143
144 +/*
145 + * Free up the memory for a worktree.
146 + */
147 +void free_worktree(struct worktree *);
148 +
149 /*
150 * Free up the memory for worktree(s)
151 */