Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 28 additions & 7 deletions cmd/api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@
PageLimit int
PageDelay int
Format string
JSON bool
JqExpr string
DryRun bool
File string
Expand Down Expand Up @@ -88,6 +89,11 @@
opts.Cmd = cmd
opts.Ctx = cmd.Context()
opts.As = core.Identity(asStr)
format, err := output.StandardFormats.Resolve(opts.Format, cmd.Flags().Changed("format"), opts.JSON)
if err != nil {
return err

Check warning on line 94 in cmd/api/api.go

View check run for this annotation

Codecov / codecov/patch

cmd/api/api.go#L94

Added line #L94 was not covered by tests
}
opts.Format = format
if runF != nil {
return runF(opts)
}
Expand All @@ -103,8 +109,8 @@
cmd.Flags().IntVar(&opts.PageSize, "page-size", 0, "page size (0 = use API default)")
cmd.Flags().IntVar(&opts.PageLimit, "page-limit", 10, "max pages to fetch with --page-all (0 = unlimited)")
cmd.Flags().IntVar(&opts.PageDelay, "page-delay", 200, "delay in ms between pages")
cmd.Flags().StringVar(&opts.Format, "format", "json", "output format: json|ndjson|table|csv")
cmd.Flags().Bool("json", false, "shorthand for --format json")
cmd.Flags().StringVar(&opts.Format, "format", "json", output.StandardFormats.Usage())
cmd.Flags().BoolVar(&opts.JSON, "json", false, "shorthand for --format json")
cmd.Flags().StringVarP(&opts.JqExpr, "jq", "q", "", "jq expression to filter JSON output")
cmd.Flags().BoolVar(&opts.DryRun, "dry-run", false, "print request without executing")
cmd.Flags().StringVar(&opts.File, "file", "", "file to upload as multipart/form-data ([field=]path, supports - for stdin)")
Expand All @@ -116,7 +122,7 @@
return nil, cobra.ShellCompDirectiveNoFileComp
}
cmdutil.RegisterFlagCompletion(cmd, "format", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return []string{"json", "ndjson", "table", "csv"}, cobra.ShellCompDirectiveNoFileComp
return output.StandardFormats.Names(), cobra.ShellCompDirectiveNoFileComp

Check warning on line 125 in cmd/api/api.go

View check run for this annotation

Codecov / codecov/patch

cmd/api/api.go#L125

Added line #L125 was not covered by tests
})
cmdutil.SetRisk(cmd, "write")

Expand Down Expand Up @@ -263,10 +269,7 @@
}

out := f.IOStreams.Out
format, formatOK := output.ParseFormat(opts.Format)
if !formatOK {
fmt.Fprintf(f.IOStreams.ErrOut, "warning: unknown format %q, falling back to json\n", opts.Format)
}
format, _ := output.ParseFormat(opts.Format)

if opts.PageAll {
return apiPaginate(opts.Ctx, ac, request, format, opts.JqExpr, out, f.IOStreams.ErrOut, opts.Cmd.CommandPath(),
Expand Down Expand Up @@ -343,6 +346,24 @@
}

switch format {
case output.FormatPretty:
result, err := ac.PaginateAll(ctx, request, pagOpts)
if err != nil {
return errs.MarkRaw(err)

Check warning on line 352 in cmd/api/api.go

View check run for this annotation

Codecov / codecov/patch

cmd/api/api.go#L352

Added line #L352 was not covered by tests
}
if apiErr := ac.CheckResponse(result, pagOpts.Identity); apiErr != nil {
output.FormatValue(out, result, output.FormatPretty)
return errs.MarkRaw(apiErr)

Check warning on line 356 in cmd/api/api.go

View check run for this annotation

Codecov / codecov/patch

cmd/api/api.go#L355-L356

Added lines #L355 - L356 were not covered by tests
}
scanResult := output.ScanForSafety(commandPath, result, errOut)
if scanResult.Blocked {
return errs.MarkRaw(scanResult.BlockErr)

Check warning on line 360 in cmd/api/api.go

View check run for this annotation

Codecov / codecov/patch

cmd/api/api.go#L360

Added line #L360 was not covered by tests
}
if scanResult.Alert != nil {
output.WriteAlertWarning(errOut, scanResult.Alert)

Check warning on line 363 in cmd/api/api.go

View check run for this annotation

Codecov / codecov/patch

cmd/api/api.go#L363

Added line #L363 was not covered by tests
}
output.FormatValue(out, result, output.FormatPretty)
return nil
case output.FormatNDJSON, output.FormatTable, output.FormatCSV:
pf := output.NewPaginatedFormatter(out, format)
result, hasItems, err := ac.StreamPages(ctx, request, func(items []interface{}) error {
Expand Down
113 changes: 113 additions & 0 deletions cmd/api/api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,42 @@ func TestApiCmd_FlagParsing(t *testing.T) {
}
}

func TestApiCmd_OutputFormatResolution(t *testing.T) {
tests := []struct {
name string
args []string
want string
}{
{name: "json shorthand", args: []string{"--json"}, want: "json"},
{name: "explicit format wins", args: []string{"--format", "table", "--json"}, want: "table"},
{name: "pretty format", args: []string{"--format", "PRETTY"}, want: "pretty"},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
})
var gotOpts *APIOptions
cmd := newTestApiCmd(f, func(opts *APIOptions) error {
gotOpts = opts
return nil
})
args := []string{"GET", "/open-apis/test", "--as", "bot"}
cmd.SetArgs(append(args, tt.args...))
if err := cmd.Execute(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if gotOpts == nil {
t.Fatal("expected options to be captured")
}
if gotOpts.Format != tt.want {
t.Fatalf("format = %q, want %q", gotOpts.Format, tt.want)
}
})
}
}

func TestApiCmd_DryRun(t *testing.T) {
f, stdout, stderr, _ := cmdutil.TestFactory(t, &core.CliConfig{
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
Expand Down Expand Up @@ -169,6 +205,43 @@ func TestApiCmd_BotMode(t *testing.T) {
}
}

func TestApiCmd_PrettyFormatsRealResponse(t *testing.T) {
f, stdout, _, reg := cmdutil.TestFactory(t, &core.CliConfig{
AppID: "test-app-pretty", AppSecret: "test-secret", Brand: core.BrandFeishu,
})
reg.Register(&httpmock.Stub{
URL: "/open-apis/test",
Body: map[string]interface{}{
"code": 0,
"data": map[string]interface{}{
"items": []interface{}{map[string]interface{}{"name": "Alice"}},
},
},
})

cmd := newTestApiCmd(f, nil)
cmd.SetArgs([]string{"GET", "/open-apis/test", "--as", "bot", "--format", "pretty"})
if err := cmd.Execute(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
out := stdout.String()
var got map[string]interface{}
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatalf("pretty output should be valid JSON: %v\n%s", err, out)
}
data, ok := got["data"].(map[string]interface{})
if !ok {
t.Fatalf("pretty output data = %#v", got["data"])
}
items, ok := data["items"].([]interface{})
if !ok || len(items) != 1 {
t.Fatalf("pretty output data.items = %#v", data["items"])
}
if !strings.Contains(out, "\n \"data\": {") || strings.Contains(out, "─") {
t.Fatalf("pretty output should be indented JSON rather than a table, got:\n%s", out)
}
}

func TestApiCmd_MissingArgs(t *testing.T) {
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
Expand Down Expand Up @@ -571,6 +644,46 @@ func TestApiCmd_PageAll_BatchAPI_DefaultJSONEnvelope(t *testing.T) {
}
}

func TestApiCmd_PageAll_PrettyAggregatesIndentedJSON(t *testing.T) {
f, stdout, _, reg := cmdutil.TestFactory(t, &core.CliConfig{
AppID: "test-app-pageall-pretty", AppSecret: "test-secret", Brand: core.BrandFeishu,
})

reg.Register(&httpmock.Stub{
URL: "/open-apis/contact/v3/users",
Body: map[string]interface{}{
"code": 0, "msg": "ok",
"data": map[string]interface{}{
"items": []interface{}{map[string]interface{}{"id": "1"}},
"has_more": false,
},
},
})

cmd := newTestApiCmd(f, nil)
cmd.SetArgs([]string{"GET", "/open-apis/contact/v3/users", "--as", "bot", "--page-all", "--format", "pretty"})
if err := cmd.Execute(); err != nil {
t.Fatalf("unexpected error: %v", err)
}

out := stdout.String()
var got map[string]interface{}
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
t.Fatalf("page-all pretty output should be valid JSON: %v\n%s", err, out)
}
data, ok := got["data"].(map[string]interface{})
if !ok {
t.Fatalf("page-all pretty output data = %#v", got["data"])
}
items, ok := data["items"].([]interface{})
if !ok || len(items) != 1 {
t.Fatalf("page-all pretty output data.items = %#v", data["items"])
}
if !strings.Contains(out, "\n \"data\": {") || strings.Contains(out, "─") {
t.Fatalf("page-all pretty output should be aggregated indented JSON, got:\n%s", out)
}
}

type apiContentSafetyProvider struct {
called bool
path string
Expand Down
30 changes: 27 additions & 3 deletions cmd/auth/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -355,7 +355,31 @@ func TestAuthScopesCmd_FlagParsing(t *testing.T) {
}
}

func TestAuthScopesCmd_JSONFlagForcesJSONFormat(t *testing.T) {
func TestAuthScopesCmd_JSONShorthand(t *testing.T) {
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
})

var gotOpts *ScopesOptions
cmd := NewCmdAuthScopes(f, func(opts *ScopesOptions) error {
gotOpts = opts
return nil
})
cmd.SetArgs([]string{"--json"})
if err := cmd.Execute(); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if gotOpts == nil {
t.Fatal("expected options to be captured")
}
if !gotOpts.JSON || gotOpts.Format != "json" {
t.Fatalf("JSON = %v, format = %q; want true, json", gotOpts.JSON, gotOpts.Format)
}
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.

func TestAuthScopesCmd_ExplicitFormatWinsOverJSONShorthand(t *testing.T) {
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
})
Expand All @@ -376,8 +400,8 @@ func TestAuthScopesCmd_JSONFlagForcesJSONFormat(t *testing.T) {
if !gotOpts.JSON {
t.Error("expected JSON=true")
}
if gotOpts.Format != "json" {
t.Errorf("expected format json, got %s", gotOpts.Format)
if gotOpts.Format != "pretty" {
t.Errorf("expected explicit format pretty, got %s", gotOpts.Format)
}
}

Expand Down
19 changes: 12 additions & 7 deletions cmd/auth/scopes.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,18 +31,23 @@
Short: "Query scopes enabled for the app",
RunE: func(cmd *cobra.Command, args []string) error {
opts.Ctx = cmd.Context()
if opts.JSON {
opts.Format = "json"
format, err := output.JSONPrettyFormats.Resolve(opts.Format, cmd.Flags().Changed("format"), opts.JSON)
if err != nil {
return err

Check warning on line 36 in cmd/auth/scopes.go

View check run for this annotation

Codecov / codecov/patch

cmd/auth/scopes.go#L36

Added line #L36 was not covered by tests
}
opts.Format = format
if runF != nil {
return runF(opts)
}
return authScopesRun(opts)
},
}

cmd.Flags().StringVar(&opts.Format, "format", "json", "output format: json (default) | pretty")
cmd.Flags().BoolVar(&opts.JSON, "json", false, "structured JSON output")
cmd.Flags().StringVar(&opts.Format, "format", "json", output.JSONPrettyFormats.Usage())
cmd.Flags().BoolVar(&opts.JSON, "json", false, "shorthand for --format json")
cmdutil.RegisterFlagCompletion(cmd, "format", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
return output.JSONPrettyFormats.Names(), cobra.ShellCompDirectiveNoFileComp
})

Check warning on line 50 in cmd/auth/scopes.go

View check run for this annotation

Codecov / codecov/patch

cmd/auth/scopes.go#L49-L50

Added lines #L49 - L50 were not covered by tests
cmdutil.SetRisk(cmd, "read")

return cmd
Expand Down Expand Up @@ -75,10 +80,10 @@
"failed to get app scope info: %v", err).WithCause(err)
}
if opts.Format == "pretty" {
fmt.Fprintf(f.IOStreams.ErrOut, "App ID: %s\n", config.AppID)
fmt.Fprintf(f.IOStreams.ErrOut, "Enabled scopes (%d):\n\n", len(appInfo.UserScopes))
fmt.Fprintf(f.IOStreams.Out, "App ID: %s\n", config.AppID)
fmt.Fprintf(f.IOStreams.Out, "Enabled scopes (%d):\n\n", len(appInfo.UserScopes))
for _, s := range appInfo.UserScopes {
fmt.Fprintf(f.IOStreams.ErrOut, " • %s\n", s)
fmt.Fprintf(f.IOStreams.Out, " • %s\n", s)
}
} else {
output.PrintJson(f.IOStreams.Out, map[string]interface{}{
Expand Down
31 changes: 31 additions & 0 deletions cmd/auth/scopes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,11 @@
package auth

import (
"bytes"
"context"
"errors"
"fmt"
"strings"
"testing"

"github.com/larksuite/cli/errs"
Expand All @@ -26,6 +28,35 @@ func stubGetAppInfoErr(t *testing.T, errToReturn error) {
t.Cleanup(func() { getAppInfoFn = prev })
}

func TestAuthScopesRun_PrettyWritesBulletedScopesToStdout(t *testing.T) {
prev := getAppInfoFn
getAppInfoFn = func(ctx context.Context, f *cmdutil.Factory, appId string) (*appInfo, error) {
return &appInfo{UserScopes: []string{"im:message"}}, nil
}
t.Cleanup(func() { getAppInfoFn = prev })

opts := scopesTestFactory(t)
opts.Format = "pretty"
out, ok := opts.Factory.IOStreams.Out.(*bytes.Buffer)
if !ok {
t.Fatalf("stdout type = %T, want *bytes.Buffer", opts.Factory.IOStreams.Out)
}
errOut, ok := opts.Factory.IOStreams.ErrOut.(*bytes.Buffer)
if !ok {
t.Fatalf("stderr type = %T, want *bytes.Buffer", opts.Factory.IOStreams.ErrOut)
}

if err := authScopesRun(opts); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !strings.Contains(out.String(), " • im:message\n") {
t.Fatalf("stdout missing bulleted scope: %q", out.String())
}
if strings.Contains(errOut.String(), "im:message") {
t.Fatalf("scope should remain on stdout, stderr = %q", errOut.String())
}
}

// scopesTestFactory builds a Factory + ScopesOptions pair sufficient to drive
// authScopesRun. Config has a non-empty AppID so we get past the config gate
// and reach the getAppInfoFn call.
Expand Down
1 change: 1 addition & 0 deletions cmd/build.go
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,7 @@ func buildInternal(ctx context.Context, inv cmdutil.InvocationContext, opts ...B
groupRootCommands(rootCmd)

installUnknownSubcommandGuard(rootCmd)
installCobraValidationGuards(rootCmd)
// Bare `lark-cli` in an interactive terminal offers an interactive upgrade
// before printing help; non-bare invocations and non-TTY are unaffected.
installRootUpgradePrompt(f, rootCmd)
Expand Down
Loading
Loading