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:
@@ -18,8 +18,7 @@ import (
|
||||
var sessionDeleteFields = []string{"id", "deleted"}
|
||||
|
||||
type DeleteOptions struct {
|
||||
Yes bool // sourced from the global -y/--yes persistent flag
|
||||
DryRun bool
|
||||
Yes bool // sourced from the global -y/--yes persistent flag
|
||||
}
|
||||
|
||||
// DeleteService is the narrow SDK surface this command depends on.
|
||||
@@ -54,14 +53,10 @@ without the user's explicit go-ahead.`,
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(c *cobra.Command, args []string) error {
|
||||
opts.Yes, _ = c.Flags().GetBool("yes")
|
||||
opts.DryRun = cmdutil.IsDryRun(c)
|
||||
jopts, err := cmdutil.CheckJSONFlags(c)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if opts.DryRun {
|
||||
return runDelete(c.Context(), opts, jopts, nil, f.Prompter(), args[0])
|
||||
}
|
||||
cli, err := f.Client()
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -75,13 +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 {
|
||||
risk := &format.Risk{Level: format.RiskHighRiskWrite, Action: fmt.Sprintf("delete session %s", id)}
|
||||
|
||||
if opts.DryRun {
|
||||
return cmdutil.EmitDryRun(jopts.Enabled(),
|
||||
deleteResult{ID: id, Deleted: false}, nil, risk)
|
||||
}
|
||||
|
||||
if err := cmdutil.ConfirmDestructive(p, opts.Yes, jopts.Enabled(), "session", id); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -91,11 +79,7 @@ func runDelete(ctx context.Context, opts *DeleteOptions, jopts *cmdutil.JSONOpti
|
||||
}
|
||||
|
||||
if jopts.Enabled() {
|
||||
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 session %s\n", id)
|
||||
return nil
|
||||
|
||||
@@ -3,7 +3,6 @@ package sessioncmd
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -82,13 +81,3 @@ func TestDelete_TTY_ConfirmNo(t *testing.T) {
|
||||
assert.Contains(t, errBuf.String(), "Aborted")
|
||||
}
|
||||
|
||||
func TestDelete_DryRun_JSON(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeDeleteSvc{}
|
||||
require.NoError(t, runDelete(context.Background(), &DeleteOptions{DryRun: true}, &cmdutil.JSONOptions{}, svc, &testutil.ConfirmPrompter{}, "s_dry"))
|
||||
body := out.String()
|
||||
assert.True(t, strings.HasPrefix(body, `{"ok":true`))
|
||||
assert.Contains(t, body, `"dry_run":true`)
|
||||
assert.Contains(t, body, `"high-risk-write"`)
|
||||
assert.False(t, svc.called, "dry-run must not call SDK")
|
||||
}
|
||||
|
||||
+3
-21
@@ -46,11 +46,6 @@ type ListService interface {
|
||||
GetSessionsByTenant(ctx context.Context, page, pageSize int) ([]sdk.Session, int, error)
|
||||
}
|
||||
|
||||
// listResult is the typed payload emitted under data.
|
||||
type listResult struct {
|
||||
Items []sdk.Session `json:"items"`
|
||||
}
|
||||
|
||||
// NewCmdList builds `weknora session list`.
|
||||
func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &ListOptions{PageSize: defaultPageSize}
|
||||
@@ -75,7 +70,7 @@ func NewCmdList(f *cmdutil.Factory) *cobra.Command {
|
||||
cmd.Flags().BoolVar(&opts.AllPages, "all-pages", false, "Walk all server pages until exhausted (or --limit hit)")
|
||||
cmd.Flags().StringVar(&opts.Since, "since", "", "Only show sessions updated within `duration` (e.g. 7d, 24h, 30m)")
|
||||
cmdutil.AddJSONFlags(cmd, sessionListFields)
|
||||
aiclient.SetAgentHelp(cmd, "Lists chat sessions. data.{items}; pagination metadata in _meta.{page, page_size, total, has_more}. --all-pages drains every server page in one call (capped by --limit). --since filters client-side after fetch.")
|
||||
aiclient.SetAgentHelp(cmd, "Lists chat sessions as a bare JSON array of Session objects (empty `[]` when none). --all-pages drains every server page in one call (capped by --limit). --since filters client-side after fetch.")
|
||||
return cmd
|
||||
}
|
||||
|
||||
@@ -154,23 +149,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 no longer surfaced; --all-pages drains for callers who need everything
|
||||
|
||||
if jopts.Enabled() {
|
||||
// has_more is suppressed when --since filter is active (server
|
||||
// total ≠ what we returned) or when --all-pages drained the server.
|
||||
meta := &format.Meta{
|
||||
Page: 1,
|
||||
PageSize: opts.PageSize,
|
||||
Total: int64(total),
|
||||
}
|
||||
if since == 0 && !opts.AllPages {
|
||||
meta.HasMore = opts.PageSize < total
|
||||
}
|
||||
return format.WriteEnvelopeFiltered(
|
||||
iostreams.IO.Out,
|
||||
format.Success(listResult{Items: items}, meta),
|
||||
jopts.Fields, jopts.JQ,
|
||||
)
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, items, jopts.Fields, jopts.JQ)
|
||||
}
|
||||
|
||||
if len(items) == 0 {
|
||||
|
||||
@@ -2,7 +2,6 @@ package sessioncmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
@@ -13,7 +12,6 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
@@ -58,7 +56,7 @@ func TestList_Table(t *testing.T) {
|
||||
assert.Equal(t, 30, svc.gotPageSize)
|
||||
}
|
||||
|
||||
func TestList_JSON_WithMeta(t *testing.T) {
|
||||
func TestList_JSON_BareArray(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListService{
|
||||
items: []sdk.Session{
|
||||
@@ -68,41 +66,23 @@ func TestList_JSON_WithMeta(t *testing.T) {
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 10}, &cmdutil.JSONOptions{}, svc))
|
||||
|
||||
var env format.Envelope
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
|
||||
require.True(t, env.OK)
|
||||
// Pagination is server-internal: CLI always asks for page 1 of size --page-size.
|
||||
// CLI always asks for page 1 of size --page-size; pagination is server-internal.
|
||||
assert.Equal(t, 1, svc.gotPage)
|
||||
assert.Equal(t, 10, svc.gotPageSize)
|
||||
// envelope.data.items shaped + paging metadata in _meta
|
||||
body := out.String()
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(body), `[`), "bare array expected; got %q", body)
|
||||
assert.Contains(t, body, `"id":"s_1"`)
|
||||
assert.Contains(t, body, `"items":`)
|
||||
// has_more inferred from page_size < total (10 < 47).
|
||||
assert.Contains(t, body, `"has_more":true`)
|
||||
// pagination metadata lives in _meta now
|
||||
assert.Contains(t, body, `"page":1`)
|
||||
assert.Contains(t, body, `"page_size":10`)
|
||||
assert.Contains(t, body, `"total":47`)
|
||||
assert.NotContains(t, body, `"ok":`)
|
||||
assert.NotContains(t, body, `"_meta":`)
|
||||
assert.NotContains(t, body, `"has_more":`)
|
||||
assert.NotContains(t, body, `"total":`)
|
||||
}
|
||||
|
||||
func TestList_JSON_PageSizeCoversAll_NoHasMore(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListService{
|
||||
items: []sdk.Session{{ID: "s_1"}},
|
||||
total: 1,
|
||||
}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.JSONOptions{}, svc))
|
||||
// page_size (30) ≥ total (1) → has_more must be false (omitempty drops the key)
|
||||
body := out.String()
|
||||
assert.NotContains(t, body, `"has_more":true`)
|
||||
}
|
||||
|
||||
func TestList_NilItems_RendersAsEmptyArray(t *testing.T) {
|
||||
func TestList_NilItems_RendersAsBareEmptyArray(t *testing.T) {
|
||||
out, _ := iostreams.SetForTest(t)
|
||||
svc := &fakeListService{items: nil, total: 0}
|
||||
require.NoError(t, runList(context.Background(), &ListOptions{PageSize: 30}, &cmdutil.JSONOptions{}, svc))
|
||||
assert.Contains(t, out.String(), `"items":[]`)
|
||||
assert.Equal(t, "[]", strings.TrimSpace(out.String()))
|
||||
}
|
||||
|
||||
func TestList_BadPagination(t *testing.T) {
|
||||
@@ -270,8 +250,6 @@ func TestList_AllPages_WalksAllServerPages(t *testing.T) {
|
||||
assert.Equal(t, []int{1, 2, 3}, svc.calls)
|
||||
got := strings.Count(out.String(), `"id":"s_`)
|
||||
assert.Equal(t, 45, got)
|
||||
// --all-pages drained, so has_more should be absent.
|
||||
assert.NotContains(t, out.String(), `"has_more":true`)
|
||||
}
|
||||
|
||||
func TestList_AllPages_WithLimit_StopsAtLimit(t *testing.T) {
|
||||
|
||||
@@ -60,11 +60,7 @@ func runView(ctx context.Context, opts *ViewOptions, jopts *cmdutil.JSONOptions,
|
||||
return cmdutil.WrapHTTP(err, "get session %q", id)
|
||||
}
|
||||
if jopts.Enabled() {
|
||||
return format.WriteEnvelopeFiltered(
|
||||
iostreams.IO.Out,
|
||||
format.Success(s, nil),
|
||||
jopts.Fields, jopts.JQ,
|
||||
)
|
||||
return format.WriteJSONFiltered(iostreams.IO.Out, s, jopts.Fields, jopts.JQ)
|
||||
}
|
||||
w := iostreams.IO.Out
|
||||
fmt.Fprintf(w, "ID: %s\n", s.ID)
|
||||
|
||||
@@ -2,7 +2,6 @@ package sessioncmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -11,7 +10,6 @@ import (
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"github.com/Tencent/WeKnora/cli/internal/cmdutil"
|
||||
"github.com/Tencent/WeKnora/cli/internal/format"
|
||||
"github.com/Tencent/WeKnora/cli/internal/iostreams"
|
||||
sdk "github.com/Tencent/WeKnora/client"
|
||||
)
|
||||
@@ -50,11 +48,9 @@ func TestView_JSON(t *testing.T) {
|
||||
svc := &fakeViewService{s: &sdk.Session{ID: "s_abc", Title: "T", UpdatedAt: "2026-05-12T14:00:00Z"}}
|
||||
require.NoError(t, runView(context.Background(), &ViewOptions{}, &cmdutil.JSONOptions{}, svc, "s_abc"))
|
||||
|
||||
var env format.Envelope
|
||||
require.NoError(t, json.Unmarshal(out.Bytes(), &env))
|
||||
require.True(t, env.OK)
|
||||
body := out.String()
|
||||
assert.Contains(t, body, `"id":"s_abc"`)
|
||||
assert.True(t, strings.HasPrefix(strings.TrimSpace(body), `{"id":"s_abc"`), "bare object expected; got %q", body)
|
||||
assert.NotContains(t, body, `"ok":`)
|
||||
}
|
||||
|
||||
func TestView_NotFound(t *testing.T) {
|
||||
|
||||
Reference in New Issue
Block a user