Files
Enterprise-Knowledge-Base/cli/internal/iostreams/iostreams.go
T
nullkey 6f8b825f5f feat(cli): agent-first WeKnora CLI
The `weknora` command-line client for the WeKnora RAG server. Full command
surface: kb / doc / chunk / session / message / agent / model / search / chat /
auth / profile / link / api / mcp / skills / config / doctor / schema /
exit-codes.

Agent-first wire contract: JSON envelope by default, typed error codes mapped to
stable exit codes, error.retry_argv / retryable / partial-failure status,
global --dry-run preview, the exit-10 confirmation protocol for writes, and
control/ANSI/Bidi input hygiene. Stateless env-credential auth
(WEKNORA_API_KEY / WEKNORA_TOKEN + WEKNORA_HOST) for headless/CI/agent use.
A curated read-only MCP tool surface (`mcp serve`) and embedded Agent Skills
(`skills install`). Extensive unit + contract-golden tests and CI.
2026-07-06 22:53:01 +08:00

76 lines
2.1 KiB
Go

// Package iostreams wraps stdout/stderr/stdin with TTY detection and color awareness.
//
// Tests swap the package-level singleton via SetForTest; production code reads
// the global IO directly. (Tests must not call SetForTest from t.Parallel(),
// since the swap is process-global.)
package iostreams
import (
"bytes"
"io"
"os"
"testing"
"github.com/mattn/go-isatty"
)
// IOStreams holds standard I/O handles plus environment-derived flags.
type IOStreams struct {
In io.Reader
Out io.Writer
Err io.Writer
stdoutTTY bool
stderrTTY bool
}
// IO is the package-level singleton.
var IO *IOStreams = newProduction()
func newProduction() *IOStreams {
return &IOStreams{
In: os.Stdin,
Out: os.Stdout,
Err: os.Stderr,
stdoutTTY: isatty.IsTerminal(os.Stdout.Fd()) || isatty.IsCygwinTerminal(os.Stdout.Fd()),
stderrTTY: isatty.IsTerminal(os.Stderr.Fd()) || isatty.IsCygwinTerminal(os.Stderr.Fd()),
}
}
// IsStdoutTTY reports whether stdout is a terminal.
func (s *IOStreams) IsStdoutTTY() bool { return s.stdoutTTY }
// IsStderrTTY reports whether stderr is a terminal.
func (s *IOStreams) IsStderrTTY() bool { return s.stderrTTY }
// SetForTest replaces the package singleton with in-memory buffers for the
// duration of t. Call it once per test. Not safe under t.Parallel().
func SetForTest(t *testing.T) (out, errBuf *bytes.Buffer) {
t.Helper()
saved := IO
out = &bytes.Buffer{}
errBuf = &bytes.Buffer{}
IO = &IOStreams{In: bytes.NewReader(nil), Out: out, Err: errBuf}
t.Cleanup(func() { IO = saved })
return out, errBuf
}
// SetForTestWithTTY is like SetForTest but reports IsStdoutTTY/IsStderrTTY
// = true so tests can exercise interactive code paths (confirm prompts,
// color, fancy renderers). Not safe under t.Parallel().
func SetForTestWithTTY(t *testing.T) (out, errBuf *bytes.Buffer) {
t.Helper()
saved := IO
out = &bytes.Buffer{}
errBuf = &bytes.Buffer{}
IO = &IOStreams{
In: bytes.NewReader(nil),
Out: out,
Err: errBuf,
stdoutTTY: true,
stderrTTY: true,
}
t.Cleanup(func() { IO = saved })
return out, errBuf
}