feat(cli): --format json default + NDJSON event stream + context→profile cascade + help calibration + docs (BREAKING)
D1 — --format default flipped to json regardless of TTY: - v0.6: smart default (text on TTY, json on pipe). - v0.7: always json; TTY only affects indent (compact in pipe). Enum values unchanged (text | json | ndjson). - Typed FormatMode enum replaces untyped string consts. - --format / --jq promoted to persistent root flags so unknown- subcommand paths still reach the typed-envelope guard (per-command registration in v0.6 would have rejected --format on unknown commands as cobra-prose exit 2). - WEKNORA_FORMAT env var added; precedence --format > env > default. Invalid env values silently ignored. D2 — chat / session ask default to NDJSON event-stream: - New cli/internal/output/ndjson_stream.go: InitEvent struct + EmitInit / EmitSDKEvent / WriteNDJSONLine helpers. EmitInit doc encodes the must-be-first-line invariant agents key on. - chat / session ask: --format json AND --format ndjson both emit one JSON event per line (no envelope wrapping). CLI injects exactly one `init` event at stream head carrying session_id + optional kb_id / agent_id / profile. Subsequent events pass through verbatim from the SDK (passthrough discipline per spec §5.1). - --format text keeps the SSE-style live renderer. context → profile full cascade: - Command group: cli/cmd/context/ → cli/cmd/profile/ (git mv; package contextcmd → profilecmd). - Global flag --context → --profile. Factory.ContextOverride → ProfileOverride. WEKNORA_PROFILE env var honored (--profile flag > env > config.CurrentContext). When --profile or WEKNORA_PROFILE references a missing profile, the error is input.invalid_argument with hint "weknora profile list" — not the destructive local.config_corrupt path (which would have told users to delete their config file). - Binding file .weknora/project.yaml field context: → profile: (no backwards-compat alias; re-run weknora link). - profile use JSON fields current_context / previous_context → current_profile / previous_profile. - weknora link JSON field context → profile. - CodeLocalContextNotFound → CodeLocalProfileNotFound (typed code rename). - Envelope top-level profile field populated via globalProfile (set by root PersistentPreRunE from Factory.ActiveProfile). chat / session ask NDJSON init event carries the same profile. - Rationale: "context" collided with LLM context window / RAG context / Go context.Context; mainstream multi-credential CLIs (AWS / Stripe / OpenAI / Anthropic / lark) all use "profile". H2/C1' help calibration: - AgentHelp gains Warnings []string; single SetAgentHelp helper routes on WEKNORA_AGENT_HELP=1 (emits JSON blob including warnings) vs human help (appends "AI agents:" block from same source). Warnings surface as both a structured JSON field and visible help-text addendum without drift. - 9 destructive commands carry warnings: kb / doc / agent / session / chunk delete; profile remove; kb / agent edit; auth logout. - weknora doc wait dedups ids at entry; SIGINT mid-wait returns silently (root signal handler maps to exit 130) instead of being miscategorised as operation.timeout / operation.failed. A4 — docs: - cli/AGENTS.md gains four agent-facing sections: Wire contract for AI agents (stdout / stderr / NDJSON / _notice evolution / SDK contract boundary); Deliberate deviations + mainstream alignments; Pre-1.0 breaking policy; Exit-10 anti-patterns. ERROR_REFERENCE table extended. - cli/README.md adds Agent quick start under Wire contract. - cli/CHANGELOG.md v0.7 section: BREAKING entries with migration notes, Added (WEKNORA_FORMAT / WEKNORA_PROFILE / retry_command / retry_after_seconds / risk / _notice reserved infra / meta.count / meta.has_more / doc fetch / doc create / session ask / doc delete --all / NDJSON init), Changed (docs additions), Deprecated (none — pre-release one-shot breaking). Spec: docs/superpowers/specs/2026-05-20-weknora-cli-v0.7-design.md §3 / §4 / §5 / §6 / §11
This commit is contained in:
@@ -1,13 +1,14 @@
|
||||
// Package-level note:
|
||||
//
|
||||
// SetAgentHelp wires structured agent-targeted help onto a cobra command.
|
||||
// Current coverage: chat, kb list. Adding it to another command requires
|
||||
// touching only that command's NewCmd (a 5-line copy of the existing call
|
||||
// sites).
|
||||
// Current coverage: chat, kb list, and destructive commands. Adding it to
|
||||
// another command requires touching only that command's NewCmd (a 5-line
|
||||
// copy of the existing call sites).
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
@@ -18,20 +19,25 @@ import (
|
||||
// `weknora <command> --help` with WEKNORA_AGENT_HELP=1. Distinct from
|
||||
// cobra's human help text — agent-readable JSON keyed by stable fields
|
||||
// so an LLM doesn't need to scrape the human help table.
|
||||
//
|
||||
// Warnings surface both as a JSON field (agent introspection) and as an
|
||||
// "AI agents:" block appended to human help. The two channels share a
|
||||
// single source list so they cannot drift.
|
||||
type AgentHelp struct {
|
||||
UsedFor string `json:"used_for"`
|
||||
RequiredFlags []string `json:"required_flags,omitempty"`
|
||||
Examples []string `json:"examples,omitempty"`
|
||||
Output string `json:"output,omitempty"`
|
||||
Warnings []string `json:"warnings,omitempty"`
|
||||
}
|
||||
|
||||
// SetAgentHelp attaches agent-targeted help metadata to a command. The
|
||||
// original HelpFunc is preserved for the human path; the agent path
|
||||
// activates only when WEKNORA_AGENT_HELP=1 (so human `--help` is
|
||||
// unaffected).
|
||||
// SetAgentHelp attaches agent-targeted help metadata to a command.
|
||||
//
|
||||
// Currently applied to a small set of representative commands (chat,
|
||||
// kb list); extend by calling SetAgentHelp in each command's NewCmd.
|
||||
// Routing:
|
||||
// - WEKNORA_AGENT_HELP=1: emit the AgentHelp JSON blob to stdout and
|
||||
// return — agents get clean parseable JSON, no trailing prose.
|
||||
// - Otherwise: render the normal human help, then append an
|
||||
// "AI agents:" block when Warnings is non-empty.
|
||||
func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
|
||||
origHelp := cmd.HelpFunc()
|
||||
cmd.SetHelpFunc(func(c *cobra.Command, args []string) {
|
||||
@@ -40,6 +46,14 @@ func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
|
||||
return
|
||||
}
|
||||
origHelp(c, args)
|
||||
if len(ah.Warnings) > 0 {
|
||||
w := c.OutOrStdout()
|
||||
fmt.Fprintln(w)
|
||||
fmt.Fprintln(w, "AI agents:")
|
||||
for _, msg := range ah.Warnings {
|
||||
fmt.Fprintln(w, "- "+msg)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -55,3 +55,46 @@ func TestSetAgentHelp_FallsThroughToHumanHelp(t *testing.T) {
|
||||
t.Errorf("human help missing from output:\n%s", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetAgentHelp_AgentJSON_NoTrailingWarningsProse(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "kb-delete-test"}
|
||||
SetAgentHelp(cmd, AgentHelp{
|
||||
UsedFor: "Delete a knowledge base",
|
||||
Warnings: []string{"irreversible"},
|
||||
})
|
||||
t.Setenv("WEKNORA_AGENT_HELP", "1")
|
||||
var buf bytes.Buffer
|
||||
cmd.SetOut(&buf)
|
||||
cmd.HelpFunc()(cmd, nil)
|
||||
|
||||
// Should be parseable as a single JSON object with the warnings field.
|
||||
var got AgentHelp
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
t.Fatalf("agent-help output is not valid JSON: %v\n%s", err, buf.String())
|
||||
}
|
||||
if len(got.Warnings) != 1 || got.Warnings[0] != "irreversible" {
|
||||
t.Errorf("warnings field missing or wrong: %v", got.Warnings)
|
||||
}
|
||||
// Should NOT contain the human-prose "AI agents:" block
|
||||
if bytes.Contains(buf.Bytes(), []byte("AI agents:")) {
|
||||
t.Errorf("agent JSON path leaked human prose:\n%s", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetAgentHelp_HumanHelp_AppendsWarningsBlock(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "kb-delete-test", Short: "short"}
|
||||
SetAgentHelp(cmd, AgentHelp{
|
||||
UsedFor: "Delete a KB",
|
||||
Warnings: []string{"irreversible"},
|
||||
})
|
||||
// Env unset → human help path
|
||||
var buf bytes.Buffer
|
||||
cmd.SetOut(&buf)
|
||||
cmd.HelpFunc()(cmd, nil)
|
||||
if !bytes.Contains(buf.Bytes(), []byte("AI agents:")) {
|
||||
t.Errorf("human help should include AI agents: block; got:\n%s", buf.String())
|
||||
}
|
||||
if !bytes.Contains(buf.Bytes(), []byte("- irreversible")) {
|
||||
t.Errorf("human help should list warning; got:\n%s", buf.String())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,7 +65,7 @@ func RunBatch(ctx context.Context, ids []string, op func(context.Context, string
|
||||
}
|
||||
|
||||
// EmitBatch writes the per-item outcomes per --format. JSON/NDJSON emit
|
||||
// the §4.5 batch envelope; human/text mode emits per-line "OK <id>" /
|
||||
// the §4.5 batch envelope; text mode emits per-line "OK <id>" /
|
||||
// "FAIL <id>: <msg>".
|
||||
//
|
||||
// resultFn builds the per-item Result map for successes; nil ⇒ omit.
|
||||
|
||||
@@ -175,7 +175,7 @@ func TestEmitBatch_Text_PerLine(t *testing.T) {
|
||||
{ID: "x", Err: nil},
|
||||
{ID: "y", Err: fmt.Errorf("boom")},
|
||||
}
|
||||
fopts := &FormatOptions{Mode: FormatHuman}
|
||||
fopts := &FormatOptions{Mode: FormatText}
|
||||
var buf bytes.Buffer
|
||||
|
||||
err := EmitBatch(outcomes, fopts, &buf, nil)
|
||||
|
||||
@@ -92,8 +92,8 @@ func ExitCode(err error) int {
|
||||
}
|
||||
|
||||
// PrintError writes err to w (typically stderr) in dual mode:
|
||||
// - text/human: code: msg\nhint: ...\nretry: ...
|
||||
// - json/ndjson: {ok:false, error:{...}, _notice?:...}
|
||||
// - text: code: msg\nhint: ...\nretry: ...
|
||||
// - json/ndjson: {ok:false, error:{...}, _notice?:...}
|
||||
//
|
||||
// Mode is read from globalFormatMode (set by root PersistentPreRunE).
|
||||
func PrintError(w io.Writer, err error) {
|
||||
|
||||
@@ -101,7 +101,7 @@ func TestPrintError_JSONMode_IncludesRetryAfter(t *testing.T) {
|
||||
|
||||
func TestPrintError_TextMode_WritesProse(t *testing.T) {
|
||||
t.Cleanup(func() { SetFormatMode("") })
|
||||
SetFormatMode("human")
|
||||
SetFormatMode("text")
|
||||
|
||||
err := NewError(CodeInputConfirmationRequired, "kb delete kb_x requires confirmation").
|
||||
WithHint("re-run with -y/--yes").
|
||||
|
||||
@@ -47,10 +47,10 @@ type Factory struct {
|
||||
Prompter func() prompt.Prompter
|
||||
Secrets func() (secrets.Store, error)
|
||||
|
||||
// ContextOverride, if non-empty, replaces config.CurrentContext for this
|
||||
// invocation only - set by the global --context flag in PersistentPreRun.
|
||||
// ProfileOverride, if non-empty, replaces config.CurrentContext for this
|
||||
// invocation only - set by the global --profile flag in PersistentPreRun.
|
||||
// Buildable Config() / Client() honor it without writing to disk.
|
||||
ContextOverride string
|
||||
ProfileOverride string
|
||||
}
|
||||
|
||||
// New constructs a production Factory wired to real config / SDK client.
|
||||
@@ -84,8 +84,8 @@ func New() *Factory {
|
||||
}
|
||||
return nil, Wrapf(CodeLocalFileIO, err, "load config")
|
||||
}
|
||||
if f.ContextOverride != "" {
|
||||
cfg.CurrentContext = f.ContextOverride
|
||||
if f.ProfileOverride != "" {
|
||||
cfg.CurrentContext = f.ProfileOverride
|
||||
}
|
||||
return cfg, nil
|
||||
}
|
||||
@@ -117,16 +117,27 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ctxName := cfg.CurrentContext
|
||||
if ctxName == "" {
|
||||
return nil, NewError(CodeAuthUnauthenticated, "no current context configured; run `weknora auth login` to set one up")
|
||||
profileName := cfg.CurrentContext
|
||||
if profileName == "" {
|
||||
return nil, NewError(CodeAuthUnauthenticated, "no current profile configured; run `weknora auth login` to set one up")
|
||||
}
|
||||
ctx, ok := cfg.Contexts[ctxName]
|
||||
ctx, ok := cfg.Contexts[profileName]
|
||||
if !ok {
|
||||
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("config references unknown context %q", ctxName))
|
||||
// If the user explicitly overrode the profile (via --profile flag or
|
||||
// WEKNORA_PROFILE env), it's a bad argument - not a corrupt config file.
|
||||
// The destructive "remove config.yaml" hint would be catastrophic for a typo.
|
||||
if f.ProfileOverride != "" {
|
||||
return nil, NewError(CodeInputInvalidArgument,
|
||||
fmt.Sprintf("profile %q not configured", profileName)).
|
||||
WithHint("list available profiles with `weknora profile list`").
|
||||
WithRetryCommand("weknora profile list")
|
||||
}
|
||||
// ProfileOverride is empty: config.CurrentContext points at a missing entry.
|
||||
// That's a genuinely corrupt config file.
|
||||
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("config references unknown profile %q", profileName))
|
||||
}
|
||||
if ctx.Host == "" {
|
||||
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("context %q has no host", ctxName))
|
||||
return nil, NewError(CodeLocalConfigCorrupt, fmt.Sprintf("profile %q has no host", profileName))
|
||||
}
|
||||
|
||||
opts := []sdk.ClientOption{}
|
||||
@@ -139,7 +150,7 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
// authenticated invocation.
|
||||
var accessToken string
|
||||
if ctx.TokenRef != "" {
|
||||
if access, err := LoadSecret(store, ctxName, "access"); err != nil {
|
||||
if access, err := LoadSecret(store, profileName, "access"); err != nil {
|
||||
return nil, err
|
||||
} else if access != "" {
|
||||
accessToken = access
|
||||
@@ -147,7 +158,7 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
}
|
||||
}
|
||||
if ctx.APIKeyRef != "" {
|
||||
if apiKey, err := LoadSecret(store, ctxName, "api_key"); err != nil {
|
||||
if apiKey, err := LoadSecret(store, profileName, "api_key"); err != nil {
|
||||
return nil, err
|
||||
} else if apiKey != "" {
|
||||
opts = append(opts, sdk.WithAPIKey(apiKey))
|
||||
@@ -161,7 +172,7 @@ func buildClient(f *Factory) (*sdk.Client, error) {
|
||||
// them propagates as auth.unauthenticated for the caller to handle.
|
||||
if ctx.TokenRef != "" && ctx.RefreshRef != "" {
|
||||
refreshFn := func(rctx context.Context) (string, error) {
|
||||
return refreshAccessToken(rctx, store, ctx.Host, ctxName)
|
||||
return refreshAccessToken(rctx, store, ctx.Host, profileName)
|
||||
}
|
||||
opts = append(opts, sdk.WithTransport(
|
||||
NewAuthRetryTransport(http.DefaultTransport, accessToken, refreshFn),
|
||||
@@ -255,6 +266,28 @@ func LoadSecret(store secrets.Store, context, key string) (string, error) {
|
||||
// being constructed - that one is itself wrapped by the transport, which
|
||||
// would recurse on refresh. The refresh endpoint is unauthenticated apart
|
||||
// from the refresh token in the body, so no credential options are needed.
|
||||
func refreshAccessToken(ctx context.Context, store secrets.Store, host, ctxName string) (string, error) {
|
||||
return RefreshAndPersist(ctx, store, sdk.NewClient(host), ctxName)
|
||||
func refreshAccessToken(ctx context.Context, store secrets.Store, host, profileName string) (string, error) {
|
||||
return RefreshAndPersist(ctx, store, sdk.NewClient(host), profileName)
|
||||
}
|
||||
|
||||
// ActiveProfile returns the resolved profile name for this invocation:
|
||||
// 1. ProfileOverride (set by --profile flag in root PersistentPreRunE)
|
||||
// 2. WEKNORA_PROFILE env var
|
||||
// 3. Config's CurrentContext (the active context / profile name)
|
||||
// 4. Empty string when nothing is configured (envelope omits the field).
|
||||
func (f *Factory) ActiveProfile() string {
|
||||
if f.ProfileOverride != "" {
|
||||
return f.ProfileOverride
|
||||
}
|
||||
if v := os.Getenv("WEKNORA_PROFILE"); v != "" {
|
||||
return v
|
||||
}
|
||||
if f.Config == nil {
|
||||
return ""
|
||||
}
|
||||
cfg, err := f.Config()
|
||||
if err != nil || cfg == nil {
|
||||
return ""
|
||||
}
|
||||
return cfg.CurrentContext
|
||||
}
|
||||
|
||||
@@ -72,10 +72,10 @@ func TestNew_FoundationDefaults(t *testing.T) {
|
||||
assert.Equal(t, CodeAuthUnauthenticated, typed.Code)
|
||||
}
|
||||
|
||||
// TestFactory_ContextOverride verifies the global --context flag mechanism:
|
||||
// f.ContextOverride replaces config.CurrentContext for this invocation only,
|
||||
// TestFactory_ProfileOverride verifies the global --profile flag mechanism:
|
||||
// f.ProfileOverride replaces config.CurrentContext for this invocation only,
|
||||
// without writing to disk.
|
||||
func TestFactory_ContextOverride(t *testing.T) {
|
||||
func TestFactory_ProfileOverride(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_CONFIG_HOME", dir)
|
||||
|
||||
@@ -94,14 +94,14 @@ contexts:
|
||||
f := New()
|
||||
|
||||
t.Run("no override: returns CurrentContext from disk", func(t *testing.T) {
|
||||
f.ContextOverride = ""
|
||||
f.ProfileOverride = ""
|
||||
cfg, err := f.Config()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "default", cfg.CurrentContext)
|
||||
})
|
||||
|
||||
t.Run("override applied: ContextOverride wins over disk", func(t *testing.T) {
|
||||
f.ContextOverride = "other"
|
||||
t.Run("override applied: ProfileOverride wins over disk", func(t *testing.T) {
|
||||
f.ProfileOverride = "other"
|
||||
cfg, err := f.Config()
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "other", cfg.CurrentContext)
|
||||
@@ -302,6 +302,26 @@ func fakeKBServer(t *testing.T, kbs []sdk.KnowledgeBase) *httptest.Server {
|
||||
return srv
|
||||
}
|
||||
|
||||
// TestFactory_ActiveProfile_EnvVarFallback verifies WEKNORA_PROFILE is honoured
|
||||
// when no override or config is present.
|
||||
func TestFactory_ActiveProfile_EnvVarFallback(t *testing.T) {
|
||||
t.Setenv("WEKNORA_PROFILE", "staging")
|
||||
f := &Factory{} // no override, no config
|
||||
if got := f.ActiveProfile(); got != "staging" {
|
||||
t.Errorf("expected env fallback to staging; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestFactory_ActiveProfile_OverrideWinsEnv verifies ProfileOverride takes
|
||||
// priority over the WEKNORA_PROFILE env var.
|
||||
func TestFactory_ActiveProfile_OverrideWinsEnv(t *testing.T) {
|
||||
t.Setenv("WEKNORA_PROFILE", "staging")
|
||||
f := &Factory{ProfileOverride: "prod"}
|
||||
if got := f.ActiveProfile(); got != "prod" {
|
||||
t.Errorf("override should win over env; got %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestResolveKB_Chain exercises the 4-level fallback chain. Each sub-test
|
||||
// isolates cwd / env / closure from the others.
|
||||
func TestResolveKB_Chain(t *testing.T) {
|
||||
|
||||
@@ -18,13 +18,13 @@ import (
|
||||
type FormatMode string
|
||||
|
||||
const (
|
||||
FormatHuman FormatMode = "human"
|
||||
FormatText FormatMode = "text"
|
||||
FormatJSON FormatMode = "json"
|
||||
FormatNDJSON FormatMode = "ndjson"
|
||||
)
|
||||
|
||||
// FormatOptions captures the resolved --format + --jq state for a command.
|
||||
// Mode is one of FormatHuman / FormatJSON / FormatNDJSON, or "" before
|
||||
// Mode is one of FormatText / FormatJSON / FormatNDJSON, or "" before
|
||||
// ResolveDefault has been called.
|
||||
type FormatOptions struct {
|
||||
Mode FormatMode
|
||||
@@ -54,7 +54,7 @@ func AddFormatFlag(cmd *cobra.Command, fieldHints ...string) {
|
||||
// CheckFormatFlag resolves --format + --jq from cmd. Returns:
|
||||
// - (*FormatOptions{Mode:""}, nil) flag not set; caller should call ResolveDefault
|
||||
// - (*FormatOptions{Mode:v,JQ:q}, nil) valid values
|
||||
// - (nil, *FlagError) invalid --format, or --jq with explicit --format human
|
||||
// - (nil, *FlagError) invalid --format, or --jq with explicit --format text
|
||||
//
|
||||
// --jq with --format unset is accepted: ResolveDefault below will promote
|
||||
// the mode to FormatJSON so the filter has somewhere to apply.
|
||||
@@ -65,26 +65,26 @@ func CheckFormatFlag(cmd *cobra.Command) (*FormatOptions, error) {
|
||||
switch v {
|
||||
case "":
|
||||
// unset; caller calls ResolveDefault
|
||||
case "human", "json", "ndjson":
|
||||
case "text", "json", "ndjson":
|
||||
fopts.Mode = FormatMode(v)
|
||||
default:
|
||||
return nil, NewFlagError(fmt.Errorf("invalid --format %q: must be human | json | ndjson", v))
|
||||
return nil, NewFlagError(fmt.Errorf("invalid --format %q: must be text | json | ndjson", v))
|
||||
}
|
||||
}
|
||||
if f := cmd.Flags().Lookup("jq"); f != nil {
|
||||
fopts.JQ = f.Value.String()
|
||||
}
|
||||
// --jq only meaningful for JSON-shaped output. Reject the explicit
|
||||
// `--format human --jq ...` combination; the `--jq` with --format unset
|
||||
// `--format text --jq ...` combination; the `--jq` with --format unset
|
||||
// case is handled by ResolveDefault.
|
||||
if fopts.JQ != "" && fopts.Mode == FormatHuman {
|
||||
if fopts.JQ != "" && fopts.Mode == FormatText {
|
||||
return nil, NewFlagError(errors.New("--jq requires --format json|ndjson"))
|
||||
}
|
||||
return fopts, nil
|
||||
}
|
||||
|
||||
// WantsJSON reports whether the resolved mode is JSON or NDJSON. Used by
|
||||
// callers to choose between the JSON emit path and human text rendering.
|
||||
// callers to choose between the JSON emit path and text rendering.
|
||||
func (o *FormatOptions) WantsJSON() bool {
|
||||
return o.Mode == FormatJSON || o.Mode == FormatNDJSON
|
||||
}
|
||||
@@ -101,7 +101,7 @@ func (o *FormatOptions) WantsJSON() bool {
|
||||
// FormatNDJSON path: emits one bare JSON object per line (no envelope).
|
||||
// Matches spec §5 NDJSON event-passthrough semantics.
|
||||
//
|
||||
// FormatHuman path returns an error so a missed dispatch surfaces loudly.
|
||||
// FormatText path returns an error so a missed dispatch surfaces loudly.
|
||||
func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
|
||||
switch o.Mode {
|
||||
case FormatJSON:
|
||||
@@ -121,8 +121,8 @@ func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
|
||||
return format.WriteJSONFiltered(w, data, nil, o.JQ)
|
||||
}
|
||||
return format.WriteNDJSON(w, data)
|
||||
case FormatHuman:
|
||||
return fmt.Errorf("FormatOptions.Emit: cannot emit human mode as JSON; caller must render human-readable separately")
|
||||
case FormatText:
|
||||
return fmt.Errorf("FormatOptions.Emit: cannot emit text mode as JSON; caller must render human-readable separately")
|
||||
default:
|
||||
return fmt.Errorf("FormatOptions.Emit: unknown mode %q", o.Mode)
|
||||
}
|
||||
@@ -131,7 +131,7 @@ func (o *FormatOptions) Emit(w io.Writer, data any, meta *output.Meta) error {
|
||||
// ResolveDefault fills in Mode when the caller has not explicitly set it:
|
||||
// - Mode defaults to FormatJSON
|
||||
// - TTY only affects the indent decision (auto-indent in TTY; compact in pipe)
|
||||
// - For human-readable rendering, pass --format human explicitly
|
||||
// - For human-readable rendering, pass --format text explicitly
|
||||
func (o *FormatOptions) ResolveDefault(tty bool) {
|
||||
o.TTY = tty
|
||||
if o.Mode == "" {
|
||||
@@ -150,7 +150,7 @@ func (o *FormatOptions) FromEnv() {
|
||||
}
|
||||
v := os.Getenv("WEKNORA_FORMAT")
|
||||
switch v {
|
||||
case "human", "json", "ndjson":
|
||||
case "text", "json", "ndjson":
|
||||
o.Mode = FormatMode(v)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -14,17 +14,16 @@ func TestCheckFormatFlags(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
wantMode FormatMode // FormatHuman | FormatJSON | FormatNDJSON | "" (unset)
|
||||
wantMode FormatMode // FormatText | FormatJSON | FormatNDJSON | "" (unset)
|
||||
wantErr bool
|
||||
}{
|
||||
// Unset → Mode is "" (caller resolves default via ResolveDefault).
|
||||
{"default", []string{}, "", false},
|
||||
{"explicit human", []string{"--format", "human"}, FormatHuman, false},
|
||||
{"explicit text", []string{"--format", "text"}, FormatText, false},
|
||||
{"json", []string{"--format", "json"}, FormatJSON, false},
|
||||
{"ndjson", []string{"--format", "ndjson"}, FormatNDJSON, false},
|
||||
{"invalid value", []string{"--format", "yaml"}, "", true},
|
||||
// v0.7 BREAKING: "text" is no longer a valid --format value.
|
||||
{"text rejected", []string{"--format", "text"}, "", true},
|
||||
{"human rejected", []string{"--format", "human"}, "", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@@ -87,11 +86,11 @@ func TestFormatOptions_JSONEmitsArray(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatOptions_HumanModeReturnsError(t *testing.T) {
|
||||
fopts := &FormatOptions{Mode: FormatHuman}
|
||||
func TestFormatOptions_TextModeReturnsError(t *testing.T) {
|
||||
fopts := &FormatOptions{Mode: FormatText}
|
||||
err := fopts.Emit(&bytes.Buffer{}, map[string]string{"a": "b"}, nil)
|
||||
if err == nil {
|
||||
t.Error("expected error for human mode, got nil")
|
||||
t.Error("expected error for text mode, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -124,7 +123,7 @@ func TestResolveDefault(t *testing.T) {
|
||||
{"already set keeps value tty", FormatNDJSON, "", true, FormatNDJSON},
|
||||
{"already set keeps value no-tty", FormatJSON, "", false, FormatJSON},
|
||||
// --jq with unset --format promotes to JSON regardless of TTY so the
|
||||
// filter has somewhere to apply (silent human drop would surprise users).
|
||||
// filter has somewhere to apply (silent text drop would surprise users).
|
||||
{"jq forces json on TTY", "", ".[]", true, FormatJSON},
|
||||
{"jq with explicit ndjson preserved", FormatNDJSON, ".[]", true, FormatNDJSON},
|
||||
}
|
||||
@@ -147,9 +146,8 @@ func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
|
||||
args []string
|
||||
}{
|
||||
{"invalid format value", []string{"--format", "yaml"}},
|
||||
// v0.7: "text" is rejected; "human" is the valid human-readable value.
|
||||
{"text rejected as invalid", []string{"--format", "text"}},
|
||||
{"jq with explicit human mode", []string{"--format", "human", "--jq", ".id"}},
|
||||
{"human rejected as invalid", []string{"--format", "human"}},
|
||||
{"jq with explicit text mode", []string{"--format", "text", "--jq", ".id"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
@@ -182,7 +180,7 @@ func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestCheckFormatFlag_InvalidValueRejected(t *testing.T) {
|
||||
for _, v := range []string{"text", "yaml", "xml", "table"} {
|
||||
for _, v := range []string{"human", "yaml", "xml", "table"} {
|
||||
v := v
|
||||
t.Run(v, func(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
@@ -192,23 +190,23 @@ func TestCheckFormatFlag_InvalidValueRejected(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatalf("expected error for --format %q", v)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "human | json | ndjson") {
|
||||
if !strings.Contains(err.Error(), "text | json | ndjson") {
|
||||
t.Errorf("expected enum hint for --format %q; got %v", v, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCheckFormatFlag_HumanAccepted(t *testing.T) {
|
||||
func TestCheckFormatFlag_TextAccepted(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().String("format", "", "")
|
||||
_ = cmd.Flags().Set("format", "human")
|
||||
_ = cmd.Flags().Set("format", "text")
|
||||
o, err := CheckFormatFlag(cmd)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if o.Mode != FormatHuman {
|
||||
t.Errorf("got %v, want FormatHuman", o.Mode)
|
||||
if o.Mode != FormatText {
|
||||
t.Errorf("got %v, want FormatText", o.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user