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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -439,7 +439,7 @@ For full flags and examples, see `timber --help` and `timber <command> --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] <path>`) |
Expand Down
9 changes: 5 additions & 4 deletions internal/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand Down
6 changes: 6 additions & 0 deletions internal/cli/list/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
33 changes: 21 additions & 12 deletions internal/cli/list/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
}
}
16 changes: 16 additions & 0 deletions internal/cli/list/locations.go
Original file line number Diff line number Diff line change
@@ -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
}
73 changes: 73 additions & 0 deletions internal/cli/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
17 changes: 15 additions & 2 deletions internal/timber/list.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
4 changes: 2 additions & 2 deletions internal/timber/list_sort.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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
}
35 changes: 22 additions & 13 deletions internal/timber/list_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
})
}
Expand All @@ -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)
})
}
Expand Down
32 changes: 14 additions & 18 deletions internal/timber/runtime.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand All @@ -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.
Expand Down
Loading
Loading