Skip to content

Commit 2f26e36

Browse files
TMHSDigitalclaude
andcommitted
refactor(cli): run against injected streams via runWith (#158)
Step 1 of the run() split. run() now calls runWith(runArgs), which takes the arguments and stdin/stdout/stderr instead of reading os.Args and the os standard streams. output.Writer gains SetStdout/SetStderr, so every result format and the jsonl summary write to the injected stdout; "-" paths (-w, -dL, -r, -exclude-file) read the injected stdin; flag parse errors and usage go to the injected stderr. The end-to-end harness (runCLI, runCLIMerged) now passes buffers to runWith and no longer swaps os.Args, os.Stdin, os.Stdout or os.Stderr. A writer test checks every format honours SetStdout. No behaviour change for the binary. Remaining for #158: the session struct and scanOneTarget (steps 2-3) and splitting cliFlags (step 5). Refs #158 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01LpkeXSPwrzd7ZCuX3no7gD
1 parent 3a30307 commit 2f26e36

7 files changed

Lines changed: 155 additions & 98 deletions

File tree

‎internal/output/summary.go‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ func (w *Writer) Summary(s Summary) {
120120
}
121121
if w.stdout {
122122
w.clearProgressLocked()
123-
fmt.Printf("%s\n", data)
123+
_, _ = fmt.Fprintf(w.stdOut(), "%s\n", data)
124124
}
125125
if w.outWriter != nil {
126126
_, _ = fmt.Fprintf(w.outWriter, "%s\n", data)

‎internal/output/writer.go‎

Lines changed: 29 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -79,9 +79,10 @@ type Writer struct {
7979
outWriter *bufio.Writer
8080
simulate bool
8181
format Format
82-
stdout bool // mirror results to os.Stdout (false for the TUI)
83-
plain bool // text stdout prints bare names, no "Found:" banner
84-
records bool // text output appends record types and values
82+
stdout bool // mirror results to stdout (false for the TUI)
83+
out io.Writer // stdout destination; nil means os.Stdout
84+
plain bool // text stdout prints bare names, no "Found:" banner
85+
records bool // text output appends record types and values
8586

8687
stderr io.Writer // diagnostics destination; nil means os.Stderr
8788
progressLen int // width of the progress line currently on screen
@@ -116,6 +117,15 @@ func NewFile(outWriter *bufio.Writer, simulate bool, format Format) *Writer {
116117
return &Writer{outWriter: outWriter, simulate: simulate, format: format, stdout: false}
117118
}
118119

120+
// SetStdout sends results meant for stdout to out instead of os.Stdout, so
121+
// the CLI can run against injected streams (#158). Call it before the first
122+
// result.
123+
func (w *Writer) SetStdout(out io.Writer) { w.out = out }
124+
125+
// SetStderr sends diagnostics, progress and notices to errOut instead of
126+
// os.Stderr.
127+
func (w *Writer) SetStderr(errOut io.Writer) { w.stderr = errOut }
128+
119129
// SetPlain makes text-mode stdout print bare subdomain names, one per line,
120130
// without the "Found:" banner, so output pipes straight into other tools. The
121131
// CLI enables it when stdout is not a terminal.
@@ -211,11 +221,11 @@ func (w *Writer) writeText(res Result) {
211221
if w.stdout {
212222
switch {
213223
case w.plain:
214-
fmt.Println(line)
224+
_, _ = fmt.Fprintln(w.stdOut(), line)
215225
case w.simulate:
216-
fmt.Printf("Found (SIMULATED): %s\n", line)
226+
_, _ = fmt.Fprintf(w.stdOut(), "Found (SIMULATED): %s\n", line)
217227
default:
218-
fmt.Printf("Found: %s\n", line)
228+
_, _ = fmt.Fprintf(w.stdOut(), "Found: %s\n", line)
219229
}
220230
}
221231
if w.outWriter != nil {
@@ -268,7 +278,7 @@ func (w *Writer) writeJSONElement(res Result) {
268278
w.jsonOpen = true
269279
data := bytes.TrimSuffix(w.jsonBuf.Bytes(), []byte("\n")) // Encode ends each value with a newline
270280
if w.stdout {
271-
_, _ = os.Stdout.Write(data)
281+
_, _ = w.stdOut().Write(data)
272282
}
273283
if w.outWriter != nil {
274284
_, _ = w.outWriter.Write(data)
@@ -294,7 +304,7 @@ func (w *Writer) writeJSONL(res Result) {
294304
return
295305
}
296306
if w.stdout {
297-
fmt.Printf("%s\n", data)
307+
_, _ = fmt.Fprintf(w.stdOut(), "%s\n", data)
298308
}
299309
if w.outWriter != nil {
300310
_, _ = fmt.Fprintf(w.outWriter, "%s\n", data)
@@ -317,7 +327,7 @@ func (w *Writer) ensureCSV() {
317327
header = append(header, "change")
318328
}
319329
if w.stdout {
320-
w.csvStdout = csv.NewWriter(os.Stdout)
330+
w.csvStdout = csv.NewWriter(w.stdOut())
321331
_ = w.csvStdout.Write(header)
322332
}
323333
if w.outWriter != nil {
@@ -369,7 +379,7 @@ func (w *Writer) Finish() error {
369379
}
370380
w.jsonOpen = false
371381
if w.stdout {
372-
fmt.Print(end)
382+
_, _ = io.WriteString(w.stdOut(), end)
373383
}
374384
if w.outWriter != nil {
375385
if _, err := w.outWriter.WriteString(end); err != nil {
@@ -395,7 +405,15 @@ func (w *Writer) Finish() error {
395405
return nil
396406
}
397407

398-
// errOut is where diagnostics go; tests may swap it.
408+
// stdOut is where results meant for stdout go.
409+
func (w *Writer) stdOut() io.Writer {
410+
if w.out != nil {
411+
return w.out
412+
}
413+
return os.Stdout
414+
}
415+
416+
// errOut is where diagnostics go.
399417
func (w *Writer) errOut() io.Writer {
400418
if w.stderr != nil {
401419
return w.stderr

‎internal/output/writer_test.go‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -606,3 +606,31 @@ func TestTakeoverHintOutput(t *testing.T) {
606606
t.Errorf("text without -show-records = %q, want the bare name", out)
607607
}
608608
}
609+
610+
// TestSetStdoutCapturesEveryFormat covers #158: with SetStdout, every format
611+
// (and the jsonl summary) writes to the injected writer, never os.Stdout, so
612+
// the CLI can run against in-memory streams.
613+
func TestSetStdoutCapturesEveryFormat(t *testing.T) {
614+
for _, format := range []Format{FormatText, FormatJSON, FormatJSONL, FormatCSV} {
615+
var out, errOut bytes.Buffer
616+
w := New(nil, false, format)
617+
w.SetStdout(&out)
618+
w.SetStderr(&errOut)
619+
leaked := captureStdout(t, func() {
620+
w.Result("www.example.com", []dns.Record{{Type: "A", Value: "192.0.2.1"}})
621+
w.Summary(Summary{})
622+
if err := w.Finish(); err != nil {
623+
t.Fatal(err)
624+
}
625+
})
626+
if leaked != "" {
627+
t.Errorf("format %v: %q went to os.Stdout", format, leaked)
628+
}
629+
if !strings.Contains(out.String(), "www.example.com") {
630+
t.Errorf("format %v: injected stdout = %q, want the result", format, out.String())
631+
}
632+
if format == FormatJSONL && !strings.Contains(out.String(), "verdict") {
633+
t.Errorf("jsonl summary missing from injected stdout: %q", out.String())
634+
}
635+
}
636+
}

‎main.go‎

Lines changed: 62 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@ import (
2828
"errors"
2929
"flag"
3030
"fmt"
31+
"io"
3132
"math/rand/v2"
3233
"os"
3334
"os/signal"
@@ -160,20 +161,33 @@ type cliFlags struct {
160161
pool *dns.Pool // built from -r; nil means the single -dns-server
161162
excludes []string // -exclude and -exclude-file patterns, merged
162163
defaults *defaultsLoader // where config-file and env values came from; nil in tests
164+
stdin io.Reader // read for a "-" path; nil means os.Stdin
165+
}
166+
167+
// readLines reads path, or f.stdin when path is "-".
168+
func (f cliFlags) readLines(path string) ([]string, error) {
169+
if path == wordlist.Stdin && f.stdin != nil {
170+
return wordlist.ReadLinesFrom(f.stdin)
171+
}
172+
return wordlist.ReadLines(path)
163173
}
164174

165175
// parseFlags parses args (without the program name). Flags may appear before or
166176
// after the domain; the returned positionals are every non-flag argument.
167177
func parseFlags(args []string) (cliFlags, []string, *flag.FlagSet, error) {
168-
return parseFlagsWith(args, nil)
178+
return parseFlagsWith(args, nil, nil)
169179
}
170180

171181
// parseFlagsWith is parseFlags with applyDefaults run after the flags are
172182
// defined and before the command line is parsed, so config-file and
173183
// environment defaults sit between built-in defaults and explicit flags (#88).
174-
func parseFlagsWith(args []string, applyDefaults func(*flag.FlagSet) error) (cliFlags, []string, *flag.FlagSet, error) {
184+
// Parse errors and usage go to stderr; nil means os.Stderr.
185+
func parseFlagsWith(args []string, applyDefaults func(*flag.FlagSet) error, stderr io.Writer) (cliFlags, []string, *flag.FlagSet, error) {
175186
var f cliFlags
176187
fs := flag.NewFlagSet(ProgramName, flag.ContinueOnError)
188+
if stderr != nil {
189+
fs.SetOutput(stderr)
190+
}
177191
fs.BoolVar(&f.tui, "tui", false, "Launch the interactive terminal UI (all other flags are ignored)")
178192
fs.BoolVar(&f.printConfig, "print-config", false, "Print every setting's effective value and its source (flag, env, config or default), then exit")
179193
fs.StringVar(&f.wordlistFile, "w", "", "Path to the wordlist file (- for stdin); omitted: the bundled top-5000 list")
@@ -288,7 +302,6 @@ func validateArgs(f cliFlags, positionals []string, fs *flag.FlagSet, out *outpu
288302
if len(positionals) == 0 && f.domainList == "" {
289303
// Say what is missing before the full flag list (#58).
290304
out.Error("missing <domain> (or -dL <domains_file>)")
291-
fs.SetOutput(os.Stderr)
292305
fs.Usage()
293306
return false
294307
}
@@ -371,7 +384,7 @@ func loadPool(f cliFlags, out *output.Writer) (*dns.Pool, int) {
371384
out.Info("Note: -r is ignored in simulation mode, which sends no DNS queries")
372385
return nil, exitOK
373386
}
374-
lines, err := wordlist.ReadLines(f.resolvers)
387+
lines, err := f.readLines(f.resolvers)
375388
if err != nil {
376389
out.Error("reading -r resolver list: %v", err)
377390
return nil, exitFailure
@@ -416,7 +429,7 @@ func loadExcludes(f cliFlags) ([]string, error) {
416429
if f.excludeFile == "" {
417430
return patterns, nil
418431
}
419-
lines, err := wordlist.ReadLines(f.excludeFile)
432+
lines, err := f.readLines(f.excludeFile)
420433
if err != nil {
421434
return nil, err
422435
}
@@ -435,7 +448,7 @@ func loadTargets(f cliFlags, domain string, out *output.Writer) ([]string, bool)
435448
if f.domainList == "" {
436449
return []string{domain}, true
437450
}
438-
lines, err := wordlist.ReadLines(f.domainList)
451+
lines, err := f.readLines(f.domainList)
439452
if err != nil {
440453
out.Error("reading domain list: %v", err)
441454
return nil, false
@@ -478,13 +491,13 @@ func openOutputFile(path string, testMode bool, format output.Format, out *outpu
478491
return output.New(f.Writer, testMode, format), f, true
479492
}
480493

481-
// stdoutIsTerminal reports whether stdout is an interactive terminal rather than
482-
// a pipe or file.
483-
func stdoutIsTerminal() bool { return isTerminal(os.Stdout) }
484-
485-
// isTerminal reports whether f is a character device (a terminal) rather than
486-
// a pipe or file.
487-
func isTerminal(f *os.File) bool {
494+
// isTerminal reports whether w is a character device (a terminal) rather than
495+
// a pipe, file or in-memory buffer.
496+
func isTerminal(w io.Writer) bool {
497+
f, ok := w.(*os.File)
498+
if !ok {
499+
return false
500+
}
488501
fi, err := f.Stat()
489502
return err == nil && fi.Mode()&os.ModeCharDevice != 0
490503
}
@@ -553,28 +566,43 @@ func logScanBreakdown(domain string, ev scan.Event, out *output.Writer) {
553566
}
554567
}
555568

556-
func run() (code int) {
569+
// runArgs is the process environment a run reads: the arguments after the
570+
// program name and the standard streams. Tests pass their own, so they do
571+
// not swap os.Args, os.Stdin, os.Stdout and os.Stderr (#158).
572+
type runArgs struct {
573+
args []string
574+
stdin io.Reader
575+
stdout io.Writer
576+
stderr io.Writer
577+
}
578+
579+
func run() int {
580+
return runWith(runArgs{args: os.Args[1:], stdin: os.Stdin, stdout: os.Stdout, stderr: os.Stderr})
581+
}
582+
583+
func runWith(a runArgs) (code int) {
557584
// completion, man (#88): handled before flag parsing.
558-
if code, ok := runSubcommand(os.Args[1:], os.Stdout, os.Stderr); ok {
585+
if code, ok := runSubcommand(a.args, a.stdout, a.stderr); ok {
559586
return code
560587
}
561588

562-
args, resume, resumeErr := resumeArgs(os.Args[1:])
589+
args, resume, resumeErr := resumeArgs(a.args)
563590
if resumeErr != nil {
564-
_, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", resumeErr)
591+
_, _ = fmt.Fprintf(a.stderr, "Error: %v\n", resumeErr)
565592
return exitUsage
566593
}
567594
defaults := newDefaultsLoader()
568-
f, positionals, fs, parseErr := parseFlagsWith(args, defaults.apply)
595+
f, positionals, fs, parseErr := parseFlagsWith(args, defaults.apply, a.stderr)
569596
f.defaults = defaults
597+
f.stdin = a.stdin
570598
if errors.Is(parseErr, errConfig) {
571599
// -version, -print-config and -tui stay usable with a broken config,
572600
// so the bad value can be found and fixed (#116).
573601
if !f.showVersion && !f.printConfig && !f.tui {
574-
_, _ = fmt.Fprintf(os.Stderr, "Error: %v\n", parseErr)
602+
_, _ = fmt.Fprintf(a.stderr, "Error: %v\n", parseErr)
575603
return exitUsage
576604
}
577-
_, _ = fmt.Fprintf(os.Stderr, "Warning: %v\n", parseErr)
605+
_, _ = fmt.Fprintf(a.stderr, "Warning: %v\n", parseErr)
578606
parseErr = nil
579607
}
580608
if parseErr != nil {
@@ -589,26 +617,32 @@ func run() (code int) {
589617
// (-o -tui) or an argument after "--" (#58).
590618
if f.tui {
591619
if fs.NFlag() > 1 || len(positionals) > 0 {
592-
fmt.Fprintln(os.Stderr, "Warning: -tui ignores every other flag and argument; set them in the form instead")
620+
_, _ = fmt.Fprintln(a.stderr, "Warning: -tui ignores every other flag and argument; set them in the form instead")
593621
}
594622
return tui.Start(tui.Options{Version: resolveVersion(), Settings: defaults.settings(fs)})
595623
}
596624

597625
if f.printConfig {
598-
defaults.printConfig(os.Stdout, fs)
626+
defaults.printConfig(a.stdout, fs)
599627
return exitOK
600628
}
601629

602630
// -version answers before anything else prints, banners included (#58).
603631
if f.showVersion {
604-
fmt.Println(formatVersion())
632+
_, _ = fmt.Fprintln(a.stdout, formatVersion())
605633
return exitOK
606634
}
607635

608636
format, formatErr := output.ParseFormat(f.format)
609637
recordTypes, typesErr := dns.ParseTypes(f.recordTypes)
610638
maxAttempts, fromRetries, err := effectiveAttempts(f.attempts, f.retries, defaults.source(fs, "attempts"), defaults.source(fs, "retries"))
611-
out := output.New(nil, f.testMode, format)
639+
// Every writer of the run uses the injected streams.
640+
wire := func(w *output.Writer) *output.Writer {
641+
w.SetStdout(a.stdout)
642+
w.SetStderr(a.stderr)
643+
return w
644+
}
645+
out := wire(output.New(nil, f.testMode, format))
612646
out.SetQuiet(f.silent)
613647
if fromRetries {
614648
out.Info("Warning: -retries is deprecated, use -attempts instead") // quiet under -silent (#166)
@@ -751,6 +785,7 @@ func run() (code int) {
751785
if !ok {
752786
return exitFailure
753787
}
788+
wire(combined)
754789
var outWriter *bufio.Writer
755790
if outFile != nil {
756791
outWriter = outFile.Writer
@@ -759,7 +794,7 @@ func run() (code int) {
759794
// the full current results, ready to be the next run's -diff input (#84).
760795
var fileOut *output.Writer
761796
if diff != nil && outFile != nil {
762-
fileOut = output.NewFile(outFile.Writer, f.testMode, format)
797+
fileOut = wire(output.NewFile(outFile.Writer, f.testMode, format))
763798
} else {
764799
out = combined
765800
}
@@ -770,7 +805,7 @@ func run() (code int) {
770805
}
771806
// Bare names when piped or -silent (no "Found:" banner), human-friendly
772807
// on a terminal.
773-
w.SetPlain(f.silent || !stdoutIsTerminal())
808+
w.SetPlain(f.silent || !isTerminal(a.stdout))
774809
w.SetQuiet(f.silent)
775810
w.SetShowRecords(f.showRecords)
776811
w.SetSeed(f.seed)
@@ -820,7 +855,7 @@ func run() (code int) {
820855
if f.silent {
821856
f.showProgress = false
822857
}
823-
if !isTerminal(os.Stderr) {
858+
if !isTerminal(a.stderr) {
824859
if defaults.source(fs, "progress") != sourceDefault {
825860
out.SetProgressLines(true)
826861
} else {

0 commit comments

Comments
 (0)