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:
+2
-14
@@ -18,8 +18,7 @@ import (
|
||||
var docDeleteFields = []string{"id", "deleted"}
|
||||
|
||||
type DeleteOptions struct {
|
||||
Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go)
|
||||
DryRun bool
|
||||
Yes bool // sourced from the global -y/--yes persistent flag (see cli/cmd/root.go)
|
||||
}
|
||||
|
||||
// DeleteService is the narrow SDK surface this command depends on.
|
||||
@@ -58,10 +57,6 @@ without the user's explicit go-ahead.`,
|
||||
return err
|
||||
}
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
if opts.DryRun {
|
||||
return runDelete(c.Context(), opts, jopts, nil, f.Prompter(), args[0])
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -75,12 +70,6 @@ without the user's explicit go-ahead.`,
|
||||
}
|
||||
|
||||
func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOptions, svc DeleteService, p prompt.Prompter, id string) error {
|
||||
if opts.DryRun {
|
||||
return cmdutil.EmitDryRun(jopts.Enabled(),
|
||||
deleteResult{ID: id, Deleted: false}, nil,
|
||||
&format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("delete document %s", id)})
|
||||
}
|
||||
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), "document", id); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -90,8 +79,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOpti
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
risk := &format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("deleted document %s", id)}
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.SuccessWithRisk(deleteResult{ID: id, Deleted: true}, nil, risk), jopts.Fields, jopts.JQ)
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, deleteResult{ID: id, Deleted: true}, jopts.Fields, jopts.JQ)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "✓ Deleted document %s\n", id)
|
||||
return nil
|
||||
|
||||
@@ -64,9 +64,9 @@ func TestDelete_Success_JSON(t *testing.T) {
|
||||
require.NoError(t, runDelete(context.Background(), opts, &cmdutil.JSONOptions{}, svc, scriptedConfirm{confirmReturn: true}, "doc_abc"))
|
||||
|
||||
got := out.String()
|
||||
assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)
|
||||
assert.Contains(t, got, `"id":"doc_abc"`)
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"doc_abc"`), "expected bare object; got %q", got)
|
||||
assert.Contains(t, got, `"deleted":true`)
|
||||
assert.NotContains(t, got, `"ok":`)
|
||||
}
|
||||
|
||||
func TestDelete_NotFound_404(t *testing.T) {
|
||||
|
||||
+4
-24
@@ -20,8 +20,7 @@ import (
|
||||
)
|
||||
|
||||
// docListFields enumerates the fields surfaced for `--json` discovery on
|
||||
// `doc list`. These are the per-item (Knowledge) fields, not the envelope
|
||||
// wrappers (items/page/total/kb_id) — filtering applies to data.items[*].
|
||||
// `doc list`. Filter applies to each Knowledge object in the bare array.
|
||||
var docListFields = []string{
|
||||
"id", "knowledge_base_id", "tag_id", "type", "title", "description",
|
||||
"source", "channel", "parse_status", "summary_status", "enable_status",
|
||||
@@ -54,14 +53,6 @@ type ListService interface {
|
||||
ListKnowledgeWithFilter(ctx context.Context, kbID string, page, pageSize int, filter sdk.KnowledgeListFilter) ([]sdk.Knowledge, int64, error)
|
||||
}
|
||||
|
||||
// listResult is the typed payload emitted under data. Pagination
|
||||
// metadata (page / page_size / total) lives in envelope `_meta`, and
|
||||
// kb_id is in `_meta.kb_id`, so this stays a single-shape `{items}`
|
||||
// payload consistent with every other list command.
|
||||
type listResult struct {
|
||||
Items []sdk.Knowledge `json:"items"`
|
||||
}
|
||||
|
||||
// NewCmdList builds `weknora doc list`.
|
||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &ListOptions{}
|
||||
@@ -104,7 +95,7 @@ backend storage order is not guaranteed and varies between deployments.`,
|
||||
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)")
|
||||
cmd.Flags().StringVar(&opts.Status, "status", "", "Filter by parse status: pending | processing | completed | failed")
|
||||
cmdutil.AddJSONFlags(cmd, docListFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists docs in the resolved KB. data.{items}; pagination + kb_id in _meta.{page, page_size, total, kb_id}. --status filters server-side; `failed` surfaces ingestion errors. --all-pages walks every server page until exhausted (capped by --limit), useful for one-shot exports.")
|
||||
aiclient.SetAgentHelp(cmd, "Lists docs in the resolved KB as a bare JSON array of Knowledge objects (empty `[]` when none). --status filters server-side; `failed` surfaces ingestion errors. --all-pages walks every server page until exhausted (capped by --limit), useful for one-shot exports.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -178,21 +169,10 @@ func runList(ctx context.Context, opts *ListOptions, jopts *cmdutil.JSONOptions,
|
||||
if opts.Limit > 0 && len(items) > opts.Limit {
|
||||
items = items[:opts.Limit]
|
||||
}
|
||||
_ = total // pagination metadata is no longer surfaced; --all-pages drains for callers who need everything
|
||||
|
||||
r := listResult{Items: items}
|
||||
if jopts.Enabled() {
|
||||
// --all-pages collapses pagination into a single conceptual page,
|
||||
// so the meta reflects "you got everything" semantics.
|
||||
meta := &format.Meta{
|
||||
KBID: kbID,
|
||||
Page: 1,
|
||||
PageSize: opts.PageSize,
|
||||
Total: total,
|
||||
}
|
||||
if !opts.AllPages {
|
||||
meta.HasMore = int64(opts.PageSize) < total
|
||||
}
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.Success(r, meta), jopts.Fields, jopts.JQ)
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, items, jopts.Fields, jopts.JQ)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
||||
@@ -79,13 +79,10 @@ func TestList_Success_JSON(t *testing.T) {
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.JSONOptions{}, svc, "kb_xxx"))
|
||||
|
||||
got := out.String()
|
||||
assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)
|
||||
assert.Contains(t, got, `"items":[`)
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `[`), "expected bare JSON array, got %q", got)
|
||||
assert.Contains(t, got, `"id":"doc1"`)
|
||||
assert.Contains(t, got, `"page":1`)
|
||||
assert.Contains(t, got, `"page_size":20`)
|
||||
assert.Contains(t, got, `"total":1`)
|
||||
assert.Contains(t, got, `"kb_id":"kb_xxx"`)
|
||||
assert.NotContains(t, got, `"ok":`)
|
||||
assert.NotContains(t, got, `"_meta":`)
|
||||
}
|
||||
|
||||
func TestList_Empty_Human(t *testing.T) {
|
||||
@@ -102,9 +99,8 @@ func TestList_Empty_JSON(t *testing.T) {
|
||||
opts := &ListOptions{PageSize: 20}
|
||||
require.NoError(t, runList(context.Background(), opts, &cmdutil.JSONOptions{}, svc, "kb_xxx"))
|
||||
|
||||
got := out.String()
|
||||
assert.Contains(t, got, `"items":[]`, "items must serialize as [] not null")
|
||||
assert.NotContains(t, got, `"items":null`)
|
||||
got := strings.TrimSpace(out.String())
|
||||
assert.Equal(t, "[]", got, "empty list must serialize as bare `[]` not null")
|
||||
}
|
||||
|
||||
func TestList_HTTPError_500(t *testing.T) {
|
||||
|
||||
+12
-39
@@ -36,7 +36,6 @@ type UploadOptions struct {
|
||||
Recursive bool // --recursive: positional arg is a directory; walk + upload each match
|
||||
Glob string // --glob: filename pattern under --recursive (default "*")
|
||||
FromURL string // --from-url: ingest a remote URL via SDK CreateKnowledgeFromURL
|
||||
DryRun bool
|
||||
}
|
||||
|
||||
// UploadService is the narrow SDK surface this command depends on.
|
||||
@@ -85,7 +84,6 @@ Use --recursive --glob to upload a directory tree (see Examples).`,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
if err := validateUploadFlags(opts, args); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -93,17 +91,9 @@ Use --recursive --glob to upload a directory tree (see Examples).`,
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Resolve the SDK client once; dry-run paths take nil and never
|
||||
// dereference it. Hoisting avoids three near-identical
|
||||
// `cli, err := f.Client()` blocks across the dispatch branches.
|
||||
var cli UploadService
|
||||
if !opts.DryRun {
|
||||
sdkCli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
cli = sdkCli
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
switch {
|
||||
@@ -157,13 +147,6 @@ func validateUploadFlags(opts *UploadOptions, args []string) error {
|
||||
// `--name` becomes the FileName hint so the server's "known file extension"
|
||||
// detection upgrades crawl-mode to file-download-mode when appropriate.
|
||||
func runUploadFromURL(ctx context.Context, opts *UploadOptions, jopts *cmdutil.JSONOptions, svc UploadService, kbID string) error {
|
||||
if opts.DryRun {
|
||||
return cmdutil.EmitDryRun(jopts.Enabled(),
|
||||
map[string]string{"from_url": opts.FromURL, "kb_id": kbID, "name": opts.Name},
|
||||
&format.Meta{KBID: kbID},
|
||||
&format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("ingest URL %s into kb %s", opts.FromURL, kbID)})
|
||||
}
|
||||
|
||||
req := sdk.CreateKnowledgeFromURLRequest{
|
||||
URL: opts.FromURL,
|
||||
FileName: opts.Name,
|
||||
@@ -182,20 +165,17 @@ func runUploadFromURL(ctx context.Context, opts *UploadOptions, jopts *cmdutil.J
|
||||
return cmdutil.WrapHTTP(err, "ingest URL %s", opts.FromURL)
|
||||
}
|
||||
|
||||
return printUploadSuccess(k, jopts, kbID, "ingested", "Ingested", opts.FromURL, opts.Name, opts.FromURL)
|
||||
return printUploadSuccess(k, jopts, "Ingested", opts.Name, opts.FromURL)
|
||||
}
|
||||
|
||||
// printUploadSuccess emits the post-upload result envelope (--json path)
|
||||
// or the human checkmark line. Shared by single-file upload and URL ingest;
|
||||
// the verb (upload/ingest), risk-action verb (uploaded/ingested), and the
|
||||
// fallback display source (local path vs source URL) are the only varying
|
||||
// pieces.
|
||||
func printUploadSuccess(k *sdk.Knowledge, jopts *cmdutil.JSONOptions, kbID, riskVerb, humanVerb, source, customName, fallbackDisplay string) error {
|
||||
// printUploadSuccess emits the post-upload result. JSON path is the bare
|
||||
// Knowledge object; human path prints a checkmark line. Shared by single-
|
||||
// file upload and URL ingest; humanVerb varies (uploaded/ingested) and
|
||||
// fallbackDisplay covers the case when the server-recorded file_name is
|
||||
// blank (URL ingest pre-redirect).
|
||||
func printUploadSuccess(k *sdk.Knowledge, jopts *cmdutil.JSONOptions, humanVerb, customName, fallbackDisplay string) error {
|
||||
if jopts.Enabled() {
|
||||
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("%s %s", riskVerb, source)}
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out,
|
||||
format.SuccessWithRisk(k, &format.Meta{KBID: kbID}, risk),
|
||||
jopts.Fields, jopts.JQ)
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, k, jopts.Fields, jopts.JQ)
|
||||
}
|
||||
displayed := customName
|
||||
if displayed == "" {
|
||||
@@ -230,16 +210,9 @@ func validateUploadPath(path string) error {
|
||||
}
|
||||
|
||||
func runUpload(ctx context.Context, opts *UploadOptions, jopts *cmdutil.JSONOptions, svc UploadService, kbID, path string) error {
|
||||
if opts.DryRun {
|
||||
return cmdutil.EmitDryRun(jopts.Enabled(),
|
||||
map[string]string{"file": path, "kb_id": kbID, "name": opts.Name},
|
||||
&format.Meta{KBID: kbID},
|
||||
&format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("upload %s to kb %s", path, kbID)})
|
||||
}
|
||||
|
||||
k, err := svc.CreateKnowledgeFromFile(ctx, kbID, path, nil /*metadata*/, nil /*enableMultimodel*/, opts.Name, uploadChannel)
|
||||
if err != nil {
|
||||
return cmdutil.WrapHTTP(err, "upload %s", path)
|
||||
}
|
||||
return printUploadSuccess(k, jopts, kbID, "uploaded", "Uploaded", path, opts.Name, path)
|
||||
return printUploadSuccess(k, jopts, "Uploaded", opts.Name, path)
|
||||
}
|
||||
|
||||
@@ -63,24 +63,12 @@ func runUploadRecursive(ctx context.Context, opts *UploadOptions, jopts *cmdutil
|
||||
}
|
||||
if len(matches) == 0 {
|
||||
if jopts.Enabled() {
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.Success(
|
||||
recursiveResult{KBID: kbID}, &format.Meta{KBID: kbID}), jopts.Fields, jopts.JQ)
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, recursiveResult{KBID: kbID}, jopts.Fields, jopts.JQ)
|
||||
}
|
||||
fmt.Fprintf(iostreams.IO.Out, "(no files matched %q under %s)\n", opts.Glob, dir)
|
||||
return nil
|
||||
}
|
||||
|
||||
if opts.DryRun {
|
||||
previews := make([]uploadOutcome, 0, len(matches))
|
||||
for _, m := range matches {
|
||||
previews = append(previews, uploadOutcome{Path: m})
|
||||
}
|
||||
return cmdutil.EmitDryRun(jopts.Enabled(),
|
||||
recursiveResult{KBID: kbID, Uploaded: previews},
|
||||
&format.Meta{KBID: kbID},
|
||||
&format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("upload %d file(s) to kb %s", len(matches), kbID)})
|
||||
}
|
||||
|
||||
var uploaded, failed []uploadOutcome
|
||||
var firstFailCode cmdutil.ErrorCode
|
||||
for _, p := range matches {
|
||||
@@ -110,9 +98,7 @@ func runUploadRecursive(ctx context.Context, opts *UploadOptions, jopts *cmdutil
|
||||
|
||||
if jopts.Enabled() {
|
||||
result := recursiveResult{KBID: kbID, Uploaded: uploaded, Failed: failed}
|
||||
risk := &format.Risk{Level: format.RiskWrite, Action: fmt.Sprintf("upload %d file(s) to kb %s", len(matches), kbID)}
|
||||
if err := format.WriteEnvelopeFiltered(iostreams.IO.Out,
|
||||
format.SuccessWithRisk(result, &format.Meta{KBID: kbID}, risk), jopts.Fields, jopts.JQ); err != nil {
|
||||
if err := format.WriteJSONFiltered(iostreams.IO.Out, result, jopts.Fields, jopts.JQ); err != nil {
|
||||
return err
|
||||
}
|
||||
} else {
|
||||
@@ -120,11 +106,10 @@ func runUploadRecursive(ctx context.Context, opts *UploadOptions, jopts *cmdutil
|
||||
}
|
||||
|
||||
if len(failed) > 0 {
|
||||
// Silent on the --json path: the success envelope above already
|
||||
// carries per-file uploaded[]/failed[] detail. Without Silent the
|
||||
// root error handler would write a second Failure envelope on
|
||||
// stdout, corrupting the stream. ExitCode still walks Code so the
|
||||
// typed exit-code-by-class contract is preserved.
|
||||
// Silent on the --json path: the success object above already
|
||||
// carries per-file uploaded[]/failed[] detail; without Silent the
|
||||
// root error handler would print to stderr in addition. ExitCode
|
||||
// still walks Code so the typed exit-code-by-class contract holds.
|
||||
return &cmdutil.Error{
|
||||
Code: firstFailCode,
|
||||
Message: fmt.Sprintf("%d of %d uploads failed", len(failed), len(matches)),
|
||||
|
||||
@@ -157,7 +157,7 @@ func TestUploadRecursive_RejectsNameFlag(t *testing.T) {
|
||||
assert.Contains(t, typed.Message, "--name")
|
||||
}
|
||||
|
||||
func TestUploadRecursive_JSON_Envelope(t *testing.T) {
|
||||
func TestUploadRecursive_JSON_BareObject(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
dir := t.TempDir()
|
||||
mkTree(t, dir, "ok.pdf", "bad.pdf")
|
||||
@@ -178,13 +178,13 @@ func TestUploadRecursive_JSON_Envelope(t *testing.T) {
|
||||
assert.Contains(t, body, `"failed":`)
|
||||
assert.Contains(t, body, `ok.pdf`)
|
||||
assert.Contains(t, body, `bad.pdf`)
|
||||
assert.NotContains(t, body, `"ok":`, "bare output must not carry envelope keys")
|
||||
|
||||
// --json must emit exactly ONE envelope. Per-file "FAIL"/"OK" progress
|
||||
// lines belong on the human path; the typed error is Silent so the root
|
||||
// handler doesn't write a second Failure envelope on top of ours.
|
||||
// --json must emit exactly ONE JSON document. Per-file "FAIL"/"OK"
|
||||
// progress lines belong on the human path; the typed error is Silent so
|
||||
// the root handler doesn't write anything additional to stdout.
|
||||
assert.NotContains(t, body, "FAIL ", "per-file plain lines must not appear under --json")
|
||||
assert.NotContains(t, body, "OK ", "per-file plain lines must not appear under --json")
|
||||
assert.Equal(t, 1, strings.Count(body, `"ok":`), "exactly one envelope on stdout")
|
||||
|
||||
var typed *cmdutil.Error
|
||||
require.ErrorAs(t, err, &typed)
|
||||
@@ -192,14 +192,3 @@ func TestUploadRecursive_JSON_Envelope(t *testing.T) {
|
||||
assert.Equal(t, cmdutil.CodeServerError, typed.Code)
|
||||
}
|
||||
|
||||
func TestUploadRecursive_DryRun(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
dir := t.TempDir()
|
||||
mkTree(t, dir, "a.pdf", "b.pdf")
|
||||
svc := &scriptedUploadSvc{}
|
||||
opts := &UploadOptions{Recursive: true, Glob: "*", DryRun: true}
|
||||
require.NoError(t, runUploadRecursive(context.Background(), opts, nil, svc, "kb_xxx", dir))
|
||||
assert.Len(t, svc.called, 0, "dry-run must not call SDK")
|
||||
got := out.String()
|
||||
assert.Contains(t, got, "would upload 2")
|
||||
}
|
||||
|
||||
@@ -103,10 +103,9 @@ func TestUpload_Success_JSON(t *testing.T) {
|
||||
require.NoError(t, runUpload(context.Background(), opts, &cmdutil.JSONOptions{}, svc, "kb_xxx", path))
|
||||
|
||||
got := out.String()
|
||||
assert.True(t, strings.HasPrefix(got, `{"ok":true`), "envelope should start with ok:true; got %q", got)
|
||||
assert.Contains(t, got, `"id":"doc_77"`)
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(got), `{"id":"doc_77"`), "expected bare Knowledge object; got %q", got)
|
||||
assert.Contains(t, got, `"file_name":"a.md"`)
|
||||
assert.Contains(t, got, `"kb_id":"kb_xxx"`, "_meta.kb_id should carry the resolved kb id")
|
||||
assert.NotContains(t, got, `"ok":`)
|
||||
}
|
||||
|
||||
func TestUpload_HTTPError_500(t *testing.T) {
|
||||
@@ -193,27 +192,16 @@ func TestUploadFromURL_WithName_Passes_AsFileName(t *testing.T) {
|
||||
"--name must be forwarded as FileName (server uses it for file-vs-crawl mode hint)")
|
||||
}
|
||||
|
||||
func TestUploadFromURL_JSON_Envelope(t *testing.T) {
|
||||
func TestUploadFromURL_JSON_BareObject(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeUploadSvc{urlResp: &sdk.Knowledge{ID: "doc_url_3", FileName: "ok.pdf"}}
|
||||
jopts := &cmdutil.JSONOptions{}
|
||||
require.NoError(t, runUploadFromURL(context.Background(),
|
||||
&UploadOptions{FromURL: "https://example.com/ok.pdf"}, jopts, svc, "kb_xxx"))
|
||||
assert.Contains(t, out.String(), `"ok":true`)
|
||||
assert.Contains(t, out.String(), `"id":"doc_url_3"`)
|
||||
assert.Contains(t, out.String(), `"risk":{"level":"write"`)
|
||||
}
|
||||
|
||||
func TestUploadFromURL_DryRun(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeUploadSvc{} // must not be called
|
||||
jopts := &cmdutil.JSONOptions{}
|
||||
opts := &UploadOptions{FromURL: "https://example.com/x.pdf", DryRun: true}
|
||||
require.NoError(t, runUploadFromURL(context.Background(), opts, jopts, svc, "kb_xxx"))
|
||||
got := out.String()
|
||||
assert.Contains(t, got, `"dry_run":true`)
|
||||
assert.Contains(t, got, `"from_url"`)
|
||||
assert.Empty(t, svc.got.urlReq.URL, "SDK call must NOT fire on --dry-run")
|
||||
assert.Contains(t, got, `"id":"doc_url_3"`)
|
||||
assert.NotContains(t, got, `"ok":`)
|
||||
assert.NotContains(t, got, `"risk":`)
|
||||
}
|
||||
|
||||
func TestUploadFromURL_DuplicateURLMaps_resource_already_exists(t *testing.T) {
|
||||
|
||||
+1
-1
@@ -63,7 +63,7 @@ func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions,
|
||||
return cmdutil.WrapHTTP(err, "get document %q", id)
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return format.WriteEnvelopeFiltered(iostreams.IO.Out, format.Success(doc, &format.Meta{KBID: doc.KnowledgeBaseID}), jopts.Fields, jopts.JQ)
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, doc, jopts.Fields, jopts.JQ)
|
||||
}
|
||||
w := iostreams.IO.Out
|
||||
fmt.Fprintf(w, "ID: %s\n", doc.ID)
|
||||
|
||||
@@ -94,14 +94,17 @@ func TestView_Human_OmitsEmptyFields(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestView_JSON_EmitsEnvelope(t *testing.T) {
|
||||
func TestView_JSON_BareObject(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeViewSvc{doc: &sdk.Knowledge{ID: "doc_abc", FileName: "x.txt", KnowledgeBaseID: "kb1"}}
|
||||
if err := runView(context.Background(), &ViewOptions{}, &cmdutil.JSONOptions{}, svc, "doc_abc"); err != nil {
|
||||
t.Fatalf("runView: %v", err)
|
||||
}
|
||||
got := out.String()
|
||||
for _, want := range []string{`"ok":true`, `"id":"doc_abc"`, `"file_name":"x.txt"`, `"knowledge_base_id":"kb1"`} {
|
||||
if strings.Contains(got, `"ok":`) || strings.Contains(got, `"data":`) {
|
||||
t.Errorf("bare output must not carry envelope keys: %q", got)
|
||||
}
|
||||
for _, want := range []string{`"id":"doc_abc"`, `"file_name":"x.txt"`, `"knowledge_base_id":"kb1"`} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Errorf("missing %q in:\n%s", want, got)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user