worktree.c: add is_worktree_locked()

We need this later to avoid double locking a worktree, or unlocking one when it's not even locked. Signed-off-by: Nguyễn Thái Ngọc Duy <pclouds@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Nguyễn Thái Ngọc Duy committed Jun 13, 2016 at 19:18 UTC 346ef53058ef25f5a7273ee77c03ebc5f732ad77
2 files changed +36
worktree.c
+28
@@ -13,6 +13,7 @@ void free_worktrees(struct worktree **worktrees)
13 free(worktrees[i]->path);
14 free(worktrees[i]->id);
15 free(worktrees[i]->head_ref);
16 + free(worktrees[i]->lock_reason);
17 free(worktrees[i]);
18 }
19 free (worktrees);
@@ -98,6 +99,8 @@ static struct worktree *get_main_worktree(void)
99 worktree->is_detached = is_detached;
100 worktree->is_current = 0;
101 add_head_info(&head_ref, worktree);
102 + worktree->lock_reason = NULL;
103 + worktree->lock_reason_valid = 0;
104
105 done:
106 strbuf_release(&path);
@@ -143,6 +146,8 @@ static struct worktree *get_linked_worktree(const char *id)
146 worktree->is_detached = is_detached;
147 worktree->is_current = 0;
148 add_head_info(&head_ref, worktree);
149 + worktree->lock_reason = NULL;
150 + worktree->lock_reason_valid = 0;
151
152 done:
153 strbuf_release(&path);
@@ -234,6 +239,29 @@ int is_main_worktree(const struct worktree *wt)
239 return !wt->id;
240 }
241
242 +const char *is_worktree_locked(struct worktree *wt)
243 +{
244 + assert(!is_main_worktree(wt));
245 +
246 + if (!wt->lock_reason_valid) {
247 + struct strbuf path = STRBUF_INIT;
248 +
249 + strbuf_addstr(&path, worktree_git_path(wt, "locked"));
250 + if (file_exists(path.buf)) {
251 + struct strbuf lock_reason = STRBUF_INIT;
252 + if (strbuf_read_file(&lock_reason, path.buf, 0) < 0)
253 + die_errno(_("failed to read '%s'"), path.buf);
254 + strbuf_trim(&lock_reason);
255 + wt->lock_reason = strbuf_detach(&lock_reason, NULL);
256 + } else
257 + wt->lock_reason = NULL;
258 + wt->lock_reason_valid = 1;
259 + strbuf_release(&path);
260 + }
261 +
262 + return wt->lock_reason;
263 +}
264 +
265 int is_worktree_being_rebased(const struct worktree *wt,
266 const char *target)
267 {
worktree.h
+8
@@ -5,10 +5,12 @@ struct worktree {
5 char *path;
6 char *id;
7 char *head_ref;
8 + char *lock_reason; /* internal use */
9 unsigned char head_sha1[20];
10 int is_detached;
11 int is_bare;
12 int is_current;
13 + int lock_reason_valid;
14 };
15
16 /* Functions for acting on the information about worktrees. */
@@ -42,6 +44,12 @@ extern struct worktree *find_worktree(struct worktree **list,
44 */
45 extern int is_main_worktree(const struct worktree *wt);
46
47 +/*
48 + * Return the reason string if the given worktree is locked or NULL
49 + * otherwise.
50 + */
51 +extern const char *is_worktree_locked(struct worktree *wt);
52 +
53 /*
54 * Free up the memory for worktree(s)
55 */