diff --git a/README.md b/README.md index 8509014..0103ba7 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 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. When invoked through the shell wrapper (`t repo import `), the shell also `cd`s to `$HOME` after success. @@ -97,21 +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 -``` +`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. @@ -423,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` | +| `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/internal/cli/complete/complete.go b/internal/cli/complete/complete.go index 0e097e9..7263e1c 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,90 @@ 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 + } + 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], args[1:], 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 string, selected []string, 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 + } + 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 + } + 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..1757fba 100644 --- a/internal/cli/completion_functional_test.go +++ b/internal/cli/completion_functional_test.go @@ -49,6 +49,32 @@ 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", "acme").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") + + 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") +} + 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 c5333c1..f49552a 100644 --- a/internal/cli/config/config.go +++ b/internal/cli/config/config.go @@ -1,59 +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 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 := 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 + 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("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 = 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") - return command +} + +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:]) + }) + }, + } +} + +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:]) + }) + }, + } +} + +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:]) + }) + }, + } +} + +// 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 + } + 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 096ab1c..128b8d9 100644 --- a/internal/cli/config_test.go +++ b/internal/cli/config_test.go @@ -9,36 +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"}, + 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 TestConfigSetAndGet(t *testing.T) { + runtime := testRuntime(t) + 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(filepath.Join(runtime.ConfigHome, "timber", "config.toml")) - 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", "--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") + + // 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) { @@ -48,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 c441fb2..15702b6 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", "append", "strip_github_owners", "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", "append", "strip_github_owners", "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/cli/repo_rename_functional_test.go b/internal/cli/repo_rename_functional_test.go index d1865a1..c4bbea8 100644 --- a/internal/cli/repo_rename_functional_test.go +++ b/internal/cli/repo_rename_functional_test.go @@ -55,6 +55,36 @@ 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") + + 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)) +} + func TestRepoRenameWithoutWorktrees(t *testing.T) { t.Parallel() testRepository := newTestRepository(t) 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 new file mode 100644 index 0000000..4c13332 --- /dev/null +++ b/internal/timber/config/keys.go @@ -0,0 +1,209 @@ +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 +} + +// LookupKey returns the setting named by name. +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) +} 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 7786698..529e433 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) @@ -142,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/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 e183a68..f17651e 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 { @@ -112,9 +113,31 @@ 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 } +// 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, @@ -154,6 +177,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)) } @@ -245,6 +271,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 == "" { diff --git a/internal/timber/runtime.go b/internal/timber/runtime.go index 575b226..eb52a76 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 } @@ -613,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 { @@ -909,12 +934,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) { @@ -1289,6 +1314,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 +1725,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) + if err := x.ensureConfigFile(); err != nil { + return config{}, 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 keys := metadata.Undecoded(); len(keys) != 0 { - return config{}, fmt.Errorf("unknown config setting: %s", keys[0]) - } - return settings, nil + return x.ReadConfig() } // managedWorktreePath returns 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..afd7272 100644 --- a/skills/timber/SKILL.md +++ b/skills/timber/SKILL.md @@ -34,9 +34,11 @@ 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`. + `~/.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. - A registered repository records `push.default=current`, so `git push` sends the checked-out branch to the same-named branch on the remote.