WeKnora/cli/internal/format/bare_test.go

141 lines
4.3 KiB
Go
Raw Normal View History

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.
2026-05-14 15:28:14 +00:00
package format_test
import (
"bytes"
"encoding/json"
"strings"
"testing"
"github.com/Tencent/WeKnora/cli/internal/format"
)
func TestWriteJSON_BareArray(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSON(buf, []map[string]string{
{"id": "1", "name": "alpha"},
{"id": "2", "name": "beta"},
}); err != nil {
t.Fatalf("err = %v", err)
}
if !bytes.HasPrefix(buf.Bytes(), []byte("[")) {
t.Errorf("expected bare JSON array, got %q", buf.String())
}
}
func TestWriteJSON_BareObject(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSON(buf, map[string]any{"id": "kb_x", "name": "Engineering"}); err != nil {
t.Fatalf("err = %v", err)
}
if !bytes.HasPrefix(buf.Bytes(), []byte("{")) {
t.Errorf("expected bare JSON object, got %q", buf.String())
}
if bytes.Contains(buf.Bytes(), []byte(`"ok":`)) || bytes.Contains(buf.Bytes(), []byte(`"data":`)) {
t.Errorf("bare output must not carry envelope keys: %s", buf.String())
}
}
func TestWriteJSONFiltered_FieldsOnArray(t *testing.T) {
buf := &bytes.Buffer{}
items := []map[string]any{
{"id": "1", "name": "alpha", "kb_id": "kb_x", "updated_at": "2026-01-01"},
{"id": "2", "name": "beta", "kb_id": "kb_x", "updated_at": "2026-01-02"},
}
if err := format.WriteJSONFiltered(buf, items, []string{"id", "name"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
var got []map[string]string
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("parse: %v\n%s", err, buf.String())
}
if len(got) != 2 {
t.Fatalf("items len = %d, want 2", len(got))
}
for i, item := range got {
if _, has := item["kb_id"]; has {
t.Errorf("item[%d] should not have kb_id: %v", i, item)
}
if item["id"] == "" || item["name"] == "" {
t.Errorf("item[%d] missing kept fields: %v", i, item)
}
}
}
func TestWriteJSONFiltered_FieldsOnObject(t *testing.T) {
buf := &bytes.Buffer{}
obj := map[string]any{"id": "kb_x", "name": "Engineering", "owner": "alice"}
if err := format.WriteJSONFiltered(buf, obj, []string{"id", "name"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
var got map[string]string
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("parse: %v\n%s", err, buf.String())
}
if _, has := got["owner"]; has {
t.Errorf("should not retain owner: %v", got)
}
if got["id"] != "kb_x" || got["name"] != "Engineering" {
t.Errorf("kept fields missing: %v", got)
}
}
func TestWriteJSONFiltered_UnknownFieldSilent(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSONFiltered(buf, map[string]any{"id": "1"}, []string{"id", "nonexistent"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
var got map[string]any
if err := json.Unmarshal(buf.Bytes(), &got); err != nil {
t.Fatalf("parse: %v", err)
}
if got["id"] != "1" {
t.Errorf("id missing: %v", got)
}
if _, has := got["nonexistent"]; has {
t.Errorf("nonexistent should be silently dropped: %v", got)
}
}
func TestWriteJSONFiltered_JQOnly(t *testing.T) {
buf := &bytes.Buffer{}
items := []map[string]any{
{"id": "1", "name": "alpha"},
{"id": "2", "name": "beta"},
}
if err := format.WriteJSONFiltered(buf, items, nil, ".[].id"); err != nil {
t.Fatalf("err = %v", err)
}
chore(cli): polish + docs sync + pre-PR audit fixes Code-reuse polish (post-implementation review pass): - Extract text.OneLine(maxWidth, s) helper combining preview-row normalization (newline/CR/tab → space) with text.Truncate's UTF-8-safe truncation. Replaces agent/view.go truncate1Line (ASCII '...' + byte-slice CJK-unsafe) and chunk/list.go singleLine. - Lift cmdutil.OpenInput(path) for the '-' = stdin / else os.Open pattern shared across agent create/edit and the api command. Replaces agent/create.go's private openInput. - Strip inline doc-spec parentheticals from source comments — those belong in commit messages and project docs, not in source where they rot. Pre-PR audit fixes: - doc upload: reject `--metadata` paired with `--from-url` as input.invalid_argument up-front (the URL-ingest request type has no metadata field server-side, so the pair would otherwise silently drop). Long help and CHANGELOG updated to call out the asymmetry. - doc upload (file path): map sdk.ErrDuplicateFile sentinel to resource.already_exists. The sentinel arrives with no "HTTP error <n>:" prefix because the SDK short-circuits on file-hash before reading the HTTP status, so the previous WrapHTTP fall-through misclassified it as network.error with a misleading "check base URL reachability" hint. The --from-url branch already handled ErrDuplicateURL this way; this closes the asymmetry. Caught by e2e re-upload of an already-ingested file; regression test added. - README exit-10 enumeration adds `agent delete` and `chunk delete` (these were missing alongside the v0.5 destructive verbs they were meant to gate). Docs sync: - cli/README.md: command tree now includes the chunk subtree; adds agent / chunk lines to the 5-minute quickstart; adds a "Contributing / Reporting issues" section pointing at the repo's SECURITY.md and AGENTS.md; drops third-party CLI parallels from the surface description. - cli/AGENTS.md: "Command surface design SOP" gains the flag-vs-escape-hatch step. "CRUD command flag canon" renamed to the hard-required-flags pattern with the contrast (TTY-prompts-fill) defined inline rather than via opaque shorthand. - cli/CHANGELOG.md: search docs case-sensitivity shift promoted to its own #### Breaking changes subsection. MCP doc_list filter count corrected from 5 to 6. Drops the bogus go.mod yaml.v3 entry (yaml.v3 was already a dependency on main; v0.5 added zero go.mod lines). Replaces internal-Go identifiers (fuzzyTime, NoOptDefVal) with user-language and drops the § section-symbol jargon.
2026-05-15 18:42:18 +00:00
// String / scalar results render without JSON quotes so scalar
// projections (e.g. `--jq '.[].id'`) pipe cleanly into shell tools.
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.
2026-05-14 15:28:14 +00:00
lines := strings.Split(strings.TrimRight(buf.String(), "\n"), "\n")
if len(lines) != 2 || lines[0] != "1" || lines[1] != "2" {
t.Errorf("jq output mismatch: %q", buf.String())
}
}
func TestWriteJSONFiltered_FieldsAndJQ(t *testing.T) {
buf := &bytes.Buffer{}
items := []map[string]any{
{"id": "1", "name": "alpha", "secret": "drop-me"},
{"id": "2", "name": "beta", "secret": "drop-me"},
}
// Field filter first → then jq selects from filtered shape.
if err := format.WriteJSONFiltered(buf, items, []string{"id"}, ".[].id"); err != nil {
t.Fatalf("err = %v", err)
}
out := buf.String()
if strings.Contains(out, "drop-me") {
t.Errorf("field filter must drop unrequested keys before jq: %q", out)
}
}
func TestWriteJSONFiltered_NilDataPassthrough(t *testing.T) {
buf := &bytes.Buffer{}
if err := format.WriteJSONFiltered(buf, nil, []string{"id"}, ""); err != nil {
t.Fatalf("err = %v", err)
}
if strings.TrimSpace(buf.String()) != "null" {
t.Errorf("nil should marshal to bare null, got %q", buf.String())
}
}