refactor(cli): delete envelope infrastructure, errors to stderr
Removes the entire envelope machinery now that every success path
emits bare JSON:
- cli/internal/format/envelope.go (Envelope, Success, Failure,
SuccessWithRisk, WriteEnvelope, Meta, Notice, UpdateNotice,
VersionSkewNotice, Risk, RiskLevel, ErrorBody) + tests.
- cli/internal/format/filter.go envelope-specific helpers
(WriteEnvelopeFiltered, marshalEnvelope, applyFieldFilter,
filterDataPayload, filterObjectData); the reusable
filterArrayItems / filterObjectKeys / writeJQ stay for bare.go.
- cli/internal/cmdutil/exporter.go + tests (envelope-only).
- cli/internal/cmdutil/PrintErrorEnvelope + ToErrorBody +
operationRiskOf + Error.OperationRisk field + OperationRisk struct.
Error path: all errors now go to stderr via cmdutil.PrintError in
`code: message\nhint: ...` form, regardless of --json. Stdout stays
empty (or holds the partial-success the command already wrote) so
downstream `--json | jq` pipelines never have to filter error shapes
out of the success stream. Typed exit codes (3 auth.* / 4
resource.not_found / 5 input.* / 6 server.rate_limited / 7 server.*
+ network.* / 10 input.confirmation_required) carry the failure
class for agents that branch on it.
Acceptance contract:
- envelope_test.go → wire_test.go (TestEnvelopeGolden → TestWireGolden).
- testdata/envelopes/ → testdata/wire/.
- Error-path cases assert the typed code substring on stderr.
- Orphan whoami.*.json goldens deleted.
AGENTS.md + README.md rewritten for the bare-data contract:
- Drop envelope schema section + dry-run rule.
- Document bare JSON on stdout + `code: msg\nhint: …` on stderr.
- ADR-3 reframed around bare data and why error separation matters
for `--json | jq` pipelines.
WriteJSONFiltered short-circuits to WriteJSON when both filters are
empty (skip the marshal-buffer round-trip for the common case).
Final review pass:
- Fix wire-contract bug: `--json id,name` (space form) is broken by
pflag's NoOptDefVal; AGENTS.md / README.md / SetAgentHelp + the
field-discovery help text all switched to `--json=id,name`.
- Fix `weknora api --jq` silently ignored: api.go now routes through
WriteJSONFiltered with jopts.JQ.
- AGENTS.md: drop the false claim that `auth logout` honors `-y`
(logout is local-only with no ConfirmDestructive guard); list the
actual destructive commands instead.
- Rewrite cli/acceptance/e2e/e2e_test.go for the bare-data wire shape
(was still parsing `out["data"]` / `env["ok"]`).
- Add `JSONOptions.Emit(w, v)` helper; collapse ~33 repeated
`format.WriteJSONFiltered(iostreams.IO.Out, X, jopts.Fields,
jopts.JQ)` sites to `jopts.Emit(iostreams.IO.Out, X)` — drops the
format import from 22 cmd/* files.
- Delete single-caller `cmdutil.MustRequireFlag`; inline as
`_ = cmd.MarkFlagRequired(...)` everywhere.
- Add `_ = cmd.MarkFlagRequired("name")` to `kb create`; it was the
only write command relying on runtime --name validation while
`context add` already used the cobra-level mark.
- `context use`: register `--json` / `--jq` (was always emitting JSON
unconditionally with no human path and no flag — diverged from
every other write command); human mode now prints
`✓ Switched context to X (was Y)`.
- Replace per-package `confirmPrompter` / `scriptedConfirm` /
`errPrompter` test doubles with `testutil.ConfirmPrompter`.
- Rename `chatService` → `ChatService` (export to match siblings
`ListService` / `ViewService`); rename `printUploadSuccess` →
`renderUploadSuccess` (siblings use `render*`).
- `defaultHint(CodeResourceNotFound)`: drop the hardcoded
"list available with `weknora kb list`" — misleading on agent /
doc / session 404. Replaced with "verify the resource ID and try
again".
- Strip stale `v0.2/v0.3` / "envelope" / "v0.0/v0.1 supports only"
historical tags from production comments and a few test
descriptions.
This commit is contained in:
@@ -1,7 +1,6 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
@@ -25,24 +24,15 @@ import (
|
||||
// proceed. See cli/AGENTS.md "Exit codes".
|
||||
//
|
||||
// `yes` should be sourced from the persistent global -y/--yes flag.
|
||||
//
|
||||
// On exit-10 path, the returned *Error carries OperationRisk so the envelope
|
||||
// printer attaches `risk: {level: "high-risk-write", action: ...}`.
|
||||
func ConfirmDestructive(p prompt.Prompter, yes, jsonOut bool, what, id string) error {
|
||||
if yes {
|
||||
return nil
|
||||
}
|
||||
risk := &OperationRisk{Level: "high-risk-write", Action: fmt.Sprintf("delete %s %s", what, id)}
|
||||
if !iostreams.IO.IsStdoutTTY() || jsonOut {
|
||||
e := NewError(
|
||||
return NewError(
|
||||
CodeInputConfirmationRequired,
|
||||
fmt.Sprintf("delete %s %s requires explicit confirmation: re-run with -y/--yes", what, id),
|
||||
)
|
||||
var typed *Error
|
||||
if errors.As(e, &typed) {
|
||||
typed.OperationRisk = risk
|
||||
}
|
||||
return e
|
||||
}
|
||||
ok, err := p.Confirm(fmt.Sprintf("Delete %s %s? This cannot be undone.", what, id), false)
|
||||
if err != nil {
|
||||
|
||||
@@ -9,9 +9,9 @@ import (
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ErrorCode is a namespaced stable identifier carried in the failure envelope.
|
||||
// SemVer governance: v0.x maintains the registry below; new codes are noted
|
||||
// in release notes. v0.9 introduces a CI compat test (see ADR-6b).
|
||||
// ErrorCode is a namespaced stable identifier emitted on stderr in the
|
||||
// `code: message` failure line. SemVer governance: v0.x maintains the
|
||||
// registry below; new codes are noted in release notes.
|
||||
type ErrorCode string
|
||||
|
||||
const (
|
||||
@@ -33,9 +33,9 @@ const (
|
||||
CodeInputMissingFlag ErrorCode = "input.missing_flag"
|
||||
// CodeInputConfirmationRequired marks a high-risk write that has no
|
||||
// interactive UI (non-TTY or --json) and was invoked without -y/--yes.
|
||||
// Mapped to exit code 10 (see cli/AGENTS.md).
|
||||
// Agents must surface the envelope to the user and only retry with -y
|
||||
// after explicit human approval; never auto-retry.
|
||||
// Mapped to exit code 10 (see cli/AGENTS.md). Agents must surface the
|
||||
// error to the user and only retry with -y after explicit human
|
||||
// approval; never auto-retry.
|
||||
CodeInputConfirmationRequired ErrorCode = "input.confirmation_required"
|
||||
|
||||
// server.* / network.*
|
||||
@@ -60,9 +60,9 @@ const (
|
||||
CodeKBNotFound ErrorCode = "local.kb_not_found"
|
||||
CodeProjectLinkCorrupt ErrorCode = "local.project_link_corrupt"
|
||||
// CodeUserAborted marks a user-cancelled destructive operation (declined a
|
||||
// confirm prompt). Distinct from SilentError so envelopes still carry a
|
||||
// stable code; distinct from input.* because the user supplied valid args
|
||||
// and simply chose not to proceed.
|
||||
// confirm prompt). Distinct from SilentError so the stderr line still
|
||||
// carries a stable code; distinct from input.* because the user supplied
|
||||
// valid args and simply chose not to proceed.
|
||||
CodeUserAborted ErrorCode = "local.user_aborted"
|
||||
// CodeUploadFileNotFound marks a `weknora doc upload` invocation pointing at
|
||||
// a path that does not exist. Distinct from CodeLocalFileIO (permission /
|
||||
@@ -81,7 +81,9 @@ const (
|
||||
)
|
||||
|
||||
// Error is the typed error implementations carry through the call stack.
|
||||
// RunE returns a *Error and the root command formats it into the envelope.
|
||||
// RunE returns a *Error and the root command renders it on stderr in
|
||||
// `code: message[: cause]\nhint: ...` form. Exit code is derived by
|
||||
// ExitCode().
|
||||
type Error struct {
|
||||
Code ErrorCode
|
||||
Message string
|
||||
@@ -89,27 +91,13 @@ type Error struct {
|
||||
Cause error
|
||||
Retryable bool
|
||||
HTTPStatus int
|
||||
// Risk classifies the operation that produced this error. Set by callers
|
||||
// invoking destructive write paths so envelope.risk surfaces to agents.
|
||||
// Stored as the format.Risk JSON shape via OperationRisk to avoid an
|
||||
// import cycle with internal/format.
|
||||
OperationRisk *OperationRisk
|
||||
// Silent suppresses the default Failure envelope written by
|
||||
// PrintErrorEnvelope while preserving the typed Code for ExitCode.
|
||||
// Set by commands that already wrote their own envelope (e.g. bulk
|
||||
// operations reporting partial-success data) but still need to surface
|
||||
// a non-zero exit code matched to the failure class.
|
||||
// Silent suppresses PrintError's stderr output while preserving the
|
||||
// typed Code for ExitCode. Set by commands that already wrote their
|
||||
// own output (e.g. bulk operations reporting partial-success data on
|
||||
// stdout) but still need to surface a non-zero exit code.
|
||||
Silent bool
|
||||
}
|
||||
|
||||
// OperationRisk mirrors format.Risk in the cmdutil layer (avoiding a circular
|
||||
// import). cmdutil → format is OK; the inverse is not, so cmdutil owns its
|
||||
// own type and ToErrorBody / PrintErrorEnvelope translate.
|
||||
type OperationRisk struct {
|
||||
Level string // "read" | "write" | "high-risk-write"
|
||||
Action string
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
if e == nil {
|
||||
return ""
|
||||
@@ -202,7 +190,7 @@ func matchPrefix(err error, prefix string) bool {
|
||||
}
|
||||
|
||||
// ClassifyHTTPStatus maps an HTTP status code to the canonical ErrorCode.
|
||||
// Single source of truth so envelope codes stay aligned whether the failure
|
||||
// Single source of truth so error codes stay aligned whether the failure
|
||||
// was detected by the SDK (string-formatted error) or by the CLI directly
|
||||
// (e.g. raw passthrough reading resp.StatusCode).
|
||||
func ClassifyHTTPStatus(status int) ErrorCode {
|
||||
@@ -229,7 +217,7 @@ func ClassifyHTTPStatus(status int) ErrorCode {
|
||||
// parsing the "HTTP error <status>: ..." message format the SDK currently
|
||||
// emits (client.parseResponse). Until the SDK exposes a typed APIError this
|
||||
// is the lowest-friction way to surface 401/404/429/etc. as the right
|
||||
// envelope code instead of every server-side problem collapsing to
|
||||
// typed code instead of every server-side problem collapsing to
|
||||
// server.error.
|
||||
//
|
||||
// Returns CodeNetworkError when err is not an HTTP error (transport / DNS),
|
||||
|
||||
@@ -4,8 +4,6 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
)
|
||||
|
||||
// ExitCode maps an error to the documented CLI exit code (spec §2.4 + ADR-3).
|
||||
@@ -56,13 +54,10 @@ func ExitCode(err error) int {
|
||||
return 1
|
||||
}
|
||||
|
||||
// PrintError writes err to w in human-readable form. The envelope-aware
|
||||
// JSON formatter is in `internal/format`; this helper is the human path used
|
||||
// when no command produced its own output.
|
||||
//
|
||||
// Typed *Error values surface their Hint as a second line so users see the
|
||||
// actionable next-step (matches envelope.error.hint visibility in --json).
|
||||
// Falls through to defaultHint when caller didn't set one.
|
||||
// PrintError writes err to w (typically stderr) as `code: message\nhint:
|
||||
// ...`. Typed *Error values surface their Hint as a second line so users
|
||||
// see the actionable next-step. Falls through to defaultHint when the
|
||||
// caller didn't set one.
|
||||
func PrintError(w io.Writer, err error) {
|
||||
if err == nil || errors.Is(err, SilentError) {
|
||||
return
|
||||
@@ -80,76 +75,10 @@ func PrintError(w io.Writer, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
// PrintErrorEnvelope writes err as a JSON envelope on w. Used in agent mode /
|
||||
// --json / --format=json output so failures stay machine-parseable. When the
|
||||
// error carries an OperationRisk (destructive write paths), it's surfaced as
|
||||
// the envelope-level Risk field so agents can decide whether to surface the
|
||||
// failure differently to the user.
|
||||
func PrintErrorEnvelope(w io.Writer, err error) {
|
||||
if err == nil || errors.Is(err, SilentError) {
|
||||
return
|
||||
}
|
||||
var typed *Error
|
||||
if errors.As(err, &typed) && typed.Silent {
|
||||
return
|
||||
}
|
||||
env := format.Failure(ToErrorBody(err))
|
||||
if r := operationRiskOf(err); r != nil {
|
||||
env.Risk = &format.Risk{Level: format.RiskLevel(r.Level), Action: r.Action}
|
||||
}
|
||||
_ = format.WriteEnvelope(w, env)
|
||||
}
|
||||
|
||||
// operationRiskOf extracts an OperationRisk from a typed *Error chain, or nil.
|
||||
func operationRiskOf(err error) *OperationRisk {
|
||||
var typed *Error
|
||||
if errors.As(err, &typed) {
|
||||
return typed.OperationRisk
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ToErrorBody projects err into the canonical envelope ErrorBody. Exposed so
|
||||
// other emit paths (planned: MCP) reuse the same projection rather than
|
||||
// reimplementing the typed-error → wire-shape mapping.
|
||||
func ToErrorBody(err error) *format.ErrorBody {
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
body := &format.ErrorBody{Message: err.Error()}
|
||||
var typed *Error
|
||||
if errors.As(err, &typed) {
|
||||
body.Code = string(typed.Code)
|
||||
body.Message = typed.Message
|
||||
body.Hint = typed.Hint
|
||||
if body.Hint == "" {
|
||||
body.Hint = defaultHint(typed.Code)
|
||||
}
|
||||
body.Retryable = typed.Retryable
|
||||
// Surface the wrapped cause so agents see the actual server / SDK
|
||||
// error string, not just the wrap message ("hybrid search"). The
|
||||
// human's printed line and the JSON envelope both end with the
|
||||
// underlying problem.
|
||||
if typed.Cause != nil {
|
||||
body.Message = typed.Message + ": " + typed.Cause.Error()
|
||||
}
|
||||
return body
|
||||
}
|
||||
var fe *FlagError
|
||||
if errors.As(err, &fe) {
|
||||
body.Code = string(CodeInputInvalidArgument)
|
||||
return body
|
||||
}
|
||||
// Unclassified error; consumers see the message but no stable code.
|
||||
body.Code = string(CodeServerError)
|
||||
return body
|
||||
}
|
||||
|
||||
// defaultHint returns a canonical actionable hint for known error codes when
|
||||
// the call site didn't set one. Spec §1.4 zero-config matrix mandates
|
||||
// `auth.unauthenticated` envelopes carry "run weknora auth login" — this
|
||||
// fallback covers the broad surface (auth status / kb list / kb get / search)
|
||||
// without per-command hint plumbing.
|
||||
// defaultHint returns a canonical actionable hint for known error codes
|
||||
// when the call site didn't set one. `auth.unauthenticated` always points
|
||||
// at `weknora auth login` — covers the broad surface (auth status / kb
|
||||
// list / kb view / search) without per-command hint plumbing.
|
||||
//
|
||||
// Empty string for codes without a stable canonical hint.
|
||||
func defaultHint(code ErrorCode) string {
|
||||
@@ -171,7 +100,7 @@ func defaultHint(code ErrorCode) string {
|
||||
case CodeServerTimeout:
|
||||
return "request timed out; retry, or run `weknora doctor` to check connectivity"
|
||||
case CodeResourceNotFound:
|
||||
return "verify the resource ID; list available with `weknora kb list`"
|
||||
return "verify the resource ID and try again"
|
||||
case CodeInputInvalidArgument, CodeInputMissingFlag:
|
||||
return "see `weknora <command> --help` for valid usage"
|
||||
case CodeInputConfirmationRequired:
|
||||
|
||||
@@ -36,34 +36,6 @@ func TestExitCode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestToErrorBody(t *testing.T) {
|
||||
t.Run("nil returns nil", func(t *testing.T) {
|
||||
assert.Nil(t, ToErrorBody(nil))
|
||||
})
|
||||
t.Run("typed without cause", func(t *testing.T) {
|
||||
body := ToErrorBody(NewError(CodeResourceNotFound, "kb missing"))
|
||||
assert.Equal(t, "resource.not_found", body.Code)
|
||||
assert.Equal(t, "kb missing", body.Message)
|
||||
})
|
||||
t.Run("typed with cause surfaces inner", func(t *testing.T) {
|
||||
inner := errors.New("HTTP error 500: server exploded")
|
||||
body := ToErrorBody(Wrapf(CodeServerError, inner, "hybrid search"))
|
||||
assert.Equal(t, "server.error", body.Code)
|
||||
// Both wrap context AND server cause must appear so agents see what
|
||||
// actually broke, not just our wrap label.
|
||||
assert.Equal(t, "hybrid search: HTTP error 500: server exploded", body.Message)
|
||||
})
|
||||
t.Run("flag error", func(t *testing.T) {
|
||||
body := ToErrorBody(NewFlagError(errors.New("bad flag")))
|
||||
assert.Equal(t, "input.invalid_argument", body.Code)
|
||||
})
|
||||
t.Run("unclassified", func(t *testing.T) {
|
||||
body := ToErrorBody(errors.New("anything"))
|
||||
assert.Equal(t, "server.error", body.Code)
|
||||
assert.Equal(t, "anything", body.Message)
|
||||
})
|
||||
}
|
||||
|
||||
func TestPrintError(t *testing.T) {
|
||||
t.Run("nil is silent", func(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
|
||||
@@ -1,25 +0,0 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"io"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
)
|
||||
|
||||
// Exporter renders an envelope to a writer. Currently the only
|
||||
// implementation is the JSON exporter; the interface stays in case a future
|
||||
// renderer (templated text, table) needs to plug in without changing call
|
||||
// sites that already write through Exporter.Write.
|
||||
type Exporter interface {
|
||||
Write(w io.Writer, env format.Envelope) error
|
||||
}
|
||||
|
||||
// NewJSONExporter returns an Exporter that emits envelope JSON via
|
||||
// format.WriteEnvelope (single-source encoder config: no HTML escape).
|
||||
func NewJSONExporter() Exporter { return &jsonExporter{} }
|
||||
|
||||
type jsonExporter struct{}
|
||||
|
||||
func (jsonExporter) Write(w io.Writer, env format.Envelope) error {
|
||||
return format.WriteEnvelope(w, env)
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
)
|
||||
|
||||
func TestJSONExporter_WritesEnvelope(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
exp := NewJSONExporter()
|
||||
require.NoError(t, exp.Write(&buf, format.Success(map[string]string{"k": "v"}, nil)))
|
||||
var got map[string]any
|
||||
require.NoError(t, json.Unmarshal(buf.Bytes(), &got))
|
||||
assert.Equal(t, true, got["ok"])
|
||||
}
|
||||
|
||||
func TestFlagError_IsSentinel(t *testing.T) {
|
||||
err := NewFlagError(assert.AnError)
|
||||
_, ok := err.(*FlagError)
|
||||
assert.True(t, ok)
|
||||
}
|
||||
@@ -76,9 +76,9 @@ func New() *Factory {
|
||||
f.Config = func() (*config.Config, error) {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
// Map raw fs / parse errors to typed codes so envelopes don't
|
||||
// surface bare `server.error` for what's actually a local IO /
|
||||
// corrupt-config problem.
|
||||
// Map raw fs / parse errors to typed codes so the stderr line
|
||||
// doesn't surface bare `server.error` for what's actually a
|
||||
// local IO / corrupt-config problem.
|
||||
if errors.Is(err, config.ErrCorrupt) {
|
||||
return nil, Wrapf(CodeLocalConfigCorrupt, err, "config malformed")
|
||||
}
|
||||
|
||||
@@ -2,17 +2,20 @@ package cmdutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
)
|
||||
|
||||
// JSONOptions captures the resolved --json + --jq state after CheckJSONFlags.
|
||||
// A non-nil value means the user requested JSON output; Fields restricts
|
||||
// data.items[*] when len(Fields) > 0; JQ is a jq expression applied to the
|
||||
// final envelope JSON.
|
||||
// each top-level object (or each element of a top-level array) to the
|
||||
// listed keys; JQ is a jq expression applied to the final JSON.
|
||||
type JSONOptions struct {
|
||||
Fields []string
|
||||
JQ string
|
||||
@@ -22,24 +25,32 @@ type JSONOptions struct {
|
||||
// shorthand for `opts != nil`.
|
||||
func (o *JSONOptions) Enabled() bool { return o != nil }
|
||||
|
||||
// jsonNoOptSentinel marks a bare `--json` (no comma-separated values
|
||||
// after it). pflag's NoOptDefVal mechanism stores this sentinel into the
|
||||
// slice; CheckJSONFlags then maps it to "no field filter" (full envelope).
|
||||
// Emit serializes v as bare JSON to w, honoring the resolved field-filter
|
||||
// and jq expression. Equivalent to calling format.WriteJSONFiltered with
|
||||
// o.Fields / o.JQ, but lets call sites stay free of the format import.
|
||||
// Safe to call on a nil receiver in case the caller composes it with
|
||||
// Enabled().
|
||||
func (o *JSONOptions) Emit(w io.Writer, v any) error {
|
||||
if o == nil {
|
||||
return format.WriteJSON(w, v)
|
||||
}
|
||||
return format.WriteJSONFiltered(w, v, o.Fields, o.JQ)
|
||||
}
|
||||
|
||||
// jsonNoOptSentinel marks a bare `--json` (no comma-separated values after
|
||||
// it). pflag's NoOptDefVal mechanism stores this sentinel into the slice;
|
||||
// CheckJSONFlags then maps it to "no field filter" (full payload).
|
||||
//
|
||||
// Rationale: WeKnora's envelope is itself the machine-readable contract
|
||||
// (carries typed error.code / _meta / risk), so a bare `--json` always
|
||||
// producing the full envelope keeps the standard `weknora kb list --json |
|
||||
// jq` pattern working. Field discovery moves to per-command `--help`
|
||||
// "JSON fields available" sections rendered by AddJSONFlags.
|
||||
// Field discovery moves to per-command `--help` "JSON fields available"
|
||||
// sections rendered by AddJSONFlags.
|
||||
const jsonNoOptSentinel = "\x00json-no-value"
|
||||
|
||||
// AddJSONFlags registers --json and --jq on cmd.
|
||||
//
|
||||
// - `--json` → full envelope (no field filter)
|
||||
// - `--json id,name` → envelope with data.items[*] / data restricted
|
||||
// to listed fields
|
||||
// - `--jq <expr>` → applies a jq expression after marshaling;
|
||||
// requires --json to be set explicitly
|
||||
// - `--json` → bare JSON payload, no field filter
|
||||
// - `--json=id,name` → each object restricted to the listed fields
|
||||
// - `--jq <expr>` → apply a jq expression to the JSON; requires
|
||||
// --json to be set explicitly
|
||||
//
|
||||
// `fields` is the set of available fields the user may pass; rendered in
|
||||
// the command's help. Pass nil to skip the help annotation (uncommon).
|
||||
@@ -48,7 +59,7 @@ func AddJSONFlags(cmd *cobra.Command, fields []string) {
|
||||
// Backticks reserved for pflag's UnquoteUsage to extract the varname;
|
||||
// avoid them in the description so the help doesn't render the flag
|
||||
// name twice.
|
||||
f.StringSlice("json", nil, "Output JSON envelope (bare for full; --json=id,name for `fields`)")
|
||||
f.StringSlice("json", nil, "Output bare JSON (--json=id,name to project `fields`)")
|
||||
f.Lookup("json").NoOptDefVal = jsonNoOptSentinel
|
||||
f.StringP("jq", "q", "", "Filter JSON output using a jq `expression` (requires --json)")
|
||||
|
||||
@@ -56,7 +67,7 @@ func AddJSONFlags(cmd *cobra.Command, fields []string) {
|
||||
sorted := append([]string(nil), fields...)
|
||||
sort.Strings(sorted)
|
||||
// Append to Long without overwriting per-command prose.
|
||||
hdr := "\n\nJSON fields available via `--json id,name,...`:\n " +
|
||||
hdr := "\n\nJSON fields available via `--json=id,name,...`:\n " +
|
||||
strings.Join(sorted, "\n ")
|
||||
if cmd.Long != "" {
|
||||
cmd.Long += hdr
|
||||
@@ -71,8 +82,8 @@ func AddJSONFlags(cmd *cobra.Command, fields []string) {
|
||||
// - (*JSONOptions, nil) --json set (possibly with --jq)
|
||||
// - (nil, error) --jq without --json (plain error, exit 1)
|
||||
//
|
||||
// Bare `--json` yields Fields == nil (full envelope). Explicit field list
|
||||
// yields Fields == []string{"id", "name", ...} (filter applied).
|
||||
// Bare `--json` yields Fields == nil (no field filter). Explicit field
|
||||
// list yields Fields == []string{"id", "name", ...} (filter applied).
|
||||
func CheckJSONFlags(cmd *cobra.Command) (*JSONOptions, error) {
|
||||
f := cmd.Flags()
|
||||
jsonFlag := f.Lookup("json")
|
||||
|
||||
@@ -32,8 +32,8 @@ func newTestCmd(t *testing.T, captured **cmdutil.JSONOptions) *cobra.Command {
|
||||
return cmd
|
||||
}
|
||||
|
||||
func TestAddJSONFlags_BareYieldsFullEnvelopeOpts(t *testing.T) {
|
||||
// `--json` bare → Enabled() with empty Fields → caller emits full envelope.
|
||||
func TestAddJSONFlags_BareYieldsEnabledOptsWithNoFields(t *testing.T) {
|
||||
// `--json` bare → Enabled() with empty Fields → caller emits full payload.
|
||||
var captured *cmdutil.JSONOptions
|
||||
cmd := newTestCmd(t, &captured)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
@@ -53,8 +53,9 @@ func TestAddJSONFlags_BareYieldsFullEnvelopeOpts(t *testing.T) {
|
||||
|
||||
func TestAddJSONFlags_FieldsFlagParsing(t *testing.T) {
|
||||
// NoOptDefVal sentinel means the `=` form is required for value passing.
|
||||
// Space form `--json id,name` parses as bare + positional, which is
|
||||
// documented divergence from gh CLI to keep bare-envelope semantics.
|
||||
// Space form `--json id,name` parses as bare + positional, which is a
|
||||
// documented divergence from gh CLI: weknora keeps bare `--json` as a
|
||||
// shortcut for "full payload".
|
||||
cases := []struct {
|
||||
args []string
|
||||
want []string
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// MustRequireFlag panics on programmer error (typo in flag name). cobra's
|
||||
// MarkFlagRequired only returns an error when the named flag does not exist
|
||||
// on the command, which means the caller has a typo at registration time —
|
||||
// non-recoverable. Wrap so command builders stay one-line.
|
||||
func MustRequireFlag(cmd *cobra.Command, name string) {
|
||||
if err := cmd.MarkFlagRequired(name); err != nil {
|
||||
panic(fmt.Sprintf("MarkFlagRequired %q: %v", name, err))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user