From 7802dc53c13aaace0b6d3f698b54fc716adc2772 Mon Sep 17 00:00:00 2001 From: kuyacarlo <106532351+kuyacarlo@users.noreply.github.com> Date: Sun, 16 Aug 2026 07:46:41 +0800 Subject: [PATCH] feat: offer git-profile pairing on add and use When the companion git-profile binary is installed, `git-ssh add ` and `git-ssh use ` now ask whether to hand off to git-profile so the same profile name carries both the SSH identity and the git identity. The pairing is best-effort and keeps the two tools fully separate: - detection is exec.LookPath only, no config coupling - `add` hands off to interactive `git-profile add` (stdin/stdout passthrough) - `use` runs `git-profile use ` in the current repo - the prompt only fires on an interactive terminal; a decline or a git-profile failure never fails the git-ssh command Adds internal/gitprofile with an injectable Runner (default Linker, Skip for tests/CI), ui.Confirm, and TTY-gated offers wired into add and use. Signed-off-by: kuyacarlo <106532351+kuyacarlo@users.noreply.github.com> --- cmd/gitprofile_test.go | 119 +++++++++++++++++++++++++ cmd/root.go | 92 ++++++++++++++++++- go.mod | 2 +- internal/gitprofile/gitprofile.go | 68 ++++++++++++++ internal/gitprofile/gitprofile_test.go | 67 ++++++++++++++ internal/ui/ui.go | 19 ++++ 6 files changed, 364 insertions(+), 3 deletions(-) create mode 100644 cmd/gitprofile_test.go create mode 100644 internal/gitprofile/gitprofile.go create mode 100644 internal/gitprofile/gitprofile_test.go diff --git a/cmd/gitprofile_test.go b/cmd/gitprofile_test.go new file mode 100644 index 0000000..c96a434 --- /dev/null +++ b/cmd/gitprofile_test.go @@ -0,0 +1,119 @@ +package cmd + +import ( + "bytes" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + + "github.com/matryer/is" +) + +// fakeRunner records git-profile invocations. +type fakeRunner struct { + available bool + addCalls int + useCalls []string +} + +func (f *fakeRunner) Available() bool { return f.available } + +func (f *fakeRunner) RunAdd(in io.Reader, out, errOut io.Writer) error { + f.addCalls++ + return nil +} + +func (f *fakeRunner) RunUse(name string, in io.Reader, out, errOut io.Writer) error { + f.useCalls = append(f.useCalls, name) + return nil +} + +// forceTerminal builds a Root whose git-profile offer always runs (terminal +// path forced, confirm answered by the given function). +func forceTerminal(t *testing.T, runner *fakeRunner, confirm func(string) bool) *Root { + t.Helper() + root := New() + root.gitProfile = runner + root.isTerminal = func(io.Reader) bool { return true } + root.confirm = func(title, affirmative, negative string, in io.Reader, out io.Writer) (bool, error) { + return confirm(title), nil + } + return root +} + +func TestOfferGitProfileAddNotOfferedWhenUnavailable(t *testing.T) { + is := is.New(t) + runner := &fakeRunner{available: false} + root := forceTerminal(t, runner, func(string) bool { return true }) + + cfg := filepath.Join(t.TempDir(), "config.json") + root.SetOut(&bytes.Buffer{}) + root.SetErr(&bytes.Buffer{}) + root.SetArgs([]string{"-c", cfg, "add", "alice"}) + root.Execute() + is.Equal(runner.addCalls, 0) +} + +func TestOfferGitProfileAddRunsOnConfirm(t *testing.T) { + is := is.New(t) + runner := &fakeRunner{available: true} + root := forceTerminal(t, runner, func(string) bool { return true }) + + cfg := filepath.Join(t.TempDir(), "config.json") + out := &bytes.Buffer{} + root.SetOut(out) + root.SetErr(&bytes.Buffer{}) + root.SetArgs([]string{"-c", cfg, "add", "alice"}) + root.Execute() + is.Equal(runner.addCalls, 1) + is.True(strings.Contains(out.String(), "Running `git-profile add`")) +} + +func TestOfferGitProfileAddSkipsOnDecline(t *testing.T) { + is := is.New(t) + runner := &fakeRunner{available: true} + root := forceTerminal(t, runner, func(string) bool { return false }) + + cfg := filepath.Join(t.TempDir(), "config.json") + root.SetOut(&bytes.Buffer{}) + root.SetErr(&bytes.Buffer{}) + root.SetArgs([]string{"-c", cfg, "add", "alice"}) + root.Execute() + is.Equal(runner.addCalls, 0) +} + +func TestOfferGitProfileUseRunsOnConfirm(t *testing.T) { + is := is.New(t) + runner := &fakeRunner{available: true} + root := forceTerminal(t, runner, func(string) bool { return true }) + + cfg := filepath.Join(t.TempDir(), "config.json") + key := writeTestKey(t, t.TempDir()) + root.SetOut(&bytes.Buffer{}) + root.SetErr(&bytes.Buffer{}) + root.SetArgs([]string{"-c", cfg, "add", "alice", "--identity", key, "--github-user", "alice"}) + root.Execute() + is.Equal(runner.addCalls, 1) + + repo := filepath.Join(t.TempDir(), "demo-repo") + is.NoErr(os.MkdirAll(repo, 0o755)) + if out, err := exec.Command("git", "init", repo).CombinedOutput(); err != nil { + t.Fatalf("git init: %v\n%s", err, out) + } + + wd, err := os.Getwd() + is.NoErr(err) + is.NoErr(os.Chdir(repo)) + t.Cleanup(func() { _ = os.Chdir(wd) }) + + root = forceTerminal(t, runner, func(string) bool { return true }) + root.SetOut(&bytes.Buffer{}) + root.SetErr(&bytes.Buffer{}) + root.SetArgs([]string{"-c", cfg, "use", "alice"}) + root.Execute() + is.Equal(len(runner.useCalls), 1) + is.Equal(runner.useCalls[0], "alice") +} diff --git a/cmd/root.go b/cmd/root.go index 4e8e1a2..088b97a 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -2,6 +2,7 @@ package cmd import ( "fmt" + "io" "os" "sort" "strings" @@ -9,10 +10,12 @@ import ( "github.com/kuyacarlo/ssh-profile/internal/apply" "github.com/kuyacarlo/ssh-profile/internal/config" "github.com/kuyacarlo/ssh-profile/internal/git" + "github.com/kuyacarlo/ssh-profile/internal/gitprofile" "github.com/kuyacarlo/ssh-profile/internal/include" "github.com/kuyacarlo/ssh-profile/internal/keys" "github.com/kuyacarlo/ssh-profile/internal/remoteurl" "github.com/kuyacarlo/ssh-profile/internal/ui" + "github.com/charmbracelet/x/term" "github.com/spf13/cobra" ) @@ -27,6 +30,14 @@ type Root struct { filename string cfg *config.Config git *git.Git + // gitProfile drives the optional git-profile pairing. Nil disables it. + gitProfile gitprofile.Runner + // confirm is the yes/no prompt. Injectable so tests can drive it without a + // terminal. Defaults to ui.Confirm. + confirm func(title, affirmative, negative string, in io.Reader, out io.Writer) (bool, error) + // isTerminal reports whether a reader is an interactive terminal. + // Injectable so tests can force the interactive path. + isTerminal func(io.Reader) bool } // New builds the root command with subcommands. @@ -37,6 +48,9 @@ func New() *Root { CompileDate: "Unknown", cfg: config.New(), git: git.New(), + gitProfile: gitprofile.New(), + confirm: ui.Confirm, + isTerminal: isTerminalReader, } r.Command = cobra.Command{ @@ -131,6 +145,71 @@ func (r *Root) saveConfig() error { return r.cfg.Save(r.filename) } +// offerGitProfileAdd hands off to git-profile's interactive `add` when the +// companion binary is installed and stdin is a terminal. It is best-effort: +// a decline or git-profile failure never fails the git-ssh command. +func (r *Root) offerGitProfileAdd(cmd *cobra.Command, name string) { + if r.gitProfile == nil || !r.gitProfile.Available() { + return + } + if !r.isTerminal(cmd.InOrStdin()) { + return + } + confirmed, err := r.confirm( + fmt.Sprintf("git-profile is installed. Also add the %q profile there?", name), + "Yes", + "No", + cmd.InOrStdin(), + cmd.OutOrStdout(), + ) + if err != nil { + return + } + if !confirmed { + return + } + fmt.Fprintln(cmd.OutOrStdout(), "Running `git-profile add` — fill the identity fields, then exit.") + if err := r.gitProfile.RunAdd(cmd.InOrStdin(), cmd.OutOrStdout(), cmd.ErrOrStderr()); err != nil { + fmt.Fprintf(cmd.ErrOrStderr(), "warning: git-profile add failed: %v\n", err) + } +} + +// offerGitProfileUse applies the same-named git-profile profile in the current +// repo when the companion binary is installed and stdin is a terminal. +func (r *Root) offerGitProfileUse(cmd *cobra.Command, name string) { + if r.gitProfile == nil || !r.gitProfile.Available() { + return + } + if !r.isTerminal(cmd.InOrStdin()) { + return + } + confirmed, err := r.confirm( + fmt.Sprintf("git-profile is installed. Also apply the %q git identity here?", name), + "Yes", + "No", + cmd.InOrStdin(), + cmd.OutOrStdout(), + ) + if err != nil { + return + } + if !confirmed { + return + } + if err := r.gitProfile.RunUse(name, cmd.InOrStdin(), cmd.OutOrStdout(), cmd.ErrOrStderr()); err != nil { + fmt.Fprintf(cmd.ErrOrStderr(), "warning: git-profile use failed: %v\n", err) + } +} + +// isTerminalReader reports whether r is a real terminal. +func isTerminalReader(r io.Reader) bool { + f, ok := r.(*os.File) + if !ok { + return false + } + return term.IsTerminal(f.Fd()) +} + func (r *Root) addCmd() *cobra.Command { var identity string var alias string @@ -192,7 +271,11 @@ func (r *Root) addCmd() *cobra.Command { profile.Config[strings.TrimSpace(key)] = strings.TrimSpace(value) } } - return r.saveProfile(cmd, name, profile, !exists, createdKey) + if err := r.saveProfile(cmd, name, profile, !exists, createdKey); err != nil { + return err + } + r.offerGitProfileAdd(cmd, name) + return nil }, } @@ -242,7 +325,11 @@ func (r *Root) addInteractive(cmd *cobra.Command) error { return err } _, existed := r.cfg.Lookup(name) - return r.saveProfile(cmd, name, profile, !existed, createdKey) + if err := r.saveProfile(cmd, name, profile, !existed, createdKey); err != nil { + return err + } + r.offerGitProfileAdd(cmd, name) + return nil } // fillProfileDefaults sets github_user from the profile name and ensures a @@ -501,6 +588,7 @@ func (r *Root) useCmd() *cobra.Command { fmt.Fprintln(cmd.OutOrStdout(), " origin: skipped") } warnNonGitHubOrigin(cmd, name, result.RemoteURL, result.RemoteAction) + r.offerGitProfileUse(cmd, name) return nil }, } diff --git a/go.mod b/go.mod index 3118a50..7e276e3 100644 --- a/go.mod +++ b/go.mod @@ -5,6 +5,7 @@ go 1.26 require ( charm.land/huh/v2 v2.0.3 github.com/adrg/xdg v0.5.3 + github.com/charmbracelet/x/term v0.2.2 github.com/matryer/is v1.4.1 github.com/spf13/cobra v1.10.2 ) @@ -20,7 +21,6 @@ require ( github.com/charmbracelet/x/ansi v0.11.6 // indirect github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect - github.com/charmbracelet/x/term v0.2.2 // indirect github.com/charmbracelet/x/termios v0.1.1 // indirect github.com/charmbracelet/x/windows v0.2.2 // indirect github.com/clipperhouse/displaywidth v0.11.0 // indirect diff --git a/internal/gitprofile/gitprofile.go b/internal/gitprofile/gitprofile.go new file mode 100644 index 0000000..deee0b2 --- /dev/null +++ b/internal/gitprofile/gitprofile.go @@ -0,0 +1,68 @@ +package gitprofile + +import ( + "io" + "os" + "os/exec" +) + +// Runner talks to the separate git-profile binary. It never couples to +// git-profile's config format — it only detects it and hands off control. +type Runner interface { + // Available reports whether git-profile is on PATH. + Available() bool + // RunAdd starts interactive `git-profile add` with stdio passthrough. + RunAdd(in io.Reader, out, errOut io.Writer) error + // RunUse applies the same-named git-profile profile in the current repo. + RunUse(name string, in io.Reader, out, errOut io.Writer) error +} + +// Linker is the default Runner backed by exec.LookPath / exec.Command. +type Linker struct { + lookPath func(string) (string, error) +} + +// New returns a Linker using the real environment. +func New() *Linker { + return &Linker{lookPath: exec.LookPath} +} + +func (l *Linker) Available() bool { + _, err := l.lookPath("git-profile") + return err == nil +} + +func (l *Linker) RunAdd(in io.Reader, out, errOut io.Writer) error { + return l.run(nil, in, out, errOut) +} + +func (l *Linker) RunUse(name string, in io.Reader, out, errOut io.Writer) error { + return l.run([]string{"use", name}, in, out, errOut) +} + +func (l *Linker) run(args []string, in io.Reader, out, errOut io.Writer) error { + cmd := exec.Command("git-profile", args...) + cmd.Stdin = in + cmd.Stdout = out + cmd.Stderr = errOut + return cmd.Run() +} + +// Compile-time check that Linker satisfies Runner. +var _ Runner = (*Linker)(nil) + +// Skip is a Runner that reports git-profile as unavailable. Useful for tests +// and for build environments where the companion binary must not be probed. +type Skip struct{} + +func (Skip) Available() bool { return false } + +func (Skip) RunAdd(_ io.Reader, _, _ io.Writer) error { + return os.ErrNotExist +} + +func (Skip) RunUse(_ string, _ io.Reader, _, _ io.Writer) error { + return os.ErrNotExist +} + +var _ Runner = Skip{} diff --git a/internal/gitprofile/gitprofile_test.go b/internal/gitprofile/gitprofile_test.go new file mode 100644 index 0000000..bd49f7a --- /dev/null +++ b/internal/gitprofile/gitprofile_test.go @@ -0,0 +1,67 @@ +package gitprofile + +import ( + "os" + "os/exec" + "path/filepath" + "strings" + "testing" +) + +// withFakeGitProfile writes an executable `git-profile` into a temp dir and +// prepends it to PATH for the duration of the test. +func withFakeGitProfile(t *testing.T) { + t.Helper() + dir := t.TempDir() + bin := filepath.Join(dir, "git-profile") + script := "#!/bin/sh\nprintf 'git-profile ran: %s\\n' \"$@\" >&2\nexit 0\n" + if err := os.WriteFile(bin, []byte(script), 0o755); err != nil { + t.Fatal(err) + } + t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH")) +} + +func TestAvailableTrueWhenPresent(t *testing.T) { + withFakeGitProfile(t) + if !New().Available() { + t.Fatal("expected Available() true with fake git-profile on PATH") + } +} + +func TestAvailableFalseWhenMissing(t *testing.T) { + l := &Linker{lookPath: func(string) (string, error) { + return "", exec.ErrNotFound + }} + if l.Available() { + t.Fatal("expected Available() false with no git-profile") + } +} + +func TestRunAddAndRunUseExecFake(t *testing.T) { + withFakeGitProfile(t) + l := New() + + var out strings.Builder + var errOut strings.Builder + if err := l.RunAdd(strings.NewReader(""), &out, &errOut); err != nil { + t.Fatalf("RunAdd: %v", err) + } + if !strings.Contains(errOut.String(), "ran:") { + t.Fatalf("RunAdd did not execute git-profile: %q", errOut.String()) + } + + errOut.Reset() + if err := l.RunUse("alice", strings.NewReader(""), &out, &errOut); err != nil { + t.Fatalf("RunUse: %v", err) + } + if !strings.Contains(errOut.String(), "alice") { + t.Fatalf("RunUse did not pass profile name: %q", errOut.String()) + } +} + +func TestSkipRunnerNeverAvailable(t *testing.T) { + skip := Skip{} + if skip.Available() { + t.Fatal("Skip should report unavailable") + } +} diff --git a/internal/ui/ui.go b/internal/ui/ui.go index 42a24d7..1a02559 100644 --- a/internal/ui/ui.go +++ b/internal/ui/ui.go @@ -82,6 +82,25 @@ func PromptProfileFields(initial ProfileFormData, in io.Reader, out io.Writer) ( return result, nil } +// Confirm asks a yes/no question and reports the result. +func Confirm(title string, affirmative, negative string, in io.Reader, out io.Writer) (bool, error) { + var confirmed bool + form := huh.NewForm( + huh.NewGroup( + huh.NewConfirm(). + Title(title). + Affirmative(affirmative). + Negative(negative). + Value(&confirmed), + ), + ).WithInput(in).WithOutput(out) + + if err := form.Run(); err != nil { + return false, err + } + return confirmed, nil +} + // IsAborted reports huh user cancel. func IsAborted(err error) bool { return errors.Is(err, huh.ErrUserAborted)