From 6ee86f259390c351bb4ba432a18dcf3c5c008b38 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Wed, 5 Aug 2026 12:47:20 +1000 Subject: [PATCH] feat(setup): Prompter interface and a TTY-gated terminal implementation archie-core-via. internal/infrastructure/configuration/setup defines Prompter -- Select, ReadLine, ReadSecret, Confirm, all context-aware -- which is all the setup step logic (to follow) needs from a prompt surface. No terminal dependency, so steps are testable without a TTY. internal/infrastructure/terminalprompt.Terminal is the real implementation, using golang.org/x/term. New refuses construction when its input isn't a real terminal, with a message naming the problem -- enforcing "a non-TTY invocation fails with a clear message rather than writing a partial config" at the earliest possible point, rather than falling back to a plain read that would silently accept piped/scripted input (ssh, `archied setup < answers.txt`, CI). Terminal satisfies Prompter structurally; this package does not import that one, so there's no infrastructure -> infrastructure edge for what Go's type system already gives for free. Each blocking read runs in a goroutine raced against ctx.Done(), so Ctrl+C returns promptly instead of leaving the operator stuck; the losing goroutine is abandoned on cancellation; term.ReadPassword's own raw-mode restoration is not interruptible, so an abandoned secret read can leave the terminal in raw mode until it unblocks on its own -- documented on Terminal.readSecret rather than worked around, since a cancelled setup command is expected to exit shortly after via its own signal handling anyway. Tested by constructing a Terminal directly (bypassing New, same package) over a plain pipe with an injected readSecret seam -- New's TTY gate itself is exercised separately against a real os.Pipe(). No weakening of the production constructor for testability. Refs archie-core-via --- go.mod | 1 + go.sum | 4 - .../configuration/setup/prompter.go | 28 +++ .../terminalprompt/terminalprompt.go | 173 +++++++++++++++ .../terminalprompt/terminalprompt_test.go | 210 ++++++++++++++++++ 5 files changed, 412 insertions(+), 4 deletions(-) create mode 100644 internal/infrastructure/configuration/setup/prompter.go create mode 100644 internal/infrastructure/terminalprompt/terminalprompt.go create mode 100644 internal/infrastructure/terminalprompt/terminalprompt_test.go diff --git a/go.mod b/go.mod index b4b9729b1..97b18a9c4 100644 --- a/go.mod +++ b/go.mod @@ -77,5 +77,6 @@ require ( github.com/samcharles93/NellDB v0.3.0 github.com/samcharles93/ai-sdk v0.1.19 github.com/traefik/yaegi v0.16.1 + golang.org/x/term v0.44.0 gopkg.in/yaml.v3 v3.0.1 ) diff --git a/go.sum b/go.sum index 4d83e79b3..3a111cb42 100644 --- a/go.sum +++ b/go.sum @@ -146,12 +146,8 @@ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94 github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= -github.com/samcharles93/NellDB v0.2.5 h1:VEasjyB4opTFAfWnV3s9TEHkfA41ee+7gYD8LqKnvns= -github.com/samcharles93/NellDB v0.2.5/go.mod h1:vyfd6/T2Cp5U0acoh2LrebJteZqoFObedDZTxP0j4W0= github.com/samcharles93/NellDB v0.3.0 h1:xRBJZhO0iuGuMFl5jxPAROw7tD+VdWU8kljbaNz9AwQ= github.com/samcharles93/NellDB v0.3.0/go.mod h1:vyfd6/T2Cp5U0acoh2LrebJteZqoFObedDZTxP0j4W0= -github.com/samcharles93/ai-sdk v0.1.18 h1:Jvz2OSnzJ68XCAiTHdLKKvgoNI/rKrNw9LJ7jbZs55c= -github.com/samcharles93/ai-sdk v0.1.18/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= github.com/samcharles93/ai-sdk v0.1.19 h1:j/F4pRx9CEjsZmW41FLaM48P+1WRitMLLTqnvlJuBLI= github.com/samcharles93/ai-sdk v0.1.19/go.mod h1:a4JYsUrwGsmm2eiXgrpcKExtYe7uHQ5zsHDbbkcPB6o= github.com/sergi/go-diff v1.4.0 h1:n/SP9D5ad1fORl+llWyN+D6qoUETXNZARKjyY2/KVCw= diff --git a/internal/infrastructure/configuration/setup/prompter.go b/internal/infrastructure/configuration/setup/prompter.go new file mode 100644 index 000000000..f3ebc70dd --- /dev/null +++ b/internal/infrastructure/configuration/setup/prompter.go @@ -0,0 +1,28 @@ +// Package setup builds a config.Config and the TOML edits to persist it, +// driven by archied's interactive first-run configuration flow. It has no +// terminal dependency of its own: everything it needs from a user-facing +// prompt surface is the [Prompter] interface below, so the step logic is +// testable end to end without a TTY. +package setup + +import "context" + +// Prompter is what setup's step logic needs from a prompt surface. The real +// implementation talks to a terminal (internal/infrastructure/ +// terminalprompt); tests drive steps through a fake. +// +// Every method takes a context so a step can be cancelled mid-prompt (e.g. +// Ctrl+C) rather than leaving the operator stuck at a prompt an outer +// timeout or signal has already decided to abandon. +type Prompter interface { + // Select presents options and returns the chosen index. Returns -1 and + // ctx.Err() if ctx is done before an answer is given. + Select(ctx context.Context, prompt string, options []string) (int, error) + // ReadLine reads one line of visible input. An empty answer returns + // defaultValue. + ReadLine(ctx context.Context, prompt, defaultValue string) (string, error) + // ReadSecret reads one line of input without echoing it. + ReadSecret(ctx context.Context, prompt string) (string, error) + // Confirm asks a yes/no question. An empty answer returns defaultYes. + Confirm(ctx context.Context, prompt string, defaultYes bool) (bool, error) +} diff --git a/internal/infrastructure/terminalprompt/terminalprompt.go b/internal/infrastructure/terminalprompt/terminalprompt.go new file mode 100644 index 000000000..997673f16 --- /dev/null +++ b/internal/infrastructure/terminalprompt/terminalprompt.go @@ -0,0 +1,173 @@ +// Package terminalprompt is the real, TTY-backed implementation of the +// prompt surface archied setup needs (see internal/infrastructure/ +// configuration/setup.Prompter, which this package satisfies structurally +// -- it does not import that package, so there is no infrastructure -> +// infrastructure edge for what is, structurally, just an interface +// satisfaction). +package terminalprompt + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "os" + "strconv" + "strings" + + "golang.org/x/term" +) + +// Terminal prompts over an interactive TTY. The zero value is not usable; +// call [New]. +type Terminal struct { + in *os.File + out io.Writer + r *bufio.Reader + + // readSecret reads one line from the given fd without echoing it. It is + // a seam so tests can exercise ReadSecret's prompt/cancellation + // behaviour over a pipe -- term.ReadPassword itself only works on a + // real TTY fd, which New already requires for production use, so this + // field is never swapped outside a test. + readSecret func(fd int) ([]byte, error) +} + +// New returns a Terminal reading from in and writing prompts to out. in +// must be a real terminal: setup's non-interactive failure requirement +// ("a non-TTY invocation without sufficient input fails with a clear +// message rather than writing a partial config") is enforced here, at +// construction, rather than by falling back to a degraded read mode that +// would silently accept piped or redirected input and produce a config +// nobody typed. +func New(in *os.File, out io.Writer) (*Terminal, error) { + if !term.IsTerminal(int(in.Fd())) { + return nil, fmt.Errorf( + "terminalprompt: %s is not a terminal; archied setup requires an "+ + "interactive session (input cannot be piped, redirected, or "+ + "scripted)", in.Name()) + } + return &Terminal{ + in: in, + out: out, + r: bufio.NewReader(in), + readSecret: term.ReadPassword, + }, nil +} + +// readLine runs a blocking read in a goroutine and races it against +// ctx.Done(). On cancellation the read is abandoned: the goroutine leaks +// until the abandoned read itself returns (real input or EOF), which is +// accepted because a cancelled setup command is expected to exit shortly +// after via its own signal handling, taking the leaked goroutine with it. +func (t *Terminal) readLine(ctx context.Context) (string, error) { + type result struct { + line string + err error + } + ch := make(chan result, 1) + go func() { + line, err := t.r.ReadString('\n') + ch <- result{line: strings.TrimRight(line, "\r\n"), err: err} + }() + select { + case <-ctx.Done(): + return "", ctx.Err() + case res := <-ch: + if res.err != nil && !errors.Is(res.err, io.EOF) { + return "", res.err + } + return res.line, nil + } +} + +// readSecretLine mirrors readLine for a non-echoing read. See the doc +// comment on Terminal.readSecret for why term.ReadPassword's own raw-mode +// restoration is not interruptible: an abandoned read on cancellation can +// leave the terminal in raw mode until it unblocks on its own. +func (t *Terminal) readSecretLine(ctx context.Context) (string, error) { + type result struct { + line string + err error + } + ch := make(chan result, 1) + go func() { + b, err := t.readSecret(int(t.in.Fd())) + ch <- result{line: string(b), err: err} + }() + select { + case <-ctx.Done(): + return "", ctx.Err() + case res := <-ch: + if res.err != nil { + return "", res.err + } + return res.line, nil + } +} + +// Select presents options and returns the chosen index. +func (t *Terminal) Select(ctx context.Context, prompt string, options []string) (int, error) { + for { + fmt.Fprintln(t.out, prompt) + for i, opt := range options { + fmt.Fprintf(t.out, " %d) %s\n", i+1, opt) + } + fmt.Fprintf(t.out, "Select [1-%d]: ", len(options)) + line, err := t.readLine(ctx) + if err != nil { + return -1, err + } + n, convErr := strconv.Atoi(strings.TrimSpace(line)) + if convErr != nil || n < 1 || n > len(options) { + fmt.Fprintf(t.out, "Please enter a number between 1 and %d.\n", len(options)) + continue + } + return n - 1, nil + } +} + +// ReadLine reads one line of visible input, falling back to defaultValue +// when the answer is empty. +func (t *Terminal) ReadLine(ctx context.Context, prompt, defaultValue string) (string, error) { + fmt.Fprint(t.out, prompt) + line, err := t.readLine(ctx) + if err != nil { + return "", err + } + if strings.TrimSpace(line) == "" { + return defaultValue, nil + } + return line, nil +} + +// ReadSecret reads one line of input without echoing it. +func (t *Terminal) ReadSecret(ctx context.Context, prompt string) (string, error) { + fmt.Fprint(t.out, prompt) + line, err := t.readSecretLine(ctx) + fmt.Fprintln(t.out) + if err != nil { + return "", err + } + return line, nil +} + +// Confirm asks a yes/no question, falling back to defaultYes when the +// answer is empty. +func (t *Terminal) Confirm(ctx context.Context, prompt string, defaultYes bool) (bool, error) { + suffix := "[y/N]" + if defaultYes { + suffix = "[Y/n]" + } + fmt.Fprintf(t.out, "%s %s: ", prompt, suffix) + line, err := t.readLine(ctx) + if err != nil { + return false, err + } + line = strings.TrimSpace(strings.ToLower(line)) + if line == "" { + return defaultYes, nil + } + return line == "y" || line == "yes", nil +} diff --git a/internal/infrastructure/terminalprompt/terminalprompt_test.go b/internal/infrastructure/terminalprompt/terminalprompt_test.go new file mode 100644 index 000000000..b4d2fe2f0 --- /dev/null +++ b/internal/infrastructure/terminalprompt/terminalprompt_test.go @@ -0,0 +1,210 @@ +package terminalprompt + +import ( + "bufio" + "bytes" + "context" + "errors" + "io" + "os" + "strings" + "testing" + "time" +) + +// New must refuse a non-terminal input with a clear message rather than +// silently degrading to a plain read -- that degraded path is exactly what +// would let a piped/scripted invocation produce a partial config nobody +// typed. +func TestNew_RejectsNonTerminalInput(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer r.Close() + defer w.Close() + + _, err = New(r, io.Discard) + if err == nil { + t.Fatal("New(pipe) = nil error, want a rejection") + } + if !strings.Contains(err.Error(), "terminal") { + t.Errorf("New(pipe) error = %q, want it to explain the input is not a terminal", err.Error()) + } +} + +// newForTest builds a Terminal directly, bypassing New's TTY gate, so the +// prompt/parsing logic can be exercised over a plain pipe. Production code +// only ever constructs a Terminal through New; this mirrors what the +// package review called for -- inject the fd, don't weaken the real +// constructor for testability. +func newForTest(t *testing.T, in io.Reader, readSecret func(int) ([]byte, error)) (*Terminal, *bytes.Buffer) { + t.Helper() + var out bytes.Buffer + return &Terminal{ + in: nil, + out: &out, + r: bufio.NewReader(in), + readSecret: readSecret, + }, &out +} + +func TestSelect_ParsesAValidChoice(t *testing.T) { + term, out := newForTest(t, strings.NewReader("2\n"), nil) + i, err := term.Select(context.Background(), "Pick one", []string{"a", "b", "c"}) + if err != nil { + t.Fatalf("Select: %v", err) + } + if i != 1 { + t.Errorf("Select() = %d, want 1", i) + } + if !strings.Contains(out.String(), "Pick one") { + t.Errorf("prompt not written to out: %q", out.String()) + } +} + +func TestSelect_RepromptsOnInvalidChoiceThenAccepts(t *testing.T) { + term, out := newForTest(t, strings.NewReader("nope\n99\n1\n"), nil) + i, err := term.Select(context.Background(), "Pick one", []string{"a", "b"}) + if err != nil { + t.Fatalf("Select: %v", err) + } + if i != 0 { + t.Errorf("Select() = %d, want 0", i) + } + if strings.Count(out.String(), "Pick one") != 3 { + t.Errorf("expected the prompt to repeat for each invalid answer, got:\n%s", out.String()) + } +} + +func TestReadLine_EmptyAnswerReturnsDefault(t *testing.T) { + term, _ := newForTest(t, strings.NewReader("\n"), nil) + got, err := term.ReadLine(context.Background(), "Name: ", "fallback") + if err != nil { + t.Fatalf("ReadLine: %v", err) + } + if got != "fallback" { + t.Errorf("ReadLine() = %q, want %q", got, "fallback") + } +} + +func TestReadLine_NonEmptyAnswerWins(t *testing.T) { + term, _ := newForTest(t, strings.NewReader("Ada\n"), nil) + got, err := term.ReadLine(context.Background(), "Name: ", "fallback") + if err != nil { + t.Fatalf("ReadLine: %v", err) + } + if got != "Ada" { + t.Errorf("ReadLine() = %q, want %q", got, "Ada") + } +} + +func TestConfirm(t *testing.T) { + tests := []struct { + name string + input string + defaultYes bool + want bool + }{ + {name: "empty answer takes the default (yes)", input: "\n", defaultYes: true, want: true}, + {name: "empty answer takes the default (no)", input: "\n", defaultYes: false, want: false}, + {name: "y overrides a false default", input: "y\n", defaultYes: false, want: true}, + {name: "yes overrides a false default", input: "yes\n", defaultYes: false, want: true}, + {name: "n overrides a true default", input: "n\n", defaultYes: true, want: false}, + {name: "case insensitive", input: "Y\n", defaultYes: false, want: true}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + term, _ := newForTest(t, strings.NewReader(tc.input), nil) + got, err := term.Confirm(context.Background(), "Continue?", tc.defaultYes) + if err != nil { + t.Fatalf("Confirm: %v", err) + } + if got != tc.want { + t.Errorf("Confirm() = %v, want %v", got, tc.want) + } + }) + } +} + +func TestReadSecret_UsesTheInjectedReaderNotEcho(t *testing.T) { + fakeReadSecret := func(fd int) ([]byte, error) { + return []byte("s3cr3t"), nil + } + term, out := newForTest(t, strings.NewReader(""), fakeReadSecret) + got, err := term.ReadSecret(context.Background(), "Token: ") + if err != nil { + t.Fatalf("ReadSecret: %v", err) + } + if got != "s3cr3t" { + t.Errorf("ReadSecret() = %q, want %q", got, "s3cr3t") + } + if strings.Contains(out.String(), "s3cr3t") { + t.Errorf("secret value must never be written to out, got: %q", out.String()) + } +} + +func TestReadSecret_PropagatesReadError(t *testing.T) { + wantErr := errors.New("boom") + fakeReadSecret := func(fd int) ([]byte, error) { return nil, wantErr } + term, _ := newForTest(t, strings.NewReader(""), fakeReadSecret) + _, err := term.ReadSecret(context.Background(), "Token: ") + if !errors.Is(err, wantErr) { + t.Fatalf("ReadSecret() error = %v, want %v", err, wantErr) + } +} + +// A cancelled context must return promptly rather than block forever on a +// read that will never come -- e.g. Ctrl+C at a prompt with no answer +// typed yet. +func TestReadLine_CancelledContextReturnsPromptly(t *testing.T) { + r, w, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + defer r.Close() + defer w.Close() // never written to: the read blocks until cancellation + + term, _ := newForTest(t, r, nil) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + done := make(chan error, 1) + go func() { + _, err := term.ReadLine(ctx, "Name: ", "") + done <- err + }() + + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Errorf("ReadLine() error = %v, want context.Canceled", err) + } + case <-time.After(2 * time.Second): + t.Fatal("ReadLine did not return promptly after cancellation") + } +} + +func TestReadSecret_CancelledContextReturnsPromptly(t *testing.T) { + blockForever := func(fd int) ([]byte, error) { + select {} // never returns; simulates a real blocking terminal read + } + term, _ := newForTest(t, strings.NewReader(""), blockForever) + ctx, cancel := context.WithCancel(context.Background()) + cancel() + + done := make(chan error, 1) + go func() { + _, err := term.ReadSecret(ctx, "Token: ") + done <- err + }() + + select { + case err := <-done: + if !errors.Is(err, context.Canceled) { + t.Errorf("ReadSecret() error = %v, want context.Canceled", err) + } + case <-time.After(2 * time.Second): + t.Fatal("ReadSecret did not return promptly after cancellation") + } +}