Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
119 changes: 119 additions & 0 deletions cmd/gitprofile_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
92 changes: 90 additions & 2 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,20 @@ package cmd

import (
"fmt"
"io"
"os"
"sort"
"strings"

"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"
)

Expand All @@ -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.
Expand All @@ -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{
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
},
}

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
},
}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand All @@ -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
Expand Down
68 changes: 68 additions & 0 deletions internal/gitprofile/gitprofile.go
Original file line number Diff line number Diff line change
@@ -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{}
Loading
Loading