Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
84 changes: 61 additions & 23 deletions internal/timber/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,39 +17,45 @@ func NewGitCommand(runtime Runtime) *cobra.Command {
options := &gitCommandOptions{runtime: runtime}

command := &cobra.Command{
Use: "git [worktree[@repo]] [-- git-args...]",
Short: "Run git with --git-dir set to a managed worktree",
Use: "git [worktree[@repo]|@repo] [-- git-args...]",
Short: "Run git with --git-dir set to a managed worktree or repository",
Args: cobra.ArbitraryArgs,
DisableFlagParsing: true,
RunE: options.Execute,
ValidArgsFunction: runtime.completeQualifiedWorktreeNames,
ValidArgsFunction: options.completeSelector,
}

return command
}

func (x *gitCommandOptions) Execute(command *cobra.Command, args []string) error {
targetDirectory := x.runtime.CurrentDirectory
explicitGitDir := ""
gitArgs := args
if len(args) > 0 && args[0] == "--" {
gitArgs = args[1:]
} else if len(args) > 0 && !strings.HasPrefix(args[0], "-") {
selected, remaining, ok, err := x.resolveWorktreeSelector(command.InOrStdin(), args)
selectedDir, selectedGitDir, remaining, ok, err := x.resolveWorktreeSelector(command.InOrStdin(), args)
if err != nil {
return err
}
if ok {
targetDirectory = selected
targetDirectory = selectedDir
explicitGitDir = selectedGitDir
gitArgs = remaining
if len(gitArgs) > 0 && gitArgs[0] == "--" {
gitArgs = gitArgs[1:]
}
}
}

gitDir, err := gitDirForDirectory(x.runtime, targetDirectory)
if err != nil {
return err
gitDir := explicitGitDir
if gitDir == "" {
resolved, err := gitDirForDirectory(x.runtime, targetDirectory)
if err != nil {
return err
}
gitDir = resolved
}

gitArgs = append([]string{"--git-dir", gitDir}, gitArgs...)
Expand All @@ -64,49 +70,81 @@ func (x *gitCommandOptions) Execute(command *cobra.Command, args []string) error
return nil
}

// resolveWorktreeSelector interprets args[0] as a <worktree> or
// <worktree>@<repo> selector like the other worktree commands. A candidate
// containing @ always selects a worktree and returns its errors. A bare
// name selects a worktree only when it resolves to an existing managed
// worktree; otherwise ok is false and the caller treats all args as git
// args so subcommands such as `status` keep working.
func (x *gitCommandOptions) resolveWorktreeSelector(input io.Reader, args []string) (string, []string, bool, error) {
// resolveWorktreeSelector interprets args[0] as a <worktree>, <worktree>@<repo>,
// or @<repo> selector. A candidate containing @ always selects a target and
// returns its errors: a bare worktree name selects the managed worktree, while
// a repo-only @<repo> selects the bare repository. A bare name selects a
// worktree only when it resolves to an existing managed worktree; otherwise
// ok is false and the caller treats all args as git args so subcommands such
// as `status` keep working. The returned gitDir is set for the repo-only
// case; it is empty for worktrees so the caller resolves it from the
// worktree directory.
func (x *gitCommandOptions) resolveWorktreeSelector(input io.Reader, args []string) (string, string, []string, bool, error) {
candidate := args[0]
if strings.Contains(candidate, "@") {
qualified, err := x.runtime.parseQualifiedName(candidate)
if err != nil {
return "", "", nil, false, err
}
if qualified.Name == "" {
repo, err := x.runtime.registeredRepoByName(qualified.Repo)
if err != nil {
return "", "", nil, false, err
}
return repo.BarePath, repo.BarePath, args[1:], true, nil
}
_, _, worktree, err := x.resolveQualifiedWorktree(input, candidate)
if err != nil {
return "", nil, false, err
return "", "", nil, false, err
}
return worktree.Path, args[1:], true, nil
return worktree.Path, "", args[1:], true, nil
}

repoName, err := x.runtime.inferUniqueRepoForWorktree(candidate)
if err != nil {
if strings.Contains(err.Error(), "not found") {
return "", nil, false, nil
return "", "", nil, false, nil
}
return "", nil, false, err
return "", "", nil, false, err
}
x.RepoName = repoName
_, _, worktree, err := x.resolveQualifiedWorktree(input, candidate)
if err != nil {
return "", nil, false, err
return "", "", nil, false, err
}
return worktree.Path, "", args[1:], true, nil
}

func (x *gitCommandOptions) completeSelector(command *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
if len(args) > 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
if name, repoPrefix, found := strings.CutLast(toComplete, "@"); found {
if name == "" {
return x.runtime.completeRepoSuffix("", repoPrefix, false)
}
return x.runtime.completeRepoSuffix(name, repoPrefix, true)
}
if toComplete != "" && !strings.HasPrefix(toComplete, "@") {
return x.runtime.completeQualifiedWorktreeNames(command, args, toComplete)
}
return worktree.Path, args[1:], true, nil
worktrees, _ := x.runtime.completeQualifiedWorktreeNames(command, args, toComplete)
repos, _ := x.runtime.completeRepoSuffix("", strings.TrimPrefix(toComplete, "@"), false)
return append(worktrees, repos...), cobra.ShellCompDirectiveNoFileComp
}

func gitDirForDirectory(runtime Runtime, directory string) (string, error) {
gitDirResult, err := gitOutput(runtime, directory, "rev-parse", "--absolute-git-dir")
if err != nil {
return "", fmt.Errorf("not inside a worktree: pass a worktree name or run inside a worktree")
return "", fmt.Errorf("not inside a worktree: pass a worktree name or @<repo> or run inside a worktree")
}

bareResult, err := gitOutput(runtime, directory, "rev-parse", "--is-bare-repository")
if err != nil {
return "", err
}
if bareResult.stdout == "true" {
return "", fmt.Errorf("not inside a worktree: pass a worktree name or run inside a worktree")
return "", fmt.Errorf("not inside a worktree: pass a worktree name or @<repo> or run inside a worktree")
}
return filepath.Clean(gitDirResult.stdout), nil
}
40 changes: 40 additions & 0 deletions internal/timber/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,3 +196,43 @@ func TestGitFallsBackToCurrentForGitSubcommand(t *testing.T) {
require.NoError(t, result.err, result.stderr)
assert.Equal(t, currentPath, strings.TrimSpace(result.stdout))
}

func TestGitRunsInRepoOnlySelector(t *testing.T) {
t.Parallel()

testRepository := newTestRepository(t)

result := runTimberFromWithRuntime(t, testRepository.runtime, testRepository.home, "git", at(testRepoName, ""), "rev-parse", "--absolute-git-dir")
require.NoError(t, result.err, result.stderr)
assert.Equal(t, testRepository.barePath, strings.TrimSpace(result.stdout))
}

func TestGitRepoOnlySelectorShowsRemotes(t *testing.T) {
t.Parallel()

testRepository := newTestRepository(t)

result := runTimberFromWithRuntime(t, testRepository.runtime, testRepository.home, "git", at(testRepoName, ""), "remote", "-v")
require.NoError(t, result.err, result.stderr)
assert.Contains(t, result.stdout, "origin")
}

func TestGitRepoOnlySelectorStripsFollowingDashDash(t *testing.T) {
t.Parallel()

testRepository := newTestRepository(t)

result := runTimberFromWithRuntime(t, testRepository.runtime, testRepository.home, "git", at(testRepoName, ""), "--", "rev-parse", "--absolute-git-dir")
require.NoError(t, result.err, result.stderr)
assert.Equal(t, testRepository.barePath, strings.TrimSpace(result.stdout))
}

func TestGitRepoOnlySelectorUnknownRepo(t *testing.T) {
t.Parallel()

testRepository := newTestRepository(t)

result := runTimberFromWithRuntime(t, testRepository.runtime, testRepository.home, "git", "@missing", "status")
require.Error(t, result.err)
assert.Contains(t, result.err.Error(), `unknown repository "missing"`)
}
30 changes: 15 additions & 15 deletions mise.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion mise.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[tools]
go = "1.27.0"
go = "1.27.1"

#####################
# Development Tasks #
Expand Down