feat(cli): --format / NDJSON / chat & agent invoke / MCP / SetAgentHelp / signal-aware ctx / kb create --storage-provider
Adds the structured-output and agent-help surface plus root-level signal
handling so AI agents (and humans working through pipes) get a stable
wire contract.
* --format text|json|ndjson flag, registered per-command on outputs that
need it; default text on TTY, json on pipe. --jq <expr> pairs with json
/ ndjson to filter or project. FormatOptions absorbs JQ; WantsJSON()
helper for the JSON dispatch.
* WriteNDJSON helper in internal/format/ (per ndjson.org: one JSON value
per line, arrays split element-per-line, empty slice → zero bytes).
* chat / agent invoke wire --format ndjson via SDK StreamResponse /
AgentStreamResponse 1:1 passthrough. Both commands detect ctx.Cancelled
in every stream + session-create path and emit a stable
"operation.cancelled" code on Ctrl-C / SIGTERM.
* main.go wires signal.NotifyContext(SIGINT, SIGTERM) into the root
context so long-running commands run their cancellation cleanup
(re-emit auto-created session id, etc); the process exits 130 when
the context was signal-cancelled, matching Unix convention.
* MCP chat / agent_invoke output schemas extended with thinking /
tool_calls / assistant_message_id (server-side accumulated; MCP
tools/call has no standard partial-response). doc_view and doc_download
now use doc_id (not knowledge_id) so agents see a single id naming
convention across all tools — matches the chunk_list / search_chunks
schemas and the CLI's <doc-id> positional.
* SetAgentHelp(cmd, AgentHelp{...}) — opt-in machine-friendly --help
payload activated by WEKNORA_AGENT_HELP=1. Applied to chat / kb list.
* kb create --storage-provider <local|minio|cos|tos|s3|oss|ks3> — sets
the new KB's storage_provider_config.provider at creation time (server
does not expose it on update). Required on self-hosted deployments
where the server-side default doesn't pre-populate a provider —
without it, subsequent doc upload returns a misleading "kb not found".
This commit is contained in:
@@ -0,0 +1,51 @@
|
||||
// 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).
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// AgentHelp is the structured help blob emitted when an agent invokes
|
||||
// `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.
|
||||
type AgentHelp struct {
|
||||
UsedFor string `json:"used_for"`
|
||||
RequiredFlags []string `json:"required_flags,omitempty"`
|
||||
Examples []string `json:"examples,omitempty"`
|
||||
Output string `json:"output,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).
|
||||
//
|
||||
// Currently applied to a small set of representative commands (chat,
|
||||
// kb list); extend by calling SetAgentHelp in each command's NewCmd.
|
||||
func SetAgentHelp(cmd *cobra.Command, ah AgentHelp) {
|
||||
origHelp := cmd.HelpFunc()
|
||||
cmd.SetHelpFunc(func(c *cobra.Command, args []string) {
|
||||
if os.Getenv("WEKNORA_AGENT_HELP") == "1" {
|
||||
emitAgentHelp(c.OutOrStdout(), ah)
|
||||
return
|
||||
}
|
||||
origHelp(c, args)
|
||||
})
|
||||
}
|
||||
|
||||
func emitAgentHelp(w io.Writer, ah AgentHelp) {
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
enc.SetIndent("", " ")
|
||||
_ = enc.Encode(ah)
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func TestSetAgentHelp_EmitsJSONWhenEnvSet(t *testing.T) {
|
||||
t.Setenv("WEKNORA_AGENT_HELP", "1")
|
||||
cmd := &cobra.Command{Use: "foo"}
|
||||
ah := AgentHelp{
|
||||
UsedFor: "frob a bar",
|
||||
RequiredFlags: []string{"--name"},
|
||||
Examples: []string{"weknora foo --name=x"},
|
||||
}
|
||||
SetAgentHelp(cmd, ah)
|
||||
|
||||
var buf bytes.Buffer
|
||||
cmd.SetOut(&buf)
|
||||
cmd.Help()
|
||||
|
||||
var got AgentHelp
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
t.Fatalf("output not JSON: %v\n%s", err, buf.String())
|
||||
}
|
||||
if got.UsedFor != "frob a bar" {
|
||||
t.Errorf("UsedFor=%q, want %q", got.UsedFor, "frob a bar")
|
||||
}
|
||||
if len(got.RequiredFlags) != 1 || got.RequiredFlags[0] != "--name" {
|
||||
t.Errorf("RequiredFlags=%v", got.RequiredFlags)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetAgentHelp_FallsThroughToHumanHelp(t *testing.T) {
|
||||
t.Setenv("WEKNORA_AGENT_HELP", "")
|
||||
cmd := &cobra.Command{
|
||||
Use: "foo",
|
||||
Short: "frob a bar",
|
||||
Long: "Detailed human help here.",
|
||||
}
|
||||
SetAgentHelp(cmd, AgentHelp{UsedFor: "ignored"})
|
||||
|
||||
var buf bytes.Buffer
|
||||
cmd.SetOut(&buf)
|
||||
cmd.Help()
|
||||
|
||||
// Should NOT be JSON (human help is text)
|
||||
if json.Valid(buf.Bytes()) {
|
||||
t.Errorf("expected human text, got JSON:\n%s", buf.String())
|
||||
}
|
||||
if !bytes.Contains(buf.Bytes(), []byte("Detailed human help")) {
|
||||
t.Errorf("human help missing from output:\n%s", buf.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"sort"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
)
|
||||
|
||||
// Typed format modes. Defined as constants to keep mode comparisons
|
||||
// type-safe and prevent string drift across call sites.
|
||||
const (
|
||||
FormatText = "text"
|
||||
FormatJSON = "json"
|
||||
FormatNDJSON = "ndjson"
|
||||
)
|
||||
|
||||
// FormatOptions captures the resolved --format + --jq state for a command.
|
||||
// Mode is one of FormatText / FormatJSON / FormatNDJSON, or "" before
|
||||
// ResolveDefault has been called.
|
||||
type FormatOptions struct {
|
||||
Mode string
|
||||
JQ string
|
||||
}
|
||||
|
||||
// AddFormatFlag registers --format and --jq on cmd. Optional fieldHints are
|
||||
// appended to cmd.Long as a documentation aid for --jq projection
|
||||
// (e.g., `weknora kb list --format json --jq '.[] | {id, name}'`).
|
||||
//
|
||||
// Uses cmd.Flags() (local) rather than a root persistent flag — only
|
||||
// commands that actually honor --format register it, so cobra rejects
|
||||
// --format on others with "unknown flag" rather than silently ignoring it.
|
||||
func AddFormatFlag(cmd *cobra.Command, fieldHints ...string) {
|
||||
cmd.Flags().String("format", "", "Output format: text | json | ndjson (default: text in TTY, json in pipe)")
|
||||
cmd.Flags().StringP("jq", "q", "", "Filter JSON output using a jq `expression` (requires --format json|ndjson)")
|
||||
|
||||
if len(fieldHints) > 0 {
|
||||
sorted := append([]string(nil), fieldHints...)
|
||||
sort.Strings(sorted)
|
||||
hdr := "\n\nJSON fields available (for --jq projection):\n " +
|
||||
strings.Join(sorted, "\n ")
|
||||
if cmd.Long != "" {
|
||||
cmd.Long += hdr
|
||||
} else {
|
||||
cmd.Long = strings.TrimSpace(cmd.Short) + hdr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 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 text
|
||||
//
|
||||
// --jq with --format unset is accepted: ResolveDefault below will promote
|
||||
// the mode to FormatJSON so the filter has somewhere to apply.
|
||||
func CheckFormatFlag(cmd *cobra.Command) (*FormatOptions, error) {
|
||||
fopts := &FormatOptions{}
|
||||
if f := cmd.Flags().Lookup("format"); f != nil {
|
||||
v := f.Value.String()
|
||||
switch v {
|
||||
case "", FormatText, FormatJSON, FormatNDJSON:
|
||||
fopts.Mode = v
|
||||
default:
|
||||
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 text --jq ...` combination; the `--jq` with --format unset
|
||||
// case is handled by ResolveDefault.
|
||||
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.
|
||||
func (o *FormatOptions) WantsJSON() bool {
|
||||
return o.Mode == FormatJSON || o.Mode == FormatNDJSON
|
||||
}
|
||||
|
||||
// Emit serializes v according to the resolved Mode + JQ. For ndjson, slice
|
||||
// values are split element-per-line (per ndjson.org); for json, v is
|
||||
// emitted as-is. When JQ is set, the jq expression runs against the
|
||||
// marshaled JSON and each result becomes a line. Text mode is the caller's
|
||||
// job — Emit returns an error so a missed dispatch surfaces loudly.
|
||||
func (o *FormatOptions) Emit(w io.Writer, v any) error {
|
||||
switch o.Mode {
|
||||
case FormatJSON:
|
||||
return format.WriteJSONFiltered(w, v, nil, o.JQ)
|
||||
case FormatNDJSON:
|
||||
// jq output is naturally line-per-result → already valid NDJSON.
|
||||
// Without jq, split arrays per ndjson.org (one object per line).
|
||||
if o.JQ != "" {
|
||||
return format.WriteJSONFiltered(w, v, nil, o.JQ)
|
||||
}
|
||||
return format.WriteNDJSON(w, v)
|
||||
case FormatText:
|
||||
return fmt.Errorf("FormatOptions.Emit: cannot emit text mode as JSON; caller must render text separately")
|
||||
default:
|
||||
return fmt.Errorf("FormatOptions.Emit: unknown mode %q", o.Mode)
|
||||
}
|
||||
}
|
||||
|
||||
// ResolveDefault fills in Mode using TTY detection when the user didn't pass
|
||||
// --format explicitly. Pass iostreams.IO.IsStdoutTTY() as isTTY.
|
||||
// No-op if Mode is already set.
|
||||
//
|
||||
// `--jq` without an explicit `--format` forces JSON regardless of TTY:
|
||||
// the filter has no meaning in text mode, so silently dropping it would
|
||||
// surprise the user. The `--jq` + `--format text` combination is caught
|
||||
// up-front by CheckFormatFlag.
|
||||
func (o *FormatOptions) ResolveDefault(isTTY bool) {
|
||||
if o.Mode != "" {
|
||||
return
|
||||
}
|
||||
if o.JQ != "" {
|
||||
o.Mode = FormatJSON
|
||||
return
|
||||
}
|
||||
if isTTY {
|
||||
o.Mode = FormatText
|
||||
} else {
|
||||
o.Mode = FormatJSON
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func TestCheckFormatFlags(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
wantMode string // "text" | "json" | "ndjson" | "" (unset)
|
||||
wantErr bool
|
||||
}{
|
||||
// Unset → Mode is "" (caller resolves TTY default via ResolveDefault).
|
||||
{"default", []string{}, "", false},
|
||||
{"explicit text", []string{"--format", "text"}, "text", false},
|
||||
{"json", []string{"--format", "json"}, "json", false},
|
||||
{"ndjson", []string{"--format", "ndjson"}, "ndjson", false},
|
||||
{"invalid value", []string{"--format", "yaml"}, "", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
AddFormatFlag(cmd)
|
||||
cmd.SetArgs(tc.args)
|
||||
cmd.RunE = func(c *cobra.Command, _ []string) error {
|
||||
opts, err := CheckFormatFlag(c)
|
||||
if (err != nil) != tc.wantErr {
|
||||
t.Fatalf("err=%v wantErr=%v", err, tc.wantErr)
|
||||
}
|
||||
if err == nil && opts.Mode != tc.wantMode {
|
||||
t.Errorf("mode=%q want %q", opts.Mode, tc.wantMode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
_ = cmd.Execute()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatOptions_NDJSONSplitsList(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
fopts := &FormatOptions{Mode: "ndjson"}
|
||||
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
|
||||
if err := fopts.Emit(&buf, arr); err != nil {
|
||||
t.Fatalf("Emit: %v", err)
|
||||
}
|
||||
want := `{"id":"a"}` + "\n" + `{"id":"b"}` + "\n"
|
||||
if buf.String() != want {
|
||||
t.Errorf("got %q want %q", buf.String(), want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatOptions_JSONEmitsArray(t *testing.T) {
|
||||
var buf bytes.Buffer
|
||||
fopts := &FormatOptions{Mode: "json"}
|
||||
arr := []map[string]string{{"id": "a"}, {"id": "b"}}
|
||||
if err := fopts.Emit(&buf, arr); err != nil {
|
||||
t.Fatalf("Emit: %v", err)
|
||||
}
|
||||
// Expect a single JSON array, e.g. [{"id":"a"},{"id":"b"}]
|
||||
var got []map[string]string
|
||||
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
|
||||
t.Fatalf("not valid JSON: %v\n%s", err, buf.String())
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Errorf("got %d items, want 2", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestFormatOptions_TextModeReturnsError(t *testing.T) {
|
||||
fopts := &FormatOptions{Mode: "text"}
|
||||
err := fopts.Emit(&bytes.Buffer{}, map[string]string{"a": "b"})
|
||||
if err == nil {
|
||||
t.Error("expected error for text mode, got nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveDefault(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
mode string // pre-set Mode
|
||||
jq string
|
||||
isTTY bool
|
||||
wantMode string
|
||||
}{
|
||||
{"empty isTTY", "", "", true, "text"},
|
||||
{"empty no-tty", "", "", false, "json"},
|
||||
{"already set keeps value tty", "ndjson", "", true, "ndjson"},
|
||||
{"already set keeps value no-tty", "json", "", false, "json"},
|
||||
// --jq with unset --format promotes to JSON regardless of TTY so the
|
||||
// filter has somewhere to apply (silent text drop would surprise users).
|
||||
{"jq forces json on TTY", "", ".[]", true, "json"},
|
||||
{"jq with explicit ndjson preserved", "ndjson", ".[]", true, "ndjson"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
o := &FormatOptions{Mode: tc.mode, JQ: tc.jq}
|
||||
o.ResolveDefault(tc.isTTY)
|
||||
if o.Mode != tc.wantMode {
|
||||
t.Errorf("mode=%q want %q", o.Mode, tc.wantMode)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestCheckFormatFlag_InvalidExitTwo guards the contract that flag-value
|
||||
// validation maps to exit 2 (FlagError class), not the unclassified bucket.
|
||||
func TestCheckFormatFlag_InvalidExitTwo(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{"invalid format value", []string{"--format", "yaml"}},
|
||||
{"jq with explicit text mode", []string{"--format", "text", "--jq", ".id"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
AddFormatFlag(cmd)
|
||||
cmd.SetArgs(tc.args)
|
||||
var got error
|
||||
cmd.RunE = func(c *cobra.Command, _ []string) error {
|
||||
_, err := CheckFormatFlag(c)
|
||||
got = err
|
||||
return err
|
||||
}
|
||||
_ = cmd.Execute()
|
||||
if got == nil {
|
||||
t.Fatal("expected error, got nil")
|
||||
}
|
||||
var fe *FlagError
|
||||
if !errors.As(got, &fe) {
|
||||
t.Fatalf("error %v is not a *FlagError; would map to exit 1 instead of 2", got)
|
||||
}
|
||||
if ExitCode(got) != 2 {
|
||||
t.Errorf("ExitCode=%d, want 2", ExitCode(got))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,119 +0,0 @@
|
||||
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
|
||||
// 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
|
||||
}
|
||||
|
||||
// Enabled reports whether the caller asked for JSON output. Convenience
|
||||
// shorthand for `opts != nil`.
|
||||
func (o *JSONOptions) Enabled() bool { return o != nil }
|
||||
|
||||
// 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).
|
||||
//
|
||||
// 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` → 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).
|
||||
func AddJSONFlags(cmd *cobra.Command, fields []string) {
|
||||
f := cmd.Flags()
|
||||
// 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 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)")
|
||||
|
||||
if len(fields) > 0 {
|
||||
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 " +
|
||||
strings.Join(sorted, "\n ")
|
||||
if cmd.Long != "" {
|
||||
cmd.Long += hdr
|
||||
} else {
|
||||
cmd.Long = strings.TrimSpace(cmd.Short) + hdr
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// CheckJSONFlags resolves the --json + --jq state from cmd. Returns:
|
||||
// - (nil, nil) neither flag set (human output mode)
|
||||
// - (*JSONOptions, nil) --json set (possibly with --jq)
|
||||
// - (nil, error) --jq without --json (plain error, exit 1)
|
||||
//
|
||||
// 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")
|
||||
jqFlag := f.Lookup("jq")
|
||||
if jsonFlag == nil {
|
||||
return nil, nil
|
||||
}
|
||||
if jsonFlag.Changed {
|
||||
sv, ok := jsonFlag.Value.(pflag.SliceValue)
|
||||
if !ok {
|
||||
return nil, errors.New("internal: --json flag is not a StringSlice")
|
||||
}
|
||||
raw := sv.GetSlice()
|
||||
opts := &JSONOptions{}
|
||||
// Strip the bare-flag sentinel if present.
|
||||
for _, v := range raw {
|
||||
if v == jsonNoOptSentinel {
|
||||
continue
|
||||
}
|
||||
opts.Fields = append(opts.Fields, v)
|
||||
}
|
||||
if jqFlag != nil {
|
||||
opts.JQ = jqFlag.Value.String()
|
||||
}
|
||||
return opts, nil
|
||||
}
|
||||
if jqFlag != nil && jqFlag.Changed {
|
||||
// Plain error, exit 1 (not FlagError → exit 2): the flag itself
|
||||
// parsed fine, the combination is what's wrong.
|
||||
return nil, errors.New("cannot use `--jq` without specifying `--json`")
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
package cmdutil_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
)
|
||||
|
||||
var testFields = []string{"id", "name", "kb_id", "updated_at"}
|
||||
|
||||
func newTestCmd(t *testing.T, captured **cmdutil.JSONOptions) *cobra.Command {
|
||||
t.Helper()
|
||||
cmd := &cobra.Command{
|
||||
Use: "test",
|
||||
SilenceErrors: true,
|
||||
SilenceUsage: true,
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
opts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*captured = opts
|
||||
return nil
|
||||
},
|
||||
}
|
||||
cmdutil.AddJSONFlags(cmd, testFields)
|
||||
return cmd
|
||||
}
|
||||
|
||||
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"})
|
||||
cmd.SetOut(&bytes.Buffer{})
|
||||
cmd.SetErr(&bytes.Buffer{})
|
||||
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("Execute() err = %v", err)
|
||||
}
|
||||
if !captured.Enabled() {
|
||||
t.Fatalf("expected Enabled, got nil")
|
||||
}
|
||||
if len(captured.Fields) != 0 {
|
||||
t.Errorf("bare --json must produce empty Fields, got %v", captured.Fields)
|
||||
}
|
||||
}
|
||||
|
||||
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; bare `--json`
|
||||
// (no value) is reserved as a shortcut for the unfiltered payload.
|
||||
cases := []struct {
|
||||
args []string
|
||||
want []string
|
||||
}{
|
||||
{[]string{"--json=id,name"}, []string{"id", "name"}},
|
||||
{[]string{"--json=id,name,kb_id"}, []string{"id", "name", "kb_id"}},
|
||||
{[]string{"--json=id"}, []string{"id"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(strings.Join(tc.args, " "), func(t *testing.T) {
|
||||
var captured *cmdutil.JSONOptions
|
||||
cmd := newTestCmd(t, &captured)
|
||||
cmd.SetArgs(tc.args)
|
||||
cmd.SetOut(&bytes.Buffer{})
|
||||
cmd.SetErr(&bytes.Buffer{})
|
||||
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("Execute() err = %v", err)
|
||||
}
|
||||
if captured == nil {
|
||||
t.Fatalf("expected JSONOptions captured, got nil")
|
||||
}
|
||||
if !equalSlice(captured.Fields, tc.want) {
|
||||
t.Errorf("Fields = %v, want %v", captured.Fields, tc.want)
|
||||
}
|
||||
if captured.JQ != "" {
|
||||
t.Errorf("JQ should be empty, got %q", captured.JQ)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddJSONFlags_NoFlagsSet(t *testing.T) {
|
||||
var captured *cmdutil.JSONOptions
|
||||
cmd := newTestCmd(t, &captured)
|
||||
cmd.SetArgs([]string{})
|
||||
cmd.SetOut(&bytes.Buffer{})
|
||||
cmd.SetErr(&bytes.Buffer{})
|
||||
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("Execute() err = %v", err)
|
||||
}
|
||||
if captured != nil {
|
||||
t.Errorf("expected nil JSONOptions for human mode, got %+v", captured)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddJSONFlags_JQWithoutJSON(t *testing.T) {
|
||||
var captured *cmdutil.JSONOptions
|
||||
cmd := newTestCmd(t, &captured)
|
||||
cmd.SetArgs([]string{"--jq", ".data.items[]"})
|
||||
cmd.SetOut(&bytes.Buffer{})
|
||||
cmd.SetErr(&bytes.Buffer{})
|
||||
|
||||
err := cmd.Execute()
|
||||
if err == nil {
|
||||
t.Fatalf("expected mutual-dep error, got nil")
|
||||
}
|
||||
want := "cannot use `--jq` without specifying `--json`"
|
||||
if err.Error() != want {
|
||||
t.Errorf("wrong message.\nwant: %q\ngot: %q", want, err.Error())
|
||||
}
|
||||
// Must NOT be a FlagError - gh emits this as a plain error so exit
|
||||
// code stays 1, not 2.
|
||||
var fe *cmdutil.FlagError
|
||||
if errors.As(err, &fe) {
|
||||
t.Errorf("error should not be FlagError; gh treats this as exit 1")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddJSONFlags_JQWithJSON(t *testing.T) {
|
||||
var captured *cmdutil.JSONOptions
|
||||
cmd := newTestCmd(t, &captured)
|
||||
cmd.SetArgs([]string{"--json=id,name", "--jq", ".data.items[0].id"})
|
||||
cmd.SetOut(&bytes.Buffer{})
|
||||
cmd.SetErr(&bytes.Buffer{})
|
||||
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("Execute() err = %v", err)
|
||||
}
|
||||
if captured == nil {
|
||||
t.Fatalf("expected JSONOptions, got nil")
|
||||
}
|
||||
if !equalSlice(captured.Fields, []string{"id", "name"}) {
|
||||
t.Errorf("Fields = %v, want [id name]", captured.Fields)
|
||||
}
|
||||
if captured.JQ != ".data.items[0].id" {
|
||||
t.Errorf("JQ = %q, want %q", captured.JQ, ".data.items[0].id")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddJSONFlags_JQShortFlag(t *testing.T) {
|
||||
// gh uses -q as shorthand for --jq.
|
||||
var captured *cmdutil.JSONOptions
|
||||
cmd := newTestCmd(t, &captured)
|
||||
cmd.SetArgs([]string{"--json=id", "-q", ".data"})
|
||||
cmd.SetOut(&bytes.Buffer{})
|
||||
cmd.SetErr(&bytes.Buffer{})
|
||||
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("Execute() err = %v", err)
|
||||
}
|
||||
if captured == nil || captured.JQ != ".data" {
|
||||
t.Errorf("expected JQ=.data, got %+v", captured)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddJSONFlags_HelpListsFields(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "test", Short: "A test command"}
|
||||
cmdutil.AddJSONFlags(cmd, []string{"name", "id", "updated_at"})
|
||||
if !strings.Contains(cmd.Long, "JSON fields available") {
|
||||
t.Errorf("expected help to include 'JSON fields available'; got Long=%q", cmd.Long)
|
||||
}
|
||||
// Fields should appear alphabetically sorted.
|
||||
idAt := strings.Index(cmd.Long, "id")
|
||||
nameAt := strings.Index(cmd.Long, "name")
|
||||
updatedAt := strings.Index(cmd.Long, "updated_at")
|
||||
if !(idAt < nameAt && nameAt < updatedAt) {
|
||||
t.Errorf("fields not sorted in Long: idAt=%d nameAt=%d updatedAt=%d", idAt, nameAt, updatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func equalSlice(a, b []string) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i] != b[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
Reference in New Issue
Block a user