diff --git a/README.md b/README.md index 0103ba7..68fd98c 100644 --- a/README.md +++ b/README.md @@ -439,7 +439,7 @@ For full flags and examples, see `timber --help` and `timber --help`. | `tui` | Interactively open an existing worktree or create a new one | | `herdr install` | Install the bundled Herdr plugin | | `herdr space` | Open a Herdr Agent + Shell space for a worktree | -| `list` | List worktrees with merge/dirtiness status, optional TODO.md progress (`-t`/`--todo`, implied by `--json`), and optional commit review progress (`-r`/`--review`, implied by `--json`; `--json`, `--pr`, `--sort`, `-L`/`--location` for checkout paths in the last column) | +| `list` | List worktrees with merge/dirtiness status, optional TODO.md progress (`-t`/`--todo`, implied by `--json`), and optional commit review progress (`-r`/`--review`, implied by `--json`; `--json`, `--pr`, `--sort`, `-L`/`--location` for checkout paths in the last column, `--locations-only` for one path per line) | | `prune` | Remove clean, merged worktrees (`--dry-run`, `--prompt`) | | `remove` | Remove one worktree and delete its branch (`--force` overrides safety) | | `move` | Move a worktree checkout to a new path (`name[@repo] `) | diff --git a/internal/cli/commands.go b/internal/cli/commands.go index db69377..d821035 100644 --- a/internal/cli/commands.go +++ b/internal/cli/commands.go @@ -88,10 +88,11 @@ func Commands(runtime timber.Runtime) []*cobra.Command { Complete: cliComplete.CreateArgs(runtime), }), clilist.New(clilist.Dependencies{ - List: func(ctx context.Context, stdout io.Writer, repoArg string, pullRequests, todo, review, location, jsonOutput bool, sortMode string) error { - return runtime.ListWorktrees(ctx, stdout, repoArg, pullRequests, todo, review, location, jsonOutput, sortMode, timber.ListRenderers{ - Table: clilist.ReportTable, - JSON: clilist.ReportJSON, + List: func(ctx context.Context, stdout io.Writer, options timber.ListOptions) error { + return runtime.ListWorktrees(ctx, stdout, options, timber.ListRenderers{ + Table: clilist.ReportTable, + JSON: clilist.ReportJSON, + Locations: clilist.ReportLocations, }) }, Complete: cliComplete.RepoQualifiers(runtime), diff --git a/internal/cli/list/json_test.go b/internal/cli/list/json_test.go index 19e9a0f..6d04d67 100644 --- a/internal/cli/list/json_test.go +++ b/internal/cli/list/json_test.go @@ -53,3 +53,9 @@ func TestReportTableReturnsWriterError(t *testing.T) { writeErr := errors.New("write failed") assert.ErrorIs(t, ReportTable(failingWriter{err: writeErr}, nil, false, false, false, false), writeErr) } + +func TestReportLocationsReturnsWriterError(t *testing.T) { + t.Parallel() + writeErr := errors.New("write failed") + assert.ErrorIs(t, ReportLocations(failingWriter{err: writeErr}, []string{"~/worktrees/repo/feature/repo"}), writeErr) +} diff --git a/internal/cli/list/list.go b/internal/cli/list/list.go index 3d51b55..581c00c 100644 --- a/internal/cli/list/list.go +++ b/internal/cli/list/list.go @@ -7,6 +7,8 @@ import ( "strings" "github.com/spf13/cobra" + + "github.com/nnutter/timber/internal/timber" ) // sortValue implements pflag.Value for the list command's sort modes. @@ -44,40 +46,47 @@ func completeSort(_ *cobra.Command, _ []string, prefix string) ([]string, cobra. // Dependencies connects the list CLI to worktree listing. type Dependencies struct { - List func(ctx context.Context, stdout io.Writer, repoArg string, pullRequests, todo, review, location, jsonOutput bool, sortMode string) error + List func(ctx context.Context, stdout io.Writer, options timber.ListOptions) error Complete func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) } // New constructs the command that lists managed worktrees. func New(deps Dependencies) *cobra.Command { - var pullRequests, todo, review, location, jsonOutput bool + var options timber.ListOptions sortBy := sortValue(sortRecency) command := &cobra.Command{ Use: "list [@repo]", Aliases: []string{"ls"}, Short: "List managed Git worktrees", Args: cobra.MaximumNArgs(1), - RunE: run(deps, &pullRequests, &todo, &review, &location, &jsonOutput, &sortBy), + RunE: run(deps, &options, &sortBy), ValidArgsFunction: deps.Complete, } - command.Flags().BoolVar(&pullRequests, "pr", false, "Include open pull request status from gh") - command.Flags().BoolVarP(&todo, "todo", "t", false, "Include TODO progress (implied by --json)") - command.Flags().BoolVarP(&review, "review", "r", false, "Include commit review progress (implied by --json)") - command.Flags().BoolVarP(&location, "location", "L", false, "Include worktree location as the last column") - command.Flags().BoolVar(&jsonOutput, "json", false, "Output worktrees as JSON instead of a table") + command.Flags().BoolVar(&options.PullRequests, "pr", false, "Include open pull request status from gh") + command.Flags().BoolVarP(&options.Todo, "todo", "t", false, "Include TODO progress (implied by --json)") + command.Flags().BoolVarP(&options.Review, "review", "r", false, "Include commit review progress (implied by --json)") + command.Flags().BoolVarP(&options.Location, "location", "L", false, "Include worktree location as the last column") + command.Flags().BoolVar(&options.LocationsOnly, "locations-only", false, "Print only worktree locations, one per line") + command.Flags().BoolVar(&options.JSON, "json", false, "Output worktrees as JSON instead of a table") command.Flags().Var(&sortBy, "sort", "Sort worktrees by recency (newest commit first), repo, or worktree") + command.MarkFlagsMutuallyExclusive("locations-only", "json") + command.MarkFlagsMutuallyExclusive("locations-only", "pr") + command.MarkFlagsMutuallyExclusive("locations-only", "todo") + command.MarkFlagsMutuallyExclusive("locations-only", "review") + command.MarkFlagsMutuallyExclusive("locations-only", "location") if err := command.RegisterFlagCompletionFunc("sort", completeSort); err != nil { panic(err) } return command } -func run(deps Dependencies, pullRequests, todo, review, location, jsonOutput *bool, sortBy *sortValue) func(*cobra.Command, []string) error { +func run(deps Dependencies, options *timber.ListOptions, sortBy *sortValue) func(*cobra.Command, []string) error { return func(command *cobra.Command, args []string) error { - var repoArg string + callOptions := *options if len(args) == 1 { - repoArg = args[0] + callOptions.RepoArg = args[0] } - return deps.List(command.Context(), command.OutOrStdout(), repoArg, *pullRequests, *todo, *review, *location, *jsonOutput, string(*sortBy)) + callOptions.SortMode = string(*sortBy) + return deps.List(command.Context(), command.OutOrStdout(), callOptions) } } diff --git a/internal/cli/list/locations.go b/internal/cli/list/locations.go new file mode 100644 index 0000000..f0473e2 --- /dev/null +++ b/internal/cli/list/locations.go @@ -0,0 +1,16 @@ +package list + +import ( + "fmt" + "io" +) + +// ReportLocations writes one worktree location per line to stdout. +func ReportLocations(stdout io.Writer, locations []string) error { + for _, location := range locations { + if _, err := fmt.Fprintln(stdout, location); err != nil { + return err + } + } + return nil +} diff --git a/internal/cli/list_test.go b/internal/cli/list_test.go index a93d288..dc31437 100644 --- a/internal/cli/list_test.go +++ b/internal/cli/list_test.go @@ -57,6 +57,79 @@ func TestListLocationIsOptionalLastColumn(t *testing.T) { } } +func TestListLocationsOnly(t *testing.T) { + t.Parallel() + repository := newTestRepository(t) + + empty := repository.runTimber(t, "ls", "--locations-only") + require.NoError(t, empty.err, empty.stderr) + assert.Empty(t, empty.stdout) + + registerAdditionalRepo(t, repository, "aaa") + const standardName = "feature/standard" + const otherName = "feature/other" + require.NoError(t, repository.runTimber(t, "create", at(testRepoName, standardName)).err) + require.NoError(t, repository.runTimber(t, "create", at("aaa", otherName)).err) + customPath := filepath.Join(resolvedTempDir(t), "checkout with spaces") + runGitCommand(t, repository.barePath, "worktree", "add", "-b", "feature/manual", customPath, "origin/main") + + standardLocation := filepath.Join("~", "worktrees", testRepoName, standardName, testRepoName) + otherLocation := filepath.Join("~", "worktrees", "aaa", otherName, "aaa") + + byRepo := repository.runTimber(t, "ls", "--locations-only", "--sort", "repo") + require.NoError(t, byRepo.err, byRepo.stderr) + assert.Equal(t, strings.Join([]string{otherLocation, customPath, standardLocation}, "\n")+"\n", byRepo.stdout) + + byWorktree := repository.runTimber(t, "ls", "--locations-only", "--sort", "worktree") + require.NoError(t, byWorktree.err, byWorktree.stderr) + assert.Equal(t, strings.Join([]string{customPath, otherLocation, standardLocation}, "\n")+"\n", byWorktree.stdout) + + scoped := repository.runTimber(t, "ls", at("aaa", ""), "--locations-only") + require.NoError(t, scoped.err, scoped.stderr) + assert.Equal(t, otherLocation+"\n", scoped.stdout) + + // Recency sorting must still order by committer date even when status + // enrichment is skipped and a checkout directory is missing. + for _, commit := range []struct{ dir, committer string }{ + {customPath, "2020-01-01T00:00:00Z"}, + {repoTestWorktreePath(repository.runtime, "aaa", otherName), "2021-01-01T00:00:00Z"}, + {repository.worktreePath(standardName), "2022-01-01T00:00:00Z"}, + } { + runtime := withTestEnvironment(repository.runtime, + "GIT_AUTHOR_DATE="+commit.committer, "GIT_COMMITTER_DATE="+commit.committer, + "GIT_AUTHOR_NAME=Test", "GIT_AUTHOR_EMAIL=test@example.com", + "GIT_COMMITTER_NAME=Test", "GIT_COMMITTER_EMAIL=test@example.com") + command := gitCommand(t, commit.dir, "commit", "--allow-empty", "-m", "order") + command.Env = runtime.Environment + output, err := command.CombinedOutput() + require.NoError(t, err, string(output)) + } + require.NoError(t, os.RemoveAll(repository.worktreePath(standardName))) + + byRecency := repository.runTimber(t, "ls", "--locations-only") + require.NoError(t, byRecency.err, byRecency.stderr) + assert.Equal(t, strings.Join([]string{standardLocation, otherLocation, customPath}, "\n")+"\n", byRecency.stdout) + + for _, conflict := range []struct { + flag string + name string + }{ + {"--json", "json"}, + {"--pr", "pr"}, + {"--todo", "todo"}, + {"-t", "todo"}, + {"--review", "review"}, + {"-r", "review"}, + {"--location", "location"}, + {"-L", "location"}, + } { + result := repository.runTimber(t, "ls", "--locations-only", conflict.flag) + require.Error(t, result.err, "flag=%s", conflict.flag) + assert.Contains(t, result.err.Error(), "locations-only") + assert.Contains(t, result.err.Error(), conflict.name) + } +} + func TestListReportsTodoProgress(t *testing.T) { t.Parallel() const branchName = "feature/todo-progress" diff --git a/internal/timber/list.go b/internal/timber/list.go index 54433de..bc29622 100644 --- a/internal/timber/list.go +++ b/internal/timber/list.go @@ -4,8 +4,21 @@ import ( "io" ) +// ListOptions controls how ListWorktrees filters, sorts, and renders worktrees. +type ListOptions struct { + RepoArg string + PullRequests bool + Todo bool + Review bool + Location bool + LocationsOnly bool + JSON bool + SortMode string +} + // ListRenderers provides the output functions used by ListWorktrees. type ListRenderers struct { - Table func(io.Writer, []ListWorktreeView, bool, bool, bool, bool) error - JSON func(io.Writer, []ListJSONWorktree) error + Table func(io.Writer, []ListWorktreeView, bool, bool, bool, bool) error + JSON func(io.Writer, []ListJSONWorktree) error + Locations func(io.Writer, []string) error } diff --git a/internal/timber/list_sort.go b/internal/timber/list_sort.go index 27052b4..78bee59 100644 --- a/internal/timber/list_sort.go +++ b/internal/timber/list_sort.go @@ -50,7 +50,7 @@ const ( // Read the recorded HEAD from the bare repository, not the checkout: even a // missing worktree can be ordered. An unborn HEAD has no commit timestamp. -func enrichWorktreeForSort(runtime Runtime, repository *Repository, worktree managedWorktree, sortBy listSort) (managedWorktree, error) { +func enrichWorktreeForSort(repository *Repository, worktree managedWorktree, sortBy listSort) (managedWorktree, error) { if sortBy == listSortRecency && !isZeroCommitHash(worktree.CommitHash) { result, err := repository.git("show", "-s", "--format=%ct", worktree.CommitHash, "--") if err != nil { @@ -62,5 +62,5 @@ func enrichWorktreeForSort(runtime Runtime, repository *Repository, worktree man } worktree.CommitTime = time.Unix(seconds, 0) } - return runtime.enrichWorktreeForList(repository, worktree) + return worktree, nil } diff --git a/internal/timber/list_test.go b/internal/timber/list_test.go index 7822a68..72ba61f 100644 --- a/internal/timber/list_test.go +++ b/internal/timber/list_test.go @@ -12,16 +12,17 @@ import ( func TestListWorktreesRequiresSelectedRenderer(t *testing.T) { t.Parallel() for _, testCase := range []struct { - name string - jsonOutput bool - errorText string + name string + options ListOptions + errorText string }{ - {name: "table", errorText: "list table renderer is not configured"}, - {name: "JSON", jsonOutput: true, errorText: "list JSON renderer is not configured"}, + {name: "table", options: ListOptions{SortMode: "recency"}, errorText: "list table renderer is not configured"}, + {name: "JSON", options: ListOptions{JSON: true, SortMode: "recency"}, errorText: "list JSON renderer is not configured"}, + {name: "locations", options: ListOptions{LocationsOnly: true, SortMode: "recency"}, errorText: "list locations renderer is not configured"}, } { t.Run(testCase.name, func(t *testing.T) { runtime := testRuntime(t) - err := runtime.ListWorktrees(t.Context(), io.Discard, "", false, false, false, false, testCase.jsonOutput, "recency", ListRenderers{}) + err := runtime.ListWorktrees(t.Context(), io.Discard, testCase.options, ListRenderers{}) require.ErrorContains(t, err, testCase.errorText) }) } @@ -31,27 +32,35 @@ func TestListWorktreesReturnsRendererError(t *testing.T) { t.Parallel() writeErr := errors.New("write failed") for _, testCase := range []struct { - name string - jsonOutput bool - renderers ListRenderers + name string + options ListOptions + renderers ListRenderers }{ { - name: "table", + name: "table", + options: ListOptions{SortMode: "recency"}, renderers: ListRenderers{Table: func(io.Writer, []ListWorktreeView, bool, bool, bool, bool) error { return writeErr }}, }, { - name: "JSON", - jsonOutput: true, + name: "JSON", + options: ListOptions{JSON: true, SortMode: "recency"}, renderers: ListRenderers{JSON: func(io.Writer, []ListJSONWorktree) error { return writeErr }}, }, + { + name: "locations", + options: ListOptions{LocationsOnly: true, SortMode: "recency"}, + renderers: ListRenderers{Locations: func(io.Writer, []string) error { + return writeErr + }}, + }, } { t.Run(testCase.name, func(t *testing.T) { runtime := testRuntime(t) - err := runtime.ListWorktrees(t.Context(), io.Discard, "", false, false, false, false, testCase.jsonOutput, "recency", testCase.renderers) + err := runtime.ListWorktrees(t.Context(), io.Discard, testCase.options, testCase.renderers) assert.ErrorIs(t, err, writeErr) }) } diff --git a/internal/timber/runtime.go b/internal/timber/runtime.go index 875168c..64f58e6 100644 --- a/internal/timber/runtime.go +++ b/internal/timber/runtime.go @@ -449,17 +449,18 @@ func (x Runtime) ListRepos(details bool) ([]repomodel.Repo, error) { return result, nil } -// ListWorktrees lists managed worktrees as a table or JSON document. All -// output is written to the given writers, preserving CLI reporting order. -func (runtime Runtime) ListWorktrees(ctx context.Context, stdout io.Writer, repoArg string, pullRequests, todo, review, location, jsonOutput bool, sortMode string, renderers ListRenderers) error { +// ListWorktrees lists managed worktrees as a table, JSON document, or one +// location per line. All output is written to the given writers, preserving +// CLI reporting order. +func (runtime Runtime) ListWorktrees(ctx context.Context, stdout io.Writer, options ListOptions, renderers ListRenderers) error { var sortBy listSort - if err := sortBy.Set(sortMode); err != nil { + if err := sortBy.Set(options.SortMode); err != nil { return err } selection := repoSelection{runtime: runtime} - if repoArg != "" { - repo, err := runtime.parseRepoOnlyArg(repoArg) + if options.RepoArg != "" { + repo, err := runtime.parseRepoOnlyArg(options.RepoArg) if err != nil { return err } @@ -470,23 +471,18 @@ func (runtime Runtime) ListWorktrees(ctx context.Context, stdout io.Writer, repo if err != nil { return err } - enrich := func(repository *Repository, worktree managedWorktree) (managedWorktree, error) { - enriched, err := enrichWorktreeForSort(runtime, repository, worktree, sortBy) - if err == nil && isSame(enriched.ListError, false) { - enriched.Todo = runtime.todoProgressForWorktree(enriched, todo, jsonOutput) - } - return enriched, err - } - worktrees, err := collectListedWorktrees(runtime, repos, enrich) + worktrees, err := collectListedWorktrees(runtime, repos, listWorktreeEnricher(runtime, sortBy, options)) if err != nil { return err } sortBy.sort(worktrees) - runtime.enrichListedWorktreesWithReviews(ctx, worktrees, review, jsonOutput) - if err := attachPullRequests(runtime, ctx, worktrees, pullRequests); err != nil { - return err + if !options.LocationsOnly { + runtime.enrichListedWorktreesWithReviews(ctx, worktrees, options.Review, options.JSON) + if err := attachPullRequests(runtime, ctx, worktrees, options.PullRequests); err != nil { + return err + } } - return renderWorktreeList(runtime, stdout, worktrees, pullRequests, todo, review, location, jsonOutput, renderers) + return renderWorktreeList(runtime, stdout, worktrees, options, renderers) } // LoadConfig loads the persistent Timber settings. diff --git a/internal/timber/runtime_helpers.go b/internal/timber/runtime_helpers.go index 952df82..a7585cc 100644 --- a/internal/timber/runtime_helpers.go +++ b/internal/timber/runtime_helpers.go @@ -70,8 +70,31 @@ func attachPullRequests(runtime Runtime, ctx context.Context, worktrees []manage return runtime.enrichListedWorktreesWithPullRequests(ctx, worktrees) } -func renderWorktreeList(runtime Runtime, stdout io.Writer, worktrees []managedWorktree, pullRequests, todo, review, location, jsonOutput bool, renderers ListRenderers) error { - if jsonOutput { +func listWorktreeEnricher(runtime Runtime, sortBy listSort, options ListOptions) worktreeEnricher { + return func(repository *Repository, worktree managedWorktree) (managedWorktree, error) { + enriched, err := enrichWorktreeForSort(repository, worktree, sortBy) + if err != nil { + return managedWorktree{}, err + } + if options.LocationsOnly { + return enriched, nil + } + enriched, err = runtime.enrichWorktreeForList(repository, enriched) + if err == nil && isSame(enriched.ListError, false) { + enriched.Todo = runtime.todoProgressForWorktree(enriched, options.Todo, options.JSON) + } + return enriched, err + } +} + +func renderWorktreeList(runtime Runtime, stdout io.Writer, worktrees []managedWorktree, options ListOptions, renderers ListRenderers) error { + if options.LocationsOnly { + if renderers.Locations == nil { + return errors.New("list locations renderer is not configured") + } + return renderers.Locations(stdout, worktreeLocations(runtime, worktrees)) + } + if options.JSON { if renderers.JSON == nil { return errors.New("list JSON renderer is not configured") } @@ -80,7 +103,15 @@ func renderWorktreeList(runtime Runtime, stdout io.Writer, worktrees []managedWo if renderers.Table == nil { return errors.New("list table renderer is not configured") } - return renderers.Table(stdout, runtime.worktreesToListTable(worktrees, location), pullRequests, todo, review, location) + return renderers.Table(stdout, runtime.worktreesToListTable(worktrees, options.Location), options.PullRequests, options.Todo, options.Review, options.Location) +} + +func worktreeLocations(runtime Runtime, worktrees []managedWorktree) []string { + locations := make([]string, 0, len(worktrees)) + for _, worktree := range worktrees { + locations = append(locations, runtime.displayHomePath(worktree.Path)) + } + return locations } func validateCreateReporters(runtime Runtime, herdr, noHerdr bool, reporters CreateReporters) error {