summaryrefslogtreecommitdiff
path: root/src/worktree.c
diff options
context:
space:
mode:
authorPatrick Steinhardt <ps@pks.im>2018-02-09 10:38:11 +0000
committerPatrick Steinhardt <ps@pks.im>2018-02-09 10:40:59 +0000
commita22f19e6c4c0bf5205cd47dd66bfacd5c7d18136 (patch)
treefccaf92a98bd4a776f542c48326afbd17a35c4a5 /src/worktree.c
parentf7225946edeae35f48e3d402e2e0c94ea07f9666 (diff)
downloadlibgit2-a22f19e6c4c0bf5205cd47dd66bfacd5c7d18136.tar.gz
worktree: add ability to create worktree with pre-existing branch
Currently, we always create a new branch after the new worktree's name when creating a worktree. In some workflows, though, the caller may want to check out an already existing reference instead of creating a new one, which is impossible to do right now. Add a new option `ref` to the options structure for adding worktrees. In case it is set, a branch and not already checked out by another worktree, we will re-use this reference instead of creating a new one.
Diffstat (limited to 'src/worktree.c')
-rw-r--r--src/worktree.c31
1 files changed, 24 insertions, 7 deletions
diff --git a/src/worktree.c b/src/worktree.c
index 5a814a2ec..59f462d10 100644
--- a/src/worktree.c
+++ b/src/worktree.c
@@ -348,13 +348,30 @@ int git_worktree_add(git_worktree **out, git_repository *repo,
|| (err = write_wtfile(gitdir.ptr, "gitdir", &buf)) < 0)
goto out;
- /* Create new branch */
- if ((err = git_repository_head(&head, repo)) < 0)
- goto out;
- if ((err = git_commit_lookup(&commit, repo, &head->target.oid)) < 0)
- goto out;
- if ((err = git_branch_create(&ref, repo, name, commit, false)) < 0)
- goto out;
+ /* Set up worktree reference */
+ if (wtopts.ref) {
+ if (!git_reference_is_branch(wtopts.ref)) {
+ giterr_set(GITERR_WORKTREE, "reference is not a branch");
+ err = -1;
+ goto out;
+ }
+
+ if (git_branch_is_checked_out(wtopts.ref)) {
+ giterr_set(GITERR_WORKTREE, "reference is already checked out");
+ err = -1;
+ goto out;
+ }
+
+ if ((err = git_reference_dup(&ref, wtopts.ref)) < 0)
+ goto out;
+ } else {
+ if ((err = git_repository_head(&head, repo)) < 0)
+ goto out;
+ if ((err = git_commit_lookup(&commit, repo, &head->target.oid)) < 0)
+ goto out;
+ if ((err = git_branch_create(&ref, repo, name, commit, false)) < 0)
+ goto out;
+ }
/* Set worktree's HEAD */
if ((err = git_repository_create_head(gitdir.ptr, git_reference_name(ref))) < 0)