commit 45cd4e47a6fe68f4dbd45961973ed61e766bfbca from: Stefan Sperling date: Sun Aug 25 11:30:38 2019 UTC detect and prevent deletion of the work tree's current branch commit - f2db9c479fbdf8dfb2f58619e6e62781117a14b8 commit + 45cd4e47a6fe68f4dbd45961973ed61e766bfbca blob - 77942a84ae2f6687f4c1b016ab97b7fcc7578feb blob + 7daf89ca750b37c1fa8b20970c7cf973af3347d7 --- got/got.c +++ got/got.c @@ -3104,10 +3104,11 @@ list_branches(struct got_repository *repo, struct got_ } static const struct got_error * -delete_branch(struct got_repository *repo, const char *branch_name) +delete_branch(struct got_repository *repo, struct got_worktree *worktree, + const char *branch_name) { const struct got_error *err = NULL; - struct got_reference *ref; + struct got_reference *ref = NULL; char *refname; if (asprintf(&refname, "refs/heads/%s", branch_name) == -1) @@ -3117,9 +3118,18 @@ delete_branch(struct got_repository *repo, const char if (err) goto done; - err = got_ref_delete(ref, repo); - got_ref_close(ref); + if (worktree && + strcmp(got_worktree_get_head_ref_name(worktree), + got_ref_get_name(ref)) == 0) { + err = got_error_msg(GOT_ERR_SAME_BRANCH, + "will not delete this work tree's current branch"); + goto done; + } + + err = got_ref_delete(ref, repo); done: + if (ref) + got_ref_close(ref); free(refname); return err; } @@ -3276,7 +3286,7 @@ cmd_branch(int argc, char *argv[]) if (do_list) error = list_branches(repo, worktree); else if (delref) - error = delete_branch(repo, delref); + error = delete_branch(repo, worktree, delref); else { const char *base_branch; if (argc == 1) { blob - e624d53380913d538422ddc4c6503cb48bdf3b02 blob + a2f5c358ddb24b6a373b03188398b95b8b3d8b8c --- regress/cmdline/branch.sh +++ regress/cmdline/branch.sh @@ -249,7 +249,32 @@ function test_branch_delete { test_done "$testroot" "$ret" } +function test_branch_delete_current_branch { + local testroot=`test_init branch_delete_current_branch` + local commit_id=`git_show_head $testroot/repo` + + got checkout $testroot/repo $testroot/wt >/dev/null + ret="$?" + if [ "$ret" != "0" ]; then + echo "got checkout command failed unexpectedly" + test_done "$testroot" "$ret" + return 1 + fi + (cd $testroot/wt && got branch -d master > $testroot/stdout \ + 2> $testroot/stderr) + + echo "got: will not delete this work tree's current branch" \ + > $testroot/stderr.expected + cmp -s $testroot/stderr $testroot/stderr.expected + ret="$?" + if [ "$ret" != "0" ]; then + diff -u $testroot/stderr.expected $testroot/stderr + fi + test_done "$testroot" "$ret" +} + run_test test_branch_create run_test test_branch_list run_test test_branch_delete +run_test test_branch_delete_current_branch