worktree: add: auto-vivify new branch when <branch> is omitted As a convenience, when <branch> is omitted from "git worktree <path> <branch>" and neither -b nor -B is used, automatically create a new branch named after <path>, as if "-b $(basename <path>)" was specified. Thus, "git worktree add ../hotfix" creates a new branch named "hotfix" and associates it with new worktree "../hotfix". Signed-off-by: Eric Sunshine <sunshine@sunshineco.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>
diff --git a/Documentation/git-worktree.txt b/Documentation/git-worktree.txt index 377ae0f..da71f50 100644 --- a/Documentation/git-worktree.txt +++ b/Documentation/git-worktree.txt
@@ -9,7 +9,7 @@ SYNOPSIS -------- [verse] -'git worktree add' [-f] [--detach] [-b <new-branch>] <path> <branch> +'git worktree add' [-f] [--detach] [-b <new-branch>] <path> [<branch>] 'git worktree prune' [-n] [-v] [--expire <expire>] DESCRIPTION @@ -45,11 +45,15 @@ COMMANDS -------- -add <path> <branch>:: +add <path> [<branch>]:: Create `<path>` and checkout `<branch>` into it. The new working directory is linked to the current repository, sharing everything except working directory specific files such as HEAD, index, etc. ++ +If `<branch>` is omitted and neither `-b` nor `-B` is used, then, as a +convenience, a new branch based at HEAD is created automatically, as if +`-b $(basename <path>)` was specified. prune::
diff --git a/builtin/worktree.c b/builtin/worktree.c index 323d444..69248ba 100644 --- a/builtin/worktree.c +++ b/builtin/worktree.c
@@ -291,12 +291,16 @@ die(_("-b and -B are mutually exclusive")); if (ac < 1 || ac > 2) usage_with_options(worktree_usage, options); - if (ac < 2 && !new_branch && !new_branch_force) - usage_with_options(worktree_usage, options); path = prefix ? prefix_filename(prefix, strlen(prefix), av[0]) : av[0]; branch = ac < 2 ? "HEAD" : av[1]; + if (ac < 2 && !new_branch && !new_branch_force) { + int n; + const char *s = worktree_basename(path, &n); + new_branch = xstrndup(s, n); + } + argv_array_push(&cmd, "checkout"); if (force) argv_array_push(&cmd, "--ignore-other-worktrees");
diff --git a/t/t2025-worktree-add.sh b/t/t2025-worktree-add.sh index 8964dec..ead8aa2 100755 --- a/t/t2025-worktree-add.sh +++ b/t/t2025-worktree-add.sh
@@ -145,4 +145,18 @@ test_cmp_rev HEAD burble ' +test_expect_success '"add" with <branch> omitted' ' + git worktree add wiffle/bat && + test_cmp_rev HEAD bat +' + +test_expect_success '"add" auto-vivify does not clobber existing branch' ' + test_commit c1 && + test_commit c2 && + git branch precious HEAD~1 && + test_must_fail git worktree add precious && + test_cmp_rev HEAD~1 precious && + test_path_is_missing precious +' + test_done