Skip to content

Commit 698eae1

Browse files
committed
worktree: error out early if given ref is not valid
When adding a new worktree, we only verify that an optionally given reference is valid half-way through the function. At this point, some data structures have already been created on-disk. If we bail out due to an invalid reference, these will be left behind and need to be manually cleaned up by the user. Improve the situation by moving the reference checks to the function's preamble. Like this, we error out as early as possible and will not leave behind any files.
1 parent e191637 commit 698eae1

File tree

1 file changed

+14
-12
lines changed

1 file changed

+14
-12
lines changed

src/worktree.c

Lines changed: 14 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -290,6 +290,20 @@ int git_worktree_add(git_worktree **out, git_repository *repo,
290290

291291
*out = NULL;
292292

293+
if (wtopts.ref) {
294+
if (!git_reference_is_branch(wtopts.ref)) {
295+
git_error_set(GIT_ERROR_WORKTREE, "reference is not a branch");
296+
err = -1;
297+
goto out;
298+
}
299+
300+
if (git_branch_is_checked_out(wtopts.ref)) {
301+
git_error_set(GIT_ERROR_WORKTREE, "reference is already checked out");
302+
err = -1;
303+
goto out;
304+
}
305+
}
306+
293307
/* Create gitdir directory ".git/worktrees/<name>" */
294308
if ((err = git_buf_joinpath(&gitdir, repo->commondir, "worktrees")) < 0)
295309
goto out;
@@ -342,18 +356,6 @@ int git_worktree_add(git_worktree **out, git_repository *repo,
342356

343357
/* Set up worktree reference */
344358
if (wtopts.ref) {
345-
if (!git_reference_is_branch(wtopts.ref)) {
346-
git_error_set(GIT_ERROR_WORKTREE, "reference is not a branch");
347-
err = -1;
348-
goto out;
349-
}
350-
351-
if (git_branch_is_checked_out(wtopts.ref)) {
352-
git_error_set(GIT_ERROR_WORKTREE, "reference is already checked out");
353-
err = -1;
354-
goto out;
355-
}
356-
357359
if ((err = git_reference_dup(&ref, wtopts.ref)) < 0)
358360
goto out;
359361
} else {

0 commit comments

Comments
 (0)