From 33d1295d4bb2c0a19f4a74597c116a2b1c5e76a8 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Mon, 16 Nov 2026 21:45:31 -0600 Subject: [PATCH 01/12] Keep nested worktrees addressable when renaming a repository A linked worktree whose checkout lives inside the bare Git directory moves with that directory when the repository is renamed, but the repair list still named the old path. `git worktree repair` then failed on the missing path, and the rename rolled back. Derive the destination path for such worktrees so repair and verification address the moved checkout. Change-Id: I10ec278c1582c7960d4d485e7a80d029b73cd179 --- internal/cli/repo_rename_functional_test.go | 19 +++++++++++++++++++ internal/timber/repo_rename_plan.go | 11 +++++++++++ 2 files changed, 30 insertions(+) diff --git a/internal/cli/repo_rename_functional_test.go b/internal/cli/repo_rename_functional_test.go index d1865a1..165e996 100644 --- a/internal/cli/repo_rename_functional_test.go +++ b/internal/cli/repo_rename_functional_test.go @@ -55,6 +55,25 @@ func TestRepoRenameMovesStandardWorktreesAndPreservesCustomWorktrees(t *testing. assert.Equal(t, unmanagedPath+"\n", switchResult.stdout) } +func TestRepoRenameMovesWorktreeNestedInBareRepository(t *testing.T) { + t.Parallel() + const newRepoName = "renamed" + + testRepository := newTestRepository(t) + nestedPath := filepath.Join(testRepository.barePath, "checkouts", "nested") + runGitCommand(t, testRepository.barePath, "worktree", "add", "--detach", nestedPath, "main") + + result := testRepository.runTimber(t, "repo", "rename", testRepoName, newRepoName) + require.NoError(t, result.err, result.stderr) + + newBarePath := repoTestBarePath(testRepository.runtime, newRepoName) + newNestedPath := filepath.Join(newBarePath, "checkouts", "nested") + assert.NoDirExists(t, testRepository.barePath) + assert.DirExists(t, newNestedPath) + commonDir := strings.TrimSpace(runGitCommand(t, newNestedPath, "rev-parse", "--path-format=absolute", "--git-common-dir")) + assert.Equal(t, shellCanonicalPath(newBarePath), shellCanonicalPath(commonDir)) +} + func TestRepoRenameWithoutWorktrees(t *testing.T) { t.Parallel() testRepository := newTestRepository(t) diff --git a/internal/timber/repo_rename_plan.go b/internal/timber/repo_rename_plan.go index e183a68..a60dd28 100644 --- a/internal/timber/repo_rename_plan.go +++ b/internal/timber/repo_rename_plan.go @@ -6,6 +6,7 @@ import ( "os" "path/filepath" "slices" + "strings" ) type repositoryRenamePlan struct { @@ -245,6 +246,16 @@ func originalLinkedPaths(worktrees []linkedWorktreePath) []string { } func renamedWorktreePath(x *repositoryRenamePlan, worktree porcelainWorktree) (string, error) { + // Compare recorded paths rather than their symlink targets: a worktree + // nested in the bare Git directory moves with that directory. + relativePath, err := filepath.Rel(x.sourceRepo.BarePath, worktree.Path) + if err != nil { + return "", fmt.Errorf("resolve worktree %q within repository: %w", worktree.Path, err) + } + if relativePath != ".." && !strings.HasPrefix(relativePath, ".."+string(filepath.Separator)) { + return filepath.Join(x.destinationRepo.BarePath, relativePath), nil + } + renamedPath := worktree.Path branchName := worktree.branchName() if branchName == "" { From 9bc1a9e1be991befd307b85c2e9054c2a138fbeb Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Mon, 16 Nov 2026 21:47:26 -0600 Subject: [PATCH 02/12] Remove empty rename destinations after a rollback A failed rename left the destination directory tree it had created (e.g. ~/worktrees/spor) behind after restoring the source repository, which made the rollback look like a partial move. Prune the empty destination parents while rolling back so a failed rename leaves no artifacts. Change-Id: I50f57323c9764c229eac766143ab609c4945f7f9 --- internal/timber/repo_rename_functional_test.go | 3 +++ internal/timber/repo_rename_plan.go | 18 ++++++++++++++++++ 2 files changed, 21 insertions(+) diff --git a/internal/timber/repo_rename_functional_test.go b/internal/timber/repo_rename_functional_test.go index 1e5d087..689c719 100644 --- a/internal/timber/repo_rename_functional_test.go +++ b/internal/timber/repo_rename_functional_test.go @@ -5,6 +5,7 @@ import ( "fmt" "io" "os" + "path/filepath" "testing" "github.com/stretchr/testify/assert" @@ -38,6 +39,7 @@ func TestRepoRenameRollsBackCompletedWorktreeMoves(t *testing.T) { assert.Contains(t, err.Error(), "injected rename failure") assert.DirExists(t, testRepository.barePath) assert.NoDirExists(t, testRepository.runtime.bareRepoPath("renamed")) + assert.NoDirExists(t, filepath.Dir(testRepository.runtime.bareRepoPath("renamed"))) for _, branchName := range []string{"feature/first", "feature/second"} { assert.DirExists(t, testRepository.worktreePath(branchName)) _, openErr := openRepository(testRepository.runtime, testRepository.worktreePath(branchName)) @@ -69,6 +71,7 @@ func TestRepoRenameRollsBackAfterRepairFailure(t *testing.T) { assert.Contains(t, err.Error(), "injected repair failure") assert.DirExists(t, testRepository.barePath) assert.NoDirExists(t, testRepository.runtime.bareRepoPath("renamed")) + assert.NoDirExists(t, filepath.Dir(testRepository.runtime.bareRepoPath("renamed"))) assert.DirExists(t, testRepository.worktreePath(branchName)) _, openErr := openRepository(testRepository.runtime, testRepository.worktreePath(branchName)) require.NoError(t, openErr) diff --git a/internal/timber/repo_rename_plan.go b/internal/timber/repo_rename_plan.go index a60dd28..3be90e8 100644 --- a/internal/timber/repo_rename_plan.go +++ b/internal/timber/repo_rename_plan.go @@ -116,6 +116,21 @@ func (x *repositoryRenamePlan) findCurrentTargetDirectory() error { return nil } +// removeEmptyDestinations prunes the destination directories that creating +// the rename destinations left empty after a rollback moved everything back. +func (x repositoryRenamePlan) removeEmptyDestinations() error { + var removeErrors []error + for _, move := range x.worktreeMoves { + if err := x.runtime.removeEmptyBareParents(move.Destination); err != nil { + removeErrors = append(removeErrors, err) + } + } + if err := x.runtime.removeEmptyBareParents(x.destinationRepo.BarePath); err != nil { + removeErrors = append(removeErrors, err) + } + return errors.Join(removeErrors...) +} + func (x repositoryRenamePlan) repairAndVerify( repairWorktrees repairWorktreesFunc, barePath string, @@ -155,6 +170,9 @@ func (x repositoryRenamePlan) rollback( rollbackErrors = append(rollbackErrors, fmt.Errorf("restore worktree %q: %w", move.Source, err)) } } + if err := x.removeEmptyDestinations(); err != nil { + rollbackErrors = append(rollbackErrors, fmt.Errorf("remove empty rename destinations: %w", err)) + } if err := repairWorktrees(x.sourceRepo.BarePath, originalLinkedPaths(x.linkedWorktrees)); err != nil { rollbackErrors = append(rollbackErrors, fmt.Errorf("repair restored worktrees: %w", err)) } From 360b07190fde656977281e74daf134563dd42458 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Mon, 16 Nov 2026 23:59:10 -0600 Subject: [PATCH 03/12] Refactor: Extract GitHub host predicate from alias derivation Owner stripping needs the same notion of a GitHub host that alias derivation already encodes. Share one predicate so both agree on github.com and ssh.github.com. Change-Id: I92ae44a5f00d615e3a81d44723abe4f2930d92f7 --- internal/timber/remote_url.go | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/internal/timber/remote_url.go b/internal/timber/remote_url.go index 7786698..7cad6bf 100644 --- a/internal/timber/remote_url.go +++ b/internal/timber/remote_url.go @@ -106,13 +106,18 @@ func remoteHostAndPath(remoteURL string) (host, repoPath string, ok bool) { return host, repoPath, true } +// isGitHubHost reports whether host serves GitHub repositories. +func isGitHubHost(host string) bool { + return strings.EqualFold(host, "github.com") || strings.EqualFold(host, "ssh.github.com") +} + // defaultRepoAliasFromRemote shortens GitHub origins while preserving other origins. func defaultRepoAliasFromRemote(remoteURL string) string { host, repoPath, ok := remoteHostAndPath(remoteURL) if !ok { return remoteURL } - if !strings.EqualFold(host, "github.com") && !strings.EqualFold(host, "ssh.github.com") { + if !isGitHubHost(host) { return remoteURL } repoPath = strings.TrimSuffix(strings.Trim(repoPath, "/"), bareRepoSuffix) From 0cf1f577e4f9f08d899ef3aa390dff7f7fae2492 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Tue, 17 Nov 2026 00:02:02 -0600 Subject: [PATCH 04/12] Refactor: Split config file creation from config loading `repo add` and `repo import` are about to read settings, but they should not create a configuration file as a side effect. Extract ensureConfigFile so a read-only load can treat a missing file as default settings. Change-Id: Ic95a21cd06d2a0f0f02f55e2694363db340c9720 --- internal/timber/runtime.go | 63 +++++++++++++++++++++++++------------- 1 file changed, 41 insertions(+), 22 deletions(-) diff --git a/internal/timber/runtime.go b/internal/timber/runtime.go index 575b226..d66f266 100644 --- a/internal/timber/runtime.go +++ b/internal/timber/runtime.go @@ -1289,6 +1289,27 @@ func (x Runtime) enrichWorktreeForList(repository *Repository, worktree managedW return worktree, nil } +// ensureConfigFile creates an empty configuration file when none exists. +func (x Runtime) ensureConfigFile() error { + path := x.configPath() + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + return fmt.Errorf("create config directory: %w", err) + } + // Do not overwrite settings if another process creates the file first. + file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) + if err == nil { + encodeErr := toml.NewEncoder(file).Encode(config{}) + if err := errors.Join(encodeErr, file.Close()); err != nil { + return fmt.Errorf("create config: %w", err) + } + return nil + } + if !errors.Is(err, os.ErrExist) { + return fmt.Errorf("create config: %w", err) + } + return nil +} + // ensureHerdrParentWorkspace returns the ID of the Herdr workspace rooted at // the repository's bare directory, creating it when no such workspace exists. // A parent left behind by an earlier workflow keeps its label unless it is @@ -1679,29 +1700,10 @@ func (x Runtime) listWorktreesForWizard(repos []registeredRepo) ([]managedWorktr } func (x Runtime) loadConfig() (config, error) { - path := x.configPath() - if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { - return config{}, fmt.Errorf("create config directory: %w", err) - } - // Do not overwrite settings if another process creates the file first. - file, err := os.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600) - if err == nil { - encodeErr := toml.NewEncoder(file).Encode(config{}) - if err := errors.Join(encodeErr, file.Close()); err != nil { - return config{}, fmt.Errorf("create config: %w", err) - } - } else if !errors.Is(err, os.ErrExist) { - return config{}, fmt.Errorf("create config: %w", err) - } - var settings config - metadata, err := toml.DecodeFile(path, &settings) - if err != nil { - return config{}, fmt.Errorf("read config: %w", err) + if err := x.ensureConfigFile(); err != nil { + return config{}, err } - if keys := metadata.Undecoded(); len(keys) != 0 { - return config{}, fmt.Errorf("unknown config setting: %s", keys[0]) - } - return settings, nil + return x.readConfig() } // managedWorktreePath returns @@ -1986,6 +1988,23 @@ func (runtime Runtime) pullRequestTarget(input io.Reader, draft PullRequestDraft return pullRequestTarget{remote: remote, owner: owner, repo: repo, head: head, base: base, headSHA: headSHA}, nil } +// readConfig loads the persistent settings without creating the file. A +// missing file describes the default settings. +func (x Runtime) readConfig() (config, error) { + var settings config + metadata, err := toml.DecodeFile(x.configPath(), &settings) + if errors.Is(err, os.ErrNotExist) { + return config{}, nil + } + if err != nil { + return config{}, fmt.Errorf("read config: %w", err) + } + if keys := metadata.Undecoded(); len(keys) != 0 { + return config{}, fmt.Errorf("unknown config setting: %s", keys[0]) + } + return settings, nil +} + // Standard-layout worktrees predate explicit name records. An empty name // identifies a manual checkout whose name must be derived from its path. // recordMovedWorktreeName preserves the worktree's selector name when the From e2249503362fe03177451d44654d48c21b790f7f Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Tue, 17 Nov 2026 07:42:41 -0600 Subject: [PATCH 05/12] Refactor: Extract config flag updates from the config command The config command is about to gain a repeatable owner flag, and its RunE already sits at the complexity limit. Extract the boolean flag handling so the new flag can be added without exceeding it. Change-Id: I5118b00d4aea2f17729ab04301a6b4026e883599 --- internal/cli/config/config.go | 45 +++++++++++++++++++++++------------ 1 file changed, 30 insertions(+), 15 deletions(-) diff --git a/internal/cli/config/config.go b/internal/cli/config/config.go index c5333c1..037ee97 100644 --- a/internal/cli/config/config.go +++ b/internal/cli/config/config.go @@ -24,21 +24,8 @@ func New(store Store) *cobra.Command { if err != nil { return err } - changed := false - if command.Flags().Changed("auto-mise-trust") || command.Flags().Changed("no-auto-mise-trust") { - settings.AutoMiseTrust = enable - if command.Flags().Changed("no-auto-mise-trust") { - settings.AutoMiseTrust = !disable - } - settings.AutoMiseTrustDecided = true - changed = true - } - if command.Flags().Changed("auto-hk-install") || command.Flags().Changed("no-auto-hk-install") { - settings.AutoHKInstall = enableHK - if command.Flags().Changed("no-auto-hk-install") { - settings.AutoHKInstall = !disableHK - } - settings.AutoHKInstallDecided = true + changed := applyAutoMiseTrust(command, &settings, enable, disable) + if applyAutoHKInstall(command, &settings, enableHK, disableHK) { changed = true } if changed { @@ -57,3 +44,31 @@ func New(store Store) *cobra.Command { command.MarkFlagsMutuallyExclusive("auto-hk-install", "no-auto-hk-install") return command } + +// applyAutoMiseTrust records the automatic mise trust flags and reports whether +// they changed the settings. +func applyAutoMiseTrust(command *cobra.Command, settings *coreconfig.Settings, enable, disable bool) bool { + if !command.Flags().Changed("auto-mise-trust") && !command.Flags().Changed("no-auto-mise-trust") { + return false + } + settings.AutoMiseTrust = enable + if command.Flags().Changed("no-auto-mise-trust") { + settings.AutoMiseTrust = !disable + } + settings.AutoMiseTrustDecided = true + return true +} + +// applyAutoHKInstall records the automatic hk install flags and reports whether +// they changed the settings. +func applyAutoHKInstall(command *cobra.Command, settings *coreconfig.Settings, enable, disable bool) bool { + if !command.Flags().Changed("auto-hk-install") && !command.Flags().Changed("no-auto-hk-install") { + return false + } + settings.AutoHKInstall = enable + if command.Flags().Changed("no-auto-hk-install") { + settings.AutoHKInstall = !disable + } + settings.AutoHKInstallDecided = true + return true +} From 5410878777a466c003aeb585ab645eef0bc6c0e1 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Tue, 17 Nov 2026 07:45:38 -0600 Subject: [PATCH 06/12] Strip a configured GitHub owner from derived repository names `repo add` and `repo import` keep the owner in a repository name so GitHub groupings stay visible, but a personal repository then nests under an extra directory. Let `timber config --strip-github-owner` name the owners whose repositories register under the short name. The list is stored as `strip_github_owners` and matched case-insensitively because GitHub logins are. Only github.com and ssh.github.com remotes are affected, an explicit `--name` still wins, and other hosts keep their full grouping. Change-Id: Idf58081fbd0eb33b1b2fff6c3c2146ebea323457 --- README.md | 9 ++- internal/cli/config/config.go | 20 ++++++ internal/cli/config_test.go | 39 ++++++++++++ internal/cli/repo_add_test.go | 62 +++++++++++++++++++ internal/timber/config/owners.go | 64 ++++++++++++++++++++ internal/timber/config/owners_test.go | 77 ++++++++++++++++++++++++ internal/timber/config/settings.go | 9 +-- internal/timber/remote_url.go | 23 +++++++ internal/timber/remote_url_test.go | 72 ++++++++++++++++++++++ internal/timber/repo_import.go | 4 +- internal/timber/repo_import_name_test.go | 24 ++++++++ internal/timber/runtime.go | 16 +++-- internal/timber/runtime_helpers.go | 6 +- internal/timber/runtime_import.go | 8 +-- skills/timber/SKILL.md | 3 +- 15 files changed, 417 insertions(+), 19 deletions(-) create mode 100644 internal/timber/config/owners.go create mode 100644 internal/timber/config/owners_test.go diff --git a/README.md b/README.md index 8509014..cf78a98 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,9 @@ Structured example (`t repo add nnutter/timber` defaults to the structured name; Rename with `timber repo rename ` to move between simple and structured names; standard-layout worktrees move with the repo. Sorting `timber list --sort repo` orders by the full structured name, so the grouping prefix controls grouping. +Listing a GitHub owner with `timber config --strip-github-owner ` registers that owner's repositories under the short name instead: `timber repo add nnutter/timber` then becomes repo name `timber` at `~/worktrees/timber/.git`. +Explicit `--name` always wins, owner matching ignores case, and other hosts keep their full grouping. + Use `timber repo import ` to register an existing clean clone and recreate its worktrees (including the former main checkout) in this layout. When invoked through the shell wrapper (`t repo import `), the shell also `cd`s to `$HOME` after success. @@ -111,8 +114,12 @@ timber config --auto-mise-trust timber config --no-auto-mise-trust timber config --auto-hk-install timber config --no-auto-hk-install +timber config --strip-github-owner nnutter +timber config --no-strip-github-owner nnutter ``` +`--strip-github-owner` is repeatable and records `strip_github_owners` in the config file; `repo add` and `repo import` drop a listed owner from names they derive from GitHub remotes. + Enabling automatic trust permits mise configuration in eligible worktrees to execute code. Eligibility requires a root-level, regular `mise.toml` and a GitHub upstream owned by you or one of your organizations. Timber uses authenticated `gh` lookups and caches the identity for 24 hours in `$XDG_DATA_HOME/timber/github-identity.json` (fallback: `~/.local/share/timber/github-identity.json`). @@ -423,7 +430,7 @@ For full flags and examples, see `timber --help` and `timber --help`. | `repo fix` | Move bare repositories from the old data directory into the worktree root, repair worktree links, and set `push.default=current` | | `repo remove` | Unregister a bare repository once its worktrees are gone | | `repo rename` | Rename a repository and move its worktree directories | -| `config` | Show settings or change them with `--auto-mise-trust` / `--no-auto-mise-trust` / `--auto-hk-install` / `--no-auto-hk-install` | +| `config` | Show settings or change them with `--auto-mise-trust` / `--no-auto-mise-trust` / `--auto-hk-install` / `--no-auto-hk-install` / `--strip-github-owner` / `--no-strip-github-owner` | | `create` | Create a worktree for a branch (`--no-herdr` skips the Herdr space) | | `switch` | Shell-only: `cd` into a worktree, creating it first with `-c` | | `tui` | Interactively open an existing worktree or create a new one | diff --git a/internal/cli/config/config.go b/internal/cli/config/config.go index 037ee97..5e21d90 100644 --- a/internal/cli/config/config.go +++ b/internal/cli/config/config.go @@ -15,6 +15,7 @@ type Store interface { func New(store Store) *cobra.Command { var enable, disable, enableHK, disableHK bool + var stripOwners, noStripOwners []string command := &cobra.Command{ Use: "config", Short: "Show or change Timber settings", @@ -28,6 +29,12 @@ func New(store Store) *cobra.Command { if applyAutoHKInstall(command, &settings, enableHK, disableHK) { changed = true } + if command.Flags().Changed("strip-github-owner") || command.Flags().Changed("no-strip-github-owner") { + if err := applyStripGitHubOwners(&settings, stripOwners, noStripOwners); err != nil { + return err + } + changed = true + } if changed { if err := store.SaveConfig(settings); err != nil { return err @@ -42,6 +49,9 @@ func New(store Store) *cobra.Command { command.Flags().BoolVar(&enableHK, "auto-hk-install", false, "Install hk hooks in worktrees owned by you or your GitHub organizations") command.Flags().BoolVar(&disableHK, "no-auto-hk-install", false, "Disable automatic hk hook installation") command.MarkFlagsMutuallyExclusive("auto-hk-install", "no-auto-hk-install") + command.Flags().StringArrayVar(&stripOwners, "strip-github-owner", nil, "Drop this GitHub owner from repository names derived from remotes (repeatable)") + command.Flags().StringArrayVar(&noStripOwners, "no-strip-github-owner", nil, "Stop dropping this GitHub owner from repository names (repeatable)") + command.MarkFlagsMutuallyExclusive("strip-github-owner", "no-strip-github-owner") return command } @@ -72,3 +82,13 @@ func applyAutoHKInstall(command *cobra.Command, settings *coreconfig.Settings, e settings.AutoHKInstallDecided = true return true } + +// applyStripGitHubOwners records the owner list flags. +func applyStripGitHubOwners(settings *coreconfig.Settings, add, remove []string) error { + owners, err := coreconfig.UpdateStripGitHubOwners(settings.StripGitHubOwners, add, remove) + if err != nil { + return err + } + settings.StripGitHubOwners = owners + return nil +} diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go index 096ab1c..1238a6d 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -41,6 +41,45 @@ func TestConfigPersistsSettingsUnderXDGConfigHome(t *testing.T) { assert.Contains(t, result.err.Error(), "none of the others can be") } +func TestConfigManagesStripGitHubOwners(t *testing.T) { + runtime := testRuntime(t) + configPath := filepath.Join(runtime.ConfigHome, "timber", "config.toml") + for _, step := range []struct { + args []string + want string + }{ + { + []string{"config", "--strip-github-owner", "nnutter"}, + "auto_mise_trust = false\nauto_hk_install = false\nstrip_github_owners = [\"nnutter\"]\n", + }, + { + []string{"config", "--strip-github-owner", "acme", "--strip-github-owner", "Nnutter"}, + "auto_mise_trust = false\nauto_hk_install = false\nstrip_github_owners = [\"acme\", \"nnutter\"]\n", + }, + { + []string{"config", "--no-strip-github-owner", "ACME"}, + "auto_mise_trust = false\nauto_hk_install = false\nstrip_github_owners = [\"nnutter\"]\n", + }, + } { + result := runTimberCommandWithRuntime(t, runtime, step.args...) + require.NoError(t, result.err) + assert.Equal(t, step.want, result.stdout) + contents, err := os.ReadFile(configPath) + require.NoError(t, err) + assert.Equal(t, step.want, string(contents)) + } + + result := runTimberCommandWithRuntime(t, runtime, "config", "--strip-github-owner", "nnutter/timber") + require.Error(t, result.err) + assert.Contains(t, result.err.Error(), "expected a single GitHub owner") + result = runTimberCommandWithRuntime(t, runtime, "config", "--strip-github-owner", "nnutter", "--no-strip-github-owner", "acme") + require.Error(t, result.err) + assert.Contains(t, result.err.Error(), "none of the others can be") + contents, err := os.ReadFile(configPath) + require.NoError(t, err) + assert.Equal(t, "auto_mise_trust = false\nauto_hk_install = false\nstrip_github_owners = [\"nnutter\"]\n", string(contents)) +} + func TestConfigDoesNotOverwriteInvalidOrUnknownSettings(t *testing.T) { for _, contents := range []string{"auto_mise_trust = \"yes\"\n", "future_setting = true\n"} { t.Run(contents, func(t *testing.T) { diff --git a/internal/cli/repo_add_test.go b/internal/cli/repo_add_test.go index c441fb2..82da979 100644 --- a/internal/cli/repo_add_test.go +++ b/internal/cli/repo_add_test.go @@ -1,12 +1,15 @@ package cli import ( + "os" "path/filepath" "strings" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" + + "github.com/nnutter/timber/internal/timber" ) func TestRepoAddRemoteURL(t *testing.T) { @@ -47,6 +50,65 @@ func TestRepoAddRemoteURL(t *testing.T) { } } +func TestRepoAddStripsConfiguredGitHubOwner(t *testing.T) { + t.Parallel() + + t.Run("listed owner is stripped", func(t *testing.T) { + t.Parallel() + runtime := githubRedirectRuntime(t, "nnutter/timber") + configure := runTimberCommandWithRuntime(t, runtime, "config", "--strip-github-owner", "NNutter") + require.NoError(t, configure.err, configure.stderr) + + result := runTimberCommandWithRuntime(t, runtime, "repo", "add", "nnutter/timber") + require.NoError(t, result.err, result.stderr) + assert.Contains(t, result.stderr, "added repository timber at") + assert.Equal(t, "git@github.com:nnutter/timber\n", + runGitCommand(t, filepath.Join(runtime.WorktreeRoot, "timber", ".git"), "config", "--local", "--get", "remote.origin.url")) + }) + + t.Run("explicit name wins", func(t *testing.T) { + t.Parallel() + runtime := githubRedirectRuntime(t, "nnutter/timber") + configure := runTimberCommandWithRuntime(t, runtime, "config", "--strip-github-owner", "nnutter") + require.NoError(t, configure.err, configure.stderr) + + result := runTimberCommandWithRuntime(t, runtime, "repo", "add", "--name", "nnutter/timber", "nnutter/timber") + require.NoError(t, result.err, result.stderr) + assert.Contains(t, result.stderr, "added repository nnutter/timber at") + _, err := os.Stat(filepath.Join(runtime.WorktreeRoot, "nnutter", "timber", ".git")) + require.NoError(t, err) + }) + + t.Run("unconfigured owner keeps the structured name", func(t *testing.T) { + t.Parallel() + runtime := githubRedirectRuntime(t, "nnutter/timber") + + result := runTimberCommandWithRuntime(t, runtime, "repo", "add", "nnutter/timber") + require.NoError(t, result.err, result.stderr) + assert.Contains(t, result.stderr, "added repository nnutter/timber at") + // Reading settings must not create the configuration file. + _, err := os.Stat(filepath.Join(runtime.ConfigHome, "timber", "config.toml")) + assert.ErrorIs(t, err, os.ErrNotExist) + }) +} + +// githubRedirectRuntime prepares a runtime whose github.com remote resolves to +// a local bare repository, so repo add never reaches the network. +func githubRedirectRuntime(t *testing.T, ownerRepo string) timber.Runtime { + t.Helper() + runtime := testRuntime(t) + remote := filepath.Join(resolvedTempDir(t), "remote.git") + runGitCommand(t, runtime.HomeDirectory, "init", "--bare", remote) + seedImportRemote(t, remote) + runtime.Environment = append(runtime.Environment, + "GIT_CONFIG_COUNT=1", + "GIT_CONFIG_KEY_0=url."+remote+".insteadOf", + "GIT_CONFIG_VALUE_0=git@github.com:"+ownerRepo, + "GIT_ALLOW_PROTOCOL=file", + ) + return runtime +} + func TestRepoAddAlias(t *testing.T) { t.Parallel() for _, alias := range []string{"", "custom-alias"} { diff --git a/internal/timber/config/owners.go b/internal/timber/config/owners.go new file mode 100644 index 0000000..dd707ca --- /dev/null +++ b/internal/timber/config/owners.go @@ -0,0 +1,64 @@ +package config + +import ( + "fmt" + "slices" + "strings" +) + +// UpdateStripGitHubOwners returns the owner list with add appended and remove +// dropped. GitHub logins are case-insensitive, so matching ignores case and the +// result keeps one spelling per owner. The result is sorted so the +// configuration file stays stable across edits. +func UpdateStripGitHubOwners(current, add, remove []string) ([]string, error) { + additions, err := normalizeGitHubOwners(add) + if err != nil { + return nil, err + } + removals, err := normalizeGitHubOwners(remove) + if err != nil { + return nil, err + } + + owners := make([]string, 0, len(current)+len(additions)) + for _, value := range current { + owner := strings.TrimSpace(value) + if isEmpty(owner) || containsGitHubOwner(removals, owner) || containsGitHubOwner(owners, owner) { + continue + } + owners = append(owners, owner) + } + for _, owner := range additions { + if !containsGitHubOwner(owners, owner) { + owners = append(owners, owner) + } + } + slices.SortFunc(owners, func(left, right string) int { + return strings.Compare(strings.ToLower(left), strings.ToLower(right)) + }) + return owners, nil +} + +func normalizeGitHubOwners(values []string) ([]string, error) { + owners := make([]string, 0, len(values)) + for _, value := range values { + owner := strings.TrimSpace(value) + if isEmpty(owner) { + return nil, fmt.Errorf("a GitHub owner must not be empty") + } + if strings.ContainsAny(owner, "/ \t") { + return nil, fmt.Errorf("expected a single GitHub owner, got %q", owner) + } + owners = append(owners, owner) + } + return owners, nil +} + +func containsGitHubOwner(owners []string, owner string) bool { + for _, candidate := range owners { + if strings.EqualFold(candidate, owner) { + return true + } + } + return false +} diff --git a/internal/timber/config/owners_test.go b/internal/timber/config/owners_test.go new file mode 100644 index 0000000..d9fce5f --- /dev/null +++ b/internal/timber/config/owners_test.go @@ -0,0 +1,77 @@ +package config + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestUpdateStripGitHubOwners(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + current []string + add []string + remove []string + want []string + }{ + { + name: "add to empty list", + add: []string{"nnutter"}, + want: []string{"nnutter"}, + }, + { + name: "adding an existing owner in another case keeps one entry", + current: []string{"nnutter"}, + add: []string{"Nnutter"}, + want: []string{"nnutter"}, + }, + { + name: "removal ignores case", + current: []string{"nnutter", "acme"}, + remove: []string{"ACME"}, + want: []string{"nnutter"}, + }, + { + name: "removing an unlisted owner changes nothing", + current: []string{"nnutter"}, + remove: []string{"other"}, + want: []string{"nnutter"}, + }, + { + name: "owners are sorted case-insensitively", + current: []string{"zeta"}, + add: []string{"Alpha"}, + want: []string{"Alpha", "zeta"}, + }, + { + name: "duplicates in the stored list collapse", + current: []string{"nnutter", "NNutter"}, + want: []string{"nnutter"}, + }, + { + name: "empty entries in the stored list are dropped", + current: []string{"nnutter", " "}, + want: []string{"nnutter"}, + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + got, err := UpdateStripGitHubOwners(test.current, test.add, test.remove) + require.NoError(t, err) + assert.Equal(t, test.want, got) + }) + } +} + +func TestUpdateStripGitHubOwnersRejectsInvalidOwners(t *testing.T) { + t.Parallel() + for _, owner := range []string{"", " ", "nnutter/timber", "nn utter"} { + t.Run(owner, func(t *testing.T) { + t.Parallel() + _, err := UpdateStripGitHubOwners(nil, []string{owner}, nil) + require.Error(t, err) + }) + } +} diff --git a/internal/timber/config/settings.go b/internal/timber/config/settings.go index 40dfe84..d779bcb 100644 --- a/internal/timber/config/settings.go +++ b/internal/timber/config/settings.go @@ -2,8 +2,9 @@ package config // Settings holds the persistent Timber configuration. type Settings struct { - AutoMiseTrust bool `toml:"auto_mise_trust"` - AutoMiseTrustDecided bool `toml:"auto_mise_trust_decided,omitempty"` - AutoHKInstall bool `toml:"auto_hk_install"` - AutoHKInstallDecided bool `toml:"auto_hk_install_decided,omitempty"` + AutoMiseTrust bool `toml:"auto_mise_trust"` + AutoMiseTrustDecided bool `toml:"auto_mise_trust_decided,omitempty"` + AutoHKInstall bool `toml:"auto_hk_install"` + AutoHKInstallDecided bool `toml:"auto_hk_install_decided,omitempty"` + StripGitHubOwners []string `toml:"strip_github_owners,omitempty"` } diff --git a/internal/timber/remote_url.go b/internal/timber/remote_url.go index 7cad6bf..529e433 100644 --- a/internal/timber/remote_url.go +++ b/internal/timber/remote_url.go @@ -147,6 +147,29 @@ func defaultRepoNameFromRemote(remoteURL string) (string, error) { return cleanRepoName(repoPath, remoteURL) } +// stripRepoNameOwner drops a GitHub owner from a derived repository name when +// owners lists that owner. GitHub logins are case-insensitive. Other hosts keep +// their grouping, and a name without an owner stays unchanged. +func stripRepoNameOwner(remoteURL, repoName string, owners []string) string { + if len(owners) == 0 { + return repoName + } + host, _, ok := remoteHostAndPath(remoteURL) + if !ok || !isGitHubHost(host) { + return repoName + } + owner, repo, found := strings.Cut(repoName, "/") + if !found || isEmpty(repo) || strings.Contains(repo, "/") { + return repoName + } + for _, candidate := range owners { + if strings.EqualFold(strings.TrimSpace(candidate), owner) { + return repo + } + } + return repoName +} + func localRepoName(trimmed, remoteURL string) (string, error) { name := strings.TrimSuffix(path.Base(strings.TrimSuffix(trimmed, "/")), bareRepoSuffix) if isReservedPathName(name) { diff --git a/internal/timber/remote_url_test.go b/internal/timber/remote_url_test.go index ee2c798..357ae7b 100644 --- a/internal/timber/remote_url_test.go +++ b/internal/timber/remote_url_test.go @@ -37,6 +37,78 @@ func TestDefaultRepoNameFromRemote(t *testing.T) { assert.Equal(t, "roam", name) } +func TestStripRepoNameOwner(t *testing.T) { + t.Parallel() + for _, test := range []struct { + name string + remoteURL string + repoName string + owners []string + want string + }{ + { + name: "listed github owner is dropped", + remoteURL: "https://github.com/nnutter/timber.git", + repoName: "nnutter/timber", + owners: []string{"nnutter"}, + want: "timber", + }, + { + name: "owner matching ignores case", + remoteURL: "git@github.com:nnutter/timber.git", + repoName: "nnutter/timber", + owners: []string{"NNutter"}, + want: "timber", + }, + { + name: "ssh.github.com counts as github", + remoteURL: "ssh://git@ssh.github.com:443/nnutter/timber.git", + repoName: "nnutter/timber", + owners: []string{"nnutter"}, + want: "timber", + }, + { + name: "unlisted owner keeps the structured name", + remoteURL: "git@github.com:nnutter/timber.git", + repoName: "nnutter/timber", + owners: []string{"acme"}, + want: "nnutter/timber", + }, + { + name: "no configured owners keeps the structured name", + remoteURL: "git@github.com:nnutter/timber.git", + repoName: "nnutter/timber", + want: "nnutter/timber", + }, + { + name: "other hosts keep their grouping", + remoteURL: "git@gitlab.com:group/sub/repo.git", + repoName: "group/sub/repo", + owners: []string{"group"}, + want: "group/sub/repo", + }, + { + name: "local paths have no owner to drop", + remoteURL: "/local/path/roam.git", + repoName: "roam", + owners: []string{"roam"}, + want: "roam", + }, + { + name: "a name without an owner is unchanged", + remoteURL: "https://github.com/nnutter/timber.git", + repoName: "timber", + owners: []string{"nnutter"}, + want: "timber", + }, + } { + t.Run(test.name, func(t *testing.T) { + t.Parallel() + assert.Equal(t, test.want, stripRepoNameOwner(test.remoteURL, test.repoName, test.owners)) + }) + } +} + func TestDefaultRepoAliasFromRemote(t *testing.T) { t.Parallel() for _, origin := range []string{ diff --git a/internal/timber/repo_import.go b/internal/timber/repo_import.go index 9741ef3..c7a688f 100644 --- a/internal/timber/repo_import.go +++ b/internal/timber/repo_import.go @@ -93,10 +93,10 @@ func isZeroCommitHash(hash string) bool { return strings.Trim(hash, "0") == "" } -func defaultRepoNameForImport(source *Repository, mainPath string) string { +func defaultRepoNameForImport(source *Repository, mainPath string, stripOwners []string) string { if result, err := source.git("remote", "get-url", remoteName); err == nil { if name, err := defaultRepoNameFromRemote(result.stdout); err == nil { - return name + return stripRepoNameOwner(result.stdout, name, stripOwners) } } return defaultRepoNameFromPath(mainPath) diff --git a/internal/timber/repo_import_name_test.go b/internal/timber/repo_import_name_test.go index 3a4db0a..61c2028 100644 --- a/internal/timber/repo_import_name_test.go +++ b/internal/timber/repo_import_name_test.go @@ -1,9 +1,12 @@ package timber import ( + "os" + "path/filepath" "testing" "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func TestDefaultRepoNameFromPathStripsGitSuffix(t *testing.T) { @@ -12,3 +15,24 @@ func TestDefaultRepoNameFromPathStripsGitSuffix(t *testing.T) { assert.Equal(t, "roam", defaultRepoNameFromPath("/tmp/src/main/roam.git")) assert.Equal(t, "roam", defaultRepoNameFromPath("/tmp/src/roam")) } + +func TestBuildImportPlanStripsConfiguredOwner(t *testing.T) { + t.Parallel() + repository := newTestRepository(t) + runtime := repository.runtime + executable, err := os.Executable() + require.NoError(t, err) + runtime.TrashExecutable = executable + + sourcePath := filepath.Join(resolvedTempDir(t), "project") + runGitCommand(t, filepath.Dir(sourcePath), "clone", repository.remotePath, sourcePath) + runGitCommand(t, sourcePath, "remote", "set-url", "origin", "git@github.com:nnutter/project.git") + + plan, err := runtime.buildImportPlan(sourcePath, "", []string{"NNutter"}) + require.NoError(t, err) + assert.Equal(t, "project", plan.repoName) + + plan, err = runtime.buildImportPlan(sourcePath, "", nil) + require.NoError(t, err) + assert.Equal(t, "nnutter/project", plan.repoName) +} diff --git a/internal/timber/runtime.go b/internal/timber/runtime.go index d66f266..0511276 100644 --- a/internal/timber/runtime.go +++ b/internal/timber/runtime.go @@ -114,7 +114,11 @@ func (runtime Runtime) AddRepo(source, name, alias string) (string, string, erro if err != nil { return "", "", err } - repoName, err := repoNameForAdd(name, remoteURL) + settings, err := runtime.readConfig() + if err != nil { + return "", "", err + } + repoName, err := repoNameForAdd(name, remoteURL, settings.StripGitHubOwners) if err != nil { return "", "", err } @@ -368,7 +372,11 @@ func (runtime Runtime) ImportRepo(source, name string, reporter ImportReporter) return err } - plan, err := runtime.buildImportPlan(sourcePath, normalizeRepoName(name)) + settings, err := runtime.readConfig() + if err != nil { + return err + } + plan, err := runtime.buildImportPlan(sourcePath, normalizeRepoName(name), settings.StripGitHubOwners) if err != nil { return err } @@ -909,12 +917,12 @@ func (x Runtime) bareRepoPath(repoName string) string { return filepath.Join(x.worktreeRoot(), filepath.FromSlash(repoName), bareRepoSuffix) } -func (x Runtime) buildImportPlan(sourcePath string, requestedName string) (importPlan, error) { +func (x Runtime) buildImportPlan(sourcePath string, requestedName string, stripOwners []string) (importPlan, error) { sourceRepository, err := openImportSource(x, sourcePath) if err != nil { return importPlan{}, err } - return importPlanForRepository(x, sourceRepository, requestedName) + return importPlanForRepository(x, sourceRepository, requestedName, stripOwners) } func (x Runtime) buildRepositoryRenamePlan(oldName string, requestedNewName string) (repositoryRenamePlan, error) { diff --git a/internal/timber/runtime_helpers.go b/internal/timber/runtime_helpers.go index 40bc130..952df82 100644 --- a/internal/timber/runtime_helpers.go +++ b/internal/timber/runtime_helpers.go @@ -13,14 +13,14 @@ import ( coreconfig "github.com/nnutter/timber/internal/timber/config" ) -func repoNameForAdd(name, remoteURL string) (string, error) { +func repoNameForAdd(name, remoteURL string, stripOwners []string) (string, error) { repoName := normalizeRepoName(name) if repoName == "" { - var err error - repoName, err = defaultRepoNameFromRemote(remoteURL) + derived, err := defaultRepoNameFromRemote(remoteURL) if err != nil { return "", err } + repoName = stripRepoNameOwner(remoteURL, derived, stripOwners) } if err := validateRepoName(repoName); err != nil { return "", err diff --git a/internal/timber/runtime_import.go b/internal/timber/runtime_import.go index 2609378..f1f4e89 100644 --- a/internal/timber/runtime_import.go +++ b/internal/timber/runtime_import.go @@ -25,7 +25,7 @@ func importOpenError(x Runtime, sourcePath string, err error) error { return fmt.Errorf("open repository at %s: %w", x.displayHomePath(sourcePath), err) } -func importPlanForRepository(x Runtime, sourceRepository *Repository, requestedName string) (importPlan, error) { +func importPlanForRepository(x Runtime, sourceRepository *Repository, requestedName string, stripOwners []string) (importPlan, error) { mainPath, porcelainWorktrees, err := importMainPath(x, sourceRepository) if err != nil { return importPlan{}, err @@ -36,7 +36,7 @@ func importPlanForRepository(x Runtime, sourceRepository *Repository, requestedN if err != nil { return importPlan{}, err } - plan, err := newImportPlan(x, sourceRepository, requestedName, mainPath) + plan, err := newImportPlan(x, sourceRepository, requestedName, mainPath, stripOwners) if err != nil { return importPlan{}, err } @@ -84,10 +84,10 @@ func importMainPath(x Runtime, sourceRepository *Repository) (string, []porcelai return mainEntry.Path, porcelainWorktrees, nil } -func newImportPlan(x Runtime, sourceRepository *Repository, requestedName, mainPath string) (importPlan, error) { +func newImportPlan(x Runtime, sourceRepository *Repository, requestedName, mainPath string, stripOwners []string) (importPlan, error) { repoName := requestedName if repoName == "" { - repoName = defaultRepoNameForImport(sourceRepository, mainPath) + repoName = defaultRepoNameForImport(sourceRepository, mainPath, stripOwners) } if err := validateRepoName(repoName); err != nil { return importPlan{}, err diff --git a/skills/timber/SKILL.md b/skills/timber/SKILL.md index d90528a..bd46a59 100644 --- a/skills/timber/SKILL.md +++ b/skills/timber/SKILL.md @@ -36,7 +36,8 @@ For detailed checklist editing, use the separate `timber-todo` skill. On a machine without a keyring, such as a headless server or CI, set `GH_TOKEN`. - `timber config` shows settings and creates the configuration file if absent: `$XDG_CONFIG_HOME/timber/config.toml`, falling back to - `~/.config/timber/config.toml`. + `~/.config/timber/config.toml`. `timber config --strip-github-owner ` records a GitHub owner whose repositories `repo add` and `repo import` register under the short name instead of `owner/repo`; `--no-strip-github-owner` removes the owner. + An explicit `--name` still wins, and other hosts keep their grouping. - Bare repositories live at `$TIMBER_WORKTREE_ROOT//.git` (fallback `~/worktrees//.git`). `TIMBER_WORKTREE_ROOT` overrides the default `~/worktrees` checkout root. Preserve the user's environment. - A registered repository records `push.default=current`, so `git push` sends the checked-out branch to the same-named branch on the remote. From 123b586fa47f0e3ac5a4c02e7853200fdf38b548 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Tue, 17 Nov 2026 08:43:41 -0600 Subject: [PATCH 07/12] Refactor: Export ReadConfig for read-only settings loads The config subcommands that only read a setting, and their shell completion, must not create the configuration file. Export the read-only loader so the CLI can load settings without that side effect. Change-Id: I72bd8cd2738e4ed3024bafc7d64cf72c476604c4 --- internal/timber/runtime.go | 40 +++++++++++++++++++------------------- 1 file changed, 20 insertions(+), 20 deletions(-) diff --git a/internal/timber/runtime.go b/internal/timber/runtime.go index 0511276..eb52a76 100644 --- a/internal/timber/runtime.go +++ b/internal/timber/runtime.go @@ -114,7 +114,7 @@ func (runtime Runtime) AddRepo(source, name, alias string) (string, string, erro if err != nil { return "", "", err } - settings, err := runtime.readConfig() + settings, err := runtime.ReadConfig() if err != nil { return "", "", err } @@ -372,7 +372,7 @@ func (runtime Runtime) ImportRepo(source, name string, reporter ImportReporter) return err } - settings, err := runtime.readConfig() + settings, err := runtime.ReadConfig() if err != nil { return err } @@ -621,6 +621,23 @@ func (x Runtime) QueryWorktreeNamesAcrossRepos(toComplete string) ([]string, err return completions, nil } +// ReadConfig loads the persistent settings without creating the file. A +// missing file describes the default settings. +func (x Runtime) ReadConfig() (config, error) { + var settings config + metadata, err := toml.DecodeFile(x.configPath(), &settings) + if errors.Is(err, os.ErrNotExist) { + return config{}, nil + } + if err != nil { + return config{}, fmt.Errorf("read config: %w", err) + } + if keys := metadata.Undecoded(); len(keys) != 0 { + return config{}, fmt.Errorf("unknown config setting: %s", keys[0]) + } + return settings, nil +} + func (runtime Runtime) RemoveRepo(repoName string) error { repository, repo, err := runtime.openRegisteredRepository(repoName) if err != nil { @@ -1711,7 +1728,7 @@ func (x Runtime) loadConfig() (config, error) { if err := x.ensureConfigFile(); err != nil { return config{}, err } - return x.readConfig() + return x.ReadConfig() } // managedWorktreePath returns @@ -1996,23 +2013,6 @@ func (runtime Runtime) pullRequestTarget(input io.Reader, draft PullRequestDraft return pullRequestTarget{remote: remote, owner: owner, repo: repo, head: head, base: base, headSHA: headSHA}, nil } -// readConfig loads the persistent settings without creating the file. A -// missing file describes the default settings. -func (x Runtime) readConfig() (config, error) { - var settings config - metadata, err := toml.DecodeFile(x.configPath(), &settings) - if errors.Is(err, os.ErrNotExist) { - return config{}, nil - } - if err != nil { - return config{}, fmt.Errorf("read config: %w", err) - } - if keys := metadata.Undecoded(); len(keys) != 0 { - return config{}, fmt.Errorf("unknown config setting: %s", keys[0]) - } - return settings, nil -} - // Standard-layout worktrees predate explicit name records. An empty name // identifies a manual checkout whose name must be derived from its path. // recordMovedWorktreeName preserves the worktree's selector name when the From e1ef73c0a2449f4a6d321afdedf1f442bede2dcc Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Tue, 17 Nov 2026 08:46:04 -0600 Subject: [PATCH 08/12] Add a typed config key registry The config subcommands need one place that knows which settings a user may change, how each value is typed, and how list values normalize. Describe each setting once so get, set, append, remove, and shell completion share it. The keys that record a setup-prompt answer stay internal; setting or removing a prompted setting updates its decided key. Change-Id: I17d173b65943b8ca9b56eac57dbf4da89194e266 --- internal/timber/config/keys.go | 208 ++++++++++++++++++++++++++++ internal/timber/config/keys_test.go | 98 +++++++++++++ 2 files changed, 306 insertions(+) create mode 100644 internal/timber/config/keys.go create mode 100644 internal/timber/config/keys_test.go diff --git a/internal/timber/config/keys.go b/internal/timber/config/keys.go new file mode 100644 index 0000000..a43caa6 --- /dev/null +++ b/internal/timber/config/keys.go @@ -0,0 +1,208 @@ +package config + +import ( + "fmt" + "slices" + "strconv" + "strings" +) + +// Kind describes how a setting holds its value. +type Kind int + +const ( + // KindBool holds true or false. + KindBool Kind = iota + // KindList holds a list of strings. + KindList +) + +// Key describes one setting a user may get and change. The *_decided keys that +// record a setup-prompt answer stay internal: set and remove update them. +type Key struct { + Name string + Kind Kind + Description string + + get func(*Settings) []string + set func(*Settings, []string) error + append func(*Settings, []string) error + remove func(*Settings, []string) error +} + +// Keys returns the configurable settings in name order. +func Keys() []Key { + return slices.Clone(keys) +} + +// KeyNames returns the configurable setting names in name order. +func KeyNames() []string { + names := make([]string, 0, len(keys)) + for _, key := range keys { + names = append(names, key.Name) + } + return names +} + +// Get returns the values stored for name. A boolean setting always reports one +// value; a list setting reports none when it is empty. +func Get(settings Settings, name string) ([]string, error) { + key, err := lookupKey(name) + if err != nil { + return nil, err + } + return key.get(&settings), nil +} + +// Set replaces the value of name. A boolean setting takes one value; a list +// setting takes the values that replace it. Setting a prompted setting also +// records the answer, so its setup prompt stops asking. +func Set(settings *Settings, name string, values []string) error { + key, err := lookupKey(name) + if err != nil { + return err + } + return key.set(settings, values) +} + +// Append adds values to a list setting. A boolean setting has nothing to +// append to. +func Append(settings *Settings, name string, values []string) error { + key, err := lookupKey(name) + if err != nil { + return err + } + return key.append(settings, values) +} + +// Remove resets name to its default, or removes matching values from a list +// setting. Boolean settings take no values because they always hold one. +func Remove(settings *Settings, name string, values []string) error { + key, err := lookupKey(name) + if err != nil { + return err + } + return key.remove(settings, values) +} + +var keys = []Key{ + boolSetting( + "auto_hk_install", + "Install hk hooks in worktrees owned by you or your GitHub organizations", + func(settings *Settings) *bool { return &settings.AutoHKInstall }, + func(settings *Settings) *bool { return &settings.AutoHKInstallDecided }, + ), + boolSetting( + "auto_mise_trust", + "Trust mise.toml in worktrees owned by you or your GitHub organizations", + func(settings *Settings) *bool { return &settings.AutoMiseTrust }, + func(settings *Settings) *bool { return &settings.AutoMiseTrustDecided }, + ), + listSetting( + "strip_github_owners", + "GitHub owners whose repositories register under the short name", + func(settings *Settings) *[]string { return &settings.StripGitHubOwners }, + UpdateStripGitHubOwners, + ), +} + +// boolSetting describes a boolean setting. decided names the key that records +// the setup-prompt answer, so set and remove keep it in step; a nil decided +// means the setting has no prompt. +func boolSetting(name, description string, value, decided func(*Settings) *bool) Key { + return Key{ + Name: name, + Kind: KindBool, + Description: description, + get: func(settings *Settings) []string { + return []string{strconv.FormatBool(*value(settings))} + }, + set: func(settings *Settings, values []string) error { + parsed, err := boolValue(name, values) + if err != nil { + return err + } + *value(settings) = parsed + if decided != nil { + *decided(settings) = true + } + return nil + }, + append: func(*Settings, []string) error { + return fmt.Errorf("setting %q is a boolean; only list settings can be appended", name) + }, + remove: func(settings *Settings, values []string) error { + if len(values) != 0 { + return fmt.Errorf("setting %q is a boolean; use set %s false to clear it", name, name) + } + *value(settings) = false + if decided != nil { + *decided(settings) = false + } + return nil + }, + } +} + +// listSetting describes a list setting. normalize validates incoming values and +// applies them to the stored list. +func listSetting(name, description string, list func(*Settings) *[]string, normalize func([]string, []string, []string) ([]string, error)) Key { + return Key{ + Name: name, + Kind: KindList, + Description: description, + get: func(settings *Settings) []string { + return slices.Clone(*list(settings)) + }, + set: func(settings *Settings, values []string) error { + normalized, err := normalize(nil, values, nil) + if err != nil { + return err + } + *list(settings) = normalized + return nil + }, + append: func(settings *Settings, values []string) error { + normalized, err := normalize(*list(settings), values, nil) + if err != nil { + return err + } + *list(settings) = normalized + return nil + }, + remove: func(settings *Settings, values []string) error { + current := *list(settings) + if len(values) == 0 { + // Removing the setting clears the list. + current = nil + } + normalized, err := normalize(current, nil, values) + if err != nil { + return err + } + *list(settings) = normalized + return nil + }, + } +} + +// boolValue parses the single value a boolean setting takes. +func boolValue(name string, values []string) (bool, error) { + if len(values) != 1 { + return false, fmt.Errorf("setting %q takes one value, true or false", name) + } + parsed, err := strconv.ParseBool(values[0]) + if err != nil { + return false, fmt.Errorf("setting %q needs true or false, got %q", name, values[0]) + } + return parsed, nil +} + +func lookupKey(name string) (Key, error) { + for _, key := range keys { + if key.Name == name { + return key, nil + } + } + return Key{}, fmt.Errorf("unknown config setting %q; valid settings are: %s", name, strings.Join(KeyNames(), ", ")) +} diff --git a/internal/timber/config/keys_test.go b/internal/timber/config/keys_test.go new file mode 100644 index 0000000..39e6277 --- /dev/null +++ b/internal/timber/config/keys_test.go @@ -0,0 +1,98 @@ +package config + +import ( + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestConfigKeysExposeSettingsInNameOrder(t *testing.T) { + t.Parallel() + assert.Equal(t, []string{"auto_hk_install", "auto_mise_trust", "strip_github_owners"}, KeyNames()) + for _, key := range Keys() { + assert.NotEmpty(t, key.Description, "setting %q needs a description", key.Name) + } + // The keys that only remember a setup-prompt answer are not configurable. + _, err := Get(Settings{}, "auto_mise_trust_decided") + require.Error(t, err) +} + +func TestConfigGet(t *testing.T) { + t.Parallel() + settings := Settings{AutoMiseTrust: true, StripGitHubOwners: []string{"nnutter"}} + + values, err := Get(settings, "auto_mise_trust") + require.NoError(t, err) + assert.Equal(t, []string{"true"}, values) + + values, err = Get(settings, "strip_github_owners") + require.NoError(t, err) + assert.Equal(t, []string{"nnutter"}, values) + + values, err = Get(Settings{}, "strip_github_owners") + require.NoError(t, err) + assert.Empty(t, values) + + _, err = Get(settings, "future_setting") + require.Error(t, err) + assert.Contains(t, err.Error(), "auto_hk_install, auto_mise_trust, strip_github_owners") +} + +func TestConfigSetBoolRecordsTheDecision(t *testing.T) { + t.Parallel() + var settings Settings + require.NoError(t, Set(&settings, "auto_mise_trust", []string{"true"})) + assert.True(t, settings.AutoMiseTrust) + assert.True(t, settings.AutoMiseTrustDecided) + + require.NoError(t, Set(&settings, "auto_hk_install", []string{"false"})) + assert.False(t, settings.AutoHKInstall) + assert.True(t, settings.AutoHKInstallDecided) +} + +func TestConfigSetRejectsInvalidValues(t *testing.T) { + t.Parallel() + settings := Settings{StripGitHubOwners: []string{"nnutter"}} + require.Error(t, Set(&settings, "auto_mise_trust", []string{"yes"})) + require.Error(t, Set(&settings, "auto_mise_trust", []string{"true", "false"})) + require.Error(t, Set(&settings, "strip_github_owners", []string{"nnutter/timber"})) + // A rejected value leaves the setting untouched. + assert.Equal(t, []string{"nnutter"}, settings.StripGitHubOwners) +} + +func TestConfigSetListReplacesValues(t *testing.T) { + t.Parallel() + settings := Settings{StripGitHubOwners: []string{"nnutter"}} + require.NoError(t, Set(&settings, "strip_github_owners", []string{"acme"})) + assert.Equal(t, []string{"acme"}, settings.StripGitHubOwners) +} + +func TestConfigAppend(t *testing.T) { + t.Parallel() + var settings Settings + require.NoError(t, Append(&settings, "strip_github_owners", []string{"nnutter", "acme"})) + require.NoError(t, Append(&settings, "strip_github_owners", []string{"NNutter"})) + assert.Equal(t, []string{"acme", "nnutter"}, settings.StripGitHubOwners) + require.Error(t, Append(&settings, "auto_mise_trust", []string{"true"})) +} + +func TestConfigRemove(t *testing.T) { + t.Parallel() + settings := Settings{ + AutoMiseTrust: true, + AutoMiseTrustDecided: true, + StripGitHubOwners: []string{"acme", "nnutter"}, + } + + require.NoError(t, Remove(&settings, "strip_github_owners", []string{"ACME"})) + assert.Equal(t, []string{"nnutter"}, settings.StripGitHubOwners) + require.Error(t, Remove(&settings, "auto_mise_trust", []string{"true"})) + + require.NoError(t, Remove(&settings, "auto_mise_trust", nil)) + assert.False(t, settings.AutoMiseTrust) + assert.False(t, settings.AutoMiseTrustDecided) + + require.NoError(t, Remove(&settings, "strip_github_owners", nil)) + assert.Empty(t, settings.StripGitHubOwners) +} From 1058f553a01f800c4eeabca31bbc9996db4b1f14 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Tue, 17 Nov 2026 08:54:00 -0600 Subject: [PATCH 09/12] Build config subcommands on the key registry `timber config` grew a flag for every setting and a matching no- flag to clear it. That does not extend to list settings and hides the key names from completion. Replace the flags with show, get, set, append, and remove subcommands that name settings directly and complete them. remove resets a setting to its default or drops matching list values, and the setup prompts now point at `timber config set ...`. Change-Id: I458b1f90284fedf7d769bbeff7cd7b6d093af7a0 --- internal/cli/complete/complete.go | 84 +++++++++++ internal/cli/completion_functional_test.go | 21 +++ internal/cli/config/config.go | 137 +++++++++++------- internal/cli/config_test.go | 155 ++++++++++++--------- internal/cli/hk_install_assert_test.go | 10 +- internal/cli/hk_install_test.go | 4 +- internal/cli/mise_trust_case_test.go | 8 +- internal/cli/repo_add_test.go | 4 +- internal/cli/setup_prompt.go | 4 +- internal/timber/config/keys.go | 11 +- 10 files changed, 307 insertions(+), 131 deletions(-) diff --git a/internal/cli/complete/complete.go b/internal/cli/complete/complete.go index 0e097e9..28bbcca 100644 --- a/internal/cli/complete/complete.go +++ b/internal/cli/complete/complete.go @@ -8,6 +8,8 @@ import ( "strings" "github.com/spf13/cobra" + + coreconfig "github.com/nnutter/timber/internal/timber/config" ) // Queries supplies the completion candidates. @@ -177,3 +179,85 @@ func canonicalName(command *cobra.Command, word string) (string, bool) { } return "", false } + +// ConfigReader supplies stored settings for config value completion. +type ConfigReader interface { + ReadConfig() (coreconfig.Settings, error) +} + +// ConfigValueMode selects which values a config command offers. +type ConfigValueMode int + +const ( + // ConfigValueSet offers true and false for boolean settings. + ConfigValueSet ConfigValueMode = iota + // ConfigValueRemove offers the stored values of a list setting. + ConfigValueRemove + // ConfigValueNone offers no value candidates. + ConfigValueNone +) + +// ConfigArgs completes config setting names, then the value that suits the +// selected setting and command. +func ConfigArgs(reader ConfigReader, mode ConfigValueMode) func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) { + return func(_ *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) { + if len(args) == 0 { + candidates := make([]string, 0) + for _, key := range coreconfig.Keys() { + candidates = append(candidates, key.Name+" "+key.Description) + } + return matchingPrefix(candidates, toComplete), cobra.ShellCompDirectiveNoFileComp + } + if len(args) > 1 { + return nil, cobra.ShellCompDirectiveNoFileComp + } + switch mode { + case ConfigValueSet: + return matchingPrefix(boolValues(args[0]), toComplete), cobra.ShellCompDirectiveNoFileComp + case ConfigValueRemove: + return listValues(reader, args[0], toComplete) + default: + return nil, cobra.ShellCompDirectiveNoFileComp + } + } +} + +func boolValues(name string) []string { + key, err := coreconfig.LookupKey(name) + if err != nil { + return nil + } + if key.Kind != coreconfig.KindBool { + return nil + } + return []string{"true", "false"} +} + +func listValues(reader ConfigReader, name, toComplete string) ([]string, cobra.ShellCompDirective) { + key, err := coreconfig.LookupKey(name) + if err != nil { + return nil, cobra.ShellCompDirectiveNoFileComp + } + if key.Kind != coreconfig.KindList { + return nil, cobra.ShellCompDirectiveNoFileComp + } + settings, err := reader.ReadConfig() + if err != nil { + return nil, cobra.ShellCompDirectiveError + } + values, err := coreconfig.Get(settings, name) + if err != nil { + return nil, cobra.ShellCompDirectiveError + } + return matchingPrefix(values, toComplete), cobra.ShellCompDirectiveNoFileComp +} + +func matchingPrefix(candidates []string, prefix string) []string { + matches := make([]string, 0, len(candidates)) + for _, candidate := range candidates { + if strings.HasPrefix(candidate, prefix) { + matches = append(matches, candidate) + } + } + return matches +} diff --git a/internal/cli/completion_functional_test.go b/internal/cli/completion_functional_test.go index c51b610..6aa620f 100644 --- a/internal/cli/completion_functional_test.go +++ b/internal/cli/completion_functional_test.go @@ -49,6 +49,27 @@ func TestWorktreeCompletionAddsAtWhenNameIsAmbiguous(t *testing.T) { assert.Contains(t, qualified, at(secondaryName, "feature/login")) } +func TestConfigCompletionOffersSettingsAndValues(t *testing.T) { + t.Parallel() + runtime := testRuntime(t) + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "append", "strip_github_owners", "nnutter").err) + + keys := runCompleteWithRuntime(t, runtime, "config", "get", "") + assert.Contains(t, keys, "auto_mise_trust\t") + assert.Contains(t, keys, "strip_github_owners\t") + assert.NotContains(t, keys, "auto_mise_trust_decided") + + values := runCompleteWithRuntime(t, runtime, "config", "set", "auto_mise_trust", "") + assert.Contains(t, values, "true") + assert.Contains(t, values, "false") + + owners := runCompleteWithRuntime(t, runtime, "config", "remove", "strip_github_owners", "") + assert.Contains(t, owners, "nnutter") + + // Appending takes values that do not exist yet, so there is nothing to offer. + assert.NotContains(t, runCompleteWithRuntime(t, runtime, "config", "append", "auto_mise_trust", ""), "true") +} + func TestAliasCompletionExpandsToCommandName(t *testing.T) { t.Parallel() testRepository := newTestRepository(t) diff --git a/internal/cli/config/config.go b/internal/cli/config/config.go index 5e21d90..f49552a 100644 --- a/internal/cli/config/config.go +++ b/internal/cli/config/config.go @@ -1,94 +1,133 @@ package config import ( + "fmt" + "github.com/BurntSushi/toml" "github.com/spf13/cobra" + "github.com/nnutter/timber/internal/cli/complete" coreconfig "github.com/nnutter/timber/internal/timber/config" ) // Store loads and saves Timber settings. type Store interface { LoadConfig() (coreconfig.Settings, error) + ReadConfig() (coreconfig.Settings, error) SaveConfig(coreconfig.Settings) error } +// New constructs the config command and its subcommands. func New(store Store) *cobra.Command { - var enable, disable, enableHK, disableHK bool - var stripOwners, noStripOwners []string command := &cobra.Command{ Use: "config", Short: "Show or change Timber settings", Args: cobra.NoArgs, + RunE: func(command *cobra.Command, _ []string) error { + return command.Help() + }, + } + command.AddCommand( + showCommand(store), + getCommand(store), + setCommand(store), + appendCommand(store), + removeCommand(store), + ) + return command +} + +func showCommand(store Store) *cobra.Command { + return &cobra.Command{ + Use: "show", + Short: "Show all settings", + Args: cobra.NoArgs, RunE: func(command *cobra.Command, _ []string) error { settings, err := store.LoadConfig() if err != nil { return err } - changed := applyAutoMiseTrust(command, &settings, enable, disable) - if applyAutoHKInstall(command, &settings, enableHK, disableHK) { - changed = true + return toml.NewEncoder(command.OutOrStdout()).Encode(settings) + }, + } +} + +func getCommand(store Store) *cobra.Command { + return &cobra.Command{ + Use: "get ", + Short: "Print a setting's value", + Args: cobra.ExactArgs(1), + ValidArgsFunction: complete.ConfigArgs(store, complete.ConfigValueNone), + RunE: func(command *cobra.Command, args []string) error { + settings, err := store.ReadConfig() + if err != nil { + return err } - if command.Flags().Changed("strip-github-owner") || command.Flags().Changed("no-strip-github-owner") { - if err := applyStripGitHubOwners(&settings, stripOwners, noStripOwners); err != nil { - return err - } - changed = true + values, err := coreconfig.Get(settings, args[0]) + if err != nil { + return err } - if changed { - if err := store.SaveConfig(settings); err != nil { + for _, value := range values { + if _, err := fmt.Fprintln(command.OutOrStdout(), value); err != nil { return err } } - return toml.NewEncoder(command.OutOrStdout()).Encode(settings) + return nil }, } - command.Flags().BoolVar(&enable, "auto-mise-trust", false, "Trust mise.toml in worktrees owned by you or your GitHub organizations") - command.Flags().BoolVar(&disable, "no-auto-mise-trust", false, "Disable automatic mise trust") - command.MarkFlagsMutuallyExclusive("auto-mise-trust", "no-auto-mise-trust") - command.Flags().BoolVar(&enableHK, "auto-hk-install", false, "Install hk hooks in worktrees owned by you or your GitHub organizations") - command.Flags().BoolVar(&disableHK, "no-auto-hk-install", false, "Disable automatic hk hook installation") - command.MarkFlagsMutuallyExclusive("auto-hk-install", "no-auto-hk-install") - command.Flags().StringArrayVar(&stripOwners, "strip-github-owner", nil, "Drop this GitHub owner from repository names derived from remotes (repeatable)") - command.Flags().StringArrayVar(&noStripOwners, "no-strip-github-owner", nil, "Stop dropping this GitHub owner from repository names (repeatable)") - command.MarkFlagsMutuallyExclusive("strip-github-owner", "no-strip-github-owner") - return command } -// applyAutoMiseTrust records the automatic mise trust flags and reports whether -// they changed the settings. -func applyAutoMiseTrust(command *cobra.Command, settings *coreconfig.Settings, enable, disable bool) bool { - if !command.Flags().Changed("auto-mise-trust") && !command.Flags().Changed("no-auto-mise-trust") { - return false - } - settings.AutoMiseTrust = enable - if command.Flags().Changed("no-auto-mise-trust") { - settings.AutoMiseTrust = !disable +func setCommand(store Store) *cobra.Command { + return &cobra.Command{ + Use: "set ", + Short: "Set a setting's value", + Args: cobra.ExactArgs(2), + ValidArgsFunction: complete.ConfigArgs(store, complete.ConfigValueSet), + RunE: func(_ *cobra.Command, args []string) error { + return changeSettings(store, func(settings *coreconfig.Settings) error { + return coreconfig.Set(settings, args[0], args[1:]) + }) + }, } - settings.AutoMiseTrustDecided = true - return true } -// applyAutoHKInstall records the automatic hk install flags and reports whether -// they changed the settings. -func applyAutoHKInstall(command *cobra.Command, settings *coreconfig.Settings, enable, disable bool) bool { - if !command.Flags().Changed("auto-hk-install") && !command.Flags().Changed("no-auto-hk-install") { - return false +func appendCommand(store Store) *cobra.Command { + return &cobra.Command{ + Use: "append ...", + Short: "Append values to a list setting", + Args: cobra.MinimumNArgs(2), + ValidArgsFunction: complete.ConfigArgs(store, complete.ConfigValueNone), + RunE: func(_ *cobra.Command, args []string) error { + return changeSettings(store, func(settings *coreconfig.Settings) error { + return coreconfig.Append(settings, args[0], args[1:]) + }) + }, } - settings.AutoHKInstall = enable - if command.Flags().Changed("no-auto-hk-install") { - settings.AutoHKInstall = !disable +} + +func removeCommand(store Store) *cobra.Command { + return &cobra.Command{ + Use: "remove [value...]", + Aliases: []string{"rm"}, + Short: "Reset a setting or remove list values", + Args: cobra.MinimumNArgs(1), + ValidArgsFunction: complete.ConfigArgs(store, complete.ConfigValueRemove), + RunE: func(_ *cobra.Command, args []string) error { + return changeSettings(store, func(settings *coreconfig.Settings) error { + return coreconfig.Remove(settings, args[0], args[1:]) + }) + }, } - settings.AutoHKInstallDecided = true - return true } -// applyStripGitHubOwners records the owner list flags. -func applyStripGitHubOwners(settings *coreconfig.Settings, add, remove []string) error { - owners, err := coreconfig.UpdateStripGitHubOwners(settings.StripGitHubOwners, add, remove) +// changeSettings loads the settings, applies change, and saves the result. +func changeSettings(store Store, change func(*coreconfig.Settings) error) error { + settings, err := store.LoadConfig() if err != nil { return err } - settings.StripGitHubOwners = owners - return nil + if err := change(&settings); err != nil { + return err + } + return store.SaveConfig(settings) } diff --git a/internal/cli/config_test.go b/internal/cli/config_test.go index 1238a6d..128b8d9 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -9,75 +9,106 @@ import ( "github.com/stretchr/testify/require" ) -func TestConfigPersistsSettingsUnderXDGConfigHome(t *testing.T) { +func TestConfigShowUsesXDGConfigHome(t *testing.T) { runtime := testRuntime(t) runtime.ConfigHome = filepath.Join(resolvedTempDir(t), "custom-config") - for _, step := range []struct { - args []string - want string - }{ - {[]string{"config"}, "auto_mise_trust = false\nauto_hk_install = false\n"}, - {[]string{"config", "--auto-mise-trust"}, "auto_mise_trust = true\nauto_mise_trust_decided = true\nauto_hk_install = false\n"}, - {[]string{"config"}, "auto_mise_trust = true\nauto_mise_trust_decided = true\nauto_hk_install = false\n"}, - {[]string{"config", "--no-auto-mise-trust"}, "auto_mise_trust = false\nauto_mise_trust_decided = true\nauto_hk_install = false\n"}, - {[]string{"config"}, "auto_mise_trust = false\nauto_mise_trust_decided = true\nauto_hk_install = false\n"}, - {[]string{"config", "--auto-hk-install"}, "auto_mise_trust = false\nauto_mise_trust_decided = true\nauto_hk_install = true\nauto_hk_install_decided = true\n"}, - {[]string{"config"}, "auto_mise_trust = false\nauto_mise_trust_decided = true\nauto_hk_install = true\nauto_hk_install_decided = true\n"}, - {[]string{"config", "--no-auto-hk-install"}, "auto_mise_trust = false\nauto_mise_trust_decided = true\nauto_hk_install = false\nauto_hk_install_decided = true\n"}, - {[]string{"config"}, "auto_mise_trust = false\nauto_mise_trust_decided = true\nauto_hk_install = false\nauto_hk_install_decided = true\n"}, - } { - result := runTimberCommandWithRuntime(t, runtime, step.args...) - require.NoError(t, result.err) - assert.Equal(t, step.want, result.stdout) - contents, err := os.ReadFile(filepath.Join(runtime.ConfigHome, "timber", "config.toml")) - require.NoError(t, err) - assert.Equal(t, step.want, string(contents)) - } - result := runTimberCommandWithRuntime(t, runtime, "config", "--auto-mise-trust", "--no-auto-mise-trust") - require.Error(t, result.err) - assert.Contains(t, result.err.Error(), "none of the others can be") - result = runTimberCommandWithRuntime(t, runtime, "config", "--auto-hk-install", "--no-auto-hk-install") - require.Error(t, result.err) - assert.Contains(t, result.err.Error(), "none of the others can be") + configPath := filepath.Join(runtime.ConfigHome, "timber", "config.toml") + _, statErr := os.Stat(configPath) + require.ErrorIs(t, statErr, os.ErrNotExist) + + result := runTimberCommandWithRuntime(t, runtime, "config", "show") + require.NoError(t, result.err) + want := "auto_mise_trust = false\nauto_hk_install = false\n" + assert.Equal(t, want, result.stdout) + contents, err := os.ReadFile(configPath) + require.NoError(t, err) + assert.Equal(t, want, string(contents)) } -func TestConfigManagesStripGitHubOwners(t *testing.T) { +func TestConfigSetAndGet(t *testing.T) { runtime := testRuntime(t) - configPath := filepath.Join(runtime.ConfigHome, "timber", "config.toml") - for _, step := range []struct { - args []string - want string - }{ - { - []string{"config", "--strip-github-owner", "nnutter"}, - "auto_mise_trust = false\nauto_hk_install = false\nstrip_github_owners = [\"nnutter\"]\n", - }, - { - []string{"config", "--strip-github-owner", "acme", "--strip-github-owner", "Nnutter"}, - "auto_mise_trust = false\nauto_hk_install = false\nstrip_github_owners = [\"acme\", \"nnutter\"]\n", - }, - { - []string{"config", "--no-strip-github-owner", "ACME"}, - "auto_mise_trust = false\nauto_hk_install = false\nstrip_github_owners = [\"nnutter\"]\n", - }, + set := runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_mise_trust", "true") + require.NoError(t, set.err) + assert.Empty(t, set.stdout) + + show := runTimberCommandWithRuntime(t, runtime, "config", "show") + require.NoError(t, show.err) + assert.Equal(t, "auto_mise_trust = true\nauto_mise_trust_decided = true\nauto_hk_install = false\n", show.stdout) + + get := runTimberCommandWithRuntime(t, runtime, "config", "get", "auto_mise_trust") + require.NoError(t, get.err) + assert.Equal(t, "true\n", get.stdout) + + get = runTimberCommandWithRuntime(t, runtime, "config", "get", "strip_github_owners") + require.NoError(t, get.err) + assert.Empty(t, get.stdout) + + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "set", "strip_github_owners", "nnutter").err) + get = runTimberCommandWithRuntime(t, runtime, "config", "get", "strip_github_owners") + require.NoError(t, get.err) + assert.Equal(t, "nnutter\n", get.stdout) +} + +func TestConfigAppendAndRemoveListValues(t *testing.T) { + runtime := testRuntime(t) + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "append", "strip_github_owners", "nnutter", "acme").err) + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "append", "strip_github_owners", "NNutter").err) + + get := runTimberCommandWithRuntime(t, runtime, "config", "get", "strip_github_owners") + require.NoError(t, get.err) + assert.Equal(t, "acme\nnnutter\n", get.stdout) + + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "rm", "strip_github_owners", "ACME").err) + get = runTimberCommandWithRuntime(t, runtime, "config", "get", "strip_github_owners") + require.NoError(t, get.err) + assert.Equal(t, "nnutter\n", get.stdout) + + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "remove", "strip_github_owners").err) + get = runTimberCommandWithRuntime(t, runtime, "config", "get", "strip_github_owners") + require.NoError(t, get.err) + assert.Empty(t, get.stdout) +} + +func TestConfigRemoveBoolClearsTheDecision(t *testing.T) { + runtime := testRuntime(t) + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_hk_install", "true").err) + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "remove", "auto_hk_install").err) + + show := runTimberCommandWithRuntime(t, runtime, "config", "show") + require.NoError(t, show.err) + assert.Equal(t, "auto_mise_trust = false\nauto_hk_install = false\n", show.stdout) +} + +func TestConfigRejectsUnknownSettingsAndInvalidValues(t *testing.T) { + runtime := testRuntime(t) + for _, args := range [][]string{ + {"config", "get", "future_setting"}, + {"config", "set", "future_setting", "true"}, + {"config", "set", "auto_mise_trust", "yes"}, + {"config", "set", "strip_github_owners", "nnutter/timber"}, + {"config", "append", "auto_mise_trust", "true"}, + {"config", "remove", "auto_mise_trust", "true"}, } { - result := runTimberCommandWithRuntime(t, runtime, step.args...) - require.NoError(t, result.err) - assert.Equal(t, step.want, result.stdout) - contents, err := os.ReadFile(configPath) - require.NoError(t, err) - assert.Equal(t, step.want, string(contents)) + result := runTimberCommandWithRuntime(t, runtime, args...) + require.Error(t, result.err, "args=%v", args) } - result := runTimberCommandWithRuntime(t, runtime, "config", "--strip-github-owner", "nnutter/timber") - require.Error(t, result.err) - assert.Contains(t, result.err.Error(), "expected a single GitHub owner") - result = runTimberCommandWithRuntime(t, runtime, "config", "--strip-github-owner", "nnutter", "--no-strip-github-owner", "acme") - require.Error(t, result.err) - assert.Contains(t, result.err.Error(), "none of the others can be") - contents, err := os.ReadFile(configPath) - require.NoError(t, err) - assert.Equal(t, "auto_mise_trust = false\nauto_hk_install = false\nstrip_github_owners = [\"nnutter\"]\n", string(contents)) + // None of the failures changed a setting. + show := runTimberCommandWithRuntime(t, runtime, "config", "show") + require.NoError(t, show.err) + assert.Equal(t, "auto_mise_trust = false\nauto_hk_install = false\n", show.stdout) +} + +func TestConfigWithoutSubcommandShowsHelp(t *testing.T) { + runtime := testRuntime(t) + result := runTimberCommandWithRuntime(t, runtime, "config") + require.NoError(t, result.err) + assert.Contains(t, result.stdout, "show") + assert.Contains(t, result.stdout, "append") + + // Help must not create the settings file. + _, err := os.Stat(filepath.Join(runtime.ConfigHome, "timber", "config.toml")) + assert.ErrorIs(t, err, os.ErrNotExist) } func TestConfigDoesNotOverwriteInvalidOrUnknownSettings(t *testing.T) { @@ -87,7 +118,7 @@ func TestConfigDoesNotOverwriteInvalidOrUnknownSettings(t *testing.T) { path := filepath.Join(runtime.ConfigHome, "timber", "config.toml") require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o700)) require.NoError(t, os.WriteFile(path, []byte(contents), 0o600)) - result := runTimberCommandWithRuntime(t, runtime, "config", "--auto-mise-trust") + result := runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_mise_trust", "true") require.Error(t, result.err) after, err := os.ReadFile(path) require.NoError(t, err) diff --git a/internal/cli/hk_install_assert_test.go b/internal/cli/hk_install_assert_test.go index 2cb4d79..091abb3 100644 --- a/internal/cli/hk_install_assert_test.go +++ b/internal/cli/hk_install_assert_test.go @@ -18,16 +18,16 @@ func configureHKInstallRuntime(t *testing.T, runtime timber.Runtime, enabled, ex t.Helper() runtime.GhExecutable = filepath.Join(resolvedTempDir(t), "missing-gh") if enabled { - result := runTimberCommandWithRuntime(t, runtime, "config", "--auto-hk-install") + result := runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_hk_install", "true") require.NoError(t, result.err) } if explicitDisable { - result := runTimberCommandWithRuntime(t, runtime, "config", "--no-auto-hk-install") + result := runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_hk_install", "false") require.NoError(t, result.err) } if interactive { // Keep automatic mise trust from asking its own question first. - result := runTimberCommandWithRuntime(t, runtime, "config", "--no-auto-mise-trust") + result := runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_mise_trust", "false") require.NoError(t, result.err) } writeHKInstallCache(t, runtime, cache, noOrganizations) @@ -129,7 +129,7 @@ func assertHKInstallPrompt(t *testing.T, runtime timber.Runtime, result commandR func assertHKInstallRefusal(t *testing.T, runtime timber.Runtime, result commandResult, logPath, timberBin string, wantInstall bool, answer string) { t.Helper() if !wantInstall { - assert.Contains(t, result.stderr, "Enable it later with: timber config --auto-hk-install") + assert.Contains(t, result.stderr, "Enable it later with: timber config set auto_hk_install true") } again := interactiveCreate(t, runtime, timberBin, answer, "second") require.NoError(t, again.err) @@ -139,7 +139,7 @@ func assertHKInstallRefusal(t *testing.T, runtime timber.Runtime, result command } assert.NoFileExists(t, logPath) // The documented command can reverse a saved refusal. - require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "--auto-hk-install").err) + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_hk_install", "true").err) require.NoError(t, runTimberCommandWithRuntime(t, runtime, "create", "--upstream", "source/main", at(testRepoName, "third")).err) assert.FileExists(t, logPath) } diff --git a/internal/cli/hk_install_test.go b/internal/cli/hk_install_test.go index 82b3b0f..bb53f19 100644 --- a/internal/cli/hk_install_test.go +++ b/internal/cli/hk_install_test.go @@ -136,8 +136,8 @@ func TestCreateTrustsMiseBeforeInstallingHKHooks(t *testing.T) { runtime := repository.runtime cache := fmt.Sprintf(`{"username":"alice","organizations":[],"fetched_at":%q}`, time.Now().UTC().Format(time.RFC3339Nano)) writeIdentityCache(t, runtime, cache) - require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "--auto-mise-trust").err) - require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "--auto-hk-install").err) + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_mise_trust", "true").err) + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_hk_install", "true").err) bin := resolvedTempDir(t) logPath := filepath.Join(bin, "automation.log") diff --git a/internal/cli/mise_trust_case_test.go b/internal/cli/mise_trust_case_test.go index e35eae9..b2c20d2 100644 --- a/internal/cli/mise_trust_case_test.go +++ b/internal/cli/mise_trust_case_test.go @@ -80,11 +80,11 @@ func configureMiseTrustRuntime(t *testing.T, runtime timber.Runtime, test miseTr t.Helper() runtime.GhExecutable = filepath.Join(resolvedTempDir(t), "missing-gh") if test.enabled { - result := runTimberCommandWithRuntime(t, runtime, "config", "--auto-mise-trust") + result := runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_mise_trust", "true") require.NoError(t, result.err) } if test.explicitDisable { - result := runTimberCommandWithRuntime(t, runtime, "config", "--no-auto-mise-trust") + result := runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_mise_trust", "false") require.NoError(t, result.err) } if test.cache == "refresh" { @@ -194,7 +194,7 @@ func assertMiseTrustPrompt(t *testing.T, runtime timber.Runtime, result commandR func assertMiseTrustRefusal(t *testing.T, runtime timber.Runtime, result commandResult, logPath, timberBin string, wantTrust bool, answer string) { t.Helper() if !wantTrust { - assert.Contains(t, result.stderr, "Enable it later with: timber config --auto-mise-trust") + assert.Contains(t, result.stderr, "Enable it later with: timber config set auto_mise_trust true") } again := interactiveCreate(t, runtime, timberBin, answer, "second") require.NoError(t, again.err) @@ -204,7 +204,7 @@ func assertMiseTrustRefusal(t *testing.T, runtime timber.Runtime, result command } assert.NoFileExists(t, logPath) // The documented command can reverse a saved refusal. - require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "--auto-mise-trust").err) + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "set", "auto_mise_trust", "true").err) require.NoError(t, runTimberCommandWithRuntime(t, runtime, "create", "--upstream", "source/main", at(testRepoName, "third")).err) assert.FileExists(t, logPath) } diff --git a/internal/cli/repo_add_test.go b/internal/cli/repo_add_test.go index 82da979..15702b6 100644 --- a/internal/cli/repo_add_test.go +++ b/internal/cli/repo_add_test.go @@ -56,7 +56,7 @@ func TestRepoAddStripsConfiguredGitHubOwner(t *testing.T) { t.Run("listed owner is stripped", func(t *testing.T) { t.Parallel() runtime := githubRedirectRuntime(t, "nnutter/timber") - configure := runTimberCommandWithRuntime(t, runtime, "config", "--strip-github-owner", "NNutter") + configure := runTimberCommandWithRuntime(t, runtime, "config", "append", "strip_github_owners", "NNutter") require.NoError(t, configure.err, configure.stderr) result := runTimberCommandWithRuntime(t, runtime, "repo", "add", "nnutter/timber") @@ -69,7 +69,7 @@ func TestRepoAddStripsConfiguredGitHubOwner(t *testing.T) { t.Run("explicit name wins", func(t *testing.T) { t.Parallel() runtime := githubRedirectRuntime(t, "nnutter/timber") - configure := runTimberCommandWithRuntime(t, runtime, "config", "--strip-github-owner", "nnutter") + configure := runTimberCommandWithRuntime(t, runtime, "config", "append", "strip_github_owners", "nnutter") require.NoError(t, configure.err, configure.stderr) result := runTimberCommandWithRuntime(t, runtime, "repo", "add", "--name", "nnutter/timber", "nnutter/timber") diff --git a/internal/cli/setup_prompt.go b/internal/cli/setup_prompt.go index abb13ce..38d34c3 100644 --- a/internal/cli/setup_prompt.go +++ b/internal/cli/setup_prompt.go @@ -93,14 +93,14 @@ func setupText(kind timber.SetupKind) (setupPromptText, error) { warning: "This worktree qualifies for automatic mise trust. Trusting mise configuration permits code execution.", question: "Enable automatic mise trust for repositories owned by you or your GitHub organizations? [y/N] ", read: "read mise trust choice", - disabled: "Automatic mise trust remains disabled. Enable it later with: timber config --auto-mise-trust", + disabled: "Automatic mise trust remains disabled. Enable it later with: timber config set auto_mise_trust true", }, nil case timber.SetupHKInstall: return setupPromptText{ warning: "This worktree qualifies for automatic hk hook installation. Installing hk hooks permits code execution.", question: "Enable automatic hk hook installation for repositories owned by you or your GitHub organizations? [y/N] ", read: "read hk install choice", - disabled: "Automatic hk hook installation remains disabled. Enable it later with: timber config --auto-hk-install", + disabled: "Automatic hk hook installation remains disabled. Enable it later with: timber config set auto_hk_install true", }, nil default: return setupPromptText{}, fmt.Errorf("unknown automatic setup kind %q", kind) diff --git a/internal/timber/config/keys.go b/internal/timber/config/keys.go index a43caa6..4c13332 100644 --- a/internal/timber/config/keys.go +++ b/internal/timber/config/keys.go @@ -47,7 +47,7 @@ func KeyNames() []string { // Get returns the values stored for name. A boolean setting always reports one // value; a list setting reports none when it is empty. func Get(settings Settings, name string) ([]string, error) { - key, err := lookupKey(name) + key, err := LookupKey(name) if err != nil { return nil, err } @@ -58,7 +58,7 @@ func Get(settings Settings, name string) ([]string, error) { // setting takes the values that replace it. Setting a prompted setting also // records the answer, so its setup prompt stops asking. func Set(settings *Settings, name string, values []string) error { - key, err := lookupKey(name) + key, err := LookupKey(name) if err != nil { return err } @@ -68,7 +68,7 @@ func Set(settings *Settings, name string, values []string) error { // Append adds values to a list setting. A boolean setting has nothing to // append to. func Append(settings *Settings, name string, values []string) error { - key, err := lookupKey(name) + key, err := LookupKey(name) if err != nil { return err } @@ -78,7 +78,7 @@ func Append(settings *Settings, name string, values []string) error { // Remove resets name to its default, or removes matching values from a list // setting. Boolean settings take no values because they always hold one. func Remove(settings *Settings, name string, values []string) error { - key, err := lookupKey(name) + key, err := LookupKey(name) if err != nil { return err } @@ -198,7 +198,8 @@ func boolValue(name string, values []string) (bool, error) { return parsed, nil } -func lookupKey(name string) (Key, error) { +// LookupKey returns the setting named by name. +func LookupKey(name string) (Key, error) { for _, key := range keys { if key.Name == name { return key, nil From fb637751a6f67a756a9b325ba97dca4c41da640d Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Tue, 17 Nov 2026 08:56:40 -0600 Subject: [PATCH 10/12] Document the config subcommands The README and the Timber skill still teach the removed flags, so a reader would run commands that no longer exist. Describe the subcommands and point the strip-owner examples at append and remove. Change-Id: Iff5d7f1f22bacad80848e8479f4cf36840cb3aa7 --- README.md | 33 ++++++++++++++++++--------------- skills/timber/SKILL.md | 5 +++-- 2 files changed, 21 insertions(+), 17 deletions(-) diff --git a/README.md b/README.md index cf78a98..0103ba7 100644 --- a/README.md +++ b/README.md @@ -54,7 +54,7 @@ Structured example (`t repo add nnutter/timber` defaults to the structured name; Rename with `timber repo rename ` to move between simple and structured names; standard-layout worktrees move with the repo. Sorting `timber list --sort repo` orders by the full structured name, so the grouping prefix controls grouping. -Listing a GitHub owner with `timber config --strip-github-owner ` registers that owner's repositories under the short name instead: `timber repo add nnutter/timber` then becomes repo name `timber` at `~/worktrees/timber/.git`. +Listing a GitHub owner with `timber config append strip_github_owners ` registers that owner's repositories under the short name instead: `timber repo add nnutter/timber` then becomes repo name `timber` at `~/worktrees/timber/.git`. Explicit `--name` always wins, owner matching ignores case, and other hosts keep their full grouping. Use `timber repo import ` to register an existing clean clone and recreate its worktrees (including the former main checkout) in this layout. @@ -100,25 +100,28 @@ npx skills add https://github.com/nnutter/timber ## Configuration -Run `timber config` to show settings and create the config file if absent. +`timber config show` prints every setting and creates the config file if absent. The file is `$XDG_CONFIG_HOME/timber/config.toml` (fallback: `~/.config/timber/config.toml`). +The other subcommands read and change one setting by name: `get` prints its values one per line, `set` replaces the value, `append` adds values to a list setting, and `remove` (alias `rm`) resets a setting or drops matching list values. +Setting names complete in the shell, as do the values of boolean settings and the stored values of list settings when they are removed. + +```bash +timber config show +timber config get auto_mise_trust +timber config set auto_mise_trust true +timber config append strip_github_owners nnutter acme +timber config remove strip_github_owners nnutter +timber config rm strip_github_owners +``` + Automatic mise trust and automatic hk hook installation are disabled by default. On the first eligible worktree creation in an interactive terminal, Timber offers to enable each feature. The prompts default to No and save your answers, so Timber does not ask again. -After No, a prompt shows the matching `timber config` flag so you can enable the feature later. -An explicit `--no-auto-mise-trust` or `--no-auto-hk-install` also suppresses its prompt. +After No, a prompt shows the matching `timber config set ...` command so you can enable the feature later. +Setting either setting records the choice explicitly, which also suppresses its prompt. Non-interactive creation does not prompt or record a choice. -```bash -timber config --auto-mise-trust -timber config --no-auto-mise-trust -timber config --auto-hk-install -timber config --no-auto-hk-install -timber config --strip-github-owner nnutter -timber config --no-strip-github-owner nnutter -``` - -`--strip-github-owner` is repeatable and records `strip_github_owners` in the config file; `repo add` and `repo import` drop a listed owner from names they derive from GitHub remotes. +`strip_github_owners` lists the owners whose GitHub repositories register under the short name; `repo add` and `repo import` drop a listed owner from names they derive from GitHub remotes. Enabling automatic trust permits mise configuration in eligible worktrees to execute code. Eligibility requires a root-level, regular `mise.toml` and a GitHub upstream owned by you or one of your organizations. @@ -430,7 +433,7 @@ For full flags and examples, see `timber --help` and `timber --help`. | `repo fix` | Move bare repositories from the old data directory into the worktree root, repair worktree links, and set `push.default=current` | | `repo remove` | Unregister a bare repository once its worktrees are gone | | `repo rename` | Rename a repository and move its worktree directories | -| `config` | Show settings or change them with `--auto-mise-trust` / `--no-auto-mise-trust` / `--auto-hk-install` / `--no-auto-hk-install` / `--strip-github-owner` / `--no-strip-github-owner` | +| `config` | Show settings or change them with `show`, `get`, `set`, `append`, and `remove` (`rm`); keys and values complete in the shell | | `create` | Create a worktree for a branch (`--no-herdr` skips the Herdr space) | | `switch` | Shell-only: `cd` into a worktree, creating it first with `-c` | | `tui` | Interactively open an existing worktree or create a new one | diff --git a/skills/timber/SKILL.md b/skills/timber/SKILL.md index bd46a59..afd7272 100644 --- a/skills/timber/SKILL.md +++ b/skills/timber/SKILL.md @@ -34,9 +34,10 @@ For detailed checklist editing, use the separate `timber-todo` skill. Timber never reads a token from a configuration file, and never accepts one on a command line. Do not write a secret into a Timber or gh configuration file. On a machine without a keyring, such as a headless server or CI, set `GH_TOKEN`. -- `timber config` shows settings and creates the configuration file if absent: +- `timber config show` prints settings and creates the configuration file if absent: `$XDG_CONFIG_HOME/timber/config.toml`, falling back to - `~/.config/timber/config.toml`. `timber config --strip-github-owner ` records a GitHub owner whose repositories `repo add` and `repo import` register under the short name instead of `owner/repo`; `--no-strip-github-owner` removes the owner. + `~/.config/timber/config.toml`. `timber config get`, `set`, `append`, and `remove` read and change one setting by name; `show` prints them all. + `timber config append strip_github_owners ` records a GitHub owner whose repositories `repo add` and `repo import` register under the short name instead of `owner/repo`; `timber config remove strip_github_owners ` removes the owner. An explicit `--name` still wins, and other hosts keep their grouping. - Bare repositories live at `$TIMBER_WORKTREE_ROOT//.git` (fallback `~/worktrees//.git`). `TIMBER_WORKTREE_ROOT` overrides the default `~/worktrees` checkout root. Preserve the user's environment. From d40de703250832c57d30ee2894399ee670703561 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Tue, 17 Nov 2026 10:31:35 -0600 Subject: [PATCH 11/12] Complete each value when removing config list entries Keep offering unselected list values after the first removal argument. Use the setting removal rules so owner matching remains case-insensitive. Change-Id: I277923c154a6ce93e0c1e0f3c9653aa1cde2f827 --- internal/cli/complete/complete.go | 15 ++++++++++----- internal/cli/completion_functional_test.go | 7 ++++++- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/internal/cli/complete/complete.go b/internal/cli/complete/complete.go index 28bbcca..7263e1c 100644 --- a/internal/cli/complete/complete.go +++ b/internal/cli/complete/complete.go @@ -208,14 +208,14 @@ func ConfigArgs(reader ConfigReader, mode ConfigValueMode) func(*cobra.Command, } return matchingPrefix(candidates, toComplete), cobra.ShellCompDirectiveNoFileComp } - if len(args) > 1 { - return nil, cobra.ShellCompDirectiveNoFileComp - } switch mode { case ConfigValueSet: + if len(args) > 1 { + return nil, cobra.ShellCompDirectiveNoFileComp + } return matchingPrefix(boolValues(args[0]), toComplete), cobra.ShellCompDirectiveNoFileComp case ConfigValueRemove: - return listValues(reader, args[0], toComplete) + return listValues(reader, args[0], args[1:], toComplete) default: return nil, cobra.ShellCompDirectiveNoFileComp } @@ -233,7 +233,7 @@ func boolValues(name string) []string { return []string{"true", "false"} } -func listValues(reader ConfigReader, name, toComplete string) ([]string, cobra.ShellCompDirective) { +func listValues(reader ConfigReader, name string, selected []string, toComplete string) ([]string, cobra.ShellCompDirective) { key, err := coreconfig.LookupKey(name) if err != nil { return nil, cobra.ShellCompDirectiveNoFileComp @@ -245,6 +245,11 @@ func listValues(reader ConfigReader, name, toComplete string) ([]string, cobra.S if err != nil { return nil, cobra.ShellCompDirectiveError } + if len(selected) > 0 { + if err := coreconfig.Remove(&settings, name, selected); err != nil { + return nil, cobra.ShellCompDirectiveError + } + } values, err := coreconfig.Get(settings, name) if err != nil { return nil, cobra.ShellCompDirectiveError diff --git a/internal/cli/completion_functional_test.go b/internal/cli/completion_functional_test.go index 6aa620f..1757fba 100644 --- a/internal/cli/completion_functional_test.go +++ b/internal/cli/completion_functional_test.go @@ -52,7 +52,7 @@ func TestWorktreeCompletionAddsAtWhenNameIsAmbiguous(t *testing.T) { func TestConfigCompletionOffersSettingsAndValues(t *testing.T) { t.Parallel() runtime := testRuntime(t) - require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "append", "strip_github_owners", "nnutter").err) + require.NoError(t, runTimberCommandWithRuntime(t, runtime, "config", "append", "strip_github_owners", "nnutter", "acme").err) keys := runCompleteWithRuntime(t, runtime, "config", "get", "") assert.Contains(t, keys, "auto_mise_trust\t") @@ -66,6 +66,11 @@ func TestConfigCompletionOffersSettingsAndValues(t *testing.T) { owners := runCompleteWithRuntime(t, runtime, "config", "remove", "strip_github_owners", "") assert.Contains(t, owners, "nnutter") + remaining := runCompleteWithRuntime(t, runtime, "config", "remove", "strip_github_owners", "ACME", "") + assert.Contains(t, remaining, "nnutter") + assert.NotContains(t, remaining, "acme") + assert.NotContains(t, runCompleteWithRuntime(t, runtime, "config", "set", "auto_mise_trust", "true", ""), "false") + // Appending takes values that do not exist yet, so there is nothing to offer. assert.NotContains(t, runCompleteWithRuntime(t, runtime, "config", "append", "auto_mise_trust", ""), "true") } From 271a768886c75555f981f4cbccf964a5b246efc1 Mon Sep 17 00:00:00 2001 From: Nathan Nutter Date: Tue, 17 Nov 2026 10:33:50 -0600 Subject: [PATCH 12/12] Follow repository renames from nested worktrees Report current directories moved implicitly with the bare repository through the existing shell path-file mechanism, so t can follow them. Change-Id: I1b8a7403428ebc33681a780fd22d73d72eecea9b --- internal/cli/repo_rename_functional_test.go | 13 ++++++++++++- internal/timber/repo_rename_plan.go | 7 +++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/internal/cli/repo_rename_functional_test.go b/internal/cli/repo_rename_functional_test.go index 165e996..c4bbea8 100644 --- a/internal/cli/repo_rename_functional_test.go +++ b/internal/cli/repo_rename_functional_test.go @@ -63,13 +63,24 @@ func TestRepoRenameMovesWorktreeNestedInBareRepository(t *testing.T) { nestedPath := filepath.Join(testRepository.barePath, "checkouts", "nested") runGitCommand(t, testRepository.barePath, "worktree", "add", "--detach", nestedPath, "main") - result := testRepository.runTimber(t, "repo", "rename", testRepoName, newRepoName) + subdirectory := filepath.Join(nestedPath, "subdirectory") + require.NoError(t, os.MkdirAll(subdirectory, 0o755)) + pathFile := filepath.Join(resolvedTempDir(t), "renamed-path") + runtime := testRepository.runtime + runtime.CurrentDirectory = subdirectory + runtime.RenamePathFile = pathFile + runtime.TemporaryDirectory = filepath.Dir(pathFile) + + result := runTimberCommandWithRuntime(t, runtime, "repo", "rename", testRepoName, newRepoName) require.NoError(t, result.err, result.stderr) newBarePath := repoTestBarePath(testRepository.runtime, newRepoName) newNestedPath := filepath.Join(newBarePath, "checkouts", "nested") assert.NoDirExists(t, testRepository.barePath) assert.DirExists(t, newNestedPath) + contents, err := os.ReadFile(pathFile) + require.NoError(t, err) + assert.Equal(t, filepath.Join(newNestedPath, "subdirectory")+"\n", string(contents)) commonDir := strings.TrimSpace(runGitCommand(t, newNestedPath, "rev-parse", "--path-format=absolute", "--git-common-dir")) assert.Equal(t, shellCanonicalPath(newBarePath), shellCanonicalPath(commonDir)) } diff --git a/internal/timber/repo_rename_plan.go b/internal/timber/repo_rename_plan.go index 3be90e8..f17651e 100644 --- a/internal/timber/repo_rename_plan.go +++ b/internal/timber/repo_rename_plan.go @@ -113,6 +113,13 @@ func (x *repositoryRenamePlan) findCurrentTargetDirectory() error { x.currentTargetDir = filepath.Join(move.Destination, relativePath) return nil } + // Worktrees nested inside the bare repository move with it rather than + // appearing in worktreeMoves. Report those implicit moves to the shell too. + target, _, err := movedCurrentDirectory(x.sourceRepo.BarePath, x.destinationRepo.BarePath, currentDirectory) + if err != nil { + return err + } + x.currentTargetDir = target return nil }