feat(cli): --json field-select, --jq, auth token, doc --from-url
Output ergonomics:
- `--json` accepts a comma-separated field list (gh-parity); selects
named keys from the per-command payload. Bare `--json` keeps the
full shape.
- `--jq <expr>` evaluates a gojq expression over the JSON; pairs with
`--json field-list` so projection runs before jq.
- `--version` is a global cobra flag in addition to the `version`
subcommand; both render the same line.
- Per-command `--help` now renders the available JSON field list under
"JSON fields available via `--json id,name,...`" (field-discovery
parity with gh / kubectl `-o jsonpath`).
New commands:
- `auth token` — print the active context's credential to stdout for
shell command substitution (`WEKNORA_TOKEN=$(weknora auth token)`).
Default: raw secret, no trailing newline. `--json` emits
`{token, mode, context}`.
- `doc upload --from-url <URL>` — ingest a remote URL via the SDK
`CreateKnowledgeFromURL`. `--name` forwarded as `FileName` so the
server's known-extension heuristic upgrades crawl-mode to
file-download-mode where appropriate.
Includes the simplify post-review polish pass (field-filter unit
tests, --json/--jq compose check, agent_help copy fixes).
This commit is contained in:
+23
-12
@@ -14,9 +14,14 @@ import (
|
||||
)
|
||||
|
||||
type AddOptions struct {
|
||||
Host string
|
||||
User string
|
||||
JSONOut bool
|
||||
Host string
|
||||
User string
|
||||
}
|
||||
|
||||
// contextAddFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `context add`. The result describes the newly-registered context.
|
||||
var contextAddFields = []string{
|
||||
"name", "host", "user", "current",
|
||||
}
|
||||
|
||||
// addResult is the typed payload emitted under data on success.
|
||||
@@ -49,18 +54,22 @@ adds leave the current context untouched.`,
|
||||
weknora context add prod --host https://prod.example.com --user alice@example.com`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
return runAdd(opts, args[0])
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runAdd(opts, jopts, args[0])
|
||||
},
|
||||
}
|
||||
cmd.Flags().StringVar(&opts.Host, "host", "", "Server base URL, e.g. https://kb.example.com (required)")
|
||||
cmd.Flags().StringVar(&opts.User, "user", "", "Account email shown in 'context list' (optional, cosmetic only)")
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
cmdutil.AddJSONFlags(cmd, contextAddFields)
|
||||
_ = cmd.MarkFlagRequired("host")
|
||||
agent.SetAgentHelp(cmd, "Adds a context. First context added auto-becomes current. Errors with resource.already_exists if name collides; input.invalid_argument if --host is not an absolute http(s) URL.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runAdd(opts *AddOptions, name string) error {
|
||||
func runAdd(opts *AddOptions, jopts *cmdutil.JSONOptions, name string) error {
|
||||
if err := validateName(name); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -93,12 +102,14 @@ func runAdd(opts *AddOptions, name string) error {
|
||||
}
|
||||
|
||||
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("add context %s", name)}
|
||||
if opts.JSONOut {
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(
|
||||
addResult{Name: name, Host: host, User: opts.User, Current: wasFirst},
|
||||
&format.Meta{Context: cfg.CurrentContext},
|
||||
risk,
|
||||
))
|
||||
if jopts.Enabled() {
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
|
||||
format.SuccessWithRisk(
|
||||
addResult{Name: name, Host: host, User: opts.User, Current: wasFirst},
|
||||
&format.Meta{Context: cfg.CurrentContext},
|
||||
risk,
|
||||
),
|
||||
jopts.Fields, jopts.JQ)
|
||||
}
|
||||
if wasFirst {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Added context %s (now current). Run `weknora auth login --name %s` to attach credentials.\n", name, name)
|
||||
|
||||
@@ -15,7 +15,7 @@ func TestAdd_HappyPath(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
if err := runAdd(&AddOptions{Host: "https://my.example.com", User: "alice@example.com"}, "staging"); err != nil {
|
||||
if err := runAdd(&AddOptions{Host: "https://my.example.com", User: "alice@example.com"}, nil, "staging"); err != nil {
|
||||
t.Fatalf("runAdd: %v", err)
|
||||
}
|
||||
|
||||
@@ -54,7 +54,7 @@ func TestAdd_DuplicateName(t *testing.T) {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
err := runAdd(&AddOptions{Host: "https://new.example.com"}, "staging")
|
||||
err := runAdd(&AddOptions{Host: "https://new.example.com"}, nil, "staging")
|
||||
if err == nil {
|
||||
t.Fatal("expected error on duplicate name")
|
||||
}
|
||||
@@ -83,7 +83,7 @@ func TestAdd_BadHost(t *testing.T) {
|
||||
"http://", // missing host
|
||||
}
|
||||
for _, h := range bad {
|
||||
err := runAdd(&AddOptions{Host: h}, "staging")
|
||||
err := runAdd(&AddOptions{Host: h}, nil, "staging")
|
||||
if err == nil {
|
||||
t.Errorf("host=%q: expected error", h)
|
||||
continue
|
||||
@@ -111,7 +111,7 @@ func TestAdd_SecondContextDoesNotChangeCurrent(t *testing.T) {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
if err := runAdd(&AddOptions{Host: "https://stg.example.com"}, "staging"); err != nil {
|
||||
if err := runAdd(&AddOptions{Host: "https://stg.example.com"}, nil, "staging"); err != nil {
|
||||
t.Fatalf("runAdd: %v", err)
|
||||
}
|
||||
got, _ := config.Load()
|
||||
@@ -124,7 +124,7 @@ func TestAdd_JSON(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
if err := runAdd(&AddOptions{Host: "https://my.example.com", JSONOut: true}, "staging"); err != nil {
|
||||
if err := runAdd(&AddOptions{Host: "https://my.example.com"}, &cmdutil.JSONOptions{}, "staging"); err != nil {
|
||||
t.Fatalf("runAdd: %v", err)
|
||||
}
|
||||
var env format.Envelope
|
||||
|
||||
+17
-9
@@ -14,8 +14,12 @@ import (
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
)
|
||||
|
||||
type ListOptions struct {
|
||||
JSONOut bool
|
||||
type ListOptions struct{}
|
||||
|
||||
// contextListFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `context list`. Each entry is a per-context summary row.
|
||||
var contextListFields = []string{
|
||||
"name", "host", "user", "current",
|
||||
}
|
||||
|
||||
type listEntry struct {
|
||||
@@ -28,7 +32,6 @@ type listEntry struct {
|
||||
// NewCmdList builds `weknora context list`. Per-host enumeration with an
|
||||
// active marker. Reads only config.yaml — no network, no keyring touch.
|
||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &ListOptions{}
|
||||
cmd := &cobra.Command{
|
||||
Use: "list",
|
||||
Short: "List configured contexts",
|
||||
@@ -41,15 +44,19 @@ run "weknora auth list" for that. "context list" is the catalog of *where*
|
||||
the CLI can talk to; "auth list" is the catalog of *how*.`,
|
||||
Args: cobra.NoArgs,
|
||||
RunE: func(c *cobra.Command, _ []string) error {
|
||||
return runList(opts)
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runList(jopts)
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
cmdutil.AddJSONFlags(cmd, contextListFields)
|
||||
agent.SetAgentHelp(cmd, "Lists CLI contexts (name/host/user/current). Read-only, no network. Use this before context use to verify the target name exists.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runList(opts *ListOptions) error {
|
||||
func runList(jopts *cmdutil.JSONOptions) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -65,9 +72,10 @@ func runList(opts *ListOptions) error {
|
||||
}
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
|
||||
|
||||
if opts.JSONOut {
|
||||
return format.WriteEnvelope(iostreams.IO.Out,
|
||||
format.Success(entries, &format.Meta{Context: cfg.CurrentContext}))
|
||||
if jopts.Enabled() {
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
|
||||
format.Success(entries, &format.Meta{Context: cfg.CurrentContext}),
|
||||
jopts.Fields, jopts.JQ)
|
||||
}
|
||||
if len(entries) == 0 {
|
||||
fmt.Fprintln(iostreams.IO.Out, "No contexts configured. Run `weknora auth login` (or `weknora context add`) to create one.")
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/config"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
@@ -14,7 +15,7 @@ func TestList_Empty(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
if err := runList(&ListOptions{}); err != nil {
|
||||
if err := runList(nil); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
if !strings.Contains(out.String(), "No contexts") {
|
||||
@@ -38,7 +39,7 @@ func TestList_MultipleSorted(t *testing.T) {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
if err := runList(&ListOptions{}); err != nil {
|
||||
if err := runList(nil); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
@@ -75,7 +76,7 @@ func TestList_JSON(t *testing.T) {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
if err := runList(&ListOptions{JSONOut: true}); err != nil {
|
||||
if err := runList(&cmdutil.JSONOptions{}); err != nil {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
|
||||
|
||||
+22
-12
@@ -15,9 +15,14 @@ import (
|
||||
)
|
||||
|
||||
type RemoveOptions struct {
|
||||
Yes bool // sourced from the global -y/--yes persistent flag (matches `kb delete`)
|
||||
JSONOut bool
|
||||
DryRun bool
|
||||
Yes bool // sourced from the global -y/--yes persistent flag (matches `kb delete`)
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// contextRemoveFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `context remove`. The result reports the disposition of the removed entry.
|
||||
var contextRemoveFields = []string{
|
||||
"name", "removed", "was_current",
|
||||
}
|
||||
|
||||
// removeResult is the typed payload emitted under data on success.
|
||||
@@ -49,21 +54,25 @@ in scripted / --json invocations (exit code 10; see cli/AGENTS.md).`,
|
||||
weknora context remove production -y # remove current → confirm`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
store, err := f.Secrets()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return runRemove(opts, args[0], store, f.Prompter())
|
||||
return runRemove(opts, jopts, args[0], store, f.Prompter())
|
||||
},
|
||||
}
|
||||
cmd.Flags().BoolVar(&opts.JSONOut, "json", false, "Output JSON envelope")
|
||||
cmdutil.AddJSONFlags(cmd, contextRemoveFields)
|
||||
agent.SetAgentHelp(cmd, "Removes a context entry. Removing the current context requires -y in non-TTY/--json (exit-10). Always best-effort clears keyring refs.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
func runRemove(opts *RemoveOptions, name string, store secrets.Store, p prompt.Prompter) error {
|
||||
func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, store secrets.Store, p prompt.Prompter) error {
|
||||
cfg, err := config.Load()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -75,8 +84,9 @@ func runRemove(opts *RemoveOptions, name string, store secrets.Store, p prompt.P
|
||||
wasCurrent := name == cfg.CurrentContext
|
||||
risk := riskForRemove(name, wasCurrent)
|
||||
|
||||
jsonOut := jopts.Enabled()
|
||||
if opts.DryRun {
|
||||
return cmdutil.EmitDryRun(opts.JSONOut,
|
||||
return cmdutil.EmitDryRun(jsonOut,
|
||||
removeResult{Name: name, Removed: false, WasCurrent: wasCurrent},
|
||||
&format.Meta{Context: cfg.CurrentContext},
|
||||
risk)
|
||||
@@ -84,7 +94,7 @@ func runRemove(opts *RemoveOptions, name string, store secrets.Store, p prompt.P
|
||||
// Confirmation only fires for removing the current context — non-current
|
||||
// remove uses the same low-friction policy as `auth logout`.
|
||||
if wasCurrent {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, opts.JSONOut, "current context", name); err != nil {
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jsonOut, "current context", name); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
@@ -101,10 +111,10 @@ func runRemove(opts *RemoveOptions, name string, store secrets.Store, p prompt.P
|
||||
clearContextSecrets(store, ctx, name)
|
||||
|
||||
result := removeResult{Name: name, Removed: true, WasCurrent: wasCurrent}
|
||||
if opts.JSONOut {
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.SuccessWithRisk(
|
||||
result, &format.Meta{Context: cfg.CurrentContext}, risk,
|
||||
))
|
||||
if jsonOut {
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
|
||||
format.SuccessWithRisk(result, &format.Meta{Context: cfg.CurrentContext}, risk),
|
||||
jopts.Fields, jopts.JQ)
|
||||
}
|
||||
if wasCurrent {
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Removed context %s (current context cleared — run `weknora context use <name>` to pick another)\n", name)
|
||||
|
||||
@@ -52,7 +52,7 @@ func TestRemove_NonCurrent_NoPromptNeeded(t *testing.T) {
|
||||
|
||||
store := seedStore(t, "staging", "api_key")
|
||||
p := &testutil.ConfirmPrompter{}
|
||||
if err := runRemove(&RemoveOptions{}, "staging", store, p); err != nil {
|
||||
if err := runRemove(&RemoveOptions{}, nil, "staging", store, p); err != nil {
|
||||
t.Fatalf("runRemove: %v", err)
|
||||
}
|
||||
if p.Asked {
|
||||
@@ -84,7 +84,7 @@ func TestRemove_NotFound_WithDidYouMean(t *testing.T) {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
err := runRemove(&RemoveOptions{}, "prodution", secrets.NewMemStore(), &testutil.ConfirmPrompter{})
|
||||
err := runRemove(&RemoveOptions{}, nil, "prodution", secrets.NewMemStore(), &testutil.ConfirmPrompter{})
|
||||
if err == nil {
|
||||
t.Fatal("expected not-found error")
|
||||
}
|
||||
@@ -116,7 +116,7 @@ func TestRemove_Current_NonTTY_NoYes_RequiresConfirmation(t *testing.T) {
|
||||
}
|
||||
|
||||
store := seedStore(t, "production", "access")
|
||||
err := runRemove(&RemoveOptions{}, "production", store, &testutil.ConfirmPrompter{})
|
||||
err := runRemove(&RemoveOptions{}, nil, "production", store, &testutil.ConfirmPrompter{})
|
||||
if err == nil {
|
||||
t.Fatal("expected confirmation-required error")
|
||||
}
|
||||
@@ -155,7 +155,7 @@ func TestRemove_Current_WithYes_ClearsCurrent(t *testing.T) {
|
||||
}
|
||||
|
||||
store := seedStore(t, "production", "access")
|
||||
if err := runRemove(&RemoveOptions{Yes: true}, "production", store, &testutil.ConfirmPrompter{}); err != nil {
|
||||
if err := runRemove(&RemoveOptions{Yes: true}, nil, "production", store, &testutil.ConfirmPrompter{}); err != nil {
|
||||
t.Fatalf("runRemove: %v", err)
|
||||
}
|
||||
got, _ := config.Load()
|
||||
@@ -184,7 +184,7 @@ func TestRemove_Current_TTY_PromptNo(t *testing.T) {
|
||||
}
|
||||
|
||||
p := &testutil.ConfirmPrompter{Answer: false}
|
||||
err := runRemove(&RemoveOptions{}, "production", secrets.NewMemStore(), p)
|
||||
err := runRemove(&RemoveOptions{}, nil, "production", secrets.NewMemStore(), p)
|
||||
if err == nil {
|
||||
t.Fatal("expected user-aborted error")
|
||||
}
|
||||
@@ -219,7 +219,7 @@ func TestRemove_DryRun(t *testing.T) {
|
||||
}
|
||||
|
||||
store := seedStore(t, "production", "access")
|
||||
if err := runRemove(&RemoveOptions{DryRun: true, JSONOut: true}, "production", store, &testutil.ConfirmPrompter{}); err != nil {
|
||||
if err := runRemove(&RemoveOptions{DryRun: true}, &cmdutil.JSONOptions{}, "production", store, &testutil.ConfirmPrompter{}); err != nil {
|
||||
t.Fatalf("runRemove dry-run: %v", err)
|
||||
}
|
||||
var env format.Envelope
|
||||
|
||||
Reference in New Issue
Block a user