mirror of
https://github.com/larksuite/cli.git
synced 2026-07-03 22:24:31 +08:00
Compare commits
1 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6b57311b2 |
26
.github/workflows/license-header.yml
vendored
26
.github/workflows/license-header.yml
vendored
@@ -1,26 +0,0 @@
|
||||
name: License Header
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
branches: [main]
|
||||
paths:
|
||||
- "**/*.go"
|
||||
- "**/*.js"
|
||||
- "**/*.py"
|
||||
- .licenserc.yaml
|
||||
- .github/workflows/license-header.yml
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
pull-requests: write
|
||||
|
||||
jobs:
|
||||
header-check:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5.0.1
|
||||
|
||||
- name: Check license headers
|
||||
uses: apache/skywalking-eyes/header@8c96ee223558797cdd9eba82c0919258e1cf2dad
|
||||
with:
|
||||
config: .licenserc.yaml
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -31,7 +31,6 @@ tests/mail/reports/
|
||||
|
||||
/log/
|
||||
|
||||
|
||||
# Generated / test artifacts
|
||||
internal/registry/meta_data.json
|
||||
cmd/api/download.bin
|
||||
|
||||
@@ -27,7 +27,6 @@ linters:
|
||||
- reassign # checks that package variables are not reassigned
|
||||
- unconvert # removes unnecessary type conversions
|
||||
- unused # checks for unused constants, variables, functions and types
|
||||
- depguard # blocks forbidden package imports
|
||||
- forbidigo # forbids specific function calls
|
||||
|
||||
# To enable later after fixing existing issues:
|
||||
@@ -46,7 +45,6 @@ linters:
|
||||
linters:
|
||||
- bodyclose
|
||||
- gocritic
|
||||
- depguard
|
||||
- forbidigo
|
||||
- path-except: (shortcuts/|internal/)
|
||||
linters:
|
||||
@@ -56,56 +54,79 @@ linters:
|
||||
- forbidigo
|
||||
|
||||
settings:
|
||||
depguard:
|
||||
rules:
|
||||
shortcuts-no-vfs:
|
||||
files:
|
||||
- "**/shortcuts/**"
|
||||
deny:
|
||||
- pkg: "github.com/larksuite/cli/internal/vfs"
|
||||
desc: >-
|
||||
shortcuts must not import internal/vfs directly.
|
||||
Use runtime.FileIO() for file operations or runtime.ValidatePath() for path validation.
|
||||
- pkg: "github.com/larksuite/cli/internal/vfs/localfileio"
|
||||
desc: >-
|
||||
shortcuts must not import internal/vfs/localfileio directly.
|
||||
Use runtime.FileIO() for file operations or runtime.ValidatePath() for path validation.
|
||||
forbidigo:
|
||||
forbid:
|
||||
# ── os: already wrapped in internal/vfs ──
|
||||
- pattern: os\.(Stat|Lstat|Open|OpenFile|Rename|ReadFile|WriteFile|Getwd|UserHomeDir|ReadDir)\b
|
||||
msg: "use the corresponding vfs.Xxx() from internal/vfs"
|
||||
- pattern: os\.(Create|CreateTemp|MkdirTemp)\b
|
||||
# ── Filesystem operations: use internal/vfs instead ──
|
||||
- pattern: os\.Stat\b
|
||||
msg: "use vfs.Stat() from internal/vfs"
|
||||
- pattern: os\.Lstat\b
|
||||
msg: "use vfs.Lstat() from internal/vfs"
|
||||
- pattern: os\.Open\b
|
||||
msg: "use vfs.Open() from internal/vfs"
|
||||
- pattern: os\.OpenFile\b
|
||||
msg: "use vfs.OpenFile() from internal/vfs"
|
||||
- pattern: os\.Create\b
|
||||
msg: "use vfs.OpenFile() from internal/vfs"
|
||||
- pattern: os\.CreateTemp\b
|
||||
msg: >-
|
||||
internal/: use vfs.CreateTemp() or vfs.OpenFile().
|
||||
shortcuts/: avoid temp files — use io.Reader streaming or in-memory buffers.
|
||||
- pattern: os\.Mkdir(All)?\b
|
||||
internal/: use vfs.CreateTemp() from internal/vfs.
|
||||
shortcuts/: avoid temp files entirely — use io.Reader streaming or in-memory buffers instead.
|
||||
- pattern: os\.Mkdir\b
|
||||
msg: "use vfs.MkdirAll() from internal/vfs"
|
||||
- pattern: os\.MkdirAll\b
|
||||
msg: "use vfs.MkdirAll() from internal/vfs"
|
||||
- pattern: os\.Remove\b
|
||||
msg: >-
|
||||
internal/: use vfs.Remove() from internal/vfs.
|
||||
shortcuts/: avoid temp files — use io.Reader streaming or in-memory buffers.
|
||||
shortcuts/: avoid temp files entirely — use io.Reader streaming or in-memory buffers instead.
|
||||
- pattern: os\.RemoveAll\b
|
||||
msg: >-
|
||||
internal/: add RemoveAll to internal/vfs/fs.go first, then use vfs.RemoveAll().
|
||||
shortcuts/: avoid temp files — use io.Reader streaming or in-memory buffers.
|
||||
# ── os: not yet in vfs — add to vfs/fs.go first ──
|
||||
- pattern: os\.(Chdir|Chmod|Chown|Lchown|Chtimes|CopyFS|DirFS|Link|Symlink|Readlink|Truncate|SameFile)\b
|
||||
msg: "add this function to internal/vfs/fs.go first, then use vfs.Xxx()"
|
||||
# ── os: IO streams ──
|
||||
- pattern: os\.Std(in|out|err)\b
|
||||
msg: "use IOStreams (In/Out/ErrOut) instead of os.Stdin/Stdout/Stderr"
|
||||
# ── os: process ──
|
||||
shortcuts/: avoid temp files entirely — use io.Reader streaming or in-memory buffers instead.
|
||||
- pattern: os\.Rename\b
|
||||
msg: "use vfs.Rename() from internal/vfs"
|
||||
- pattern: os\.ReadFile\b
|
||||
msg: "use vfs.ReadFile() from internal/vfs"
|
||||
- pattern: os\.WriteFile\b
|
||||
msg: "use vfs.WriteFile() from internal/vfs"
|
||||
- pattern: os\.ReadDir\b
|
||||
msg: "add ReadDir to internal/vfs/fs.go first, then use vfs.ReadDir()"
|
||||
- pattern: os\.Getwd\b
|
||||
msg: "use vfs.Getwd() from internal/vfs"
|
||||
- pattern: os\.Chdir\b
|
||||
msg: "add Chdir to internal/vfs/fs.go first, then use vfs.Chdir()"
|
||||
- pattern: os\.UserHomeDir\b
|
||||
msg: "use vfs.UserHomeDir() from internal/vfs"
|
||||
- pattern: os\.Chmod\b
|
||||
msg: "add Chmod to internal/vfs/fs.go first, then use vfs.Chmod()"
|
||||
- pattern: os\.Chown\b
|
||||
msg: "add Chown to internal/vfs/fs.go first, then use vfs.Chown()"
|
||||
- pattern: os\.Lchown\b
|
||||
msg: "add Lchown to internal/vfs/fs.go first, then use vfs.Lchown()"
|
||||
- pattern: os\.Link\b
|
||||
msg: "add Link to internal/vfs/fs.go first, then use vfs.Link()"
|
||||
- pattern: os\.Symlink\b
|
||||
msg: "add Symlink to internal/vfs/fs.go first, then use vfs.Symlink()"
|
||||
- pattern: os\.Readlink\b
|
||||
msg: "add Readlink to internal/vfs/fs.go first, then use vfs.Readlink()"
|
||||
- pattern: os\.Truncate\b
|
||||
msg: "add Truncate to internal/vfs/fs.go first, then use vfs.Truncate()"
|
||||
- pattern: os\.DirFS\b
|
||||
msg: "add DirFS to internal/vfs/fs.go first, then use vfs.DirFS()"
|
||||
- pattern: os\.SameFile\b
|
||||
msg: "add SameFile to internal/vfs/fs.go first, then use vfs.SameFile()"
|
||||
# ── IO streams: use IOStreams from cmdutil instead ──
|
||||
- pattern: os\.Stdin\b
|
||||
msg: "use IOStreams.In instead of os.Stdin"
|
||||
- pattern: os\.Stdout\b
|
||||
msg: "use IOStreams.Out instead of os.Stdout"
|
||||
- pattern: os\.Stderr\b
|
||||
msg: "use IOStreams.ErrOut instead of os.Stderr"
|
||||
# ── Process-level rules ──
|
||||
- pattern: os\.Exit\b
|
||||
msg: >-
|
||||
Do not use os.Exit in shortcuts/. Return an error instead and let
|
||||
the caller (cmd layer) decide how to terminate.
|
||||
# ── filepath: functions that access the filesystem ──
|
||||
- pattern: filepath\.(EvalSymlinks|Walk|WalkDir|Glob|Abs)\b
|
||||
msg: >-
|
||||
These filepath functions access the filesystem directly.
|
||||
internal/: use vfs helpers or localfileio path validation.
|
||||
shortcuts/: use runtime.ValidatePath() or runtime.FileIO().
|
||||
analyze-types: true
|
||||
gocritic:
|
||||
disabled-checks:
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
header:
|
||||
license:
|
||||
content: |
|
||||
Copyright (c) [year] Lark Technologies Pte. Ltd.
|
||||
SPDX-License-Identifier: MIT
|
||||
copyright-year: "2026"
|
||||
|
||||
paths:
|
||||
- '**/*.go'
|
||||
- '**/*.js'
|
||||
- '**/*.py'
|
||||
|
||||
paths-ignore:
|
||||
- '**/testdata/**'
|
||||
|
||||
comment: on-failure
|
||||
66
CHANGELOG.md
66
CHANGELOG.md
@@ -2,71 +2,6 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [v1.0.8] - 2026-04-10
|
||||
|
||||
### Features
|
||||
|
||||
- Add `update` command with self-update, verification, and rollback (#391)
|
||||
- Add `--file` flag for multipart/form-data file uploads (#395)
|
||||
- Support file comment reply reactions (#380)
|
||||
- **base**: Add `+dashboard-arrange` command for auto-arranging dashboard blocks layout and `text` block type with Markdown support (#388)
|
||||
- **base**: Add record batch `+add` / `+set` shortcuts (#277)
|
||||
- **base**: Add `+record-search` for keyword-based record search (#328)
|
||||
- **base**: Add view visible fields `+get` / `+set` shortcuts (#326)
|
||||
- **base**: Add record field filters (#327)
|
||||
- **base**: Optimize workflow skills (#345)
|
||||
- **calendar**: Add room find workflow (#403)
|
||||
- **mail**: Add `--page-token` and `--page-size` to mail `+triage` (#301)
|
||||
- **whiteboard**: Add `+query` shortcut and enhance `+update` with Mermaid/PlantUML support (#382)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- Improve error hints for sandbox and initialization issues (#384)
|
||||
- Fix markdown line breaks support (#338)
|
||||
- Return raw base field and view responses (#378)
|
||||
- **base**: Return raw table list response and clarify sort help (#393)
|
||||
- **calendar**: Add default video meeting to `+create` (#383)
|
||||
- **mail**: Replace `os.Exit` with graceful shutdown in mail watch (#350)
|
||||
|
||||
### Documentation
|
||||
|
||||
- **base**: Document Base attachment download via docs `+media-download` (#404)
|
||||
- Reorganize lark-base skill guidance (#374)
|
||||
|
||||
## [v1.0.7] - 2026-04-09
|
||||
|
||||
### Features
|
||||
|
||||
- Auto-grant current user access for bot-created docs, sheets, imports, and uploads (#360)
|
||||
- **mail**: Add `send_as` alias support, mailbox/sender discovery APIs, and mail rules API
|
||||
- **vc**: Extract note doc tokens from calendar event relation API (#333)
|
||||
- **wiki**: Add wiki node create shortcut (#320)
|
||||
- **sheets**: Add `+write-image` shortcut (#343)
|
||||
- **docs**: Add media-preview shortcut (#334)
|
||||
- **docs**: Add support for additional search filters (#353)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **api**: Support stdin and quoted JSON inputs on Windows (#367)
|
||||
- **doc**: Post-process `docs +fetch` output to improve round-trip fidelity (#214)
|
||||
- **run**: Add missing binary check for lark-cli execution (#362)
|
||||
- **config**: Validate appId and appSecret keychain key consistency (#295)
|
||||
|
||||
### Refactor
|
||||
|
||||
- Route base import guidance to drive `+import` (#368)
|
||||
- Migrate mail shortcuts to FileIO (#356)
|
||||
- Migrate drive/doc/sheets shortcuts to FileIO (#339)
|
||||
- Migrate base shortcuts to FileIO (#347)
|
||||
|
||||
### Documentation
|
||||
|
||||
- **lark-doc**: Document advanced boolean and intitle search syntax for AI agents (#210)
|
||||
|
||||
### Chore
|
||||
|
||||
- Add depguard and forbidigo rules to guide FileIO adoption (#342)
|
||||
|
||||
## [v1.0.6] - 2026-04-08
|
||||
|
||||
### Features
|
||||
@@ -287,7 +222,6 @@ Bundled AI agent skills for intelligent assistance:
|
||||
- Bilingual documentation (English & Chinese).
|
||||
- CI/CD pipelines: linting, testing, coverage reporting, and automated releases.
|
||||
|
||||
[v1.0.7]: https://github.com/larksuite/cli/releases/tag/v1.0.7
|
||||
[v1.0.6]: https://github.com/larksuite/cli/releases/tag/v1.0.6
|
||||
[v1.0.5]: https://github.com/larksuite/cli/releases/tag/v1.0.5
|
||||
[v1.0.4]: https://github.com/larksuite/cli/releases/tag/v1.0.4
|
||||
|
||||
102
cmd/api/api.go
102
cmd/api/api.go
@@ -5,6 +5,7 @@ package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
@@ -41,7 +42,17 @@ type APIOptions struct {
|
||||
Format string
|
||||
JqExpr string
|
||||
DryRun bool
|
||||
File string
|
||||
}
|
||||
|
||||
func parseJsonOpt(input, label string) (map[string]interface{}, error) {
|
||||
if input == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var result map[string]interface{}
|
||||
if err := json.Unmarshal([]byte(input), &result); err != nil {
|
||||
return nil, output.ErrValidation("%s invalid format, expected JSON object", label)
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
var urlPrefixRe = regexp.MustCompile(`https?://[^/]+(/open-apis/.+)`)
|
||||
@@ -77,8 +88,8 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*APIOptions) error) *cobra.Command
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVar(&opts.Params, "params", "", "query parameters JSON (supports - for stdin)")
|
||||
cmd.Flags().StringVar(&opts.Data, "data", "", "request body JSON (supports - for stdin)")
|
||||
cmd.Flags().StringVar(&opts.Params, "params", "", "query parameters JSON")
|
||||
cmd.Flags().StringVar(&opts.Data, "data", "", "request body JSON")
|
||||
cmd.Flags().StringVar(&asStr, "as", "auto", "identity type: user | bot | auto (default)")
|
||||
cmd.Flags().StringVarP(&opts.Output, "output", "o", "", "output file path for binary responses")
|
||||
cmd.Flags().BoolVar(&opts.PageAll, "page-all", false, "automatically paginate through all pages")
|
||||
@@ -88,7 +99,6 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*APIOptions) error) *cobra.Command
|
||||
cmd.Flags().StringVar(&opts.Format, "format", "json", "output format: json|ndjson|table|csv")
|
||||
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)")
|
||||
|
||||
cmd.ValidArgsFunction = func(_ *cobra.Command, args []string, _ string) ([]string, cobra.ShellCompDirective) {
|
||||
if len(args) == 0 {
|
||||
@@ -107,24 +117,20 @@ func NewCmdApi(f *cmdutil.Factory, runF func(*APIOptions) error) *cobra.Command
|
||||
}
|
||||
|
||||
// buildAPIRequest validates flags and builds a RawApiRequest.
|
||||
// When dryRun is true and a file is provided, file reading is skipped and
|
||||
// FileUploadMeta is returned instead so the caller can render dry-run output.
|
||||
func buildAPIRequest(opts *APIOptions) (client.RawApiRequest, *cmdutil.FileUploadMeta, error) {
|
||||
stdin := opts.Factory.IOStreams.In
|
||||
|
||||
// Validate --file mutual exclusions first.
|
||||
if err := cmdutil.ValidateFileFlag(opts.File, opts.Params, opts.Data, opts.Output, opts.PageAll, opts.Method); err != nil {
|
||||
return client.RawApiRequest{}, nil, err
|
||||
}
|
||||
|
||||
// stdin conflict: --params and --data cannot both read from stdin, regardless of --file.
|
||||
if opts.Params == "-" && opts.Data == "-" {
|
||||
return client.RawApiRequest{}, nil, output.ErrValidation("--params and --data cannot both read from stdin (-)")
|
||||
}
|
||||
|
||||
params, err := cmdutil.ParseJSONMap(opts.Params, "--params", stdin)
|
||||
func buildAPIRequest(opts *APIOptions) (client.RawApiRequest, error) {
|
||||
params, err := parseJsonOpt(opts.Params, "--params")
|
||||
if err != nil {
|
||||
return client.RawApiRequest{}, nil, err
|
||||
return client.RawApiRequest{}, err
|
||||
}
|
||||
if params == nil {
|
||||
params = map[string]interface{}{}
|
||||
}
|
||||
var data interface{}
|
||||
if opts.Data != "" {
|
||||
data, err = parseJsonOpt(opts.Data, "--data")
|
||||
if err != nil {
|
||||
return client.RawApiRequest{}, err
|
||||
}
|
||||
}
|
||||
if opts.PageSize > 0 {
|
||||
params["page_size"] = opts.PageSize
|
||||
@@ -134,53 +140,14 @@ func buildAPIRequest(opts *APIOptions) (client.RawApiRequest, *cmdutil.FileUploa
|
||||
Method: opts.Method,
|
||||
URL: normalisePath(opts.Path),
|
||||
Params: params,
|
||||
Data: data,
|
||||
As: opts.As,
|
||||
}
|
||||
|
||||
if opts.File != "" {
|
||||
// File upload path: build formdata.
|
||||
fieldName, filePath, isStdin := cmdutil.ParseFileFlag(opts.File, "file")
|
||||
|
||||
// Parse --data as JSON map for form fields (not as body).
|
||||
var dataFields any
|
||||
if opts.Data != "" {
|
||||
dataFields, err = cmdutil.ParseOptionalBody(opts.Method, opts.Data, stdin)
|
||||
if err != nil {
|
||||
return client.RawApiRequest{}, nil, err
|
||||
}
|
||||
if _, ok := dataFields.(map[string]any); !ok {
|
||||
return client.RawApiRequest{}, nil, output.ErrValidation("--data must be a JSON object when used with --file")
|
||||
}
|
||||
}
|
||||
|
||||
if opts.DryRun {
|
||||
return request, &cmdutil.FileUploadMeta{
|
||||
FieldName: fieldName, FilePath: filePath, FormFields: dataFields,
|
||||
}, nil
|
||||
}
|
||||
|
||||
fd, err := cmdutil.BuildFormdata(
|
||||
opts.Factory.ResolveFileIO(opts.Ctx),
|
||||
fieldName, filePath, isStdin, stdin, dataFields,
|
||||
)
|
||||
if err != nil {
|
||||
return client.RawApiRequest{}, nil, err
|
||||
}
|
||||
request.Data = fd
|
||||
request.ExtraOpts = append(request.ExtraOpts, larkcore.WithFileUpload())
|
||||
} else {
|
||||
// Normal path: JSON body.
|
||||
data, err := cmdutil.ParseOptionalBody(opts.Method, opts.Data, stdin)
|
||||
if err != nil {
|
||||
return client.RawApiRequest{}, nil, err
|
||||
}
|
||||
request.Data = data
|
||||
if opts.Output != "" {
|
||||
request.ExtraOpts = append(request.ExtraOpts, larkcore.WithFileDownload())
|
||||
}
|
||||
// WithFileDownload tells the SDK to skip CodeError parsing on 200 OK.
|
||||
if opts.Output != "" {
|
||||
request.ExtraOpts = append(request.ExtraOpts, larkcore.WithFileDownload())
|
||||
}
|
||||
|
||||
return request, nil, nil
|
||||
return request, nil
|
||||
}
|
||||
|
||||
func apiRun(opts *APIOptions) error {
|
||||
@@ -198,7 +165,7 @@ func apiRun(opts *APIOptions) error {
|
||||
return err
|
||||
}
|
||||
|
||||
request, fileMeta, err := buildAPIRequest(opts)
|
||||
request, err := buildAPIRequest(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -209,9 +176,6 @@ func apiRun(opts *APIOptions) error {
|
||||
}
|
||||
|
||||
if opts.DryRun {
|
||||
if fileMeta != nil {
|
||||
return cmdutil.PrintDryRunWithFile(f.IOStreams.Out, request, config, opts.Format, fileMeta.FieldName, fileMeta.FilePath, fileMeta.FormFields)
|
||||
}
|
||||
return apiDryRun(f, request, config, opts.Format)
|
||||
}
|
||||
// Identity info is now included in the JSON envelope; skip stderr printing.
|
||||
|
||||
@@ -5,7 +5,6 @@ package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"os"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -200,22 +199,6 @@ func TestApiCmd_PageLimitDefault(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestApiCmd_ParamsAndDataBothStdinConflict(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
|
||||
})
|
||||
|
||||
cmd := NewCmdApi(f, nil)
|
||||
cmd.SetArgs([]string{"POST", "/open-apis/test", "--as", "bot", "--params", "-", "--data", "-"})
|
||||
err := cmd.Execute()
|
||||
if err == nil {
|
||||
t.Fatal("expected error when both --params and --data use stdin")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "cannot both read from stdin") {
|
||||
t.Errorf("expected stdin conflict error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApiCmd_OutputAndPageAllConflict(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
|
||||
@@ -707,98 +690,3 @@ func TestApiCmd_MethodUppercase(t *testing.T) {
|
||||
t.Errorf("expected method POST (uppercased), got %s", gotOpts.Method)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApiCmd_FileFlagParsing(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
|
||||
})
|
||||
var gotOpts *APIOptions
|
||||
cmd := NewCmdApi(f, func(opts *APIOptions) error {
|
||||
gotOpts = opts
|
||||
return nil
|
||||
})
|
||||
cmd.SetArgs([]string{"POST", "/open-apis/test", "--file", "image=photo.jpg", "--data", `{"image_type":"message"}`})
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if gotOpts.File != "image=photo.jpg" {
|
||||
t.Errorf("expected File = %q, got %q", "image=photo.jpg", gotOpts.File)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApiCmd_FileAndOutputConflict(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
|
||||
})
|
||||
cmd := NewCmdApi(f, func(opts *APIOptions) error {
|
||||
return apiRun(opts)
|
||||
})
|
||||
cmd.SetArgs([]string{"POST", "/open-apis/test", "--as", "bot", "--file", "photo.jpg", "--output", "out.json"})
|
||||
err := cmd.Execute()
|
||||
if err == nil {
|
||||
t.Fatal("expected error for --file with --output")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "mutually exclusive") {
|
||||
t.Errorf("expected mutual exclusion error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApiCmd_FileWithGET(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
|
||||
})
|
||||
cmd := NewCmdApi(f, func(opts *APIOptions) error {
|
||||
return apiRun(opts)
|
||||
})
|
||||
cmd.SetArgs([]string{"GET", "/open-apis/test", "--as", "bot", "--file", "photo.jpg"})
|
||||
err := cmd.Execute()
|
||||
if err == nil {
|
||||
t.Fatal("expected error for --file with GET")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "requires POST") {
|
||||
t.Errorf("expected method error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApiCmd_FileStdinConflictWithData(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
|
||||
})
|
||||
cmd := NewCmdApi(f, func(opts *APIOptions) error {
|
||||
return apiRun(opts)
|
||||
})
|
||||
cmd.SetArgs([]string{"POST", "/open-apis/test", "--as", "bot", "--file", "-", "--data", "-"})
|
||||
err := cmd.Execute()
|
||||
if err == nil {
|
||||
t.Fatal("expected error for --file stdin with --data stdin")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "cannot both read from stdin") {
|
||||
t.Errorf("expected stdin conflict error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestApiCmd_DryRunWithFile(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
tmpFile := tmpDir + "/test.jpg"
|
||||
if err := os.WriteFile(tmpFile, []byte("fake-image"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, &core.CliConfig{
|
||||
AppID: "test-app", AppSecret: "test-secret", Brand: core.BrandFeishu,
|
||||
})
|
||||
cmd := NewCmdApi(f, nil)
|
||||
cmd.SetArgs([]string{"POST", "/open-apis/im/v1/images", "--file", "image=" + tmpFile, "--data", `{"image_type":"message"}`, "--dry-run", "--as", "bot"})
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, "image") {
|
||||
t.Errorf("expected dry-run output to mention file field, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "Dry Run") {
|
||||
t.Errorf("expected dry-run header, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -134,7 +134,18 @@ func authLoginRun(opts *LoginOptions) error {
|
||||
// Expand --domain all to all available domains (from_meta projects + shortcut services)
|
||||
for _, d := range selectedDomains {
|
||||
if strings.EqualFold(d, "all") {
|
||||
selectedDomains = sortedKnownDomains()
|
||||
domainSet := make(map[string]bool)
|
||||
for _, p := range registry.ListFromMetaProjects() {
|
||||
domainSet[p] = true
|
||||
}
|
||||
for _, sc := range shortcuts.AllShortcuts() {
|
||||
domainSet[sc.Service] = true
|
||||
}
|
||||
selectedDomains = make([]string, 0, len(domainSet))
|
||||
for d := range domainSet {
|
||||
selectedDomains = append(selectedDomains, d)
|
||||
}
|
||||
sort.Strings(selectedDomains)
|
||||
break
|
||||
}
|
||||
}
|
||||
@@ -440,8 +451,6 @@ func findProfileByName(multi *core.MultiAppConfig, profileName string) *core.App
|
||||
|
||||
// collectScopesForDomains collects API scopes (from from_meta projects) and
|
||||
// shortcut scopes for the given domain names.
|
||||
// Domains with auth_domain children are automatically expanded to include
|
||||
// their children's scopes.
|
||||
func collectScopesForDomains(domains []string, identity string) []string {
|
||||
scopeSet := make(map[string]bool)
|
||||
|
||||
@@ -450,16 +459,11 @@ func collectScopesForDomains(domains []string, identity string) []string {
|
||||
scopeSet[s] = true
|
||||
}
|
||||
|
||||
// 2. Expand domains: include auth_domain children
|
||||
// 2. Shortcut scopes matching by Service (only include shortcuts supporting the identity)
|
||||
domainSet := make(map[string]bool, len(domains))
|
||||
for _, d := range domains {
|
||||
domainSet[d] = true
|
||||
for _, child := range registry.GetAuthChildren(d) {
|
||||
domainSet[child] = true
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Shortcut scopes matching by Service (only include shortcuts supporting the identity)
|
||||
for _, sc := range shortcuts.AllShortcuts() {
|
||||
if domainSet[sc.Service] && shortcutSupportsIdentity(sc, identity) {
|
||||
for _, s := range sc.ScopesForIdentity(identity) {
|
||||
@@ -468,7 +472,7 @@ func collectScopesForDomains(domains []string, identity string) []string {
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Deduplicate and sort
|
||||
// 3. Deduplicate and sort
|
||||
result := make([]string, 0, len(scopeSet))
|
||||
for s := range scopeSet {
|
||||
result = append(result, s)
|
||||
@@ -477,20 +481,14 @@ func collectScopesForDomains(domains []string, identity string) []string {
|
||||
return result
|
||||
}
|
||||
|
||||
// allKnownDomains returns all valid auth domain names (from_meta projects +
|
||||
// shortcut services), excluding domains that have auth_domain set (they are
|
||||
// folded into their parent domain).
|
||||
// allKnownDomains returns all valid domain names (from_meta projects + shortcut services).
|
||||
func allKnownDomains() map[string]bool {
|
||||
domains := make(map[string]bool)
|
||||
for _, p := range registry.ListFromMetaProjects() {
|
||||
if !registry.HasAuthDomain(p) {
|
||||
domains[p] = true
|
||||
}
|
||||
domains[p] = true
|
||||
}
|
||||
for _, sc := range shortcuts.AllShortcuts() {
|
||||
if !registry.HasAuthDomain(sc.Service) {
|
||||
domains[sc.Service] = true
|
||||
}
|
||||
domains[sc.Service] = true
|
||||
}
|
||||
return domains
|
||||
}
|
||||
|
||||
@@ -34,12 +34,8 @@ func getDomainMetadata(lang string) []domainMeta {
|
||||
seen := make(map[string]bool)
|
||||
var domains []domainMeta
|
||||
|
||||
// 1. Domains from from_meta projects (skip domains with auth_domain)
|
||||
// 1. Domains from from_meta projects
|
||||
for _, project := range registry.ListFromMetaProjects() {
|
||||
if registry.HasAuthDomain(project) {
|
||||
seen[project] = true
|
||||
continue
|
||||
}
|
||||
dm := buildDomainMeta(project, lang)
|
||||
domains = append(domains, dm)
|
||||
seen[project] = true
|
||||
@@ -56,14 +52,13 @@ func getDomainMetadata(lang string) []domainMeta {
|
||||
}
|
||||
|
||||
// 3. Auto-discover remaining shortcut services that are listed as shortcut-only domains
|
||||
// (skip domains with auth_domain — they are folded into their parent)
|
||||
shortcutOnlySet := make(map[string]bool)
|
||||
for _, n := range shortcutOnlyNames {
|
||||
shortcutOnlySet[n] = true
|
||||
}
|
||||
for _, sc := range shortcuts.AllShortcuts() {
|
||||
if !seen[sc.Service] {
|
||||
if shortcutOnlySet[sc.Service] && !registry.HasAuthDomain(sc.Service) {
|
||||
if shortcutOnlySet[sc.Service] {
|
||||
dm := buildDomainMeta(sc.Service, lang)
|
||||
domains = append(domains, dm)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package auth
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package auth
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package auth
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package auth
|
||||
|
||||
import (
|
||||
|
||||
@@ -903,37 +903,3 @@ func TestGetDomainMetadata_ExcludesEvent(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllKnownDomains_ExcludesAuthDomainChildren(t *testing.T) {
|
||||
domains := allKnownDomains()
|
||||
if domains["whiteboard"] {
|
||||
t.Error("whiteboard should not appear in known auth domains (it has auth_domain=docs)")
|
||||
}
|
||||
if !domains["docs"] {
|
||||
t.Error("docs should still be a known auth domain")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCollectScopesForDomains_ExpandsAuthDomainChildren(t *testing.T) {
|
||||
scopes := collectScopesForDomains([]string{"docs"}, "user")
|
||||
// docs domain should include whiteboard shortcut scopes (board:whiteboard:*)
|
||||
found := false
|
||||
for _, s := range scopes {
|
||||
if strings.HasPrefix(s, "board:whiteboard:") {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Error("collectScopesForDomains([docs]) should include whiteboard scopes (board:whiteboard:*)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetDomainMetadata_ExcludesAuthDomainChildren(t *testing.T) {
|
||||
domains := getDomainMetadata("zh")
|
||||
for _, dm := range domains {
|
||||
if dm.Name == "whiteboard" {
|
||||
t.Error("whiteboard should not appear in interactive domain list (has auth_domain=docs)")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,203 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/registry"
|
||||
"github.com/larksuite/cli/shortcuts"
|
||||
shortcutTypes "github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// ── Data types ────────────────────────────────────────────────────────
|
||||
|
||||
type diagMethodEntry struct {
|
||||
Domain string `json:"domain"`
|
||||
Type string `json:"type"` // "api" or "shortcut"
|
||||
Method string `json:"method"` // "calendar.calendars.search" or "+agenda"
|
||||
Scope string `json:"scope"` // minimum-privilege scope
|
||||
Identity []string `json:"identity"` // ["user"], ["bot"], or ["user","bot"]
|
||||
}
|
||||
|
||||
type diagScopeInfo struct {
|
||||
Scope string `json:"scope"`
|
||||
Recommend bool `json:"recommend"`
|
||||
InPriority bool `json:"in_priority"`
|
||||
}
|
||||
|
||||
type diagOutput struct {
|
||||
Methods []diagMethodEntry `json:"methods"`
|
||||
Scopes []diagScopeInfo `json:"scopes"`
|
||||
}
|
||||
|
||||
// ── Core logic ────────────────────────────────────────────────────────
|
||||
|
||||
// diagAllKnownDomains returns sorted, deduplicated domain names from both
|
||||
// from_meta projects and shortcuts.
|
||||
func diagAllKnownDomains() []string {
|
||||
seen := make(map[string]bool)
|
||||
for _, p := range registry.ListFromMetaProjects() {
|
||||
seen[p] = true
|
||||
}
|
||||
for _, s := range shortcuts.AllShortcuts() {
|
||||
if s.Service != "" {
|
||||
seen[s.Service] = true
|
||||
}
|
||||
}
|
||||
result := make([]string, 0, len(seen))
|
||||
for d := range seen {
|
||||
result = append(result, d)
|
||||
}
|
||||
sort.Strings(result)
|
||||
return result
|
||||
}
|
||||
|
||||
// methodKey uniquely identifies a method+scope pair for merging identities.
|
||||
type methodKey struct {
|
||||
domain string
|
||||
typ string
|
||||
method string
|
||||
scope string
|
||||
}
|
||||
|
||||
// diagBuild builds the full output: flat methods list (merged identities) + scopes.
|
||||
func diagBuild(domains []string) diagOutput {
|
||||
recommend := registry.LoadAutoApproveSet()
|
||||
identities := []string{"user", "bot"}
|
||||
|
||||
merged := make(map[methodKey]*diagMethodEntry)
|
||||
allSC := shortcuts.AllShortcuts()
|
||||
|
||||
for _, domain := range domains {
|
||||
for _, identity := range identities {
|
||||
for _, ce := range registry.CollectCommandScopes([]string{domain}, identity) {
|
||||
for _, scope := range ce.Scopes {
|
||||
method := domain + "." + strings.ReplaceAll(ce.Command, " ", ".")
|
||||
k := methodKey{domain, "api", method, scope}
|
||||
if e, ok := merged[k]; ok {
|
||||
e.Identity = appendUniq(e.Identity, identity)
|
||||
} else {
|
||||
merged[k] = &diagMethodEntry{
|
||||
Domain: domain, Type: "api",
|
||||
Method: method,
|
||||
Scope: scope, Identity: []string{identity},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, sc := range allSC {
|
||||
if sc.Service != domain || !diagShortcutSupportsIdentity(&sc, identity) {
|
||||
continue
|
||||
}
|
||||
for _, scope := range sc.ScopesForIdentity(identity) {
|
||||
k := methodKey{domain, "shortcut", sc.Command, scope}
|
||||
if e, ok := merged[k]; ok {
|
||||
e.Identity = appendUniq(e.Identity, identity)
|
||||
} else {
|
||||
merged[k] = &diagMethodEntry{
|
||||
Domain: domain, Type: "shortcut",
|
||||
Method: sc.Command,
|
||||
Scope: scope, Identity: []string{identity},
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
methods := make([]diagMethodEntry, 0, len(merged))
|
||||
scopeSet := make(map[string]bool)
|
||||
for _, e := range merged {
|
||||
methods = append(methods, *e)
|
||||
scopeSet[e.Scope] = true
|
||||
}
|
||||
sort.Slice(methods, func(i, j int) bool {
|
||||
if methods[i].Domain != methods[j].Domain {
|
||||
return methods[i].Domain < methods[j].Domain
|
||||
}
|
||||
if methods[i].Type != methods[j].Type {
|
||||
return methods[i].Type < methods[j].Type
|
||||
}
|
||||
if methods[i].Method != methods[j].Method {
|
||||
return methods[i].Method < methods[j].Method
|
||||
}
|
||||
return methods[i].Scope < methods[j].Scope
|
||||
})
|
||||
|
||||
scopeList := make([]string, 0, len(scopeSet))
|
||||
for s := range scopeSet {
|
||||
scopeList = append(scopeList, s)
|
||||
}
|
||||
sort.Strings(scopeList)
|
||||
|
||||
priorities := registry.LoadScopePriorities()
|
||||
scopes := make([]diagScopeInfo, len(scopeList))
|
||||
for i, s := range scopeList {
|
||||
_, inPri := priorities[s]
|
||||
scopes[i] = diagScopeInfo{Scope: s, Recommend: recommend[s], InPriority: inPri}
|
||||
}
|
||||
|
||||
return diagOutput{Methods: methods, Scopes: scopes}
|
||||
}
|
||||
|
||||
func diagShortcutSupportsIdentity(sc *shortcutTypes.Shortcut, identity string) bool {
|
||||
if len(sc.AuthTypes) == 0 {
|
||||
return identity == "user"
|
||||
}
|
||||
for _, a := range sc.AuthTypes {
|
||||
if a == identity {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func appendUniq(ss []string, s string) []string {
|
||||
for _, existing := range ss {
|
||||
if existing == s {
|
||||
return ss
|
||||
}
|
||||
}
|
||||
return append(ss, s)
|
||||
}
|
||||
|
||||
// ── Snapshot generation ───────────────────────────────────────────────
|
||||
//
|
||||
// Generates a JSON snapshot of all API methods and shortcuts with their
|
||||
// minimum-privilege scopes. Consumed by scripts/scope_audit.py.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// SCOPE_SNAPSHOT_DIR=/tmp/scope-audit go test ./cmd/ -run TestScopeSnapshot -v
|
||||
func TestScopeSnapshot(t *testing.T) {
|
||||
dir := os.Getenv("SCOPE_SNAPSHOT_DIR")
|
||||
if dir == "" {
|
||||
t.Skip("set SCOPE_SNAPSHOT_DIR to enable snapshot generation")
|
||||
}
|
||||
|
||||
registry.Init()
|
||||
result := diagBuild(diagAllKnownDomains())
|
||||
|
||||
if err := os.MkdirAll(dir, 0o755); err != nil {
|
||||
t.Fatalf("mkdir: %v", err)
|
||||
}
|
||||
path := filepath.Join(dir, "snapshot.json")
|
||||
|
||||
data, err := json.MarshalIndent(result, "", " ")
|
||||
if err != nil {
|
||||
t.Fatalf("marshal: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(path, data, 0o644); err != nil {
|
||||
t.Fatalf("write: %v", err)
|
||||
}
|
||||
|
||||
t.Logf("Wrote %s (%d methods, %d scopes)", path, len(result.Methods), len(result.Scopes))
|
||||
}
|
||||
@@ -238,7 +238,7 @@ func checkCLIUpdate() []checkResult {
|
||||
if update.IsNewer(latest, current) {
|
||||
return []checkResult{warn("cli_update",
|
||||
fmt.Sprintf("%s → %s available", current, latest),
|
||||
"run: lark-cli update (or: npm install -g @larksuite/cli)")}
|
||||
"run: npm update -g @larksuite/cli")}
|
||||
}
|
||||
return []checkResult{pass("cli_update", latest+" (up to date)")}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,6 @@ import (
|
||||
"github.com/larksuite/cli/cmd/profile"
|
||||
"github.com/larksuite/cli/cmd/schema"
|
||||
"github.com/larksuite/cli/cmd/service"
|
||||
cmdupdate "github.com/larksuite/cli/cmd/update"
|
||||
internalauth "github.com/larksuite/cli/internal/auth"
|
||||
"github.com/larksuite/cli/internal/build"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
@@ -119,7 +118,6 @@ func Execute() int {
|
||||
rootCmd.AddCommand(api.NewCmdApi(f, nil))
|
||||
rootCmd.AddCommand(schema.NewCmdSchema(f, nil))
|
||||
rootCmd.AddCommand(completion.NewCmdCompletion(f))
|
||||
rootCmd.AddCommand(cmdupdate.NewCmdUpdate(f))
|
||||
service.RegisterServiceCommands(rootCmd, f)
|
||||
shortcuts.RegisterShortcuts(rootCmd, f)
|
||||
|
||||
|
||||
@@ -73,12 +73,6 @@ func printResourceList(w io.Writer, spec map[string]interface{}) {
|
||||
fmt.Fprintf(w, "%sUsage: lark-cli schema %s.<resource>.<method>%s\n", output.Dim, name, output.Reset)
|
||||
}
|
||||
|
||||
// hasFileFields returns true if any requestBody field has type "file".
|
||||
func hasFileFields(method map[string]interface{}) (bool, []string) {
|
||||
names := cmdutil.DetectFileFields(method)
|
||||
return len(names) > 0, names
|
||||
}
|
||||
|
||||
func printMethodDetail(w io.Writer, spec map[string]interface{}, resName, methodName string, method map[string]interface{}) {
|
||||
servicePath := registry.GetStrFromMap(spec, "servicePath")
|
||||
specName := registry.GetStrFromMap(spec, "name")
|
||||
@@ -86,7 +80,6 @@ func printMethodDetail(w io.Writer, spec map[string]interface{}, resName, method
|
||||
fullPath := servicePath + "/" + methodPath
|
||||
httpMethod := registry.GetStrFromMap(method, "httpMethod")
|
||||
desc := registry.GetStrFromMap(method, "description")
|
||||
isFileUpload, fileFieldNames := hasFileFields(method)
|
||||
|
||||
fmt.Fprintf(w, "%s%s.%s.%s%s\n\n", output.Bold, specName, resName, methodName, output.Reset)
|
||||
|
||||
@@ -145,25 +138,11 @@ func printMethodDetail(w io.Writer, spec map[string]interface{}, resName, method
|
||||
if len(params) == 0 {
|
||||
fmt.Fprintf(w, "%sParameters:%s\n\n", output.Bold, output.Reset)
|
||||
}
|
||||
fileUploadTag := ""
|
||||
if isFileUpload {
|
||||
fileUploadTag = fmt.Sprintf(" %s[file upload]%s", output.Yellow, output.Reset)
|
||||
}
|
||||
fmt.Fprintf(w, " %s--data%s <json> %soptional%s%s\n", output.Cyan, output.Reset, output.Dim, output.Reset, fileUploadTag)
|
||||
fmt.Fprintf(w, " %s--data%s <json> %soptional%s\n", output.Cyan, output.Reset, output.Dim, output.Reset)
|
||||
requestBody, _ := method["requestBody"].(map[string]interface{})
|
||||
if len(requestBody) > 0 {
|
||||
printNestedFields(w, requestBody, " ", "")
|
||||
}
|
||||
|
||||
if isFileUpload {
|
||||
if len(fileFieldNames) == 1 {
|
||||
fmt.Fprintf(w, "\n %s--file%s <[field=]path> %sfile upload%s\n", output.Cyan, output.Reset, output.Dim, output.Reset)
|
||||
fmt.Fprintf(w, " Upload file as multipart/form-data. Default field: %q\n", fileFieldNames[0])
|
||||
} else {
|
||||
fmt.Fprintf(w, "\n %s--file%s <field=path> %sfile upload%s\n", output.Cyan, output.Reset, output.Dim, output.Reset)
|
||||
fmt.Fprintf(w, " Upload file as multipart/form-data. Fields: %s\n", strings.Join(fileFieldNames, ", "))
|
||||
}
|
||||
}
|
||||
fmt.Fprintln(w)
|
||||
}
|
||||
|
||||
@@ -205,13 +184,7 @@ func printMethodDetail(w io.Writer, spec map[string]interface{}, resName, method
|
||||
}
|
||||
|
||||
// CLI example
|
||||
if isFileUpload && len(fileFieldNames) == 1 {
|
||||
fmt.Fprintf(w, "%sCLI:%s lark-cli %s %s %s --file <path>\n", output.Bold, output.Reset, specName, resName, methodName)
|
||||
} else if isFileUpload {
|
||||
fmt.Fprintf(w, "%sCLI:%s lark-cli %s %s %s --file <field=path>\n", output.Bold, output.Reset, specName, resName, methodName)
|
||||
} else {
|
||||
fmt.Fprintf(w, "%sCLI:%s lark-cli %s %s %s\n", output.Bold, output.Reset, specName, resName, methodName)
|
||||
}
|
||||
fmt.Fprintf(w, "%sCLI:%s lark-cli %s %s %s\n", output.Bold, output.Reset, specName, resName, methodName)
|
||||
|
||||
// Docs
|
||||
if docUrl := registry.GetStrFromMap(method, "docUrl"); docUrl != "" {
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
package schema
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -62,123 +61,3 @@ func TestSchemaCmd_UnknownService(t *testing.T) {
|
||||
t.Errorf("expected 'Unknown service' error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintMethodDetail_FileUpload(t *testing.T) {
|
||||
spec := map[string]interface{}{
|
||||
"name": "im",
|
||||
"servicePath": "/open-apis/im/v1",
|
||||
}
|
||||
method := map[string]interface{}{
|
||||
"path": "images",
|
||||
"httpMethod": "POST",
|
||||
"description": "Upload an image",
|
||||
"requestBody": map[string]interface{}{
|
||||
"image_type": map[string]interface{}{
|
||||
"type": "string",
|
||||
"required": true,
|
||||
},
|
||||
"image": map[string]interface{}{
|
||||
"type": "file",
|
||||
"required": true,
|
||||
},
|
||||
},
|
||||
"accessTokens": []interface{}{"user", "tenant"},
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
printMethodDetail(&buf, spec, "images", "create", method)
|
||||
out := buf.String()
|
||||
|
||||
if !strings.Contains(out, "file upload") {
|
||||
t.Errorf("expected 'file upload' marker in output, got:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(out, "--file") {
|
||||
t.Errorf("expected '--file' in output, got:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(out, `"image"`) {
|
||||
t.Errorf("expected default field name 'image' in output, got:\n%s", out)
|
||||
}
|
||||
if !strings.Contains(out, "--file <path>") {
|
||||
t.Errorf("expected CLI example with --file <path>, got:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrintMethodDetail_NoFileUpload(t *testing.T) {
|
||||
spec := map[string]interface{}{
|
||||
"name": "calendar",
|
||||
"servicePath": "/open-apis/calendar/v4",
|
||||
}
|
||||
method := map[string]interface{}{
|
||||
"path": "events",
|
||||
"httpMethod": "POST",
|
||||
"description": "Create an event",
|
||||
"requestBody": map[string]interface{}{
|
||||
"summary": map[string]interface{}{
|
||||
"type": "string",
|
||||
"required": true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
var buf bytes.Buffer
|
||||
printMethodDetail(&buf, spec, "events", "create", method)
|
||||
out := buf.String()
|
||||
|
||||
if strings.Contains(out, "file upload") {
|
||||
t.Errorf("did not expect 'file upload' marker for non-file method, got:\n%s", out)
|
||||
}
|
||||
if strings.Contains(out, "--file") {
|
||||
t.Errorf("did not expect '--file' for non-file method, got:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasFileFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method map[string]interface{}
|
||||
wantBool bool
|
||||
wantFields []string
|
||||
}{
|
||||
{
|
||||
name: "has file field",
|
||||
method: map[string]interface{}{
|
||||
"requestBody": map[string]interface{}{
|
||||
"image": map[string]interface{}{"type": "file"},
|
||||
"name": map[string]interface{}{"type": "string"},
|
||||
},
|
||||
},
|
||||
wantBool: true,
|
||||
wantFields: []string{"image"},
|
||||
},
|
||||
{
|
||||
name: "no file field",
|
||||
method: map[string]interface{}{
|
||||
"requestBody": map[string]interface{}{
|
||||
"name": map[string]interface{}{"type": "string"},
|
||||
},
|
||||
},
|
||||
wantBool: false,
|
||||
wantFields: nil,
|
||||
},
|
||||
{
|
||||
name: "no requestBody",
|
||||
method: map[string]interface{}{},
|
||||
wantBool: false,
|
||||
wantFields: nil,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, names := hasFileFields(tt.method)
|
||||
if got != tt.wantBool {
|
||||
t.Errorf("hasFileFields() = %v, want %v", got, tt.wantBool)
|
||||
}
|
||||
if tt.wantFields == nil && names != nil {
|
||||
t.Errorf("expected nil names, got %v", names)
|
||||
}
|
||||
if tt.wantFields != nil && len(names) != len(tt.wantFields) {
|
||||
t.Errorf("expected %d field names, got %d", len(tt.wantFields), len(names))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ package service
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
@@ -111,13 +112,6 @@ type ServiceMethodOptions struct {
|
||||
Format string
|
||||
JqExpr string
|
||||
DryRun bool
|
||||
File string // --file flag value
|
||||
FileFields []string // auto-detected file field names from metadata
|
||||
}
|
||||
|
||||
// detectFileFields delegates to the shared cmdutil.DetectFileFields helper.
|
||||
func detectFileFields(method map[string]interface{}) []string {
|
||||
return cmdutil.DetectFileFields(method)
|
||||
}
|
||||
|
||||
func registerMethod(parent *cobra.Command, spec map[string]interface{}, method map[string]interface{}, name string, resName string, f *cmdutil.Factory) {
|
||||
@@ -154,10 +148,10 @@ func NewCmdServiceMethod(f *cmdutil.Factory, spec, method map[string]interface{}
|
||||
},
|
||||
}
|
||||
|
||||
cmd.Flags().StringVar(&opts.Params, "params", "", "URL/query parameters JSON (supports - for stdin)")
|
||||
cmd.Flags().StringVar(&opts.Params, "params", "", "URL/query parameters JSON")
|
||||
switch httpMethod {
|
||||
case "POST", "PUT", "PATCH", "DELETE":
|
||||
cmd.Flags().StringVar(&opts.Data, "data", "", "request body JSON (supports - for stdin)")
|
||||
cmd.Flags().StringVar(&opts.Data, "data", "", "request body JSON")
|
||||
}
|
||||
cmd.Flags().StringVar(&asStr, "as", "auto", "identity type: user | bot | auto (default)")
|
||||
cmd.Flags().StringVarP(&opts.Output, "output", "o", "", "output file path for binary responses")
|
||||
@@ -168,16 +162,6 @@ func NewCmdServiceMethod(f *cmdutil.Factory, spec, method map[string]interface{}
|
||||
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")
|
||||
|
||||
// Conditionally register --file for methods with file-type fields.
|
||||
fileFields := detectFileFields(method)
|
||||
opts.FileFields = fileFields
|
||||
if len(fileFields) > 0 {
|
||||
switch httpMethod {
|
||||
case "POST", "PUT", "PATCH", "DELETE":
|
||||
cmd.Flags().StringVar(&opts.File, "file", "", "file to upload ([field=]path, supports - for stdin)")
|
||||
}
|
||||
}
|
||||
|
||||
_ = cmd.RegisterFlagCompletionFunc("as", func(_ *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) {
|
||||
return []string{"user", "bot"}, cobra.ShellCompDirectiveNoFileComp
|
||||
})
|
||||
@@ -229,15 +213,12 @@ func serviceMethodRun(opts *ServiceMethodOptions) error {
|
||||
}
|
||||
}
|
||||
|
||||
request, fileMeta, err := buildServiceRequest(opts)
|
||||
request, err := buildServiceRequest(opts)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if opts.DryRun {
|
||||
if fileMeta != nil {
|
||||
return cmdutil.PrintDryRunWithFile(f.IOStreams.Out, request, config, opts.Format, fileMeta.FieldName, fileMeta.FilePath, fileMeta.FormFields)
|
||||
}
|
||||
return serviceDryRun(f, request, config, opts.Format)
|
||||
}
|
||||
|
||||
@@ -323,28 +304,19 @@ func checkServiceScopes(ctx context.Context, cred *credential.CredentialProvider
|
||||
}
|
||||
|
||||
// buildServiceRequest parses flags, builds the URL with path/query params, and returns a RawApiRequest.
|
||||
// When dryRun is true and a file is provided, file reading is skipped and
|
||||
// FileUploadMeta is returned instead so the caller can render dry-run output.
|
||||
func buildServiceRequest(opts *ServiceMethodOptions) (client.RawApiRequest, *cmdutil.FileUploadMeta, error) {
|
||||
func buildServiceRequest(opts *ServiceMethodOptions) (client.RawApiRequest, error) {
|
||||
spec := opts.Spec
|
||||
method := opts.Method
|
||||
schemaPath := opts.SchemaPath
|
||||
httpMethod := registry.GetStrFromMap(method, "httpMethod")
|
||||
|
||||
// stdin is an io.Reader consumed at most once. Only one of --params/--data
|
||||
// may use "-" (stdin); the conflict check below prevents silent data loss.
|
||||
stdin := opts.Factory.IOStreams.In
|
||||
|
||||
// Validate --file mutual exclusions.
|
||||
if err := cmdutil.ValidateFileFlag(opts.File, opts.Params, opts.Data, opts.Output, opts.PageAll, httpMethod); err != nil {
|
||||
return client.RawApiRequest{}, nil, err
|
||||
}
|
||||
if opts.Params == "-" && opts.Data == "-" {
|
||||
return client.RawApiRequest{}, nil, output.ErrValidation("--params and --data cannot both read from stdin (-)")
|
||||
}
|
||||
params, err := cmdutil.ParseJSONMap(opts.Params, "--params", stdin)
|
||||
if err != nil {
|
||||
return client.RawApiRequest{}, nil, err
|
||||
var params map[string]interface{}
|
||||
if opts.Params != "" {
|
||||
if err := json.Unmarshal([]byte(opts.Params), ¶ms); err != nil {
|
||||
return client.RawApiRequest{}, output.ErrValidation("--params invalid JSON format")
|
||||
}
|
||||
} else {
|
||||
params = map[string]interface{}{}
|
||||
}
|
||||
|
||||
url := registry.GetStrFromMap(spec, "servicePath") + "/" + registry.GetStrFromMap(method, "path")
|
||||
@@ -357,13 +329,13 @@ func buildServiceRequest(opts *ServiceMethodOptions) (client.RawApiRequest, *cmd
|
||||
}
|
||||
val, ok := params[name]
|
||||
if !ok || util.IsEmptyValue(val) {
|
||||
return client.RawApiRequest{}, nil, output.ErrWithHint(output.ExitValidation, "validation",
|
||||
return client.RawApiRequest{}, output.ErrWithHint(output.ExitValidation, "validation",
|
||||
fmt.Sprintf("missing required path parameter: %s", name),
|
||||
fmt.Sprintf("lark-cli schema %s", schemaPath))
|
||||
}
|
||||
valStr := fmt.Sprintf("%v", val)
|
||||
if err := validate.ResourceName(valStr, name); err != nil {
|
||||
return client.RawApiRequest{}, nil, output.ErrValidation("%s", err)
|
||||
return client.RawApiRequest{}, output.ErrValidation("%s", err)
|
||||
}
|
||||
url = strings.Replace(url, "{"+name+"}", validate.EncodePathSegment(valStr), 1)
|
||||
delete(params, name)
|
||||
@@ -379,7 +351,7 @@ func buildServiceRequest(opts *ServiceMethodOptions) (client.RawApiRequest, *cmd
|
||||
required, _ := p["required"].(bool)
|
||||
isPaginationParam := opts.PageAll && (name == "page_token" || name == "page_size")
|
||||
if required && !isPaginationParam && (!exists || util.IsEmptyValue(value)) {
|
||||
return client.RawApiRequest{}, nil, output.ErrWithHint(output.ExitValidation, "validation",
|
||||
return client.RawApiRequest{}, output.ErrWithHint(output.ExitValidation, "validation",
|
||||
fmt.Sprintf("missing required query parameter: %s", name),
|
||||
fmt.Sprintf("lark-cli schema %s", schemaPath))
|
||||
}
|
||||
@@ -393,60 +365,22 @@ func buildServiceRequest(opts *ServiceMethodOptions) (client.RawApiRequest, *cmd
|
||||
}
|
||||
}
|
||||
|
||||
data, err := cmdutil.ParseOptionalBody(httpMethod, opts.Data)
|
||||
if err != nil {
|
||||
return client.RawApiRequest{}, err
|
||||
}
|
||||
|
||||
request := client.RawApiRequest{
|
||||
Method: httpMethod,
|
||||
URL: url,
|
||||
Params: queryParams,
|
||||
Data: data,
|
||||
As: opts.As,
|
||||
}
|
||||
|
||||
if opts.File != "" {
|
||||
// File upload: determine default field name from metadata.
|
||||
defaultField := "file"
|
||||
if len(opts.FileFields) == 1 {
|
||||
defaultField = opts.FileFields[0]
|
||||
}
|
||||
fieldName, filePath, isStdin := cmdutil.ParseFileFlag(opts.File, defaultField)
|
||||
|
||||
// Parse --data as form fields.
|
||||
var dataFields any
|
||||
if opts.Data != "" {
|
||||
dataFields, err = cmdutil.ParseOptionalBody(httpMethod, opts.Data, stdin)
|
||||
if err != nil {
|
||||
return client.RawApiRequest{}, nil, err
|
||||
}
|
||||
if _, ok := dataFields.(map[string]any); !ok {
|
||||
return client.RawApiRequest{}, nil, output.ErrValidation("--data must be a JSON object when used with --file")
|
||||
}
|
||||
}
|
||||
|
||||
if opts.DryRun {
|
||||
return request, &cmdutil.FileUploadMeta{
|
||||
FieldName: fieldName, FilePath: filePath, FormFields: dataFields,
|
||||
}, nil
|
||||
}
|
||||
|
||||
fd, err := cmdutil.BuildFormdata(
|
||||
opts.Factory.ResolveFileIO(opts.Ctx),
|
||||
fieldName, filePath, isStdin, stdin, dataFields,
|
||||
)
|
||||
if err != nil {
|
||||
return client.RawApiRequest{}, nil, err
|
||||
}
|
||||
request.Data = fd
|
||||
request.ExtraOpts = append(request.ExtraOpts, larkcore.WithFileUpload())
|
||||
} else {
|
||||
data, err := cmdutil.ParseOptionalBody(httpMethod, opts.Data, stdin)
|
||||
if err != nil {
|
||||
return client.RawApiRequest{}, nil, err
|
||||
}
|
||||
request.Data = data
|
||||
if opts.Output != "" {
|
||||
request.ExtraOpts = append(request.ExtraOpts, larkcore.WithFileDownload())
|
||||
}
|
||||
if opts.Output != "" {
|
||||
request.ExtraOpts = append(request.ExtraOpts, larkcore.WithFileDownload())
|
||||
}
|
||||
|
||||
return request, nil, nil
|
||||
return request, nil
|
||||
}
|
||||
|
||||
func serviceDryRun(f *cmdutil.Factory, request client.RawApiRequest, config *core.CliConfig, format string) error {
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
package service
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -309,7 +308,7 @@ func TestServiceMethod_InvalidParamsJSON(t *testing.T) {
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid JSON")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "--params invalid format") {
|
||||
if !strings.Contains(err.Error(), "--params invalid JSON format") {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -332,24 +331,6 @@ func TestServiceMethod_InvalidDataJSON(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMethod_ParamsAndDataBothStdinConflict(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, testConfig)
|
||||
spec := map[string]interface{}{
|
||||
"name": "svc", "servicePath": "/open-apis/svc/v1",
|
||||
}
|
||||
method := map[string]interface{}{"path": "items", "httpMethod": "POST", "parameters": map[string]interface{}{}}
|
||||
cmd := NewCmdServiceMethod(f, spec, method, "create", "items", nil)
|
||||
cmd.SetArgs([]string{"--params", "-", "--data", "-", "--dry-run"})
|
||||
|
||||
err := cmd.Execute()
|
||||
if err == nil {
|
||||
t.Fatal("expected error when both --params and --data use stdin")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "cannot both read from stdin") {
|
||||
t.Errorf("expected stdin conflict error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMethod_OutputAndPageAllConflict(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, testConfig)
|
||||
spec := map[string]interface{}{
|
||||
@@ -711,144 +692,6 @@ func TestScopeAwareChecker_ScopeError_BotMode(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// ── file upload ──
|
||||
|
||||
func imImageMethod() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"path": "images",
|
||||
"httpMethod": "POST",
|
||||
"requestBody": map[string]interface{}{
|
||||
"image_type": map[string]interface{}{
|
||||
"type": "string",
|
||||
"required": true,
|
||||
},
|
||||
"image": map[string]interface{}{
|
||||
"type": "file",
|
||||
"required": true,
|
||||
},
|
||||
},
|
||||
"accessTokens": []interface{}{"user", "tenant"},
|
||||
}
|
||||
}
|
||||
|
||||
func imSpec() map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"name": "im",
|
||||
"servicePath": "/open-apis/im/v1",
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMethod_FileFlagRegistered(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, testConfig)
|
||||
cmd := NewCmdServiceMethod(f, imSpec(), imImageMethod(), "create", "images", nil)
|
||||
flag := cmd.Flags().Lookup("file")
|
||||
if flag == nil {
|
||||
t.Fatal("expected --file flag to be registered for file upload method")
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMethod_FileFlagNotRegistered(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, testConfig)
|
||||
cmd := NewCmdServiceMethod(f, driveSpec(), driveMethod("POST", nil), "copy", "files", nil)
|
||||
flag := cmd.Flags().Lookup("file")
|
||||
if flag != nil {
|
||||
t.Fatal("expected --file flag NOT to be registered for non-file method")
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMethod_FileFlagNotRegisteredForGET(t *testing.T) {
|
||||
getMethod := map[string]interface{}{
|
||||
"path": "images",
|
||||
"httpMethod": "GET",
|
||||
"requestBody": map[string]interface{}{
|
||||
"image": map[string]interface{}{
|
||||
"type": "file",
|
||||
},
|
||||
},
|
||||
}
|
||||
f, _, _, _ := cmdutil.TestFactory(t, testConfig)
|
||||
cmd := NewCmdServiceMethod(f, imSpec(), getMethod, "get", "images", nil)
|
||||
flag := cmd.Flags().Lookup("file")
|
||||
if flag != nil {
|
||||
t.Fatal("expected --file flag NOT to be registered for GET method")
|
||||
}
|
||||
}
|
||||
|
||||
func TestServiceMethod_FileUpload_DryRun(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
tmpFile := tmpDir + "/test.jpg"
|
||||
if err := os.WriteFile(tmpFile, []byte("fake-image"), 0600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, testConfig)
|
||||
cmd := NewCmdServiceMethod(f, imSpec(), imImageMethod(), "create", "images", nil)
|
||||
cmd.SetArgs([]string{
|
||||
"--file", "image=" + tmpFile,
|
||||
"--data", `{"image_type":"message"}`,
|
||||
"--dry-run",
|
||||
"--as", "bot",
|
||||
})
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, "image") {
|
||||
t.Errorf("expected dry-run output to mention file field, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "Dry Run") {
|
||||
t.Errorf("expected dry-run header, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDetectFileFields(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method map[string]interface{}
|
||||
want []string
|
||||
}{
|
||||
{
|
||||
name: "single file field",
|
||||
method: map[string]interface{}{
|
||||
"requestBody": map[string]interface{}{
|
||||
"image": map[string]interface{}{"type": "file"},
|
||||
"name": map[string]interface{}{"type": "string"},
|
||||
},
|
||||
},
|
||||
want: []string{"image"},
|
||||
},
|
||||
{
|
||||
name: "no file fields",
|
||||
method: map[string]interface{}{
|
||||
"requestBody": map[string]interface{}{
|
||||
"name": map[string]interface{}{"type": "string"},
|
||||
},
|
||||
},
|
||||
want: nil,
|
||||
},
|
||||
{
|
||||
name: "no requestBody",
|
||||
method: map[string]interface{}{},
|
||||
want: nil,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got := detectFileFields(tt.method)
|
||||
if len(got) != len(tt.want) {
|
||||
t.Errorf("detectFileFields() = %v, want %v", got, tt.want)
|
||||
return
|
||||
}
|
||||
for i := range got {
|
||||
if got[i] != tt.want[i] {
|
||||
t.Errorf("detectFileFields()[%d] = %q, want %q", i, got[i], tt.want[i])
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// ── helpers ──
|
||||
|
||||
func isExitError(err error, target **output.ExitError) bool {
|
||||
|
||||
@@ -1,314 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmdupdate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"runtime"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/larksuite/cli/internal/build"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/internal/selfupdate"
|
||||
"github.com/larksuite/cli/internal/update"
|
||||
)
|
||||
|
||||
const (
|
||||
repoURL = "https://github.com/larksuite/cli"
|
||||
maxNpmOutput = 2000
|
||||
osWindows = "windows"
|
||||
)
|
||||
|
||||
// Overridable for testing.
|
||||
var (
|
||||
fetchLatest = func() (string, error) { return update.FetchLatest() }
|
||||
currentVersion = func() string { return build.Version }
|
||||
currentOS = runtime.GOOS
|
||||
newUpdater = func() *selfupdate.Updater { return selfupdate.New() }
|
||||
)
|
||||
|
||||
func isWindows() bool { return currentOS == osWindows }
|
||||
|
||||
func releaseURL(version string) string {
|
||||
return repoURL + "/releases/tag/v" + strings.TrimPrefix(version, "v")
|
||||
}
|
||||
|
||||
func changelogURL() string { return repoURL + "/blob/main/CHANGELOG.md" }
|
||||
|
||||
// --- Terminal symbols (ASCII fallback on Windows) ---
|
||||
|
||||
func symOK() string {
|
||||
if isWindows() {
|
||||
return "[OK]"
|
||||
}
|
||||
return "✓"
|
||||
}
|
||||
|
||||
func symFail() string {
|
||||
if isWindows() {
|
||||
return "[FAIL]"
|
||||
}
|
||||
return "✗"
|
||||
}
|
||||
|
||||
func symWarn() string {
|
||||
if isWindows() {
|
||||
return "[WARN]"
|
||||
}
|
||||
return "⚠"
|
||||
}
|
||||
|
||||
func symArrow() string {
|
||||
if isWindows() {
|
||||
return "->"
|
||||
}
|
||||
return "→"
|
||||
}
|
||||
|
||||
// --- Command ---
|
||||
|
||||
// UpdateOptions holds inputs for the update command.
|
||||
type UpdateOptions struct {
|
||||
Factory *cmdutil.Factory
|
||||
JSON bool
|
||||
Force bool
|
||||
Check bool
|
||||
}
|
||||
|
||||
// NewCmdUpdate creates the update command.
|
||||
func NewCmdUpdate(f *cmdutil.Factory) *cobra.Command {
|
||||
opts := &UpdateOptions{Factory: f}
|
||||
|
||||
cmd := &cobra.Command{
|
||||
Use: "update",
|
||||
Short: "Update lark-cli to the latest version",
|
||||
Long: `Update lark-cli to the latest version.
|
||||
|
||||
Detects the installation method automatically:
|
||||
- npm install: runs npm install -g @larksuite/cli@<version>
|
||||
- manual/other: shows GitHub Releases download URL
|
||||
|
||||
Use --json for structured output (for AI agents and scripts).
|
||||
Use --check to only check for updates without installing.`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
return updateRun(opts)
|
||||
},
|
||||
}
|
||||
cmdutil.DisableAuthCheck(cmd)
|
||||
cmd.Flags().BoolVar(&opts.JSON, "json", false, "structured JSON output")
|
||||
cmd.Flags().BoolVar(&opts.Force, "force", false, "force reinstall even if already up to date")
|
||||
cmd.Flags().BoolVar(&opts.Check, "check", false, "only check for updates, do not install")
|
||||
|
||||
return cmd
|
||||
}
|
||||
|
||||
func updateRun(opts *UpdateOptions) error {
|
||||
io := opts.Factory.IOStreams
|
||||
cur := currentVersion()
|
||||
updater := newUpdater()
|
||||
|
||||
updater.CleanupStaleFiles()
|
||||
output.PendingNotice = nil
|
||||
|
||||
// 1. Fetch latest version
|
||||
latest, err := fetchLatest()
|
||||
if err != nil {
|
||||
return reportError(opts, io, output.ExitNetwork, "network", "failed to check latest version: %s", err)
|
||||
}
|
||||
|
||||
// 2. Validate version format
|
||||
if update.ParseVersion(latest) == nil {
|
||||
return reportError(opts, io, output.ExitInternal, "update_error", "invalid version from registry: %s", latest)
|
||||
}
|
||||
|
||||
// 3. Compare versions
|
||||
if !opts.Force && !update.IsNewer(latest, cur) {
|
||||
if opts.JSON {
|
||||
output.PrintJson(io.Out, map[string]interface{}{
|
||||
"ok": true, "previous_version": cur, "current_version": cur,
|
||||
"latest_version": latest, "action": "already_up_to_date",
|
||||
"message": fmt.Sprintf("lark-cli %s is already up to date", cur),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
fmt.Fprintf(io.ErrOut, "%s lark-cli %s is already up to date\n", symOK(), cur)
|
||||
return nil
|
||||
}
|
||||
|
||||
// 4. Detect installation method
|
||||
detect := updater.DetectInstallMethod()
|
||||
|
||||
// 5. --check
|
||||
if opts.Check {
|
||||
return reportCheckResult(opts, io, cur, latest, detect.CanAutoUpdate())
|
||||
}
|
||||
|
||||
// 6. Execute update
|
||||
if !detect.CanAutoUpdate() {
|
||||
return doManualUpdate(opts, io, cur, latest, detect)
|
||||
}
|
||||
return doNpmUpdate(opts, io, cur, latest, updater)
|
||||
}
|
||||
|
||||
// --- Output helpers ---
|
||||
|
||||
func reportError(opts *UpdateOptions, io *cmdutil.IOStreams, exitCode int, errType, format string, args ...interface{}) error {
|
||||
msg := fmt.Sprintf(format, args...)
|
||||
if opts.JSON {
|
||||
output.PrintJson(io.Out, map[string]interface{}{
|
||||
"ok": false, "error": map[string]interface{}{"type": errType, "message": msg},
|
||||
})
|
||||
return output.ErrBare(exitCode)
|
||||
}
|
||||
return output.Errorf(exitCode, errType, "%s", msg)
|
||||
}
|
||||
|
||||
func reportCheckResult(opts *UpdateOptions, io *cmdutil.IOStreams, cur, latest string, canAutoUpdate bool) error {
|
||||
if opts.JSON {
|
||||
output.PrintJson(io.Out, map[string]interface{}{
|
||||
"ok": true, "previous_version": cur, "current_version": cur,
|
||||
"latest_version": latest, "action": "update_available",
|
||||
"auto_update": canAutoUpdate,
|
||||
"message": fmt.Sprintf("lark-cli %s %s %s available", cur, symArrow(), latest),
|
||||
"url": releaseURL(latest), "changelog": changelogURL(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
fmt.Fprintf(io.ErrOut, "Update available: %s %s %s\n", cur, symArrow(), latest)
|
||||
fmt.Fprintf(io.ErrOut, " Release: %s\n", releaseURL(latest))
|
||||
fmt.Fprintf(io.ErrOut, " Changelog: %s\n", changelogURL())
|
||||
if canAutoUpdate {
|
||||
fmt.Fprintf(io.ErrOut, "\nRun `lark-cli update` to install.\n")
|
||||
} else {
|
||||
fmt.Fprintf(io.ErrOut, "\nDownload the release above to update manually.\n")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func doManualUpdate(opts *UpdateOptions, io *cmdutil.IOStreams, cur, latest string, detect selfupdate.DetectResult) error {
|
||||
reason := detect.ManualReason()
|
||||
if opts.JSON {
|
||||
output.PrintJson(io.Out, map[string]interface{}{
|
||||
"ok": true, "previous_version": cur, "latest_version": latest,
|
||||
"action": "manual_required",
|
||||
"message": fmt.Sprintf("Automatic update unavailable: %s (path: %s)", reason, detect.ResolvedPath),
|
||||
"url": releaseURL(latest), "changelog": changelogURL(),
|
||||
})
|
||||
return nil
|
||||
}
|
||||
fmt.Fprintf(io.ErrOut, "Automatic update unavailable: %s (path: %s).\n\n", reason, detect.ResolvedPath)
|
||||
fmt.Fprintf(io.ErrOut, "To update manually, download the latest release:\n")
|
||||
fmt.Fprintf(io.ErrOut, " Release: %s\n", releaseURL(latest))
|
||||
fmt.Fprintf(io.ErrOut, " Changelog: %s\n", changelogURL())
|
||||
fmt.Fprintf(io.ErrOut, "\nOr install via npm:\n npm install -g %s@%s\n", selfupdate.NpmPackage, latest)
|
||||
fmt.Fprintf(io.ErrOut, "\nAfter updating, also update skills:\n npx -y skills add larksuite/cli -g -y\n")
|
||||
return nil
|
||||
}
|
||||
|
||||
func doNpmUpdate(opts *UpdateOptions, io *cmdutil.IOStreams, cur, latest string, updater *selfupdate.Updater) error {
|
||||
restore, err := updater.PrepareSelfReplace()
|
||||
if err != nil {
|
||||
return reportError(opts, io, output.ExitAPI, "update_error", "failed to prepare update: %s", err)
|
||||
}
|
||||
|
||||
if !opts.JSON {
|
||||
fmt.Fprintf(io.ErrOut, "Updating lark-cli %s %s %s via npm ...\n", cur, symArrow(), latest)
|
||||
}
|
||||
|
||||
npmResult := updater.RunNpmInstall(latest)
|
||||
if npmResult.Err != nil {
|
||||
restore()
|
||||
combined := npmResult.CombinedOutput()
|
||||
if opts.JSON {
|
||||
output.PrintJson(io.Out, map[string]interface{}{
|
||||
"ok": false, "error": map[string]interface{}{
|
||||
"type": "update_error", "message": fmt.Sprintf("npm install failed: %s", npmResult.Err),
|
||||
"detail": selfupdate.Truncate(combined, maxNpmOutput),
|
||||
"hint": permissionHint(combined),
|
||||
},
|
||||
})
|
||||
return output.ErrBare(output.ExitAPI)
|
||||
}
|
||||
if npmResult.Stdout.Len() > 0 {
|
||||
fmt.Fprint(io.ErrOut, npmResult.Stdout.String())
|
||||
}
|
||||
if npmResult.Stderr.Len() > 0 {
|
||||
fmt.Fprint(io.ErrOut, npmResult.Stderr.String())
|
||||
}
|
||||
fmt.Fprintf(io.ErrOut, "\n%s Update failed: %s\n", symFail(), npmResult.Err)
|
||||
if hint := permissionHint(combined); hint != "" {
|
||||
fmt.Fprintf(io.ErrOut, " %s\n", hint)
|
||||
}
|
||||
return output.ErrBare(output.ExitAPI)
|
||||
}
|
||||
|
||||
// Verify the new binary is functional before proceeding.
|
||||
// If corrupt, restore the previous version from .old.
|
||||
if err := updater.VerifyBinary(latest); err != nil {
|
||||
restore()
|
||||
msg := fmt.Sprintf("new binary verification failed: %s", err)
|
||||
hint := verificationFailureHint(updater, latest)
|
||||
if opts.JSON {
|
||||
output.PrintJson(io.Out, map[string]interface{}{
|
||||
"ok": false,
|
||||
"error": map[string]interface{}{"type": "update_error", "message": msg, "hint": hint},
|
||||
})
|
||||
return output.ErrBare(output.ExitAPI)
|
||||
}
|
||||
fmt.Fprintf(io.ErrOut, "\n%s %s\n", symFail(), msg)
|
||||
fmt.Fprintf(io.ErrOut, " %s\n", hint)
|
||||
return output.ErrBare(output.ExitAPI)
|
||||
}
|
||||
|
||||
// Skills update (best-effort).
|
||||
skillsResult := updater.RunSkillsUpdate()
|
||||
|
||||
if opts.JSON {
|
||||
result := map[string]interface{}{
|
||||
"ok": true, "previous_version": cur, "current_version": latest,
|
||||
"latest_version": latest, "action": "updated",
|
||||
"message": fmt.Sprintf("lark-cli updated from %s to %s", cur, latest),
|
||||
"url": releaseURL(latest), "changelog": changelogURL(),
|
||||
}
|
||||
if skillsResult.Err != nil {
|
||||
result["skills_warning"] = fmt.Sprintf("skills update failed: %s", skillsResult.Err)
|
||||
if detail := strings.TrimSpace(skillsResult.Stderr.String()); detail != "" {
|
||||
result["skills_detail"] = selfupdate.Truncate(detail, maxNpmOutput)
|
||||
}
|
||||
}
|
||||
output.PrintJson(io.Out, result)
|
||||
return nil
|
||||
}
|
||||
|
||||
fmt.Fprintf(io.ErrOut, "\n%s Successfully updated lark-cli from %s to %s\n", symOK(), cur, latest)
|
||||
fmt.Fprintf(io.ErrOut, " Changelog: %s\n", changelogURL())
|
||||
fmt.Fprintf(io.ErrOut, "\nUpdating skills ...\n")
|
||||
if skillsResult.Err != nil {
|
||||
fmt.Fprintf(io.ErrOut, "%s Skills update failed: %s\n", symWarn(), skillsResult.Err)
|
||||
if detail := strings.TrimSpace(skillsResult.Stderr.String()); detail != "" {
|
||||
fmt.Fprintf(io.ErrOut, " %s\n", selfupdate.Truncate(detail, 500))
|
||||
}
|
||||
fmt.Fprintf(io.ErrOut, " Run manually: npx -y skills add larksuite/cli -g -y\n")
|
||||
} else {
|
||||
fmt.Fprintf(io.ErrOut, "%s Skills updated\n", symOK())
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func permissionHint(npmOutput string) string {
|
||||
if strings.Contains(npmOutput, "EACCES") && !isWindows() {
|
||||
return "Permission denied. Try: sudo lark-cli update, or adjust your npm global prefix: https://docs.npmjs.com/resolving-eacces-permissions-errors"
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func verificationFailureHint(updater *selfupdate.Updater, latest string) string {
|
||||
if updater.CanRestorePreviousVersion() {
|
||||
return "the previous version has been restored"
|
||||
}
|
||||
return fmt.Sprintf("automatic rollback is unavailable on this platform; reinstall manually: npm install -g %s@%s, or download %s", selfupdate.NpmPackage, latest, releaseURL(latest))
|
||||
}
|
||||
@@ -1,851 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmdupdate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/internal/selfupdate"
|
||||
)
|
||||
|
||||
// newTestFactory creates a test factory with minimal config.
|
||||
func newTestFactory(t *testing.T) (*cmdutil.Factory, *bytes.Buffer, *bytes.Buffer) {
|
||||
t.Helper()
|
||||
f, stdout, stderr, _ := cmdutil.TestFactory(t, &core.CliConfig{})
|
||||
return f, stdout, stderr
|
||||
}
|
||||
|
||||
// mockDetect sets up newUpdater to return an Updater with the given DetectResult.
|
||||
// It preserves any existing NpmInstallOverride/SkillsUpdateOverride that may be set later.
|
||||
func mockDetect(t *testing.T, result selfupdate.DetectResult) {
|
||||
t.Helper()
|
||||
origNew := newUpdater
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
u := selfupdate.New()
|
||||
u.DetectOverride = func() selfupdate.DetectResult { return result }
|
||||
return u
|
||||
}
|
||||
t.Cleanup(func() { newUpdater = origNew })
|
||||
}
|
||||
|
||||
// mockDetectAndNpm sets up newUpdater with detect, npm install, and skills overrides all at once.
|
||||
func mockDetectAndNpm(t *testing.T, result selfupdate.DetectResult,
|
||||
npmFn func(string) *selfupdate.NpmResult,
|
||||
skillsFn func() *selfupdate.NpmResult) {
|
||||
t.Helper()
|
||||
origNew := newUpdater
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
u := selfupdate.New()
|
||||
u.DetectOverride = func() selfupdate.DetectResult { return result }
|
||||
u.NpmInstallOverride = npmFn
|
||||
u.SkillsUpdateOverride = skillsFn
|
||||
u.VerifyOverride = func(string) error { return nil }
|
||||
return u
|
||||
}
|
||||
t.Cleanup(func() { newUpdater = origNew })
|
||||
}
|
||||
|
||||
func TestUpdateAlreadyUpToDate_JSON(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "1.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, `"action": "already_up_to_date"`) {
|
||||
t.Errorf("expected already_up_to_date in JSON output, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, `"ok": true`) {
|
||||
t.Errorf("expected ok:true in JSON output, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateAlreadyUpToDate_Human(t *testing.T) {
|
||||
f, _, stderr := newTestFactory(t)
|
||||
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "1.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
out := stderr.String()
|
||||
if !strings.Contains(out, "already up to date") {
|
||||
t.Errorf("expected 'already up to date' in stderr, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateManual_JSON(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
cmd.SilenceErrors = true
|
||||
cmd.SilenceUsage = true
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
mockDetect(t, selfupdate.DetectResult{Method: selfupdate.InstallManual, ResolvedPath: "/usr/local/bin/lark-cli"})
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, `"action": "manual_required"`) {
|
||||
t.Errorf("expected manual_required in output, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "not installed via npm") {
|
||||
t.Errorf("expected accurate reason in output, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "releases/tag/v2.0.0") {
|
||||
t.Errorf("expected version-pinned URL in output, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateManual_Human(t *testing.T) {
|
||||
f, _, stderr := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
mockDetect(t, selfupdate.DetectResult{Method: selfupdate.InstallManual, ResolvedPath: "/usr/local/bin/lark-cli"})
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stderr.String()
|
||||
if !strings.Contains(out, "not installed via npm") {
|
||||
t.Errorf("expected 'not installed via npm' in stderr, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "releases/tag/v2.0.0") {
|
||||
t.Errorf("expected version-pinned URL in stderr, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateNpm_JSON(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
mockDetectAndNpm(t,
|
||||
selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true},
|
||||
func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
func() *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
)
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, `"action": "updated"`) {
|
||||
t.Errorf("expected updated in output, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateNpm_Human(t *testing.T) {
|
||||
f, _, stderr := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
mockDetectAndNpm(t,
|
||||
selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true},
|
||||
func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
func() *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
)
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stderr.String()
|
||||
if !strings.Contains(out, "Successfully updated") {
|
||||
t.Errorf("expected success message in stderr, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateForce_JSON(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--force", "--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "1.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
mockDetectAndNpm(t,
|
||||
selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true},
|
||||
func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
func() *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
)
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, `"action": "updated"`) {
|
||||
t.Errorf("expected updated in JSON output, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateFetchError_JSON(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "", errors.New("network timeout") }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
|
||||
err := cmd.Execute()
|
||||
// cobra silences errors when RunE returns; we just check stdout
|
||||
_ = err
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, `"ok": false`) {
|
||||
t.Errorf("expected ok:false in JSON output, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "network timeout") {
|
||||
t.Errorf("expected 'network timeout' in JSON output, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateFetchError_Human(t *testing.T) {
|
||||
f, _, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "", errors.New("network timeout") }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
|
||||
// Suppress cobra's default error printing.
|
||||
cmd.SilenceErrors = true
|
||||
cmd.SilenceUsage = true
|
||||
|
||||
err := cmd.Execute()
|
||||
if err == nil {
|
||||
t.Fatal("expected non-nil error, got nil")
|
||||
}
|
||||
var exitErr *output.ExitError
|
||||
if !errors.As(err, &exitErr) {
|
||||
t.Fatalf("expected *output.ExitError, got %T: %v", err, err)
|
||||
}
|
||||
if exitErr.Code != output.ExitNetwork {
|
||||
t.Errorf("expected ExitNetwork (%d), got %d", output.ExitNetwork, exitErr.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateInvalidVersion_JSON(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "not-a-version", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
|
||||
_ = cmd.Execute()
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, "invalid version") {
|
||||
t.Errorf("expected 'invalid version' in JSON output, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateDevVersion_JSON(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "1.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "DEV" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
mockDetectAndNpm(t,
|
||||
selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true},
|
||||
func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
func() *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
)
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, `"action": "updated"`) {
|
||||
t.Errorf("expected updated in JSON output, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateNpmFail_JSON(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
|
||||
origNew := newUpdater
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
u := selfupdate.New()
|
||||
u.DetectOverride = func() selfupdate.DetectResult {
|
||||
return selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true}
|
||||
}
|
||||
u.NpmInstallOverride = func(version string) *selfupdate.NpmResult {
|
||||
r := &selfupdate.NpmResult{}
|
||||
fmt.Fprint(&r.Stderr, "EACCES: permission denied")
|
||||
r.Err = errors.New("npm install failed")
|
||||
return r
|
||||
}
|
||||
return u
|
||||
}
|
||||
defer func() { newUpdater = origNew }()
|
||||
|
||||
_ = cmd.Execute()
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, "permission denied") {
|
||||
t.Errorf("expected 'permission denied' in JSON output, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, `"hint"`) {
|
||||
t.Errorf("expected 'hint' field in JSON output, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateNpmFail_Human(t *testing.T) {
|
||||
f, _, stderr := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
|
||||
origNew := newUpdater
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
u := selfupdate.New()
|
||||
u.DetectOverride = func() selfupdate.DetectResult {
|
||||
return selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true}
|
||||
}
|
||||
u.NpmInstallOverride = func(version string) *selfupdate.NpmResult {
|
||||
r := &selfupdate.NpmResult{}
|
||||
fmt.Fprint(&r.Stderr, "EACCES: permission denied")
|
||||
r.Err = errors.New("npm install failed")
|
||||
return r
|
||||
}
|
||||
return u
|
||||
}
|
||||
defer func() { newUpdater = origNew }()
|
||||
|
||||
cmd.SilenceErrors = true
|
||||
cmd.SilenceUsage = true
|
||||
_ = cmd.Execute()
|
||||
out := stderr.String()
|
||||
if !strings.Contains(out, "Update failed") {
|
||||
t.Errorf("expected 'Update failed' in stderr, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "Permission denied") {
|
||||
t.Errorf("expected permission hint in stderr, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateNpmVerifyFail_JSON_NoRestoreHintWhenBackupUnavailable(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
|
||||
origNew := newUpdater
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
u := selfupdate.New()
|
||||
u.DetectOverride = func() selfupdate.DetectResult {
|
||||
return selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true}
|
||||
}
|
||||
u.NpmInstallOverride = func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} }
|
||||
u.VerifyOverride = func(string) error { return errors.New("bad binary") }
|
||||
u.RestoreAvailableOverride = func() bool { return false }
|
||||
u.SkillsUpdateOverride = func() *selfupdate.NpmResult {
|
||||
t.Fatal("skills update should not run when binary verification fails")
|
||||
return nil
|
||||
}
|
||||
return u
|
||||
}
|
||||
defer func() { newUpdater = origNew }()
|
||||
|
||||
err := cmd.Execute()
|
||||
if err == nil {
|
||||
t.Fatal("expected verification failure")
|
||||
}
|
||||
var exitErr *output.ExitError
|
||||
if !errors.As(err, &exitErr) {
|
||||
t.Fatalf("expected *output.ExitError, got %T: %v", err, err)
|
||||
}
|
||||
if exitErr.Code != output.ExitAPI {
|
||||
t.Fatalf("expected ExitAPI (%d), got %d", output.ExitAPI, exitErr.Code)
|
||||
}
|
||||
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, "automatic rollback is unavailable") {
|
||||
t.Errorf("expected unavailable rollback hint, got: %s", out)
|
||||
}
|
||||
if strings.Contains(out, "previous version has been restored") {
|
||||
t.Errorf("should not claim restore when no backup is available, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "npm install -g @larksuite/cli@2.0.0") {
|
||||
t.Errorf("expected manual reinstall command in hint, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateCheck_JSON_Npm(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json", "--check"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
mockDetect(t, selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true})
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, `"action": "update_available"`) {
|
||||
t.Errorf("expected update_available action, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, `"auto_update": true`) {
|
||||
t.Errorf("expected auto_update:true for npm, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "releases/tag/v2.0.0") {
|
||||
t.Errorf("expected version-pinned release URL, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "CHANGELOG") {
|
||||
t.Errorf("expected changelog URL, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateCheck_Human_Npm(t *testing.T) {
|
||||
f, _, stderr := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--check"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
mockDetect(t, selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true})
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stderr.String()
|
||||
if !strings.Contains(out, "Update available") {
|
||||
t.Errorf("expected 'Update available' in stderr, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "lark-cli update") {
|
||||
t.Errorf("expected 'lark-cli update' instruction for npm, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateCheck_Human_Manual(t *testing.T) {
|
||||
f, _, stderr := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--check"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
mockDetect(t, selfupdate.DetectResult{Method: selfupdate.InstallManual, ResolvedPath: "/usr/local/bin/lark-cli"})
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stderr.String()
|
||||
if !strings.Contains(out, "Update available") {
|
||||
t.Errorf("expected 'Update available' in stderr, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "manually") {
|
||||
t.Errorf("expected manual download instruction for non-npm, got: %s", out)
|
||||
}
|
||||
if strings.Contains(out, "lark-cli update` to install") {
|
||||
t.Errorf("should NOT suggest 'lark-cli update' for manual install, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateNpmNotFound_FallsBackToManual(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
// npm detected (node_modules in path) but npm binary not available
|
||||
mockDetect(t, selfupdate.DetectResult{
|
||||
Method: selfupdate.InstallNpm,
|
||||
ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli",
|
||||
NpmAvailable: false,
|
||||
})
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, `"action": "manual_required"`) {
|
||||
t.Errorf("expected manual_required when npm not found, got: %s", out)
|
||||
}
|
||||
// Must say "npm is not available", not generic "not installed via npm"
|
||||
if !strings.Contains(out, "npm is not available") {
|
||||
t.Errorf("expected 'npm is not available' reason when npm detected but missing, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReleaseURL(t *testing.T) {
|
||||
got := releaseURL("2.0.0")
|
||||
if got != "https://github.com/larksuite/cli/releases/tag/v2.0.0" {
|
||||
t.Errorf("expected version-pinned URL, got: %s", got)
|
||||
}
|
||||
got2 := releaseURL("v1.5.0")
|
||||
if got2 != "https://github.com/larksuite/cli/releases/tag/v1.5.0" {
|
||||
t.Errorf("expected no double v prefix, got: %s", got2)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPermissionHint(t *testing.T) {
|
||||
origOS := currentOS
|
||||
defer func() { currentOS = origOS }()
|
||||
|
||||
// Linux: EACCES should produce a hint with npm prefix guidance.
|
||||
currentOS = "linux"
|
||||
hint := permissionHint("EACCES: permission denied, access '/usr/local/lib'")
|
||||
if !strings.Contains(hint, "npm global prefix") {
|
||||
t.Errorf("expected npm prefix hint on linux, got: %s", hint)
|
||||
}
|
||||
if strings.Contains(hint, "sudo npm install -g") {
|
||||
t.Errorf("should not suggest raw sudo npm install, got: %s", hint)
|
||||
}
|
||||
|
||||
// Windows: EACCES hint is suppressed (no EACCES on Windows).
|
||||
currentOS = "windows"
|
||||
hint = permissionHint("EACCES: permission denied")
|
||||
if hint != "" {
|
||||
t.Errorf("expected empty hint on Windows, got: %s", hint)
|
||||
}
|
||||
|
||||
// Non-EACCES error: always empty.
|
||||
currentOS = "linux"
|
||||
if got := permissionHint("some other error"); got != "" {
|
||||
t.Errorf("expected empty hint for non-EACCES, got: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateWindows_NpmSuccess_JSON(t *testing.T) {
|
||||
// With the rename trick, Windows npm installs can now auto-update.
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
origOS := currentOS
|
||||
currentOS = osWindows
|
||||
defer func() { currentOS = origOS }()
|
||||
mockDetectAndNpm(t,
|
||||
selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: `C:\npm\node_modules\@larksuite\cli\bin\lark-cli.exe`, NpmAvailable: true},
|
||||
func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
func() *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
)
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, `"action": "updated"`) {
|
||||
t.Errorf("expected updated on Windows with rename trick, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateWindows_Check_JSON(t *testing.T) {
|
||||
// --check on Windows npm should report auto_update: true (rename trick available).
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json", "--check"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
origOS := currentOS
|
||||
currentOS = osWindows
|
||||
defer func() { currentOS = origOS }()
|
||||
mockDetect(t, selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: `C:\node_modules\@larksuite\cli\bin\lark-cli.exe`, NpmAvailable: true})
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
if !strings.Contains(out, `"auto_update": true`) {
|
||||
t.Errorf("expected auto_update:true on Windows (rename trick), got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateWindows_Symbols(t *testing.T) {
|
||||
origOS := currentOS
|
||||
defer func() { currentOS = origOS }()
|
||||
|
||||
currentOS = "windows"
|
||||
if symOK() != "[OK]" {
|
||||
t.Errorf("expected [OK] on Windows, got: %s", symOK())
|
||||
}
|
||||
if symFail() != "[FAIL]" {
|
||||
t.Errorf("expected [FAIL] on Windows, got: %s", symFail())
|
||||
}
|
||||
if symWarn() != "[WARN]" {
|
||||
t.Errorf("expected [WARN] on Windows, got: %s", symWarn())
|
||||
}
|
||||
if symArrow() != "->" {
|
||||
t.Errorf("expected -> on Windows, got: %s", symArrow())
|
||||
}
|
||||
|
||||
currentOS = "darwin"
|
||||
if symOK() != "\u2713" {
|
||||
t.Errorf("expected \u2713 on darwin, got: %s", symOK())
|
||||
}
|
||||
if symArrow() != "\u2192" {
|
||||
t.Errorf("expected \u2192 on darwin, got: %s", symArrow())
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateNpm_SkillsSuccess_JSON(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
mockDetectAndNpm(t,
|
||||
selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true},
|
||||
func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
func() *selfupdate.NpmResult { return &selfupdate.NpmResult{} },
|
||||
)
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
// Should NOT have skills_warning when skills succeed
|
||||
if strings.Contains(out, "skills_warning") {
|
||||
t.Errorf("expected no skills_warning on success, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateNpm_SkillsFail_JSON(t *testing.T) {
|
||||
f, stdout, _ := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{"--json"})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
|
||||
origNew := newUpdater
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
u := selfupdate.New()
|
||||
u.DetectOverride = func() selfupdate.DetectResult {
|
||||
return selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true}
|
||||
}
|
||||
u.NpmInstallOverride = func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} }
|
||||
u.VerifyOverride = func(string) error { return nil }
|
||||
// Skills update fails
|
||||
u.SkillsUpdateOverride = func() *selfupdate.NpmResult {
|
||||
r := &selfupdate.NpmResult{}
|
||||
r.Stderr.WriteString("npx: command not found")
|
||||
r.Err = fmt.Errorf("exit status 127")
|
||||
return r
|
||||
}
|
||||
return u
|
||||
}
|
||||
defer func() { newUpdater = origNew }()
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stdout.String()
|
||||
// CLI update should still succeed (ok:true)
|
||||
if !strings.Contains(out, `"ok": true`) {
|
||||
t.Errorf("expected ok:true despite skills failure, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, `"action": "updated"`) {
|
||||
t.Errorf("expected action:updated despite skills failure, got: %s", out)
|
||||
}
|
||||
// Should have skills_warning with detail
|
||||
if !strings.Contains(out, "skills_warning") {
|
||||
t.Errorf("expected skills_warning in output, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "skills_detail") {
|
||||
t.Errorf("expected skills_detail in output, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUpdateNpm_SkillsFail_Human(t *testing.T) {
|
||||
f, _, stderr := newTestFactory(t)
|
||||
cmd := NewCmdUpdate(f)
|
||||
cmd.SetArgs([]string{})
|
||||
|
||||
origFetch := fetchLatest
|
||||
fetchLatest = func() (string, error) { return "2.0.0", nil }
|
||||
defer func() { fetchLatest = origFetch }()
|
||||
origVersion := currentVersion
|
||||
currentVersion = func() string { return "1.0.0" }
|
||||
defer func() { currentVersion = origVersion }()
|
||||
|
||||
origNew := newUpdater
|
||||
newUpdater = func() *selfupdate.Updater {
|
||||
u := selfupdate.New()
|
||||
u.DetectOverride = func() selfupdate.DetectResult {
|
||||
return selfupdate.DetectResult{Method: selfupdate.InstallNpm, ResolvedPath: "/node_modules/@larksuite/cli/bin/lark-cli", NpmAvailable: true}
|
||||
}
|
||||
u.NpmInstallOverride = func(version string) *selfupdate.NpmResult { return &selfupdate.NpmResult{} }
|
||||
u.VerifyOverride = func(string) error { return nil }
|
||||
u.SkillsUpdateOverride = func() *selfupdate.NpmResult {
|
||||
r := &selfupdate.NpmResult{}
|
||||
r.Stderr.WriteString("npx: command not found")
|
||||
r.Err = fmt.Errorf("exit status 127")
|
||||
return r
|
||||
}
|
||||
return u
|
||||
}
|
||||
defer func() { newUpdater = origNew }()
|
||||
|
||||
err := cmd.Execute()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
out := stderr.String()
|
||||
// CLI update should still show success
|
||||
if !strings.Contains(out, "Successfully updated") {
|
||||
t.Errorf("expected CLI success message, got: %s", out)
|
||||
}
|
||||
// Skills warning should be shown
|
||||
if !strings.Contains(out, "Skills update failed") {
|
||||
t.Errorf("expected skills failure warning, got: %s", out)
|
||||
}
|
||||
if !strings.Contains(out, "npx -y skills add") {
|
||||
t.Errorf("expected manual skills command hint, got: %s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTruncate(t *testing.T) {
|
||||
long := strings.Repeat("x", 3000)
|
||||
got := selfupdate.Truncate(long, 2000)
|
||||
if len(got) != 2000 {
|
||||
t.Errorf("expected truncated length 2000, got %d", len(got))
|
||||
}
|
||||
|
||||
short := "hello"
|
||||
got2 := selfupdate.Truncate(short, 2000)
|
||||
if got2 != "hello" {
|
||||
t.Errorf("expected 'hello', got %q", got2)
|
||||
}
|
||||
}
|
||||
3
extension/credential/env/env_test.go
vendored
3
extension/credential/env/env_test.go
vendored
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package env
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package credential
|
||||
|
||||
import (
|
||||
|
||||
@@ -6,7 +6,6 @@ package fileio
|
||||
import (
|
||||
"context"
|
||||
"io"
|
||||
"io/fs"
|
||||
)
|
||||
|
||||
// Provider creates FileIO instances.
|
||||
@@ -47,7 +46,6 @@ type FileIO interface {
|
||||
type FileInfo interface {
|
||||
Size() int64
|
||||
IsDir() bool
|
||||
Mode() fs.FileMode
|
||||
}
|
||||
|
||||
// File is the interface returned by FileIO.Open.
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package auth
|
||||
|
||||
import (
|
||||
|
||||
@@ -215,51 +215,6 @@ func encodeParams(params map[string]interface{}) string {
|
||||
return vals.Encode()
|
||||
}
|
||||
|
||||
// PrintDryRunWithFile outputs a dry-run summary for file upload requests.
|
||||
// Instead of serializing the Formdata body, it shows file metadata.
|
||||
func PrintDryRunWithFile(w io.Writer, request client.RawApiRequest, config *core.CliConfig, format, fileField, filePath string, formFields any) error {
|
||||
dr := NewDryRunAPI()
|
||||
switch request.Method {
|
||||
case "POST":
|
||||
dr.POST(request.URL)
|
||||
case "PUT":
|
||||
dr.PUT(request.URL)
|
||||
case "PATCH":
|
||||
dr.PATCH(request.URL)
|
||||
case "DELETE":
|
||||
dr.DELETE(request.URL)
|
||||
default:
|
||||
dr.GET(request.URL)
|
||||
}
|
||||
if len(request.Params) > 0 {
|
||||
dr.Params(request.Params)
|
||||
}
|
||||
filePathDisplay := filePath
|
||||
if filePathDisplay == "" {
|
||||
filePathDisplay = "<stdin>"
|
||||
}
|
||||
fileInfo := map[string]any{
|
||||
"file": map[string]string{"field": fileField, "path": filePathDisplay},
|
||||
}
|
||||
if formFields != nil {
|
||||
fileInfo["form_fields"] = formFields
|
||||
}
|
||||
fileInfo["options"] = []string{"WithFileUpload"}
|
||||
dr.Body(fileInfo)
|
||||
dr.Set("as", string(request.As))
|
||||
dr.Set("appId", config.AppID)
|
||||
if config.UserOpenId != "" {
|
||||
dr.Set("userOpenId", config.UserOpenId)
|
||||
}
|
||||
fmt.Fprintln(w, "=== Dry Run ===")
|
||||
if format == "pretty" {
|
||||
fmt.Fprint(w, dr.Format())
|
||||
} else {
|
||||
output.PrintJson(w, dr)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PrintDryRun outputs a standardised dry-run summary using DryRunAPI.
|
||||
// When format is "pretty", outputs human-readable text; otherwise JSON.
|
||||
func PrintDryRun(w io.Writer, request client.RawApiRequest, config *core.CliConfig, format string) error {
|
||||
|
||||
@@ -1,130 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/internal/registry"
|
||||
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
|
||||
)
|
||||
|
||||
// DetectFileFields returns field names with type "file" in the method's requestBody.
|
||||
func DetectFileFields(method map[string]interface{}) []string {
|
||||
rb, _ := method["requestBody"].(map[string]interface{})
|
||||
var fields []string
|
||||
for name, field := range rb {
|
||||
f, _ := field.(map[string]interface{})
|
||||
if registry.GetStrFromMap(f, "type") == "file" {
|
||||
fields = append(fields, name)
|
||||
}
|
||||
}
|
||||
return fields
|
||||
}
|
||||
|
||||
// ParseFileFlag parses a --file flag value into its components.
|
||||
// The format is either "path" or "field=path". When no explicit "field="
|
||||
// prefix is present, defaultField is used as the field name.
|
||||
// A path of "-" indicates stdin; in that case filePath is empty and isStdin is true.
|
||||
func ParseFileFlag(raw, defaultField string) (fieldName, filePath string, isStdin bool) {
|
||||
if idx := strings.IndexByte(raw, '='); idx > 0 {
|
||||
fieldName = raw[:idx]
|
||||
filePath = raw[idx+1:]
|
||||
} else {
|
||||
fieldName = defaultField
|
||||
filePath = raw
|
||||
}
|
||||
if filePath == "-" {
|
||||
return fieldName, "", true
|
||||
}
|
||||
return fieldName, filePath, false
|
||||
}
|
||||
|
||||
// ValidateFileFlag checks mutual exclusion rules for the --file flag.
|
||||
// Returns nil if file is empty (flag not provided).
|
||||
func ValidateFileFlag(file, params, data, outputPath string, pageAll bool, httpMethod string) error {
|
||||
if file == "" {
|
||||
return nil
|
||||
}
|
||||
|
||||
_, filePath, isStdin := ParseFileFlag(file, "file")
|
||||
if !isStdin && filePath == "" {
|
||||
return output.ErrValidation("--file: empty file path")
|
||||
}
|
||||
|
||||
if outputPath != "" {
|
||||
return output.ErrValidation("--file and --output are mutually exclusive")
|
||||
}
|
||||
if pageAll {
|
||||
return output.ErrValidation("--file and --page-all are mutually exclusive")
|
||||
}
|
||||
if isStdin && data == "-" {
|
||||
return output.ErrValidation("--file and --data cannot both read from stdin")
|
||||
}
|
||||
if isStdin && params == "-" {
|
||||
return output.ErrValidation("--file and --params cannot both read from stdin")
|
||||
}
|
||||
|
||||
switch httpMethod {
|
||||
case "POST", "PUT", "PATCH", "DELETE":
|
||||
default:
|
||||
return output.ErrValidation("--file requires POST, PUT, PATCH, or DELETE method")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// FileUploadMeta holds file upload metadata for dry-run display.
|
||||
// Returned by request builders when dry-run mode skips actual file reading.
|
||||
type FileUploadMeta struct {
|
||||
FieldName string
|
||||
FilePath string
|
||||
FormFields any
|
||||
}
|
||||
|
||||
// BuildFormdata constructs a multipart form data payload for file upload.
|
||||
// If isStdin is true, the file content is read from stdin.
|
||||
// Top-level keys from dataJSON are added as text form fields.
|
||||
func BuildFormdata(fileIO fileio.FileIO, fieldName, filePath string, isStdin bool, stdin io.Reader, dataJSON any) (*larkcore.Formdata, error) {
|
||||
fd := larkcore.NewFormdata()
|
||||
|
||||
if isStdin {
|
||||
if stdin == nil {
|
||||
return nil, output.ErrValidation("--file: stdin is not available")
|
||||
}
|
||||
data, err := io.ReadAll(stdin)
|
||||
if err != nil {
|
||||
return nil, output.ErrValidation("--file: failed to read stdin: %v", err)
|
||||
}
|
||||
if len(data) == 0 {
|
||||
return nil, output.ErrValidation("--file: stdin is empty")
|
||||
}
|
||||
fd.AddFile(fieldName, bytes.NewReader(data))
|
||||
} else {
|
||||
f, err := fileIO.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, output.ErrValidation("cannot open file: %s", filePath)
|
||||
}
|
||||
defer f.Close()
|
||||
data, err := io.ReadAll(f)
|
||||
if err != nil {
|
||||
return nil, output.ErrValidation("--file: failed to read %s: %v", filePath, err)
|
||||
}
|
||||
fd.AddFile(fieldName, bytes.NewReader(data))
|
||||
}
|
||||
|
||||
// Add top-level JSON keys as text form fields.
|
||||
if m, ok := dataJSON.(map[string]any); ok {
|
||||
for k, v := range m {
|
||||
fd.AddField(k, fmt.Sprintf("%v", v))
|
||||
}
|
||||
}
|
||||
|
||||
return fd, nil
|
||||
}
|
||||
@@ -1,338 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/vfs/localfileio"
|
||||
)
|
||||
|
||||
func TestParseFileFlag(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
raw string
|
||||
defaultField string
|
||||
wantField string
|
||||
wantPath string
|
||||
wantStdin bool
|
||||
}{
|
||||
{
|
||||
name: "simple filename uses default field",
|
||||
raw: "photo.jpg",
|
||||
defaultField: "file",
|
||||
wantField: "file",
|
||||
wantPath: "photo.jpg",
|
||||
wantStdin: false,
|
||||
},
|
||||
{
|
||||
name: "simple filename with custom default",
|
||||
raw: "photo.jpg",
|
||||
defaultField: "image",
|
||||
wantField: "image",
|
||||
wantPath: "photo.jpg",
|
||||
wantStdin: false,
|
||||
},
|
||||
{
|
||||
name: "explicit field prefix",
|
||||
raw: "image=photo.jpg",
|
||||
defaultField: "file",
|
||||
wantField: "image",
|
||||
wantPath: "photo.jpg",
|
||||
wantStdin: false,
|
||||
},
|
||||
{
|
||||
name: "stdin bare",
|
||||
raw: "-",
|
||||
defaultField: "file",
|
||||
wantField: "file",
|
||||
wantPath: "",
|
||||
wantStdin: true,
|
||||
},
|
||||
{
|
||||
name: "stdin with field prefix",
|
||||
raw: "image=-",
|
||||
defaultField: "file",
|
||||
wantField: "image",
|
||||
wantPath: "",
|
||||
wantStdin: true,
|
||||
},
|
||||
{
|
||||
name: "path with equals sign (only first equals splits)",
|
||||
raw: "field=path/to/file=1.jpg",
|
||||
defaultField: "file",
|
||||
wantField: "field",
|
||||
wantPath: "path/to/file=1.jpg",
|
||||
wantStdin: false,
|
||||
},
|
||||
{
|
||||
name: "absolute path no prefix",
|
||||
raw: "/tmp/photo.jpg",
|
||||
defaultField: "file",
|
||||
wantField: "file",
|
||||
wantPath: "/tmp/photo.jpg",
|
||||
wantStdin: false,
|
||||
},
|
||||
{
|
||||
name: "absolute path with field prefix",
|
||||
raw: "image=/tmp/photo.jpg",
|
||||
defaultField: "file",
|
||||
wantField: "image",
|
||||
wantPath: "/tmp/photo.jpg",
|
||||
wantStdin: false,
|
||||
},
|
||||
{
|
||||
name: "empty field prefix falls through to default",
|
||||
raw: "=photo.jpg",
|
||||
defaultField: "file",
|
||||
wantField: "file",
|
||||
wantPath: "=photo.jpg",
|
||||
wantStdin: false,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
field, path, isStdin := ParseFileFlag(tt.raw, tt.defaultField)
|
||||
if field != tt.wantField {
|
||||
t.Errorf("field = %q, want %q", field, tt.wantField)
|
||||
}
|
||||
if path != tt.wantPath {
|
||||
t.Errorf("path = %q, want %q", path, tt.wantPath)
|
||||
}
|
||||
if isStdin != tt.wantStdin {
|
||||
t.Errorf("isStdin = %v, want %v", isStdin, tt.wantStdin)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateFileFlag(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
file string
|
||||
params string
|
||||
data string
|
||||
outputPath string
|
||||
pageAll bool
|
||||
httpMethod string
|
||||
wantErr string // empty means no error
|
||||
}{
|
||||
{
|
||||
name: "empty file is valid",
|
||||
file: "",
|
||||
httpMethod: "GET",
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "empty file path",
|
||||
file: "field=",
|
||||
httpMethod: "POST",
|
||||
wantErr: "--file: empty file path",
|
||||
},
|
||||
{
|
||||
name: "file with output",
|
||||
file: "photo.jpg",
|
||||
outputPath: "out.json",
|
||||
httpMethod: "POST",
|
||||
wantErr: "--file and --output are mutually exclusive",
|
||||
},
|
||||
{
|
||||
name: "file with page-all",
|
||||
file: "photo.jpg",
|
||||
pageAll: true,
|
||||
httpMethod: "POST",
|
||||
wantErr: "--file and --page-all are mutually exclusive",
|
||||
},
|
||||
{
|
||||
name: "stdin file with stdin data",
|
||||
file: "-",
|
||||
data: "-",
|
||||
httpMethod: "POST",
|
||||
wantErr: "--file and --data cannot both read from stdin",
|
||||
},
|
||||
{
|
||||
name: "stdin file with stdin params",
|
||||
file: "-",
|
||||
params: "-",
|
||||
httpMethod: "POST",
|
||||
wantErr: "--file and --params cannot both read from stdin",
|
||||
},
|
||||
{
|
||||
name: "file with GET method",
|
||||
file: "photo.jpg",
|
||||
httpMethod: "GET",
|
||||
wantErr: "--file requires POST, PUT, PATCH, or DELETE method",
|
||||
},
|
||||
{
|
||||
name: "file with POST method",
|
||||
file: "photo.jpg",
|
||||
httpMethod: "POST",
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "file with PUT method",
|
||||
file: "photo.jpg",
|
||||
httpMethod: "PUT",
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "file with PATCH method",
|
||||
file: "photo.jpg",
|
||||
httpMethod: "PATCH",
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "file with DELETE method",
|
||||
file: "photo.jpg",
|
||||
httpMethod: "DELETE",
|
||||
wantErr: "",
|
||||
},
|
||||
{
|
||||
name: "stdin with field prefix and data stdin",
|
||||
file: "image=-",
|
||||
data: "-",
|
||||
httpMethod: "POST",
|
||||
wantErr: "--file and --data cannot both read from stdin",
|
||||
},
|
||||
{
|
||||
name: "stdin with field prefix and params stdin",
|
||||
file: "image=-",
|
||||
params: "-",
|
||||
httpMethod: "POST",
|
||||
wantErr: "--file and --params cannot both read from stdin",
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := ValidateFileFlag(tt.file, tt.params, tt.data, tt.outputPath, tt.pageAll, tt.httpMethod)
|
||||
if tt.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Errorf("unexpected error: %v", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil {
|
||||
t.Fatalf("expected error containing %q, got nil", tt.wantErr)
|
||||
}
|
||||
if !strings.Contains(err.Error(), tt.wantErr) {
|
||||
t.Errorf("error = %q, want containing %q", err.Error(), tt.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildFormdata(t *testing.T) {
|
||||
fio := &localfileio.LocalFileIO{}
|
||||
|
||||
t.Run("stdin success", func(t *testing.T) {
|
||||
stdin := bytes.NewReader([]byte("file-content-here"))
|
||||
fd, err := BuildFormdata(fio, "file", "", true, stdin, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if fd == nil {
|
||||
t.Fatal("expected non-nil Formdata")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stdin nil reader", func(t *testing.T) {
|
||||
_, err := BuildFormdata(fio, "file", "", true, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for nil stdin")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "stdin is not available") {
|
||||
t.Errorf("error = %q, want containing %q", err.Error(), "stdin is not available")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("stdin empty", func(t *testing.T) {
|
||||
stdin := bytes.NewReader([]byte{})
|
||||
_, err := BuildFormdata(fio, "file", "", true, stdin, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty stdin")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "stdin is empty") {
|
||||
t.Errorf("error = %q, want containing %q", err.Error(), "stdin is empty")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("file open success", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
TestChdir(t, dir)
|
||||
|
||||
if err := os.WriteFile(filepath.Join(dir, "test.txt"), []byte("hello"), 0600); err != nil {
|
||||
t.Fatalf("failed to create test file: %v", err)
|
||||
}
|
||||
|
||||
fd, err := BuildFormdata(fio, "photo", "test.txt", false, nil, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if fd == nil {
|
||||
t.Fatal("expected non-nil Formdata")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("file not found", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
TestChdir(t, dir)
|
||||
|
||||
_, err := BuildFormdata(fio, "file", "nonexistent.txt", false, nil, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for missing file")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "cannot open file:") {
|
||||
t.Errorf("error = %q, want containing %q", err.Error(), "cannot open file:")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("dataJSON fields added", func(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
TestChdir(t, dir)
|
||||
|
||||
if err := os.WriteFile(filepath.Join(dir, "upload.bin"), []byte("data"), 0600); err != nil {
|
||||
t.Fatalf("failed to create test file: %v", err)
|
||||
}
|
||||
|
||||
dataJSON := map[string]any{
|
||||
"file_name": "report.pdf",
|
||||
"parent_type": "doc_image",
|
||||
"size": 1024,
|
||||
}
|
||||
|
||||
fd, err := BuildFormdata(fio, "file", "upload.bin", false, nil, dataJSON)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if fd == nil {
|
||||
t.Fatal("expected non-nil Formdata")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("dataJSON nil is fine", func(t *testing.T) {
|
||||
stdin := bytes.NewReader([]byte("content"))
|
||||
fd, err := BuildFormdata(fio, "file", "", true, stdin, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if fd == nil {
|
||||
t.Fatal("expected non-nil Formdata")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("dataJSON non-map is ignored", func(t *testing.T) {
|
||||
stdin := bytes.NewReader([]byte("content"))
|
||||
fd, err := BuildFormdata(fio, "file", "", true, stdin, "not-a-map")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if fd == nil {
|
||||
t.Fatal("expected non-nil Formdata")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -5,46 +5,35 @@ package cmdutil
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
)
|
||||
|
||||
// ParseOptionalBody parses --data JSON for methods that accept a request body.
|
||||
// Supports stdin (-) and single-quote stripping via ResolveInput.
|
||||
// Returns (nil, nil) if the method has no body or data is empty.
|
||||
func ParseOptionalBody(httpMethod, data string, stdin io.Reader) (interface{}, error) {
|
||||
func ParseOptionalBody(httpMethod, data string) (interface{}, error) {
|
||||
switch httpMethod {
|
||||
case "POST", "PUT", "PATCH", "DELETE":
|
||||
default:
|
||||
return nil, nil
|
||||
}
|
||||
resolved, err := ResolveInput(data, stdin)
|
||||
if err != nil {
|
||||
return nil, output.ErrValidation("--data: %s", err)
|
||||
}
|
||||
if resolved == "" {
|
||||
if data == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var body interface{}
|
||||
if err := json.Unmarshal([]byte(resolved), &body); err != nil {
|
||||
if err := json.Unmarshal([]byte(data), &body); err != nil {
|
||||
return nil, output.ErrValidation("--data invalid JSON format")
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
// ParseJSONMap parses a JSON string into a map. Returns an empty map if input is empty.
|
||||
// Supports stdin (-) and single-quote stripping via ResolveInput.
|
||||
func ParseJSONMap(input, label string, stdin io.Reader) (map[string]any, error) {
|
||||
resolved, err := ResolveInput(input, stdin)
|
||||
if err != nil {
|
||||
return nil, output.ErrValidation("%s: %s", label, err)
|
||||
}
|
||||
if resolved == "" {
|
||||
func ParseJSONMap(input, label string) (map[string]any, error) {
|
||||
if input == "" {
|
||||
return map[string]any{}, nil
|
||||
}
|
||||
var result map[string]any
|
||||
if err := json.Unmarshal([]byte(resolved), &result); err != nil {
|
||||
if err := json.Unmarshal([]byte(input), &result); err != nil {
|
||||
return nil, output.ErrValidation("%s invalid format, expected JSON object", label)
|
||||
}
|
||||
return result, nil
|
||||
|
||||
@@ -23,7 +23,7 @@ func TestParseOptionalBody(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ParseOptionalBody(tt.method, tt.data, nil)
|
||||
got, err := ParseOptionalBody(tt.method, tt.data)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("ParseOptionalBody() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
@@ -53,7 +53,7 @@ func TestParseJSONMap(t *testing.T) {
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ParseJSONMap(tt.input, tt.label, nil)
|
||||
got, err := ParseJSONMap(tt.input, tt.label)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("ParseJSONMap() error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
|
||||
@@ -1,46 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// ResolveInput resolves special input conventions for a raw flag value:
|
||||
// - "-" → read all bytes from stdin
|
||||
// - "'...'" → strip surrounding single quotes (Windows cmd.exe compatibility)
|
||||
// - other → return as-is
|
||||
//
|
||||
// This allows callers to bypass shell quoting issues (especially on Windows
|
||||
// PowerShell) by piping JSON via stdin instead of command-line arguments.
|
||||
func ResolveInput(raw string, stdin io.Reader) (string, error) {
|
||||
if raw == "" {
|
||||
return "", nil
|
||||
}
|
||||
|
||||
// stdin
|
||||
if raw == "-" {
|
||||
if stdin == nil {
|
||||
return "", fmt.Errorf("stdin is not available")
|
||||
}
|
||||
data, err := io.ReadAll(stdin)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("failed to read stdin: %w", err)
|
||||
}
|
||||
s := strings.TrimSpace(string(data))
|
||||
if s == "" {
|
||||
return "", fmt.Errorf("stdin is empty (did you forget to pipe input?)")
|
||||
}
|
||||
return s, nil
|
||||
}
|
||||
|
||||
// strip surrounding single quotes (Windows cmd.exe passes them literally)
|
||||
if len(raw) >= 2 && raw[0] == '\'' && raw[len(raw)-1] == '\'' {
|
||||
raw = raw[1 : len(raw)-1]
|
||||
}
|
||||
|
||||
return raw, nil
|
||||
}
|
||||
@@ -1,189 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestResolveInput_Stdin(t *testing.T) {
|
||||
got, err := ResolveInput("-", strings.NewReader(`{"key":"value"}`))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != `{"key":"value"}` {
|
||||
t.Errorf("got %q, want %q", got, `{"key":"value"}`)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveInput_Stdin_TrimNewline(t *testing.T) {
|
||||
got, err := ResolveInput("-", strings.NewReader("{\"k\":\"v\"}\n"))
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != `{"k":"v"}` {
|
||||
t.Errorf("got %q, want %q", got, `{"k":"v"}`)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveInput_Stdin_Empty(t *testing.T) {
|
||||
_, err := ResolveInput("-", strings.NewReader(""))
|
||||
if err == nil {
|
||||
t.Error("expected error for empty stdin")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "stdin is empty") {
|
||||
t.Errorf("expected 'stdin is empty' error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type errorReader struct{}
|
||||
|
||||
func (errorReader) Read([]byte) (int, error) { return 0, fmt.Errorf("disk failure") }
|
||||
|
||||
func TestResolveInput_Stdin_ReadError(t *testing.T) {
|
||||
_, err := ResolveInput("-", errorReader{})
|
||||
if err == nil || !strings.Contains(err.Error(), "failed to read stdin") {
|
||||
t.Errorf("expected read error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveInput_Stdin_WhitespaceOnly(t *testing.T) {
|
||||
_, err := ResolveInput("-", strings.NewReader(" \n\t\n "))
|
||||
if err == nil {
|
||||
t.Error("expected error for whitespace-only stdin")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveInput_Stdin_Nil(t *testing.T) {
|
||||
_, err := ResolveInput("-", nil)
|
||||
if err == nil {
|
||||
t.Error("expected error for nil stdin")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveInput_StripSingleQuotes(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
in string
|
||||
want string
|
||||
}{
|
||||
{"cmd.exe JSON", `'{"key":"value"}'`, `{"key":"value"}`},
|
||||
{"cmd.exe empty", `'{}'`, `{}`},
|
||||
{"no quotes", `{"key":"value"}`, `{"key":"value"}`},
|
||||
{"just quotes", `''`, ``},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ResolveInput(tt.in, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Errorf("got %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveInput_Empty(t *testing.T) {
|
||||
got, err := ResolveInput("", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != "" {
|
||||
t.Errorf("got %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveInput_PlainValue(t *testing.T) {
|
||||
got, err := ResolveInput(`{"already":"valid"}`, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != `{"already":"valid"}` {
|
||||
t.Errorf("got %q, want %q", got, `{"already":"valid"}`)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveInput_AtPrefixPassedThrough(t *testing.T) {
|
||||
// Without @file support, @-prefixed values are passed as-is
|
||||
got, err := ResolveInput("@something", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got != "@something" {
|
||||
t.Errorf("got %q, want %q", got, "@something")
|
||||
}
|
||||
}
|
||||
|
||||
// Integration: ResolveInput flows through ParseJSONMap correctly.
|
||||
func TestParseJSONMap_WithStdin(t *testing.T) {
|
||||
stdin := strings.NewReader(`{"message_id":"om_xxx","user_id_type":"open_id"}`)
|
||||
got, err := ParseJSONMap("-", "--params", stdin)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if len(got) != 2 {
|
||||
t.Errorf("got %d keys, want 2", len(got))
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseJSONMap_StripSingleQuotes_CmdExe(t *testing.T) {
|
||||
got, err := ParseJSONMap(`'{"key":"value"}'`, "--params", nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got["key"] != "value" {
|
||||
t.Errorf("got %v, want key=value", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseOptionalBody_WithStdin(t *testing.T) {
|
||||
stdin := strings.NewReader(`{"text":"hello"}`)
|
||||
got, err := ParseOptionalBody("POST", "-", stdin)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatal("expected non-nil body")
|
||||
}
|
||||
m, ok := got.(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("expected map, got %T", got)
|
||||
}
|
||||
if m["text"] != "hello" {
|
||||
t.Errorf("got %v, want text=hello", m)
|
||||
}
|
||||
}
|
||||
|
||||
// Simulates exact strings Go receives on different Windows shells.
|
||||
func TestParseJSONMap_WindowsShellScenarios(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
wantLen int
|
||||
wantErr bool
|
||||
}{
|
||||
{"bash: normal JSON", `{"a":"1","b":"2"}`, 2, false},
|
||||
{"cmd.exe: single-quoted", `'{"a":"1","b":"2"}'`, 2, false}, // strip ' fix
|
||||
{"PS 5.x: mangled", `{a:1,b:2}`, 0, true}, // unrecoverable
|
||||
{"PS 5.x: empty JSON OK", `{}`, 0, false}, // no inner "
|
||||
{"PS 7.3+: normal JSON", `{"a":"1"}`, 1, false}, // already fixed
|
||||
{"PS escaped: correct", `{"a":"1"}`, 1, false}, // after CommandLineToArgvW
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := ParseJSONMap(tt.input, "--params", nil)
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Errorf("error = %v, wantErr %v", err, tt.wantErr)
|
||||
return
|
||||
}
|
||||
if !tt.wantErr && len(got) != tt.wantLen {
|
||||
t.Errorf("got %d keys, want %d", len(got), tt.wantLen)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -240,12 +240,6 @@ func ResolveConfigFromMulti(raw *MultiAppConfig, kc keychain.KeychainAccess, pro
|
||||
}
|
||||
}
|
||||
|
||||
if err := ValidateSecretKeyMatch(app.AppId, app.AppSecret); err != nil {
|
||||
return nil, &ConfigError{Code: 2, Type: "config",
|
||||
Message: "appId and appSecret keychain key are out of sync",
|
||||
Hint: err.Error()}
|
||||
}
|
||||
|
||||
secret, err := ResolveSecretInput(app.AppSecret, kc)
|
||||
if err != nil {
|
||||
// If the error comes from the keychain, it will already be wrapped as an ExitError.
|
||||
|
||||
@@ -5,21 +5,9 @@ package core
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/keychain"
|
||||
)
|
||||
|
||||
// stubKeychain is a minimal KeychainAccess that always returns ErrNotFound.
|
||||
type stubKeychain struct{}
|
||||
|
||||
func (stubKeychain) Get(service, account string) (string, error) {
|
||||
return "", keychain.ErrNotFound
|
||||
}
|
||||
func (stubKeychain) Set(service, account, value string) error { return nil }
|
||||
func (stubKeychain) Remove(service, account string) error { return nil }
|
||||
|
||||
func TestAppConfig_LangSerialization(t *testing.T) {
|
||||
app := AppConfig{
|
||||
AppId: "cli_test", AppSecret: PlainSecret("secret"),
|
||||
@@ -85,85 +73,6 @@ func TestMultiAppConfig_RoundTrip(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveConfigFromMulti_RejectsSecretKeyMismatch(t *testing.T) {
|
||||
raw := &MultiAppConfig{
|
||||
Apps: []AppConfig{
|
||||
{
|
||||
AppId: "cli_new_app",
|
||||
AppSecret: SecretInput{Ref: &SecretRef{
|
||||
Source: "keychain",
|
||||
ID: "appsecret:cli_old_app",
|
||||
}},
|
||||
Brand: BrandFeishu,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, err := ResolveConfigFromMulti(raw, nil, "")
|
||||
if err == nil {
|
||||
t.Fatal("expected error for mismatched appId and appSecret keychain key")
|
||||
}
|
||||
var cfgErr *ConfigError
|
||||
if !errors.As(err, &cfgErr) {
|
||||
t.Fatalf("expected ConfigError, got %T: %v", err, err)
|
||||
}
|
||||
if cfgErr.Hint == "" {
|
||||
t.Error("expected non-empty hint in ConfigError")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveConfigFromMulti_AcceptsPlainSecret(t *testing.T) {
|
||||
raw := &MultiAppConfig{
|
||||
Apps: []AppConfig{
|
||||
{
|
||||
AppId: "cli_abc",
|
||||
AppSecret: PlainSecret("my-secret"),
|
||||
Brand: BrandFeishu,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
cfg, err := ResolveConfigFromMulti(raw, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if cfg.AppID != "cli_abc" {
|
||||
t.Errorf("AppID = %q, want %q", cfg.AppID, "cli_abc")
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveConfigFromMulti_MatchingKeychainRefPassesValidation(t *testing.T) {
|
||||
// Keychain ref matches appId, so validation passes.
|
||||
// The subsequent ResolveSecretInput will fail (no real keychain),
|
||||
// but that proves the mismatch check itself passed.
|
||||
raw := &MultiAppConfig{
|
||||
Apps: []AppConfig{
|
||||
{
|
||||
AppId: "cli_abc",
|
||||
AppSecret: SecretInput{Ref: &SecretRef{
|
||||
Source: "keychain",
|
||||
ID: "appsecret:cli_abc",
|
||||
}},
|
||||
Brand: BrandFeishu,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
_, err := ResolveConfigFromMulti(raw, stubKeychain{}, "")
|
||||
if err == nil {
|
||||
// stubKeychain returns ErrNotFound, so we expect a keychain error,
|
||||
// but NOT a mismatch error — that's the point of this test.
|
||||
t.Fatal("expected error (keychain entry not found), got nil")
|
||||
}
|
||||
// The error should come from keychain resolution, NOT from our mismatch check.
|
||||
var cfgErr *ConfigError
|
||||
if errors.As(err, &cfgErr) {
|
||||
if cfgErr.Message == "appId and appSecret keychain key are out of sync" {
|
||||
t.Fatal("error came from mismatch check, but keys should match")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveConfigFromMulti_DoesNotUseEnvProfileFallback(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_PROFILE", "missing")
|
||||
|
||||
|
||||
@@ -52,25 +52,6 @@ func ForStorage(appId string, input SecretInput, kc keychain.KeychainAccess) (Se
|
||||
return SecretInput{Ref: &SecretRef{Source: "keychain", ID: key}}, nil
|
||||
}
|
||||
|
||||
// ValidateSecretKeyMatch checks that the appSecret keychain key references the
|
||||
// expected appId. This prevents silent mismatches when config.json is edited by
|
||||
// hand (e.g. appId changed but appSecret.id still points to the old app).
|
||||
// Only applicable when appSecret is a keychain SecretRef; other forms are skipped.
|
||||
func ValidateSecretKeyMatch(appId string, secret SecretInput) error {
|
||||
if secret.Ref == nil || secret.Ref.Source != "keychain" {
|
||||
return nil
|
||||
}
|
||||
expected := secretAccountKey(appId)
|
||||
if secret.Ref.ID != expected {
|
||||
return fmt.Errorf(
|
||||
"appSecret keychain key %q does not match appId %q (expected %q); "+
|
||||
"please run `lark-cli config init` to reconfigure",
|
||||
secret.Ref.ID, appId, expected,
|
||||
)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RemoveSecretStore cleans up keychain entries when an app is removed.
|
||||
// Errors are intentionally ignored — cleanup is best-effort.
|
||||
func RemoveSecretStore(input SecretInput, kc keychain.KeychainAccess) {
|
||||
|
||||
@@ -1,59 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package core
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateSecretKeyMatch_KeychainMatches(t *testing.T) {
|
||||
secret := SecretInput{Ref: &SecretRef{Source: "keychain", ID: "appsecret:cli_abc123"}}
|
||||
if err := ValidateSecretKeyMatch("cli_abc123", secret); err != nil {
|
||||
t.Errorf("expected no error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSecretKeyMatch_KeychainMismatch(t *testing.T) {
|
||||
secret := SecretInput{Ref: &SecretRef{Source: "keychain", ID: "appsecret:cli_old_app"}}
|
||||
err := ValidateSecretKeyMatch("cli_new_app", secret)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for mismatched appId and keychain key")
|
||||
}
|
||||
// Verify the error message contains useful context
|
||||
msg := err.Error()
|
||||
for _, want := range []string{"cli_old_app", "cli_new_app", "appsecret:cli_new_app", "config init"} {
|
||||
if !strings.Contains(msg, want) {
|
||||
t.Errorf("error message missing %q: %s", want, msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSecretKeyMatch_PlainSecret_Skipped(t *testing.T) {
|
||||
secret := PlainSecret("some-secret")
|
||||
if err := ValidateSecretKeyMatch("cli_abc123", secret); err != nil {
|
||||
t.Errorf("plain secret should be skipped, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSecretKeyMatch_FileRef_Skipped(t *testing.T) {
|
||||
secret := SecretInput{Ref: &SecretRef{Source: "file", ID: "/tmp/secret.txt"}}
|
||||
if err := ValidateSecretKeyMatch("cli_abc123", secret); err != nil {
|
||||
t.Errorf("file ref should be skipped, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSecretKeyMatch_ZeroValue_Skipped(t *testing.T) {
|
||||
if err := ValidateSecretKeyMatch("cli_abc123", SecretInput{}); err != nil {
|
||||
t.Errorf("zero SecretInput should be skipped, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateSecretKeyMatch_EmptyAppId_Mismatch(t *testing.T) {
|
||||
secret := SecretInput{Ref: &SecretRef{Source: "keychain", ID: "appsecret:cli_abc123"}}
|
||||
err := ValidateSecretKeyMatch("", secret)
|
||||
if err == nil {
|
||||
t.Fatal("expected error when appId is empty but keychain key references a real app")
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package credential
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package credential
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package credential_test
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package credential
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package credential
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package keychain
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package keychain
|
||||
|
||||
import (
|
||||
|
||||
@@ -36,10 +36,10 @@ func wrapError(op string, err error) error {
|
||||
}
|
||||
|
||||
msg := fmt.Sprintf("keychain %s failed: %v", op, err)
|
||||
hint := "Check if the OS keychain/credential manager is locked or accessible. If running inside a sandbox or CI environment, please ensure the process has the necessary permissions to access the keychain, you can try running this outside the sandbox."
|
||||
hint := "Check if the OS keychain/credential manager is locked or accessible. If running inside a sandbox or CI environment, please ensure the process has the necessary permissions to access the keychain."
|
||||
|
||||
if errors.Is(err, errNotInitialized) {
|
||||
hint = "The keychain master key may have been cleaned up or deleted. If running inside a sandbox or CI environment, please ensure the process has the necessary permissions to access the keychain, you can try running this outside the sandbox. Otherwise, please reconfigure the CLI by running lark-cli config init."
|
||||
hint = "The keychain master key may have been cleaned up or deleted. Please reconfigure the CLI by running `lark-cli config init`."
|
||||
}
|
||||
|
||||
func() {
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//go:build darwin
|
||||
|
||||
package keychain
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//go:build linux
|
||||
|
||||
package keychain
|
||||
|
||||
@@ -564,54 +564,3 @@ func TestCollectScopesForProjects_NonexistentProject(t *testing.T) {
|
||||
t.Errorf("expected empty scopes for nonexistent project, got %d", len(scopes))
|
||||
}
|
||||
}
|
||||
|
||||
// --- auth_domain functions ---
|
||||
|
||||
func TestGetAuthDomain_Configured(t *testing.T) {
|
||||
// whiteboard has auth_domain: "docs" in service_descriptions.json
|
||||
if got := GetAuthDomain("whiteboard"); got != "docs" {
|
||||
t.Errorf("GetAuthDomain(whiteboard) = %q, want %q", got, "docs")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAuthDomain_NotConfigured(t *testing.T) {
|
||||
if got := GetAuthDomain("calendar"); got != "" {
|
||||
t.Errorf("GetAuthDomain(calendar) = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAuthDomain_Unknown(t *testing.T) {
|
||||
if got := GetAuthDomain("nonexistent_xyz"); got != "" {
|
||||
t.Errorf("GetAuthDomain(nonexistent_xyz) = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHasAuthDomain(t *testing.T) {
|
||||
if !HasAuthDomain("whiteboard") {
|
||||
t.Error("HasAuthDomain(whiteboard) = false, want true")
|
||||
}
|
||||
if HasAuthDomain("calendar") {
|
||||
t.Error("HasAuthDomain(calendar) = true, want false")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAuthChildren(t *testing.T) {
|
||||
children := GetAuthChildren("docs")
|
||||
found := false
|
||||
for _, c := range children {
|
||||
if c == "whiteboard" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("GetAuthChildren(docs) = %v, want to contain 'whiteboard'", children)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetAuthChildren_NoChildren(t *testing.T) {
|
||||
children := GetAuthChildren("calendar")
|
||||
if len(children) != 0 {
|
||||
t.Errorf("GetAuthChildren(calendar) = %v, want empty", children)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,7 +4,8 @@
|
||||
"im:message:send_as_bot": 1,
|
||||
"calendar:calendar:read": 70,
|
||||
"calendar:calendar:readonly": 1,
|
||||
"sheets:spreadsheet:write_only": 60,
|
||||
"sheets:spreadsheet:write_only": 45,
|
||||
"docs:document.comment:delete": 60,
|
||||
"drive:drive:readonly": 1,
|
||||
"docs:doc:readonly": 1,
|
||||
"sheets:spreadsheet:readonly": 1,
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -19,9 +19,8 @@ type serviceDescLocale struct {
|
||||
|
||||
// serviceDescEntry holds bilingual descriptions for a service domain.
|
||||
type serviceDescEntry struct {
|
||||
En serviceDescLocale `json:"en"`
|
||||
Zh serviceDescLocale `json:"zh"`
|
||||
AuthDomain string `json:"auth_domain,omitempty"`
|
||||
En serviceDescLocale `json:"en"`
|
||||
Zh serviceDescLocale `json:"zh"`
|
||||
}
|
||||
|
||||
var serviceDescMap map[string]serviceDescEntry
|
||||
@@ -77,31 +76,3 @@ func GetServiceDetailDescription(name, lang string) string {
|
||||
}
|
||||
return loc.Description
|
||||
}
|
||||
|
||||
// GetAuthDomain returns the auth_domain for a service, or "" if not set.
|
||||
// When auth_domain is set, the service's scopes are collected under the
|
||||
// parent domain during auth login.
|
||||
func GetAuthDomain(service string) string {
|
||||
m := loadServiceDescriptions()
|
||||
if entry, ok := m[service]; ok {
|
||||
return entry.AuthDomain
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
// HasAuthDomain reports whether the service has an auth_domain configured.
|
||||
func HasAuthDomain(service string) bool {
|
||||
return GetAuthDomain(service) != ""
|
||||
}
|
||||
|
||||
// GetAuthChildren returns all service names whose auth_domain equals parent.
|
||||
func GetAuthChildren(parent string) []string {
|
||||
m := loadServiceDescriptions()
|
||||
var children []string
|
||||
for name, entry := range m {
|
||||
if entry.AuthDomain == parent {
|
||||
children = append(children, name)
|
||||
}
|
||||
}
|
||||
return children
|
||||
}
|
||||
|
||||
@@ -53,8 +53,7 @@
|
||||
},
|
||||
"whiteboard": {
|
||||
"en": { "title": "Whiteboard", "description": "Create and edit boards" },
|
||||
"zh": { "title": "画板", "description": "画板创建、编辑" },
|
||||
"auth_domain": "docs"
|
||||
"zh": { "title": "画板", "description": "画板创建、编辑" }
|
||||
},
|
||||
"wiki": {
|
||||
"en": { "title": "Wiki", "description": "Wiki space and node management" },
|
||||
|
||||
@@ -1,231 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package selfupdate handles installation detection, npm-based updates,
|
||||
// skills updates, and platform-specific binary replacement for the CLI
|
||||
// self-update flow.
|
||||
package selfupdate
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"fmt"
|
||||
"os/exec"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
)
|
||||
|
||||
// InstallMethod describes how the CLI was installed.
|
||||
type InstallMethod int
|
||||
|
||||
const (
|
||||
InstallNpm InstallMethod = iota
|
||||
InstallManual
|
||||
)
|
||||
|
||||
const (
|
||||
NpmPackage = "@larksuite/cli"
|
||||
)
|
||||
|
||||
const (
|
||||
npmInstallTimeout = 10 * time.Minute
|
||||
skillsUpdateTimeout = 2 * time.Minute
|
||||
verifyTimeout = 10 * time.Second
|
||||
)
|
||||
|
||||
// DetectResult holds installation detection results.
|
||||
type DetectResult struct {
|
||||
Method InstallMethod
|
||||
ResolvedPath string
|
||||
NpmAvailable bool
|
||||
}
|
||||
|
||||
// CanAutoUpdate returns true if the CLI can update itself automatically.
|
||||
func (d DetectResult) CanAutoUpdate() bool {
|
||||
return d.Method == InstallNpm && d.NpmAvailable
|
||||
}
|
||||
|
||||
// ManualReason returns a human-readable explanation of why auto-update is unavailable.
|
||||
func (d DetectResult) ManualReason() string {
|
||||
if d.Method == InstallNpm && !d.NpmAvailable {
|
||||
return "installed via npm, but npm is not available in PATH"
|
||||
}
|
||||
return "not installed via npm"
|
||||
}
|
||||
|
||||
// NpmResult holds the result of an npm install or skills update execution.
|
||||
type NpmResult struct {
|
||||
Stdout bytes.Buffer
|
||||
Stderr bytes.Buffer
|
||||
Err error
|
||||
}
|
||||
|
||||
// CombinedOutput returns stdout + stderr concatenated.
|
||||
func (r *NpmResult) CombinedOutput() string {
|
||||
return r.Stdout.String() + r.Stderr.String()
|
||||
}
|
||||
|
||||
// Updater manages self-update operations.
|
||||
// Platform-specific methods (PrepareSelfReplace, CleanupStaleFiles)
|
||||
// are in updater_unix.go and updater_windows.go.
|
||||
//
|
||||
// Override DetectOverride / NpmInstallOverride / SkillsUpdateOverride / VerifyOverride
|
||||
// / RestoreAvailableOverride for testing.
|
||||
type Updater struct {
|
||||
DetectOverride func() DetectResult
|
||||
NpmInstallOverride func(version string) *NpmResult
|
||||
SkillsUpdateOverride func() *NpmResult
|
||||
VerifyOverride func(expectedVersion string) error
|
||||
RestoreAvailableOverride func() bool
|
||||
|
||||
// backupCreated is set to true by PrepareSelfReplace (Windows) when the
|
||||
// running binary is successfully renamed to .old. Used by
|
||||
// CanRestorePreviousVersion to report whether rollback is possible.
|
||||
backupCreated bool
|
||||
}
|
||||
|
||||
// New creates an Updater with default (real) behavior.
|
||||
func New() *Updater { return &Updater{} }
|
||||
|
||||
// DetectInstallMethod determines how the CLI was installed and whether
|
||||
// npm is available for auto-update.
|
||||
func (u *Updater) DetectInstallMethod() DetectResult {
|
||||
if u.DetectOverride != nil {
|
||||
return u.DetectOverride()
|
||||
}
|
||||
exe, err := vfs.Executable()
|
||||
if err != nil {
|
||||
return DetectResult{Method: InstallManual}
|
||||
}
|
||||
resolved, err := vfs.EvalSymlinks(exe)
|
||||
if err != nil {
|
||||
return DetectResult{Method: InstallManual, ResolvedPath: exe}
|
||||
}
|
||||
|
||||
method := InstallManual
|
||||
if strings.Contains(resolved, "node_modules") {
|
||||
method = InstallNpm
|
||||
}
|
||||
|
||||
npmAvailable := false
|
||||
if method == InstallNpm {
|
||||
if _, err := exec.LookPath("npm"); err == nil {
|
||||
npmAvailable = true
|
||||
}
|
||||
}
|
||||
|
||||
return DetectResult{
|
||||
Method: method,
|
||||
ResolvedPath: resolved,
|
||||
NpmAvailable: npmAvailable,
|
||||
}
|
||||
}
|
||||
|
||||
// RunNpmInstall executes npm install -g @larksuite/cli@<version>.
|
||||
func (u *Updater) RunNpmInstall(version string) *NpmResult {
|
||||
if u.NpmInstallOverride != nil {
|
||||
return u.NpmInstallOverride(version)
|
||||
}
|
||||
r := &NpmResult{}
|
||||
npmPath, err := exec.LookPath("npm")
|
||||
if err != nil {
|
||||
r.Err = fmt.Errorf("npm not found in PATH: %w", err)
|
||||
return r
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), npmInstallTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, npmPath, "install", "-g", NpmPackage+"@"+version)
|
||||
cmd.Stdout = &r.Stdout
|
||||
cmd.Stderr = &r.Stderr
|
||||
r.Err = cmd.Run()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
r.Err = fmt.Errorf("npm install timed out after %s", npmInstallTimeout)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// RunSkillsUpdate executes npx -y skills add larksuite/cli -g -y.
|
||||
func (u *Updater) RunSkillsUpdate() *NpmResult {
|
||||
if u.SkillsUpdateOverride != nil {
|
||||
return u.SkillsUpdateOverride()
|
||||
}
|
||||
r := &NpmResult{}
|
||||
npxPath, err := exec.LookPath("npx")
|
||||
if err != nil {
|
||||
r.Err = fmt.Errorf("npx not found in PATH: %w", err)
|
||||
return r
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), skillsUpdateTimeout)
|
||||
defer cancel()
|
||||
cmd := exec.CommandContext(ctx, npxPath, "-y", "skills", "add", "larksuite/cli", "-g", "-y")
|
||||
cmd.Stdout = &r.Stdout
|
||||
cmd.Stderr = &r.Stderr
|
||||
r.Err = cmd.Run()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
r.Err = fmt.Errorf("skills update timed out after %s", skillsUpdateTimeout)
|
||||
}
|
||||
return r
|
||||
}
|
||||
|
||||
// VerifyBinary checks that the installed binary reports the expected version
|
||||
// by running "lark-cli --version" and comparing the version token exactly.
|
||||
// Output format is "lark-cli version X.Y.Z"; the last field is extracted and
|
||||
// compared against expectedVersion (both stripped of any "v" prefix).
|
||||
func (u *Updater) VerifyBinary(expectedVersion string) error {
|
||||
if u.VerifyOverride != nil {
|
||||
return u.VerifyOverride(expectedVersion)
|
||||
}
|
||||
// Prefer the current executable path (what the user actually launched).
|
||||
// Use Executable() directly without EvalSymlinks — after npm install the
|
||||
// symlink target may have changed, but the path itself is still valid for
|
||||
// execution. Fall back to LookPath only if Executable() fails entirely.
|
||||
exe, err := vfs.Executable()
|
||||
if err != nil {
|
||||
exe, err = exec.LookPath("lark-cli")
|
||||
if err != nil {
|
||||
return fmt.Errorf("cannot locate binary: %w", err)
|
||||
}
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), verifyTimeout)
|
||||
defer cancel()
|
||||
out, err := exec.CommandContext(ctx, exe, "--version").Output()
|
||||
if ctx.Err() == context.DeadlineExceeded {
|
||||
return fmt.Errorf("binary verification timed out after %s", verifyTimeout)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("binary not executable: %w", err)
|
||||
}
|
||||
fields := strings.Fields(strings.TrimSpace(string(out)))
|
||||
if len(fields) == 0 {
|
||||
return fmt.Errorf("empty version output")
|
||||
}
|
||||
actual := strings.TrimPrefix(fields[len(fields)-1], "v")
|
||||
expected := strings.TrimPrefix(expectedVersion, "v")
|
||||
if actual != expected {
|
||||
return fmt.Errorf("expected version %s, got %q", expectedVersion, actual)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Truncate returns the last maxLen runes of s.
|
||||
func Truncate(s string, maxLen int) string {
|
||||
if maxLen <= 0 {
|
||||
return ""
|
||||
}
|
||||
r := []rune(s)
|
||||
if len(r) <= maxLen {
|
||||
return s
|
||||
}
|
||||
return string(r[len(r)-maxLen:])
|
||||
}
|
||||
|
||||
// resolveExe returns the resolved path of the current running binary.
|
||||
func (u *Updater) resolveExe() (string, error) {
|
||||
exe, err := vfs.Executable()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return vfs.EvalSymlinks(exe)
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package selfupdate
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
)
|
||||
|
||||
type executableTestFS struct {
|
||||
vfs.OsFs
|
||||
exe string
|
||||
}
|
||||
|
||||
func (f executableTestFS) Executable() (string, error) { return f.exe, nil }
|
||||
|
||||
func TestResolveExe(t *testing.T) {
|
||||
u := New()
|
||||
p, err := u.resolveExe()
|
||||
if err != nil {
|
||||
t.Fatalf("resolveExe() error: %v", err)
|
||||
}
|
||||
if !filepath.IsAbs(p) {
|
||||
t.Errorf("expected absolute path, got: %s", p)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPrepareSelfReplace_ReturnsNoError(t *testing.T) {
|
||||
u := New()
|
||||
restore, err := u.PrepareSelfReplace()
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
restore()
|
||||
}
|
||||
|
||||
func TestCleanupStaleFiles_NoPanic(t *testing.T) {
|
||||
u := New()
|
||||
u.CleanupStaleFiles()
|
||||
}
|
||||
|
||||
func TestVerifyBinaryChecksVersion(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("uses a POSIX shell script")
|
||||
}
|
||||
|
||||
dir := t.TempDir()
|
||||
exe := filepath.Join(dir, "lark-cli")
|
||||
// Script prints version string matching real CLI format when --version is passed.
|
||||
script := "#!/bin/sh\nif [ \"$1\" = \"--version\" ]; then echo \"lark-cli version 2.0.0\"; exit 0; fi\nexit 12\n"
|
||||
if err := os.WriteFile(exe, []byte(script), 0755); err != nil {
|
||||
t.Fatalf("write test binary: %v", err)
|
||||
}
|
||||
|
||||
// Mock vfs.Executable to return our test script, matching VerifyBinary's
|
||||
// primary lookup path. Also prepend to PATH for the LookPath fallback.
|
||||
origFS := vfs.DefaultFS
|
||||
vfs.DefaultFS = executableTestFS{OsFs: vfs.OsFs{}, exe: exe}
|
||||
t.Cleanup(func() { vfs.DefaultFS = origFS })
|
||||
|
||||
origPath := os.Getenv("PATH")
|
||||
t.Setenv("PATH", dir+string(os.PathListSeparator)+origPath)
|
||||
|
||||
// Matching version → success.
|
||||
if err := New().VerifyBinary("2.0.0"); err != nil {
|
||||
t.Fatalf("VerifyBinary(matching) error = %v, want nil", err)
|
||||
}
|
||||
|
||||
// Mismatched version → error.
|
||||
if err := New().VerifyBinary("3.0.0"); err == nil {
|
||||
t.Fatal("VerifyBinary(mismatched) expected error, got nil")
|
||||
}
|
||||
|
||||
// Substring of actual version must not match (e.g. "0.0" is in "2.0.0").
|
||||
if err := New().VerifyBinary("0.0"); err == nil {
|
||||
t.Fatal("VerifyBinary(substring) expected error, got nil")
|
||||
}
|
||||
|
||||
// Version that is a prefix of actual must not match (e.g. "2.0.0" in "12.0.0").
|
||||
// Binary reports "2.0.0", asking for "12.0.0" must fail.
|
||||
if err := New().VerifyBinary("12.0.0"); err == nil {
|
||||
t.Fatal("VerifyBinary(prefix-mismatch) expected error, got nil")
|
||||
}
|
||||
}
|
||||
@@ -1,24 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//go:build !windows
|
||||
|
||||
package selfupdate
|
||||
|
||||
// PrepareSelfReplace is a no-op on Unix.
|
||||
// Unix allows overwriting a running executable via inode semantics.
|
||||
func (u *Updater) PrepareSelfReplace() (restore func(), err error) {
|
||||
return func() {}, nil
|
||||
}
|
||||
|
||||
// CleanupStaleFiles is a no-op on Unix (no .old files are created).
|
||||
func (u *Updater) CleanupStaleFiles() {}
|
||||
|
||||
// CanRestorePreviousVersion reports whether PrepareSelfReplace created a
|
||||
// restorable backup for the current update attempt.
|
||||
func (u *Updater) CanRestorePreviousVersion() bool {
|
||||
if u.RestoreAvailableOverride != nil {
|
||||
return u.RestoreAvailableOverride()
|
||||
}
|
||||
return u.backupCreated
|
||||
}
|
||||
@@ -1,87 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//go:build windows
|
||||
|
||||
package selfupdate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
)
|
||||
|
||||
// PrepareSelfReplace renames the running .exe to .old so that npm's
|
||||
// postinstall script can write the new binary without hitting EBUSY.
|
||||
// Returns a restore function that undoes the rename on failure.
|
||||
func (u *Updater) PrepareSelfReplace() (restore func(), err error) {
|
||||
noop := func() {}
|
||||
|
||||
exe, err := u.resolveExe()
|
||||
if err != nil {
|
||||
return noop, nil // best-effort; don't block update
|
||||
}
|
||||
|
||||
oldPath := exe + ".old"
|
||||
|
||||
// Clean up stale .old from a previous upgrade.
|
||||
vfs.Remove(oldPath)
|
||||
|
||||
// Rename running.exe → running.exe.old (Windows allows rename of locked files).
|
||||
if err := vfs.Rename(exe, oldPath); err != nil {
|
||||
return noop, fmt.Errorf("cannot rename binary for update: %w", err)
|
||||
}
|
||||
u.backupCreated = true
|
||||
|
||||
// Restore: move .old back to the original path.
|
||||
// Guard with Stat: run.js may have already recovered .old on its own
|
||||
// during VerifyBinary; if .old is gone, skip to avoid deleting the
|
||||
// only working binary.
|
||||
// On any failure, clear backupCreated so CanRestorePreviousVersion
|
||||
// reports the real outcome instead of claiming success.
|
||||
restore = func() {
|
||||
if _, err := vfs.Stat(oldPath); err != nil {
|
||||
u.backupCreated = false
|
||||
return
|
||||
}
|
||||
vfs.Remove(exe)
|
||||
if err := vfs.Rename(oldPath, exe); err != nil {
|
||||
u.backupCreated = false
|
||||
}
|
||||
}
|
||||
|
||||
return restore, nil
|
||||
}
|
||||
|
||||
// CleanupStaleFiles removes leftover .old files from previous upgrades.
|
||||
// If the original binary is missing but .old exists (crash mid-update),
|
||||
// it restores the .old to recover the installation.
|
||||
func (u *Updater) CleanupStaleFiles() {
|
||||
exe, err := u.resolveExe()
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
oldPath := exe + ".old"
|
||||
|
||||
if _, err := vfs.Stat(oldPath); err != nil {
|
||||
return // no .old file
|
||||
}
|
||||
|
||||
if _, err := vfs.Stat(exe); err != nil {
|
||||
// Original missing, .old exists — restore to recover.
|
||||
vfs.Rename(oldPath, exe)
|
||||
return
|
||||
}
|
||||
|
||||
// Both exist — .old is stale, clean up.
|
||||
vfs.Remove(oldPath)
|
||||
}
|
||||
|
||||
// CanRestorePreviousVersion reports whether PrepareSelfReplace created a
|
||||
// restorable backup for the current update attempt.
|
||||
func (u *Updater) CanRestorePreviousVersion() bool {
|
||||
if u.RestoreAvailableOverride != nil {
|
||||
return u.RestoreAvailableOverride()
|
||||
}
|
||||
return u.backupCreated
|
||||
}
|
||||
@@ -218,8 +218,8 @@ func fetchLatestVersion() (string, error) {
|
||||
// is considered newer — an unparseable local version is assumed outdated.
|
||||
// When a cannot be parsed, returns false (can't confirm it's newer).
|
||||
func IsNewer(a, b string) bool {
|
||||
ap := parseVersionDetail(a)
|
||||
bp := parseVersionDetail(b)
|
||||
ap := ParseVersion(a)
|
||||
bp := ParseVersion(b)
|
||||
if ap == nil {
|
||||
return false // can't confirm remote is newer
|
||||
}
|
||||
@@ -227,59 +227,28 @@ func IsNewer(a, b string) bool {
|
||||
return true // local version unparseable → assume outdated
|
||||
}
|
||||
for i := 0; i < 3; i++ {
|
||||
if ap.core[i] > bp.core[i] {
|
||||
if ap[i] > bp[i] {
|
||||
return true
|
||||
}
|
||||
if ap.core[i] < bp.core[i] {
|
||||
if ap[i] < bp[i] {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return comparePrerelease(ap.prerelease, bp.prerelease) > 0
|
||||
return false
|
||||
}
|
||||
|
||||
// ParseVersion parses "X.Y.Z" (with optional "v" prefix and pre-release suffix)
|
||||
// into [major, minor, patch]. Returns nil on invalid input.
|
||||
func ParseVersion(v string) []int {
|
||||
parsed := parseVersionDetail(v)
|
||||
if parsed == nil {
|
||||
return nil
|
||||
}
|
||||
return []int{parsed.core[0], parsed.core[1], parsed.core[2]}
|
||||
}
|
||||
|
||||
type parsedVersion struct {
|
||||
core [3]int
|
||||
prerelease string
|
||||
}
|
||||
|
||||
// validPrerelease matches semver pre-release identifiers (dot-separated).
|
||||
// Each identifier is either: "0", a non-zero-leading numeric, or alphanumeric with at least one letter/hyphen.
|
||||
// Rejects empty identifiers ("1.0.0-"), leading-zero numerics ("1.0.0-01"), etc.
|
||||
var validPrerelease = regexp.MustCompile(
|
||||
`^(?:0|[1-9]\d*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*)` +
|
||||
`(?:\.(?:0|[1-9]\d*|[0-9]*[a-zA-Z-][0-9a-zA-Z-]*))*$`)
|
||||
|
||||
func parseVersionDetail(v string) *parsedVersion {
|
||||
v = strings.TrimPrefix(v, "v")
|
||||
if idx := strings.Index(v, "+"); idx >= 0 {
|
||||
v = v[:idx]
|
||||
}
|
||||
prerelease := ""
|
||||
if idx := strings.Index(v, "-"); idx >= 0 {
|
||||
prerelease = v[idx+1:]
|
||||
v = v[:idx]
|
||||
if prerelease == "" || !validPrerelease.MatchString(prerelease) {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
parts := strings.SplitN(v, ".", 3)
|
||||
if len(parts) != 3 {
|
||||
return nil
|
||||
}
|
||||
var nums [3]int
|
||||
nums := make([]int, 3)
|
||||
for i, p := range parts {
|
||||
if len(p) > 1 && p[0] == '0' {
|
||||
return nil // leading zero in core part (e.g. "01.0.0")
|
||||
if idx := strings.IndexAny(p, "-+"); idx >= 0 {
|
||||
p = p[:idx]
|
||||
}
|
||||
n, err := strconv.Atoi(p)
|
||||
if err != nil {
|
||||
@@ -287,56 +256,5 @@ func parseVersionDetail(v string) *parsedVersion {
|
||||
}
|
||||
nums[i] = n
|
||||
}
|
||||
return &parsedVersion{core: nums, prerelease: prerelease}
|
||||
}
|
||||
|
||||
func comparePrerelease(a, b string) int {
|
||||
if a == "" && b == "" {
|
||||
return 0
|
||||
}
|
||||
if a == "" {
|
||||
return 1
|
||||
}
|
||||
if b == "" {
|
||||
return -1
|
||||
}
|
||||
ap := strings.Split(a, ".")
|
||||
bp := strings.Split(b, ".")
|
||||
for i := 0; i < len(ap) && i < len(bp); i++ {
|
||||
cmp := comparePrereleaseIdentifier(ap[i], bp[i])
|
||||
if cmp != 0 {
|
||||
return cmp
|
||||
}
|
||||
}
|
||||
switch {
|
||||
case len(ap) > len(bp):
|
||||
return 1
|
||||
case len(ap) < len(bp):
|
||||
return -1
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func comparePrereleaseIdentifier(a, b string) int {
|
||||
an, aErr := strconv.Atoi(a)
|
||||
bn, bErr := strconv.Atoi(b)
|
||||
aNumeric := aErr == nil
|
||||
bNumeric := bErr == nil
|
||||
switch {
|
||||
case aNumeric && bNumeric:
|
||||
if an > bn {
|
||||
return 1
|
||||
}
|
||||
if an < bn {
|
||||
return -1
|
||||
}
|
||||
return 0
|
||||
case aNumeric:
|
||||
return -1
|
||||
case bNumeric:
|
||||
return 1
|
||||
default:
|
||||
return strings.Compare(a, b)
|
||||
}
|
||||
return nums
|
||||
}
|
||||
|
||||
@@ -56,9 +56,6 @@ func TestIsNewer(t *testing.T) {
|
||||
{"1.0.0", "9b933f1", true}, // bare commit hash → assume outdated
|
||||
{"", "1.0.0", false}, // empty remote → false
|
||||
{"1.1.0", "v1.0.0-12-g9b933f1-dirty", true}, // git describe: 1.1.0 > 1.0.0
|
||||
{"1.0.0", "1.0.0-rc.1", true}, // stable release > prerelease
|
||||
{"1.0.0-rc.2", "1.0.0-rc.1", true}, // prerelease identifiers are ordered
|
||||
{"1.0.0-rc.1", "1.0.0", false}, // prerelease < stable release
|
||||
}
|
||||
for _, tt := range tests {
|
||||
got := IsNewer(tt.a, tt.b)
|
||||
@@ -77,16 +74,6 @@ func TestParseVersion(t *testing.T) {
|
||||
{"v1.2.3", []int{1, 2, 3}},
|
||||
{"0.0.1", []int{0, 0, 1}},
|
||||
{"1.0.0-beta.1", []int{1, 0, 0}},
|
||||
{"1.0.0-rc.1", []int{1, 0, 0}},
|
||||
{"1.0.0-0", []int{1, 0, 0}},
|
||||
{"1.0.0+build.123", []int{1, 0, 0}},
|
||||
{"1.0.0-beta.1+build", []int{1, 0, 0}},
|
||||
{"1.0.0-", nil}, // empty pre-release
|
||||
{"1.0.0-01", nil}, // leading zero in numeric pre-release
|
||||
{"1.0.0-beta..1", nil}, // empty identifier between dots
|
||||
{"01.0.0", nil}, // leading zero in major
|
||||
{"1.00.0", nil}, // leading zero in minor
|
||||
{"1.0.00", nil}, // leading zero in patch
|
||||
{"DEV", nil},
|
||||
{"", nil},
|
||||
{"1.2", nil},
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package vfs
|
||||
|
||||
import (
|
||||
@@ -31,5 +28,3 @@ func MkdirAll(path string, perm fs.FileMode) error { return DefaultFS.MkdirA
|
||||
func ReadDir(name string) ([]os.DirEntry, error) { return DefaultFS.ReadDir(name) }
|
||||
func Remove(name string) error { return DefaultFS.Remove(name) }
|
||||
func Rename(oldpath, newpath string) error { return DefaultFS.Rename(oldpath, newpath) }
|
||||
func EvalSymlinks(path string) (string, error) { return DefaultFS.EvalSymlinks(path) }
|
||||
func Executable() (string, error) { return DefaultFS.Executable() }
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package vfs
|
||||
|
||||
import (
|
||||
@@ -29,8 +26,4 @@ type FS interface {
|
||||
ReadDir(name string) ([]os.DirEntry, error)
|
||||
Remove(name string) error
|
||||
Rename(oldpath, newpath string) error
|
||||
|
||||
// Path resolution
|
||||
EvalSymlinks(path string) (string, error)
|
||||
Executable() (string, error)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,8 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package vfs
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
)
|
||||
|
||||
// OsFs delegates every method to the os standard library.
|
||||
@@ -34,7 +30,3 @@ func (OsFs) MkdirAll(path string, perm fs.FileMode) error { return os.MkdirAll(p
|
||||
func (OsFs) ReadDir(name string) ([]os.DirEntry, error) { return os.ReadDir(name) }
|
||||
func (OsFs) Remove(name string) error { return os.Remove(name) }
|
||||
func (OsFs) Rename(oldpath, newpath string) error { return os.Rename(oldpath, newpath) }
|
||||
|
||||
// Path resolution
|
||||
func (OsFs) EvalSymlinks(path string) (string, error) { return filepath.EvalSymlinks(path) }
|
||||
func (OsFs) Executable() (string, error) { return os.Executable() }
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package vfs
|
||||
|
||||
import (
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@larksuite/cli",
|
||||
"version": "1.0.8",
|
||||
"version": "1.0.6",
|
||||
"description": "The official CLI for Lark/Feishu open platform",
|
||||
"bin": {
|
||||
"lark-cli": "scripts/run.js"
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
const { execSync } = require("child_process");
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
/*
|
||||
* Issue labeler for this repository.
|
||||
*
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
const fs = require('fs');
|
||||
const { execFileSync } = require('child_process');
|
||||
const path = require('path');
|
||||
|
||||
49
scripts/run.js
Executable file → Normal file
49
scripts/run.js
Executable file → Normal file
@@ -1,59 +1,10 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
const { execFileSync } = require("child_process");
|
||||
const fs = require("fs");
|
||||
const path = require("path");
|
||||
|
||||
const ext = process.platform === "win32" ? ".exe" : "";
|
||||
const bin = path.join(__dirname, "..", "bin", "lark-cli" + ext);
|
||||
|
||||
// On Windows, a crashed self-update may have left the binary renamed to .old.
|
||||
// Recover it before proceeding so the CLI remains functional.
|
||||
const oldBin = bin + ".old";
|
||||
function restoreOldBinary() {
|
||||
try {
|
||||
if (fs.existsSync(bin)) {
|
||||
fs.rmSync(bin, { force: true });
|
||||
}
|
||||
fs.renameSync(oldBin, bin);
|
||||
return true;
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
if (process.platform === "win32" && fs.existsSync(oldBin)) {
|
||||
if (!fs.existsSync(bin)) {
|
||||
restoreOldBinary();
|
||||
} else {
|
||||
try {
|
||||
execFileSync(bin, ["--version"], { stdio: "ignore", timeout: 10000 });
|
||||
try {
|
||||
fs.rmSync(oldBin, { force: true });
|
||||
} catch (_) {
|
||||
// Best-effort cleanup; keep running the healthy binary.
|
||||
}
|
||||
} catch (_) {
|
||||
restoreOldBinary();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!fs.existsSync(bin)) {
|
||||
console.error(
|
||||
`Error: lark-cli binary not found at ${bin}\n\n` +
|
||||
`This usually means the postinstall script was skipped.\n` +
|
||||
`Common causes:\n` +
|
||||
` - npm is configured with ignore-scripts=true\n` +
|
||||
` - The postinstall download failed\n\n` +
|
||||
`To fix, run the install script manually:\n` +
|
||||
` node "${path.join(__dirname, "install.js")}"\n`
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
try {
|
||||
execFileSync(bin, process.argv.slice(2), { stdio: "inherit" });
|
||||
} catch (e) {
|
||||
|
||||
@@ -1,6 +1,3 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
const fs = require('fs');
|
||||
const path = require('path');
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import (
|
||||
|
||||
// ── Dashboard CRUD ──────────────────────────────────────────────────
|
||||
|
||||
// TestBaseDashboardExecuteList tests the +dashboard-list command.
|
||||
func TestBaseDashboardExecuteList(t *testing.T) {
|
||||
t.Run("single page", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
@@ -42,7 +41,6 @@ func TestBaseDashboardExecuteList(t *testing.T) {
|
||||
|
||||
}
|
||||
|
||||
// TestBaseDashboardExecuteGet tests the +dashboard-get command.
|
||||
func TestBaseDashboardExecuteGet(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
@@ -69,7 +67,6 @@ func TestBaseDashboardExecuteGet(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardExecuteCreate tests the +dashboard-create command.
|
||||
func TestBaseDashboardExecuteCreate(t *testing.T) {
|
||||
t.Run("name only", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
@@ -117,7 +114,6 @@ func TestBaseDashboardExecuteCreate(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// TestBaseDashboardExecuteUpdate tests the +dashboard-update command.
|
||||
func TestBaseDashboardExecuteUpdate(t *testing.T) {
|
||||
t.Run("update name", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
@@ -165,7 +161,6 @@ func TestBaseDashboardExecuteUpdate(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// TestBaseDashboardExecuteDelete tests the +dashboard-delete command.
|
||||
func TestBaseDashboardExecuteDelete(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
@@ -184,7 +179,6 @@ func TestBaseDashboardExecuteDelete(t *testing.T) {
|
||||
|
||||
// ── Dashboard Block CRUD ────────────────────────────────────────────
|
||||
|
||||
// TestBaseDashboardBlockExecuteList tests the +dashboard-block-list command.
|
||||
func TestBaseDashboardBlockExecuteList(t *testing.T) {
|
||||
t.Run("single page", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
@@ -214,7 +208,6 @@ func TestBaseDashboardBlockExecuteList(t *testing.T) {
|
||||
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockExecuteGet tests the +dashboard-block-get command.
|
||||
func TestBaseDashboardBlockExecuteGet(t *testing.T) {
|
||||
t.Run("basic", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
@@ -268,7 +261,6 @@ func TestBaseDashboardBlockExecuteGet(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockExecuteCreate tests the +dashboard-block-create command.
|
||||
func TestBaseDashboardBlockExecuteCreate(t *testing.T) {
|
||||
t.Run("with data-config", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
@@ -362,7 +354,6 @@ func TestBaseDashboardBlockExecuteCreate(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockExecuteUpdate tests the +dashboard-block-update command.
|
||||
func TestBaseDashboardBlockExecuteUpdate(t *testing.T) {
|
||||
t.Run("update name and data-config", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
@@ -429,7 +420,6 @@ func TestBaseDashboardBlockExecuteUpdate(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockExecuteDelete tests the +dashboard-block-delete command.
|
||||
func TestBaseDashboardBlockExecuteDelete(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
@@ -448,7 +438,6 @@ func TestBaseDashboardBlockExecuteDelete(t *testing.T) {
|
||||
|
||||
// ── Dry Run: Dashboard & Blocks ──────────────────────────────────────
|
||||
|
||||
// TestBaseDashboardDryRun_List tests the +dashboard-list --dry-run flag.
|
||||
func TestBaseDashboardDryRun_List(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
if err := runShortcut(t, BaseDashboardList, []string{"+dashboard-list", "--base-token", "app_x", "--page-size", "50", "--dry-run", "--format", "pretty"}, factory, stdout); err != nil {
|
||||
@@ -460,7 +449,6 @@ func TestBaseDashboardDryRun_List(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardDryRun_Get tests the +dashboard-get --dry-run flag.
|
||||
func TestBaseDashboardDryRun_Get(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
if err := runShortcut(t, BaseDashboardGet, []string{"+dashboard-get", "--base-token", "app_x", "--dashboard-id", "dsh_1", "--dry-run", "--format", "pretty"}, factory, stdout); err != nil {
|
||||
@@ -472,7 +460,6 @@ func TestBaseDashboardDryRun_Get(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardDryRun_Create tests the +dashboard-create --dry-run flag.
|
||||
func TestBaseDashboardDryRun_Create(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := []string{"+dashboard-create", "--base-token", "app_x", "--name", "新报表", "--theme-style", "default", "--dry-run", "--format", "pretty"}
|
||||
@@ -485,7 +472,6 @@ func TestBaseDashboardDryRun_Create(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardDryRun_Update tests the +dashboard-update --dry-run flag.
|
||||
func TestBaseDashboardDryRun_Update(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := []string{"+dashboard-update", "--base-token", "app_x", "--dashboard-id", "dsh_1", "--name", "更新名", "--dry-run", "--format", "pretty"}
|
||||
@@ -498,7 +484,6 @@ func TestBaseDashboardDryRun_Update(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardDryRun_Delete tests the +dashboard-delete --dry-run flag.
|
||||
func TestBaseDashboardDryRun_Delete(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := []string{"+dashboard-delete", "--base-token", "app_x", "--dashboard-id", "dsh_1", "--dry-run", "--format", "pretty"}
|
||||
@@ -511,7 +496,6 @@ func TestBaseDashboardDryRun_Delete(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockDryRun_List tests the +dashboard-block-list --dry-run flag.
|
||||
func TestBaseDashboardBlockDryRun_List(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := []string{"+dashboard-block-list", "--base-token", "app_x", "--dashboard-id", "dsh_1", "--page-size", "10", "--dry-run", "--format", "pretty"}
|
||||
@@ -524,7 +508,6 @@ func TestBaseDashboardBlockDryRun_List(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockDryRun_Get tests the +dashboard-block-get --dry-run flag.
|
||||
func TestBaseDashboardBlockDryRun_Get(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := []string{"+dashboard-block-get", "--base-token", "app_x", "--dashboard-id", "dsh_1", "--block-id", "blk_a", "--user-id-type", "union_id", "--dry-run", "--format", "pretty"}
|
||||
@@ -537,7 +520,6 @@ func TestBaseDashboardBlockDryRun_Get(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockDryRun_Create tests the +dashboard-block-create --dry-run flag.
|
||||
func TestBaseDashboardBlockDryRun_Create(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := []string{"+dashboard-block-create", "--base-token", "app_x", "--dashboard-id", "dsh_1", "--name", "订单趋势", "--type", "column", "--data-config", `{"table_name":"订单表","count_all":true}`, "--user-id-type", "open_id", "--dry-run", "--format", "pretty"}
|
||||
@@ -550,7 +532,6 @@ func TestBaseDashboardBlockDryRun_Create(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockDryRun_Update tests the +dashboard-block-update --dry-run flag.
|
||||
func TestBaseDashboardBlockDryRun_Update(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := []string{"+dashboard-block-update", "--base-token", "app_x", "--dashboard-id", "dsh_1", "--block-id", "blk_a", "--name", "订单趋势v2", "--data-config", `{"table_name":"订单表2","count_all":true}`, "--dry-run", "--format", "pretty"}
|
||||
@@ -563,7 +544,6 @@ func TestBaseDashboardBlockDryRun_Update(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockDryRun_Delete tests the +dashboard-block-delete --dry-run flag.
|
||||
func TestBaseDashboardBlockDryRun_Delete(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := []string{"+dashboard-block-delete", "--base-token", "app_x", "--dashboard-id", "dsh_1", "--block-id", "blk_a", "--dry-run", "--format", "pretty"}
|
||||
@@ -578,7 +558,6 @@ func TestBaseDashboardBlockDryRun_Delete(t *testing.T) {
|
||||
|
||||
// ── Validator: data_config ───────────────────────────────────────────
|
||||
|
||||
// TestBaseDashboardBlockCreate_ValidateFails tests that data_config validation catches missing table_name.
|
||||
func TestBaseDashboardBlockCreate_ValidateFails(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
// 缺 table_name 且 series 与 count_all 同时存在
|
||||
@@ -595,7 +574,6 @@ func TestBaseDashboardBlockCreate_ValidateFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockCreate_NoValidateFlagAllocs tests that --no-validate flag skips client-side validation.
|
||||
func TestBaseDashboardBlockCreate_NoValidateFlagAllocs(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{Method: "POST", URL: "/open-apis/base/v3/bases/app_x/dashboards/dsh_1/blocks",
|
||||
@@ -613,7 +591,6 @@ func TestBaseDashboardBlockCreate_NoValidateFlagAllocs(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockCreate_InvalidRollup tests that invalid rollup values are rejected during validation.
|
||||
func TestBaseDashboardBlockCreate_InvalidRollup(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
// 合法 JSON,但 rollup=COUNTA(不支持)
|
||||
@@ -629,186 +606,3 @@ func TestBaseDashboardBlockCreate_InvalidRollup(t *testing.T) {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Text Block Tests ────────────────────────────────────────────────
|
||||
|
||||
// TestBaseDashboardBlockExecuteCreate_TextType tests creating text blocks with markdown content.
|
||||
func TestBaseDashboardBlockExecuteCreate_TextType(t *testing.T) {
|
||||
t.Run("valid text block", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/base/v3/bases/app_x/dashboards/dsh_001/blocks",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"block_id": "blk_text",
|
||||
"name": "说明文字",
|
||||
"type": "text",
|
||||
"data_config": map[string]interface{}{
|
||||
"text": "# 标题\n**加粗**",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
args := []string{"+dashboard-block-create", "--base-token", "app_x", "--dashboard-id", "dsh_001",
|
||||
"--name", "说明文字", "--type", "text",
|
||||
"--data-config", `{"text":"# 标题\n**加粗**"}`,
|
||||
}
|
||||
if err := runShortcut(t, BaseDashboardBlockCreate, args, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
got := stdout.String()
|
||||
if !strings.Contains(got, `"blk_text"`) || !strings.Contains(got, `"created": true`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("text block missing text field", func(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := []string{"+dashboard-block-create", "--base-token", "app_x", "--dashboard-id", "dsh_001",
|
||||
"--name", "Bad", "--type", "text",
|
||||
"--data-config", `{}`,
|
||||
}
|
||||
err := runShortcut(t, BaseDashboardBlockCreate, args, factory, stdout)
|
||||
if err == nil {
|
||||
t.Fatalf("expected validation error for missing text field")
|
||||
}
|
||||
if got := err.Error(); !strings.Contains(got, "text") || !strings.Contains(got, "data_config 校验失败") {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestBaseDashboardBlockExecuteUpdate_TextType tests updating text block content and name.
|
||||
func TestBaseDashboardBlockExecuteUpdate_TextType(t *testing.T) {
|
||||
t.Run("update text content", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PATCH",
|
||||
URL: "/open-apis/base/v3/bases/app_x/dashboards/dsh_001/blocks/blk_text",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"block_id": "blk_text",
|
||||
"name": "更新后的标题",
|
||||
"type": "text",
|
||||
"data_config": map[string]interface{}{
|
||||
"text": "# 新内容",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
args := []string{"+dashboard-block-update", "--base-token", "app_x", "--dashboard-id", "dsh_001", "--block-id", "blk_text",
|
||||
"--name", "更新后的标题",
|
||||
"--data-config", `{"text":"# 新内容"}`,
|
||||
}
|
||||
if err := runShortcut(t, BaseDashboardBlockUpdate, args, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
got := stdout.String()
|
||||
if !strings.Contains(got, `"updated": true`) || !strings.Contains(got, "新内容") {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("update without type skips strict validation", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
// update 不传 type,不做强类型校验,直接透传给后端
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PATCH",
|
||||
URL: "/open-apis/base/v3/bases/app_x/dashboards/dsh_001/blocks/blk_text",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"block_id": "blk_text",
|
||||
"type": "text",
|
||||
},
|
||||
},
|
||||
})
|
||||
args := []string{"+dashboard-block-update", "--base-token", "app_x", "--dashboard-id", "dsh_001", "--block-id", "blk_text",
|
||||
"--data-config", `{"content":"xxx"}`,
|
||||
}
|
||||
// 不传 type,本地不做强校验,让后端处理
|
||||
err := runShortcut(t, BaseDashboardBlockUpdate, args, factory, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"updated": true`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// ── Dashboard Arrange ────────────────────────────────────────────────
|
||||
|
||||
// TestBaseDashboardExecuteArrange tests the +dashboard-arrange command for auto-arranging dashboard blocks.
|
||||
func TestBaseDashboardExecuteArrange(t *testing.T) {
|
||||
t.Run("arrange dashboard blocks", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/base/v3/bases/app_x/dashboards/dsh_001/arrange",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"dashboard_id": "dsh_001",
|
||||
"name": "测试仪表盘",
|
||||
"blocks": []interface{}{
|
||||
map[string]interface{}{
|
||||
"block_id": "cht_xxx",
|
||||
"block_name": "组件1",
|
||||
"block_type": "column",
|
||||
"layout": map[string]interface{}{
|
||||
"x": 0, "y": 0, "w": 500, "h": 400,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
args := []string{"+dashboard-arrange", "--base-token", "app_x", "--dashboard-id", "dsh_001"}
|
||||
if err := runShortcut(t, BaseDashboardArrange, args, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
got := stdout.String()
|
||||
if !strings.Contains(got, `"arranged": true`) || !strings.Contains(got, `"dashboard_id"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("arrange with user-id-type", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "user_id_type=union_id",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"dashboard_id": "dsh_001",
|
||||
"blocks": []interface{}{},
|
||||
},
|
||||
},
|
||||
})
|
||||
args := []string{"+dashboard-arrange", "--base-token", "app_x", "--dashboard-id", "dsh_001", "--user-id-type", "union_id"}
|
||||
if err := runShortcut(t, BaseDashboardArrange, args, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"arranged": true`) || !strings.Contains(got, `"dashboard_id"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestBaseDashboardDryRun_Arrange tests the +dashboard-arrange --dry-run flag includes empty body.
|
||||
func TestBaseDashboardDryRun_Arrange(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := []string{"+dashboard-arrange", "--base-token", "app_x", "--dashboard-id", "dsh_001", "--user-id-type", "union_id", "--dry-run", "--format", "pretty"}
|
||||
if err := runShortcut(t, BaseDashboardArrange, args, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
got := stdout.String()
|
||||
if !strings.Contains(got, "POST /open-apis/base/v3/bases/app_x/dashboards/dsh_001/arrange") || !strings.Contains(got, "union_id") || !strings.Contains(got, "{}") {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -63,49 +63,18 @@ func TestDryRunFieldOps(t *testing.T) {
|
||||
func TestDryRunRecordOps(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
listRT := newBaseTestRuntimeWithArrays(
|
||||
listRT := newBaseTestRuntime(
|
||||
map[string]string{"base-token": "app_x", "table-id": "tbl_1", "view-id": "viw_1"},
|
||||
map[string][]string{"field-id": {"Name", "Age"}},
|
||||
nil,
|
||||
map[string]int{"offset": -3, "limit": 500},
|
||||
)
|
||||
assertDryRunContains(t, dryRunRecordList(ctx, listRT), "GET /open-apis/base/v3/bases/app_x/tables/tbl_1/records", "offset=0", "limit=200", "view_id=viw_1", "field_id=Name", "field_id=Age")
|
||||
|
||||
commaFieldRT := newBaseTestRuntimeWithArrays(
|
||||
map[string]string{"base-token": "app_x", "table-id": "tbl_1"},
|
||||
map[string][]string{"field-id": {"A,B", "C"}},
|
||||
nil,
|
||||
map[string]int{"limit": 1},
|
||||
)
|
||||
assertDryRunContains(t, dryRunRecordList(ctx, commaFieldRT), "limit=1", "offset=0", "field_id=A%2CB", "field_id=C")
|
||||
|
||||
searchRT := newBaseTestRuntime(
|
||||
map[string]string{
|
||||
"base-token": "app_x",
|
||||
"table-id": "tbl_1",
|
||||
"json": `{"view_id":"viw_1","keyword":"Created","search_fields":["Title","fld_owner"],"select_fields":["Title","fld_owner"],"offset":-1,"limit":500}`,
|
||||
},
|
||||
nil, nil,
|
||||
)
|
||||
assertDryRunContains(
|
||||
t,
|
||||
dryRunRecordSearch(ctx, searchRT),
|
||||
"POST /open-apis/base/v3/bases/app_x/tables/tbl_1/records/search",
|
||||
`"view_id":"viw_1"`,
|
||||
`"keyword":"Created"`,
|
||||
`"search_fields":["Title","fld_owner"]`,
|
||||
`"select_fields":["Title","fld_owner"]`,
|
||||
`"offset":-1`,
|
||||
`"limit":500`,
|
||||
)
|
||||
assertDryRunContains(t, dryRunRecordList(ctx, listRT), "GET /open-apis/base/v3/bases/app_x/tables/tbl_1/records", "offset=0", "limit=200", "view_id=viw_1")
|
||||
|
||||
upsertCreateRT := newBaseTestRuntime(
|
||||
map[string]string{"base-token": "app_x", "table-id": "tbl_1", "json": `{"Name":"A"}`},
|
||||
nil, nil,
|
||||
)
|
||||
assertDryRunContains(t, dryRunRecordUpsert(ctx, upsertCreateRT), "POST /open-apis/base/v3/bases/app_x/tables/tbl_1/records")
|
||||
assertDryRunContains(t, dryRunRecordBatchCreate(ctx, upsertCreateRT), "POST /open-apis/base/v3/bases/app_x/tables/tbl_1/records/batch_create")
|
||||
assertDryRunContains(t, dryRunRecordBatchUpdate(ctx, upsertCreateRT), "POST /open-apis/base/v3/bases/app_x/tables/tbl_1/records/batch_update")
|
||||
|
||||
rt := newBaseTestRuntime(
|
||||
map[string]string{"base-token": "app_x", "table-id": "tbl_1", "record-id": "rec_1", "json": `{"Name":"B"}`},
|
||||
@@ -242,7 +211,6 @@ func TestDryRunViewOps(t *testing.T) {
|
||||
assertDryRunContains(t, dryRunViewSetWrapped(setWrappedInvalidRT, "group", "group_config"), "PUT /open-apis/base/v3/bases/app_x/tables/tbl_1/views/viw_1/group")
|
||||
|
||||
assertDryRunContains(t, dryRunViewGetFilter(ctx, listRT), "GET /open-apis/base/v3/bases/app_x/tables/tbl_1/views/viw_1/filter")
|
||||
assertDryRunContains(t, dryRunViewGetVisibleFields(ctx, listRT), "GET /open-apis/base/v3/bases/app_x/tables/tbl_1/views/viw_1/visible_fields")
|
||||
assertDryRunContains(t, dryRunViewGetGroup(ctx, listRT), "GET /open-apis/base/v3/bases/app_x/tables/tbl_1/views/viw_1/group")
|
||||
assertDryRunContains(t, dryRunViewGetSort(ctx, listRT), "GET /open-apis/base/v3/bases/app_x/tables/tbl_1/views/viw_1/sort")
|
||||
assertDryRunContains(t, dryRunViewGetTimebar(ctx, listRT), "GET /open-apis/base/v3/bases/app_x/tables/tbl_1/views/viw_1/timebar")
|
||||
|
||||
@@ -303,7 +303,7 @@ func TestBaseFieldExecuteCRUD(t *testing.T) {
|
||||
if err := runShortcut(t, BaseFieldList, []string{"+field-list", "--base-token", "app_x", "--table-id", "tbl_x", "--offset", "0", "--limit", "1"}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"total": 2`) || !strings.Contains(got, `"fields"`) || !strings.Contains(got, `"name": "Amount"`) || strings.Contains(got, `"items"`) || strings.Contains(got, `"offset"`) || strings.Contains(got, `"limit"`) || strings.Contains(got, `"count"`) || strings.Contains(got, `"field_name": "Amount"`) {
|
||||
if got := stdout.String(); !strings.Contains(got, `"total": 2`) || !strings.Contains(got, `"field_name": "Amount"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
@@ -376,7 +376,7 @@ func TestBaseTableExecuteReadAndDelete(t *testing.T) {
|
||||
if err := runShortcut(t, BaseTableList, []string{"+table-list", "--base-token", "app_x", "--limit", "1"}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"total": 2`) || !strings.Contains(got, `"tables"`) || !strings.Contains(got, `"name": "Alpha"`) || strings.Contains(got, `"items"`) || strings.Contains(got, `"offset"`) || strings.Contains(got, `"limit"`) || strings.Contains(got, `"count"`) || strings.Contains(got, `"table_name": "Alpha"`) {
|
||||
if got := stdout.String(); !strings.Contains(got, `"total": 2`) || !strings.Contains(got, `"table_name": "Alpha"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
@@ -427,7 +427,7 @@ func TestBaseTableExecuteReadAndDelete(t *testing.T) {
|
||||
if err := runShortcut(t, BaseTableGet, []string{"+table-get", "--base-token", "app_x", "--table-id", "tbl_x"}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"name": "Orders"`) || !strings.Contains(got, `"primary_field": "fld_x"`) || !strings.Contains(got, `"id": "fld_x"`) || !strings.Contains(got, `"name": "OrderNo"`) || !strings.Contains(got, `"id": "vew_x"`) || !strings.Contains(got, `"name": "Main"`) || strings.Contains(got, `"field_name": "OrderNo"`) || strings.Contains(got, `"view_name": "Main"`) {
|
||||
if got := stdout.String(); !strings.Contains(got, `"name": "Orders"`) || !strings.Contains(got, `"primary_field": "fld_x"`) || !strings.Contains(got, `"vew_x"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
@@ -471,52 +471,6 @@ func TestBaseRecordExecuteReadCreateDelete(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("list with fields and view", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "field_id=Name&field_id=Age&limit=1&offset=0&view_id=vew_x",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"fields": []interface{}{"Name", "Age"},
|
||||
"record_id_list": []interface{}{"rec_fields"},
|
||||
"data": []interface{}{[]interface{}{"Alice", 18}},
|
||||
"total": 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
if err := runShortcut(t, BaseRecordList, []string{"+record-list", "--base-token", "app_x", "--table-id", "tbl_x", "--view-id", "vew_x", "--limit", "1", "--field-id", "Name", "--field-id", "Age"}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"rec_fields"`) || !strings.Contains(got, `"Alice"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("list with comma field", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "field_id=A%2CB&field_id=C&limit=1&offset=0",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"fields": []interface{}{"A,B", "C"},
|
||||
"record_id_list": []interface{}{"rec_json_fields"},
|
||||
"data": []interface{}{[]interface{}{"value-1", "value-2"}},
|
||||
"total": 1,
|
||||
},
|
||||
},
|
||||
})
|
||||
if err := runShortcut(t, BaseRecordList, []string{"+record-list", "--base-token", "app_x", "--table-id", "tbl_x", "--limit", "1", "--field-id", "A,B", "--field-id", "C"}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"A,B"`) || !strings.Contains(got, `"rec_json_fields"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("list new shape", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
@@ -540,72 +494,6 @@ func TestBaseRecordExecuteReadCreateDelete(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("search", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
searchStub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/records/search",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"fields": []interface{}{"Title", "Owner"},
|
||||
"field_id_list": []interface{}{"fld_title", "fld_owner"},
|
||||
"record_id_list": []interface{}{"rec_1"},
|
||||
"data": []interface{}{[]interface{}{"Created by AI", "Alice"}},
|
||||
"has_more": false,
|
||||
"query_context": map[string]interface{}{
|
||||
"record_scope": "filtered_records",
|
||||
"field_scope": "selected_fields",
|
||||
"search_scope": "fld_title(Title)",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(searchStub)
|
||||
if err := runShortcut(
|
||||
t,
|
||||
BaseRecordSearch,
|
||||
[]string{
|
||||
"+record-search",
|
||||
"--base-token", "app_x",
|
||||
"--table-id", "tbl_x",
|
||||
"--json", `{"view_id":"vew_x","keyword":"Created","search_fields":["Title","fld_owner"],"select_fields":["Title","fld_owner"],"offset":0,"limit":2}`,
|
||||
},
|
||||
factory,
|
||||
stdout,
|
||||
); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"record_id_list"`) || !strings.Contains(got, `"rec_1"`) || !strings.Contains(got, `"query_context"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
body := string(searchStub.CapturedBody)
|
||||
if !strings.Contains(body, `"view_id":"vew_x"`) ||
|
||||
!strings.Contains(body, `"keyword":"Created"`) ||
|
||||
!strings.Contains(body, `"search_fields":["Title","fld_owner"]`) ||
|
||||
!strings.Contains(body, `"select_fields":["Title","fld_owner"]`) ||
|
||||
!strings.Contains(body, `"offset":0`) ||
|
||||
!strings.Contains(body, `"limit":2`) {
|
||||
t.Fatalf("captured body=%s", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("list legacy fields flag rejected", func(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
err := runShortcut(t, BaseRecordList, []string{"+record-list", "--base-token", "app_x", "--table-id", "tbl_x", "--fields", "Name"}, factory, stdout)
|
||||
if err == nil || !strings.Contains(err.Error(), "unknown flag: --fields") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("list legacy fields flag rejected in dry-run", func(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
err := runShortcut(t, BaseRecordList, []string{"+record-list", "--base-token", "app_x", "--table-id", "tbl_x", "--fields", "Name", "--dry-run"}, factory, stdout)
|
||||
if err == nil || !strings.Contains(err.Error(), "unknown flag: --fields") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("get", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
@@ -664,75 +552,6 @@ func TestBaseRecordExecuteReadCreateDelete(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("batch create", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/records/batch_create",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"fields": []interface{}{"Name"},
|
||||
"record_id_list": []interface{}{"rec_1", "rec_2"},
|
||||
"data": []interface{}{[]interface{}{"Alice"}, []interface{}{"Bob"}},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err := runShortcut(t, BaseRecordBatchCreate, []string{"+record-batch-create", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"fields":["Name"],"rows":[["Alice"],["Bob"]]}`}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"record_id_list"`) || !strings.Contains(got, `"rec_1"`) || !strings.Contains(got, `"Alice"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("batch update", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/records/batch_update",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"has_more": false,
|
||||
"record_id_list": []interface{}{"rec_1"},
|
||||
"update": map[string]interface{}{"Status": "Done"},
|
||||
},
|
||||
},
|
||||
})
|
||||
if err := runShortcut(t, BaseRecordBatchUpdate, []string{"+record-batch-update", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"record_id_list":["rec_1"],"patch":{"Status":"Done"}}`}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"record_id_list"`) || !strings.Contains(got, `"update"`) || !strings.Contains(got, `"Done"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("batch update passthrough", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
updateStub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/records/batch_update",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"record_id_list": []interface{}{"rec_1"},
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(updateStub)
|
||||
if err := runShortcut(t, BaseRecordBatchUpdate, []string{"+record-batch-update", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"record_id_list":["rec_1"],"patch":{"Name":"Alice","Status":"Done"}}`}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"record_id_list"`) || !strings.Contains(got, `"rec_1"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
body := string(updateStub.CapturedBody)
|
||||
if !strings.Contains(body, `"record_id_list":["rec_1"]`) || !strings.Contains(body, `"patch":{"Name":"Alice","Status":"Done"}`) {
|
||||
t.Fatalf("request body=%s", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("delete", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
@@ -920,7 +739,7 @@ func TestBaseViewExecuteReadCreateDeleteAndFilter(t *testing.T) {
|
||||
if err := runShortcut(t, BaseViewList, []string{"+view-list", "--base-token", "app_x", "--table-id", "tbl_x", "--offset", "0", "--limit", "1"}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"total": 3`) || !strings.Contains(got, `"views"`) || !strings.Contains(got, `"name": "Main"`) || strings.Contains(got, `"items"`) || strings.Contains(got, `"offset"`) || strings.Contains(got, `"limit"`) || strings.Contains(got, `"count"`) || strings.Contains(got, `"view_name": "Main"`) {
|
||||
if got := stdout.String(); !strings.Contains(got, `"total": 3`) || !strings.Contains(got, `"view_name": "Main"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
@@ -993,61 +812,6 @@ func TestBaseViewExecuteReadCreateDeleteAndFilter(t *testing.T) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("get-visible-fields", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/views/vew_1/visible_fields",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": []interface{}{"fld_primary", "fld_status"},
|
||||
},
|
||||
})
|
||||
if err := runShortcut(t, BaseViewGetVisibleFields, []string{"+view-get-visible-fields", "--base-token", "app_x", "--table-id", "tbl_x", "--view-id", "vew_1"}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"visible_fields"`) || !strings.Contains(got, `"fld_primary"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("set-visible-fields-array-invalid", func(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
err := runShortcut(
|
||||
t,
|
||||
BaseViewSetVisibleFields,
|
||||
[]string{"+view-set-visible-fields", "--base-token", "app_x", "--table-id", "tbl_x", "--view-id", "vew_1", "--json", `["fld_status"]`},
|
||||
factory,
|
||||
stdout,
|
||||
)
|
||||
if err == nil || !strings.Contains(err.Error(), "invalid JSON object") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("set-visible-fields-object", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
updateStub := &httpmock.Stub{
|
||||
Method: "PUT",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/views/vew_1/visible_fields",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": []interface{}{"fld_primary", "fld_status"},
|
||||
},
|
||||
}
|
||||
reg.Register(updateStub)
|
||||
if err := runShortcut(t, BaseViewSetVisibleFields, []string{"+view-set-visible-fields", "--base-token", "app_x", "--table-id", "tbl_x", "--view-id", "vew_1", "--json", `{"visible_fields":["fld_status"]}`}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
body := string(updateStub.CapturedBody)
|
||||
if !strings.Contains(body, `"visible_fields":["fld_status"]`) {
|
||||
t.Fatalf("request body=%s", body)
|
||||
}
|
||||
if strings.Contains(body, `{"visible_fields":{"visible_fields":`) {
|
||||
t.Fatalf("request body double wrapped: %s", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestBaseTableExecuteListFallbackShapes(t *testing.T) {
|
||||
|
||||
@@ -5,29 +5,19 @@ package base
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// parseCtx carries file I/O dependency for JSON/file parsing helpers.
|
||||
type parseCtx struct {
|
||||
fio fileio.FileIO
|
||||
}
|
||||
|
||||
func newParseCtx(runtime *common.RuntimeContext) *parseCtx {
|
||||
return &parseCtx{fio: runtime.FileIO()}
|
||||
}
|
||||
|
||||
func baseTableID(runtime *common.RuntimeContext) string {
|
||||
return strings.TrimSpace(runtime.Str("table-id"))
|
||||
}
|
||||
|
||||
func loadJSONInput(pc *parseCtx, raw string, flagName string) (string, error) {
|
||||
func loadJSONInput(raw string, flagName string) (string, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return "", common.FlagErrorf("--%s cannot be empty", flagName)
|
||||
@@ -39,19 +29,11 @@ func loadJSONInput(pc *parseCtx, raw string, flagName string) (string, error) {
|
||||
if path == "" {
|
||||
return "", common.FlagErrorf("--%s file path cannot be empty after @", flagName)
|
||||
}
|
||||
if pc.fio == nil {
|
||||
return "", common.FlagErrorf("--%s @file inputs require a FileIO provider", flagName)
|
||||
}
|
||||
f, err := pc.fio.Open(path)
|
||||
safePath, err := validate.SafeInputPath(path)
|
||||
if err != nil {
|
||||
var pathErr *fileio.PathValidationError
|
||||
if errors.As(err, &pathErr) {
|
||||
return "", common.FlagErrorf("--%s invalid JSON file path %q: %v", flagName, path, pathErr.Err)
|
||||
}
|
||||
return "", common.FlagErrorf("--%s cannot open JSON file %q: %v", flagName, path, err)
|
||||
return "", common.FlagErrorf("--%s invalid JSON file path %q: %v", flagName, path, err)
|
||||
}
|
||||
defer f.Close()
|
||||
data, err := io.ReadAll(f)
|
||||
data, err := vfs.ReadFile(safePath)
|
||||
if err != nil {
|
||||
return "", common.FlagErrorf("--%s cannot read JSON file %q: %v", flagName, path, err)
|
||||
}
|
||||
@@ -104,18 +86,18 @@ func baseAction(runtime *common.RuntimeContext, boolFlags []string, stringFlags
|
||||
return active[0], nil
|
||||
}
|
||||
|
||||
func parseObjectList(pc *parseCtx, raw string, flagName string) ([]map[string]interface{}, error) {
|
||||
func parseObjectList(raw string, flagName string) ([]map[string]interface{}, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil, nil
|
||||
}
|
||||
var err error
|
||||
raw, err = loadJSONInput(pc, raw, flagName)
|
||||
raw, err = loadJSONInput(raw, flagName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.HasPrefix(raw, "[") {
|
||||
arr, err := parseJSONArray(pc, raw, flagName)
|
||||
arr, err := parseJSONArray(raw, flagName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -129,16 +111,16 @@ func parseObjectList(pc *parseCtx, raw string, flagName string) ([]map[string]in
|
||||
}
|
||||
return items, nil
|
||||
}
|
||||
obj, err := parseJSONObject(pc, raw, flagName)
|
||||
obj, err := parseJSONObject(raw, flagName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return []map[string]interface{}{obj}, nil
|
||||
}
|
||||
|
||||
func parseJSONValue(pc *parseCtx, raw string, flagName string) (interface{}, error) {
|
||||
func parseJSONValue(raw string, flagName string) (interface{}, error) {
|
||||
var err error
|
||||
raw, err = loadJSONInput(pc, raw, flagName)
|
||||
raw, err = loadJSONInput(raw, flagName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
@@ -18,17 +18,10 @@ import (
|
||||
)
|
||||
|
||||
func newBaseTestRuntime(stringFlags map[string]string, boolFlags map[string]bool, intFlags map[string]int) *common.RuntimeContext {
|
||||
return newBaseTestRuntimeWithArrays(stringFlags, nil, boolFlags, intFlags)
|
||||
}
|
||||
|
||||
func newBaseTestRuntimeWithArrays(stringFlags map[string]string, stringArrayFlags map[string][]string, boolFlags map[string]bool, intFlags map[string]int) *common.RuntimeContext {
|
||||
cmd := &cobra.Command{Use: "test"}
|
||||
for name := range stringFlags {
|
||||
cmd.Flags().String(name, "", "")
|
||||
}
|
||||
for name := range stringArrayFlags {
|
||||
cmd.Flags().StringArray(name, nil, "")
|
||||
}
|
||||
for name := range boolFlags {
|
||||
cmd.Flags().Bool(name, false, "")
|
||||
}
|
||||
@@ -39,11 +32,6 @@ func newBaseTestRuntimeWithArrays(stringFlags map[string]string, stringArrayFlag
|
||||
for name, value := range stringFlags {
|
||||
_ = cmd.Flags().Set(name, value)
|
||||
}
|
||||
for name, values := range stringArrayFlags {
|
||||
for _, value := range values {
|
||||
_ = cmd.Flags().Set(name, value)
|
||||
}
|
||||
}
|
||||
for name, value := range boolFlags {
|
||||
if value {
|
||||
_ = cmd.Flags().Set(name, "true")
|
||||
@@ -82,22 +70,22 @@ func TestBaseAction(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestParseObjectList(t *testing.T) {
|
||||
items, err := parseObjectList(testPC, "", "view")
|
||||
items, err := parseObjectList("", "view")
|
||||
if err != nil || items != nil {
|
||||
t.Fatalf("items=%v err=%v", items, err)
|
||||
}
|
||||
|
||||
items, err = parseObjectList(testPC, `{"name":"grid"}`, "view")
|
||||
items, err = parseObjectList(`{"name":"grid"}`, "view")
|
||||
if err != nil || len(items) != 1 || items[0]["name"] != "grid" {
|
||||
t.Fatalf("items=%v err=%v", items, err)
|
||||
}
|
||||
|
||||
items, err = parseObjectList(testPC, `[{"name":"grid"}]`, "view")
|
||||
items, err = parseObjectList(`[{"name":"grid"}]`, "view")
|
||||
if err != nil || len(items) != 1 || items[0]["name"] != "grid" {
|
||||
t.Fatalf("items=%v err=%v", items, err)
|
||||
}
|
||||
|
||||
_, err = parseObjectList(testPC, `[1]`, "view")
|
||||
_, err = parseObjectList(`[1]`, "view")
|
||||
if err == nil || !strings.Contains(err.Error(), "must be an object") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
@@ -120,19 +108,13 @@ func TestWrapViewPropertyBody(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestViewSetVisibleFieldsNoValidateHook(t *testing.T) {
|
||||
if BaseViewSetVisibleFields.Validate != nil {
|
||||
t.Fatalf("expected no validate hook, got non-nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortcutsCatalog(t *testing.T) {
|
||||
shortcuts := Shortcuts()
|
||||
want := []string{
|
||||
"+table-list", "+table-get", "+table-create", "+table-update", "+table-delete",
|
||||
"+field-list", "+field-get", "+field-create", "+field-update", "+field-delete", "+field-search-options",
|
||||
"+view-list", "+view-get", "+view-create", "+view-delete", "+view-get-filter", "+view-set-filter", "+view-get-visible-fields", "+view-set-visible-fields", "+view-get-group", "+view-set-group", "+view-get-sort", "+view-set-sort", "+view-get-timebar", "+view-set-timebar", "+view-get-card", "+view-set-card", "+view-rename",
|
||||
"+record-list", "+record-search", "+record-get", "+record-upsert", "+record-batch-create", "+record-batch-update", "+record-upload-attachment", "+record-delete",
|
||||
"+view-list", "+view-get", "+view-create", "+view-delete", "+view-get-filter", "+view-set-filter", "+view-get-group", "+view-set-group", "+view-get-sort", "+view-set-sort", "+view-get-timebar", "+view-set-timebar", "+view-get-card", "+view-set-card", "+view-rename",
|
||||
"+record-list", "+record-get", "+record-upsert", "+record-upload-attachment", "+record-delete",
|
||||
"+record-history-list",
|
||||
"+base-get", "+base-copy", "+base-create",
|
||||
"+role-create", "+role-delete", "+role-update", "+role-list", "+role-get", "+advperm-enable", "+advperm-disable",
|
||||
@@ -140,7 +122,7 @@ func TestShortcutsCatalog(t *testing.T) {
|
||||
"+data-query",
|
||||
"+form-create", "+form-delete", "+form-list", "+form-update", "+form-get",
|
||||
"+form-questions-create", "+form-questions-delete", "+form-questions-update", "+form-questions-list",
|
||||
"+dashboard-list", "+dashboard-get", "+dashboard-create", "+dashboard-update", "+dashboard-delete", "+dashboard-arrange",
|
||||
"+dashboard-list", "+dashboard-get", "+dashboard-create", "+dashboard-update", "+dashboard-delete",
|
||||
"+dashboard-block-list", "+dashboard-block-get", "+dashboard-block-create", "+dashboard-block-update", "+dashboard-block-delete",
|
||||
}
|
||||
if len(shortcuts) != len(want) {
|
||||
@@ -252,19 +234,21 @@ func TestBaseTableValidate(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestBaseRecordValidate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
if BaseRecordList.Validate != nil {
|
||||
t.Fatalf("record list validate should be nil for repeatable --field-id")
|
||||
}
|
||||
if BaseRecordSearch.Validate != nil {
|
||||
t.Fatalf("record search validate should be nil for API passthrough")
|
||||
t.Fatalf("record list validate should be nil after removing --fields")
|
||||
}
|
||||
if BaseRecordGet.Validate != nil {
|
||||
t.Fatalf("record get validate should be nil")
|
||||
t.Fatalf("record get validate should be nil after removing --fields")
|
||||
}
|
||||
if BaseRecordUpsert.Validate != nil {
|
||||
t.Fatalf("record upsert validate should be nil for API passthrough")
|
||||
if err := BaseRecordUpsert.Validate(ctx, newBaseTestRuntime(map[string]string{"base-token": "b", "table-id": "tbl_1", "json": `{"Name":"A"}`}, nil, nil)); err != nil {
|
||||
t.Fatalf("upsert validate err=%v", err)
|
||||
}
|
||||
if err := BaseRecordUpsert.Validate(ctx, newBaseTestRuntime(map[string]string{"base-token": "b", "table-id": "tbl_1", "json": "{"}, nil, nil)); err != nil {
|
||||
t.Fatalf("invalid record json should bypass CLI validate, err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseViewValidate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
if err := BaseViewCreate.Validate(ctx, newBaseTestRuntime(map[string]string{"base-token": "b", "table-id": "tbl_1", "json": `{"name":"Main"}`}, nil, nil)); err != nil {
|
||||
|
||||
@@ -1,29 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package base
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
var BaseDashboardArrange = common.Shortcut{
|
||||
Service: "base",
|
||||
Command: "+dashboard-arrange",
|
||||
Description: "Auto-arrange dashboard blocks layout (server-side smart layout)",
|
||||
Risk: "write",
|
||||
Scopes: []string{"base:dashboard:update"},
|
||||
AuthTypes: authTypes(),
|
||||
HasFormat: true,
|
||||
Flags: []common.Flag{
|
||||
baseTokenFlag(true),
|
||||
dashboardIDFlag(true),
|
||||
{Name: "user-id-type", Desc: "user ID type: open_id / union_id / user_id"},
|
||||
},
|
||||
DryRun: dryRunDashboardArrange,
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return executeDashboardArrange(runtime)
|
||||
},
|
||||
}
|
||||
@@ -6,7 +6,6 @@ package base
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
@@ -24,25 +23,20 @@ var BaseDashboardBlockCreate = common.Shortcut{
|
||||
baseTokenFlag(true),
|
||||
dashboardIDFlag(true),
|
||||
{Name: "name", Desc: "block name", Required: true},
|
||||
{Name: "type", Desc: "block type: column(柱状图)|bar(条形图)|line(折线图)|pie(饼图)|ring(环形图)|area(面积图)|combo(组合图)|scatter(散点图)|funnel(漏斗图)|wordCloud(词云)|radar(雷达图)|statistics(指标卡)|text(文本). Read dashboard-block-data-config.md before creating.", Required: true},
|
||||
{Name: "type", Desc: "block type: column(柱状图)|bar(条形图)|line(折线图)|pie(饼图)|ring(环形图)|area(面积图)|combo(组合图)|scatter(散点图)|funnel(漏斗图)|wordCloud(词云)|radar(雷达图)|statistics(指标卡). Read dashboard-block-data-config.md before creating.", Required: true},
|
||||
{Name: "data-config", Desc: "data config JSON object (table_name, series, count_all, group_by, filter, etc.)"},
|
||||
{Name: "user-id-type", Desc: "user ID type: open_id / union_id / user_id"},
|
||||
{Name: "no-validate", Type: "bool", Desc: "skip local data_config validation"},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
if runtime.Bool("no-validate") {
|
||||
return nil
|
||||
}
|
||||
raw := runtime.Str("data-config")
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
// text 类型必须提供 data-config(含 text 内容)
|
||||
if strings.ToLower(runtime.Str("type")) == "text" {
|
||||
return fmt.Errorf("text 类型组件必须提供 data-config,包含必填字段 text")
|
||||
}
|
||||
return nil
|
||||
return nil // 允许无 data_config 的创建(某些类型可先创建后配置)
|
||||
}
|
||||
cfg, err := parseJSONObject(pc, raw, "data-config")
|
||||
cfg, err := parseJSONObject(raw, "data-config")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -56,7 +50,6 @@ var BaseDashboardBlockCreate = common.Shortcut{
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
body := map[string]interface{}{}
|
||||
if name := runtime.Str("name"); name != "" {
|
||||
body["name"] = name
|
||||
@@ -65,7 +58,7 @@ var BaseDashboardBlockCreate = common.Shortcut{
|
||||
body["type"] = t
|
||||
}
|
||||
if raw := runtime.Str("data-config"); raw != "" {
|
||||
if parsed, err := parseJSONObject(pc, raw, "data-config"); err == nil {
|
||||
if parsed, err := parseJSONObject(raw, "data-config"); err == nil {
|
||||
body["data_config"] = parsed
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,12 +24,11 @@ var BaseDashboardBlockUpdate = common.Shortcut{
|
||||
dashboardIDFlag(true),
|
||||
blockIDFlag(true),
|
||||
{Name: "name", Desc: "new block name"},
|
||||
{Name: "data-config", Desc: "data config JSON. For chart types: table_name, series|count_all, group_by, filter. For text type: text (markdown supported). See dashboard-block-data-config.md for details."},
|
||||
{Name: "data-config", Desc: "data config JSON: table_name, series|count_all (mutually exclusive), group_by, filter. See dashboard-block-data-config.md for details."},
|
||||
{Name: "user-id-type", Desc: "user ID type: open_id / union_id / user_id"},
|
||||
{Name: "no-validate", Type: "bool", Desc: "skip local data_config validation"},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
if runtime.Bool("no-validate") {
|
||||
return nil
|
||||
}
|
||||
@@ -37,24 +36,25 @@ var BaseDashboardBlockUpdate = common.Shortcut{
|
||||
if strings.TrimSpace(raw) == "" {
|
||||
return nil
|
||||
}
|
||||
cfg, err := parseJSONObject(pc, raw, "data-config")
|
||||
cfg, err := parseJSONObject(raw, "data-config")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
norm := normalizeDataConfig(cfg)
|
||||
// update 时不做强类型校验(不传 type),让后端验证具体字段
|
||||
if errs := validateBlockDataConfig("", norm); len(errs) > 0 { // update 时不强校验类型特性
|
||||
return formatDataConfigErrors(errs)
|
||||
}
|
||||
b, _ := json.Marshal(norm)
|
||||
_ = runtime.Cmd.Flags().Set("data-config", string(b))
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
body := map[string]interface{}{}
|
||||
if name := runtime.Str("name"); name != "" {
|
||||
body["name"] = name
|
||||
}
|
||||
if raw := runtime.Str("data-config"); raw != "" {
|
||||
if parsed, err := parseJSONObject(pc, raw, "data-config"); err == nil {
|
||||
if parsed, err := parseJSONObject(raw, "data-config"); err == nil {
|
||||
body["data_config"] = parsed
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,17 +10,14 @@ import (
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// dashboardIDFlag returns a Flag for dashboard ID.
|
||||
func dashboardIDFlag(required bool) common.Flag {
|
||||
return common.Flag{Name: "dashboard-id", Desc: "dashboard ID", Required: required}
|
||||
}
|
||||
|
||||
// blockIDFlag returns a Flag for dashboard block ID.
|
||||
func blockIDFlag(required bool) common.Flag {
|
||||
return common.Flag{Name: "block-id", Desc: "dashboard block ID", Required: required}
|
||||
}
|
||||
|
||||
// dryRunDashboardBase returns a base DryRunAPI with common dashboard parameters set.
|
||||
func dryRunDashboardBase(runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return common.NewDryRunAPI().
|
||||
Set("base_token", runtime.Str("base-token")).
|
||||
@@ -28,7 +25,6 @@ func dryRunDashboardBase(runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
Set("block_id", runtime.Str("block-id"))
|
||||
}
|
||||
|
||||
// dryRunDashboardList returns a DryRunAPI for listing dashboards.
|
||||
func dryRunDashboardList(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
params := map[string]interface{}{}
|
||||
if pageSize := strings.TrimSpace(runtime.Str("page-size")); pageSize != "" {
|
||||
@@ -42,13 +38,11 @@ func dryRunDashboardList(_ context.Context, runtime *common.RuntimeContext) *com
|
||||
Params(params)
|
||||
}
|
||||
|
||||
// dryRunDashboardGet returns a DryRunAPI for getting a dashboard.
|
||||
func dryRunDashboardGet(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return dryRunDashboardBase(runtime).
|
||||
GET("/open-apis/base/v3/bases/:base_token/dashboards/:dashboard_id")
|
||||
}
|
||||
|
||||
// dryRunDashboardCreate returns a DryRunAPI for creating a dashboard.
|
||||
func dryRunDashboardCreate(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
body := map[string]interface{}{"name": runtime.Str("name")}
|
||||
if themeStyle := strings.TrimSpace(runtime.Str("theme-style")); themeStyle != "" {
|
||||
@@ -59,7 +53,6 @@ func dryRunDashboardCreate(_ context.Context, runtime *common.RuntimeContext) *c
|
||||
Body(body)
|
||||
}
|
||||
|
||||
// dryRunDashboardUpdate returns a DryRunAPI for updating a dashboard.
|
||||
func dryRunDashboardUpdate(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
body := map[string]interface{}{}
|
||||
if name := strings.TrimSpace(runtime.Str("name")); name != "" {
|
||||
@@ -73,13 +66,11 @@ func dryRunDashboardUpdate(_ context.Context, runtime *common.RuntimeContext) *c
|
||||
Body(body)
|
||||
}
|
||||
|
||||
// dryRunDashboardDelete returns a DryRunAPI for deleting a dashboard.
|
||||
func dryRunDashboardDelete(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return dryRunDashboardBase(runtime).
|
||||
DELETE("/open-apis/base/v3/bases/:base_token/dashboards/:dashboard_id")
|
||||
}
|
||||
|
||||
// dryRunDashboardBlockList returns a DryRunAPI for listing dashboard blocks.
|
||||
func dryRunDashboardBlockList(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
params := map[string]interface{}{}
|
||||
if pageSize := strings.TrimSpace(runtime.Str("page-size")); pageSize != "" {
|
||||
@@ -93,7 +84,6 @@ func dryRunDashboardBlockList(_ context.Context, runtime *common.RuntimeContext)
|
||||
Params(params)
|
||||
}
|
||||
|
||||
// dryRunDashboardBlockGet returns a DryRunAPI for getting a dashboard block.
|
||||
func dryRunDashboardBlockGet(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
params := map[string]interface{}{}
|
||||
if userIDType := strings.TrimSpace(runtime.Str("user-id-type")); userIDType != "" {
|
||||
@@ -104,9 +94,7 @@ func dryRunDashboardBlockGet(_ context.Context, runtime *common.RuntimeContext)
|
||||
Params(params)
|
||||
}
|
||||
|
||||
// dryRunDashboardBlockCreate returns a DryRunAPI for creating a dashboard block.
|
||||
func dryRunDashboardBlockCreate(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
body := map[string]interface{}{}
|
||||
if name := strings.TrimSpace(runtime.Str("name")); name != "" {
|
||||
body["name"] = name
|
||||
@@ -115,7 +103,7 @@ func dryRunDashboardBlockCreate(_ context.Context, runtime *common.RuntimeContex
|
||||
body["type"] = blockType
|
||||
}
|
||||
if raw := runtime.Str("data-config"); raw != "" {
|
||||
if parsed, err := parseJSONObject(pc, raw, "data-config"); err == nil {
|
||||
if parsed, err := parseJSONObject(raw, "data-config"); err == nil {
|
||||
body["data_config"] = parsed
|
||||
}
|
||||
}
|
||||
@@ -130,15 +118,13 @@ func dryRunDashboardBlockCreate(_ context.Context, runtime *common.RuntimeContex
|
||||
Body(body)
|
||||
}
|
||||
|
||||
// dryRunDashboardBlockUpdate returns a DryRunAPI for updating a dashboard block.
|
||||
func dryRunDashboardBlockUpdate(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
body := map[string]interface{}{}
|
||||
if name := strings.TrimSpace(runtime.Str("name")); name != "" {
|
||||
body["name"] = name
|
||||
}
|
||||
if raw := runtime.Str("data-config"); raw != "" {
|
||||
if parsed, err := parseJSONObject(pc, raw, "data-config"); err == nil {
|
||||
if parsed, err := parseJSONObject(raw, "data-config"); err == nil {
|
||||
body["data_config"] = parsed
|
||||
}
|
||||
}
|
||||
@@ -152,7 +138,6 @@ func dryRunDashboardBlockUpdate(_ context.Context, runtime *common.RuntimeContex
|
||||
Body(body)
|
||||
}
|
||||
|
||||
// dryRunDashboardBlockDelete returns a DryRunAPI for deleting a dashboard block.
|
||||
func dryRunDashboardBlockDelete(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return dryRunDashboardBase(runtime).
|
||||
DELETE("/open-apis/base/v3/bases/:base_token/dashboards/:dashboard_id/blocks/:block_id")
|
||||
@@ -160,7 +145,6 @@ func dryRunDashboardBlockDelete(_ context.Context, runtime *common.RuntimeContex
|
||||
|
||||
// ── Dashboard CRUD ──────────────────────────────────────────────────
|
||||
|
||||
// executeDashboardList lists all dashboards in a base.
|
||||
func executeDashboardList(runtime *common.RuntimeContext) error {
|
||||
params := map[string]interface{}{}
|
||||
if pageSize := strings.TrimSpace(runtime.Str("page-size")); pageSize != "" {
|
||||
@@ -177,7 +161,6 @@ func executeDashboardList(runtime *common.RuntimeContext) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// executeDashboardGet retrieves a dashboard by ID.
|
||||
func executeDashboardGet(runtime *common.RuntimeContext) error {
|
||||
data, err := baseV3Call(runtime, "GET", baseV3Path("bases", runtime.Str("base-token"), "dashboards", runtime.Str("dashboard-id")), nil, nil)
|
||||
if err != nil {
|
||||
@@ -187,7 +170,6 @@ func executeDashboardGet(runtime *common.RuntimeContext) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// executeDashboardCreate creates a new dashboard.
|
||||
func executeDashboardCreate(runtime *common.RuntimeContext) error {
|
||||
body := map[string]interface{}{"name": runtime.Str("name")}
|
||||
if themeStyle := strings.TrimSpace(runtime.Str("theme-style")); themeStyle != "" {
|
||||
@@ -201,7 +183,6 @@ func executeDashboardCreate(runtime *common.RuntimeContext) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// executeDashboardUpdate updates an existing dashboard.
|
||||
func executeDashboardUpdate(runtime *common.RuntimeContext) error {
|
||||
body := map[string]interface{}{}
|
||||
if name := strings.TrimSpace(runtime.Str("name")); name != "" {
|
||||
@@ -218,7 +199,6 @@ func executeDashboardUpdate(runtime *common.RuntimeContext) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// executeDashboardDelete deletes a dashboard by ID.
|
||||
func executeDashboardDelete(runtime *common.RuntimeContext) error {
|
||||
_, err := baseV3Call(runtime, "DELETE", baseV3Path("bases", runtime.Str("base-token"), "dashboards", runtime.Str("dashboard-id")), nil, nil)
|
||||
if err != nil {
|
||||
@@ -230,7 +210,6 @@ func executeDashboardDelete(runtime *common.RuntimeContext) error {
|
||||
|
||||
// ── Dashboard Block CRUD ────────────────────────────────────────────
|
||||
|
||||
// executeDashboardBlockList lists all blocks in a dashboard.
|
||||
func executeDashboardBlockList(runtime *common.RuntimeContext) error {
|
||||
params := map[string]interface{}{}
|
||||
if pageSize := strings.TrimSpace(runtime.Str("page-size")); pageSize != "" {
|
||||
@@ -247,7 +226,6 @@ func executeDashboardBlockList(runtime *common.RuntimeContext) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// executeDashboardBlockGet retrieves a dashboard block by ID.
|
||||
func executeDashboardBlockGet(runtime *common.RuntimeContext) error {
|
||||
params := map[string]interface{}{}
|
||||
if userIDType := strings.TrimSpace(runtime.Str("user-id-type")); userIDType != "" {
|
||||
@@ -261,9 +239,7 @@ func executeDashboardBlockGet(runtime *common.RuntimeContext) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// executeDashboardBlockCreate creates a new dashboard block.
|
||||
func executeDashboardBlockCreate(runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
body := map[string]interface{}{}
|
||||
if name := strings.TrimSpace(runtime.Str("name")); name != "" {
|
||||
body["name"] = name
|
||||
@@ -272,7 +248,7 @@ func executeDashboardBlockCreate(runtime *common.RuntimeContext) error {
|
||||
body["type"] = blockType
|
||||
}
|
||||
if raw := runtime.Str("data-config"); raw != "" {
|
||||
parsed, err := parseJSONObject(pc, raw, "data-config")
|
||||
parsed, err := parseJSONObject(raw, "data-config")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -292,15 +268,13 @@ func executeDashboardBlockCreate(runtime *common.RuntimeContext) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// executeDashboardBlockUpdate updates an existing dashboard block.
|
||||
func executeDashboardBlockUpdate(runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
body := map[string]interface{}{}
|
||||
if name := strings.TrimSpace(runtime.Str("name")); name != "" {
|
||||
body["name"] = name
|
||||
}
|
||||
if raw := runtime.Str("data-config"); raw != "" {
|
||||
parsed, err := parseJSONObject(pc, raw, "data-config")
|
||||
parsed, err := parseJSONObject(raw, "data-config")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -319,7 +293,6 @@ func executeDashboardBlockUpdate(runtime *common.RuntimeContext) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// executeDashboardBlockDelete deletes a dashboard block by ID.
|
||||
func executeDashboardBlockDelete(runtime *common.RuntimeContext) error {
|
||||
_, err := baseV3Call(runtime, "DELETE", baseV3Path("bases", runtime.Str("base-token"), "dashboards", runtime.Str("dashboard-id"), "blocks", runtime.Str("block-id")), nil, nil)
|
||||
if err != nil {
|
||||
@@ -328,36 +301,3 @@ func executeDashboardBlockDelete(runtime *common.RuntimeContext) error {
|
||||
runtime.Out(map[string]interface{}{"deleted": true, "block_id": runtime.Str("block-id")}, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ── Dashboard Arrange ────────────────────────────────────────────────
|
||||
|
||||
// dryRunDashboardArrange returns a DryRunAPI for the dashboard arrange endpoint.
|
||||
func dryRunDashboardArrange(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
params := map[string]interface{}{}
|
||||
if userIDType := strings.TrimSpace(runtime.Str("user-id-type")); userIDType != "" {
|
||||
params["user_id_type"] = userIDType
|
||||
}
|
||||
return dryRunDashboardBase(runtime).
|
||||
POST("/open-apis/base/v3/bases/:base_token/dashboards/:dashboard_id/arrange").
|
||||
Params(params).
|
||||
Body(map[string]interface{}{})
|
||||
}
|
||||
|
||||
// executeDashboardArrange sends a POST request to auto-arrange dashboard blocks layout.
|
||||
func executeDashboardArrange(runtime *common.RuntimeContext) error {
|
||||
params := map[string]interface{}{}
|
||||
if userIDType := strings.TrimSpace(runtime.Str("user-id-type")); userIDType != "" {
|
||||
params["user_id_type"] = userIDType
|
||||
}
|
||||
// 请求体为空对象,由服务端智能重排
|
||||
data, err := baseV3Call(runtime, "POST", baseV3Path("bases", runtime.Str("base-token"), "dashboards", runtime.Str("dashboard-id"), "arrange"), params, map[string]interface{}{})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if data == nil {
|
||||
data = map[string]interface{}{}
|
||||
}
|
||||
data["arranged"] = true
|
||||
runtime.Out(data, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -22,10 +22,6 @@ var BaseFieldCreate = common.Shortcut{
|
||||
{Name: "json", Desc: "field property JSON object", Required: true},
|
||||
{Name: "i-have-read-guide", Type: "bool", Desc: "set only after you have read the formula/lookup guide for those field types", Hidden: true},
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: --json '{"name":"Status","type":"text"}'`,
|
||||
"Agent hint: use the lark-base skill's field-create guide for usage and limits.",
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return validateFieldCreate(runtime)
|
||||
},
|
||||
|
||||
@@ -32,8 +32,7 @@ func dryRunFieldGet(_ context.Context, runtime *common.RuntimeContext) *common.D
|
||||
}
|
||||
|
||||
func dryRunFieldCreate(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
body, _ := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
body, _ := parseJSONObject(runtime.Str("json"), "json")
|
||||
return common.NewDryRunAPI().
|
||||
POST("/open-apis/base/v3/bases/:base_token/tables/:table_id/fields").
|
||||
Body(body).
|
||||
@@ -42,8 +41,7 @@ func dryRunFieldCreate(_ context.Context, runtime *common.RuntimeContext) *commo
|
||||
}
|
||||
|
||||
func dryRunFieldUpdate(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
body, _ := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
body, _ := parseJSONObject(runtime.Str("json"), "json")
|
||||
return common.NewDryRunAPI().
|
||||
PUT("/open-apis/base/v3/bases/:base_token/tables/:table_id/fields/:field_id").
|
||||
Body(body).
|
||||
@@ -80,8 +78,7 @@ func dryRunFieldSearchOptions(_ context.Context, runtime *common.RuntimeContext)
|
||||
}
|
||||
|
||||
func validateFieldJSON(runtime *common.RuntimeContext) (map[string]interface{}, error) {
|
||||
pc := newParseCtx(runtime)
|
||||
raw, _ := loadJSONInput(pc, runtime.Str("json"), "json")
|
||||
raw, _ := loadJSONInput(runtime.Str("json"), "json")
|
||||
if raw == "" {
|
||||
return nil, nil
|
||||
}
|
||||
@@ -134,7 +131,7 @@ func executeFieldList(runtime *common.RuntimeContext) error {
|
||||
if total == 0 {
|
||||
total = len(fields)
|
||||
}
|
||||
runtime.Out(map[string]interface{}{"fields": fields, "total": total}, nil)
|
||||
runtime.Out(map[string]interface{}{"items": simplifyFields(fields), "offset": offset, "limit": limit, "count": len(fields), "total": total}, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -151,8 +148,7 @@ func executeFieldGet(runtime *common.RuntimeContext) error {
|
||||
}
|
||||
|
||||
func executeFieldCreate(runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
body, err := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
body, err := parseJSONObject(runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -165,10 +161,9 @@ func executeFieldCreate(runtime *common.RuntimeContext) error {
|
||||
}
|
||||
|
||||
func executeFieldUpdate(runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
baseToken := runtime.Str("base-token")
|
||||
tableIDValue := baseTableID(runtime)
|
||||
body, err := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
body, err := parseJSONObject(runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -23,10 +23,6 @@ var BaseFieldUpdate = common.Shortcut{
|
||||
{Name: "json", Desc: "field property JSON object", Required: true},
|
||||
{Name: "i-have-read-guide", Type: "bool", Desc: "acknowledge reading formula/lookup guide before creating or updating those field types", Hidden: true},
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: --json '{"name":"Status","type":"text"}'`,
|
||||
"Agent hint: use the lark-base skill's field-update guide for usage and limits.",
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return validateFieldUpdate(runtime)
|
||||
},
|
||||
|
||||
@@ -29,8 +29,8 @@ type fieldTypeSpec struct {
|
||||
Extra map[string]interface{}
|
||||
}
|
||||
|
||||
func parseJSONObject(pc *parseCtx, raw string, flagName string) (map[string]interface{}, error) {
|
||||
resolved, err := loadJSONInput(pc, raw, flagName)
|
||||
func parseJSONObject(raw string, flagName string) (map[string]interface{}, error) {
|
||||
resolved, err := loadJSONInput(raw, flagName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -41,8 +41,8 @@ func parseJSONObject(pc *parseCtx, raw string, flagName string) (map[string]inte
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func parseJSONArray(pc *parseCtx, raw string, flagName string) ([]interface{}, error) {
|
||||
resolved, err := loadJSONInput(pc, raw, flagName)
|
||||
func parseJSONArray(raw string, flagName string) ([]interface{}, error) {
|
||||
resolved, err := loadJSONInput(raw, flagName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -53,12 +53,12 @@ func parseJSONArray(pc *parseCtx, raw string, flagName string) ([]interface{}, e
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func parseStringListFlexible(pc *parseCtx, raw string, flagName string) ([]string, error) {
|
||||
func parseStringListFlexible(raw string, flagName string) ([]string, error) {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil, nil
|
||||
}
|
||||
resolved, err := loadJSONInput(pc, raw, flagName)
|
||||
resolved, err := loadJSONInput(raw, flagName)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -82,19 +82,8 @@ func parseStringListFlexible(pc *parseCtx, raw string, flagName string) ([]strin
|
||||
}
|
||||
|
||||
func parseStringList(raw string) []string {
|
||||
raw = strings.TrimSpace(raw)
|
||||
if raw == "" {
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(raw, ",")
|
||||
result := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
item := strings.TrimSpace(part)
|
||||
if item != "" {
|
||||
result = append(result, item)
|
||||
}
|
||||
}
|
||||
return result
|
||||
items, _ := parseStringListFlexible(raw, "fields")
|
||||
return items
|
||||
}
|
||||
|
||||
func deepMergeMaps(dst, src map[string]interface{}) map[string]interface{} {
|
||||
@@ -379,18 +368,7 @@ func baseV3Path(parts ...string) string {
|
||||
func baseV3Raw(runtime *common.RuntimeContext, method, path string, params map[string]interface{}, data interface{}) (map[string]interface{}, error) {
|
||||
queryParams := make(larkcore.QueryParams)
|
||||
for k, v := range params {
|
||||
switch val := v.(type) {
|
||||
case []string:
|
||||
for _, item := range val {
|
||||
queryParams.Add(k, item)
|
||||
}
|
||||
case []interface{}:
|
||||
for _, item := range val {
|
||||
queryParams.Add(k, fmt.Sprintf("%v", item))
|
||||
}
|
||||
default:
|
||||
queryParams.Set(k, fmt.Sprintf("%v", v))
|
||||
}
|
||||
queryParams.Set(k, fmt.Sprintf("%v", v))
|
||||
}
|
||||
req := &larkcore.ApiReq{
|
||||
HttpMethod: strings.ToUpper(method),
|
||||
@@ -673,6 +651,45 @@ func viewName(view map[string]interface{}) string {
|
||||
return v
|
||||
}
|
||||
|
||||
func viewType(view map[string]interface{}) string {
|
||||
if v, _ := view["type"].(string); v != "" {
|
||||
return v
|
||||
}
|
||||
v, _ := view["view_type"].(string)
|
||||
return v
|
||||
}
|
||||
|
||||
func simplifyFields(fields []map[string]interface{}) []interface{} {
|
||||
items := make([]interface{}, 0, len(fields))
|
||||
for _, field := range fields {
|
||||
entry := map[string]interface{}{
|
||||
"field_id": fieldID(field),
|
||||
"field_name": fieldName(field),
|
||||
"type": fieldTypeName(field),
|
||||
}
|
||||
if style, ok := field["style"].(map[string]interface{}); ok && len(style) > 0 {
|
||||
entry["style"] = style
|
||||
}
|
||||
if multiple, ok := field["multiple"].(bool); ok {
|
||||
entry["multiple"] = multiple
|
||||
}
|
||||
items = append(items, entry)
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func simplifyViews(views []map[string]interface{}) []interface{} {
|
||||
items := make([]interface{}, 0, len(views))
|
||||
for _, view := range views {
|
||||
items = append(items, map[string]interface{}{
|
||||
"view_id": viewID(view),
|
||||
"view_name": viewName(view),
|
||||
"view_type": viewType(view),
|
||||
})
|
||||
}
|
||||
return items
|
||||
}
|
||||
|
||||
func canonicalValue(v interface{}) string {
|
||||
switch val := v.(type) {
|
||||
case nil:
|
||||
@@ -956,8 +973,6 @@ func sleepBetweenBatches(index int, total int) {
|
||||
|
||||
// ── Dashboard Block data_config normalization & validation ───────────
|
||||
|
||||
// normalizeDataConfig normalizes data_config fields for dashboard blocks.
|
||||
// It converts series[].rollup to uppercase and group_by[].sort fields to lowercase.
|
||||
func normalizeDataConfig(cfg map[string]interface{}) map[string]interface{} {
|
||||
if cfg == nil {
|
||||
return nil
|
||||
@@ -999,21 +1014,8 @@ func normalizeDataConfig(cfg map[string]interface{}) map[string]interface{} {
|
||||
return out
|
||||
}
|
||||
|
||||
// validateBlockDataConfig validates data_config based on block type.
|
||||
// For text type, it checks for the presence of text field.
|
||||
// For chart types, it validates table_name, series/count_all, group_by, and filter fields.
|
||||
func validateBlockDataConfig(blockType string, cfg map[string]interface{}) []string {
|
||||
var errs []string
|
||||
|
||||
// text 类型特殊校验:只需要有 text 字段即可
|
||||
if strings.ToLower(blockType) == "text" {
|
||||
if txt, _ := cfg["text"].(string); strings.TrimSpace(txt) == "" {
|
||||
errs = append(errs, "text 类型组件缺少必填字段 text")
|
||||
}
|
||||
return errs
|
||||
}
|
||||
|
||||
// 图表类型通用校验
|
||||
// table_name 必填
|
||||
if tn, _ := cfg["table_name"].(string); strings.TrimSpace(tn) == "" {
|
||||
errs = append(errs, "缺少必填字段 table_name")
|
||||
|
||||
@@ -10,12 +10,8 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/larksuite/cli/internal/vfs/localfileio"
|
||||
)
|
||||
|
||||
var testPC = &parseCtx{fio: &localfileio.LocalFileIO{}}
|
||||
|
||||
func TestParseHelpers(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
cwd, err := os.Getwd()
|
||||
@@ -34,36 +30,36 @@ func TestParseHelpers(t *testing.T) {
|
||||
t.Fatalf("write temp file err=%v", err)
|
||||
}
|
||||
_ = tmp.Close()
|
||||
obj, err := parseJSONObject(testPC, `{"name":"demo"}`, "json")
|
||||
obj, err := parseJSONObject(`{"name":"demo"}`, "json")
|
||||
if err != nil || obj["name"] != "demo" {
|
||||
t.Fatalf("obj=%v err=%v", obj, err)
|
||||
}
|
||||
if _, err := parseJSONObject(testPC, `[1]`, "json"); err == nil || !strings.Contains(err.Error(), "invalid JSON object") {
|
||||
if _, err := parseJSONObject(`[1]`, "json"); err == nil || !strings.Contains(err.Error(), "invalid JSON object") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
obj, err = parseJSONObject(testPC, "@"+tmp.Name(), "json")
|
||||
obj, err = parseJSONObject("@"+tmp.Name(), "json")
|
||||
if err != nil || obj["name"] != "from-file" {
|
||||
t.Fatalf("file obj=%v err=%v", obj, err)
|
||||
}
|
||||
arr, err := parseJSONArray(testPC, `[1,2]`, "items")
|
||||
arr, err := parseJSONArray(`[1,2]`, "items")
|
||||
if err != nil || len(arr) != 2 {
|
||||
t.Fatalf("arr=%v err=%v", arr, err)
|
||||
}
|
||||
if _, err := parseJSONArray(testPC, `{"a":1}`, "items"); err == nil || !strings.Contains(err.Error(), "invalid JSON array") {
|
||||
if _, err := parseJSONArray(`{"a":1}`, "items"); err == nil || !strings.Contains(err.Error(), "invalid JSON array") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
list, err := parseStringListFlexible(testPC, "a, b, ,c", "fields")
|
||||
list, err := parseStringListFlexible("a, b, ,c", "fields")
|
||||
if err != nil || !reflect.DeepEqual(list, []string{"a", "b", "c"}) {
|
||||
t.Fatalf("list=%v err=%v", list, err)
|
||||
}
|
||||
list, err = parseStringListFlexible(testPC, `["x","y"]`, "fields")
|
||||
list, err = parseStringListFlexible(`["x","y"]`, "fields")
|
||||
if err != nil || !reflect.DeepEqual(list, []string{"x", "y"}) {
|
||||
t.Fatalf("list=%v err=%v", list, err)
|
||||
}
|
||||
if _, err := parseStringListFlexible(testPC, `[1]`, "fields"); err == nil || !strings.Contains(err.Error(), "invalid JSON string array") {
|
||||
if _, err := parseStringListFlexible(`[1]`, "fields"); err == nil || !strings.Contains(err.Error(), "invalid JSON string array") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if _, err := parseJSONValue(testPC, "{", "json"); err == nil || !strings.Contains(err.Error(), "tip: pass a JSON object/array directly") {
|
||||
if _, err := parseJSONValue("{", "json"); err == nil || !strings.Contains(err.Error(), "tip: pass a JSON object/array directly") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if !reflect.DeepEqual(parseStringList("m,n"), []string{"m", "n"}) {
|
||||
@@ -198,7 +194,7 @@ func TestRecordAndChunkHelpers(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveHelpers(t *testing.T) {
|
||||
func TestResolveAndSimplifyHelpers(t *testing.T) {
|
||||
fields := []map[string]interface{}{{"id": "fld_1", "name": "Name", "type": "text"}, {"field_id": "fld_2", "field_name": "Age", "type": "number", "multiple": true}}
|
||||
tables := []map[string]interface{}{{"id": "tbl_1", "name": "Orders"}}
|
||||
views := []map[string]interface{}{{"id": "vew_1", "name": "Main", "type": "grid"}}
|
||||
@@ -214,6 +210,14 @@ func TestResolveHelpers(t *testing.T) {
|
||||
if _, err := resolveViewRef(views, "Missing"); err == nil || !strings.Contains(err.Error(), "not found") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
simplifiedFields := simplifyFields(fields)
|
||||
if len(simplifiedFields) != 2 {
|
||||
t.Fatalf("simplifiedFields=%v", simplifiedFields)
|
||||
}
|
||||
simplifiedViews := simplifyViews(views)
|
||||
if len(simplifiedViews) != 1 {
|
||||
t.Fatalf("simplifiedViews=%v", simplifiedViews)
|
||||
}
|
||||
}
|
||||
|
||||
func TestFilterAndSortHelpers(t *testing.T) {
|
||||
@@ -258,10 +262,10 @@ func TestFilterAndSortHelpers(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestJSONInputHelpers(t *testing.T) {
|
||||
if got, err := loadJSONInput(testPC, `{"name":"demo"}`, "json"); err != nil || got != `{"name":"demo"}` {
|
||||
if got, err := loadJSONInput(`{"name":"demo"}`, "json"); err != nil || got != `{"name":"demo"}` {
|
||||
t.Fatalf("got=%q err=%v", got, err)
|
||||
}
|
||||
if _, err := loadJSONInput(testPC, "@", "json"); err == nil || !strings.Contains(err.Error(), "file path cannot be empty") {
|
||||
if _, err := loadJSONInput("@", "json"); err == nil || !strings.Contains(err.Error(), "file path cannot be empty") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
tmp := t.TempDir()
|
||||
@@ -277,7 +281,7 @@ func TestJSONInputHelpers(t *testing.T) {
|
||||
if err := os.WriteFile(emptyPath, []byte(" \n"), 0o644); err != nil {
|
||||
t.Fatalf("write empty file err=%v", err)
|
||||
}
|
||||
if _, err := loadJSONInput(testPC, "@"+emptyPath, "json"); err == nil || !strings.Contains(err.Error(), "is empty") {
|
||||
if _, err := loadJSONInput("@"+emptyPath, "json"); err == nil || !strings.Contains(err.Error(), "is empty") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
syntaxErr := formatJSONError("json", "object", &json.SyntaxError{Offset: 7})
|
||||
@@ -306,6 +310,9 @@ func TestIdentifierAndValueHelpers(t *testing.T) {
|
||||
if viewName(map[string]interface{}{"view_name": "Main"}) != "Main" {
|
||||
t.Fatalf("viewName alt key failed")
|
||||
}
|
||||
if viewType(map[string]interface{}{"view_type": "grid"}) != "grid" {
|
||||
t.Fatalf("viewType alt key failed")
|
||||
}
|
||||
if !valueEmpty(nil) || !valueEmpty(" ") || !valueEmpty([]interface{}{}) || !valueEmpty(map[string]interface{}{}) {
|
||||
t.Fatalf("valueEmpty empty cases failed")
|
||||
}
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package base
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
var BaseRecordBatchCreate = common.Shortcut{
|
||||
Service: "base",
|
||||
Command: "+record-batch-create",
|
||||
Description: "Batch create records",
|
||||
Risk: "write",
|
||||
Scopes: []string{"base:record:create"},
|
||||
AuthTypes: authTypes(),
|
||||
Flags: []common.Flag{
|
||||
baseTokenFlag(true),
|
||||
tableRefFlag(true),
|
||||
{Name: "json", Desc: "batch create JSON object", Required: true},
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: --json '{"fields":["Title","Status"],"rows":[["Task A","Open"],["Task B","Done"]]}'`,
|
||||
"Agent hint: use the lark-base skill's record-batch-create guide for usage and limits.",
|
||||
},
|
||||
DryRun: dryRunRecordBatchCreate,
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return executeRecordBatchCreate(runtime)
|
||||
},
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package base
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
var BaseRecordBatchUpdate = common.Shortcut{
|
||||
Service: "base",
|
||||
Command: "+record-batch-update",
|
||||
Description: "Batch update records",
|
||||
Risk: "write",
|
||||
Scopes: []string{"base:record:update"},
|
||||
AuthTypes: authTypes(),
|
||||
Flags: []common.Flag{
|
||||
baseTokenFlag(true),
|
||||
tableRefFlag(true),
|
||||
{Name: "json", Desc: "batch update JSON object", Required: true},
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: --json '{"record_id_list":["recXXX"],"patch":{"Status":"Done"}}'`,
|
||||
"Agent hint: use the lark-base skill's record-batch-update guide for usage and limits.",
|
||||
},
|
||||
DryRun: dryRunRecordBatchUpdate,
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return executeRecordBatchUpdate(runtime)
|
||||
},
|
||||
}
|
||||
@@ -19,7 +19,6 @@ var BaseRecordList = common.Shortcut{
|
||||
Flags: []common.Flag{
|
||||
baseTokenFlag(true),
|
||||
tableRefFlag(true),
|
||||
{Name: "field-id", Type: "string_array", Desc: "field ID or field name to include (repeatable)"},
|
||||
{Name: "view-id", Desc: "view ID"},
|
||||
{Name: "offset", Type: "int", Default: "0", Desc: "pagination offset"},
|
||||
{Name: "limit", Type: "int", Default: "100", Desc: "pagination size"},
|
||||
|
||||
@@ -5,8 +5,6 @@ package base
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/url"
|
||||
"strconv"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
@@ -17,18 +15,13 @@ func dryRunRecordList(_ context.Context, runtime *common.RuntimeContext) *common
|
||||
offset = 0
|
||||
}
|
||||
limit := common.ParseIntBounded(runtime, "limit", 1, 200)
|
||||
params := url.Values{}
|
||||
params.Set("offset", strconv.Itoa(offset))
|
||||
params.Set("limit", strconv.Itoa(limit))
|
||||
for _, field := range recordListFields(runtime) {
|
||||
params.Add("field_id", field)
|
||||
}
|
||||
params := map[string]interface{}{"offset": offset, "limit": limit}
|
||||
if viewID := runtime.Str("view-id"); viewID != "" {
|
||||
params.Set("view_id", viewID)
|
||||
params["view_id"] = viewID
|
||||
}
|
||||
path := "/open-apis/base/v3/bases/:base_token/tables/:table_id/records?" + params.Encode()
|
||||
return common.NewDryRunAPI().
|
||||
GET(path).
|
||||
GET("/open-apis/base/v3/bases/:base_token/tables/:table_id/records").
|
||||
Params(params).
|
||||
Set("base_token", runtime.Str("base-token")).
|
||||
Set("table_id", baseTableID(runtime))
|
||||
}
|
||||
@@ -41,19 +34,8 @@ func dryRunRecordGet(_ context.Context, runtime *common.RuntimeContext) *common.
|
||||
Set("record_id", runtime.Str("record-id"))
|
||||
}
|
||||
|
||||
func dryRunRecordSearch(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
body, _ := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
return common.NewDryRunAPI().
|
||||
POST("/open-apis/base/v3/bases/:base_token/tables/:table_id/records/search").
|
||||
Body(body).
|
||||
Set("base_token", runtime.Str("base-token")).
|
||||
Set("table_id", baseTableID(runtime))
|
||||
}
|
||||
|
||||
func dryRunRecordUpsert(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
body, _ := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
body, _ := parseJSONObject(runtime.Str("json"), "json")
|
||||
if recordID := runtime.Str("record-id"); recordID != "" {
|
||||
return common.NewDryRunAPI().
|
||||
PATCH("/open-apis/base/v3/bases/:base_token/tables/:table_id/records/:record_id").
|
||||
@@ -69,26 +51,6 @@ func dryRunRecordUpsert(_ context.Context, runtime *common.RuntimeContext) *comm
|
||||
Set("table_id", baseTableID(runtime))
|
||||
}
|
||||
|
||||
func dryRunRecordBatchCreate(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
body, _ := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
return common.NewDryRunAPI().
|
||||
POST("/open-apis/base/v3/bases/:base_token/tables/:table_id/records/batch_create").
|
||||
Body(body).
|
||||
Set("base_token", runtime.Str("base-token")).
|
||||
Set("table_id", baseTableID(runtime))
|
||||
}
|
||||
|
||||
func dryRunRecordBatchUpdate(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
body, _ := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
return common.NewDryRunAPI().
|
||||
POST("/open-apis/base/v3/bases/:base_token/tables/:table_id/records/batch_update").
|
||||
Body(body).
|
||||
Set("base_token", runtime.Str("base-token")).
|
||||
Set("table_id", baseTableID(runtime))
|
||||
}
|
||||
|
||||
func dryRunRecordDelete(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return common.NewDryRunAPI().
|
||||
DELETE("/open-apis/base/v3/bases/:base_token/tables/:table_id/records/:record_id").
|
||||
@@ -116,10 +78,6 @@ func validateRecordJSON(runtime *common.RuntimeContext) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func recordListFields(runtime *common.RuntimeContext) []string {
|
||||
return runtime.StrArray("field-id")
|
||||
}
|
||||
|
||||
func executeRecordList(runtime *common.RuntimeContext) error {
|
||||
offset := runtime.Int("offset")
|
||||
if offset < 0 {
|
||||
@@ -127,10 +85,6 @@ func executeRecordList(runtime *common.RuntimeContext) error {
|
||||
}
|
||||
limit := common.ParseIntBounded(runtime, "limit", 1, 200)
|
||||
params := map[string]interface{}{"offset": offset, "limit": limit}
|
||||
fields := recordListFields(runtime)
|
||||
if len(fields) > 0 {
|
||||
params["field_id"] = fields
|
||||
}
|
||||
if viewID := runtime.Str("view-id"); viewID != "" {
|
||||
params["view_id"] = viewID
|
||||
}
|
||||
@@ -151,23 +105,8 @@ func executeRecordGet(runtime *common.RuntimeContext) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func executeRecordSearch(runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
body, err := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := baseV3Call(runtime, "POST", baseV3Path("bases", runtime.Str("base-token"), "tables", baseTableID(runtime), "records", "search"), nil, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
runtime.Out(data, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func executeRecordUpsert(runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
body, err := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
body, err := parseJSONObject(runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -189,36 +128,6 @@ func executeRecordUpsert(runtime *common.RuntimeContext) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func executeRecordBatchCreate(runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
body, err := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := baseV3Raw(runtime, "POST", baseV3Path("bases", runtime.Str("base-token"), "tables", baseTableID(runtime), "records", "batch_create"), nil, body)
|
||||
data, err := handleBaseAPIResult(result, err, "batch create records")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
runtime.Out(data, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func executeRecordBatchUpdate(runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
body, err := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := baseV3Raw(runtime, "POST", baseV3Path("bases", runtime.Str("base-token"), "tables", baseTableID(runtime), "records", "batch_update"), nil, body)
|
||||
data, err := handleBaseAPIResult(result, err, "batch update records")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
runtime.Out(data, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func executeRecordDelete(runtime *common.RuntimeContext) error {
|
||||
_, err := baseV3Call(runtime, "DELETE", baseV3Path("bases", runtime.Str("base-token"), "tables", baseTableID(runtime), "records", runtime.Str("record-id")), nil, nil)
|
||||
if err != nil {
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package base
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
var BaseRecordSearch = common.Shortcut{
|
||||
Service: "base",
|
||||
Command: "+record-search",
|
||||
Description: "Search records in a table",
|
||||
Risk: "read",
|
||||
Scopes: []string{"base:record:read"},
|
||||
AuthTypes: authTypes(),
|
||||
Flags: []common.Flag{
|
||||
baseTokenFlag(true),
|
||||
tableRefFlag(true),
|
||||
{Name: "json", Desc: "record search JSON object", Required: true},
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: --json '{"keyword":"Alice","search_fields":["Name"]}'`,
|
||||
"Agent hint: use the lark-base skill's record-search guide for usage and limits.",
|
||||
},
|
||||
DryRun: dryRunRecordSearch,
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return executeRecordSearch(runtime)
|
||||
},
|
||||
}
|
||||
@@ -14,9 +14,10 @@ import (
|
||||
|
||||
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
|
||||
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/internal/output"
|
||||
"github.com/larksuite/cli/internal/util"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
@@ -90,16 +91,15 @@ func dryRunRecordUploadAttachment(_ context.Context, runtime *common.RuntimeCont
|
||||
|
||||
func executeRecordUploadAttachment(runtime *common.RuntimeContext) error {
|
||||
filePath := runtime.Str("file")
|
||||
fio := runtime.FileIO()
|
||||
if fio == nil {
|
||||
return output.ErrValidation("file operations require a FileIO provider")
|
||||
}
|
||||
fileInfo, err := fio.Stat(filePath)
|
||||
safeFilePath, err := validate.SafeInputPath(filePath)
|
||||
if err != nil {
|
||||
if errors.Is(err, fileio.ErrPathValidation) {
|
||||
return output.ErrValidation("unsafe file path: %s", err)
|
||||
}
|
||||
return output.ErrValidation("file not accessible: %s: %v", filePath, err)
|
||||
return output.ErrValidation("unsafe file path: %s", err)
|
||||
}
|
||||
filePath = safeFilePath
|
||||
|
||||
fileInfo, err := vfs.Stat(filePath)
|
||||
if err != nil {
|
||||
return output.ErrValidation("file not found: %s", filePath)
|
||||
}
|
||||
if fileInfo.Size() > baseAttachmentUploadMaxFileSize {
|
||||
return output.ErrValidation("file %.1fMB exceeds 20MB limit", float64(fileInfo.Size())/1024/1024)
|
||||
@@ -209,7 +209,7 @@ func normalizeAttachmentForPatch(attachment map[string]interface{}) map[string]i
|
||||
}
|
||||
|
||||
func uploadAttachmentToBase(runtime *common.RuntimeContext, filePath, fileName, baseToken string, fileSize int64) (map[string]interface{}, error) {
|
||||
f, err := runtime.FileIO().Open(filePath)
|
||||
f, err := vfs.Open(filePath)
|
||||
if err != nil {
|
||||
return nil, output.ErrValidation("cannot open file: %v", err)
|
||||
}
|
||||
|
||||
@@ -22,9 +22,8 @@ var BaseRecordUpsert = common.Shortcut{
|
||||
recordRefFlag(false),
|
||||
{Name: "json", Desc: "record JSON object", Required: true},
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: --json '{"Name":"Alice"}'`,
|
||||
"Agent hint: use the lark-base skill's record-upsert guide for usage and limits.",
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return validateRecordJSON(runtime)
|
||||
},
|
||||
DryRun: dryRunRecordUpsert,
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
|
||||
@@ -25,8 +25,6 @@ func Shortcuts() []common.Shortcut {
|
||||
BaseViewDelete,
|
||||
BaseViewGetFilter,
|
||||
BaseViewSetFilter,
|
||||
BaseViewGetVisibleFields,
|
||||
BaseViewSetVisibleFields,
|
||||
BaseViewGetGroup,
|
||||
BaseViewSetGroup,
|
||||
BaseViewGetSort,
|
||||
@@ -37,11 +35,8 @@ func Shortcuts() []common.Shortcut {
|
||||
BaseViewSetCard,
|
||||
BaseViewRename,
|
||||
BaseRecordList,
|
||||
BaseRecordSearch,
|
||||
BaseRecordGet,
|
||||
BaseRecordUpsert,
|
||||
BaseRecordBatchCreate,
|
||||
BaseRecordBatchUpdate,
|
||||
BaseRecordUploadAttachment,
|
||||
BaseRecordDelete,
|
||||
BaseRecordHistoryList,
|
||||
@@ -76,7 +71,6 @@ func Shortcuts() []common.Shortcut {
|
||||
BaseDashboardCreate,
|
||||
BaseDashboardUpdate,
|
||||
BaseDashboardDelete,
|
||||
BaseDashboardArrange,
|
||||
BaseDashboardBlockList,
|
||||
BaseDashboardBlockGet,
|
||||
BaseDashboardBlockCreate,
|
||||
|
||||
@@ -68,7 +68,11 @@ func executeTableList(runtime *common.RuntimeContext) error {
|
||||
if total == 0 {
|
||||
total = len(tables)
|
||||
}
|
||||
runtime.Out(map[string]interface{}{"tables": tables, "total": total}, nil)
|
||||
items := make([]interface{}, 0, len(tables))
|
||||
for _, table := range tables {
|
||||
items = append(items, map[string]interface{}{"table_id": tableID(table), "table_name": tableNameFromMap(table)})
|
||||
}
|
||||
runtime.Out(map[string]interface{}{"items": items, "offset": offset, "limit": limit, "count": len(items), "total": total}, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -89,8 +93,8 @@ func executeTableGet(runtime *common.RuntimeContext) error {
|
||||
}
|
||||
runtime.Out(map[string]interface{}{
|
||||
"table": table,
|
||||
"fields": fields,
|
||||
"views": views,
|
||||
"fields": simplifyFields(fields),
|
||||
"views": simplifyViews(views),
|
||||
}, nil)
|
||||
return nil
|
||||
}
|
||||
@@ -103,9 +107,8 @@ func executeTableCreate(runtime *common.RuntimeContext) error {
|
||||
}
|
||||
result := map[string]interface{}{"table": created}
|
||||
tableIDValue := tableID(created)
|
||||
pc := newParseCtx(runtime)
|
||||
if tableIDValue != "" && runtime.Str("fields") != "" {
|
||||
fieldItems, err := parseJSONArray(pc, runtime.Str("fields"), "fields")
|
||||
fieldItems, err := parseJSONArray(runtime.Str("fields"), "fields")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -136,7 +139,7 @@ func executeTableCreate(runtime *common.RuntimeContext) error {
|
||||
result["fields"] = createdFields
|
||||
}
|
||||
if tableIDValue != "" && runtime.Str("view") != "" {
|
||||
viewItems, err := parseObjectList(pc, runtime.Str("view"), "view")
|
||||
viewItems, err := parseObjectList(runtime.Str("view"), "view")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
@@ -21,10 +21,6 @@ var BaseViewCreate = common.Shortcut{
|
||||
tableRefFlag(true),
|
||||
{Name: "json", Desc: "view JSON object/array", Required: true},
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: --json '{"name":"Main","type":"grid"}'`,
|
||||
"Agent hint: use the lark-base skill's view-create guide for usage and limits.",
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return validateViewCreate(runtime)
|
||||
},
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package base
|
||||
|
||||
import (
|
||||
"context"
|
||||
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
var BaseViewGetVisibleFields = common.Shortcut{
|
||||
Service: "base",
|
||||
Command: "+view-get-visible-fields",
|
||||
Description: "Get view visible fields configuration",
|
||||
Risk: "read",
|
||||
Scopes: []string{"base:view:read"},
|
||||
AuthTypes: authTypes(),
|
||||
Flags: []common.Flag{baseTokenFlag(true), tableRefFlag(true), viewRefFlag(true)},
|
||||
DryRun: dryRunViewGetVisibleFields,
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return executeViewGetProperty(runtime, "visible_fields", "visible_fields")
|
||||
},
|
||||
}
|
||||
@@ -35,9 +35,8 @@ func dryRunViewGet(_ context.Context, runtime *common.RuntimeContext) *common.Dr
|
||||
}
|
||||
|
||||
func dryRunViewCreate(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
api := dryRunViewBase(runtime)
|
||||
bodyList, err := parseObjectList(pc, runtime.Str("json"), "json")
|
||||
bodyList, err := parseObjectList(runtime.Str("json"), "json")
|
||||
if err != nil || len(bodyList) == 0 {
|
||||
return api.POST("/open-apis/base/v3/bases/:base_token/tables/:table_id/views")
|
||||
}
|
||||
@@ -58,16 +57,14 @@ func dryRunViewGetProperty(runtime *common.RuntimeContext, segment string) *comm
|
||||
}
|
||||
|
||||
func dryRunViewSetJSONObject(runtime *common.RuntimeContext, segment string) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
body, _ := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
body, _ := parseJSONObject(runtime.Str("json"), "json")
|
||||
return dryRunViewBase(runtime).
|
||||
PUT(fmt.Sprintf("/open-apis/base/v3/bases/:base_token/tables/:table_id/views/:view_id/%s", url.PathEscape(segment))).
|
||||
Body(body)
|
||||
}
|
||||
|
||||
func dryRunViewSetWrapped(runtime *common.RuntimeContext, segment string, wrapper string) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
raw, err := parseJSONValue(pc, runtime.Str("json"), "json")
|
||||
raw, err := parseJSONValue(runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
raw = nil
|
||||
}
|
||||
@@ -80,18 +77,10 @@ func dryRunViewGetFilter(_ context.Context, runtime *common.RuntimeContext) *com
|
||||
return dryRunViewGetProperty(runtime, "filter")
|
||||
}
|
||||
|
||||
func dryRunViewGetVisibleFields(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return dryRunViewGetProperty(runtime, "visible_fields")
|
||||
}
|
||||
|
||||
func dryRunViewSetFilter(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return dryRunViewSetJSONObject(runtime, "filter")
|
||||
}
|
||||
|
||||
func dryRunViewSetVisibleFields(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return dryRunViewSetJSONObject(runtime, "visible_fields")
|
||||
}
|
||||
|
||||
func dryRunViewGetGroup(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return dryRunViewGetProperty(runtime, "group")
|
||||
}
|
||||
@@ -162,7 +151,7 @@ func executeViewList(runtime *common.RuntimeContext) error {
|
||||
if total == 0 {
|
||||
total = len(views)
|
||||
}
|
||||
runtime.Out(map[string]interface{}{"views": views, "total": total}, nil)
|
||||
runtime.Out(map[string]interface{}{"items": simplifyViews(views), "offset": offset, "limit": limit, "count": len(views), "total": total}, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -179,10 +168,9 @@ func executeViewGet(runtime *common.RuntimeContext) error {
|
||||
}
|
||||
|
||||
func executeViewCreate(runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
baseToken := runtime.Str("base-token")
|
||||
tableIDValue := baseTableID(runtime)
|
||||
viewItems, err := parseObjectList(pc, runtime.Str("json"), "json")
|
||||
viewItems, err := parseObjectList(runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -223,11 +211,10 @@ func executeViewGetProperty(runtime *common.RuntimeContext, segment string, key
|
||||
}
|
||||
|
||||
func executeViewSetJSONObject(runtime *common.RuntimeContext, segment string, key string) error {
|
||||
pc := newParseCtx(runtime)
|
||||
baseToken := runtime.Str("base-token")
|
||||
tableIDValue := baseTableID(runtime)
|
||||
viewRef := runtime.Str("view-id")
|
||||
body, err := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
body, err := parseJSONObject(runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -240,11 +227,10 @@ func executeViewSetJSONObject(runtime *common.RuntimeContext, segment string, ke
|
||||
}
|
||||
|
||||
func executeViewSetWrapped(runtime *common.RuntimeContext, segment string, wrapper string, key string) error {
|
||||
pc := newParseCtx(runtime)
|
||||
baseToken := runtime.Str("base-token")
|
||||
tableIDValue := baseTableID(runtime)
|
||||
viewRef := runtime.Str("view-id")
|
||||
raw, err := parseJSONValue(pc, runtime.Str("json"), "json")
|
||||
raw, err := parseJSONValue(runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -257,23 +243,6 @@ func executeViewSetWrapped(runtime *common.RuntimeContext, segment string, wrapp
|
||||
return nil
|
||||
}
|
||||
|
||||
func executeViewSetVisibleFields(runtime *common.RuntimeContext) error {
|
||||
pc := newParseCtx(runtime)
|
||||
baseToken := runtime.Str("base-token")
|
||||
tableIDValue := baseTableID(runtime)
|
||||
viewRef := runtime.Str("view-id")
|
||||
body, err := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := baseV3CallAny(runtime, "PUT", baseV3Path("bases", baseToken, "tables", tableIDValue, "views", viewRef, "visible_fields"), nil, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
runtime.Out(map[string]interface{}{"visible_fields": data}, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func executeViewRename(runtime *common.RuntimeContext) error {
|
||||
baseToken := runtime.Str("base-token")
|
||||
tableIDValue := baseTableID(runtime)
|
||||
|
||||
@@ -22,10 +22,6 @@ var BaseViewSetCard = common.Shortcut{
|
||||
viewRefFlag(true),
|
||||
{Name: "json", Desc: "card JSON object", Required: true},
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: --json '{"cover_field":"fldCover"}'`,
|
||||
"Agent hint: use the lark-base skill's view-set-card guide for usage and limits.",
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return validateViewJSONObject(runtime)
|
||||
},
|
||||
|
||||
@@ -22,10 +22,6 @@ var BaseViewSetFilter = common.Shortcut{
|
||||
viewRefFlag(true),
|
||||
{Name: "json", Desc: "filter JSON object", Required: true},
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: --json '{"logic":"and","conditions":[["fldStatus","==","Todo"]]}'`,
|
||||
"Agent hint: use the lark-base skill's view-set-filter guide for usage and limits.",
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return validateViewJSONObject(runtime)
|
||||
},
|
||||
|
||||
@@ -20,11 +20,7 @@ var BaseViewSetGroup = common.Shortcut{
|
||||
baseTokenFlag(true),
|
||||
tableRefFlag(true),
|
||||
viewRefFlag(true),
|
||||
{Name: "json", Desc: "group JSON object", Required: true},
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: --json '{"group_config":[{"field":"fldStatus","desc":false}]}'`,
|
||||
"Agent hint: use the lark-base skill's view-set-group guide for usage and limits.",
|
||||
{Name: "json", Desc: "group JSON object/array", Required: true},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return validateViewJSONValue(runtime)
|
||||
|
||||
@@ -20,11 +20,7 @@ var BaseViewSetSort = common.Shortcut{
|
||||
baseTokenFlag(true),
|
||||
tableRefFlag(true),
|
||||
viewRefFlag(true),
|
||||
{Name: "json", Desc: "sort_config JSON object", Required: true},
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: --json '{"sort_config":[{"field":"fldPriority","desc":true}]}'`,
|
||||
"Agent hint: use the lark-base skill's view-set-sort guide for usage and limits.",
|
||||
{Name: "json", Desc: "sort JSON object/array", Required: true},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return validateViewJSONValue(runtime)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user