refactor(cli): drop --dry-run + introduce bare-JSON output path
Two intertwined mainstream-alignment moves bundled because they share
the migration target (every command's --json path):
1. Drop --dry-run entirely. Survey of comparable API-wrapper CLIs
(gh, aws, stripe, lark): none expose --dry-run. The mainstream that
does (kubectl/git/helm/ansible) operates on declarative manifests
or local state where the preview is materially different from the
executed action. WeKnora's CLI just echoed the same parameters
that would have gone on the wire — the preview added no real
signal over `--help` + reading the call site. Removes:
- root --dry-run persistent flag + cmdutil/dryrun.go
- DryRun fields + EmitDryRun calls in 12 write commands
- format.Envelope.DryRun field
- 8 corresponding *_test.go cases
- --dry-run mention from README.md and CHANGELOG.md
- "dry_run":false from 16 golden envelopes
2. Migrate every --json output to bare data:
- New format.WriteJSON / WriteJSONFiltered helpers
(cli/internal/format/bare.go) share filterArrayItems /
filterObjectKeys / writeJQ with the (still-live for now) envelope
filter helpers.
- Read commands (kb/doc/session list+view, search chunks/docs/
sessions/kb, auth list/status, agent list/view, context list,
doctor) emit bare arrays / objects on stdout.
- Write commands (kb create/edit/delete/pin/empty, doc upload/
upload_recursive/delete, session delete, auth login/logout/
refresh/token, link/unlink, context add/use/remove, agent
invoke, chat, api, version) emit bare result objects. Risk
classification dropped — the resource + exit code already
convey the action.
Per-command shape changes:
list / search → []T (was {ok, data:{items:[…]}})
view → T (was {ok, data:T, _meta:…})
create / edit → T
delete / pin / etc. → {id, …action result…}
doctor → {summary, checks}
api → {status, headers, body}
_meta dropped on the read path:
pagination (page/page_size/total/has_more) — agents iterate with
--all-pages or accept --limit (gh CLI parity);
kb_id / context echo — caller already knows what it asked for.
Acceptance contract goldens regenerated for the new bare shape.
Error envelope on stdout (PrintErrorEnvelope) stays live for now —
the envelope-infra deletion lands in the next commit.
This commit is contained in:
@@ -101,14 +101,9 @@ func runAdd(opts *AddOptions, jopts *cmdutil.JSONOptions, name string) error {
|
||||
return cmdutil.Wrapf(cmdutil.CodeLocalFileIO, err, "save config")
|
||||
}
|
||||
|
||||
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("add context %s", name)}
|
||||
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,
|
||||
),
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out,
|
||||
addResult{Name: name, Host: host, User: opts.User, Current: wasFirst},
|
||||
jopts.Fields, jopts.JQ)
|
||||
}
|
||||
if wasFirst {
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
@@ -127,15 +126,18 @@ func TestAdd_JSON(t *testing.T) {
|
||||
if err := runAdd(&AddOptions{Host: "https://my.example.com"}, &cmdutil.JSONOptions{}, "staging"); err != nil {
|
||||
t.Fatalf("runAdd: %v", err)
|
||||
}
|
||||
var env format.Envelope
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("invalid JSON envelope: %v\noutput=%q", err, out.String())
|
||||
var got map[string]any
|
||||
if err := json.Unmarshal(out.Bytes(), &got); err != nil {
|
||||
t.Fatalf("invalid JSON: %v\noutput=%q", err, out.String())
|
||||
}
|
||||
if !env.OK {
|
||||
t.Fatalf("envelope.ok=false, error=%+v", env.Error)
|
||||
if got["name"] != "staging" {
|
||||
t.Errorf("name should be staging, got %v", got)
|
||||
}
|
||||
if env.Risk == nil || env.Risk.Level != format.RiskWrite {
|
||||
t.Errorf("envelope.risk should be write-level, got %+v", env.Risk)
|
||||
if got["host"] != "https://my.example.com" {
|
||||
t.Errorf("host wrong: %v", got)
|
||||
}
|
||||
if got["current"] != true {
|
||||
t.Errorf("first added context must be current=true, got %v", got)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -73,9 +73,7 @@ func runList(jopts *cmdutil.JSONOptions) error {
|
||||
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
|
||||
|
||||
if jopts.Enabled() {
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
|
||||
format.Success(entries, &format.Meta{Context: cfg.CurrentContext}),
|
||||
jopts.Fields, jopts.JQ)
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, entries, 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.")
|
||||
|
||||
@@ -7,7 +7,6 @@ import (
|
||||
|
||||
"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"
|
||||
)
|
||||
|
||||
@@ -80,31 +79,19 @@ func TestList_JSON(t *testing.T) {
|
||||
t.Fatalf("runList: %v", err)
|
||||
}
|
||||
|
||||
var env format.Envelope
|
||||
if err := json.Unmarshal(out.Bytes(), &env); err != nil {
|
||||
t.Fatalf("invalid JSON envelope: %v\noutput=%q", err, out.String())
|
||||
}
|
||||
if !env.OK {
|
||||
t.Fatalf("envelope.ok=false, error=%+v", env.Error)
|
||||
}
|
||||
if env.Meta == nil || env.Meta.Context != "staging" {
|
||||
t.Errorf("envelope._meta.context should be %q, got %+v", "staging", env.Meta)
|
||||
}
|
||||
rows, ok := env.Data.([]any)
|
||||
if !ok {
|
||||
t.Fatalf("envelope.data should be []listEntry, got %T", env.Data)
|
||||
var rows []map[string]any
|
||||
if err := json.Unmarshal(out.Bytes(), &rows); err != nil {
|
||||
t.Fatalf("invalid JSON: %v\noutput=%q", err, out.String())
|
||||
}
|
||||
if len(rows) != 2 {
|
||||
t.Fatalf("expected 2 entries, got %d", len(rows))
|
||||
}
|
||||
// alphabetical: production before staging
|
||||
first := rows[0].(map[string]any)
|
||||
if first["name"] != "production" {
|
||||
t.Errorf("first row should be production, got %v", first)
|
||||
if rows[0]["name"] != "production" {
|
||||
t.Errorf("first row should be production, got %v", rows[0])
|
||||
}
|
||||
second := rows[1].(map[string]any)
|
||||
if second["name"] != "staging" || second["current"] != true {
|
||||
t.Errorf("second row should be staging with current=true, got %v", second)
|
||||
if rows[1]["name"] != "staging" || rows[1]["current"] != true {
|
||||
t.Errorf("second row should be staging with current=true, got %v", rows[1])
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,7 @@ import (
|
||||
)
|
||||
|
||||
type RemoveOptions struct {
|
||||
Yes bool // sourced from the global -y/--yes persistent flag (matches `kb delete`)
|
||||
DryRun bool
|
||||
Yes bool // sourced from the global -y/--yes persistent flag (matches `kb delete`)
|
||||
}
|
||||
|
||||
// contextRemoveFields enumerates the fields surfaced for `--json` discovery on
|
||||
@@ -59,7 +58,6 @@ in scripted / --json invocations (exit code 10; see cli/AGENTS.md).`,
|
||||
return err
|
||||
}
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
store, err := f.Secrets()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -85,12 +83,6 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto
|
||||
risk := riskForRemove(name, wasCurrent)
|
||||
|
||||
jsonOut := jopts.Enabled()
|
||||
if opts.DryRun {
|
||||
return cmdutil.EmitDryRun(jsonOut,
|
||||
removeResult{Name: name, Removed: false, WasCurrent: wasCurrent},
|
||||
&format.Meta{Context: cfg.CurrentContext},
|
||||
risk)
|
||||
}
|
||||
// Confirmation only fires for removing the current context — non-current
|
||||
// remove uses the same low-friction policy as `auth logout`.
|
||||
if wasCurrent {
|
||||
@@ -110,11 +102,10 @@ func runRemove(opts *RemoveOptions, jopts *cmdutil.JSONOptions, name string, sto
|
||||
}
|
||||
clearContextSecrets(store, ctx, name)
|
||||
|
||||
_ = risk // risk classification dropped in v0.4; exit code already signals
|
||||
result := removeResult{Name: name, Removed: true, WasCurrent: wasCurrent}
|
||||
if jsonOut {
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
|
||||
format.SuccessWithRisk(result, &format.Meta{Context: cfg.CurrentContext}, risk),
|
||||
jopts.Fields, jopts.JQ)
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, result, 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)
|
||||
|
||||
@@ -1,14 +1,12 @@
|
||||
package contextcmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"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"
|
||||
"github.com/Tencent/WeKnora/cli/internal/secrets"
|
||||
"github.com/Tencent/WeKnora/cli/internal/testutil"
|
||||
@@ -206,37 +204,3 @@ func TestRemove_Current_TTY_PromptNo(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestRemove_DryRun(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
|
||||
cfg := &config.Config{
|
||||
CurrentContext: "production",
|
||||
Contexts: map[string]config.Context{"production": {Host: "https://prod", TokenRef: "mem://production/access"}},
|
||||
}
|
||||
if err := config.Save(cfg); err != nil {
|
||||
t.Fatalf("Save: %v", err)
|
||||
}
|
||||
|
||||
store := seedStore(t, "production", "access")
|
||||
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
|
||||
if jerr := json.Unmarshal(out.Bytes(), &env); jerr != nil {
|
||||
t.Fatalf("invalid envelope: %v\noutput=%q", jerr, out.String())
|
||||
}
|
||||
if !env.OK || !env.DryRun {
|
||||
t.Errorf("envelope should be ok=true, dry_run=true, got %+v", env)
|
||||
}
|
||||
if env.Risk == nil || env.Risk.Level != format.RiskHighRiskWrite {
|
||||
t.Errorf("dry-run on current context should report high-risk-write, got %+v", env.Risk)
|
||||
}
|
||||
// Nothing actually mutated.
|
||||
if got, _ := config.Load(); got.CurrentContext != "production" {
|
||||
t.Errorf("dry-run must not mutate config")
|
||||
}
|
||||
if v, err := store.Get("production", "access"); err != nil || v == "" {
|
||||
t.Errorf("dry-run must not touch keyring; get=%q err=%v", v, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,10 +57,10 @@ func runUse(name string) error {
|
||||
if err := config.Save(cfg); err != nil {
|
||||
return err
|
||||
}
|
||||
return format.WriteEnvelope(iostreams.IO.Out, format.Success(useResult{
|
||||
return format.WriteJSON(iostreams.IO.Out, useResult{
|
||||
CurrentContext: name,
|
||||
PreviousContext: prev,
|
||||
}, nil))
|
||||
})
|
||||
}
|
||||
|
||||
func notFoundError(name string, cfg *config.Config) error {
|
||||
|
||||
Reference in New Issue
Block a user