mirror of
https://github.com/larksuite/cli.git
synced 2026-08-03 08:32:46 +08:00
Compare commits
31 Commits
v1.0.74
...
sun/tempv2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f13ff1b267 | ||
|
|
20cf972725 | ||
|
|
4807283368 | ||
|
|
d2bb36591f | ||
|
|
5a54bc07db | ||
|
|
a528b3cb69 | ||
|
|
f0176af330 | ||
|
|
715aa8d960 | ||
|
|
ebc0c53ab5 | ||
|
|
1e682bd97c | ||
|
|
70424c486c | ||
|
|
b8f56dbc0b | ||
|
|
c74d9b63fb | ||
|
|
67015eef8e | ||
|
|
af8507ea8e | ||
|
|
02c2ebcf7c | ||
|
|
abf6f99d7e | ||
|
|
8ba910eb9f | ||
|
|
78bf126bb0 | ||
|
|
4eefe32c1a | ||
|
|
8f6f8eb0fc | ||
|
|
80323bb464 | ||
|
|
0a33bd7c57 | ||
|
|
aafaed06a7 | ||
|
|
54ddcf490b | ||
|
|
bb246b591f | ||
|
|
fc2761d16b | ||
|
|
409a3172da | ||
|
|
483aadee3b | ||
|
|
e43f497650 | ||
|
|
990d633c07 |
16
.github/workflows/ci.yml
vendored
16
.github/workflows/ci.yml
vendored
@@ -99,6 +99,22 @@ jobs:
|
||||
- name: Run tests
|
||||
run: go test -v -race -count=1 -timeout=5m ./cmd/... ./internal/... ./shortcuts/... ./extension/...
|
||||
|
||||
windows-compat:
|
||||
needs: fast-gate
|
||||
runs-on: windows-latest
|
||||
steps:
|
||||
- uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5
|
||||
- uses: actions/setup-go@4a3601121dd01d1626a1e23e37211e3254c1c06c # v6
|
||||
with:
|
||||
go-version-file: go.mod
|
||||
- uses: actions/setup-python@a309ff8b426b58ec0e2a45f0f869d46889d02405 # v6
|
||||
with:
|
||||
python-version: '3.x'
|
||||
- name: Fetch meta data
|
||||
run: python scripts/fetch_meta.py
|
||||
- name: Run Windows compatibility tests
|
||||
run: go test -count=1 -timeout=5m . ./shortcuts/doc/...
|
||||
|
||||
lint:
|
||||
needs: fast-gate
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
103
.github/workflows/release.yml
vendored
103
.github/workflows/release.yml
vendored
@@ -9,7 +9,40 @@ permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
goreleaser:
|
||||
preflight:
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
contents: read
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
with:
|
||||
fetch-depth: 0
|
||||
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
|
||||
with:
|
||||
node-version: '22.14.0'
|
||||
|
||||
- name: Validate tag and commit
|
||||
env:
|
||||
TAG: ${{ github.ref_name }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
node scripts/release-preflight.js --tag "$TAG"
|
||||
git fetch origin main
|
||||
HEAD_SHA="$(git rev-parse --verify 'HEAD^{commit}')"
|
||||
MAIN_SHA="$(git rev-parse --verify 'FETCH_HEAD^{commit}')"
|
||||
TAG_SHA="$(git rev-parse --verify "refs/tags/${TAG}^{commit}")"
|
||||
if [[ "$TAG_SHA" != "$HEAD_SHA" ]]; then
|
||||
echo "Tag ${TAG} does not resolve to the checked-out HEAD commit." >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! git merge-base --is-ancestor "$HEAD_SHA" "$MAIN_SHA"; then
|
||||
echo "Tag ${TAG} does not point to a commit contained in origin/main." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
build-release:
|
||||
needs: preflight
|
||||
runs-on: ubuntu-22.04
|
||||
permissions:
|
||||
contents: write
|
||||
@@ -26,35 +59,79 @@ jobs:
|
||||
with:
|
||||
python-version: '3.x'
|
||||
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
|
||||
with:
|
||||
node-version: '22.14.0'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Install pinned npm
|
||||
run: npm install --global npm@11.16.0
|
||||
|
||||
- name: Run GoReleaser
|
||||
uses: goreleaser/goreleaser-action@e435ccd777264be153ace6237001ef4d979d3a7a # v6
|
||||
with:
|
||||
version: '~> v2'
|
||||
args: release --clean
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GITHUB_TOKEN: ${{ github.token }}
|
||||
|
||||
- name: Include release checksums
|
||||
run: |
|
||||
set -euo pipefail
|
||||
test -s dist/checksums.txt
|
||||
(cd dist && sha256sum --check checksums.txt)
|
||||
cp dist/checksums.txt checksums.txt
|
||||
|
||||
- name: Collect release asset
|
||||
run: |
|
||||
set -euo pipefail
|
||||
mkdir npm-publish-asset
|
||||
cp dist/*.tar.gz dist/*.zip dist/checksums.txt npm-publish-asset/
|
||||
|
||||
- name: Upload release asset
|
||||
uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4
|
||||
with:
|
||||
name: npm-publish-asset-${{ github.run_id }}
|
||||
path: npm-publish-asset/
|
||||
if-no-files-found: error
|
||||
overwrite: true
|
||||
|
||||
publish-npm:
|
||||
needs: goreleaser
|
||||
needs: build-release
|
||||
runs-on: ubuntu-22.04
|
||||
environment: npm-production
|
||||
permissions:
|
||||
contents: read
|
||||
id-token: write
|
||||
steps:
|
||||
- uses: actions/checkout@34e114876b0b11c390a56381ad16ebd13914f8d5 # v4
|
||||
|
||||
- uses: actions/setup-node@49933ea5288caeca8642d1e84afbd3f7d6820020 # v4
|
||||
- uses: actions/setup-node@249970729cb0ef3589644e2896645e5dc5ba9c38 # v6
|
||||
with:
|
||||
node-version: '20'
|
||||
node-version: '22.14.0'
|
||||
registry-url: 'https://registry.npmjs.org'
|
||||
package-manager-cache: false
|
||||
|
||||
- name: Download checksums from release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
- name: Install pinned npm
|
||||
run: npm install --global npm@11.16.0
|
||||
|
||||
- name: Download release asset
|
||||
uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8
|
||||
with:
|
||||
name: npm-publish-asset-${{ github.run_id }}
|
||||
path: npm-publish-asset
|
||||
|
||||
- name: Verify npm publish asset
|
||||
run: |
|
||||
set -euo pipefail
|
||||
TAG="${GITHUB_REF_NAME}"
|
||||
gh release download "${TAG}" --pattern checksums.txt --dir .
|
||||
test -s checksums.txt || { echo "checksums.txt missing or empty for ${TAG}"; exit 1; }
|
||||
(cd npm-publish-asset && sha256sum --check checksums.txt)
|
||||
cp npm-publish-asset/checksums.txt checksums.txt
|
||||
PACK_JSON="$(npm pack --ignore-scripts --json)"
|
||||
PACK_FILE="$(node -e 'const p=JSON.parse(process.argv[1]); if(p.length!==1 || !p[0].filename) process.exit(1); process.stdout.write(p[0].filename)' "$PACK_JSON")"
|
||||
test -s "$PACK_FILE"
|
||||
tar -tzf "$PACK_FILE" | grep -qx 'package/checksums.txt'
|
||||
rm "$PACK_FILE"
|
||||
|
||||
- name: Publish to npm
|
||||
env:
|
||||
NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
run: npm publish --access public
|
||||
|
||||
1
.gitignore
vendored
1
.gitignore
vendored
@@ -42,6 +42,7 @@ tests/mail/reports/
|
||||
|
||||
# Generated / test artifacts
|
||||
.hammer/
|
||||
.lark-cli-e2e-test/reports/
|
||||
.lark-slides/
|
||||
/notes/
|
||||
/minutes/
|
||||
|
||||
31
CHANGELOG.md
31
CHANGELOG.md
@@ -2,6 +2,36 @@
|
||||
|
||||
All notable changes to this project will be documented in this file.
|
||||
|
||||
## [v1.0.75] - 2026-07-22
|
||||
|
||||
### Features
|
||||
|
||||
- add okr single create shortcut & skill text opti (#1941)
|
||||
- **calendar**: auto-add bot self as attendee and note user-only search (#1991)
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **base**: improve table shortcut behavior & guidance (#1803)
|
||||
- issue#1935 & whiteboard shortcut reformat (#1980)
|
||||
- remove legacy shortcut (#1997)
|
||||
- **e2e**: inject shared credentials by identity (#1995)
|
||||
|
||||
### Documentation
|
||||
|
||||
- **skill**: describe html5 block xml usage (#1380)
|
||||
- clarify fetch metadata and user cites (#1981)
|
||||
- add topic move collector workflow (#1473)
|
||||
- update lark doc HTML size limit (#2001)
|
||||
- **base**: align record write schema guidance (#2000)
|
||||
|
||||
### Tests
|
||||
|
||||
- **e2e**: declare request identities explicitly (#2004)
|
||||
|
||||
### Misc
|
||||
|
||||
- harden npm release publishing (#1918)
|
||||
|
||||
## [v1.0.74] - 2026-07-21
|
||||
|
||||
### Features
|
||||
@@ -1608,6 +1638,7 @@ Bundled AI agent skills for intelligent assistance:
|
||||
- Bilingual documentation (English & Chinese).
|
||||
- CI/CD pipelines: linting, testing, coverage reporting, and automated releases.
|
||||
|
||||
[v1.0.75]: https://github.com/larksuite/cli/releases/tag/v1.0.75
|
||||
[v1.0.74]: https://github.com/larksuite/cli/releases/tag/v1.0.74
|
||||
[v1.0.73]: https://github.com/larksuite/cli/releases/tag/v1.0.73
|
||||
[v1.0.72]: https://github.com/larksuite/cli/releases/tag/v1.0.72
|
||||
|
||||
2
Makefile
2
Makefile
@@ -51,7 +51,7 @@ script-test:
|
||||
bash scripts/resolve-changed-from.test.sh
|
||||
bash scripts/ci-workflow.test.sh
|
||||
bash scripts/semantic-review-workflow.test.sh
|
||||
$(NODE) --test scripts/e2e_domains.test.js scripts/fetch_e2e_tat.test.js scripts/semantic-review-verify-artifact.test.js scripts/pr-quality-summary.test.js scripts/semantic-review-publish.test.js scripts/ci-quality-summary-publish.test.js
|
||||
$(NODE) --test scripts/e2e_domains.test.js scripts/fetch_e2e_tat.test.js scripts/install.test.js scripts/release-preflight.test.js scripts/semantic-review-verify-artifact.test.js scripts/pr-quality-summary.test.js scripts/semantic-review-publish.test.js scripts/ci-quality-summary-publish.test.js
|
||||
|
||||
# ./extension/... keeps the public plugin SDK in the default test matrix.
|
||||
unit-test: fetch_meta
|
||||
|
||||
105
cmd/build_bench_test.go
Normal file
105
cmd/build_bench_test.go
Normal file
@@ -0,0 +1,105 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"runtime"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// BenchmarkBuild_Default measures the per-Build cost for the default
|
||||
// configuration (service commands + shortcuts + plugins + strict mode).
|
||||
// This is the hot-path baseline for repeated Build invocations.
|
||||
func BenchmarkBuild_Default(b *testing.B) {
|
||||
// Warm one-time caches first
|
||||
_ = Build(context.Background(), cmdutil.InvocationContext{})
|
||||
runtime.GC()
|
||||
|
||||
b.ResetTimer()
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = Build(context.Background(), cmdutil.InvocationContext{})
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkBuild_WithoutServiceCommands measures the Build cost without
|
||||
// service command registration. The delta from Default gives the
|
||||
// service-command registration cost.
|
||||
func BenchmarkBuild_WithoutServiceCommands(b *testing.B) {
|
||||
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutServiceCommands())
|
||||
runtime.GC()
|
||||
|
||||
b.ResetTimer()
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutServiceCommands())
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkBuild_WithoutPlugins measures the Build cost without plugins.
|
||||
// The delta from Default gives the plugin + policy + hook cost.
|
||||
func BenchmarkBuild_WithoutPlugins(b *testing.B) {
|
||||
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutPlugins())
|
||||
runtime.GC()
|
||||
|
||||
b.ResetTimer()
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutPlugins())
|
||||
}
|
||||
}
|
||||
|
||||
// BenchmarkBuild_WithoutServiceAndPlugins measures the Build cost with
|
||||
// neither service commands nor plugins. This isolates the base cost
|
||||
// (root command + builtins + shortcuts).
|
||||
func BenchmarkBuild_WithoutServiceAndPlugins(b *testing.B) {
|
||||
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutServiceCommands(), WithoutPlugins())
|
||||
runtime.GC()
|
||||
|
||||
b.ResetTimer()
|
||||
b.ReportAllocs()
|
||||
for i := 0; i < b.N; i++ {
|
||||
_ = Build(context.Background(), cmdutil.InvocationContext{}, WithoutServiceCommands(), WithoutPlugins())
|
||||
}
|
||||
}
|
||||
|
||||
// TestBuild_CommandTreeStats counts the total number of commands,
|
||||
// runnable commands, and flags in the default build. This gives us
|
||||
// the scale of the command tree to reason about optimization targets.
|
||||
func TestBuild_CommandTreeStats(t *testing.T) {
|
||||
root := Build(context.Background(), cmdutil.InvocationContext{}, WithoutPlugins())
|
||||
|
||||
var totalCmds, runnableCmds, groupCmds int
|
||||
var totalFlags int
|
||||
|
||||
var walk func(cmd *cobra.Command)
|
||||
walk = func(cmd *cobra.Command) {
|
||||
totalCmds++
|
||||
if cmd.RunE != nil || cmd.Run != nil {
|
||||
runnableCmds++
|
||||
} else {
|
||||
groupCmds++
|
||||
}
|
||||
if cmd.Flags() != nil {
|
||||
cmd.Flags().VisitAll(func(f *pflag.Flag) {
|
||||
totalFlags++
|
||||
})
|
||||
}
|
||||
for _, child := range cmd.Commands() {
|
||||
walk(child)
|
||||
}
|
||||
}
|
||||
walk(root)
|
||||
|
||||
t.Logf("Command tree stats:")
|
||||
t.Logf(" Total commands: %d", totalCmds)
|
||||
t.Logf(" Runnable commands: %d", runnableCmds)
|
||||
t.Logf(" Group commands: %d", groupCmds)
|
||||
t.Logf(" Total flags: %d", totalFlags)
|
||||
}
|
||||
@@ -42,6 +42,15 @@ type FileIO interface {
|
||||
Save(path string, opts SaveOptions, body io.Reader) (SaveResult, error)
|
||||
}
|
||||
|
||||
// TempDirFileCreator is an optional FileIO capability for atomically creating
|
||||
// a unique directory and an empty named file inside it. The directory pattern
|
||||
// follows os.MkdirTemp semantics: the last '*' is replaced with a random
|
||||
// value. Implementations return a relative file path that can be passed back
|
||||
// to FileIO.
|
||||
type TempDirFileCreator interface {
|
||||
CreateTempDirFile(directoryPattern, fileName string) (string, error)
|
||||
}
|
||||
|
||||
// FileInfo is a minimal subset of os.FileInfo covering actual CLI usage.
|
||||
// os.FileInfo satisfies this interface.
|
||||
type FileInfo interface {
|
||||
|
||||
1
go.mod
1
go.mod
@@ -18,6 +18,7 @@ require (
|
||||
github.com/spf13/pflag v1.0.9
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/tidwall/gjson v1.18.0
|
||||
github.com/yuin/goldmark v1.7.16
|
||||
github.com/zalando/go-keyring v0.2.8
|
||||
golang.org/x/net v0.33.0
|
||||
golang.org/x/sync v0.15.0
|
||||
|
||||
2
go.sum
2
go.sum
@@ -131,6 +131,8 @@ github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e h1:JVG44RsyaB9T2KIHavM
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e/go.mod h1:RbqR21r5mrJuqunuUZ/Dhy/avygyECGrLceyNeo4LiM=
|
||||
github.com/yuin/goldmark v1.1.27/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||
github.com/yuin/goldmark v1.7.16 h1:n+CJdUxaFMiDUNnWC3dMWCIQJSkxH4uz3ZwQBkAlVNE=
|
||||
github.com/yuin/goldmark v1.7.16/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg=
|
||||
github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
|
||||
github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
|
||||
36
internal/cmdutil/localfile.go
Normal file
36
internal/cmdutil/localfile.go
Normal file
@@ -0,0 +1,36 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"io/fs"
|
||||
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
)
|
||||
|
||||
// StatLocalFile returns metadata for a path in the process filesystem namespace.
|
||||
// It is intended for advisory validation; callers must validate the opened file
|
||||
// again before using its contents.
|
||||
func StatLocalFile(path string) (fs.FileInfo, error) {
|
||||
localPath, err := validate.LocalInputPath(path)
|
||||
if err != nil {
|
||||
return nil, &fileio.PathValidationError{Err: err}
|
||||
}
|
||||
return vfs.Stat(localPath)
|
||||
}
|
||||
|
||||
// OpenLocalFile opens a path in the process filesystem namespace.
|
||||
// Absolute and relative paths are accepted. It is the shared replacement for
|
||||
// direct os.Open/os.ReadFile use in commands that intentionally read local
|
||||
// paths outside the workspace sandbox. Callers inspect the returned descriptor
|
||||
// before reading so validation and use apply to the same opened file.
|
||||
func OpenLocalFile(path string) (fs.File, error) {
|
||||
localPath, err := validate.LocalInputPath(path)
|
||||
if err != nil {
|
||||
return nil, &fileio.PathValidationError{Err: err}
|
||||
}
|
||||
return vfs.Open(localPath)
|
||||
}
|
||||
96
internal/cmdutil/localfile_test.go
Normal file
96
internal/cmdutil/localfile_test.go
Normal file
@@ -0,0 +1,96 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package cmdutil
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
)
|
||||
|
||||
func TestOpenLocalFile_AcceptsAbsoluteAndParentRelativePaths(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
workDir := filepath.Join(root, "work")
|
||||
if err := os.Mkdir(workDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(root, "input.txt")
|
||||
if err := os.WriteFile(path, []byte("content"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
TestChdir(t, workDir)
|
||||
|
||||
for _, input := range []string{path, filepath.Join("..", "input.txt")} {
|
||||
f, err := OpenLocalFile(input)
|
||||
if err != nil {
|
||||
t.Fatalf("OpenLocalFile(%q) error = %v", input, err)
|
||||
}
|
||||
got, readErr := io.ReadAll(f)
|
||||
closeErr := f.Close()
|
||||
if readErr != nil || closeErr != nil || string(got) != "content" {
|
||||
t.Fatalf("OpenLocalFile(%q) content=%q read=%v close=%v", input, got, readErr, closeErr)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenLocalFile_RejectsInvalidInput(t *testing.T) {
|
||||
if _, err := OpenLocalFile("input\n.txt"); !errors.Is(err, fileio.ErrPathValidation) {
|
||||
t.Fatalf("OpenLocalFile() error = %v, want ErrPathValidation", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStatLocalFile_ReturnsMetadata(t *testing.T) {
|
||||
info, err := StatLocalFile(t.TempDir())
|
||||
if err != nil {
|
||||
t.Fatalf("StatLocalFile() error = %v", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
t.Fatalf("StatLocalFile() mode = %v, want directory", info.Mode())
|
||||
}
|
||||
}
|
||||
|
||||
func TestOpenLocalFile_DoesNotStatBeforeOpen(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "input.txt")
|
||||
if err := os.WriteFile(path, []byte("content"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
previous := vfs.DefaultFS
|
||||
counting := &countingLocalFileFS{FS: previous}
|
||||
vfs.DefaultFS = counting
|
||||
t.Cleanup(func() { vfs.DefaultFS = previous })
|
||||
|
||||
f, err := OpenLocalFile(path)
|
||||
if err != nil {
|
||||
t.Fatalf("OpenLocalFile() error = %v", err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if counting.openCalls != 1 || counting.statCalls != 0 {
|
||||
t.Fatalf("OpenLocalFile() calls: Open=%d Stat=%d, want Open=1 Stat=0", counting.openCalls, counting.statCalls)
|
||||
}
|
||||
}
|
||||
|
||||
type countingLocalFileFS struct {
|
||||
vfs.FS
|
||||
openCalls int
|
||||
statCalls int
|
||||
}
|
||||
|
||||
func (f *countingLocalFileFS) Open(name string) (*os.File, error) {
|
||||
f.openCalls++
|
||||
return f.FS.Open(name)
|
||||
}
|
||||
|
||||
func (f *countingLocalFileFS) Stat(name string) (fs.FileInfo, error) {
|
||||
f.statCalls++
|
||||
return f.FS.Stat(name)
|
||||
}
|
||||
@@ -17,6 +17,13 @@ func SafeInputPath(path string) (string, error) {
|
||||
return localfileio.SafeInputPath(path)
|
||||
}
|
||||
|
||||
// LocalInputPath validates a local input path without restricting it to the
|
||||
// current working directory. It delegates to localfileio.LocalInputPath so
|
||||
// command validation and shared local-file readers use one policy.
|
||||
func LocalInputPath(path string) (string, error) {
|
||||
return localfileio.LocalInputPath(path)
|
||||
}
|
||||
|
||||
// SafeEnvDirPath validates an environment-provided application directory path.
|
||||
// Delegates to localfileio.SafeEnvDirPath.
|
||||
func SafeEnvDirPath(path, envName string) (string, error) {
|
||||
|
||||
@@ -211,6 +211,18 @@ func TestSafeLocalFlagPath(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalInputPath_AllowsLocalPathsAndRejectsUnsafeCharacters(t *testing.T) {
|
||||
for _, path := range []string{"/tmp/report.pdf", "../report.pdf"} {
|
||||
got, err := LocalInputPath(path)
|
||||
if err != nil || got != path {
|
||||
t.Fatalf("LocalInputPath(%q) = %q, %v; want unchanged path", path, got, err)
|
||||
}
|
||||
}
|
||||
if _, err := LocalInputPath("report\n.pdf"); err == nil {
|
||||
t.Fatal("LocalInputPath() unexpectedly accepted a control character")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeUploadPath_AllowsTempFileAbsolutePath(t *testing.T) {
|
||||
// GIVEN: a real temp file (absolute path under os.TempDir())
|
||||
f, err := os.CreateTemp("", "upload-test-*.bin")
|
||||
|
||||
@@ -5,10 +5,14 @@ package localfileio
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/internal/charcheck"
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
)
|
||||
|
||||
@@ -30,6 +34,8 @@ func init() {
|
||||
// and atomic writes are handled internally.
|
||||
type LocalFileIO struct{}
|
||||
|
||||
var _ fileio.TempDirFileCreator = (*LocalFileIO)(nil)
|
||||
|
||||
// Open opens a local file for reading after validating the path.
|
||||
func (l *LocalFileIO) Open(name string) (fileio.File, error) {
|
||||
safePath, err := SafeInputPath(name)
|
||||
@@ -62,6 +68,46 @@ func (l *LocalFileIO) ResolvePath(path string) (string, error) {
|
||||
return resolved, nil
|
||||
}
|
||||
|
||||
// CreateTempDirFile atomically creates a unique directory in the current
|
||||
// working directory, then creates the requested empty file inside it.
|
||||
func (l *LocalFileIO) CreateTempDirFile(directoryPattern, fileName string) (string, error) {
|
||||
if err := validateTempDirectoryPattern(directoryPattern); err != nil {
|
||||
return "", &fileio.PathValidationError{Err: err}
|
||||
}
|
||||
if err := validateTempFileName(fileName); err != nil {
|
||||
return "", &fileio.PathValidationError{Err: err}
|
||||
}
|
||||
tempDir, err := vfs.MkdirTemp(".", directoryPattern)
|
||||
if err != nil {
|
||||
return "", &fileio.MkdirError{Err: err}
|
||||
}
|
||||
path := filepath.Join(tempDir, fileName)
|
||||
tempFile, err := vfs.OpenFile(path, os.O_WRONLY|os.O_CREATE|os.O_EXCL, 0o600)
|
||||
if err != nil {
|
||||
_ = vfs.RemoveAll(tempDir)
|
||||
return "", &fileio.WriteError{Err: err}
|
||||
}
|
||||
if err := tempFile.Close(); err != nil {
|
||||
_ = vfs.RemoveAll(tempDir)
|
||||
return "", &fileio.WriteError{Err: fmt.Errorf("close temporary file: %w", err)}
|
||||
}
|
||||
return filepath.Join(filepath.Base(tempDir), fileName), nil
|
||||
}
|
||||
|
||||
func validateTempDirectoryPattern(pattern string) error {
|
||||
if strings.TrimSpace(pattern) == "" || strings.ContainsAny(pattern, `/\\`) || strings.Count(pattern, "*") != 1 {
|
||||
return fmt.Errorf("temporary directory pattern must be one non-empty path component containing exactly one '*'")
|
||||
}
|
||||
return charcheck.RejectControlChars(pattern, "temporary directory pattern")
|
||||
}
|
||||
|
||||
func validateTempFileName(fileName string) error {
|
||||
if strings.TrimSpace(fileName) == "" || fileName != filepath.Base(fileName) || strings.ContainsAny(fileName, "/\\\t\r\n") {
|
||||
return fmt.Errorf("temporary file name must be one non-empty path component")
|
||||
}
|
||||
return charcheck.RejectControlChars(fileName, "temporary file name")
|
||||
}
|
||||
|
||||
// Save writes body to path atomically after validating the output path.
|
||||
// Parent directories are created as needed. The body is streamed directly
|
||||
// to a temp file and renamed, avoiding full in-memory buffering.
|
||||
|
||||
@@ -4,10 +4,12 @@
|
||||
package localfileio
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
@@ -250,6 +252,81 @@ func TestLocalFileIO_ResolvePath_RejectsAbsolute(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalFileIO_CreateTempDirFileIsUniqueUnderConcurrency(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
testChdir(t, dir)
|
||||
|
||||
const count = 32
|
||||
type result struct {
|
||||
path string
|
||||
err error
|
||||
}
|
||||
results := make(chan result, count)
|
||||
var wg sync.WaitGroup
|
||||
for i := 0; i < count; i++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
path, err := (&LocalFileIO{}).CreateTempDirFile("川西_*_folder", "川西.xml")
|
||||
results <- result{path: path, err: err}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
close(results)
|
||||
|
||||
seen := make(map[string]struct{}, count)
|
||||
for result := range results {
|
||||
if result.err != nil {
|
||||
t.Fatalf("CreateTempDirFile failed: %v", result.err)
|
||||
}
|
||||
directory := filepath.Dir(result.path)
|
||||
if filepath.Base(result.path) != "川西.xml" || filepath.Base(directory) != directory ||
|
||||
!strings.HasPrefix(directory, "川西_") || !strings.HasSuffix(directory, "_folder") {
|
||||
t.Fatalf("CreateTempDirFile path = %q, want 川西_<random>_folder/川西.xml", result.path)
|
||||
}
|
||||
if _, ok := seen[directory]; ok {
|
||||
t.Fatalf("CreateTempDirFile returned duplicate directory %q", directory)
|
||||
}
|
||||
seen[directory] = struct{}{}
|
||||
info, err := os.Stat(result.path)
|
||||
if err != nil {
|
||||
t.Fatalf("stat temporary file %q: %v", result.path, err)
|
||||
}
|
||||
if info.Size() != 0 {
|
||||
t.Fatalf("temporary file %q size = %d, want 0", result.path, info.Size())
|
||||
}
|
||||
}
|
||||
if len(seen) != count {
|
||||
t.Fatalf("unique temporary files = %d, want %d", len(seen), count)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalFileIO_CreateTempDirFileRejectsUnsafeComponents(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
testChdir(t, dir)
|
||||
fio := &LocalFileIO{}
|
||||
|
||||
for _, test := range []struct {
|
||||
pattern string
|
||||
fileName string
|
||||
}{
|
||||
{pattern: "../lark-doc-*", fileName: "draft.xml"},
|
||||
{pattern: "lark-doc-*", fileName: "../draft.xml"},
|
||||
{pattern: "lark-doc-*", fileName: `folder\draft.xml`},
|
||||
} {
|
||||
if _, err := fio.CreateTempDirFile(test.pattern, test.fileName); !errors.Is(err, fileio.ErrPathValidation) {
|
||||
t.Errorf("CreateTempDirFile(%q, %q) error = %v, want path validation", test.pattern, test.fileName, err)
|
||||
}
|
||||
}
|
||||
entries, err := os.ReadDir(dir)
|
||||
if err != nil {
|
||||
t.Fatalf("read work directory: %v", err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("invalid inputs created files: %+v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
// ── Error message consistency ──
|
||||
|
||||
func TestLocalFileIO_ErrorMessages_ContainCorrectFlagName(t *testing.T) {
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"unicode"
|
||||
|
||||
"github.com/larksuite/cli/internal/charcheck"
|
||||
"github.com/larksuite/cli/internal/vfs"
|
||||
@@ -22,6 +23,32 @@ func SafeInputPath(path string) (string, error) {
|
||||
return safePath(path, "--file")
|
||||
}
|
||||
|
||||
// LocalInputPath validates an input path in the process local filesystem
|
||||
// namespace. It intentionally does not impose cwd containment or canonicalize
|
||||
// the path: absolute paths, parent-relative paths, and symlink traversal retain
|
||||
// their normal OS semantics. Character validation remains mandatory because
|
||||
// paths are user-controlled and may appear in errors or progress output.
|
||||
func LocalInputPath(path string) (string, error) {
|
||||
if strings.TrimSpace(path) == "" {
|
||||
return "", fmt.Errorf("local input path must not be empty")
|
||||
}
|
||||
if strings.IndexFunc(path, unicode.IsControl) >= 0 {
|
||||
return "", fmt.Errorf("local input path must not contain control characters")
|
||||
}
|
||||
if err := charcheck.RejectControlChars(path, "local input path"); err != nil {
|
||||
return "", err
|
||||
}
|
||||
if err := validateLocalInputPlatform(path); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return path, nil
|
||||
}
|
||||
|
||||
func isWindowsNonLocalNamespace(path string) bool {
|
||||
normalized := strings.ReplaceAll(path, "/", `\`)
|
||||
return strings.HasPrefix(normalized, `\\`) || strings.HasPrefix(normalized, `\??\`)
|
||||
}
|
||||
|
||||
// SafeLocalFlagPath validates a flag value as a local file path.
|
||||
// Empty values and http/https URLs are returned unchanged without validation.
|
||||
func SafeLocalFlagPath(flagName, value string) (string, error) {
|
||||
@@ -29,7 +56,7 @@ func SafeLocalFlagPath(flagName, value string) (string, error) {
|
||||
return value, nil
|
||||
}
|
||||
if _, err := SafeInputPath(value); err != nil {
|
||||
return "", fmt.Errorf("%s: %v", flagName, err)
|
||||
return "", fmt.Errorf("%s: %w", flagName, err)
|
||||
}
|
||||
return value, nil
|
||||
}
|
||||
|
||||
8
internal/vfs/localfileio/path_local_other.go
Normal file
8
internal/vfs/localfileio/path_local_other.go
Normal file
@@ -0,0 +1,8 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//go:build !windows
|
||||
|
||||
package localfileio
|
||||
|
||||
func validateLocalInputPlatform(string) error { return nil }
|
||||
33
internal/vfs/localfileio/path_local_windows.go
Normal file
33
internal/vfs/localfileio/path_local_windows.go
Normal file
@@ -0,0 +1,33 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//go:build windows
|
||||
|
||||
package localfileio
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
)
|
||||
|
||||
func validateLocalInputPlatform(path string) error {
|
||||
if isWindowsNonLocalNamespace(path) {
|
||||
return fmt.Errorf("local input path must not use a Windows network or device namespace")
|
||||
}
|
||||
|
||||
cleaned := filepath.Clean(path)
|
||||
volume := filepath.VolumeName(cleaned)
|
||||
remainder := strings.TrimLeft(cleaned[len(volume):], `\/`)
|
||||
for _, component := range strings.FieldsFunc(remainder, func(r rune) bool {
|
||||
return r == '\\' || r == '/'
|
||||
}) {
|
||||
if component == "." || component == ".." {
|
||||
continue
|
||||
}
|
||||
if !filepath.IsLocal(component) {
|
||||
return fmt.Errorf("local input path contains a reserved Windows path component %q", component)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
27
internal/vfs/localfileio/path_local_windows_test.go
Normal file
27
internal/vfs/localfileio/path_local_windows_test.go
Normal file
@@ -0,0 +1,27 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//go:build windows
|
||||
|
||||
package localfileio
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestLocalInputPath_RejectsWindowsNetworkDeviceAndReservedPaths(t *testing.T) {
|
||||
for _, input := range []string{
|
||||
`\\server\share\report.pdf`,
|
||||
`//server/share/report.pdf`,
|
||||
`\\.\pipe\upload`,
|
||||
`\\?\C:\Users\agent\report.pdf`,
|
||||
`\\?\UNC\server\share\report.pdf`,
|
||||
`\??\C:\Users\agent\report.pdf`,
|
||||
`C:\Users\agent\NUL.txt`,
|
||||
`CON`,
|
||||
} {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
if _, err := LocalInputPath(input); err == nil {
|
||||
t.Fatalf("LocalInputPath(%q) unexpectedly succeeded", input)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,7 @@
|
||||
package localfileio
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -71,6 +72,72 @@ func TestSafeOutputPath_RejectsPathTraversalAndDangerousInput(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalInputPath_AllowsLocalNamespaceWithoutRewriting(t *testing.T) {
|
||||
for _, input := range []string{
|
||||
"/tmp/report.pdf",
|
||||
"../outside/report.pdf",
|
||||
"./report.pdf",
|
||||
"nested/../report.pdf",
|
||||
`C:\Users\agent\report.pdf`,
|
||||
"报告.pdf",
|
||||
} {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
got, err := LocalInputPath(input)
|
||||
if err != nil {
|
||||
t.Fatalf("LocalInputPath(%q) error = %v", input, err)
|
||||
}
|
||||
if got != input {
|
||||
t.Fatalf("LocalInputPath(%q) = %q, want path preserved verbatim", input, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestWindowsNonLocalNamespace(t *testing.T) {
|
||||
for _, input := range []string{
|
||||
`\\server\share\report.pdf`,
|
||||
`//server/share/report.pdf`,
|
||||
`\\.\pipe\upload`,
|
||||
`\\?\C:\Users\agent\report.pdf`,
|
||||
`\\?\UNC\server\share\report.pdf`,
|
||||
`\??\C:\Users\agent\report.pdf`,
|
||||
} {
|
||||
if !isWindowsNonLocalNamespace(input) {
|
||||
t.Errorf("isWindowsNonLocalNamespace(%q) = false, want true", input)
|
||||
}
|
||||
}
|
||||
|
||||
for _, input := range []string{
|
||||
`C:\Users\agent\report.pdf`,
|
||||
`C:/Users/agent/report.pdf`,
|
||||
`..\outside\report.pdf`,
|
||||
`.\report.pdf`,
|
||||
} {
|
||||
if isWindowsNonLocalNamespace(input) {
|
||||
t.Errorf("isWindowsNonLocalNamespace(%q) = true, want false", input)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLocalInputPath_RejectsEmptyControlAndDangerousUnicode(t *testing.T) {
|
||||
for _, input := range []string{
|
||||
"",
|
||||
" ",
|
||||
"file\x00.txt",
|
||||
"file\tname.txt",
|
||||
"file\nname.txt",
|
||||
"file\rname.txt",
|
||||
"file\u202Ename.txt",
|
||||
"file\u200Bname.txt",
|
||||
} {
|
||||
t.Run(fmt.Sprintf("%q", input), func(t *testing.T) {
|
||||
if _, err := LocalInputPath(input); err == nil {
|
||||
t.Fatalf("LocalInputPath(%q) unexpectedly succeeded", input)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSafeOutputPath_ReturnsCanonicalAbsolutePath(t *testing.T) {
|
||||
// GIVEN: a clean temp directory as CWD
|
||||
dir := t.TempDir()
|
||||
|
||||
7
package-lock.json
generated
7
package-lock.json
generated
@@ -1,15 +1,16 @@
|
||||
{
|
||||
"name": "@larksuite/cli",
|
||||
"version": "1.0.11",
|
||||
"version": "1.0.76",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "@larksuite/cli",
|
||||
"version": "1.0.11",
|
||||
"version": "1.0.76",
|
||||
"cpu": [
|
||||
"x64",
|
||||
"arm64"
|
||||
"arm64",
|
||||
"riscv64"
|
||||
],
|
||||
"hasInstallScript": true,
|
||||
"license": "MIT",
|
||||
|
||||
@@ -1,12 +1,13 @@
|
||||
{
|
||||
"name": "@larksuite/cli",
|
||||
"version": "1.0.74",
|
||||
"version": "1.0.76",
|
||||
"description": "The official CLI for Lark/Feishu open platform",
|
||||
"bin": {
|
||||
"lark-cli": "scripts/run.js"
|
||||
},
|
||||
"scripts": {
|
||||
"postinstall": "node scripts/install.js"
|
||||
"postinstall": "node scripts/install.js",
|
||||
"release:check": "node scripts/release-preflight.js"
|
||||
},
|
||||
"os": [
|
||||
"darwin",
|
||||
|
||||
@@ -265,10 +265,7 @@ function getExpectedChecksum(archiveName, checksumsDir) {
|
||||
const checksumsPath = path.join(dir, "checksums.txt");
|
||||
|
||||
if (!fs.existsSync(checksumsPath)) {
|
||||
console.error(
|
||||
"[WARN] checksums.txt not found, skipping checksum verification"
|
||||
);
|
||||
return null;
|
||||
throw new Error(`[SECURITY] checksums.txt not found at ${checksumsPath}`);
|
||||
}
|
||||
|
||||
const content = fs.readFileSync(checksumsPath, "utf8");
|
||||
@@ -286,7 +283,14 @@ function getExpectedChecksum(archiveName, checksumsDir) {
|
||||
}
|
||||
|
||||
function verifyChecksum(archivePath, expectedHash) {
|
||||
if (expectedHash === null) return;
|
||||
if (typeof expectedHash !== "string" || expectedHash.length === 0) {
|
||||
throw new Error("[SECURITY] Expected checksum is missing or invalid");
|
||||
}
|
||||
if (!/^[0-9a-f]{64}$/i.test(expectedHash)) {
|
||||
throw new Error(
|
||||
"[SECURITY] Expected checksum must be a 64-character hexadecimal SHA-256 digest"
|
||||
);
|
||||
}
|
||||
|
||||
// Stream the file to avoid loading the entire archive into memory.
|
||||
// Archives can be 10-100MB; streaming keeps RSS constant.
|
||||
|
||||
@@ -52,11 +52,12 @@ describe("getExpectedChecksum", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("returns null when checksums.txt does not exist", () => {
|
||||
it("throws [SECURITY]-prefixed Error when checksums.txt does not exist", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "checksum-test-"));
|
||||
// No checksums.txt in dir
|
||||
const result = getExpectedChecksum("anything.tar.gz", dir);
|
||||
assert.equal(result, null);
|
||||
assert.throws(
|
||||
() => getExpectedChecksum("anything.tar.gz", dir),
|
||||
{ message: /^\[SECURITY\] checksums\.txt not found/ }
|
||||
);
|
||||
});
|
||||
|
||||
it("skips malformed lines and still finds valid entry", () => {
|
||||
@@ -106,7 +107,7 @@ describe("verifyChecksum", () => {
|
||||
verifyChecksum(filePath, hash);
|
||||
});
|
||||
|
||||
it("matches case-insensitively", () => {
|
||||
it("accepts a valid uppercase 64-character hex hash", () => {
|
||||
const content = "case test";
|
||||
const filePath = makeTmpFile(content);
|
||||
const hash = sha256(content).toUpperCase();
|
||||
@@ -114,6 +115,40 @@ describe("verifyChecksum", () => {
|
||||
verifyChecksum(filePath, hash);
|
||||
});
|
||||
|
||||
for (const [name, expectedHash] of [
|
||||
["null", null],
|
||||
["empty", ""],
|
||||
["non-string", 123],
|
||||
]) {
|
||||
it(`throws [SECURITY]-prefixed Error for ${name} expected hash`, () => {
|
||||
const filePath = makeTmpFile("real content");
|
||||
assert.throws(
|
||||
() => verifyChecksum(filePath, expectedHash),
|
||||
(err) => {
|
||||
assert.match(err.message, /^\[SECURITY\]/);
|
||||
assert.match(err.message, /Expected checksum is missing or invalid/);
|
||||
return true;
|
||||
}
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
it("throws [SECURITY] format Error for an incorrectly sized hash", () => {
|
||||
const filePath = makeTmpFile("real content");
|
||||
assert.throws(
|
||||
() => verifyChecksum(filePath, "abc123"),
|
||||
{ message: /^\[SECURITY\] Expected checksum must be a 64-character hexadecimal SHA-256 digest$/ }
|
||||
);
|
||||
});
|
||||
|
||||
it("throws [SECURITY] format Error for a non-hex hash", () => {
|
||||
const filePath = makeTmpFile("real content");
|
||||
assert.throws(
|
||||
() => verifyChecksum(filePath, "g".repeat(64)),
|
||||
{ message: /^\[SECURITY\] Expected checksum must be a 64-character hexadecimal SHA-256 digest$/ }
|
||||
);
|
||||
});
|
||||
|
||||
it("throws [SECURITY]-prefixed Error on mismatch", () => {
|
||||
const filePath = makeTmpFile("real content");
|
||||
assert.throws(
|
||||
|
||||
108
scripts/release-preflight.js
Normal file
108
scripts/release-preflight.js
Normal file
@@ -0,0 +1,108 @@
|
||||
#!/usr/bin/env node
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const STABLE_VERSION_PATTERN = /^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/;
|
||||
|
||||
function isStableVersion(value) {
|
||||
return typeof value === "string" && STABLE_VERSION_PATTERN.test(value);
|
||||
}
|
||||
|
||||
function releaseError(message, observed, hint) {
|
||||
return { ok: false, error: { type: "release_preflight", message, observed, hint } };
|
||||
}
|
||||
|
||||
function validateReleasePreflight(packageJson, packageLockJson, tag) {
|
||||
const packageVersion = packageJson?.version;
|
||||
const lockVersion = packageLockJson?.version;
|
||||
const lockRootVersion = packageLockJson?.packages?.[""]?.version;
|
||||
const observed = {
|
||||
packageVersion: packageVersion ?? null,
|
||||
lockVersion: lockVersion ?? null,
|
||||
lockRootVersion: lockRootVersion ?? null,
|
||||
tagVersion: null,
|
||||
};
|
||||
|
||||
for (const [field, value] of [
|
||||
["package.json.version", packageVersion],
|
||||
["package-lock.json.version", lockVersion],
|
||||
['package-lock.json.packages[""].version', lockRootVersion],
|
||||
]) {
|
||||
if (!isStableVersion(value)) {
|
||||
return releaseError(
|
||||
`${field} must be a stable release version in X.Y.Z form`,
|
||||
observed,
|
||||
"Use the same stable X.Y.Z version in all package fields; prerelease and build metadata are not allowed for production releases.",
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (packageVersion !== lockVersion || packageVersion !== lockRootVersion) {
|
||||
return releaseError(
|
||||
"Package version fields do not match",
|
||||
observed,
|
||||
"Synchronize package.json.version and both package-lock.json version fields.",
|
||||
);
|
||||
}
|
||||
|
||||
if (tag === undefined) {
|
||||
return { ok: true, data: observed };
|
||||
}
|
||||
if (typeof tag !== "string" || !tag.startsWith("v") || !isStableVersion(tag.slice(1))) {
|
||||
return releaseError(
|
||||
"--tag must use the stable release form vX.Y.Z",
|
||||
{ ...observed, tag },
|
||||
`Use --tag v${packageVersion}; prerelease and build metadata are not allowed for production releases.`,
|
||||
);
|
||||
}
|
||||
|
||||
const tagVersion = tag.slice(1);
|
||||
if (tagVersion !== packageVersion) {
|
||||
return releaseError(
|
||||
"Tag version does not match the package version",
|
||||
{ ...observed, tagVersion, tag },
|
||||
`Use --tag v${packageVersion}.`,
|
||||
);
|
||||
}
|
||||
return { ok: true, data: { ...observed, tagVersion } };
|
||||
}
|
||||
|
||||
function writeResult(result) {
|
||||
(result.ok ? process.stdout : process.stderr).write(`${JSON.stringify(result)}\n`);
|
||||
if (!result.ok) process.exitCode = 1;
|
||||
}
|
||||
|
||||
function main() {
|
||||
const args = process.argv.slice(2);
|
||||
let tag;
|
||||
if (args.length === 2 && args[0] === "--tag") {
|
||||
tag = args[1];
|
||||
} else if (args.length !== 0) {
|
||||
writeResult(releaseError(
|
||||
"Expected no arguments or --tag vX.Y.Z",
|
||||
{ arguments: args },
|
||||
"Run release:check without arguments or pass exactly one --tag value.",
|
||||
));
|
||||
return;
|
||||
}
|
||||
|
||||
const repoRoot = path.resolve(__dirname, "..");
|
||||
try {
|
||||
const packageJson = JSON.parse(fs.readFileSync(path.join(repoRoot, "package.json"), "utf8"));
|
||||
const packageLockJson = JSON.parse(fs.readFileSync(path.join(repoRoot, "package-lock.json"), "utf8"));
|
||||
writeResult(validateReleasePreflight(packageJson, packageLockJson, tag));
|
||||
} catch (error) {
|
||||
writeResult(releaseError(
|
||||
"Could not read release package metadata",
|
||||
{ reason: error.message },
|
||||
"Ensure package.json and package-lock.json exist and contain valid JSON.",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { validateReleasePreflight };
|
||||
|
||||
if (require.main === module) main();
|
||||
66
scripts/release-preflight.test.js
Normal file
66
scripts/release-preflight.test.js
Normal file
@@ -0,0 +1,66 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
const assert = require("node:assert/strict");
|
||||
const { describe, it } = require("node:test");
|
||||
|
||||
const { validateReleasePreflight } = require("./release-preflight");
|
||||
|
||||
function metadata(version = "1.2.3") {
|
||||
return {
|
||||
packageJson: { version },
|
||||
packageLockJson: {
|
||||
version,
|
||||
packages: { "": { version } },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function assertRejected(result) {
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.error.type, "release_preflight");
|
||||
assert.equal(typeof result.error.message, "string");
|
||||
}
|
||||
|
||||
describe("validateReleasePreflight", () => {
|
||||
it("accepts matching stable package, lock, and tag versions", () => {
|
||||
const { packageJson, packageLockJson } = metadata();
|
||||
|
||||
assert.deepEqual(
|
||||
validateReleasePreflight(packageJson, packageLockJson, "v1.2.3"),
|
||||
{
|
||||
ok: true,
|
||||
data: {
|
||||
packageVersion: "1.2.3",
|
||||
lockVersion: "1.2.3",
|
||||
lockRootVersion: "1.2.3",
|
||||
tagVersion: "1.2.3",
|
||||
},
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("rejects non-stable or inconsistent package metadata", () => {
|
||||
const prerelease = metadata("1.2.3-beta.1");
|
||||
const topLevelMismatch = metadata();
|
||||
topLevelMismatch.packageLockJson.version = "1.2.4";
|
||||
const rootMismatch = metadata();
|
||||
rootMismatch.packageLockJson.packages[""].version = "1.2.4";
|
||||
|
||||
for (const { packageJson, packageLockJson } of [
|
||||
prerelease,
|
||||
topLevelMismatch,
|
||||
rootMismatch,
|
||||
]) {
|
||||
assertRejected(validateReleasePreflight(packageJson, packageLockJson));
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects an invalid or mismatched release tag", () => {
|
||||
const { packageJson, packageLockJson } = metadata();
|
||||
|
||||
for (const tag of ["1.2.3", "v1.2.3-beta.1", "v1.2.4"]) {
|
||||
assertRejected(validateReleasePreflight(packageJson, packageLockJson, tag));
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -3,49 +3,48 @@ set -euo pipefail
|
||||
|
||||
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)"
|
||||
cd "${REPO_ROOT}"
|
||||
|
||||
# Read version from package.json
|
||||
VERSION=$(node -p "require('${REPO_ROOT}/package.json').version")
|
||||
|
||||
if [ -z "$VERSION" ]; then
|
||||
echo "Error: could not read version from package.json" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VERSION=$(node -p "require('./package.json').version")
|
||||
TAG="v${VERSION}"
|
||||
|
||||
node "${SCRIPT_DIR}/release-preflight.js" --tag "${TAG}"
|
||||
|
||||
echo "Version: ${VERSION}"
|
||||
echo "Tag: ${TAG}"
|
||||
|
||||
# Check if tag already exists locally
|
||||
if git rev-parse "$TAG" >/dev/null 2>&1; then
|
||||
echo "Tag ${TAG} already exists locally, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Check if tag already exists on remote
|
||||
if git ls-remote --tags origin "$TAG" | grep -q "$TAG"; then
|
||||
echo "Tag ${TAG} already exists on remote, skipping."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
# Ensure package.json changes are committed before tagging
|
||||
if git diff --name-only | grep -q 'package.json' || git diff --cached --name-only | grep -q 'package.json'; then
|
||||
echo "Error: package.json has uncommitted changes. Please commit before tagging." >&2
|
||||
CURRENT_BRANCH=$(git branch --show-current)
|
||||
if [ "${CURRENT_BRANCH}" != "main" ]; then
|
||||
echo "Error: releases must be tagged from main; current branch is '${CURRENT_BRANCH}'." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Ensure current branch is pushed to remote before tagging
|
||||
CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)
|
||||
LOCAL_SHA=$(git rev-parse HEAD)
|
||||
REMOTE_SHA=$(git rev-parse "origin/${CURRENT_BRANCH}" 2>/dev/null || echo "")
|
||||
if [ "$LOCAL_SHA" != "$REMOTE_SHA" ]; then
|
||||
echo "Error: local branch '${CURRENT_BRANCH}' is not in sync with remote. Please push your commits first." >&2
|
||||
if ! git diff --quiet HEAD -- package.json package-lock.json; then
|
||||
echo "Error: package.json or package-lock.json has uncommitted changes. Please commit them before tagging." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Create and push tag
|
||||
git tag "$TAG"
|
||||
git push origin "$TAG"
|
||||
git fetch origin main
|
||||
|
||||
echo "Successfully created and pushed tag ${TAG}"
|
||||
HEAD_SHA=$(git rev-parse HEAD)
|
||||
FETCHED_MAIN_SHA=$(git rev-parse "FETCH_HEAD^{commit}")
|
||||
if [ "${HEAD_SHA}" != "${FETCHED_MAIN_SHA}" ]; then
|
||||
echo "Error: HEAD must exactly match origin/main before tagging." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
|
||||
echo "Error: local tag ${TAG} already exists." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
REMOTE_TAG=$(git ls-remote --tags origin "refs/tags/${TAG}")
|
||||
if [ -n "${REMOTE_TAG}" ]; then
|
||||
echo "Error: remote tag ${TAG} already exists." >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
git tag "${TAG}" "${HEAD_SHA}"
|
||||
git push origin "refs/tags/${TAG}"
|
||||
|
||||
echo "Successfully pushed tag ${TAG}"
|
||||
|
||||
@@ -12,10 +12,23 @@ import (
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// maxFileListPageSize 是 file_list 分页上限,与后端 paas_storage checkMaxKeys 的 (0, 200] 契约对齐:
|
||||
// page_size > 200 服务端直接返回 ErrInvalidRequest("maxKeys not in range (0, 200]")。CLI 前置校验避免无谓往返。
|
||||
// 注:服务端对 page_size<=0 会兜底为默认值,但 CLI 默认已是 20、显式传 <1 属误用,故与其它 list 命令一致地按 [1, 200] 校验。
|
||||
const maxFileListPageSize = 200
|
||||
|
||||
// validateFileListPageSize 前置校验 --page-size ∈ [1, maxFileListPageSize],与后端 checkMaxKeys 的 (0, 200] 契约对齐。
|
||||
func validateFileListPageSize(n int) error {
|
||||
if n < 1 || n > maxFileListPageSize {
|
||||
return appsValidationParamError("--page-size", "--page-size must be between 1 and %d", maxFileListPageSize)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AppsFileList lists files in a Miaoda app's storage (cursor pagination)。
|
||||
//
|
||||
// GET /apps/{app_id}/storage/file_list。过滤器:--name / --path / --type / --size-gt /
|
||||
// --size-lt / --uploaded-since / --uploaded-until(精确或区间),分页 --page-size/--page-token。
|
||||
// --size-lt / --uploaded-since / --uploaded-until(精确或区间),分页 --page-size(1..200)/--page-token。
|
||||
// file 域不分 dev/online,无 --env。
|
||||
//
|
||||
// pretty 渲染 5 列:file_name / path / size / type / uploaded_at;空结果打 "No files found."。
|
||||
@@ -41,13 +54,17 @@ var AppsFileList = common.Shortcut{
|
||||
{Name: "size-lt", Type: "int", Desc: "filter: size less than (bytes)"},
|
||||
{Name: "uploaded-since", Desc: "filter: uploaded at or after; relative (7d/2h/30s) | date (2026-04-15) | datetime (2026-04-15T10:00:00) | ISO 8601 w/ TZ (bare date/datetime read in local timezone)"},
|
||||
{Name: "uploaded-until", Desc: "filter: uploaded at or before; relative (7d/2h/30s) | date (2026-04-15) | datetime (2026-04-15T10:00:00) | ISO 8601 w/ TZ (bare date/datetime read in local timezone)"},
|
||||
{Name: "page-size", Type: "int", Default: "20", Desc: "page size"},
|
||||
{Name: "page-size", Type: "int", Default: "20", Desc: "page size (1..200)"},
|
||||
{Name: "page-token", Desc: "pagination cursor from previous response"},
|
||||
},
|
||||
Validate: func(ctx context.Context, rctx *common.RuntimeContext) error {
|
||||
if _, err := requireAppID(rctx.Str("app-id")); err != nil {
|
||||
return err
|
||||
}
|
||||
// page_size 前置校验:对齐后端 checkMaxKeys 的 (0, 200] 契约,避免 >200 触发服务端 ErrInvalidRequest。
|
||||
if err := validateFileListPageSize(rctx.Int("page-size")); err != nil {
|
||||
return err
|
||||
}
|
||||
// 设计原则三:<timestamp> 多格式 → 归一化为 RFC3339 UTC,回写到 flag 供 buildFileListParams 透传。
|
||||
for _, f := range []string{"uploaded-since", "uploaded-until"} {
|
||||
if strings.TrimSpace(rctx.Str(f)) == "" {
|
||||
|
||||
@@ -82,6 +82,34 @@ func TestAppsFileList_RequiresAppID(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAppsFileList_PageSizeOutOfRange 验证 --page-size 超出 (0, 200] 契约时前置报 --page-size 校验错误,不发请求。
|
||||
func TestAppsFileList_PageSizeOutOfRange(t *testing.T) {
|
||||
for _, ps := range []string{"0", "201", "500"} {
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
err := runAppsShortcut(t, AppsFileList,
|
||||
[]string{"+file-list", "--app-id", "app_x", "--page-size", ps, "--as", "user"}, factory, stdout)
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("page-size=%s: err = %T %v, want *errs.ValidationError", ps, err, err)
|
||||
}
|
||||
if ve.Param != "--page-size" {
|
||||
t.Fatalf("page-size=%s: Param = %q, want --page-size", ps, ve.Param)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestAppsFileList_PageSizeBoundaryOK 验证边界值 1 与 200 通过校验(dry-run 不报错并把 page_size 下发)。
|
||||
func TestAppsFileList_PageSizeBoundaryOK(t *testing.T) {
|
||||
for _, ps := range []string{"1", "200"} {
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
if err := runAppsShortcut(t, AppsFileList,
|
||||
[]string{"+file-list", "--app-id", "app_x", "--page-size", ps, "--dry-run", "--as", "user"},
|
||||
factory, stdout); err != nil {
|
||||
t.Fatalf("page-size=%s: dry-run err=%v", ps, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 过滤器 + 分页全部进 query(size-gt/lt 走 int,uploaded_since/until 原样)。
|
||||
func TestAppsFileList_DryRunSendsFiltersAndPagination(t *testing.T) {
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
|
||||
@@ -14,7 +14,6 @@ import (
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
@@ -47,21 +46,7 @@ var AppsFileUpload = common.Shortcut{
|
||||
if _, err := requireAppID(rctx.Str("app-id")); err != nil {
|
||||
return err
|
||||
}
|
||||
f := strings.TrimSpace(rctx.Str("file"))
|
||||
if f == "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--file is required").WithParam("--file")
|
||||
}
|
||||
st, err := rctx.FileIO().Stat(f)
|
||||
if err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--file: %v", err).WithParam("--file").WithCause(err)
|
||||
}
|
||||
if st.IsDir() {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--file must be a file, not a directory").WithParam("--file")
|
||||
}
|
||||
if st.Size() > fileUploadMaxBytes {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "file size %d bytes exceeds the 100 MB upload limit", st.Size()).WithParam("--file")
|
||||
}
|
||||
return nil
|
||||
return rctx.ValidateLocalFileFlag("file", fileUploadMaxBytes)
|
||||
},
|
||||
DryRun: func(ctx context.Context, rctx *common.RuntimeContext) *common.DryRunAPI {
|
||||
appID, _ := requireAppID(rctx.Str("app-id"))
|
||||
@@ -76,9 +61,9 @@ var AppsFileUpload = common.Shortcut{
|
||||
return err
|
||||
}
|
||||
localPath := strings.TrimSpace(rctx.Str("file"))
|
||||
content, err := cmdutil.ReadInputFile(rctx.FileIO(), localPath)
|
||||
content, err := rctx.ReadLocalFileFlag("file", fileUploadMaxBytes)
|
||||
if err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--file: %v", err).WithParam("--file").WithCause(err)
|
||||
return err
|
||||
}
|
||||
fileName := filepath.Base(localPath)
|
||||
contentType := mimeByExt(fileName)
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -58,22 +59,17 @@ func TestAppsFileUpload_RejectsDirectory(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAppsFileUpload_DryRunPreUpload 验证 dry-run 输出 POST file_pre_upload,body.file_name 取文件 basename。
|
||||
// TestAppsFileUpload_DryRunPreUpload verifies that dry-run validates the local
|
||||
// file and previews the pre-upload request without reading or uploading it.
|
||||
func TestAppsFileUpload_DryRunPreUpload(t *testing.T) {
|
||||
// Validate 会 Stat --file(在 DryRun 之前),故 dry-run 也需要真实存在的文件。
|
||||
dir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(dir, "logo.png"), []byte("x"), 0o600); err != nil {
|
||||
absolutePath := filepath.Join(t.TempDir(), "logo.png")
|
||||
if err := os.WriteFile(absolutePath, []byte("not-read-by-dry-run"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldWD, _ := os.Getwd()
|
||||
if err := os.Chdir(dir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chdir(oldWD) })
|
||||
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
if err := runAppsShortcut(t, AppsFileUpload,
|
||||
[]string{"+file-upload", "--app-id", "app_x", "--file", "logo.png", "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
[]string{"+file-upload", "--app-id", "app_x", "--file", absolutePath, "--dry-run", "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("dry-run err=%v", err)
|
||||
}
|
||||
var env dryRunAPIEnvelope
|
||||
@@ -87,6 +83,18 @@ func TestAppsFileUpload_DryRunPreUpload(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppsFileUpload_DryRunRejectsMissingFile(t *testing.T) {
|
||||
missingAbsolutePath := filepath.Join(t.TempDir(), "does-not-exist", "logo.png")
|
||||
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
err := runAppsShortcut(t, AppsFileUpload,
|
||||
[]string{"+file-upload", "--app-id", "app_x", "--file", missingAbsolutePath, "--dry-run", "--as", "user"}, factory, stdout)
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || validationErr.Subtype != errs.SubtypeInvalidArgument || validationErr.Param != "--file" {
|
||||
t.Fatalf("error = %T %v, want invalid_argument for --file", err, err)
|
||||
}
|
||||
}
|
||||
|
||||
// 三步直传:pre-upload → 客户端 PUT 字节 → callback。
|
||||
func TestAppsFileUpload_EndToEnd(t *testing.T) {
|
||||
var putBody []byte
|
||||
@@ -149,6 +157,142 @@ func TestAppsFileUpload_EndToEnd(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestAppsFileUpload_AcceptsAbsolutePath verifies that file-upload can read an
|
||||
// absolute path outside the current working directory.
|
||||
func TestAppsFileUpload_AcceptsAbsolutePath(t *testing.T) {
|
||||
var putBody []byte
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method != http.MethodPut {
|
||||
w.WriteHeader(http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
putBody, _ = io.ReadAll(r.Body)
|
||||
w.Header().Set("ETag", `"etag-abs"`)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
// Keep the process cwd unchanged so the temporary file is outside it.
|
||||
dir := t.TempDir()
|
||||
absFile := filepath.Join(dir, "report.pdf")
|
||||
if !filepath.IsAbs(absFile) {
|
||||
t.Fatalf("test setup: %q is not absolute", absFile)
|
||||
}
|
||||
if err := os.WriteFile(absFile, []byte("PDFBYTES"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/storage/file_pre_upload",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"upload_url": srv.URL, "upload_id": "up-abs"}},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/storage/file_upload_callback",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{
|
||||
"file_name": "report.pdf", "path": "/1858537546760999.pdf", "size_bytes": 8,
|
||||
}},
|
||||
})
|
||||
|
||||
if err := runAppsShortcut(t, AppsFileUpload,
|
||||
[]string{"+file-upload", "--app-id", "app_x", "--file", absFile, "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("execute with absolute path err=%v", err)
|
||||
}
|
||||
if string(putBody) != "PDFBYTES" {
|
||||
t.Fatalf("PUT body = %q, want file bytes", putBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppsFileUpload_AcceptsParentRelativePathOutsideCWD(t *testing.T) {
|
||||
var putBody []byte
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
putBody, _ = io.ReadAll(r.Body)
|
||||
w.Header().Set("ETag", `"etag-parent"`)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
root := t.TempDir()
|
||||
workDir := filepath.Join(root, "work")
|
||||
if err := os.Mkdir(workDir, 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(root, "report.pdf"), []byte("PARENT"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
oldWD, _ := os.Getwd()
|
||||
if err := os.Chdir(workDir); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = os.Chdir(oldWD) })
|
||||
|
||||
factory, stdout, reg := newAppsExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/storage/file_pre_upload",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{"upload_url": srv.URL, "upload_id": "up-parent"}},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST", URL: "/open-apis/spark/v1/apps/app_x/storage/file_upload_callback",
|
||||
Body: map[string]interface{}{"code": 0, "data": map[string]interface{}{
|
||||
"file_name": "report.pdf", "path": "/parent.pdf", "size_bytes": 6,
|
||||
}},
|
||||
})
|
||||
|
||||
if err := runAppsShortcut(t, AppsFileUpload,
|
||||
[]string{"+file-upload", "--app-id", "app_x", "--file", filepath.Join("..", "report.pdf"), "--as", "user"}, factory, stdout); err != nil {
|
||||
t.Fatalf("execute with parent-relative path err=%v", err)
|
||||
}
|
||||
if string(putBody) != "PARENT" {
|
||||
t.Fatalf("PUT body = %q, want PARENT", putBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppsFileUpload_RejectsFileAboveLimit(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "too-large.bin")
|
||||
f, err := os.Create(path)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Truncate(fileUploadMaxBytes + 1); err != nil {
|
||||
_ = f.Close()
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := f.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
err = runAppsShortcut(t, AppsFileUpload,
|
||||
[]string{"+file-upload", "--app-id", "app_x", "--file", path, "--as", "user"}, factory, stdout)
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || validationErr.Param != "--file" {
|
||||
t.Fatalf("error = %T %v, want --file ValidationError", err, err)
|
||||
}
|
||||
if !strings.Contains(validationErr.Error(), "limit") {
|
||||
t.Fatalf("error = %v, want size limit context", validationErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAppsFileUpload_RejectsDeviceWithoutReadingIt(t *testing.T) {
|
||||
if runtime.GOOS == "windows" {
|
||||
t.Skip("/dev/zero is unavailable on Windows")
|
||||
}
|
||||
if _, err := os.Stat("/dev/zero"); err != nil {
|
||||
t.Skipf("/dev/zero unavailable: %v", err)
|
||||
}
|
||||
|
||||
factory, stdout, _ := newAppsExecuteFactory(t)
|
||||
err := runAppsShortcut(t, AppsFileUpload,
|
||||
[]string{"+file-upload", "--app-id", "app_x", "--file", "/dev/zero", "--as", "user"}, factory, stdout)
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || validationErr.Param != "--file" {
|
||||
t.Fatalf("error = %T %v, want --file ValidationError", err, err)
|
||||
}
|
||||
if !strings.Contains(validationErr.Error(), "regular file") {
|
||||
t.Fatalf("error = %v, want non-regular-file context", validationErr)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSanitizeUploadFileName_Cases 验证 sanitizeUploadFileName:空格转 %20、去 TOS 非法字符、全非法兜底、非 ASCII 百分号编码。
|
||||
func TestSanitizeUploadFileName_Cases(t *testing.T) {
|
||||
cases := []struct{ in, want string }{
|
||||
|
||||
@@ -104,6 +104,22 @@ func TestDryRunFieldOps(t *testing.T) {
|
||||
assertDryRunContains(t, dryRunFieldUpdate(ctx, rt), "PUT /open-apis/base/v3/bases/app_x/tables/tbl_1/fields/fld_1")
|
||||
assertDryRunContains(t, dryRunFieldDelete(ctx, rt), "DELETE /open-apis/base/v3/bases/app_x/tables/tbl_1/fields/fld_1")
|
||||
assertDryRunContains(t, dryRunFieldSearchOptions(ctx, rt), "GET /open-apis/base/v3/bases/app_x/tables/tbl_1/fields/fld_1/options", "offset=3", "limit=30", "query=open")
|
||||
|
||||
autoNumberRT := newBaseTestRuntime(
|
||||
map[string]string{
|
||||
"base-token": "app_x",
|
||||
"table-id": "tbl_1",
|
||||
"field-id": "fld_1",
|
||||
"json": `{"name":"编号","type":"auto_number","style":{"rules":[{"type":"text","text":"TASK-"},{"type":"created_time","date_format":"yyyyMM"},{"type":"text","text":"-"},{"type":"incremental_number","length":4}]}}`,
|
||||
},
|
||||
nil,
|
||||
nil,
|
||||
)
|
||||
autoNumberDR := dryRunFieldUpdate(ctx, autoNumberRT)
|
||||
assertDryRunContains(t, autoNumberDR, "PUT /open-apis/base/v3/bases/app_x/tables/tbl_1/fields/fld_1", `"name":"编号"`, `"type":"auto_number"`, `"rules":[`, `"length":4`)
|
||||
if out := autoNumberDR.Format(); strings.Contains(out, "auto_serial") || strings.Contains(out, "reformat_existing_records") || strings.Contains(out, "/open-apis/bitable/v1/") {
|
||||
t.Fatalf("auto_number dry-run must stay on v3 field JSON, got:\n%s", out)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDryRunRecordOps(t *testing.T) {
|
||||
@@ -117,7 +133,7 @@ func TestDryRunRecordOps(t *testing.T) {
|
||||
)
|
||||
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")
|
||||
|
||||
listFieldNamesAliasRT := newBaseTestRuntimeWithSlices(
|
||||
listFieldNamesAliasRT := newBaseTestRuntimeWithArrays(
|
||||
map[string]string{"base-token": "app_x", "table-id": "tbl_1"},
|
||||
map[string][]string{"field-names": {"Name", "Age"}},
|
||||
nil,
|
||||
|
||||
@@ -81,6 +81,37 @@ func runShortcutWithAuthTypes(t *testing.T, shortcut common.Shortcut, authTypes
|
||||
return parent.ExecuteContext(context.Background())
|
||||
}
|
||||
|
||||
func assertInvalidArgumentValidation(t *testing.T, err error, wantParam string, wantParams []string, messageContains string) {
|
||||
t.Helper()
|
||||
if err == nil {
|
||||
t.Fatal("expected invalid-argument validation error, got nil")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok || p.Category != errs.CategoryValidation || p.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("expected invalid-argument validation problem, got %T %v", err, err)
|
||||
}
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) {
|
||||
t.Fatalf("expected ValidationError, got %T %v", err, err)
|
||||
}
|
||||
if validationErr.Param != wantParam {
|
||||
t.Fatalf("param=%q, want %q", validationErr.Param, wantParam)
|
||||
}
|
||||
if wantParams != nil {
|
||||
if len(validationErr.Params) != len(wantParams) {
|
||||
t.Fatalf("params=%#v, want %v", validationErr.Params, wantParams)
|
||||
}
|
||||
for i, want := range wantParams {
|
||||
if validationErr.Params[i].Name != want {
|
||||
t.Fatalf("params=%#v, want %v", validationErr.Params, wantParams)
|
||||
}
|
||||
}
|
||||
}
|
||||
if messageContains != "" && !strings.Contains(err.Error(), messageContains) {
|
||||
t.Fatalf("err=%v, want message containing %q", err, messageContains)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseWorkspaceExecuteCreate(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
stderr, _ := factory.IOStreams.ErrOut.(*bytes.Buffer)
|
||||
@@ -818,8 +849,189 @@ func TestBaseFieldExecuteUpdate(t *testing.T) {
|
||||
if err := runShortcut(t, BaseFieldUpdate, []string{"+field-update", "--base-token", "app_x", "--table-id", "tbl_x", "--field-id", "fld_x", "--json", `{"name":"Amount","type":"number"}`, "--yes"}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"updated": true`) || !strings.Contains(got, `"fld_x"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
got := stdout.String()
|
||||
for _, want := range []string{`"updated": true`, `"fld_x"`, `"field_get_recommended": true`, `"next_step": "field_get"`, `"verification_hint"`} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("stdout missing %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestFieldUpdateResultAlwaysRecommendsReadback(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
field interface{}
|
||||
submitted map[string]interface{}
|
||||
hintContains []string
|
||||
}{
|
||||
{
|
||||
name: "direct complex server type overrides simple submitted type",
|
||||
field: map[string]interface{}{"type": "auto_number"},
|
||||
submitted: map[string]interface{}{"type": "number"},
|
||||
hintContains: []string{`submitted type "number"`, `server returned type "auto_number"`},
|
||||
},
|
||||
{
|
||||
name: "nested simple server type still recommends readback",
|
||||
field: map[string]interface{}{"field": map[string]interface{}{"type": "number"}},
|
||||
submitted: map[string]interface{}{"type": "auto_number"},
|
||||
hintContains: []string{`submitted type "auto_number"`, `server returned type "number"`},
|
||||
},
|
||||
{
|
||||
name: "submitted simple type still recommends readback when response omits type",
|
||||
field: map[string]interface{}{"id": "fld_x"},
|
||||
submitted: map[string]interface{}{"type": "text"},
|
||||
hintContains: []string{`type "text"`, "cannot determine the previous type"},
|
||||
},
|
||||
{
|
||||
name: "missing type is conservative",
|
||||
field: map[string]interface{}{"id": "fld_x"},
|
||||
submitted: map[string]interface{}{"name": "Amount"},
|
||||
hintContains: []string{"unknown or uncommon field type", "+field-get"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := fieldUpdateResult(map[string]interface{}{"field": tc.field, "updated": true}, tc.submitted)
|
||||
if got["field_get_recommended"] != true || got["next_step"] != "field_get" {
|
||||
t.Fatalf("result=%#v, want readback recommendation", got)
|
||||
}
|
||||
hint, _ := got["verification_hint"].(string)
|
||||
for _, want := range tc.hintContains {
|
||||
if !strings.Contains(hint, want) {
|
||||
t.Fatalf("verification_hint=%q, want substring %q", hint, want)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseFieldExecuteUpdateNoopReturnsAPIError(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "PUT",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/fields/fld_x",
|
||||
Body: map[string]interface{}{
|
||||
"code": 800070003,
|
||||
"msg": "no operation produced",
|
||||
},
|
||||
})
|
||||
err := runShortcut(t, BaseFieldUpdate, []string{"+field-update", "--base-token", "app_x", "--table-id", "tbl_x", "--field-id", "fld_x", "--json", `{"name":"Amount","type":"number"}`, "--yes"}, factory, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("expected the API no-op response to surface as an error, got nil")
|
||||
}
|
||||
p, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
t.Fatalf("expected a typed API error, got %T %v", err, err)
|
||||
}
|
||||
if p.Category != errs.CategoryAPI || p.Subtype != errs.SubtypeUnknown || p.Code != 800070003 {
|
||||
t.Fatalf("category/subtype/code=%s/%s/%d", p.Category, p.Subtype, p.Code)
|
||||
}
|
||||
var apiErr *errs.APIError
|
||||
if !errors.As(err, &apiErr) {
|
||||
t.Fatalf("expected APIError, got %T %v", err, err)
|
||||
}
|
||||
if got := stdout.String(); strings.TrimSpace(got) != "" {
|
||||
t.Fatalf("no success envelope should be emitted on a no-op API error:\n%s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseFieldExecuteUpdateAutoNumberUsesV3FieldJSON(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
stub := &httpmock.Stub{
|
||||
Method: "PUT",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/fields/fld_x",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"field": map[string]interface{}{"id": "fld_x", "name": "编号", "type": "auto_number"},
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(stub)
|
||||
jsonBody := `{"name":"编号","type":"auto_number","style":{"rules":[{"type":"text","text":"TASK-"},{"type":"created_time","date_format":"yyyyMM"},{"type":"text","text":"-"},{"type":"incremental_number","length":4}]}}`
|
||||
if err := runShortcut(t, BaseFieldUpdate, []string{"+field-update", "--base-token", "app_x", "--table-id", "tbl_x", "--field-id", "fld_x", "--json", jsonBody, "--yes"}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
gotBody := string(stub.CapturedBody)
|
||||
for _, want := range []string{
|
||||
`"name":"编号"`,
|
||||
`"type":"auto_number"`,
|
||||
`"rules":[`,
|
||||
`"date_format":"yyyyMM"`,
|
||||
`"length":4`,
|
||||
} {
|
||||
if !strings.Contains(gotBody, want) {
|
||||
t.Fatalf("request body missing %q:\n%s", want, gotBody)
|
||||
}
|
||||
}
|
||||
for _, forbidden := range []string{"auto_serial", "reformat_existing_records", `"type":1005`} {
|
||||
if strings.Contains(gotBody, forbidden) {
|
||||
t.Fatalf("request body must not contain v1 field %q:\n%s", forbidden, gotBody)
|
||||
}
|
||||
}
|
||||
got := stdout.String()
|
||||
for _, want := range []string{`"updated": true`, `"fld_x"`, `"field_get_recommended": true`, `"next_step": "field_get"`, `"verification_hint"`} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("stdout missing %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
for _, forbidden := range []string{`"reformat_existing_records"`} {
|
||||
if strings.Contains(got, forbidden) {
|
||||
t.Fatalf("stdout must not expose %q:\n%s", forbidden, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseFieldExecuteUpdateDoesNotRejectExtraJSONKeys(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
stub := &httpmock.Stub{
|
||||
Method: "PUT",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/fields/fld_x",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{"id": "fld_x", "name": "编号", "type": "auto_number"},
|
||||
},
|
||||
}
|
||||
reg.Register(stub)
|
||||
// Unknown v3 keys are forwarded unchanged; the server remains the source of
|
||||
// truth for whether a field-update property is supported.
|
||||
jsonBody := `{"name":"编号","type":"auto_number","style":{"rules":[{"type":"incremental_number","length":4}]},"reformat_existing_records":true}`
|
||||
if err := runShortcut(t, BaseFieldUpdate, []string{"+field-update", "--base-token", "app_x", "--table-id", "tbl_x", "--field-id", "fld_x", "--json", jsonBody, "--yes"}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if gotBody := string(stub.CapturedBody); !strings.Contains(gotBody, `"reformat_existing_records":true`) {
|
||||
t.Fatalf("request body must preserve unknown v3 key:\n%s", gotBody)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"updated": true`) {
|
||||
t.Fatalf("expected successful update, got: %s", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseFieldValidateAllowsRatingMaxAboveLimit(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
tests := []struct {
|
||||
name string
|
||||
shortcut common.Shortcut
|
||||
runtime *common.RuntimeContext
|
||||
}{
|
||||
{
|
||||
name: "create",
|
||||
shortcut: BaseFieldCreate,
|
||||
runtime: newBaseTestRuntime(map[string]string{"base-token": "app_x", "table-id": "tbl_x", "json": `{"name":"评分","type":"number","style":{"type":"rating","icon":"star","min":0,"max":20}}`}, nil, nil),
|
||||
},
|
||||
{
|
||||
name: "update",
|
||||
shortcut: BaseFieldUpdate,
|
||||
runtime: newBaseTestRuntime(map[string]string{"base-token": "app_x", "table-id": "tbl_x", "field-id": "fld_x", "json": `{"name":"评分","type":"number","style":{"type":"rating","icon":"star","min":0,"max":20}}`}, nil, nil),
|
||||
},
|
||||
}
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if err := tc.shortcut.Validate(ctx, tc.runtime); err != nil {
|
||||
t.Fatalf("rating max above 10 should not be blocked by CLI validation: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1091,8 +1303,32 @@ func TestBaseFieldExecuteCRUD(t *testing.T) {
|
||||
if err := runShortcut(t, BaseFieldCreate, []string{"+field-create", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"name":"Status","type":"text"}`}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"created": true`) || !strings.Contains(got, `"fld_new"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
got := stdout.String()
|
||||
for _, want := range []string{`"created": true`, `"fld_new"`, `"field_get_recommended": false`, `"next_step": "done"`, `"verification_hint"`} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("stdout missing %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("create generated field recommends readback", 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/fields",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{"id": "fld_auto", "name": "编号", "type": "auto_number"},
|
||||
},
|
||||
})
|
||||
if err := runShortcut(t, BaseFieldCreate, []string{"+field-create", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"name":"编号","type":"auto_number"}`}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
got := stdout.String()
|
||||
for _, want := range []string{`"created": true`, `"fld_auto"`, `"field_get_recommended": true`, `"next_step": "field_get"`, `"verification_hint"`} {
|
||||
if !strings.Contains(got, want) {
|
||||
t.Fatalf("stdout missing %q:\n%s", want, got)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
@@ -1139,11 +1375,58 @@ func TestBaseFieldExecuteCRUD(t *testing.T) {
|
||||
if len(fields) != 2 {
|
||||
t.Fatalf("fields len=%d output=%#v", len(fields), data)
|
||||
}
|
||||
if data["field_get_recommended"] != false || data["next_step"] != "done" || data["verification_hint"] == nil {
|
||||
t.Fatalf("simple batch create must carry field_get_recommended:false + next_step:done + verification_hint: %#v", data)
|
||||
}
|
||||
if !strings.Contains(string(firstStub.CapturedBody), `"name":"A"`) || !strings.Contains(string(secondStub.CapturedBody), `"name":"B"`) {
|
||||
t.Fatalf("unexpected request bodies: %s / %s", firstStub.CapturedBody, secondStub.CapturedBody)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("create array with generated field recommends readback", func(t *testing.T) {
|
||||
oldDelay := fieldCreateBatchDelay
|
||||
fieldCreateBatchDelay = 0
|
||||
t.Cleanup(func() { fieldCreateBatchDelay = oldDelay })
|
||||
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/fields",
|
||||
BodyFilter: func(body []byte) bool {
|
||||
return strings.Contains(string(body), `"name":"Title"`)
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{"id": "fld_title", "name": "Title", "type": "text"},
|
||||
},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/fields",
|
||||
BodyFilter: func(body []byte) bool {
|
||||
return strings.Contains(string(body), `"name":"编号"`)
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{"id": "fld_no", "name": "编号", "type": "auto_number"},
|
||||
},
|
||||
})
|
||||
|
||||
if err := runShortcut(t, BaseFieldCreate, []string{"+field-create", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `[{"name":"Title","type":"text"},{"name":"编号","type":"auto_number"}]`}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
data := decodeBaseEnvelope(t, stdout)
|
||||
if data["created"] != true || data["total"] != float64(2) {
|
||||
t.Fatalf("unexpected output: %#v", data)
|
||||
}
|
||||
if _, ok := data["fields"].([]interface{}); !ok {
|
||||
t.Fatalf("batch create must keep fields array: %#v", data)
|
||||
}
|
||||
if data["field_get_recommended"] != true || data["next_step"] != "field_get" || data["verification_hint"] == nil {
|
||||
t.Fatalf("batch with auto_number must recommend readback: %#v", data)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("delete", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
@@ -1318,6 +1601,32 @@ func TestBaseRecordExecuteReadCreateDelete(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("list field names alias preserves quoted commas and at-sign names", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "field_id=A%2CB&field_id=%40Owner&limit=1&offset=0",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"fields": []interface{}{"A,B", "@Owner"},
|
||||
"record_id_list": []interface{}{"rec_alias_special"},
|
||||
"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-names", `"A,B",@Owner`, "--format", "json",
|
||||
}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if got := stdout.String(); !strings.Contains(got, `"rec_alias_special"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("list json format", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
reg.Register(&httpmock.Stub{
|
||||
@@ -1614,28 +1923,162 @@ func TestBaseRecordExecuteReadCreateDelete(t *testing.T) {
|
||||
}
|
||||
})
|
||||
|
||||
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.Run("list fields alias accepts JSON array projection", 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",
|
||||
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", "--limit", "1", "--fields", `["Name","Age"]`, "--format", "json"}, 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 field ids and field names alias are mutually exclusive", func(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
err := runShortcut(t, BaseRecordList, []string{"+record-list", "--base-token", "app_x", "--table-id", "tbl_x", "--field-id", "Name", "--field-names", "Age"}, factory, stdout)
|
||||
if err == nil || !strings.Contains(err.Error(), "--field-id and --field-names are mutually exclusive") {
|
||||
t.Run("list field names alias accepts repeated projection", 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",
|
||||
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", "--limit", "1", "--field-names", "Name", "--field-names", "Age", "--format", "json"}, 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 legacy fields flag rejected in dry-run", func(t *testing.T) {
|
||||
t.Run("list projection aliases report only supplied ambiguous inputs", func(t *testing.T) {
|
||||
baseArgs := []string{"+record-list", "--base-token", "app_x", "--table-id", "tbl_x"}
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
wantParam string
|
||||
wantParams []string
|
||||
}{
|
||||
{name: "canonical and fields alias", args: []string{"--field-id", "Name", "--fields", `["Age"]`}, wantParam: "--field-id", wantParams: []string{"--field-id", "--fields"}},
|
||||
{name: "canonical and field names alias", args: []string{"--field-id", "Name", "--field-names", "Age"}, wantParam: "--field-id", wantParams: []string{"--field-id", "--field-names"}},
|
||||
{name: "compatibility aliases", args: []string{"--fields", `["Name"]`, "--field-names", "Age"}, wantParam: "--fields", wantParams: []string{"--fields", "--field-names"}},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := append(append([]string{}, baseArgs...), tc.args...)
|
||||
err := runShortcut(t, BaseRecordList, args, factory, stdout)
|
||||
assertInvalidArgumentValidation(t, err, tc.wantParam, tc.wantParams, "mutually exclusive")
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || validationErr.Hint != "Use only --field-id for projection." {
|
||||
t.Fatalf("hint=%q, want canonical projection guidance", validationErr.Hint)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("search json conflict reports each supplied projection parameter", 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") {
|
||||
err := runShortcut(t, BaseRecordSearch, []string{
|
||||
"+record-search", "--base-token", "app_x", "--table-id", "tbl_x",
|
||||
"--json", `{"keyword":"Alice","search_fields":["Name"]}`,
|
||||
"--field-names", "Age",
|
||||
}, factory, stdout)
|
||||
assertInvalidArgumentValidation(t, err, "--json", []string{"--json", "--field-names"}, "mutually exclusive")
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || !strings.Contains(validationErr.Hint, "inside --json") {
|
||||
t.Fatalf("hint=%q, want JSON-body guidance", validationErr.Hint)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("list canonical and alias projections reject duplicates consistently", func(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
args []string
|
||||
param string
|
||||
}{
|
||||
{name: "canonical", args: []string{"--field-id", "Cost--USD", "--field-id", "Cost--USD"}, param: "--field-id"},
|
||||
{name: "fields alias", args: []string{"--fields", `["Cost--USD","Cost--USD"]`}, param: "--fields"},
|
||||
{name: "field names alias", args: []string{"--field-names", "Cost--USD", "--field-names", "Cost--USD"}, param: "--field-names"},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := append([]string{"+record-list", "--base-token", "app_x", "--table-id", "tbl_x"}, tc.args...)
|
||||
err := runShortcut(t, BaseRecordList, args, factory, stdout)
|
||||
assertInvalidArgumentValidation(t, err, tc.param, []string{tc.param}, "duplicate field id")
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("search fields alias accepts JSON array projection", 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{}{"Name", "Age"},
|
||||
"record_id_list": []interface{}{"rec_search"},
|
||||
"data": []interface{}{[]interface{}{"Alice", 18}},
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(searchStub)
|
||||
if err := runShortcut(t, BaseRecordSearch, []string{
|
||||
"+record-search", "--base-token", "app_x", "--table-id", "tbl_x",
|
||||
"--keyword", "Alice", "--search-field", "Name", "--fields", `["Name","Age"]`, "--format", "json",
|
||||
}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if body := string(searchStub.CapturedBody); !strings.Contains(body, `"select_fields":["Name","Age"]`) {
|
||||
t.Fatalf("captured body=%s", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("get field names alias accepts repeated projection", func(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
batchStub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/base/v3/bases/app_x/tables/tbl_x/records/batch_get",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"data": map[string]interface{}{
|
||||
"record_id_list": []interface{}{"rec_1"},
|
||||
"fields": []interface{}{"Name", "Age"},
|
||||
"data": []interface{}{[]interface{}{"Alice", 18}},
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(batchStub)
|
||||
if err := runShortcut(t, BaseRecordGet, []string{
|
||||
"+record-get", "--base-token", "app_x", "--table-id", "tbl_x", "--record-id", "rec_1",
|
||||
"--field-names", "Name", "--field-names", "Age", "--format", "json",
|
||||
}, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if body := string(batchStub.CapturedBody); !strings.Contains(body, `"select_fields":["Name","Age"]`) {
|
||||
t.Fatalf("request body=%s", body)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("get", func(t *testing.T) {
|
||||
@@ -1992,16 +2435,14 @@ func TestBaseRecordExecuteReadCreateDelete(t *testing.T) {
|
||||
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 {
|
||||
if err := runShortcut(t, BaseRecordBatchCreate, []string{"+record-batch-create", "--base-token", "app_x", "--table-id", "tbl_x", "--json", `{"create_records":[{"Name":"Alice"},{"Name":"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"`) {
|
||||
if got := stdout.String(); !strings.Contains(got, `"record_id_list"`) || !strings.Contains(got, `"rec_1"`) {
|
||||
t.Fatalf("stdout=%s", got)
|
||||
}
|
||||
})
|
||||
|
||||
@@ -26,7 +26,7 @@ var BaseFormSubmit = common.Shortcut{
|
||||
Service: "base",
|
||||
Command: "+form-submit",
|
||||
Description: "Submit a form (fill and submit form data)",
|
||||
Risk: "write",
|
||||
Risk: "high-risk-write",
|
||||
Scopes: []string{"base:form:update", "docs:document.media:upload"},
|
||||
AuthTypes: authTypes(),
|
||||
HasFormat: true,
|
||||
@@ -39,6 +39,7 @@ var BaseFormSubmit = common.Shortcut{
|
||||
`Example (no attachments): --share-token shrXXXX --json '{"fields":{"Service Rating":5,"Review":"Good service"}}'`,
|
||||
`Example (with attachments): --share-token shrXXXX --base-token basXXX --json '{"fields":{"Service Rating":5},"attachments":{"Attachment":["./report.pdf"]}}'`,
|
||||
`Cell values in "fields" follow lark-base-cell-value.md conventions; "attachments" maps field names to local file path arrays — the CLI uploads them in parallel and merges them into the submission.`,
|
||||
baseHighRiskYesTip,
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return validateFormSubmit(runtime)
|
||||
|
||||
@@ -28,23 +28,16 @@ func newBaseTestRuntime(stringFlags map[string]string, boolFlags map[string]bool
|
||||
}
|
||||
|
||||
func newBaseTestRuntimeWithArrays(stringFlags map[string]string, stringArrayFlags map[string][]string, boolFlags map[string]bool, intFlags map[string]int) *common.RuntimeContext {
|
||||
return newBaseTestRuntimeWithArraysAndSlices(stringFlags, stringArrayFlags, nil, boolFlags, intFlags)
|
||||
}
|
||||
|
||||
func newBaseTestRuntimeWithSlices(stringFlags map[string]string, stringSliceFlags map[string][]string, boolFlags map[string]bool, intFlags map[string]int) *common.RuntimeContext {
|
||||
return newBaseTestRuntimeWithArraysAndSlices(stringFlags, nil, stringSliceFlags, boolFlags, intFlags)
|
||||
}
|
||||
|
||||
func newBaseTestRuntimeWithArraysAndSlices(stringFlags map[string]string, stringArrayFlags map[string][]string, stringSliceFlags 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 stringSliceFlags {
|
||||
cmd.Flags().StringSlice(name, nil, "")
|
||||
if name == "field-names" {
|
||||
cmd.Flags().StringSlice(name, nil, "")
|
||||
} else {
|
||||
cmd.Flags().StringArray(name, nil, "")
|
||||
}
|
||||
}
|
||||
for name := range boolFlags {
|
||||
cmd.Flags().Bool(name, false, "")
|
||||
@@ -61,11 +54,6 @@ func newBaseTestRuntimeWithArraysAndSlices(stringFlags map[string]string, string
|
||||
_ = cmd.Flags().Set(name, value)
|
||||
}
|
||||
}
|
||||
for name, values := range stringSliceFlags {
|
||||
for _, value := range values {
|
||||
_ = cmd.Flags().Set(name, value)
|
||||
}
|
||||
}
|
||||
for name, value := range boolFlags {
|
||||
if value {
|
||||
_ = cmd.Flags().Set(name, "true")
|
||||
@@ -477,6 +465,40 @@ func TestBaseLimitPageSizeAliasIsHidden(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseRecordProjectionAliasesAreHidden(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
shortcut common.Shortcut
|
||||
}{
|
||||
{name: "record list", shortcut: BaseRecordList},
|
||||
{name: "record search", shortcut: BaseRecordSearch},
|
||||
{name: "record get", shortcut: BaseRecordGet},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
parent := &cobra.Command{Use: "base"}
|
||||
tt.shortcut.Mount(parent, &cmdutil.Factory{})
|
||||
cmd := parent.Commands()[0]
|
||||
|
||||
primary := cmd.Flags().Lookup("field-id")
|
||||
if primary == nil || primary.Hidden {
|
||||
t.Fatalf("public projection flag --field-id missing or hidden: %#v", primary)
|
||||
}
|
||||
help := cmd.Flags().FlagUsages()
|
||||
for _, aliasName := range []string{"fields", "field-names"} {
|
||||
alias := cmd.Flags().Lookup(aliasName)
|
||||
if alias == nil || !alias.Hidden {
|
||||
t.Fatalf("projection alias --%s should exist and be hidden: %#v", aliasName, alias)
|
||||
}
|
||||
if strings.Contains(help, "--"+aliasName) {
|
||||
t.Fatalf("help should not include hidden --%s:\n%s", aliasName, help)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseDashboardHelpGuidesAgents(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
@@ -779,7 +801,8 @@ func TestBaseJSONExamplesLiveInFlagDescriptions(t *testing.T) {
|
||||
name: "record batch create json",
|
||||
shortcut: BaseRecordBatchCreate,
|
||||
wantHelp: []string{
|
||||
`batch create JSON object, e.g. {"fields":["Name","Status"],"rows":[["Task A","Todo"],["Task B",null]]}; rows follow fields order`,
|
||||
"create_records contains one field map per record",
|
||||
`{"create_records":[{"Name":"Task A","Status":"Todo"},{"Name":"Task B","Score":20}]}`,
|
||||
},
|
||||
},
|
||||
{
|
||||
@@ -823,9 +846,13 @@ func TestBaseRecordWriteHelpGuidesAgents(t *testing.T) {
|
||||
"does not auto-upsert by business key",
|
||||
"use +field-list to confirm real writable fields",
|
||||
"do not write system fields, formula, lookup, or attachment fields",
|
||||
"Sub-record/child-record path",
|
||||
"set that link field to a parent record reference array",
|
||||
`{"Parent Link":[{"id":"rec_xxx"}]}`,
|
||||
"do not look for parent_record_id or a separate child-record API",
|
||||
"CellValue happy path: text/phone/url",
|
||||
"select -> \"Todo\"",
|
||||
"multi-select -> [\"Tag A\",\"Tag B\"]",
|
||||
"select (multiple=false) -> \"Todo\"",
|
||||
"select (multiple=true) -> [\"Tag A\",\"Tag B\"]",
|
||||
"datetime -> \"2026-03-24 10:00:00\"",
|
||||
"checkbox -> true/false",
|
||||
`ID-based CellValue: user/group/link fields use arrays like [{"id":"ou_xxx"}]`,
|
||||
@@ -839,11 +866,11 @@ func TestBaseRecordWriteHelpGuidesAgents(t *testing.T) {
|
||||
name: "record batch create",
|
||||
shortcut: BaseRecordBatchCreate,
|
||||
wantTips: []string{
|
||||
"Happy path fields: fields is the column order",
|
||||
"rows is an array of row arrays",
|
||||
"may use null for empty cells",
|
||||
"Happy path field: create_records",
|
||||
"create_records is an array of independent record field maps",
|
||||
`{"create_records":[{"Name":"Task A","Status":"Todo"},{"Name":"Task B","Score":20}]}`,
|
||||
"use +field-list to confirm real writable fields",
|
||||
"Batch create supports max 200 rows per call",
|
||||
"Batch create supports max 200 records per call",
|
||||
"do not immediately +record-list the same table",
|
||||
"CellValue happy path: text/phone/url",
|
||||
`ID-based CellValue: user/group/link fields use arrays like [{"id":"ou_xxx"}]`,
|
||||
@@ -973,11 +1000,17 @@ func TestBaseFieldUpdateHelpGuidesAgents(t *testing.T) {
|
||||
t.Fatalf("flag help missing %q:\n%s", want, help)
|
||||
}
|
||||
}
|
||||
if strings.Contains(help, "reformat-existing-records") {
|
||||
t.Fatalf("+field-update must not expose a --reformat-existing-records flag:\n%s", help)
|
||||
}
|
||||
|
||||
tips := strings.Join(cmdutil.GetTips(cmd), "\n")
|
||||
wantTips := []string{
|
||||
`lark-cli base +field-update --base-token <base_token> --table-id <table_id> --field-id "Status" --json '{"name":"Status","type":"text"}' --yes`,
|
||||
`"type":"select","multiple":false,"options":[{"name":"Todo"},{"name":"Done"}]`,
|
||||
`Example auto_number update: lark-cli base +field-update`,
|
||||
`When --json.type is "auto_number", updating the numbering rules also reapplies them to existing numbers`,
|
||||
"just submit the target field definition and do not add extra low-level parameters",
|
||||
"full field-definition PUT semantics",
|
||||
"Read the current field first with +field-get",
|
||||
"Type conversion is allowlist-based",
|
||||
@@ -990,6 +1023,9 @@ func TestBaseFieldUpdateHelpGuidesAgents(t *testing.T) {
|
||||
t.Fatalf("tips missing %q:\n%s", want, tips)
|
||||
}
|
||||
}
|
||||
if strings.Contains(tips, "--reformat-existing-records") {
|
||||
t.Fatalf("+field-update tips must not ask agents to pass --reformat-existing-records:\n%s", tips)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseAttachmentHelpGuidesAgents(t *testing.T) {
|
||||
@@ -1112,6 +1148,10 @@ func TestBaseFieldValidate(t *testing.T) {
|
||||
if err := BaseFieldUpdate.Validate(ctx, newBaseTestRuntime(map[string]string{"base-token": "b", "table-id": "t", "field-id": "fld_1", "json": `{"name":"f1","type":"formula"}`}, map[string]bool{"i-have-read-guide": true}, nil)); err != nil {
|
||||
t.Fatalf("formula update validate err=%v", err)
|
||||
}
|
||||
autoNumberJSON := `{"name":"编号","type":"auto_number","style":{"rules":[{"type":"text","text":"TASK-"},{"type":"created_time","date_format":"yyyyMM"},{"type":"incremental_number","length":4}]}}`
|
||||
if err := BaseFieldUpdate.Validate(ctx, newBaseTestRuntime(map[string]string{"base-token": "b", "table-id": "t", "field-id": "fld_1", "json": autoNumberJSON}, nil, nil)); err != nil {
|
||||
t.Fatalf("auto number update validate err=%v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseTableValidate(t *testing.T) {
|
||||
@@ -1233,13 +1273,89 @@ func TestBaseRecordValidate(t *testing.T) {
|
||||
)); err != nil {
|
||||
t.Fatalf("record search json with sort-json validate err=%v", err)
|
||||
}
|
||||
if err := BaseRecordSearch.Validate(ctx, newBaseTestRuntime(
|
||||
err := BaseRecordSearch.Validate(ctx, newBaseTestRuntime(
|
||||
map[string]string{"base-token": "b", "table-id": "tbl_1", "json": `{"keyword":"Alice","search_fields":["Name"]}`, "keyword": "Bob"},
|
||||
nil,
|
||||
nil,
|
||||
)); err == nil || !strings.Contains(err.Error(), "--json is mutually exclusive") {
|
||||
t.Fatalf("err=%v", err)
|
||||
))
|
||||
assertInvalidArgumentValidation(t, err, "--json", []string{"--json", "--keyword"}, "mutually exclusive")
|
||||
err = BaseRecordSearch.Validate(ctx, newBaseTestRuntimeWithArrays(
|
||||
map[string]string{"base-token": "b", "table-id": "tbl_1", "json": `{"keyword":"Alice","search_fields":["Name"]}`, "fields": "Name"},
|
||||
map[string][]string{"field-id": {"fld_name"}},
|
||||
nil,
|
||||
nil,
|
||||
))
|
||||
assertInvalidArgumentValidation(t, err, "--json", []string{"--json", "--field-id", "--fields"}, "mutually exclusive")
|
||||
}
|
||||
|
||||
func TestBaseRecordSearchProjectionLimit(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
fields := make([]string, 51)
|
||||
for i := range fields {
|
||||
fields[i] = "Field " + strconv.Itoa(i+1)
|
||||
}
|
||||
|
||||
if err := BaseRecordSearch.Validate(ctx, newBaseTestRuntimeWithArrays(
|
||||
map[string]string{"base-token": "b", "table-id": "tbl_1", "keyword": "Alice"},
|
||||
map[string][]string{"search-field": {"Name"}, "field-id": fields[:50]},
|
||||
nil,
|
||||
nil,
|
||||
)); err != nil {
|
||||
t.Fatalf("50 projection fields should be accepted: %v", err)
|
||||
}
|
||||
|
||||
err := BaseRecordSearch.Validate(ctx, newBaseTestRuntimeWithArrays(
|
||||
map[string]string{"base-token": "b", "table-id": "tbl_1", "keyword": "Alice"},
|
||||
map[string][]string{"search-field": {"Name"}, "field-id": fields},
|
||||
nil,
|
||||
nil,
|
||||
))
|
||||
assertInvalidArgumentValidation(t, err, "--field-id", []string{"--field-id"}, "maximum limit of 50")
|
||||
|
||||
body, marshalErr := json.Marshal(map[string]interface{}{
|
||||
"keyword": "Alice",
|
||||
"search_fields": []string{"Name"},
|
||||
"select_fields": fields,
|
||||
})
|
||||
if marshalErr != nil {
|
||||
t.Fatalf("marshal search body: %v", marshalErr)
|
||||
}
|
||||
err = BaseRecordSearch.Validate(ctx, newBaseTestRuntime(
|
||||
map[string]string{"base-token": "b", "table-id": "tbl_1", "json": string(body)},
|
||||
nil,
|
||||
nil,
|
||||
))
|
||||
assertInvalidArgumentValidation(t, err, "--json", []string{"--json"}, "maximum limit of 50")
|
||||
}
|
||||
|
||||
func TestRecordSearchJSONNullProjectionIsOmitted(t *testing.T) {
|
||||
runtime := newBaseTestRuntime(map[string]string{
|
||||
"json": `{"keyword":"Alice","search_fields":["Name"],"select_fields":null,"sort":{"sort_config":[{"field":"Updated","desc":true}]}}`,
|
||||
}, nil, nil)
|
||||
body, err := recordSearchJSONBody(runtime)
|
||||
if err != nil {
|
||||
t.Fatalf("recordSearchJSONBody() error = %v", err)
|
||||
}
|
||||
if _, exists := body["select_fields"]; exists {
|
||||
t.Fatalf("select_fields:null must normalize to omitted, body=%#v", body)
|
||||
}
|
||||
if sortConfig, ok := body["sort"].([]interface{}); !ok || len(sortConfig) != 1 {
|
||||
t.Fatalf("sort normalization must continue after omitting null select_fields, body=%#v", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBaseRecordSearchJSONProjectionParamIgnoresFlagLikeFieldNames(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
err := BaseRecordSearch.Validate(ctx, newBaseTestRuntime(
|
||||
map[string]string{
|
||||
"base-token": "b",
|
||||
"table-id": "tbl_1",
|
||||
"json": `{"keyword":"cost","search_fields":["Name"],"select_fields":["Cost--USD","Cost--USD"]}`,
|
||||
},
|
||||
nil,
|
||||
nil,
|
||||
))
|
||||
assertInvalidArgumentValidation(t, err, "--json", []string{"--json"}, "duplicate field id")
|
||||
}
|
||||
|
||||
func TestBasePaginationValidationRejectsOutOfRange(t *testing.T) {
|
||||
@@ -1940,8 +2056,8 @@ func TestBaseFormSubmitShortcut(t *testing.T) {
|
||||
if s.Service != "base" {
|
||||
t.Fatalf("Service=%q want base", s.Service)
|
||||
}
|
||||
if s.Risk != "write" {
|
||||
t.Fatalf("Risk=%q want write", s.Risk)
|
||||
if s.Risk != "high-risk-write" {
|
||||
t.Fatalf("Risk=%q want high-risk-write", s.Risk)
|
||||
}
|
||||
if !s.HasFormat {
|
||||
t.Fatal("HasFormat should be true")
|
||||
@@ -2241,6 +2357,7 @@ func TestExecuteFormSubmit(t *testing.T) {
|
||||
"+form-submit",
|
||||
"--share-token", "shr_exec1",
|
||||
"--json", `{"fields":{"Name":"Alice","Rating":5}}`,
|
||||
"--yes",
|
||||
}
|
||||
if err := runShortcut(t, BaseFormSubmit, args, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
@@ -2309,6 +2426,7 @@ func TestExecuteFormSubmit(t *testing.T) {
|
||||
"--share-token", "shr_exec6",
|
||||
"--base-token", "bas_exec6",
|
||||
"--json", `{"attachments":{"File":["./nonexistent.pdf"]}}`,
|
||||
"--yes",
|
||||
}
|
||||
err := runShortcut(t, BaseFormSubmit, args, factory, stdout)
|
||||
if err == nil {
|
||||
@@ -2357,6 +2475,7 @@ func TestExecuteFormSubmit(t *testing.T) {
|
||||
"--share-token", "shr_dedup",
|
||||
"--base-token", "bas_dedup",
|
||||
"--json", `{"attachments":{"FieldA":["./shared.pdf"],"FieldB":["./shared.pdf"]}}`,
|
||||
"--yes",
|
||||
}
|
||||
if err := runShortcut(t, BaseFormSubmit, args, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
@@ -2368,6 +2487,33 @@ func TestExecuteFormSubmit(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
// TestFormSubmitRequiresConfirmation pins the high-risk-write classification:
|
||||
// without --yes the runner's confirmation gate must fire before Execute runs,
|
||||
// returning a typed confirmation_required error and touching no API.
|
||||
func TestFormSubmitRequiresConfirmation(t *testing.T) {
|
||||
if BaseFormSubmit.Risk != "high-risk-write" {
|
||||
t.Fatalf("Risk=%q want high-risk-write", BaseFormSubmit.Risk)
|
||||
}
|
||||
|
||||
factory, stdout, _ := newExecuteFactory(t)
|
||||
args := []string{
|
||||
"+form-submit",
|
||||
"--share-token", "shr_confirm",
|
||||
"--json", `{"fields":{"Rating":5}}`,
|
||||
}
|
||||
err := runShortcut(t, BaseFormSubmit, args, factory, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("expected confirmation_required error without --yes")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
t.Fatalf("expected typed error, got %T: %v", err, err)
|
||||
}
|
||||
if problem.Subtype != errs.SubtypeConfirmationRequired {
|
||||
t.Fatalf("subtype=%q want %q", problem.Subtype, errs.SubtypeConfirmationRequired)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUploadAttachmentsParallel(t *testing.T) {
|
||||
t.Run("single file upload via execute path", func(t *testing.T) {
|
||||
tmpDir := t.TempDir()
|
||||
@@ -2404,6 +2550,7 @@ func TestUploadAttachmentsParallel(t *testing.T) {
|
||||
"--share-token", "shr_para1",
|
||||
"--base-token", "bas_para1",
|
||||
"--json", `{"attachments":{"Doc":["./doc.txt"]}}`,
|
||||
"--yes",
|
||||
}
|
||||
if err := runShortcut(t, BaseFormSubmit, args, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
@@ -2438,6 +2585,7 @@ func TestUploadAttachmentsParallel(t *testing.T) {
|
||||
"--share-token", "shr_err",
|
||||
"--base-token", "bas_err",
|
||||
"--json", `{"attachments":{"Bad":["./bad.txt"]}}`,
|
||||
"--yes",
|
||||
}
|
||||
err := runShortcut(t, BaseFormSubmit, args, factory, stdout)
|
||||
if err == nil {
|
||||
|
||||
@@ -5,6 +5,7 @@ package base
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -36,7 +37,10 @@ func dryRunFieldGet(_ context.Context, runtime *common.RuntimeContext) *common.D
|
||||
|
||||
func dryRunFieldCreate(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
pc := newParseCtx(runtime)
|
||||
bodies, _ := parseFieldCreateBodies(pc, runtime.Str("json"))
|
||||
bodies, err := parseFieldCreateBodies(pc, runtime.Str("json"))
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().Desc(fmt.Sprintf("dry-run validation failed: %v", err))
|
||||
}
|
||||
dr := common.NewDryRunAPI().
|
||||
Set("base_token", runtime.Str("base-token")).
|
||||
Set("table_id", baseTableID(runtime))
|
||||
@@ -48,7 +52,10 @@ 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, err := parseJSONObject(pc, runtime.Str("json"), "json")
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().Desc(fmt.Sprintf("dry-run validation failed: %v", err))
|
||||
}
|
||||
return common.NewDryRunAPI().
|
||||
PUT("/open-apis/base/v3/bases/:base_token/tables/:table_id/fields/:field_id").
|
||||
Body(body).
|
||||
@@ -166,10 +173,10 @@ func executeFieldCreate(runtime *common.RuntimeContext) error {
|
||||
fields = append(fields, data)
|
||||
}
|
||||
if len(fields) == 1 {
|
||||
runtime.Out(map[string]interface{}{"field": fields[0], "created": true}, nil)
|
||||
runtime.Out(fieldCreateResult(map[string]interface{}{"field": fields[0], "created": true}, bodies[0]), nil)
|
||||
return nil
|
||||
}
|
||||
runtime.Out(map[string]interface{}{"fields": fields, "created": true, "total": len(fields)}, nil)
|
||||
runtime.Out(fieldCreateBatchResult(map[string]interface{}{"fields": fields, "created": true, "total": len(fields)}, bodies), nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -197,10 +204,101 @@ func executeFieldUpdate(runtime *common.RuntimeContext) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
runtime.Out(map[string]interface{}{"field": data, "updated": true}, nil)
|
||||
runtime.Out(fieldUpdateResult(map[string]interface{}{"field": data, "updated": true}, body), nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func fieldCreateResult(result map[string]interface{}, submitted map[string]interface{}) map[string]interface{} {
|
||||
readbackRecommended, reason := fieldWriteReadbackRecommendation(submitted, "create")
|
||||
return attachFieldReadbackRecommendation(result, readbackRecommended, reason)
|
||||
}
|
||||
|
||||
// fieldCreateBatchResult attaches the same top-level readback contract to a
|
||||
// multi-field create. It recommends +field-get when any submitted field is a
|
||||
// computed/linked/generated (or unknown) type, so agents know when to verify
|
||||
// server state without breaking the existing fields/total structure.
|
||||
func fieldCreateBatchResult(result map[string]interface{}, submitted []map[string]interface{}) map[string]interface{} {
|
||||
recommend := false
|
||||
reason := "simple fields created successfully; use +field-get only when extra properties or explicit verification are needed"
|
||||
for _, body := range submitted {
|
||||
if rec, r := fieldWriteReadbackRecommendation(body, "create"); rec {
|
||||
recommend = true
|
||||
reason = r
|
||||
break
|
||||
}
|
||||
}
|
||||
return attachFieldReadbackRecommendation(result, recommend, reason)
|
||||
}
|
||||
|
||||
func fieldUpdateResult(result map[string]interface{}, submitted map[string]interface{}) map[string]interface{} {
|
||||
returnedType := normalizeFieldType(fieldResultType(result["field"]))
|
||||
submittedType := normalizeFieldType(common.GetString(submitted, "type"))
|
||||
readbackRecommended, reason := fieldUpdateReadbackRecommendation(returnedType, submittedType)
|
||||
return attachFieldReadbackRecommendation(result, readbackRecommended, reason)
|
||||
}
|
||||
|
||||
func fieldUpdateReadbackRecommendation(returnedType, submittedType string) (bool, string) {
|
||||
if returnedType != "" && submittedType != "" && returnedType != submittedType {
|
||||
return true, fmt.Sprintf("field update submitted type %q but the server returned type %q; run +field-get and verify record values before declaring completion", submittedType, returnedType)
|
||||
}
|
||||
|
||||
fieldType := returnedType
|
||||
if fieldType == "" {
|
||||
fieldType = submittedType
|
||||
}
|
||||
if recommended, reason := fieldTypeReadbackRecommendation(fieldType, "update"); recommended {
|
||||
return true, reason + "; sample record values when generated, computed, or converted values are in scope"
|
||||
}
|
||||
return true, fmt.Sprintf("field update request succeeded for type %q, but +field-update cannot determine the previous type; run +field-get and sample record values if the type changed before declaring completion", fieldType)
|
||||
}
|
||||
|
||||
func attachFieldReadbackRecommendation(result map[string]interface{}, readbackRecommended bool, reason string) map[string]interface{} {
|
||||
result["field_get_recommended"] = readbackRecommended
|
||||
result["verification_hint"] = reason
|
||||
if readbackRecommended {
|
||||
result["next_step"] = "field_get"
|
||||
} else {
|
||||
result["next_step"] = "done"
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func fieldWriteReadbackRecommendation(submitted map[string]interface{}, operation string) (bool, string) {
|
||||
fieldType := normalizeFieldType(common.GetString(submitted, "type"))
|
||||
return fieldTypeReadbackRecommendation(fieldType, operation)
|
||||
}
|
||||
|
||||
func fieldTypeReadbackRecommendation(fieldType, operation string) (bool, string) {
|
||||
fieldType = normalizeFieldType(fieldType)
|
||||
switch fieldType {
|
||||
case "formula", "lookup", "auto_number", "link":
|
||||
return true, fmt.Sprintf("computed, linked, or generated field %s should be verified with +field-get before declaring completion", operation)
|
||||
case "text", "number", "select", "datetime", "checkbox", "user", "group_chat", "attachment", "location":
|
||||
return false, fmt.Sprintf("simple field %s returned successfully; use +field-get only when extra properties or explicit verification are needed", operation)
|
||||
default:
|
||||
return true, "unknown or uncommon field type; run +field-get to avoid assuming the submitted JSON fully describes server state"
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeFieldType(fieldType string) string {
|
||||
return strings.ToLower(strings.TrimSpace(fieldType))
|
||||
}
|
||||
|
||||
func fieldResultType(value interface{}) string {
|
||||
field, ok := value.(map[string]interface{})
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
if fieldType := strings.ToLower(strings.TrimSpace(common.GetString(field, "type"))); fieldType != "" {
|
||||
return fieldType
|
||||
}
|
||||
nested, ok := field["field"].(map[string]interface{})
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return strings.ToLower(strings.TrimSpace(common.GetString(nested, "type")))
|
||||
}
|
||||
|
||||
func executeFieldDelete(runtime *common.RuntimeContext) error {
|
||||
baseToken := runtime.Str("base-token")
|
||||
tableIDValue := baseTableID(runtime)
|
||||
|
||||
@@ -27,7 +27,7 @@ var BaseFieldSearchOptions = common.Shortcut{
|
||||
},
|
||||
Tips: []string{
|
||||
`Example: lark-cli base +field-search-options --base-token <base_token> --table-id <table_id> --field-id "Status" --keyword "Do"`,
|
||||
"Use only for fields with options, such as select or multi-select fields.",
|
||||
"Use only for select fields, whether multiple is false or true.",
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
if err := validateLimitPageSizeAlias(runtime); err != nil {
|
||||
|
||||
@@ -27,7 +27,9 @@ var BaseFieldUpdate = common.Shortcut{
|
||||
baseHighRiskYesTip,
|
||||
`Example text: lark-cli base +field-update --base-token <base_token> --table-id <table_id> --field-id "Status" --json '{"name":"Status","type":"text"}' --yes`,
|
||||
`Example select: lark-cli base +field-update --base-token <base_token> --table-id <table_id> --field-id "Status" --json '{"name":"Status","type":"select","multiple":false,"options":[{"name":"Todo"},{"name":"Done"}]}' --yes`,
|
||||
`Example auto_number update: lark-cli base +field-update --base-token <base_token> --table-id <table_id> --field-id "编号" --json '{"name":"编号","type":"auto_number","style":{"rules":[{"type":"text","text":"TASK-"},{"type":"created_time","date_format":"yyyyMM"},{"type":"text","text":"-"},{"type":"incremental_number","length":4}]}}' --yes`,
|
||||
"Update uses full field-definition PUT semantics. Read the current field first with +field-get, then send the target state.",
|
||||
`When --json.type is "auto_number", updating the numbering rules also reapplies them to existing numbers; just submit the target field definition and do not add extra low-level parameters.`,
|
||||
"Type conversion is allowlist-based: only use CLI for safe conversions; otherwise migrate through a new field, or ask the user to finish high-risk conversions in the web UI.",
|
||||
"Formula and lookup updates require reading the corresponding guide first.",
|
||||
"Agent hint: use the lark-base skill's field-update guide for JSON shape, type-conversion rules, and limits.",
|
||||
|
||||
@@ -238,14 +238,14 @@ func TestRecordSelectionHelpers(t *testing.T) {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
|
||||
fields, err = resolveRecordGetSelectFields(nil, map[string]interface{}{"select_fields": []interface{}{"Name"}})
|
||||
fields, err = resolveRecordGetSelectFields(nil, "--field-id", map[string]interface{}{"select_fields": []interface{}{"Name"}})
|
||||
if err != nil || !reflect.DeepEqual(fields, []string{"Name"}) {
|
||||
t.Fatalf("fields=%v err=%v", fields, err)
|
||||
}
|
||||
if _, err := resolveRecordGetSelectFields([]string{"Name"}, map[string]interface{}{"select_fields": []interface{}{"Age"}}); err == nil || !strings.Contains(err.Error(), "mutually exclusive") {
|
||||
if _, err := resolveRecordGetSelectFields([]string{"Name"}, "--field-id", map[string]interface{}{"select_fields": []interface{}{"Age"}}); err == nil || !strings.Contains(err.Error(), "mutually exclusive") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
if _, err := resolveRecordGetSelectFields(nil, map[string]interface{}{"select_fields": []interface{}{}}); err == nil || !strings.Contains(err.Error(), "must not be empty") {
|
||||
if _, err := resolveRecordGetSelectFields(nil, "--field-id", map[string]interface{}{"select_fields": []interface{}{}}); err == nil || !strings.Contains(err.Error(), "must not be empty") {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
|
||||
|
||||
@@ -19,12 +19,13 @@ var BaseRecordBatchCreate = common.Shortcut{
|
||||
Flags: []common.Flag{
|
||||
baseTokenFlag(true),
|
||||
tableRefFlag(true),
|
||||
{Name: "json", Desc: `batch create JSON object, e.g. {"fields":["Name","Status"],"rows":[["Task A","Todo"],["Task B",null]]}; rows follow fields order`, Required: true},
|
||||
{Name: "json", Desc: `batch create JSON object; create_records contains one field map per record, e.g. {"create_records":[{"Name":"Task A","Status":"Todo"},{"Name":"Task B","Score":20}]}`, Required: true},
|
||||
},
|
||||
Tips: append([]string{
|
||||
"Happy path fields: fields is the column order; rows is an array of row arrays; each row must match fields order and may use null for empty cells.",
|
||||
"Happy path field: create_records is an array of independent record field maps.",
|
||||
`Example: {"create_records":[{"Name":"Task A","Status":"Todo"},{"Name":"Task B","Score":20}]}.`,
|
||||
"Before writing, use +field-list to confirm real writable fields; do not write system fields, formula, lookup, or attachment fields as normal CellValue.",
|
||||
"Batch create supports max 200 rows per call.",
|
||||
"Batch create supports max 200 records per call.",
|
||||
"After batch-creating known helper rows, use the returned record IDs and your submitted rows; do not immediately +record-list the same table unless you need server-normalized formula/lookup values or failure diagnosis.",
|
||||
"Use the record-batch-create guide for command limits and edge cases.",
|
||||
}, recordCellValueHappyPathTips...),
|
||||
|
||||
@@ -21,7 +21,9 @@ var BaseRecordGet = common.Shortcut{
|
||||
baseTokenFlag(true),
|
||||
tableRefFlag(true),
|
||||
{Name: "record-id", Type: "string_array", Desc: "record ID (repeatable)"},
|
||||
{Name: "field-id", Type: "string_array", Desc: "field ID or name to project; repeat to keep only needed columns"},
|
||||
recordProjectionFieldFlag("field ID or name to project; repeat to keep only needed columns"),
|
||||
recordProjectionAliasFlag("fields"),
|
||||
recordProjectionAliasFlag("field-names"),
|
||||
{Name: "json", Desc: `JSON object with record_id_list, e.g. {"record_id_list":["rec_xxx"]}`},
|
||||
recordReadFormatFlag(),
|
||||
},
|
||||
|
||||
@@ -20,8 +20,9 @@ var BaseRecordList = common.Shortcut{
|
||||
Flags: []common.Flag{
|
||||
baseTokenFlag(true),
|
||||
tableRefFlag(true),
|
||||
recordListFieldRefFlag(),
|
||||
recordListFieldNamesAliasFlag(),
|
||||
recordProjectionFieldFlag("field ID or name to include; repeat to project only needed fields"),
|
||||
recordProjectionAliasFlag("fields"),
|
||||
recordProjectionAliasFlag("field-names"),
|
||||
recordListViewRefFlag(),
|
||||
recordFilterFlag(),
|
||||
recordSortFlag(),
|
||||
@@ -44,9 +45,6 @@ var BaseRecordList = common.Shortcut{
|
||||
"Use --field-id repeatedly to keep output small and aligned with the task.",
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
if err := validateRecordListFieldAlias(runtime); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := validateRecordReadFormat(runtime); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -61,6 +59,9 @@ var BaseRecordList = common.Shortcut{
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := recordProjectionFields(runtime); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateRecordQueryOptions(runtime)
|
||||
},
|
||||
DryRun: dryRunRecordList,
|
||||
@@ -72,22 +73,6 @@ var BaseRecordList = common.Shortcut{
|
||||
},
|
||||
}
|
||||
|
||||
func recordListFieldRefFlag() common.Flag {
|
||||
flag := fieldRefFlag(false)
|
||||
flag.Type = "string_array"
|
||||
flag.Desc = "field ID or name to include; repeat to project only needed fields"
|
||||
return flag
|
||||
}
|
||||
|
||||
func recordListFieldNamesAliasFlag() common.Flag {
|
||||
return common.Flag{
|
||||
Name: "field-names",
|
||||
Type: "string_slice",
|
||||
Desc: "hidden alias for --field-id; accepts comma-separated field names",
|
||||
Hidden: true,
|
||||
}
|
||||
}
|
||||
|
||||
func recordListViewRefFlag() common.Flag {
|
||||
flag := viewRefFlag(false)
|
||||
flag.Desc = "view ID or name; omit for reading all table records, or set to read a user-specified or temporary filtered/sorted view"
|
||||
@@ -102,10 +87,3 @@ func recordReadFormatFlag() common.Flag {
|
||||
Desc: "output format: markdown (default) | json",
|
||||
}
|
||||
}
|
||||
|
||||
func validateRecordListFieldAlias(runtime *common.RuntimeContext) error {
|
||||
if runtime.Changed("field-id") && runtime.Changed("field-names") {
|
||||
return baseFlagErrorf("--field-id and --field-names are mutually exclusive; use --field-id")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -5,18 +5,21 @@ package base
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
const maxRecordSelectionCount = 200
|
||||
const maxBatchGetSelectFieldCount = 100
|
||||
const maxRecordSearchSelectFieldCount = 50
|
||||
|
||||
var recordCellValueHappyPathTips = []string{
|
||||
`CellValue happy path: text/phone/url -> "text"; number/currency/percent/rating -> 12.5; select -> "Todo"; multi-select -> ["Tag A","Tag B"]; datetime -> "2026-03-24 10:00:00"; checkbox -> true/false.`,
|
||||
`CellValue happy path: text/phone/url -> "text"; number/currency/percent/rating -> 12.5; select (multiple=false) -> "Todo"; select (multiple=true) -> ["Tag A","Tag B"]; datetime -> "2026-03-24 10:00:00"; checkbox -> true/false.`,
|
||||
`ID-based CellValue: user/group/link fields use arrays like [{"id":"ou_xxx"}], [{"id":"oc_xxx"}], [{"id":"rec_xxx"}]; location uses {"lng":116.397428,"lat":39.90923}; null clears a cell when allowed.`,
|
||||
"Do not guess user/chat/linked-record IDs or location coordinates; resolve them first with the relevant contact/im/record lookup flow.",
|
||||
"Use lark-base-cell-value.md for complex CellValue shapes and special field types; do not invent values for fields not covered by the happy path.",
|
||||
@@ -46,7 +49,6 @@ func validateRecordSelection(runtime *common.RuntimeContext) error {
|
||||
|
||||
func resolveRecordSelection(runtime *common.RuntimeContext) (recordSelection, error) {
|
||||
recordIDs := runtime.StrArray("record-id")
|
||||
fieldIDs := runtime.StrArray("field-id")
|
||||
jsonRaw := strings.TrimSpace(runtime.Str("json"))
|
||||
if len(recordIDs) > 0 && jsonRaw != "" {
|
||||
return recordSelection{}, baseFlagErrorf("--record-id and --json are mutually exclusive")
|
||||
@@ -69,7 +71,11 @@ func resolveRecordSelection(runtime *common.RuntimeContext) (recordSelection, er
|
||||
if err != nil {
|
||||
return recordSelection{}, err
|
||||
}
|
||||
selectFields, err := resolveRecordGetSelectFields(fieldIDs, body)
|
||||
projectionFields, err := recordProjectionFields(runtime)
|
||||
if err != nil {
|
||||
return recordSelection{}, err
|
||||
}
|
||||
selectFields, err := resolveRecordGetSelectFields(projectionFields, recordProjectionParam(runtime), body)
|
||||
if err != nil {
|
||||
return recordSelection{}, err
|
||||
}
|
||||
@@ -83,7 +89,11 @@ func resolveRecordSelection(runtime *common.RuntimeContext) (recordSelection, er
|
||||
if err != nil {
|
||||
return recordSelection{}, err
|
||||
}
|
||||
selectFields, err := resolveRecordGetSelectFields(fieldIDs, nil)
|
||||
projectionFields, err := recordProjectionFields(runtime)
|
||||
if err != nil {
|
||||
return recordSelection{}, err
|
||||
}
|
||||
selectFields, err := resolveRecordGetSelectFields(projectionFields, recordProjectionParam(runtime), nil)
|
||||
if err != nil {
|
||||
return recordSelection{}, err
|
||||
}
|
||||
@@ -104,20 +114,20 @@ func normalizeRecordIDs(values interface{}) ([]string, error) {
|
||||
})
|
||||
}
|
||||
|
||||
func resolveRecordGetSelectFields(flagFields []string, body map[string]interface{}) ([]string, error) {
|
||||
func resolveRecordGetSelectFields(flagFields []string, projectionParam string, body map[string]interface{}) ([]string, error) {
|
||||
fromFlags, err := normalizeRecordGetSelectFields(flagFields)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, withValidationParam(err, projectionParam)
|
||||
}
|
||||
if body == nil {
|
||||
return fromFlags, nil
|
||||
}
|
||||
rawJSONFields, ok := body["select_fields"]
|
||||
if !ok {
|
||||
if !ok || rawJSONFields == nil {
|
||||
return fromFlags, nil
|
||||
}
|
||||
if len(fromFlags) > 0 {
|
||||
return nil, baseFlagErrorf(`--field-id and --json field "select_fields" are mutually exclusive`)
|
||||
return nil, baseFlagErrorf(`%s and --json field "select_fields" are mutually exclusive`, projectionParam)
|
||||
}
|
||||
items, ok := rawJSONFields.([]interface{})
|
||||
if !ok {
|
||||
@@ -128,18 +138,26 @@ func resolveRecordGetSelectFields(flagFields []string, body map[string]interface
|
||||
}
|
||||
normalized, err := normalizeRecordGetSelectFields(items)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, withValidationParam(err, "--json")
|
||||
}
|
||||
return normalized, nil
|
||||
}
|
||||
|
||||
func normalizeRecordGetSelectFields(values interface{}) ([]string, error) {
|
||||
return normalizeRecordSelectFields(values, maxBatchGetSelectFieldCount)
|
||||
}
|
||||
|
||||
func normalizeRecordSearchSelectFields(values interface{}) ([]string, error) {
|
||||
return normalizeRecordSelectFields(values, maxRecordSearchSelectFieldCount)
|
||||
}
|
||||
|
||||
func normalizeRecordSelectFields(values interface{}, max int) ([]string, error) {
|
||||
return normalizeStringList(values, stringListNormalizeOptions{
|
||||
typeError: "field selection must be a string array",
|
||||
itemName: "field selection item",
|
||||
duplicateName: "field id",
|
||||
limitName: "field selection",
|
||||
max: maxBatchGetSelectFieldCount,
|
||||
max: max,
|
||||
allowNil: true,
|
||||
allowEmpty: true,
|
||||
})
|
||||
@@ -211,7 +229,11 @@ func dryRunRecordList(_ context.Context, runtime *common.RuntimeContext) *common
|
||||
params := url.Values{}
|
||||
params.Set("offset", strconv.Itoa(offset))
|
||||
params.Set("limit", strconv.Itoa(limit))
|
||||
for _, field := range recordListFields(runtime) {
|
||||
fields, err := recordProjectionFields(runtime)
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI()
|
||||
}
|
||||
for _, field := range fields {
|
||||
params.Add("field_id", field)
|
||||
}
|
||||
if viewID := runtime.Str("view-id"); viewID != "" {
|
||||
@@ -375,11 +397,121 @@ func validateRecordJSON(runtime *common.RuntimeContext) error {
|
||||
return err
|
||||
}
|
||||
|
||||
func recordListFields(runtime *common.RuntimeContext) []string {
|
||||
if runtime.Changed("field-names") {
|
||||
return runtime.StrSlice("field-names")
|
||||
func recordProjectionFieldFlag(desc string) common.Flag {
|
||||
flag := fieldRefFlag(false)
|
||||
flag.Type = "string_array"
|
||||
flag.Desc = desc
|
||||
return flag
|
||||
}
|
||||
|
||||
func recordProjectionAliasFlag(name string) common.Flag {
|
||||
flagType := "string_array"
|
||||
if name == "field-names" {
|
||||
// Preserve the original compatibility contract: --field-names uses
|
||||
// pflag's CSV parser, including quoted commas, and treats @ literally.
|
||||
flagType = "string_slice"
|
||||
}
|
||||
return runtime.StrArray("field-id")
|
||||
return common.Flag{
|
||||
Name: name,
|
||||
Type: flagType,
|
||||
Desc: "hidden alias for --field-id projection",
|
||||
Hidden: true,
|
||||
}
|
||||
}
|
||||
|
||||
func recordProjectionParam(runtime *common.RuntimeContext) string {
|
||||
switch {
|
||||
case runtime.Changed("fields"):
|
||||
return "--fields"
|
||||
case runtime.Changed("field-names"):
|
||||
return "--field-names"
|
||||
default:
|
||||
return "--field-id"
|
||||
}
|
||||
}
|
||||
|
||||
func withValidationParam(err error, param string) error {
|
||||
if err == nil || param == "" {
|
||||
return err
|
||||
}
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) {
|
||||
return err
|
||||
}
|
||||
reason := validationErr.Error()
|
||||
// The caller knows which input produced this validation error. Replace any
|
||||
// params inferred from the rendered message: field values such as Cost--USD
|
||||
// must not be mistaken for a --USD flag.
|
||||
validationErr.Param = param
|
||||
validationErr.Params = []errs.InvalidParam{{Name: param, Reason: reason}}
|
||||
return err
|
||||
}
|
||||
|
||||
func recordProjectionFields(runtime *common.RuntimeContext) ([]string, error) {
|
||||
return recordProjectionFieldsWithLimit(runtime, maxBatchGetSelectFieldCount)
|
||||
}
|
||||
|
||||
func recordSearchProjectionFields(runtime *common.RuntimeContext) ([]string, error) {
|
||||
return recordProjectionFieldsWithLimit(runtime, maxRecordSearchSelectFieldCount)
|
||||
}
|
||||
|
||||
func recordProjectionFieldsWithLimit(runtime *common.RuntimeContext, max int) ([]string, error) {
|
||||
fieldIDs := runtime.StrArray("field-id")
|
||||
fieldIDsSet := runtime.Changed("field-id")
|
||||
fieldsSet := runtime.Changed("fields")
|
||||
fieldNamesSet := runtime.Changed("field-names")
|
||||
projectionParams := make([]string, 0, 3)
|
||||
if fieldIDsSet {
|
||||
projectionParams = append(projectionParams, "--field-id")
|
||||
}
|
||||
if fieldsSet {
|
||||
projectionParams = append(projectionParams, "--fields")
|
||||
}
|
||||
if fieldNamesSet {
|
||||
projectionParams = append(projectionParams, "--field-names")
|
||||
}
|
||||
if len(projectionParams) > 1 {
|
||||
invalidParams := make([]errs.InvalidParam, 0, len(projectionParams))
|
||||
for _, param := range projectionParams {
|
||||
invalidParams = append(invalidParams, errs.InvalidParam{Name: param, Reason: "mutually exclusive"})
|
||||
}
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "%s are mutually exclusive", strings.Join(projectionParams, " and ")).
|
||||
WithParam(projectionParams[0]).
|
||||
WithParams(invalidParams...).
|
||||
WithHint("Use only --field-id for projection.")
|
||||
}
|
||||
if fieldsSet {
|
||||
return recordProjectionAliasFields(runtime, "fields", max)
|
||||
}
|
||||
if fieldNamesSet {
|
||||
return recordProjectionAliasFields(runtime, "field-names", max)
|
||||
}
|
||||
fields, err := normalizeRecordSelectFields(fieldIDs, max)
|
||||
return fields, withValidationParam(err, "--field-id")
|
||||
}
|
||||
|
||||
func recordProjectionAliasFields(runtime *common.RuntimeContext, flagName string, max int) ([]string, error) {
|
||||
var fields []string
|
||||
if flagName == "field-names" {
|
||||
fields = runtime.StrSlice(flagName)
|
||||
} else {
|
||||
pc := newParseCtx(runtime)
|
||||
values := runtime.StrArray(flagName)
|
||||
fields = make([]string, 0, len(values))
|
||||
for _, raw := range values {
|
||||
parsed, err := parseStringListFlexible(pc, raw, flagName)
|
||||
if err != nil {
|
||||
return nil, withValidationParam(err, "--"+flagName)
|
||||
}
|
||||
fields = append(fields, parsed...)
|
||||
}
|
||||
}
|
||||
if len(fields) == 0 {
|
||||
err := baseFlagErrorf("--%s must include at least one field", flagName)
|
||||
return nil, withValidationParam(err, "--"+flagName)
|
||||
}
|
||||
normalized, err := normalizeRecordSelectFields(fields, max)
|
||||
return normalized, withValidationParam(err, "--"+flagName)
|
||||
}
|
||||
|
||||
func executeRecordList(runtime *common.RuntimeContext) error {
|
||||
@@ -392,7 +524,10 @@ func executeRecordList(runtime *common.RuntimeContext) error {
|
||||
}
|
||||
limit := getPaginationLimit(runtime)
|
||||
params := map[string]interface{}{"offset": offset, "limit": limit}
|
||||
fields := recordListFields(runtime)
|
||||
fields, err := recordProjectionFields(runtime)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(fields) > 0 {
|
||||
params["field_id"] = fields
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"net/url"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
@@ -174,7 +175,10 @@ func recordSearchFlagBody(runtime *common.RuntimeContext) (map[string]interface{
|
||||
if len(searchFields) > 0 {
|
||||
body["search_fields"] = searchFields
|
||||
}
|
||||
selectFields := recordListFields(runtime)
|
||||
selectFields, err := recordSearchProjectionFields(runtime)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(selectFields) > 0 {
|
||||
body["select_fields"] = selectFields
|
||||
}
|
||||
@@ -203,6 +207,19 @@ func recordSearchJSONBody(runtime *common.RuntimeContext) (map[string]interface{
|
||||
}
|
||||
|
||||
func normalizeRecordSearchJSONBody(body map[string]interface{}) error {
|
||||
if rawSelectFields, ok := body["select_fields"]; ok {
|
||||
if rawSelectFields == nil {
|
||||
delete(body, "select_fields")
|
||||
} else {
|
||||
selectFields, err := normalizeRecordSearchSelectFields(rawSelectFields)
|
||||
if err != nil {
|
||||
return withValidationParam(err, "--json")
|
||||
}
|
||||
if len(selectFields) > 0 {
|
||||
body["select_fields"] = selectFields
|
||||
}
|
||||
}
|
||||
}
|
||||
if rawSort, ok := body["sort"]; ok {
|
||||
if sortConfig, err := normalizeRecordSortValue(rawSort, "--json.sort"); err == nil {
|
||||
body["sort"] = sortConfig
|
||||
@@ -219,8 +236,20 @@ func validateRecordSearchFlags(runtime *common.RuntimeContext) error {
|
||||
}
|
||||
jsonRaw := strings.TrimSpace(runtime.Str("json"))
|
||||
if jsonRaw != "" {
|
||||
if recordSearchHasJSONExclusiveFlagInputs(runtime) {
|
||||
return baseFlagErrorf("--json is mutually exclusive with keyword/search/projection/pagination flags; put those fields inside --json, or omit --json")
|
||||
if exclusiveParams := recordSearchJSONExclusiveFlagParams(runtime); len(exclusiveParams) > 0 {
|
||||
allParams := append([]string{"--json"}, exclusiveParams...)
|
||||
invalidParams := make([]errs.InvalidParam, 0, len(allParams))
|
||||
for _, param := range allParams {
|
||||
invalidParams = append(invalidParams, errs.InvalidParam{Name: param, Reason: "mutually exclusive"})
|
||||
}
|
||||
return errs.NewValidationError(
|
||||
errs.SubtypeInvalidArgument,
|
||||
"--json is mutually exclusive with %s",
|
||||
strings.Join(exclusiveParams, " and "),
|
||||
).
|
||||
WithParam("--json").
|
||||
WithParams(invalidParams...).
|
||||
WithHint("Put keyword, search, projection, view, and pagination fields inside --json, or omit --json.")
|
||||
}
|
||||
_, err := recordSearchJSONBody(runtime)
|
||||
return err
|
||||
@@ -242,17 +271,31 @@ func validateRecordSearchFlags(runtime *common.RuntimeContext) error {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := recordSearchProjectionFields(runtime); err != nil {
|
||||
return err
|
||||
}
|
||||
return validateRecordQueryOptions(runtime)
|
||||
}
|
||||
|
||||
func recordSearchHasJSONExclusiveFlagInputs(runtime *common.RuntimeContext) bool {
|
||||
return strings.TrimSpace(runtime.Str("keyword")) != "" ||
|
||||
len(runtime.StrArray("search-field")) > 0 ||
|
||||
len(recordListFields(runtime)) > 0 ||
|
||||
runtime.Str("view-id") != "" ||
|
||||
runtime.Changed("offset") ||
|
||||
runtime.Changed("limit") ||
|
||||
runtime.Changed("page-size")
|
||||
func recordSearchJSONExclusiveFlagParams(runtime *common.RuntimeContext) []string {
|
||||
names := []string{
|
||||
"keyword",
|
||||
"search-field",
|
||||
"field-id",
|
||||
"fields",
|
||||
"field-names",
|
||||
"view-id",
|
||||
"offset",
|
||||
"limit",
|
||||
"page-size",
|
||||
}
|
||||
params := make([]string, 0, len(names))
|
||||
for _, name := range names {
|
||||
if runtime.Changed(name) {
|
||||
params = append(params, "--"+name)
|
||||
}
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func formatRecordQueryPriorityTip() string {
|
||||
|
||||
@@ -23,7 +23,9 @@ var BaseRecordSearch = common.Shortcut{
|
||||
{Name: "json", Desc: `record search JSON object for the full request body, e.g. {"keyword":"Alice","search_fields":["Name"],"select_fields":["Name","Status"],"filter":{"logic":"and","conditions":[]},"sort":[{"field":"Updated","desc":true}],"limit":50}; escape hatch for advanced cases`},
|
||||
{Name: "keyword", Desc: "keyword for record search; required unless --json is used"},
|
||||
{Name: "search-field", Type: "string_array", Desc: "field ID or name to search; repeat for multiple fields; required unless --json is used"},
|
||||
recordListFieldRefFlag(),
|
||||
recordProjectionFieldFlag("field ID or name to include; repeat to project only needed fields"),
|
||||
recordProjectionAliasFlag("fields"),
|
||||
recordProjectionAliasFlag("field-names"),
|
||||
recordListViewRefFlag(),
|
||||
recordFilterFlag(),
|
||||
recordSortFlag(),
|
||||
|
||||
@@ -26,6 +26,7 @@ var BaseRecordUpsert = common.Shortcut{
|
||||
"Happy path JSON is a top-level field map: each key is a real field name or field ID, each value is that field's CellValue.",
|
||||
"Without --record-id this creates a record; with --record-id this updates that record. It does not auto-upsert by business key.",
|
||||
"Before writing, use +field-list to confirm real writable fields; do not write system fields, formula, lookup, or attachment fields as normal CellValue.",
|
||||
"Sub-record/child-record path: when a one-way/two-way link field represents hierarchy, create a normal record and set that link field to a parent record reference array, e.g. {\"Parent Link\":[{\"id\":\"rec_xxx\"}]}; do not look for parent_record_id or a separate child-record API.",
|
||||
"Use the record-upsert guide for command limits and edge cases.",
|
||||
}, recordCellValueHappyPathTips...),
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
|
||||
@@ -67,6 +67,25 @@ func parseAttendees(attendeesStr string, currentUserId string) ([]map[string]str
|
||||
return attendees, nil
|
||||
}
|
||||
|
||||
// selfAttendeeId resolves the open_id of the identity running the command so it
|
||||
// can be auto-added to the attendee list, mirroring how a human user is joined
|
||||
// to their own events. For a user it comes from config; for a bot it is fetched
|
||||
// from /bot/v3/info. If the bot lookup fails, we warn and return "" so the event
|
||||
// is still created with the explicitly requested attendees.
|
||||
func selfAttendeeId(runtime *common.RuntimeContext) string {
|
||||
if !runtime.IsBot() {
|
||||
return runtime.UserOpenId()
|
||||
}
|
||||
info, err := runtime.BotInfo()
|
||||
if err != nil {
|
||||
fmt.Fprintf(runtime.IO().ErrOut,
|
||||
"[calendar +create] warning: could not resolve bot identity to add it as an attendee (%v); proceeding without the bot\n",
|
||||
err)
|
||||
return ""
|
||||
}
|
||||
return info.OpenID
|
||||
}
|
||||
|
||||
func attendeesIncludeRoom(attendees []map[string]string) bool {
|
||||
for _, attendee := range attendees {
|
||||
if attendee["type"] == "resource" || attendee["room_id"] != "" {
|
||||
@@ -176,7 +195,9 @@ var CalendarCreate = common.Shortcut{
|
||||
eventData := buildEventData(runtime, startTs, endTs)
|
||||
attendeesStr := runtime.Str("attendee-ids")
|
||||
if attendeesStr != "" {
|
||||
// Note: dry-run doesn't network resolve the current user's open_id.
|
||||
// Note: dry-run doesn't network resolve the running identity's own
|
||||
// open_id (user from config, bot from /bot/v3/info), so the auto-joined
|
||||
// self attendee is not shown here.
|
||||
attendees, err := parseAttendees(attendeesStr, "")
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
@@ -228,11 +249,8 @@ var CalendarCreate = common.Shortcut{
|
||||
|
||||
// Add attendees if specified
|
||||
if attendeesStr := runtime.Str("attendee-ids"); attendeesStr != "" {
|
||||
currentUserId := ""
|
||||
if !runtime.IsBot() {
|
||||
currentUserId = runtime.UserOpenId()
|
||||
}
|
||||
attendees, err := parseAttendees(attendeesStr, currentUserId)
|
||||
selfId := selfAttendeeId(runtime)
|
||||
attendees, err := parseAttendees(attendeesStr, selfId)
|
||||
if err != nil {
|
||||
return withParam(err, "--attendee-ids")
|
||||
}
|
||||
|
||||
@@ -251,6 +251,136 @@ func TestCreate_WithAttendees_Success(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_WithAttendees_AsBot_AddsBotSelf(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/bot/v3/info",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"bot": map[string]interface{}{
|
||||
"open_id": "ou_botself",
|
||||
"app_name": "Test Bot",
|
||||
},
|
||||
},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/calendars/cal_test123/events",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"event": map[string]interface{}{
|
||||
"event_id": "evt_bot",
|
||||
"summary": "Bot Sync",
|
||||
"start_time": map[string]interface{}{
|
||||
"timestamp": "1742515200",
|
||||
},
|
||||
"end_time": map[string]interface{}{
|
||||
"timestamp": "1742518800",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
attendeesStub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/events/evt_bot/attendees",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{},
|
||||
},
|
||||
}
|
||||
reg.Register(attendeesStub)
|
||||
|
||||
err := mountAndRun(t, CalendarCreate, []string{
|
||||
"+create",
|
||||
"--summary", "Bot Sync",
|
||||
"--start", "2025-03-21T00:00:00+08:00",
|
||||
"--end", "2025-03-21T01:00:00+08:00",
|
||||
"--calendar-id", "cal_test123",
|
||||
"--attendee-ids", "ou_user1",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if attendeesStub.CapturedBody == nil {
|
||||
t.Fatal("attendees API was not called")
|
||||
}
|
||||
if !bytes.Contains(attendeesStub.CapturedBody, []byte("ou_botself")) {
|
||||
t.Fatalf("expected bot open_id ou_botself in attendees request, got: %s", attendeesStub.CapturedBody)
|
||||
}
|
||||
if !bytes.Contains(attendeesStub.CapturedBody, []byte("ou_user1")) {
|
||||
t.Fatalf("expected requested attendee ou_user1 in attendees request, got: %s", attendeesStub.CapturedBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_WithAttendees_AsBot_BotInfoFails_ProceedsWithoutBot(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/bot/v3/info",
|
||||
Body: map[string]interface{}{
|
||||
"code": 99991663, "msg": "app ticket invalid",
|
||||
},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/calendar/v4/calendars/cal_test123/events",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"event": map[string]interface{}{
|
||||
"event_id": "evt_nobot",
|
||||
"summary": "Bot Sync",
|
||||
"start_time": map[string]interface{}{
|
||||
"timestamp": "1742515200",
|
||||
},
|
||||
"end_time": map[string]interface{}{
|
||||
"timestamp": "1742518800",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
attendeesStub := &httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/events/evt_nobot/attendees",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "ok",
|
||||
"data": map[string]interface{}{},
|
||||
},
|
||||
}
|
||||
reg.Register(attendeesStub)
|
||||
|
||||
err := mountAndRun(t, CalendarCreate, []string{
|
||||
"+create",
|
||||
"--summary", "Bot Sync",
|
||||
"--start", "2025-03-21T00:00:00+08:00",
|
||||
"--end", "2025-03-21T01:00:00+08:00",
|
||||
"--calendar-id", "cal_test123",
|
||||
"--attendee-ids", "ou_user1",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
|
||||
if attendeesStub.CapturedBody == nil {
|
||||
t.Fatal("attendees API was not called")
|
||||
}
|
||||
if !bytes.Contains(attendeesStub.CapturedBody, []byte("ou_user1")) {
|
||||
t.Fatalf("expected requested attendee ou_user1 in attendees request, got: %s", attendeesStub.CapturedBody)
|
||||
}
|
||||
if bytes.Contains(attendeesStub.CapturedBody, []byte("ou_botself")) {
|
||||
t.Fatalf("bot open_id should be absent when /bot/v3/info fails, got: %s", attendeesStub.CapturedBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreate_WithAttendees_APIError_RollsBack(t *testing.T) {
|
||||
f, _, _, reg := cmdutil.TestFactory(t, defaultConfig())
|
||||
|
||||
|
||||
146
shortcuts/common/localfile.go
Normal file
146
shortcuts/common/localfile.go
Normal file
@@ -0,0 +1,146 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package common
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io"
|
||||
"io/fs"
|
||||
"math"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/validate"
|
||||
)
|
||||
|
||||
// ValidateLocalFileFlag validates that a local input path exists, is a regular
|
||||
// file, and does not exceed maxBytes. Absolute and relative paths use
|
||||
// the process filesystem namespace.
|
||||
func (ctx *RuntimeContext) ValidateLocalFileFlag(flagName string, maxBytes int64) error {
|
||||
path, param, err := ctx.localFileFlag(flagName, maxBytes)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
info, err := cmdutil.StatLocalFile(path)
|
||||
if err != nil {
|
||||
return localFileReadError(param, path, "inspect", err)
|
||||
}
|
||||
if err := localFileRegularError(param, path, info.Mode()); err != nil {
|
||||
return err
|
||||
}
|
||||
if info.Size() > maxBytes {
|
||||
return localFileSizeError(param, path, info.Size(), maxBytes)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReadLocalFileFlag is the shared replacement for direct os.ReadFile calls in
|
||||
// shortcuts. It accepts absolute and relative paths, enforces a hard size
|
||||
// limit, and returns command-facing typed errors.
|
||||
func (ctx *RuntimeContext) ReadLocalFileFlag(flagName string, maxBytes int64) (data []byte, retErr error) {
|
||||
path, param, err := ctx.localFileFlag(flagName, maxBytes)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
f, err := cmdutil.OpenLocalFile(path)
|
||||
if err != nil {
|
||||
return nil, localFileReadError(param, path, "open", err)
|
||||
}
|
||||
defer func() {
|
||||
if err := f.Close(); err != nil && retErr == nil {
|
||||
data = nil
|
||||
retErr = errs.NewInternalError(errs.SubtypeFileIO, "cannot close %s %q: %v", param, path, err).WithCause(err)
|
||||
}
|
||||
}()
|
||||
|
||||
openedInfo, err := f.Stat()
|
||||
if err != nil {
|
||||
return nil, localFileReadError(param, path, "inspect opened", err)
|
||||
}
|
||||
if err := localFileRegularError(param, path, openedInfo.Mode()); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if openedInfo.Size() > maxBytes {
|
||||
return nil, localFileSizeError(param, path, openedInfo.Size(), maxBytes)
|
||||
}
|
||||
|
||||
readLimit := maxBytes + 1
|
||||
if maxBytes == math.MaxInt64 {
|
||||
readLimit = maxBytes
|
||||
}
|
||||
data, err = io.ReadAll(io.LimitReader(f, readLimit))
|
||||
if err != nil {
|
||||
return nil, localFileReadError(param, path, "read", err)
|
||||
}
|
||||
if int64(len(data)) > maxBytes {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"%s %q grew beyond the %d-byte limit while being read", param, path, maxBytes).
|
||||
WithParam(param)
|
||||
}
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func (ctx *RuntimeContext) localFileFlag(flagName string, maxBytes int64) (path, param string, err error) {
|
||||
name, param, err := localFileFlagNames(flagName)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
if ctx == nil || ctx.Cmd == nil {
|
||||
return "", param, errs.NewInternalError(errs.SubtypeUnknown, "cannot read %s: runtime command is unavailable", param)
|
||||
}
|
||||
|
||||
path = strings.TrimSpace(ctx.Str(name))
|
||||
if path == "" {
|
||||
return "", param, errs.NewValidationError(errs.SubtypeInvalidArgument, "%s is required", param).WithParam(param)
|
||||
}
|
||||
if _, err := validate.LocalInputPath(path); err != nil {
|
||||
return "", param, errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid %s path: %v", param, err).
|
||||
WithParam(param).
|
||||
WithCause(err)
|
||||
}
|
||||
if maxBytes < 0 {
|
||||
return "", param, errs.NewInternalError(errs.SubtypeUnknown, "invalid read limit configured for %s", param)
|
||||
}
|
||||
return path, param, nil
|
||||
}
|
||||
|
||||
func localFileRegularError(param, path string, mode fs.FileMode) error {
|
||||
if mode.IsRegular() {
|
||||
return nil
|
||||
}
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"%s %q is not a regular file", param, path).
|
||||
WithParam(param)
|
||||
}
|
||||
|
||||
func localFileReadError(param, path, op string, cause error) error {
|
||||
if errors.Is(cause, fileio.ErrPathValidation) {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid %s %q: %v", param, path, cause).
|
||||
WithParam(param).
|
||||
WithCause(cause)
|
||||
}
|
||||
if errors.Is(cause, fs.ErrNotExist) {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "%s %q does not exist", param, path).
|
||||
WithParam(param).
|
||||
WithCause(cause)
|
||||
}
|
||||
return errs.NewInternalError(errs.SubtypeFileIO, "cannot %s %s %q: %v", op, param, path, cause).WithCause(cause)
|
||||
}
|
||||
|
||||
func localFileSizeError(param, path string, size, limit int64) error {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"%s %q is %d bytes; limit is %d bytes", param, path, size, limit).
|
||||
WithParam(param)
|
||||
}
|
||||
|
||||
func localFileFlagNames(flagName string) (name, param string, err error) {
|
||||
name = strings.TrimLeft(strings.TrimSpace(flagName), "-")
|
||||
if name == "" {
|
||||
return "", "", errs.NewInternalError(errs.SubtypeUnknown, "local file flag name must not be empty")
|
||||
}
|
||||
return name, "--" + name, nil
|
||||
}
|
||||
95
shortcuts/common/localfile_test.go
Normal file
95
shortcuts/common/localfile_test.go
Normal file
@@ -0,0 +1,95 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package common
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func TestReadLocalFileFlag_AcceptsAbsolutePath(t *testing.T) {
|
||||
path := filepath.Join(t.TempDir(), "input.txt")
|
||||
if err := os.WriteFile(path, []byte("content"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rctx := localFileTestRuntime(t, path)
|
||||
|
||||
if err := rctx.ValidateLocalFileFlag("file", 7); err != nil {
|
||||
t.Fatalf("ValidateLocalFileFlag() error = %v", err)
|
||||
}
|
||||
got, err := rctx.ReadLocalFileFlag("file", 7)
|
||||
if err != nil || string(got) != "content" {
|
||||
t.Fatalf("ReadLocalFileFlag() = %q, %v; want content", got, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateLocalFileFlag_ReturnsTypedInputErrors(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
path func(t *testing.T) string
|
||||
max int64
|
||||
}{
|
||||
{name: "invalid characters", path: func(*testing.T) string { return "input\n.txt" }, max: 10},
|
||||
{name: "missing file", path: func(t *testing.T) string { return filepath.Join(t.TempDir(), "missing") }, max: 10},
|
||||
{name: "directory", path: func(t *testing.T) string { return t.TempDir() }, max: 10},
|
||||
{name: "too large", path: func(t *testing.T) string {
|
||||
path := filepath.Join(t.TempDir(), "large")
|
||||
if err := os.WriteFile(path, []byte("123456"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}, max: 5},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := localFileTestRuntime(t, tc.path(t)).ValidateLocalFileFlag("file", tc.max)
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || validationErr.Subtype != errs.SubtypeInvalidArgument || validationErr.Param != "--file" {
|
||||
t.Fatalf("error = %T %v, want invalid_argument for --file", err, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadLocalFileFlag_ReturnsTypedInputErrors(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
path func(t *testing.T) string
|
||||
max int64
|
||||
}{
|
||||
{name: "invalid characters", path: func(*testing.T) string { return "input\n.txt" }, max: 10},
|
||||
{name: "missing file", path: func(t *testing.T) string { return filepath.Join(t.TempDir(), "missing") }, max: 10},
|
||||
{name: "directory", path: func(t *testing.T) string { return t.TempDir() }, max: 10},
|
||||
{name: "too large", path: func(t *testing.T) string {
|
||||
path := filepath.Join(t.TempDir(), "large")
|
||||
if err := os.WriteFile(path, []byte("123456"), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return path
|
||||
}, max: 5},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := localFileTestRuntime(t, tc.path(t)).ReadLocalFileFlag("file", tc.max)
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || validationErr.Subtype != errs.SubtypeInvalidArgument || validationErr.Param != "--file" {
|
||||
t.Fatalf("error = %T %v, want invalid_argument for --file", err, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func localFileTestRuntime(t *testing.T, path string) *RuntimeContext {
|
||||
t.Helper()
|
||||
cmd := &cobra.Command{Use: "test"}
|
||||
cmd.Flags().String("file", "", "")
|
||||
if err := cmd.Flags().Set("file", path); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return &RuntimeContext{ctx: context.Background(), Cmd: cmd}
|
||||
}
|
||||
418
shortcuts/doc/docs_script.go
Normal file
418
shortcuts/doc/docs_script.go
Normal file
@@ -0,0 +1,418 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package doc
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/fs"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/internal/charcheck"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
"github.com/larksuite/cli/shortcuts/doc/internal/docxparse"
|
||||
)
|
||||
|
||||
const (
|
||||
docsScriptParse = "parse"
|
||||
docsScriptMarkdownToXML = "markdown-to-xml"
|
||||
docsScriptCreateTempXML = "create-temp-xml"
|
||||
docsScriptTempDirSuffix = "_*_folder"
|
||||
)
|
||||
|
||||
var DocsScript = common.Shortcut{
|
||||
Service: "docs",
|
||||
Command: "+script",
|
||||
Description: "Create a unique temporary XML file, parse and profile local or online documents, or convert Markdown to LarkOpenCLI XML",
|
||||
Risk: "read",
|
||||
AuthTypes: []string{"user", "bot"},
|
||||
Scopes: []string{},
|
||||
ConditionalScopes: []string{
|
||||
"docx:document:readonly",
|
||||
},
|
||||
Flags: []common.Flag{
|
||||
{
|
||||
Name: "command",
|
||||
Desc: "local document operation",
|
||||
Required: true,
|
||||
Enum: []string{docsScriptParse, docsScriptMarkdownToXML, docsScriptCreateTempXML},
|
||||
},
|
||||
{
|
||||
Name: "content",
|
||||
Desc: "local content for parse or markdown-to-xml; use @relative-file or - for stdin; mutually exclusive with --doc",
|
||||
Input: []string{common.File, common.Stdin},
|
||||
},
|
||||
{
|
||||
Name: "doc",
|
||||
Desc: "online document URL or token for --command parse; mutually exclusive with --content",
|
||||
},
|
||||
{
|
||||
Name: "output",
|
||||
Desc: "local XML output path for markdown-to-xml; omit to return XML in data.xml",
|
||||
},
|
||||
{
|
||||
Name: "file-name",
|
||||
Desc: "portable base name without .xml; create-temp-xml writes <name>_<random>_folder/<name>.xml",
|
||||
},
|
||||
{
|
||||
Name: "overwrite",
|
||||
Type: "bool",
|
||||
Desc: "overwrite an existing --output file",
|
||||
},
|
||||
},
|
||||
Tips: []string{
|
||||
"create-temp-xml atomically creates <file-name>_<random>_folder/<file-name>.xml in the current directory",
|
||||
"parse accepts local --content or an online --doc URL/token and returns only the text and block profile",
|
||||
"markdown-to-xml converts Markdown to LarkOpenCLI XML",
|
||||
"use --output to save converted XML directly and keep stdout compact",
|
||||
},
|
||||
PostMount: installDocsScriptHelp,
|
||||
Validate: validateDocsScript,
|
||||
DryRun: dryRunDocsScript,
|
||||
Execute: executeDocsScript,
|
||||
}
|
||||
|
||||
type docsScriptParseResult struct {
|
||||
Profile docsScriptPublicProfile `json:"profile"`
|
||||
}
|
||||
|
||||
// docsScriptPublicProfile is the stable shortcut response. The parser keeps
|
||||
// the more detailed breakdown internally so it can be exposed later without
|
||||
// changing the counting implementation.
|
||||
type docsScriptPublicProfile struct {
|
||||
WordCount int `json:"word_count"`
|
||||
CharCount int `json:"char_count"`
|
||||
BlockCount int `json:"block_count"`
|
||||
Blocks []docxparse.BlockShare `json:"blocks"`
|
||||
}
|
||||
|
||||
type docsScriptMarkdownResult struct {
|
||||
XML string `json:"xml"`
|
||||
}
|
||||
|
||||
type docsScriptMarkdownFileResult struct {
|
||||
SavedPath string `json:"saved_path"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
}
|
||||
|
||||
type docsScriptTempXMLResult struct {
|
||||
Path string `json:"path"`
|
||||
}
|
||||
|
||||
func installDocsScriptHelp(cmd *cobra.Command) {
|
||||
installDocsShortcutHelp("+script")(cmd)
|
||||
cmd.Example = ` lark-cli docs +script --command create-temp-xml --file-name "draft"
|
||||
lark-cli docs +script --command parse --content "@draft.xml"
|
||||
lark-cli docs +script --command parse --content "@draft.md"
|
||||
lark-cli docs +script --command parse --doc "https://example.larksuite.com/docx/doxcn..."
|
||||
lark-cli docs +script --command markdown-to-xml --content "@draft.md" --output "draft.xml"`
|
||||
}
|
||||
|
||||
func validateDocsScript(_ context.Context, runtime *common.RuntimeContext) error {
|
||||
content := strings.TrimSpace(runtime.Str("content"))
|
||||
doc := strings.TrimSpace(runtime.Str("doc"))
|
||||
outputPath := strings.TrimSpace(runtime.Str("output"))
|
||||
fileName := strings.TrimSpace(runtime.Str("file-name"))
|
||||
if runtime.Str("command") == docsScriptCreateTempXML {
|
||||
switch {
|
||||
case content != "":
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--content is not supported with --command create-temp-xml").WithParam("--content")
|
||||
case doc != "":
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--doc is not supported with --command create-temp-xml").WithParam("--doc")
|
||||
case outputPath != "":
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--output is not supported with --command create-temp-xml").WithParam("--output")
|
||||
case runtime.Bool("overwrite"):
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--overwrite is not supported with --command create-temp-xml").WithParam("--overwrite")
|
||||
case fileName == "":
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--file-name is required with --command create-temp-xml").WithParam("--file-name")
|
||||
case runtime.Str("file-name") != fileName:
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--file-name must not start or end with whitespace").WithParam("--file-name")
|
||||
default:
|
||||
return validateDocsScriptTempXMLFileName(fileName)
|
||||
}
|
||||
}
|
||||
if fileName != "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--file-name is only supported with --command create-temp-xml").WithParam("--file-name")
|
||||
}
|
||||
if content == "" && doc == "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "one of --content or --doc is required").WithParams(
|
||||
errs.InvalidParam{Name: "--content", Reason: "provide local document content"},
|
||||
errs.InvalidParam{Name: "--doc", Reason: "provide an online document URL or token"},
|
||||
)
|
||||
}
|
||||
if content != "" && doc != "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--content and --doc are mutually exclusive").WithParams(
|
||||
errs.InvalidParam{Name: "--content", Reason: "mutually exclusive with --doc"},
|
||||
errs.InvalidParam{Name: "--doc", Reason: "mutually exclusive with --content"},
|
||||
)
|
||||
}
|
||||
if doc != "" {
|
||||
if runtime.Str("command") != docsScriptParse {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--doc is only supported with --command parse").WithParam("--doc")
|
||||
}
|
||||
if _, err := parseDocumentRef(doc); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := runtime.EnsureScopes([]string{"docx:document:readonly"}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if outputPath == "" {
|
||||
if runtime.Bool("overwrite") {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--overwrite requires --output").WithParam("--overwrite")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if runtime.Str("command") != docsScriptMarkdownToXML {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--output is only supported with --command markdown-to-xml").WithParam("--output")
|
||||
}
|
||||
if _, err := runtime.ResolveSavePath(outputPath); err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "unsafe output path: %s", err).
|
||||
WithParam("--output").
|
||||
WithCause(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func dryRunDocsScript(_ context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
if runtime.Str("command") == docsScriptCreateTempXML {
|
||||
fileName := strings.TrimSpace(runtime.Str("file-name"))
|
||||
return common.NewDryRunAPI().
|
||||
Desc("Create a random directory and an empty named XML file inside it; no API call is made").
|
||||
Set("command", docsScriptCreateTempXML).
|
||||
Set("directory_pattern", docsScriptTempDirectoryPattern(fileName)).
|
||||
Set("file_name", fileName).
|
||||
Set("xml_file_name", docsScriptXMLFileName(fileName)).
|
||||
Set("creates_file", false).
|
||||
Set("network", false)
|
||||
}
|
||||
if doc := strings.TrimSpace(runtime.Str("doc")); doc != "" {
|
||||
ref, _ := parseDocumentRef(doc)
|
||||
return common.NewDryRunAPI().
|
||||
POST("/open-apis/docs_ai/v1/documents/:document_id/fetch").
|
||||
Desc("OpenAPI: fetch document for parsing and profiling").
|
||||
Body(docsScriptFetchBody(runtime)).
|
||||
Set("command", runtime.Str("command")).
|
||||
Set("document_id", ref.Token).
|
||||
Set("network", true)
|
||||
}
|
||||
dry := common.NewDryRunAPI().
|
||||
Desc("Local LarkOpenCLI document parsing or conversion; no API call is made").
|
||||
Set("command", runtime.Str("command")).
|
||||
Set("input_bytes", len(runtime.Str("content"))).
|
||||
Set("network", false)
|
||||
if outputPath := strings.TrimSpace(runtime.Str("output")); outputPath != "" {
|
||||
dry.Set("output", outputPath).Set("overwrite", runtime.Bool("overwrite"))
|
||||
}
|
||||
return dry
|
||||
}
|
||||
|
||||
func executeDocsScript(_ context.Context, runtime *common.RuntimeContext) error {
|
||||
command := runtime.Str("command")
|
||||
content := runtime.Str("content")
|
||||
switch command {
|
||||
case docsScriptCreateTempXML:
|
||||
return createDocsScriptTempXML(runtime)
|
||||
case docsScriptParse:
|
||||
inputParam := "--content"
|
||||
inputLabel := "--content"
|
||||
if strings.TrimSpace(runtime.Str("doc")) != "" {
|
||||
var err error
|
||||
content, err = fetchDocsScriptContent(runtime)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
inputParam = "--doc"
|
||||
inputLabel = "fetched document content"
|
||||
}
|
||||
profile, err := docxparse.ParseAuto(content)
|
||||
if err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"could not parse %s as LarkOpenCLI XML or Markdown: %s", inputLabel, err).
|
||||
WithParam(inputParam).
|
||||
WithCause(err)
|
||||
}
|
||||
runtime.OutFormatRaw(docsScriptParseResult{Profile: docsScriptPublicProfile{
|
||||
WordCount: profile.WordCount,
|
||||
CharCount: profile.CharCount,
|
||||
BlockCount: profile.BlockCount,
|
||||
Blocks: profile.Blocks,
|
||||
}}, nil, nil)
|
||||
return nil
|
||||
case docsScriptMarkdownToXML:
|
||||
xml, err := docxparse.MarkdownToXML(content)
|
||||
if err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"could not convert --content from Markdown to LarkOpenCLI XML: %s", err).
|
||||
WithParam("--content").
|
||||
WithCause(err)
|
||||
}
|
||||
if outputPath := strings.TrimSpace(runtime.Str("output")); outputPath != "" {
|
||||
return saveDocsScriptXML(runtime, outputPath, xml)
|
||||
}
|
||||
runtime.OutFormatRaw(docsScriptMarkdownResult{XML: xml}, nil, nil)
|
||||
return nil
|
||||
default:
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"unsupported --command %q", command).
|
||||
WithParam("--command")
|
||||
}
|
||||
}
|
||||
|
||||
func createDocsScriptTempXML(runtime *common.RuntimeContext) error {
|
||||
creator, ok := runtime.FileIO().(fileio.TempDirFileCreator)
|
||||
if !ok {
|
||||
return errs.NewValidationError(errs.SubtypeFailedPrecondition,
|
||||
"the active file I/O provider does not support temporary file creation").
|
||||
WithHint("run this command with the local file I/O provider")
|
||||
}
|
||||
fileName := strings.TrimSpace(runtime.Str("file-name"))
|
||||
path, err := creator.CreateTempDirFile(docsScriptTempDirectoryPattern(fileName), docsScriptXMLFileName(fileName))
|
||||
if err != nil {
|
||||
return common.WrapSaveErrorTyped(err)
|
||||
}
|
||||
if _, err := runtime.ResolveSavePath(path); err != nil {
|
||||
return errs.NewInternalError(errs.SubtypeFileIO,
|
||||
"resolve temporary XML path %s: %s", path, err).
|
||||
WithCause(err)
|
||||
}
|
||||
runtime.Out(docsScriptTempXMLResult{
|
||||
Path: path,
|
||||
}, nil)
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDocsScriptTempXMLFileName(fileName string) error {
|
||||
if fileName != filepath.Base(fileName) || strings.ContainsAny(fileName, "<>:\"/\\|?*\t\r\n") {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--file-name must be a portable file name without path separators or reserved characters").WithParam("--file-name")
|
||||
}
|
||||
if err := charcheck.RejectControlChars(fileName, "--file-name"); err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "%s", err).
|
||||
WithParam("--file-name").
|
||||
WithCause(err)
|
||||
}
|
||||
if strings.HasSuffix(fileName, ".") || strings.HasSuffix(fileName, " ") {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--file-name must not end with a dot or space").WithParam("--file-name")
|
||||
}
|
||||
if strings.EqualFold(filepath.Ext(fileName), ".xml") {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--file-name must omit the .xml extension").WithParam("--file-name")
|
||||
}
|
||||
base := strings.ToUpper(strings.SplitN(fileName, ".", 2)[0])
|
||||
if isWindowsReservedFileName(base) {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument,
|
||||
"--file-name uses a Windows-reserved device name").WithParam("--file-name")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func docsScriptTempDirectoryPattern(fileName string) string {
|
||||
return fileName + docsScriptTempDirSuffix
|
||||
}
|
||||
|
||||
func docsScriptXMLFileName(fileName string) string {
|
||||
return fileName + ".xml"
|
||||
}
|
||||
|
||||
func isWindowsReservedFileName(base string) bool {
|
||||
switch base {
|
||||
case "CON", "PRN", "AUX", "NUL":
|
||||
return true
|
||||
}
|
||||
if len(base) == 4 && (strings.HasPrefix(base, "COM") || strings.HasPrefix(base, "LPT")) {
|
||||
return base[3] >= '1' && base[3] <= '9'
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func docsScriptFetchBody(runtime *common.RuntimeContext) map[string]interface{} {
|
||||
body := map[string]interface{}{
|
||||
"format": "xml",
|
||||
"extra_param": docsFetchExtraParam,
|
||||
"export_option": map[string]interface{}{
|
||||
"export_block_id": false,
|
||||
"export_style_attrs": false,
|
||||
"export_cite_extra_data": false,
|
||||
},
|
||||
}
|
||||
if lang := resolveFetchLang(runtime); lang != "" {
|
||||
body["lang"] = lang
|
||||
}
|
||||
return body
|
||||
}
|
||||
|
||||
func fetchDocsScriptContent(runtime *common.RuntimeContext) (string, error) {
|
||||
ref, _ := parseDocumentRef(runtime.Str("doc"))
|
||||
apiPath := fmt.Sprintf("/open-apis/docs_ai/v1/documents/%s/fetch", ref.Token)
|
||||
data, err := doDocAPI(runtime, "POST", apiPath, docsScriptFetchBody(runtime))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
document, ok := data["document"].(map[string]interface{})
|
||||
if !ok || document == nil {
|
||||
return "", errs.NewInternalError(errs.SubtypeUnknown,
|
||||
"document fetch response for --doc is missing document")
|
||||
}
|
||||
content, ok := document["content"].(string)
|
||||
if !ok {
|
||||
return "", errs.NewInternalError(errs.SubtypeUnknown,
|
||||
"document fetch response for --doc is missing document.content")
|
||||
}
|
||||
return content, nil
|
||||
}
|
||||
|
||||
func saveDocsScriptXML(runtime *common.RuntimeContext, outputPath, xml string) error {
|
||||
if !runtime.Bool("overwrite") {
|
||||
if _, err := runtime.FileIO().Stat(outputPath); err == nil {
|
||||
return errs.NewValidationError(errs.SubtypeFailedPrecondition,
|
||||
"output file already exists: %s (use --overwrite to replace)", outputPath).
|
||||
WithParam("--output")
|
||||
} else if !errors.Is(err, fs.ErrNotExist) {
|
||||
if errors.Is(err, fileio.ErrPathValidation) {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "unsafe output path: %s", err).
|
||||
WithParam("--output").
|
||||
WithCause(err)
|
||||
}
|
||||
return errs.NewInternalError(errs.SubtypeFileIO,
|
||||
"cannot access output path %s: %s", outputPath, err).
|
||||
WithCause(err)
|
||||
}
|
||||
}
|
||||
|
||||
result, err := runtime.FileIO().Save(outputPath, fileio.SaveOptions{
|
||||
ContentType: "application/xml",
|
||||
ContentLength: int64(len(xml)),
|
||||
}, strings.NewReader(xml))
|
||||
if err != nil {
|
||||
return common.WrapSaveErrorTyped(err)
|
||||
}
|
||||
savedPath, err := runtime.ResolveSavePath(outputPath)
|
||||
if err != nil {
|
||||
return errs.NewInternalError(errs.SubtypeFileIO,
|
||||
"resolve saved XML path %s: %s", outputPath, err).
|
||||
WithCause(err)
|
||||
}
|
||||
runtime.Out(docsScriptMarkdownFileResult{
|
||||
SavedPath: savedPath,
|
||||
SizeBytes: result.Size(),
|
||||
}, nil)
|
||||
return nil
|
||||
}
|
||||
660
shortcuts/doc/docs_script_test.go
Normal file
660
shortcuts/doc/docs_script_test.go
Normal file
@@ -0,0 +1,660 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package doc
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/shortcuts/doc/internal/docxparse"
|
||||
)
|
||||
|
||||
func TestDocsScriptParsesAndProfilesXML(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-test"))
|
||||
source := `<title>标题</title><p>一个苹果是 an apple。</p>`
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", source,
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script: %v", err)
|
||||
}
|
||||
|
||||
var envelope struct {
|
||||
OK bool `json:"ok"`
|
||||
Data map[string]json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if !envelope.OK {
|
||||
t.Fatalf("ok = false: %s", stdout)
|
||||
}
|
||||
if len(envelope.Data) != 1 || envelope.Data["profile"] == nil {
|
||||
t.Fatalf("data = %+v, want only profile", envelope.Data)
|
||||
}
|
||||
var profile docsScriptPublicProfile
|
||||
if err := json.Unmarshal(envelope.Data["profile"], &profile); err != nil {
|
||||
t.Fatalf("decode profile: %v", err)
|
||||
}
|
||||
var profileFields map[string]json.RawMessage
|
||||
if err := json.Unmarshal(envelope.Data["profile"], &profileFields); err != nil {
|
||||
t.Fatalf("decode profile fields: %v", err)
|
||||
}
|
||||
if len(profileFields) != 4 || profileFields["breakdown"] != nil {
|
||||
t.Fatalf("profile fields = %+v, want breakdown hidden", profileFields)
|
||||
}
|
||||
if profile.WordCount != 10 || profile.CharCount != 15 || profile.BlockCount != 2 {
|
||||
t.Fatalf("profile = %+v", profile)
|
||||
}
|
||||
if got := blockCount(profile.Blocks, "title"); got != 1 {
|
||||
t.Fatalf("title count = %d, want 1", got)
|
||||
}
|
||||
if got := blockCount(profile.Blocks, "p"); got != 1 {
|
||||
t.Fatalf("p count = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptParseAutoDetectsMarkdown(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-auto-markdown"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", "# 标题\n\n- item",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script: %v", err)
|
||||
}
|
||||
|
||||
var envelope struct {
|
||||
Data docsScriptParseResult `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if envelope.Data.Profile.BlockCount != 3 {
|
||||
t.Fatalf("profile = %+v, want 3 blocks", envelope.Data.Profile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptParsesOnlineDocumentFromToken(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-online-token"))
|
||||
registerDocsAIStub(reg, "POST", "/open-apis/docs_ai/v1/documents/doxcnScriptToken/fetch", map[string]interface{}{
|
||||
"document": map[string]interface{}{
|
||||
"document_id": "doxcnScriptToken",
|
||||
"content": `<title>在线文档</title><p>Hello world</p>`,
|
||||
},
|
||||
})
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--doc", "doxcnScriptToken",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script with token: %v", err)
|
||||
}
|
||||
|
||||
var envelope struct {
|
||||
Data docsScriptParseResult `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if envelope.Data.Profile.BlockCount != 2 {
|
||||
t.Fatalf("profile = %+v, want 2 blocks", envelope.Data.Profile)
|
||||
}
|
||||
if got := blockCount(envelope.Data.Profile.Blocks, "title"); got != 1 {
|
||||
t.Fatalf("title count = %d, want 1", got)
|
||||
}
|
||||
if got := blockCount(envelope.Data.Profile.Blocks, "p"); got != 1 {
|
||||
t.Fatalf("p count = %d, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptParsesOnlineDocumentFromURL(t *testing.T) {
|
||||
t.Setenv("LARKSUITE_CLI_CONFIG_DIR", t.TempDir())
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-online-url"))
|
||||
stub := registerDocsAIStub(reg, "POST", "/open-apis/docs_ai/v1/documents/wikcnScriptURL/fetch", map[string]interface{}{
|
||||
"document": map[string]interface{}{
|
||||
"document_id": "doxcnResolvedScriptURL",
|
||||
"content": `<p>从 Wiki URL 读取</p>`,
|
||||
},
|
||||
})
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--doc", "https://example.larksuite.com/wiki/wikcnScriptURL",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script with URL: %v", err)
|
||||
}
|
||||
if stub.CapturedBody == nil {
|
||||
t.Fatal("online parse did not call the document fetch API")
|
||||
}
|
||||
|
||||
var envelope struct {
|
||||
Data docsScriptParseResult `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if envelope.Data.Profile.BlockCount != 1 || blockCount(envelope.Data.Profile.Blocks, "p") != 1 {
|
||||
t.Fatalf("profile = %+v, want one paragraph", envelope.Data.Profile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptRejectsContentAndDocTogether(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-input-conflict"))
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", `<p>local</p>`,
|
||||
"--doc", "doxcnScriptConflict",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
assertValidationContract(t, err, errs.SubtypeInvalidArgument, "", "--content", "--doc")
|
||||
}
|
||||
|
||||
func TestDocsScriptRejectsDocForMarkdownConversion(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-doc-convert"))
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptMarkdownToXML,
|
||||
"--doc", "doxcnScriptConvert",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
assertValidationContract(t, err, errs.SubtypeInvalidArgument, "--doc")
|
||||
}
|
||||
|
||||
func TestDocsScriptConvertsMarkdownFromStdin(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-markdown"))
|
||||
f.IOStreams.In = bytes.NewBufferString("# 标题\n\n- item")
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptMarkdownToXML,
|
||||
"--content", "-",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script: %v", err)
|
||||
}
|
||||
if !strings.Contains(stdout.String(), `<h1>标题</h1><ul><li>item</li></ul>`) {
|
||||
t.Fatalf("stdout missing converted XML: %s", stdout)
|
||||
}
|
||||
var envelope struct {
|
||||
Data map[string]json.RawMessage `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if len(envelope.Data) != 1 || envelope.Data["xml"] == nil {
|
||||
t.Fatalf("data = %+v, want only xml", envelope.Data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptConvertsMarkdownToOutputFile(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
withDocsWorkingDir(t, workDir)
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-output"))
|
||||
wantXML := `<h1>标题</h1><ul><li>item</li></ul>`
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptMarkdownToXML,
|
||||
"--content", "# 标题\n\n- item",
|
||||
"--output", "draft.xml",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script: %v", err)
|
||||
}
|
||||
gotXML, err := os.ReadFile("draft.xml")
|
||||
if err != nil {
|
||||
t.Fatalf("read output XML: %v", err)
|
||||
}
|
||||
if string(gotXML) != wantXML {
|
||||
t.Fatalf("output XML = %q, want %q", gotXML, wantXML)
|
||||
}
|
||||
|
||||
var envelope struct {
|
||||
Data struct {
|
||||
SavedPath string `json:"saved_path"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
XML json.RawMessage `json:"xml"`
|
||||
} `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if envelope.Data.SavedPath != filepath.Join(workDir, "draft.xml") {
|
||||
t.Fatalf("saved_path = %q, want %q", envelope.Data.SavedPath, filepath.Join(workDir, "draft.xml"))
|
||||
}
|
||||
if envelope.Data.SizeBytes != int64(len(wantXML)) {
|
||||
t.Fatalf("size_bytes = %d, want %d", envelope.Data.SizeBytes, len(wantXML))
|
||||
}
|
||||
if envelope.Data.XML != nil {
|
||||
t.Fatalf("data.xml should be omitted when --output is used: %s", stdout)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptCreatesUniqueTempXMLFiles(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
withDocsWorkingDir(t, workDir)
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-temp-xml"))
|
||||
|
||||
create := func() docsScriptTempXMLResult {
|
||||
t.Helper()
|
||||
stdout.Reset()
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptCreateTempXML,
|
||||
"--file-name", "川西",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script: %v", err)
|
||||
}
|
||||
var envelope struct {
|
||||
Data docsScriptTempXMLResult `json:"data"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
return envelope.Data
|
||||
}
|
||||
|
||||
first := create()
|
||||
second := create()
|
||||
if first.Path == second.Path {
|
||||
t.Fatalf("temporary paths are identical: %q", first.Path)
|
||||
}
|
||||
for _, got := range []docsScriptTempXMLResult{first, second} {
|
||||
directory := filepath.Dir(got.Path)
|
||||
if filepath.Base(got.Path) != "川西.xml" || filepath.Base(directory) != directory ||
|
||||
!strings.HasPrefix(directory, "川西_") || !strings.HasSuffix(directory, "_folder") {
|
||||
t.Fatalf("path = %q, want 川西_<random>_folder/川西.xml", got.Path)
|
||||
}
|
||||
info, err := os.Stat(got.Path)
|
||||
if err != nil {
|
||||
t.Fatalf("stat temporary XML %q: %v", got.Path, err)
|
||||
}
|
||||
if info.Size() != 0 {
|
||||
t.Fatalf("temporary XML %q size = %d, want 0", got.Path, info.Size())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptCreateTempXMLRejectsOtherFlags(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
args []string
|
||||
param string
|
||||
}{
|
||||
{name: "content", args: []string{"--content", "<p>text</p>"}, param: "--content"},
|
||||
{name: "doc", args: []string{"--doc", "doxcnScriptTemp"}, param: "--doc"},
|
||||
{name: "output", args: []string{"--output", "draft.xml"}, param: "--output"},
|
||||
{name: "overwrite", args: []string{"--overwrite"}, param: "--overwrite"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-temp-xml-flags"))
|
||||
args := []string{"+script", "--command", docsScriptCreateTempXML, "--file-name", "川西", "--as", "bot"}
|
||||
args = append(args, test.args...)
|
||||
err := mountAndRunDocs(t, DocsScript, args, f, nil)
|
||||
if err == nil {
|
||||
t.Fatalf("expected %s validation error", test.param)
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
var validationErr *errs.ValidationError
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument ||
|
||||
!errors.As(err, &validationErr) || validationErr.Param != test.param {
|
||||
t.Fatalf("problem = %+v, validation = %+v, ok=%v", problem, validationErr, ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptCreateTempXMLValidatesFileName(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
fileName string
|
||||
}{
|
||||
{name: "missing"},
|
||||
{name: "path", fileName: "folder/川西"},
|
||||
{name: "windows path", fileName: `folder\川西`},
|
||||
{name: "reserved character", fileName: "川西:一"},
|
||||
{name: "xml extension included", fileName: "川西.xml"},
|
||||
{name: "windows device", fileName: "CON"},
|
||||
{name: "surrounding whitespace", fileName: " 川西"},
|
||||
{name: "dangerous unicode", fileName: "川\u200b西"},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-temp-xml-file-name"))
|
||||
args := []string{"+script", "--command", docsScriptCreateTempXML, "--as", "bot"}
|
||||
if test.fileName != "" {
|
||||
args = append(args, "--file-name", test.fileName)
|
||||
}
|
||||
err := mountAndRunDocs(t, DocsScript, args, f, nil)
|
||||
if err == nil {
|
||||
t.Fatalf("expected --file-name validation error for %q", test.fileName)
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
var validationErr *errs.ValidationError
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument ||
|
||||
!errors.As(err, &validationErr) || validationErr.Param != "--file-name" {
|
||||
t.Fatalf("problem = %+v, validation = %+v, ok=%v", problem, validationErr, ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptOutputRequiresExplicitOverwrite(t *testing.T) {
|
||||
withDocsWorkingDir(t, t.TempDir())
|
||||
if err := os.WriteFile("draft.xml", []byte("old"), 0o600); err != nil {
|
||||
t.Fatalf("write existing output: %v", err)
|
||||
}
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-overwrite"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptMarkdownToXML,
|
||||
"--content", "# new",
|
||||
"--output", "draft.xml",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("expected existing output error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
var validationErr *errs.ValidationError
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeFailedPrecondition ||
|
||||
!errors.As(err, &validationErr) || validationErr.Param != "--output" {
|
||||
t.Fatalf("problem = %+v, validation = %+v, ok=%v", problem, validationErr, ok)
|
||||
}
|
||||
got, readErr := os.ReadFile("draft.xml")
|
||||
if readErr != nil || string(got) != "old" {
|
||||
t.Fatalf("existing output changed: content=%q err=%v", got, readErr)
|
||||
}
|
||||
|
||||
err = mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptMarkdownToXML,
|
||||
"--content", "# new",
|
||||
"--output", "draft.xml",
|
||||
"--overwrite",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script with --overwrite: %v", err)
|
||||
}
|
||||
got, readErr = os.ReadFile("draft.xml")
|
||||
if readErr != nil || string(got) != "<h1>new</h1>" {
|
||||
t.Fatalf("overwritten output = %q, err=%v", got, readErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptRejectsOutputForParse(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-output-parse"))
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", `<p>text</p>`,
|
||||
"--output", "draft.xml",
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected --output validation error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
var validationErr *errs.ValidationError
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument ||
|
||||
!errors.As(err, &validationErr) || validationErr.Param != "--output" {
|
||||
t.Fatalf("problem = %+v, validation = %+v, ok=%v", problem, validationErr, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptRejectsUnsafeOutputPath(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-output-path"))
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptMarkdownToXML,
|
||||
"--content", "# title",
|
||||
"--output", filepath.Join(t.TempDir(), "draft.xml"),
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected unsafe output path error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
var validationErr *errs.ValidationError
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument ||
|
||||
!errors.As(err, &validationErr) || validationErr.Param != "--output" {
|
||||
t.Fatalf("problem = %+v, validation = %+v, ok=%v", problem, validationErr, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptDryRunHasNoAPICall(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-dry-run"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", `<p>text</p>`,
|
||||
"--dry-run",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script dry-run: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
API []any `json:"api"`
|
||||
Command string `json:"command"`
|
||||
Network bool `json:"network"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode dry-run stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if len(got.API) != 0 || got.Command != docsScriptParse || got.Network {
|
||||
t.Fatalf("dry-run output = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptCreateTempXMLDryRunDoesNotWrite(t *testing.T) {
|
||||
workDir := t.TempDir()
|
||||
withDocsWorkingDir(t, workDir)
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-temp-xml-dry-run"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptCreateTempXML,
|
||||
"--file-name", "川西",
|
||||
"--dry-run",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script dry-run: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
API []any `json:"api"`
|
||||
Command string `json:"command"`
|
||||
DirectoryPattern string `json:"directory_pattern"`
|
||||
FileName string `json:"file_name"`
|
||||
XMLFileName string `json:"xml_file_name"`
|
||||
CreatesFile bool `json:"creates_file"`
|
||||
Network bool `json:"network"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode dry-run stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if len(got.API) != 0 || got.Command != docsScriptCreateTempXML ||
|
||||
got.DirectoryPattern != "川西_*_folder" || got.FileName != "川西" || got.XMLFileName != "川西.xml" ||
|
||||
got.CreatesFile || got.Network {
|
||||
t.Fatalf("dry-run output = %+v", got)
|
||||
}
|
||||
entries, err := os.ReadDir(workDir)
|
||||
if err != nil {
|
||||
t.Fatalf("read work directory: %v", err)
|
||||
}
|
||||
if len(entries) != 0 {
|
||||
t.Fatalf("dry-run created files: %+v", entries)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptOnlineDryRunShowsFetchAPICall(t *testing.T) {
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-online-dry-run"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--doc", "https://example.larksuite.com/docx/doxcnScriptDryRun",
|
||||
"--dry-run",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute online docs +script dry-run: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
Command string `json:"command"`
|
||||
DocumentID string `json:"document_id"`
|
||||
Network bool `json:"network"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode dry-run stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if len(got.API) != 1 || got.API[0].Method != "POST" ||
|
||||
got.API[0].URL != "/open-apis/docs_ai/v1/documents/doxcnScriptDryRun/fetch" {
|
||||
t.Fatalf("dry-run API = %+v", got.API)
|
||||
}
|
||||
if got.API[0].Body["format"] != "xml" {
|
||||
t.Fatalf("dry-run body = %+v, want XML fetch", got.API[0].Body)
|
||||
}
|
||||
if got.Command != docsScriptParse || got.DocumentID != "doxcnScriptDryRun" || !got.Network {
|
||||
t.Fatalf("dry-run output = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptOutputDryRunDoesNotWrite(t *testing.T) {
|
||||
withDocsWorkingDir(t, t.TempDir())
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-output-dry-run"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptMarkdownToXML,
|
||||
"--content", "# title",
|
||||
"--output", "draft.xml",
|
||||
"--overwrite",
|
||||
"--dry-run",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("execute docs +script dry-run: %v", err)
|
||||
}
|
||||
var got struct {
|
||||
API []any `json:"api"`
|
||||
Command string `json:"command"`
|
||||
Network bool `json:"network"`
|
||||
Output string `json:"output"`
|
||||
Overwrite bool `json:"overwrite"`
|
||||
}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode dry-run stdout: %v\n%s", err, stdout)
|
||||
}
|
||||
if len(got.API) != 0 || got.Command != docsScriptMarkdownToXML || got.Network || got.Output != "draft.xml" || !got.Overwrite {
|
||||
t.Fatalf("dry-run output = %+v", got)
|
||||
}
|
||||
if _, err := os.Stat("draft.xml"); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("dry-run created output file: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptReturnsTypedParseError(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-error"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", `<!DOCTYPE document><p>text</p>`,
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected parse error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("problem = %+v, ok=%v", problem, ok)
|
||||
}
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || validationErr.Param != "--content" {
|
||||
t.Fatalf("error = %#v, want --content metadata", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptRejectsMalformedXML(t *testing.T) {
|
||||
f, _, _, _ := cmdutil.TestFactory(t, docsTestConfigWithAppID("docs-script-malformed"))
|
||||
|
||||
err := mountAndRunDocs(t, DocsScript, []string{
|
||||
"+script",
|
||||
"--command", docsScriptParse,
|
||||
"--content", `<p>text`,
|
||||
"--as", "bot",
|
||||
}, f, nil)
|
||||
if err == nil {
|
||||
t.Fatal("expected malformed XML error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("problem = %+v, ok=%v", problem, ok)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDocsScriptHelpExamplesAreCrossShellSafe(t *testing.T) {
|
||||
cmd := &cobra.Command{Short: "local document parser"}
|
||||
installDocsScriptHelp(cmd)
|
||||
if strings.Contains(cmd.Example, "cat ") {
|
||||
t.Fatalf("help examples require a platform-specific command: %q", cmd.Example)
|
||||
}
|
||||
if strings.Contains(cmd.Example, "--content @") {
|
||||
t.Fatalf("help examples contain an unquoted @file argument: %q", cmd.Example)
|
||||
}
|
||||
for _, want := range []string{`--command create-temp-xml --file-name "draft"`, `--content "@draft.xml"`, `--content "@draft.md"`, `--output "draft.xml"`} {
|
||||
if !strings.Contains(cmd.Example, want) {
|
||||
t.Errorf("help examples missing %q: %q", want, cmd.Example)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func blockCount(blocks []docxparse.BlockShare, typ string) int {
|
||||
for _, block := range blocks {
|
||||
if block.Type == typ {
|
||||
return block.Count
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
743
shortcuts/doc/internal/docxparse/markdown.go
Normal file
743
shortcuts/doc/internal/docxparse/markdown.go
Normal file
@@ -0,0 +1,743 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
// Markdown conversion is scoped to the docs +script business domain.
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/yuin/goldmark"
|
||||
gast "github.com/yuin/goldmark/ast"
|
||||
"github.com/yuin/goldmark/extension"
|
||||
extast "github.com/yuin/goldmark/extension/ast"
|
||||
"github.com/yuin/goldmark/parser"
|
||||
"github.com/yuin/goldmark/text"
|
||||
gmutil "github.com/yuin/goldmark/util"
|
||||
)
|
||||
|
||||
var markdownParser parser.Parser
|
||||
|
||||
func init() {
|
||||
markdown := goldmark.New(
|
||||
goldmark.WithExtensions(
|
||||
extension.GFM,
|
||||
extension.DefinitionList,
|
||||
&mathExtension{},
|
||||
&underscoreHTMLExtension{},
|
||||
),
|
||||
goldmark.WithParserOptions(
|
||||
parser.WithBlockParsers(gmutil.Prioritized(&containerBlockParser{}, 90)),
|
||||
),
|
||||
)
|
||||
markdownParser = markdown.Parser()
|
||||
}
|
||||
|
||||
func parseMarkdown(source string) ([]*Node, error) {
|
||||
if err := validateSource(source); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
source = strings.TrimPrefix(source, "\uFEFF")
|
||||
source = normalizeListIndent(source)
|
||||
source = preprocessCJKAdjacentMarkup(source)
|
||||
data := []byte(source)
|
||||
document := markdownParser.Parse(text.NewReader(data))
|
||||
return renderBlockChildren(document, data)
|
||||
}
|
||||
|
||||
func renderBlockChildren(parent gast.Node, source []byte) ([]*Node, error) {
|
||||
var out []*Node
|
||||
for child := parent.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
nodes, err := renderBlockNode(child, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, nodes...)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func renderBlockNode(node gast.Node, source []byte) ([]*Node, error) {
|
||||
switch node.Kind() {
|
||||
case gast.KindParagraph, gast.KindTextBlock:
|
||||
children, err := renderInlineChildren(node, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return wrapParagraphChildren(children), nil
|
||||
case gast.KindHeading:
|
||||
heading := newElement(headingTag(node.(*gast.Heading).Level), nil)
|
||||
children, err := renderInlineChildren(node, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, child := range children {
|
||||
heading.addChild(child)
|
||||
}
|
||||
return []*Node{heading}, nil
|
||||
case gast.KindBlockquote:
|
||||
return renderContainer("blockquote", nil, node, source)
|
||||
case gast.KindList:
|
||||
return renderList(node.(*gast.List), source)
|
||||
case gast.KindFencedCodeBlock:
|
||||
block := node.(*gast.FencedCodeBlock)
|
||||
language := string(block.Language(source))
|
||||
content := trimOneTrailingNewline(string(node.Lines().Value(source)))
|
||||
lowerLanguage := strings.ToLower(language)
|
||||
if content != "" && (lowerLanguage == "mermaid" || lowerLanguage == "plantuml" || lowerLanguage == "svg") {
|
||||
whiteboard := newElement("whiteboard", map[string]string{"type": lowerLanguage})
|
||||
appendRawTextWithBreaks(whiteboard, content)
|
||||
return []*Node{whiteboard}, nil
|
||||
}
|
||||
attrs := map[string]string(nil)
|
||||
if language != "" {
|
||||
attrs = map[string]string{"lang": language}
|
||||
}
|
||||
pre := newElement("pre", attrs)
|
||||
code := newElement("code", nil)
|
||||
appendRawTextWithBreaks(code, content)
|
||||
pre.addChild(code)
|
||||
return []*Node{pre}, nil
|
||||
case gast.KindCodeBlock:
|
||||
pre := newElement("pre", nil)
|
||||
code := newElement("code", nil)
|
||||
appendRawTextWithBreaks(code, trimOneTrailingNewline(string(node.Lines().Value(source))))
|
||||
pre.addChild(code)
|
||||
return []*Node{pre}, nil
|
||||
case gast.KindThematicBreak:
|
||||
return []*Node{newElement("hr", nil)}, nil
|
||||
case gast.KindHTMLBlock:
|
||||
nodes, err := parseMarkdownHTMLBlock(string(node.Lines().Value(source)))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stripMarkdownEscapesInNodes(nodes, false, false)
|
||||
return nodes, nil
|
||||
case kindContainerBlock:
|
||||
container := node.(*containerBlock)
|
||||
return renderContainer(container.spec.tag, container.attrs, node, source)
|
||||
}
|
||||
|
||||
switch node.Kind() {
|
||||
case extast.KindTable:
|
||||
return renderTable(node, source)
|
||||
case extast.KindDefinitionList:
|
||||
return renderDefinitionList(node, source)
|
||||
}
|
||||
|
||||
value := strings.TrimSpace(extractMarkdownText(node, source))
|
||||
if value == "" {
|
||||
return nil, nil
|
||||
}
|
||||
paragraph := newElement("p", nil)
|
||||
paragraph.addChild(newText(value))
|
||||
return []*Node{paragraph}, nil
|
||||
}
|
||||
|
||||
// parseMarkdownHTMLBlock handles the source-bearing LarkOpenCLI blocks whose
|
||||
// Markdown bodies are literal text, then delegates every other XML fragment to
|
||||
// the strict XML parser. Escaping literal code is part of Markdown conversion.
|
||||
func parseMarkdownHTMLBlock(fragment string) ([]*Node, error) {
|
||||
trimmed := strings.TrimSpace(fragment)
|
||||
for _, tag := range []string{"code", "whiteboard"} {
|
||||
closing := "</" + tag + ">"
|
||||
if !strings.HasPrefix(trimmed, "<"+tag) || !strings.HasSuffix(trimmed, closing) {
|
||||
continue
|
||||
}
|
||||
token, contentStart, state := scanXMLToken(trimmed, 0)
|
||||
if state != tokenOK || token.closing || token.selfClosing || token.name != tag {
|
||||
return nil, fmt.Errorf("invalid Markdown <%s> block", tag)
|
||||
}
|
||||
contentEnd := len(trimmed) - len(closing)
|
||||
if contentStart > contentEnd {
|
||||
return nil, fmt.Errorf("invalid Markdown <%s> block", tag)
|
||||
}
|
||||
attrs := normalizeAttributes(tag, tag, token.attrs)
|
||||
block := newElement(tag, attrs)
|
||||
appendRawTextWithBreaks(block, strings.Trim(trimmed[contentStart:contentEnd], "\r\n"))
|
||||
return []*Node{block}, nil
|
||||
}
|
||||
return parseXML(fragment)
|
||||
}
|
||||
|
||||
func renderContainer(tag string, attrs map[string]string, node gast.Node, source []byte) ([]*Node, error) {
|
||||
attrs = normalizeAttributes(tag, tag, attrs)
|
||||
container := newElement(tag, attrs)
|
||||
children, err := renderBlockChildren(node, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, child := range children {
|
||||
container.addChild(child)
|
||||
}
|
||||
return []*Node{container}, nil
|
||||
}
|
||||
|
||||
func renderList(list *gast.List, source []byte) ([]*Node, error) {
|
||||
if isTaskList(list) {
|
||||
return renderTaskList(list, source)
|
||||
}
|
||||
tag := "ul"
|
||||
if list.IsOrdered() {
|
||||
tag = "ol"
|
||||
}
|
||||
listNode := newElement(tag, nil)
|
||||
for child := list.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
if child.Kind() != gast.KindListItem {
|
||||
continue
|
||||
}
|
||||
item, err := renderListItem(child.(*gast.ListItem), list.IsTight, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
listNode.addChild(item)
|
||||
}
|
||||
return []*Node{listNode}, nil
|
||||
}
|
||||
|
||||
func isTaskList(list *gast.List) bool {
|
||||
first := list.FirstChild()
|
||||
if first == nil || first.Kind() != gast.KindListItem {
|
||||
return false
|
||||
}
|
||||
return findTaskCheckbox(first.(*gast.ListItem)) != nil
|
||||
}
|
||||
|
||||
func findTaskCheckbox(item *gast.ListItem) *extast.TaskCheckBox {
|
||||
for child := item.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
if child.Kind() != gast.KindTextBlock && child.Kind() != gast.KindParagraph {
|
||||
continue
|
||||
}
|
||||
if first := child.FirstChild(); first != nil && first.Kind() == extast.KindTaskCheckBox {
|
||||
return first.(*extast.TaskCheckBox)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func renderTaskList(list *gast.List, source []byte) ([]*Node, error) {
|
||||
var out []*Node
|
||||
for child := list.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
if child.Kind() != gast.KindListItem {
|
||||
continue
|
||||
}
|
||||
item := child.(*gast.ListItem)
|
||||
checkboxAST := findTaskCheckbox(item)
|
||||
if checkboxAST == nil {
|
||||
li, err := renderListItem(item, list.IsTight, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
ul := newElement("ul", nil)
|
||||
ul.addChild(li)
|
||||
out = append(out, ul)
|
||||
continue
|
||||
}
|
||||
done := "false"
|
||||
if checkboxAST.IsChecked {
|
||||
done = "true"
|
||||
}
|
||||
checkbox := newElement("checkbox", map[string]string{"done": done})
|
||||
for block := item.FirstChild(); block != nil; block = block.NextSibling() {
|
||||
if block.Kind() == gast.KindTextBlock || block.Kind() == gast.KindParagraph {
|
||||
fragment, err := renderInlineFragment(block, source, true)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodes, err := parseMarkdownInlineFragment(fragment)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, node := range nodes {
|
||||
checkbox.addChild(node)
|
||||
}
|
||||
continue
|
||||
}
|
||||
nodes, err := renderBlockNode(block, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, node := range nodes {
|
||||
checkbox.addChild(node)
|
||||
}
|
||||
}
|
||||
out = append(out, checkbox)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func renderListItem(item *gast.ListItem, tight bool, source []byte) (*Node, error) {
|
||||
li := newElement("li", nil)
|
||||
children, err := renderBlockChildren(item, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, child := range children {
|
||||
if child.tag == "p" && (tight || paragraphOnlyInline(child)) {
|
||||
for _, grandchild := range child.children {
|
||||
li.addChild(grandchild)
|
||||
}
|
||||
continue
|
||||
}
|
||||
li.addChild(child)
|
||||
}
|
||||
return li, nil
|
||||
}
|
||||
|
||||
func renderInlineChildren(node gast.Node, source []byte) ([]*Node, error) {
|
||||
fragment, err := renderInlineFragment(node, source, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodes, err := parseMarkdownInlineFragment(fragment)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
stripMarkdownEscapesInNodes(nodes, false, false)
|
||||
return nodes, nil
|
||||
}
|
||||
|
||||
// parseMarkdownInlineFragment wraps an inline fragment in a space-preserving
|
||||
// parent while parsing so XML normalization keeps semantic spaces between
|
||||
// adjacent inline elements. The wrapper is removed from the returned nodes.
|
||||
func parseMarkdownInlineFragment(fragment string) ([]*Node, error) {
|
||||
nodes, err := parseXML("<p>" + fragment + "</p>")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(nodes) != 1 || nodes[0].typ != nodeElement || nodes[0].tag != "p" {
|
||||
return nil, fmt.Errorf("invalid Markdown inline fragment")
|
||||
}
|
||||
children := nodes[0].children
|
||||
for _, child := range children {
|
||||
child.parent = nil
|
||||
}
|
||||
return children, nil
|
||||
}
|
||||
|
||||
func renderInlineFragment(parent gast.Node, source []byte, skipCheckbox bool) (string, error) {
|
||||
var out strings.Builder
|
||||
for child := parent.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
if skipCheckbox && child.Kind() == extast.KindTaskCheckBox {
|
||||
continue
|
||||
}
|
||||
fragment, err := renderInlineNode(child, source)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
out.WriteString(fragment)
|
||||
}
|
||||
return out.String(), nil
|
||||
}
|
||||
|
||||
func renderInlineNode(node gast.Node, source []byte) (string, error) {
|
||||
switch node.Kind() {
|
||||
case gast.KindText:
|
||||
textNode := node.(*gast.Text)
|
||||
value := escapeXMLText(stripBackslashEscapes(string(textNode.Value(source))))
|
||||
switch {
|
||||
case textNode.HardLineBreak():
|
||||
value += "<br/>"
|
||||
case textNode.SoftLineBreak():
|
||||
value += " "
|
||||
}
|
||||
return value, nil
|
||||
case gast.KindString:
|
||||
return escapeXMLText(string(node.(*gast.String).Value)), nil
|
||||
case gast.KindEmphasis:
|
||||
tag := "em"
|
||||
if node.(*gast.Emphasis).Level >= 2 {
|
||||
tag = "b"
|
||||
}
|
||||
return renderInlineContainer(node, tag, nil, source)
|
||||
case gast.KindCodeSpan:
|
||||
return elementXML("code", nil, escapeXMLText(collectMarkdownChildText(node, source))), nil
|
||||
case gast.KindLink:
|
||||
link := node.(*gast.Link)
|
||||
attrs := map[string]string{"href": string(link.Destination)}
|
||||
if len(link.Title) > 0 {
|
||||
attrs["title"] = string(link.Title)
|
||||
}
|
||||
children, err := renderInlineFragment(node, source, false)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
if children == "" {
|
||||
children = escapeXMLText(string(link.Destination))
|
||||
}
|
||||
return elementXML("a", attrs, children), nil
|
||||
case gast.KindImage:
|
||||
image := node.(*gast.Image)
|
||||
destination := string(image.Destination)
|
||||
attrs := map[string]string{}
|
||||
if strings.HasPrefix(destination, "http://") || strings.HasPrefix(destination, "https://") {
|
||||
attrs["href"] = destination
|
||||
} else {
|
||||
attrs["src"] = destination
|
||||
}
|
||||
if len(image.Title) > 0 {
|
||||
attrs["title"] = string(image.Title)
|
||||
}
|
||||
return elementXML("img", attrs, ""), nil
|
||||
case gast.KindRawHTML:
|
||||
return string(node.(*gast.RawHTML).Segments.Value(source)), nil
|
||||
case gast.KindAutoLink:
|
||||
link := node.(*gast.AutoLink)
|
||||
return elementXML("a", map[string]string{"href": string(link.URL(source))}, escapeXMLText(string(link.Label(source)))), nil
|
||||
}
|
||||
|
||||
switch node.Kind() {
|
||||
case extast.KindStrikethrough:
|
||||
return renderInlineContainer(node, "del", nil, source)
|
||||
case kindMathInline:
|
||||
return elementXML("latex", nil, escapeXMLText(stripLatexMarkdownEscapes(string(node.(*mathInline).content)))), nil
|
||||
case kindMathBlock:
|
||||
return elementXML("latex", nil, escapeXMLText(stripLatexMarkdownEscapes(string(node.(*mathBlock).content)))), nil
|
||||
case extast.KindTaskCheckBox:
|
||||
return "", nil
|
||||
}
|
||||
|
||||
if node.Type() == gast.TypeBlock {
|
||||
return escapeXMLText(strings.TrimSpace(extractMarkdownText(node, source))), nil
|
||||
}
|
||||
return escapeXMLText(extractMarkdownText(node, source)), nil
|
||||
}
|
||||
|
||||
func renderInlineContainer(node gast.Node, tag string, attrs map[string]string, source []byte) (string, error) {
|
||||
children, err := renderInlineFragment(node, source, false)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return elementXML(tag, attrs, children), nil
|
||||
}
|
||||
|
||||
func elementXML(tag string, attrs map[string]string, inner string) string {
|
||||
node := newElement(tag, attrs)
|
||||
rendered := renderNodes([]*Node{node})
|
||||
if inner == "" {
|
||||
return rendered
|
||||
}
|
||||
close := "</" + tag + ">"
|
||||
if strings.HasSuffix(rendered, close) {
|
||||
return strings.TrimSuffix(rendered, close) + inner + close
|
||||
}
|
||||
return rendered
|
||||
}
|
||||
|
||||
func wrapParagraphChildren(children []*Node) []*Node {
|
||||
var out []*Node
|
||||
var inline []*Node
|
||||
flush := func() {
|
||||
if len(inline) == 0 {
|
||||
return
|
||||
}
|
||||
paragraph := newElement("p", nil)
|
||||
for _, child := range inline {
|
||||
paragraph.addChild(child)
|
||||
}
|
||||
out = append(out, paragraph)
|
||||
inline = nil
|
||||
}
|
||||
for _, child := range children {
|
||||
if child != nil && child.typ == nodeElement && layoutOf(child.tag) == layoutBlock {
|
||||
flush()
|
||||
out = append(out, child)
|
||||
continue
|
||||
}
|
||||
inline = append(inline, child)
|
||||
}
|
||||
flush()
|
||||
return out
|
||||
}
|
||||
|
||||
func paragraphOnlyInline(node *Node) bool {
|
||||
if node == nil || node.typ != nodeElement || node.tag != "p" {
|
||||
return false
|
||||
}
|
||||
for _, child := range node.children {
|
||||
if child.typ == nodeElement && layoutOf(child.tag) == layoutBlock {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func renderTable(node gast.Node, source []byte) ([]*Node, error) {
|
||||
table := newElement("table", nil)
|
||||
var body *Node
|
||||
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
switch child.Kind() {
|
||||
case extast.KindTableHeader:
|
||||
head := newElement("thead", nil)
|
||||
row, err := renderTableRow(child, true, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
head.addChild(row)
|
||||
table.addChild(head)
|
||||
case extast.KindTableRow:
|
||||
if body == nil {
|
||||
body = newElement("tbody", nil)
|
||||
table.addChild(body)
|
||||
}
|
||||
row, err := renderTableRow(child, false, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
body.addChild(row)
|
||||
}
|
||||
}
|
||||
return []*Node{table}, nil
|
||||
}
|
||||
|
||||
func renderTableRow(node gast.Node, header bool, source []byte) (*Node, error) {
|
||||
row := newElement("tr", nil)
|
||||
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
if child.Kind() != extast.KindTableCell {
|
||||
continue
|
||||
}
|
||||
cellAST := child.(*extast.TableCell)
|
||||
tag := "td"
|
||||
if header {
|
||||
tag = "th"
|
||||
}
|
||||
attrs := map[string]string(nil)
|
||||
switch cellAST.Alignment {
|
||||
case extast.AlignCenter:
|
||||
attrs = map[string]string{"align": "center"}
|
||||
case extast.AlignRight:
|
||||
attrs = map[string]string{"align": "right"}
|
||||
}
|
||||
cell := newElement(tag, attrs)
|
||||
content, err := renderInlineChildren(cellAST, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
for _, inline := range content {
|
||||
cell.addChild(inline)
|
||||
}
|
||||
row.addChild(cell)
|
||||
}
|
||||
return row, nil
|
||||
}
|
||||
|
||||
func renderDefinitionList(node gast.Node, source []byte) ([]*Node, error) {
|
||||
var out []*Node
|
||||
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
switch child.Kind() {
|
||||
case extast.KindDefinitionTerm:
|
||||
fragment, err := renderInlineFragment(child, source, false)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodes, err := parseXML(fragment)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
paragraph := newElement("p", nil)
|
||||
bold := newElement("b", nil)
|
||||
for _, node := range nodes {
|
||||
bold.addChild(node)
|
||||
}
|
||||
paragraph.addChild(bold)
|
||||
out = append(out, paragraph)
|
||||
case extast.KindDefinitionDescription:
|
||||
quote, err := renderContainer("blockquote", nil, child, source)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, quote...)
|
||||
}
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
func appendRawTextWithBreaks(parent *Node, content string) {
|
||||
if content == "" {
|
||||
return
|
||||
}
|
||||
start := 0
|
||||
for i := 0; i < len(content); i++ {
|
||||
if content[i] != '\n' && content[i] != '\r' {
|
||||
continue
|
||||
}
|
||||
if i > start {
|
||||
parent.addChild(newText(content[start:i]))
|
||||
}
|
||||
if content[i] == '\r' && i+1 < len(content) && content[i+1] == '\n' {
|
||||
i++
|
||||
}
|
||||
parent.addChild(newElement("br", nil))
|
||||
start = i + 1
|
||||
}
|
||||
if start < len(content) {
|
||||
parent.addChild(newText(content[start:]))
|
||||
}
|
||||
}
|
||||
|
||||
func stripMarkdownEscapesInNodes(nodes []*Node, inCode, inLatex bool) {
|
||||
for _, node := range nodes {
|
||||
if node == nil {
|
||||
continue
|
||||
}
|
||||
if node.typ == nodeText {
|
||||
switch {
|
||||
case inCode:
|
||||
case inLatex:
|
||||
node.text = stripLatexMarkdownEscapes(node.text)
|
||||
default:
|
||||
node.text = stripBackslashEscapes(node.text)
|
||||
}
|
||||
continue
|
||||
}
|
||||
stripMarkdownEscapesInNodes(node.children, inCode || node.tag == "code" || node.tag == "pre", inLatex || node.tag == "latex")
|
||||
}
|
||||
}
|
||||
|
||||
func stripBackslashEscapes(value string) string {
|
||||
if !strings.Contains(value, `\`) {
|
||||
return value
|
||||
}
|
||||
var out strings.Builder
|
||||
out.Grow(len(value))
|
||||
for i := 0; i < len(value); i++ {
|
||||
if value[i] == '\\' && i+1 < len(value) && isASCIIPunctuation(value[i+1]) {
|
||||
out.WriteByte(value[i+1])
|
||||
i++
|
||||
continue
|
||||
}
|
||||
out.WriteByte(value[i])
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func stripLatexMarkdownEscapes(value string) string {
|
||||
if !strings.Contains(value, `\`) {
|
||||
return value
|
||||
}
|
||||
var out strings.Builder
|
||||
out.Grow(len(value))
|
||||
for i := 0; i < len(value); i++ {
|
||||
if value[i] == '\\' && i+1 < len(value) && strings.ContainsRune("_^&*[]$~<>`#+-=:", rune(value[i+1])) {
|
||||
out.WriteByte(value[i+1])
|
||||
i++
|
||||
continue
|
||||
}
|
||||
out.WriteByte(value[i])
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func isASCIIPunctuation(ch byte) bool {
|
||||
return ch >= '!' && ch <= '/' || ch >= ':' && ch <= '@' || ch >= '[' && ch <= '`' || ch >= '{' && ch <= '~'
|
||||
}
|
||||
|
||||
func trimOneTrailingNewline(value string) string {
|
||||
if strings.HasSuffix(value, "\r\n") {
|
||||
return value[:len(value)-2]
|
||||
}
|
||||
return strings.TrimSuffix(value, "\n")
|
||||
}
|
||||
|
||||
func collectMarkdownChildText(node gast.Node, source []byte) string {
|
||||
var out strings.Builder
|
||||
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
switch child.Kind() {
|
||||
case gast.KindText:
|
||||
out.Write(child.(*gast.Text).Value(source))
|
||||
case gast.KindString:
|
||||
out.Write(child.(*gast.String).Value)
|
||||
default:
|
||||
out.WriteString(collectMarkdownChildText(child, source))
|
||||
}
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func extractMarkdownText(node gast.Node, source []byte) string {
|
||||
switch node.Kind() {
|
||||
case gast.KindText:
|
||||
return string(node.(*gast.Text).Value(source))
|
||||
case gast.KindString:
|
||||
return string(node.(*gast.String).Value)
|
||||
case gast.KindCodeSpan:
|
||||
return collectMarkdownChildText(node, source)
|
||||
}
|
||||
if node.Type() == gast.TypeBlock && node.Lines() != nil && node.Lines().Len() > 0 {
|
||||
return string(node.Lines().Value(source))
|
||||
}
|
||||
var out strings.Builder
|
||||
for child := node.FirstChild(); child != nil; child = child.NextSibling() {
|
||||
out.WriteString(extractMarkdownText(child, source))
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func headingTag(level int) string {
|
||||
if level < 1 || level > 6 {
|
||||
return "p"
|
||||
}
|
||||
return fmt.Sprintf("h%d", level)
|
||||
}
|
||||
|
||||
func normalizeListIndent(markdown string) string {
|
||||
lines := strings.Split(markdown, "\n")
|
||||
type stackEntry struct{ indent int }
|
||||
var stack []stackEntry
|
||||
inFence := false
|
||||
changed := false
|
||||
lastOriginal, lastNormalized := 0, 0
|
||||
for i, line := range lines {
|
||||
trimmed := strings.TrimLeft(line, " ")
|
||||
if strings.HasPrefix(trimmed, "```") || strings.HasPrefix(trimmed, "~~~") {
|
||||
inFence = !inFence
|
||||
continue
|
||||
}
|
||||
if inFence || trimmed == "" {
|
||||
continue
|
||||
}
|
||||
indent := len(line) - len(trimmed)
|
||||
if markdownListMarkerLength(trimmed) > 0 {
|
||||
for len(stack) > 0 && indent <= stack[len(stack)-1].indent {
|
||||
stack = stack[:len(stack)-1]
|
||||
}
|
||||
normalized := len(stack) * 4
|
||||
stack = append(stack, stackEntry{indent: indent})
|
||||
lastOriginal, lastNormalized = indent, normalized
|
||||
if indent != normalized {
|
||||
lines[i] = strings.Repeat(" ", normalized) + trimmed
|
||||
changed = true
|
||||
}
|
||||
} else if len(stack) > 0 && indent > lastOriginal {
|
||||
delta := lastNormalized - lastOriginal
|
||||
if delta != 0 {
|
||||
normalized := indent + delta
|
||||
if normalized < 0 {
|
||||
normalized = 0
|
||||
}
|
||||
lines[i] = strings.Repeat(" ", normalized) + trimmed
|
||||
changed = true
|
||||
}
|
||||
}
|
||||
}
|
||||
if !changed {
|
||||
return markdown
|
||||
}
|
||||
return strings.Join(lines, "\n")
|
||||
}
|
||||
|
||||
func markdownListMarkerLength(value string) int {
|
||||
if len(value) >= 2 && (value[0] == '-' || value[0] == '*' || value[0] == '+') && value[1] == ' ' {
|
||||
return 2
|
||||
}
|
||||
i := 0
|
||||
for i < len(value) && value[i] >= '0' && value[i] <= '9' {
|
||||
i++
|
||||
}
|
||||
if i > 0 && i+1 < len(value) && (value[i] == '.' || value[i] == ')') && value[i+1] == ' ' {
|
||||
return i + 2
|
||||
}
|
||||
return 0
|
||||
}
|
||||
284
shortcuts/doc/internal/docxparse/markdown_cjk.go
Normal file
284
shortcuts/doc/internal/docxparse/markdown_cjk.go
Normal file
@@ -0,0 +1,284 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"unicode"
|
||||
)
|
||||
|
||||
// preprocessCJKAdjacentMarkup disambiguates a narrow CommonMark pattern common in
|
||||
// Chinese prose: emphasis that ends in punctuation and is immediately followed
|
||||
// by a letter (for example **结论。**下一步). Goldmark correctly follows
|
||||
// CommonMark's delimiter rules, while LarkOpenCLI accepts this authoring form.
|
||||
// Rewriting simple CJK delimiter spans to equivalent DocxXML
|
||||
// before parsing removes the ambiguity while leaving nested Markdown, links,
|
||||
// code, fenced blocks, and source-bearing XML untouched.
|
||||
func preprocessCJKAdjacentMarkup(markdown string) string {
|
||||
if !strings.Contains(markdown, "**") && !strings.Contains(markdown, "~~") {
|
||||
return markdown
|
||||
}
|
||||
lines := strings.SplitAfter(markdown, "\n")
|
||||
var out strings.Builder
|
||||
fenceMarker := rune(0)
|
||||
fenceLength := 0
|
||||
rawSourceTag := ""
|
||||
for _, line := range lines {
|
||||
trimmed := strings.TrimLeft(line, " \t>")
|
||||
if marker, length, ok := markdownFence(trimmed); ok {
|
||||
if fenceMarker == 0 {
|
||||
fenceMarker, fenceLength = marker, length
|
||||
} else if marker == fenceMarker && length >= fenceLength && strings.TrimSpace(runeTail(trimmed, length)) == "" {
|
||||
fenceMarker, fenceLength = 0, 0
|
||||
}
|
||||
out.WriteString(line)
|
||||
continue
|
||||
}
|
||||
if fenceMarker != 0 || leadingIndent(line) >= 4 {
|
||||
out.WriteString(line)
|
||||
continue
|
||||
}
|
||||
out.WriteString(rewriteCJKMarkupLine(line, &rawSourceTag))
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func markdownFence(line string) (rune, int, bool) {
|
||||
runes := []rune(line)
|
||||
if len(runes) < 3 || runes[0] != '`' && runes[0] != '~' {
|
||||
return 0, 0, false
|
||||
}
|
||||
marker := runes[0]
|
||||
length := 0
|
||||
for length < len(runes) && runes[length] == marker {
|
||||
length++
|
||||
}
|
||||
return marker, length, length >= 3
|
||||
}
|
||||
|
||||
func runeTail(value string, start int) string {
|
||||
runes := []rune(value)
|
||||
if start >= len(runes) {
|
||||
return ""
|
||||
}
|
||||
return string(runes[start:])
|
||||
}
|
||||
|
||||
func leadingIndent(line string) int {
|
||||
count := 0
|
||||
for _, r := range line {
|
||||
switch r {
|
||||
case ' ':
|
||||
count++
|
||||
case '\t':
|
||||
count += 4
|
||||
default:
|
||||
return count
|
||||
}
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
type cjkMarkupRule struct {
|
||||
delimiter []rune
|
||||
openXML string
|
||||
closeXML string
|
||||
}
|
||||
|
||||
var cjkMarkupRules = []cjkMarkupRule{
|
||||
{delimiter: []rune("***"), openXML: "<em><b>", closeXML: "</b></em>"},
|
||||
{delimiter: []rune("~~"), openXML: "<del>", closeXML: "</del>"},
|
||||
{delimiter: []rune("**"), openXML: "<b>", closeXML: "</b>"},
|
||||
}
|
||||
|
||||
func rewriteCJKMarkupLine(line string, rawSourceTag *string) string {
|
||||
if *rawSourceTag != "" {
|
||||
runes := []rune(line)
|
||||
closeTag := []rune("</" + *rawSourceTag + ">")
|
||||
closeAt := indexRunesFold(runes, 0, closeTag)
|
||||
if closeAt < 0 {
|
||||
return line
|
||||
}
|
||||
closeEnd := closeAt + len(closeTag)
|
||||
prefix := string(runes[:closeEnd])
|
||||
*rawSourceTag = ""
|
||||
return prefix + rewriteCJKMarkupLine(string(runes[closeEnd:]), rawSourceTag)
|
||||
}
|
||||
|
||||
runes := []rune(line)
|
||||
var out strings.Builder
|
||||
for i := 0; i < len(runes); {
|
||||
if runes[i] == '`' && !runeEscaped(runes, i) {
|
||||
if end := codeSpanEnd(runes, i); end > i {
|
||||
out.WriteString(string(runes[i:end]))
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
}
|
||||
if runes[i] == '<' {
|
||||
if tag, end, selfClosing, ok := rawTagAt(runes, i); ok {
|
||||
out.WriteString(string(runes[i:end]))
|
||||
i = end
|
||||
if !selfClosing && (tag == "code" || tag == "pre" || tag == "whiteboard") {
|
||||
close := []rune("</" + tag + ">")
|
||||
if closeAt := indexRunesFold(runes, i, close); closeAt >= 0 {
|
||||
closeEnd := closeAt + len(close)
|
||||
out.WriteString(string(runes[i:closeEnd]))
|
||||
i = closeEnd
|
||||
} else {
|
||||
out.WriteString(string(runes[i:]))
|
||||
*rawSourceTag = tag
|
||||
return out.String()
|
||||
}
|
||||
}
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
rewritten := false
|
||||
for _, rule := range cjkMarkupRules {
|
||||
if !exactDelimiterAt(runes, i, rule.delimiter) || runeEscaped(runes, i) {
|
||||
continue
|
||||
}
|
||||
closeAt := delimiterCloser(runes, i+len(rule.delimiter), rule.delimiter)
|
||||
if closeAt < 0 {
|
||||
continue
|
||||
}
|
||||
content := runes[i+len(rule.delimiter) : closeAt]
|
||||
if !shouldRewriteCJKMarkup(content) {
|
||||
continue
|
||||
}
|
||||
out.WriteString(rule.openXML)
|
||||
out.WriteString(escapeXMLText(stripBackslashEscapes(string(content))))
|
||||
out.WriteString(rule.closeXML)
|
||||
i = closeAt + len(rule.delimiter)
|
||||
rewritten = true
|
||||
break
|
||||
}
|
||||
if rewritten {
|
||||
continue
|
||||
}
|
||||
out.WriteRune(runes[i])
|
||||
i++
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func rawTagAt(runes []rune, start int) (tag string, end int, selfClosing, ok bool) {
|
||||
if start+1 >= len(runes) || !isASCIILetterRune(runes[start+1]) {
|
||||
return "", 0, false, false
|
||||
}
|
||||
i := start + 1
|
||||
for i < len(runes) && (isASCIILetterRune(runes[i]) || isASCIIDigitRune(runes[i]) || runes[i] == '-' || runes[i] == '_') {
|
||||
i++
|
||||
}
|
||||
tag = strings.ToLower(string(runes[start+1 : i]))
|
||||
quote := rune(0)
|
||||
for ; i < len(runes); i++ {
|
||||
if runes[i] == '\'' || runes[i] == '"' {
|
||||
if quote == 0 {
|
||||
quote = runes[i]
|
||||
} else if quote == runes[i] {
|
||||
quote = 0
|
||||
}
|
||||
continue
|
||||
}
|
||||
if runes[i] == '>' && quote == 0 {
|
||||
trimmed := strings.TrimSpace(string(runes[start : i+1]))
|
||||
return tag, i + 1, strings.HasSuffix(trimmed, "/>"), true
|
||||
}
|
||||
}
|
||||
return "", 0, false, false
|
||||
}
|
||||
|
||||
func indexRunesFold(haystack []rune, start int, needle []rune) int {
|
||||
for i := start; i+len(needle) <= len(haystack); i++ {
|
||||
if strings.EqualFold(string(haystack[i:i+len(needle)]), string(needle)) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func codeSpanEnd(runes []rune, open int) int {
|
||||
length := 0
|
||||
for open+length < len(runes) && runes[open+length] == '`' {
|
||||
length++
|
||||
}
|
||||
for i := open + length; i < len(runes); i++ {
|
||||
if runes[i] != '`' || runeEscaped(runes, i) {
|
||||
continue
|
||||
}
|
||||
end := i
|
||||
for end < len(runes) && runes[end] == '`' {
|
||||
end++
|
||||
}
|
||||
if end-i == length {
|
||||
return end
|
||||
}
|
||||
i = end - 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func exactDelimiterAt(runes []rune, start int, delimiter []rune) bool {
|
||||
if start+len(delimiter) > len(runes) {
|
||||
return false
|
||||
}
|
||||
for i, want := range delimiter {
|
||||
if runes[start+i] != want {
|
||||
return false
|
||||
}
|
||||
}
|
||||
marker := delimiter[0]
|
||||
return (start == 0 || runes[start-1] != marker) && (start+len(delimiter) == len(runes) || runes[start+len(delimiter)] != marker)
|
||||
}
|
||||
|
||||
func delimiterCloser(runes []rune, start int, delimiter []rune) int {
|
||||
for i := start; i+len(delimiter) <= len(runes); i++ {
|
||||
if runes[i] == '\n' {
|
||||
return -1
|
||||
}
|
||||
if exactDelimiterAt(runes, i, delimiter) && !runeEscaped(runes, i) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func shouldRewriteCJKMarkup(content []rune) bool {
|
||||
if len(content) == 0 || unicode.IsSpace(content[0]) || unicode.IsSpace(content[len(content)-1]) {
|
||||
return false
|
||||
}
|
||||
for _, r := range content {
|
||||
if r == '`' || r == '[' || r == ']' || r == '<' || r == '>' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if !containsCJK(content) {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func containsCJK(value []rune) bool {
|
||||
for _, r := range value {
|
||||
if isCJKRune(r) || r > unicode.MaxASCII && (unicode.IsPunct(r) || unicode.IsSymbol(r)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isCJKRune(r rune) bool {
|
||||
return unicode.In(r, unicode.Han, unicode.Hiragana, unicode.Katakana, unicode.Hangul)
|
||||
}
|
||||
|
||||
func runeEscaped(runes []rune, index int) bool {
|
||||
count := 0
|
||||
for i := index - 1; i >= 0 && runes[i] == '\\'; i-- {
|
||||
count++
|
||||
}
|
||||
return count%2 == 1
|
||||
}
|
||||
334
shortcuts/doc/internal/docxparse/markdown_extensions.go
Normal file
334
shortcuts/doc/internal/docxparse/markdown_extensions.go
Normal file
@@ -0,0 +1,334 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
// This file contains the small Goldmark extensions needed to match the
|
||||
// LarkOpenCLI's Markdown surface: math, DocxXML tag names containing
|
||||
// underscores, and Markdown-aware callout/grid/column containers.
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/yuin/goldmark"
|
||||
gast "github.com/yuin/goldmark/ast"
|
||||
"github.com/yuin/goldmark/parser"
|
||||
"github.com/yuin/goldmark/text"
|
||||
gmutil "github.com/yuin/goldmark/util"
|
||||
)
|
||||
|
||||
// ---------- Math ----------
|
||||
|
||||
var kindMathInline = gast.NewNodeKind("DocxMathInline")
|
||||
var kindMathBlock = gast.NewNodeKind("DocxMathBlock")
|
||||
|
||||
type mathInline struct {
|
||||
gast.BaseInline
|
||||
content []byte
|
||||
}
|
||||
|
||||
func (n *mathInline) Kind() gast.NodeKind { return kindMathInline }
|
||||
func (n *mathInline) Dump(source []byte, level int) {
|
||||
gast.DumpHelper(n, source, level, nil, nil)
|
||||
}
|
||||
|
||||
type mathBlock struct {
|
||||
gast.BaseInline
|
||||
content []byte
|
||||
}
|
||||
|
||||
func (n *mathBlock) Kind() gast.NodeKind { return kindMathBlock }
|
||||
func (n *mathBlock) Dump(source []byte, level int) {
|
||||
gast.DumpHelper(n, source, level, nil, nil)
|
||||
}
|
||||
|
||||
var (
|
||||
mathBlockMultiLine = regexp.MustCompile(`(?s)^\$\$(.+?)\$\$`)
|
||||
mathInlineMultiLine = regexp.MustCompile(`(?s)^\$([^ \t$].*?)\$`)
|
||||
)
|
||||
|
||||
type mathInlineParser struct{}
|
||||
|
||||
func (p *mathInlineParser) Trigger() []byte { return []byte{'$'} }
|
||||
|
||||
func (p *mathInlineParser) Parse(_ gast.Node, reader text.Reader, _ parser.Context) gast.Node {
|
||||
line, _ := reader.PeekLine()
|
||||
if len(line) == 0 || line[0] != '$' {
|
||||
return nil
|
||||
}
|
||||
if len(line) >= 2 && line[1] == '$' {
|
||||
if content, advance := scanMathClose(line[2:], "$$"); advance >= 0 && len(content) > 0 {
|
||||
reader.Advance(2 + advance)
|
||||
return &mathBlock{content: append([]byte(nil), content...)}
|
||||
}
|
||||
match := reader.FindSubMatch(mathBlockMultiLine)
|
||||
if len(match) >= 2 && len(bytes.TrimSpace(match[1])) > 0 && !bytes.Contains(match[1], []byte("<latex")) {
|
||||
return &mathBlock{content: append([]byte(nil), bytes.TrimSpace(match[1])...)}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(line) < 2 || line[1] == ' ' || line[1] == '\t' || line[1] == '$' {
|
||||
return nil
|
||||
}
|
||||
if content, advance := scanMathClose(line[1:], "$"); advance >= 0 && len(content) > 0 {
|
||||
if content[len(content)-1] == ' ' || content[len(content)-1] == '\t' {
|
||||
return nil
|
||||
}
|
||||
reader.Advance(1 + advance)
|
||||
return &mathInline{content: append([]byte(nil), content...)}
|
||||
}
|
||||
match := reader.FindSubMatch(mathInlineMultiLine)
|
||||
if len(match) < 2 || bytes.Contains(match[1], []byte("<latex")) {
|
||||
return nil
|
||||
}
|
||||
trimmed := bytes.TrimRight(match[1], "\n\r")
|
||||
if len(trimmed) == 0 || trimmed[len(trimmed)-1] == ' ' || trimmed[len(trimmed)-1] == '\t' {
|
||||
return nil
|
||||
}
|
||||
return &mathInline{content: append([]byte(nil), trimmed...)}
|
||||
}
|
||||
|
||||
func scanMathClose(data []byte, delimiter string) ([]byte, int) {
|
||||
delim := []byte(delimiter)
|
||||
for offset := 0; offset < len(data); {
|
||||
if data[offset] == '\\' && offset+1 < len(data) && data[offset+1] == '$' {
|
||||
offset += 2
|
||||
continue
|
||||
}
|
||||
rel := bytes.Index(data[offset:], delim)
|
||||
if rel < 0 {
|
||||
return nil, -1
|
||||
}
|
||||
end := offset + rel
|
||||
if bytes.Contains(data[:end], []byte("<latex")) {
|
||||
return nil, -1
|
||||
}
|
||||
return data[:end], end + len(delim)
|
||||
}
|
||||
return nil, -1
|
||||
}
|
||||
|
||||
type mathExtension struct{}
|
||||
|
||||
func (e *mathExtension) Extend(markdown goldmark.Markdown) {
|
||||
markdown.Parser().AddOptions(parser.WithInlineParsers(
|
||||
gmutil.Prioritized(&mathInlineParser{}, 100),
|
||||
))
|
||||
}
|
||||
|
||||
// ---------- Underscore-bearing raw XML tags ----------
|
||||
|
||||
type underscoreHTMLExtension struct{}
|
||||
|
||||
func (e *underscoreHTMLExtension) Extend(markdown goldmark.Markdown) {
|
||||
markdown.Parser().AddOptions(
|
||||
parser.WithInlineParsers(gmutil.Prioritized(&underscoreRawHTMLParser{}, 99)),
|
||||
parser.WithBlockParsers(gmutil.Prioritized(&underscoreHTMLBlockParser{}, 99)),
|
||||
)
|
||||
}
|
||||
|
||||
var (
|
||||
extendedTagNamePattern = `([A-Za-z][A-Za-z0-9_-]*)`
|
||||
extendedAttributePattern = `(?:\s+[a-zA-Z_:][a-zA-Z0-9:._-]*(?:\s*=\s*(?:[^"'=<>` + "`" + `\x00-\x20]+|'[^']*'|"[^"]*"))?)`
|
||||
extendedOpenTag = regexp.MustCompile("^<" + extendedTagNamePattern + extendedAttributePattern + `*\s*/?>`)
|
||||
extendedCloseTag = regexp.MustCompile("^</" + extendedTagNamePattern + `\s*>`)
|
||||
peekExtendedOpenTag = regexp.MustCompile(`^<([A-Za-z][A-Za-z0-9_-]*)`)
|
||||
peekExtendedCloseTag = regexp.MustCompile(`^</([A-Za-z][A-Za-z0-9_-]*)`)
|
||||
extendedBlockTag = regexp.MustCompile(`^[ ]{0,3}<(/)?\s*([a-zA-Z0-9_\-]+)(` + extendedAttributePattern + `*)\s*(?:>|/>)\s*\n?$`)
|
||||
)
|
||||
|
||||
type underscoreRawHTMLParser struct{}
|
||||
|
||||
func (p *underscoreRawHTMLParser) Trigger() []byte { return []byte{'<'} }
|
||||
|
||||
func (p *underscoreRawHTMLParser) Parse(_ gast.Node, reader text.Reader, _ parser.Context) gast.Node {
|
||||
line, _ := reader.PeekLine()
|
||||
if len(line) > 1 && gmutil.IsAlphaNumeric(line[1]) {
|
||||
if match := peekExtendedOpenTag.FindSubmatch(line); match != nil && bytes.IndexByte(match[1], '_') >= 0 {
|
||||
return p.parseMultiLine(extendedOpenTag, reader)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if len(line) > 2 && line[1] == '/' && gmutil.IsAlphaNumeric(line[2]) {
|
||||
if match := peekExtendedCloseTag.FindSubmatch(line); match != nil && bytes.IndexByte(match[1], '_') >= 0 {
|
||||
return p.parseMultiLine(extendedCloseTag, reader)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (p *underscoreRawHTMLParser) parseMultiLine(re *regexp.Regexp, reader text.Reader) gast.Node {
|
||||
startLine, startSegment := reader.Position()
|
||||
if !reader.Match(re) {
|
||||
return nil
|
||||
}
|
||||
endLine, endSegment := reader.Position()
|
||||
reader.SetPosition(startLine, startSegment)
|
||||
node := gast.NewRawHTML()
|
||||
for {
|
||||
line, segment := reader.PeekLine()
|
||||
if line == nil {
|
||||
break
|
||||
}
|
||||
lineNo, _ := reader.Position()
|
||||
start := segment.Start
|
||||
if lineNo == startLine {
|
||||
start = startSegment.Start
|
||||
}
|
||||
end := segment.Stop
|
||||
if lineNo == endLine {
|
||||
end = endSegment.Start
|
||||
}
|
||||
node.Segments.Append(text.NewSegment(start, end))
|
||||
if lineNo == endLine {
|
||||
reader.Advance(end - start)
|
||||
break
|
||||
}
|
||||
reader.AdvanceLine()
|
||||
}
|
||||
return node
|
||||
}
|
||||
|
||||
type underscoreHTMLBlockParser struct{}
|
||||
|
||||
func (p *underscoreHTMLBlockParser) Trigger() []byte { return []byte{'<'} }
|
||||
|
||||
func (p *underscoreHTMLBlockParser) Open(_ gast.Node, reader text.Reader, pc parser.Context) (gast.Node, parser.State) {
|
||||
line, segment := reader.PeekLine()
|
||||
pos := pc.BlockOffset()
|
||||
if pos < 0 || pos >= len(line) || line[pos] != '<' {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
match := extendedBlockTag.FindSubmatchIndex(line)
|
||||
if match == nil {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
tag := string(line[match[4]:match[5]])
|
||||
if !strings.Contains(tag, "_") {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
isClose := match[2] > -1 && bytes.Equal(line[match[2]:match[3]], []byte("/"))
|
||||
hasAttrs := match[6] != match[7]
|
||||
if isClose && hasAttrs {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
node := gast.NewHTMLBlock(gast.HTMLBlockType7)
|
||||
node.Lines().Append(segment)
|
||||
reader.Advance(segment.Len() - 1)
|
||||
return node, parser.NoChildren
|
||||
}
|
||||
|
||||
func (p *underscoreHTMLBlockParser) Continue(node gast.Node, reader text.Reader, _ parser.Context) parser.State {
|
||||
line, segment := reader.PeekLine()
|
||||
if gmutil.IsBlank(line) {
|
||||
return parser.Close
|
||||
}
|
||||
node.Lines().Append(segment)
|
||||
reader.Advance(segment.Len() - 1)
|
||||
return parser.Continue | parser.NoChildren
|
||||
}
|
||||
|
||||
func (p *underscoreHTMLBlockParser) Close(gast.Node, text.Reader, parser.Context) {}
|
||||
func (p *underscoreHTMLBlockParser) CanInterruptParagraph() bool { return false }
|
||||
func (p *underscoreHTMLBlockParser) CanAcceptIndentedLine() bool { return false }
|
||||
|
||||
// ---------- Markdown-aware DocxXML containers ----------
|
||||
|
||||
type containerSpec struct {
|
||||
tag string
|
||||
}
|
||||
|
||||
var containerSpecs = map[string]*containerSpec{
|
||||
"callout": {tag: "callout"},
|
||||
"grid": {tag: "grid"},
|
||||
"column": {tag: "column"},
|
||||
"div": {tag: "div"},
|
||||
}
|
||||
|
||||
var kindContainerBlock = gast.NewNodeKind("DocxContainerBlock")
|
||||
|
||||
type containerBlock struct {
|
||||
gast.BaseBlock
|
||||
spec *containerSpec
|
||||
attrs map[string]string
|
||||
}
|
||||
|
||||
func (n *containerBlock) Kind() gast.NodeKind { return kindContainerBlock }
|
||||
func (n *containerBlock) Dump(source []byte, level int) {
|
||||
gast.DumpHelper(n, source, level, nil, nil)
|
||||
}
|
||||
|
||||
type containerBlockParser struct{}
|
||||
|
||||
func (p *containerBlockParser) Trigger() []byte { return []byte{'<'} }
|
||||
|
||||
var containerOpenTag = regexp.MustCompile(`^<([A-Za-z][A-Za-z0-9_-]*)`)
|
||||
|
||||
func (p *containerBlockParser) Open(_ gast.Node, reader text.Reader, _ parser.Context) (gast.Node, parser.State) {
|
||||
line, _ := reader.PeekLine()
|
||||
trimmed := bytes.TrimLeft(line, " \t")
|
||||
leading := len(line) - len(trimmed)
|
||||
if len(trimmed) < 2 || trimmed[0] != '<' {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
match := containerOpenTag.FindSubmatch(trimmed)
|
||||
if match == nil {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
spec := containerSpecs[strings.ToLower(string(match[1]))]
|
||||
if spec == nil {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
openEnd := bytes.IndexByte(trimmed, '>')
|
||||
if openEnd < 0 || openEnd >= 1 && trimmed[openEnd-1] == '/' {
|
||||
return nil, parser.NoChildren
|
||||
}
|
||||
tagEnd := len(match[0])
|
||||
node := &containerBlock{spec: spec, attrs: parseAttributes(string(trimmed[tagEnd:openEnd]))}
|
||||
reader.Advance(leading + openEnd + 1)
|
||||
return node, parser.HasChildren
|
||||
}
|
||||
|
||||
func (p *containerBlockParser) Continue(node gast.Node, reader text.Reader, _ parser.Context) parser.State {
|
||||
container := node.(*containerBlock)
|
||||
line, segment := reader.PeekLine()
|
||||
trimmed := bytes.TrimLeft(line, " \t")
|
||||
if hasCloseTagPrefix(trimmed, container.spec.tag) {
|
||||
reader.Advance(len(line) - len(trimmed) + closeTagLength(container.spec.tag))
|
||||
return parser.Close
|
||||
}
|
||||
if isXMLTagLine(trimmed) {
|
||||
indent := len(line) - len(trimmed)
|
||||
if indent > 0 && segment.Start+indent <= segment.Stop {
|
||||
reader.AdvanceAndSetPadding(indent, 0)
|
||||
}
|
||||
}
|
||||
return parser.Continue | parser.HasChildren
|
||||
}
|
||||
|
||||
func (p *containerBlockParser) Close(gast.Node, text.Reader, parser.Context) {}
|
||||
func (p *containerBlockParser) CanInterruptParagraph() bool { return true }
|
||||
func (p *containerBlockParser) CanAcceptIndentedLine() bool { return true }
|
||||
|
||||
func closeTagLength(tag string) int { return len(tag) + len("</>") }
|
||||
|
||||
func hasCloseTagPrefix(line []byte, tag string) bool {
|
||||
want := []byte("</" + tag + ">")
|
||||
return len(line) >= len(want) && bytes.EqualFold(line[:len(want)], want)
|
||||
}
|
||||
|
||||
func isXMLTagLine(line []byte) bool {
|
||||
if len(line) < 2 || line[0] != '<' {
|
||||
return false
|
||||
}
|
||||
if line[1] == '/' {
|
||||
return len(line) >= 3 && isASCIILetter(line[2])
|
||||
}
|
||||
return isASCIILetter(line[1])
|
||||
}
|
||||
|
||||
func isASCIILetter(ch byte) bool {
|
||||
return ch >= 'a' && ch <= 'z' || ch >= 'A' && ch <= 'Z'
|
||||
}
|
||||
172
shortcuts/doc/internal/docxparse/model.go
Normal file
172
shortcuts/doc/internal/docxparse/model.go
Normal file
@@ -0,0 +1,172 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// Package docxparse parses LarkOpenCLI DocxXML and Markdown into a small,
|
||||
// offline DOM for the docs +script shortcut.
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Format is an accepted source document format.
|
||||
type Format string
|
||||
|
||||
const (
|
||||
FormatXML Format = "xml"
|
||||
FormatMarkdown Format = "markdown"
|
||||
)
|
||||
|
||||
// ParseResult is the complete result returned by Parse.
|
||||
type ParseResult struct {
|
||||
Format Format `json:"format"`
|
||||
XML string `json:"xml"`
|
||||
Profile Profile `json:"profile"`
|
||||
}
|
||||
|
||||
type nodeType uint8
|
||||
|
||||
const (
|
||||
nodeText nodeType = iota
|
||||
nodeElement
|
||||
)
|
||||
|
||||
// Node is the internal DocxXML DOM representation.
|
||||
type Node struct {
|
||||
typ nodeType
|
||||
tag string
|
||||
attrs map[string]string
|
||||
children []*Node
|
||||
text string
|
||||
parent *Node
|
||||
}
|
||||
|
||||
func newText(text string) *Node {
|
||||
return &Node{typ: nodeText, text: text}
|
||||
}
|
||||
|
||||
func newElement(tag string, attrs map[string]string) *Node {
|
||||
return &Node{typ: nodeElement, tag: tag, attrs: attrs}
|
||||
}
|
||||
|
||||
func (n *Node) addChild(child *Node) {
|
||||
if n == nil || child == nil {
|
||||
return
|
||||
}
|
||||
child.parent = n
|
||||
n.children = append(n.children, child)
|
||||
}
|
||||
|
||||
func (n *Node) writeXML(out *strings.Builder) {
|
||||
if n == nil {
|
||||
return
|
||||
}
|
||||
if n.typ == nodeText {
|
||||
out.WriteString(escapeXMLText(n.text))
|
||||
return
|
||||
}
|
||||
|
||||
out.WriteByte('<')
|
||||
out.WriteString(n.tag)
|
||||
keys := make([]string, 0, len(n.attrs))
|
||||
for key := range n.attrs {
|
||||
keys = append(keys, key)
|
||||
}
|
||||
sort.Slice(keys, func(i, j int) bool {
|
||||
wi, iWeighted := attributeWeight[keys[i]]
|
||||
wj, jWeighted := attributeWeight[keys[j]]
|
||||
switch {
|
||||
case iWeighted && jWeighted && wi != wj:
|
||||
return wi < wj
|
||||
case iWeighted != jWeighted:
|
||||
return iWeighted
|
||||
default:
|
||||
return keys[i] < keys[j]
|
||||
}
|
||||
})
|
||||
for _, key := range keys {
|
||||
out.WriteByte(' ')
|
||||
out.WriteString(key)
|
||||
out.WriteString(`="`)
|
||||
out.WriteString(escapeXMLAttr(n.attrs[key]))
|
||||
out.WriteByte('"')
|
||||
}
|
||||
|
||||
if isVoidTag(n.tag) {
|
||||
out.WriteString("/>")
|
||||
return
|
||||
}
|
||||
out.WriteByte('>')
|
||||
for _, child := range n.children {
|
||||
child.writeXML(out)
|
||||
}
|
||||
out.WriteString("</")
|
||||
out.WriteString(n.tag)
|
||||
out.WriteByte('>')
|
||||
}
|
||||
|
||||
func renderNodes(nodes []*Node) string {
|
||||
var out strings.Builder
|
||||
for _, node := range nodes {
|
||||
node.writeXML(&out)
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
var attributeWeight = map[string]int{
|
||||
"id": 0,
|
||||
"name": 1,
|
||||
"top-block-id": 2,
|
||||
"parent-block-path": 3,
|
||||
"mode": 4,
|
||||
"start-block-id": 5,
|
||||
"end-block-id": 6,
|
||||
"hit-block-ids": 7,
|
||||
}
|
||||
|
||||
func escapeXMLText(value string) string {
|
||||
if !strings.ContainsAny(value, "&<>") {
|
||||
return value
|
||||
}
|
||||
var out strings.Builder
|
||||
out.Grow(len(value) + 8)
|
||||
for _, r := range value {
|
||||
switch r {
|
||||
case '&':
|
||||
out.WriteString("&")
|
||||
case '<':
|
||||
out.WriteString("<")
|
||||
case '>':
|
||||
out.WriteString(">")
|
||||
default:
|
||||
out.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func escapeXMLAttr(value string) string {
|
||||
if !strings.ContainsAny(value, "&<>\"'") {
|
||||
return value
|
||||
}
|
||||
var out strings.Builder
|
||||
out.Grow(len(value) + 8)
|
||||
for _, r := range value {
|
||||
switch r {
|
||||
case '&':
|
||||
out.WriteString("&")
|
||||
case '<':
|
||||
out.WriteString("<")
|
||||
case '>':
|
||||
out.WriteString(">")
|
||||
case '"':
|
||||
out.WriteString(""")
|
||||
case '\'':
|
||||
out.WriteString("'")
|
||||
default:
|
||||
out.WriteRune(r)
|
||||
}
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
488
shortcuts/doc/internal/docxparse/parse_test.go
Normal file
488
shortcuts/doc/internal/docxparse/parse_test.go
Normal file
@@ -0,0 +1,488 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseXMLBuildsBlockDistribution(t *testing.T) {
|
||||
result, err := Parse(`<title>T</title><p>P</p><ul><li>A</li><li>B</li></ul>`, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != `<title>T</title><p>P</p><ul><li>A</li><li>B</li></ul>` {
|
||||
t.Fatalf("XML = %q", result.XML)
|
||||
}
|
||||
if result.Profile.BlockCount != 5 {
|
||||
t.Fatalf("block total = %d, want 5", result.Profile.BlockCount)
|
||||
}
|
||||
shares := map[string]BlockShare{}
|
||||
for _, share := range result.Profile.Blocks {
|
||||
shares[share.Type] = share
|
||||
}
|
||||
if got := shares["li"]; got.Count != 2 || got.Ratio != 0.4 {
|
||||
t.Fatalf("li share = %+v, want count=2 ratio=0.4", got)
|
||||
}
|
||||
for _, typ := range []string{"title", "p", "ul"} {
|
||||
if got := shares[typ]; got.Count != 1 || got.Ratio != 0.2 {
|
||||
t.Errorf("%s share = %+v, want count=1 ratio=0.2", typ, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLRejectsInvalidInput(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
source string
|
||||
}{
|
||||
{name: "unsupported tag", source: `<unknown>x</unknown>`},
|
||||
{name: "missing closing tag", source: `<p>one`},
|
||||
{name: "invalid nesting", source: `<span>x<table><tr><td>y</td></tr></table></span>`},
|
||||
{name: "malformed block id", source: `<block_id="8,9"/>`},
|
||||
{name: "unterminated cdata", source: `<code><![CDATA[a < b</code>`},
|
||||
{name: "tag spacing", source: `< p>text< / p>`},
|
||||
{name: "self closing slash spacing", source: `<p/ >`},
|
||||
{name: "unquoted attribute", source: `<p align=center>text</p>`},
|
||||
{name: "invalid entity", source: `<p>one &unknown;</p>`},
|
||||
{name: "invalid attribute entity", source: `<img href="https://example.com/&unknown;"/>`},
|
||||
{name: "missing required ancestor", source: `<td>cell</td>`},
|
||||
{name: "missing required attribute", source: `<img/>`},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if _, err := Parse(tt.source, FormatXML); err == nil {
|
||||
t.Fatalf("Parse(%q) succeeded, want validation error", tt.source)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAutoDetectsXMLAndMarkdown(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
source string
|
||||
blocks int
|
||||
}{
|
||||
{name: "xml", source: `<title>T</title><p>P</p>`, blocks: 2},
|
||||
{name: "markdown", source: "# T\n\nP", blocks: 2},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
profile, err := ParseAuto(tt.source)
|
||||
if err != nil {
|
||||
t.Fatalf("ParseAuto() error = %v", err)
|
||||
}
|
||||
if profile.BlockCount != tt.blocks {
|
||||
t.Fatalf("profile = %+v, want %d blocks", profile, tt.blocks)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAutoDoesNotTreatMalformedXMLAsMarkdown(t *testing.T) {
|
||||
if _, err := ParseAuto(`<p>text`); err == nil {
|
||||
t.Fatal("ParseAuto() succeeded, want malformed XML error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLAcceptsPublicTagAliasesWithoutChangingInput(t *testing.T) {
|
||||
source := `<P>one<strong>two</strong><br></P><image href="https://example.com/image.png">`
|
||||
result, err := Parse(source, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != source {
|
||||
t.Fatalf("XML = %q, want original %q", result.XML, source)
|
||||
}
|
||||
if result.Profile.BlockCount != 2 {
|
||||
t.Fatalf("profile = %+v, want p and img blocks", result.Profile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLAcceptsPublicAttributeAliasesWithoutChangingInput(t *testing.T) {
|
||||
source := `<callout color="blue" icon="💡"><p>x</p></callout><at id="ou_legacy"></at><img url="https://example.com/image.png"/>`
|
||||
result, err := Parse(source, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != source {
|
||||
t.Fatalf("XML = %q, want original %q", result.XML, source)
|
||||
}
|
||||
if result.Profile.BlockCount != 3 {
|
||||
t.Fatalf("profile = %+v, want callout, p, and img blocks", result.Profile)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLAcceptsBareAmpersandsInAttributes(t *testing.T) {
|
||||
source := `<block_insert><parameter><block_id>-1</block_id><content><img href="https://picsum.photos/320/200?seed=lark-cli&raw=1"/></content></parameter></block_insert>`
|
||||
result, err := Parse(source, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != source {
|
||||
t.Fatalf("XML = %q, want original %q", result.XML, source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeXMLAttributeAmpersandsPreservesEntityReferences(t *testing.T) {
|
||||
source := `https://example.com?a=1&b=2&c=3&d=4&e=5&unknown;`
|
||||
want := `https://example.com?a=1&b=2&c=3&d=4&e=5&unknown;`
|
||||
if got := normalizeXMLAttributeAmpersands(source); got != want {
|
||||
t.Fatalf("normalizeXMLAttributeAmpersands() = %q, want %q", got, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLPreservesValidCDATA(t *testing.T) {
|
||||
source := `<code><![CDATA[a < b && c > d]]></code>`
|
||||
result, err := Parse(source, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != source {
|
||||
t.Fatalf("XML = %q, want original %q", result.XML, source)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLPreservesUTF8BOM(t *testing.T) {
|
||||
source := "\uFEFF<p>text</p>"
|
||||
result, err := Parse(source, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != source {
|
||||
t.Fatalf("XML = %q, want original input", result.XML)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMarkdownConvertsLarkOpenCLIBlocks(t *testing.T) {
|
||||
source := "# 标题\n\nHello **world**.\n\n- [x] Done\n- [ ] Todo\n\n" +
|
||||
"| A | B |\n| --- | --- |\n| 1 | 2 |\n\n" +
|
||||
"```go\nfmt.Println(\"x\")\n```\n\n$E=mc^2$\n"
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
for _, fragment := range []string{
|
||||
`<h1>标题</h1>`,
|
||||
`<p>Hello <b>world</b>.</p>`,
|
||||
`<checkbox done="true">Done</checkbox>`,
|
||||
`<checkbox done="false">Todo</checkbox>`,
|
||||
`<table><thead><tr><th>A</th><th>B</th></tr></thead><tbody><tr><td>1</td><td>2</td></tr></tbody></table>`,
|
||||
`<pre lang="go"><code>fmt.Println("x")</code></pre>`,
|
||||
`<p><latex>E=mc^2</latex></p>`,
|
||||
} {
|
||||
if !strings.Contains(result.XML, fragment) {
|
||||
t.Errorf("XML missing %q:\n%s", fragment, result.XML)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMarkdownPreservesLineBreakSemantics(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
source string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "soft breaks become spaces",
|
||||
source: "**文号:桂汛旱指〔2026〕17号**\n**签发人:XXX**\n**发布日期:2026年7月13日**",
|
||||
want: `<p><b>文号:桂汛旱指〔2026〕17号</b> <b>签发人:XXX</b> <b>发布日期:2026年7月13日</b></p>`,
|
||||
},
|
||||
{
|
||||
name: "hard breaks remain line breaks",
|
||||
source: "**文号:A** \n**签发人:B**",
|
||||
want: `<p><b>文号:A</b><br/><b>签发人:B</b></p>`,
|
||||
},
|
||||
{
|
||||
name: "blank lines remain paragraph breaks",
|
||||
source: "**文号:A**\n\n**签发人:B**",
|
||||
want: `<p><b>文号:A</b></p><p><b>签发人:B</b></p>`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := Parse(tt.source, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != tt.want {
|
||||
t.Fatalf("XML = %q, want %q", result.XML, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMarkdownContainerKeepsMarkdownChildren(t *testing.T) {
|
||||
source := "<callout emoji=\"💡\">\n\n## Note\n\n- item\n\n</callout>\n"
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
want := `<callout emoji="💡"><h2>Note</h2><ul><li>item</li></ul></callout>`
|
||||
if result.XML != want {
|
||||
t.Fatalf("XML = %q, want %q", result.XML, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseMarkdownMatchesLarkOpenCLIFixtures(t *testing.T) {
|
||||
t.Run("deep nested list", func(t *testing.T) {
|
||||
result, err := Parse("1. 第一层\n - 第二层\n - 第三层\n - 第四层\n", FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if strings.Contains(result.XML, "<pre>") || strings.Contains(result.XML, "<code>") || !strings.Contains(result.XML, "第四层") {
|
||||
t.Fatalf("nested list converted incorrectly: %s", result.XML)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("fenced mermaid", func(t *testing.T) {
|
||||
result, err := Parse("```mermaid\nflowchart LR\nA-->B\n```", FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
want := `<whiteboard type="mermaid">flowchart LR<br/>A-->B</whiteboard>`
|
||||
if result.XML != want {
|
||||
t.Fatalf("XML = %q, want %q", result.XML, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("raw whiteboard source", func(t *testing.T) {
|
||||
source := "<whiteboard type=\"mermaid\">\nflowchart LR\n A --> B\n</whiteboard>"
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
want := `<whiteboard type="mermaid">flowchart LR<br/> A --> B</whiteboard>`
|
||||
if result.XML != want {
|
||||
t.Fatalf("XML = %q, want %q", result.XML, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("raw code stays literal", func(t *testing.T) {
|
||||
source := "<code lang=\"go\">\nif a < b && c > d {\n fmt.Println(\"**raw**\")\n}\n</code>"
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
want := `<code lang="go">if a < b && c > d {<br/> fmt.Println("**raw**")<br/>}</code>`
|
||||
if result.XML != want {
|
||||
t.Fatalf("XML = %q, want %q", result.XML, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("underscore tags", func(t *testing.T) {
|
||||
result, err := Parse(`text <synced_reference src-block-id="abc" src-token="def"/> more`, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if !strings.Contains(result.XML, `<synced_reference`) || strings.Contains(result.XML, `<synced_reference`) {
|
||||
t.Fatalf("underscore tag was not preserved: %s", result.XML)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("canonical user cite", func(t *testing.T) {
|
||||
result, err := Parse(`hello <cite type="user" user-id="ou_user"></cite>`, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
for _, want := range []string{`<cite`, `type="user"`, `user-id="ou_user"`} {
|
||||
if !strings.Contains(result.XML, want) {
|
||||
t.Errorf("XML missing %q: %s", want, result.XML)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("public tag alias converts to canonical XML", func(t *testing.T) {
|
||||
result, err := Parse(`hello <strong>world</strong>`, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != `<p>hello <b>world</b></p>` {
|
||||
t.Fatalf("XML = %q", result.XML)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("public cite alias converts attributes", func(t *testing.T) {
|
||||
result, err := Parse(`hello <at id="ou_legacy"></at>`, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != `<p>hello <cite type="user" user-id="ou_legacy"></cite></p>` {
|
||||
t.Fatalf("XML = %q", result.XML)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("markdown backslash escapes", func(t *testing.T) {
|
||||
result, err := Parse(`"source\_token": \[abc\] path\\to`, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
for _, want := range []string{`source_token`, `[abc]`, `path\to`} {
|
||||
if !strings.Contains(result.XML, want) {
|
||||
t.Errorf("XML missing %q: %s", want, result.XML)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("adjacent CJK emphasis", func(t *testing.T) {
|
||||
source := `***你好。***S 和 ~~再见。~~T。**agent team 做 brownfield 项目,带来的感知会强烈得多**——前提。**这个时刻,才是真正属于 agent team 的"闪光时刻"。**翟霖`
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
for _, want := range []string{
|
||||
`<em><b>你好。</b></em>S`,
|
||||
`<del>再见。</del>T`,
|
||||
`<b>agent team 做 brownfield 项目,带来的感知会强烈得多</b>`,
|
||||
`<b>这个时刻,才是真正属于 agent team 的"闪光时刻"。</b>翟霖`,
|
||||
} {
|
||||
if !strings.Contains(result.XML, want) {
|
||||
t.Errorf("XML missing %q: %s", want, result.XML)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("div parses markdown children", func(t *testing.T) {
|
||||
result, err := Parse("<div>\n\n**bold**\n\n</div>", FormatMarkdown)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
if result.XML != `<div><p><b>bold</b></p></div>` {
|
||||
t.Fatalf("XML = %q", result.XML)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestPreprocessCJKAdjacentMarkupUsesRuneOffsetsAfterRawBlock(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
lineEnding string
|
||||
final string
|
||||
}{
|
||||
{name: "EOF", lineEnding: "\n"},
|
||||
{name: "LF", lineEnding: "\n", final: "\n"},
|
||||
{name: "CRLF", lineEnding: "\r\n", final: "\r\n"},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
source := "<code>**raw**" + tt.lineEnding + "Ⱥ</code>**你好。**S" + tt.final
|
||||
want := "<code>**raw**" + tt.lineEnding + "Ⱥ</code><b>你好。</b>S" + tt.final
|
||||
if got := preprocessCJKAdjacentMarkup(source); got != want {
|
||||
t.Fatalf("preprocessCJKAdjacentMarkup() = %q, want %q", got, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextProfileMatchesLarkOpenCLIContract(t *testing.T) {
|
||||
result, err := Parse(`<title>标题</title><p>一个苹果是 an apple。</p>`, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
profile := result.Profile
|
||||
if profile.WordCount != 10 || profile.CharCount != 15 {
|
||||
t.Fatalf("profile = %+v, want word_count=10 char_count=15", profile)
|
||||
}
|
||||
if profile.Breakdown.HanChars != 7 || profile.Breakdown.EnglishWords != 2 || profile.Breakdown.ChinesePunctuations != 1 {
|
||||
t.Fatalf("breakdown = %+v", profile.Breakdown)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextProfileMatchesAuthoringCounterCases(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
source string
|
||||
words int
|
||||
chars int
|
||||
blocks int
|
||||
english int
|
||||
numbers int
|
||||
han int
|
||||
listItems int
|
||||
}{
|
||||
{
|
||||
name: "english number and punctuation",
|
||||
source: `<p>Hello world 123.45。</p>`,
|
||||
words: 4, chars: 17, blocks: 1, english: 2, numbers: 1,
|
||||
},
|
||||
{
|
||||
name: "list and checkbox markers",
|
||||
source: `<ul><li>甲</li><li>two</li></ul><checkbox done="true">完成</checkbox>`,
|
||||
words: 7, chars: 9, blocks: 4, english: 1, han: 3, listItems: 2,
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result, err := Parse(tt.source, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
profile := result.Profile
|
||||
if profile.WordCount != tt.words || profile.CharCount != tt.chars || profile.BlockCount != tt.blocks {
|
||||
t.Fatalf("profile = %+v, want words=%d chars=%d blocks=%d", profile, tt.words, tt.chars, tt.blocks)
|
||||
}
|
||||
if profile.Breakdown.EnglishWords != tt.english || profile.Breakdown.NumberWords != tt.numbers || profile.Breakdown.HanChars != tt.han {
|
||||
t.Fatalf("breakdown = %+v", profile.Breakdown)
|
||||
}
|
||||
if got := blockCountForTest(profile.Blocks, "li"); got != tt.listItems {
|
||||
t.Fatalf("li count = %d, want %d", got, tt.listItems)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTextProfileUsesVisibleAttributeFallbacks(t *testing.T) {
|
||||
result, err := Parse(`<p text="Hello"/><p><span title="world"/></p><img href="https://example.com/image.png" caption="图"/>`, FormatXML)
|
||||
if err != nil {
|
||||
t.Fatalf("Parse() error = %v", err)
|
||||
}
|
||||
profile := result.Profile
|
||||
if profile.WordCount != 3 || profile.CharCount != 11 {
|
||||
t.Fatalf("profile = %+v, want word_count=3 char_count=11", profile)
|
||||
}
|
||||
if profile.Breakdown.EnglishWords != 2 || profile.Breakdown.HanChars != 1 {
|
||||
t.Fatalf("breakdown = %+v", profile.Breakdown)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsUnsafeXMLDeclarations(t *testing.T) {
|
||||
_, err := Parse(`<!DOCTYPE foo [<!ENTITY x "value">]><p>&x;</p>`, FormatXML)
|
||||
if err == nil || !strings.Contains(err.Error(), "DOCTYPE or ENTITY") {
|
||||
t.Fatalf("Parse() error = %v, want unsafe declaration rejection", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsInvalidUTF8(t *testing.T) {
|
||||
_, err := Parse(string([]byte{'<', 'p', '>', 0xff, '<', '/', 'p', '>'}), FormatXML)
|
||||
if err == nil || !strings.Contains(err.Error(), "valid UTF-8") {
|
||||
t.Fatalf("Parse() error = %v, want UTF-8 rejection", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsExcessiveNesting(t *testing.T) {
|
||||
source := strings.Repeat("<span>", MaxNestingDepth+1)
|
||||
_, err := Parse(source, FormatXML)
|
||||
if err == nil || !strings.Contains(err.Error(), "nesting exceeds") {
|
||||
t.Fatalf("Parse() error = %v, want nesting limit rejection", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseXMLRejectsNestedInvalidTagStarts(t *testing.T) {
|
||||
if _, err := Parse(`<<<<p>text</p>`, FormatXML); err == nil {
|
||||
t.Fatal("Parse() succeeded, want invalid XML token error")
|
||||
}
|
||||
}
|
||||
|
||||
func blockCountForTest(blocks []BlockShare, typ string) int {
|
||||
for _, block := range blocks {
|
||||
if block.Type == typ {
|
||||
return block.Count
|
||||
}
|
||||
}
|
||||
return 0
|
||||
}
|
||||
397
shortcuts/doc/internal/docxparse/profile.go
Normal file
397
shortcuts/doc/internal/docxparse/profile.go
Normal file
@@ -0,0 +1,397 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"math"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Profile describes LarkOpenCLI document structure and visible text without
|
||||
// requiring callers to inspect the full XML.
|
||||
type Profile struct {
|
||||
WordCount int `json:"word_count"`
|
||||
CharCount int `json:"char_count"`
|
||||
Breakdown TextBreakdown `json:"breakdown"`
|
||||
BlockCount int `json:"block_count"`
|
||||
Blocks []BlockShare `json:"blocks"`
|
||||
}
|
||||
|
||||
// BlockShare reports one LarkOpenCLI block type's count and share. Structural
|
||||
// and inline-only tags are intentionally excluded.
|
||||
type BlockShare struct {
|
||||
Type string `json:"type"`
|
||||
Count int `json:"count"`
|
||||
Ratio float64 `json:"ratio"`
|
||||
}
|
||||
|
||||
// TextProfile is the internal result of the LarkOpenCLI semantic counter.
|
||||
type TextProfile struct {
|
||||
WordCount int `json:"word_count"`
|
||||
CharCount int `json:"char_count"`
|
||||
Breakdown TextBreakdown `json:"breakdown"`
|
||||
}
|
||||
|
||||
type TextBreakdown struct {
|
||||
HanChars int `json:"han_chars"`
|
||||
EnglishWords int `json:"english_words"`
|
||||
NumberWords int `json:"number_words"`
|
||||
ChinesePunctuations int `json:"chinese_punctuations"`
|
||||
EnglishLetters int `json:"english_letters"`
|
||||
Digits int `json:"digits"`
|
||||
EnglishPunctuations int `json:"english_punctuations"`
|
||||
SymbolWords int `json:"symbol_words"`
|
||||
SymbolChars int `json:"symbol_chars"`
|
||||
}
|
||||
|
||||
// Parse validates XML or converts Markdown to DocxXML, then builds its
|
||||
// structure and visible-text profile.
|
||||
func Parse(source string, format Format) (ParseResult, error) {
|
||||
var (
|
||||
nodes []*Node
|
||||
outputXML string
|
||||
err error
|
||||
)
|
||||
switch format {
|
||||
case FormatXML:
|
||||
nodes, err = parseXML(source)
|
||||
outputXML = source
|
||||
case FormatMarkdown:
|
||||
nodes, err = parseMarkdown(source)
|
||||
default:
|
||||
return ParseResult{}, fmt.Errorf("unsupported input format %q", format)
|
||||
}
|
||||
if err != nil {
|
||||
return ParseResult{}, err
|
||||
}
|
||||
if err := validateStructure(nodes); err != nil {
|
||||
return ParseResult{}, err
|
||||
}
|
||||
if format == FormatMarkdown {
|
||||
outputXML = renderNodes(nodes)
|
||||
}
|
||||
|
||||
return ParseResult{
|
||||
Format: format,
|
||||
XML: outputXML,
|
||||
Profile: buildProfile(nodes),
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ParseAuto detects XML versus Markdown from the content and returns only the
|
||||
// document profile. XML-like input is parsed strictly; all other input is
|
||||
// interpreted as Markdown.
|
||||
func ParseAuto(source string) (Profile, error) {
|
||||
result, err := Parse(source, detectFormat(source))
|
||||
if err != nil {
|
||||
return Profile{}, err
|
||||
}
|
||||
return result.Profile, nil
|
||||
}
|
||||
|
||||
// MarkdownToXML converts Markdown to canonical LarkOpenCLI XML.
|
||||
func MarkdownToXML(source string) (string, error) {
|
||||
result, err := Parse(source, FormatMarkdown)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return result.XML, nil
|
||||
}
|
||||
|
||||
func detectFormat(source string) Format {
|
||||
trimmed := strings.TrimSpace(strings.TrimPrefix(source, "\uFEFF"))
|
||||
if strings.HasPrefix(trimmed, "<") {
|
||||
return FormatXML
|
||||
}
|
||||
return FormatMarkdown
|
||||
}
|
||||
|
||||
func validateStructure(nodes []*Node) error {
|
||||
type frame struct {
|
||||
node *Node
|
||||
exit bool
|
||||
}
|
||||
frames := make([]frame, 0, len(nodes))
|
||||
for i := len(nodes) - 1; i >= 0; i-- {
|
||||
frames = append(frames, frame{node: nodes[i]})
|
||||
}
|
||||
ancestors := map[string]int{}
|
||||
depth := 0
|
||||
for len(frames) > 0 {
|
||||
current := frames[len(frames)-1]
|
||||
frames = frames[:len(frames)-1]
|
||||
node := current.node
|
||||
if node == nil || node.typ != nodeElement {
|
||||
continue
|
||||
}
|
||||
if current.exit {
|
||||
ancestors[node.tag]--
|
||||
depth--
|
||||
continue
|
||||
}
|
||||
if depth >= MaxNestingDepth {
|
||||
return fmt.Errorf("document nesting exceeds limit %d at <%s>", MaxNestingDepth, node.tag)
|
||||
}
|
||||
if err := validateRequiredAttributes(node); err != nil {
|
||||
return err
|
||||
}
|
||||
if required := requiredAncestorTags[node.tag]; len(required) > 0 {
|
||||
matched := false
|
||||
for tag := range required {
|
||||
if ancestors[tag] > 0 {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
allowed := make([]string, 0, len(required))
|
||||
for tag := range required {
|
||||
allowed = append(allowed, tag)
|
||||
}
|
||||
sort.Strings(allowed)
|
||||
return fmt.Errorf("LarkOpenCLI tag <%s> requires an ancestor in [%s]", node.tag, strings.Join(allowed, ", "))
|
||||
}
|
||||
}
|
||||
|
||||
ancestors[node.tag]++
|
||||
depth++
|
||||
frames = append(frames, frame{node: node, exit: true})
|
||||
for i := len(node.children) - 1; i >= 0; i-- {
|
||||
frames = append(frames, frame{node: node.children[i]})
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateRequiredAttributes(node *Node) error {
|
||||
for _, attr := range requiredAttributes[node.tag] {
|
||||
if strings.TrimSpace(node.attrs[attr]) == "" {
|
||||
return fmt.Errorf("LarkOpenCLI tag <%s> requires attribute %q", node.tag, attr)
|
||||
}
|
||||
}
|
||||
for _, alternatives := range requiredAnyAttributes[node.tag] {
|
||||
matched := false
|
||||
for _, attr := range alternatives {
|
||||
if strings.TrimSpace(node.attrs[attr]) != "" {
|
||||
matched = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !matched {
|
||||
return fmt.Errorf("LarkOpenCLI tag <%s> requires one of attributes [%s]", node.tag, strings.Join(alternatives, ", "))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func buildProfile(nodes []*Node) Profile {
|
||||
counts := map[string]int{}
|
||||
total := 0
|
||||
var walk func(*Node)
|
||||
walk = func(node *Node) {
|
||||
if node == nil || node.typ != nodeElement {
|
||||
return
|
||||
}
|
||||
layout := layoutOf(node.tag)
|
||||
isBlock := layout == layoutBlock || layout == layoutDual && node.parent == nil
|
||||
if isBlock {
|
||||
counts[node.tag]++
|
||||
total++
|
||||
}
|
||||
for _, child := range node.children {
|
||||
walk(child)
|
||||
}
|
||||
}
|
||||
for _, node := range nodes {
|
||||
walk(node)
|
||||
}
|
||||
|
||||
distribution := make([]BlockShare, 0, len(counts))
|
||||
for typ, count := range counts {
|
||||
ratio := 0.0
|
||||
if total > 0 {
|
||||
ratio = math.Round(float64(count)/float64(total)*1_000_000) / 1_000_000
|
||||
}
|
||||
distribution = append(distribution, BlockShare{Type: typ, Count: count, Ratio: ratio})
|
||||
}
|
||||
sort.Slice(distribution, func(i, j int) bool {
|
||||
if distribution[i].Count != distribution[j].Count {
|
||||
return distribution[i].Count > distribution[j].Count
|
||||
}
|
||||
return distribution[i].Type < distribution[j].Type
|
||||
})
|
||||
segments := extractSegments(nodes)
|
||||
stats := newTextCounter().countSegments(segments)
|
||||
return Profile{
|
||||
WordCount: stats.WordCount,
|
||||
CharCount: stats.CharCount,
|
||||
Breakdown: stats.Breakdown,
|
||||
BlockCount: total,
|
||||
Blocks: distribution,
|
||||
}
|
||||
}
|
||||
|
||||
type segmentKind uint8
|
||||
|
||||
const (
|
||||
segmentText segmentKind = iota
|
||||
segmentMarker
|
||||
segmentCode
|
||||
)
|
||||
|
||||
type textSegment struct {
|
||||
text string
|
||||
kind segmentKind
|
||||
}
|
||||
|
||||
var ignoredResourceTags = map[string]bool{
|
||||
"whiteboard": true, "sheet": true, "source": true, "chat_card": true,
|
||||
"base_refer": true, "bitable": true, "synced_reference": true,
|
||||
"poll": true, "isv": true, "mindnote": true, "sub-page-list": true,
|
||||
"okr": true, "html5-block": true,
|
||||
}
|
||||
|
||||
var ignoredInlineTags = map[string]bool{
|
||||
"button": true, "cite": true, "latex": true, "bookmark": true,
|
||||
}
|
||||
|
||||
func extractSegments(nodes []*Node) []textSegment {
|
||||
var segments []textSegment
|
||||
for _, node := range nodes {
|
||||
extractNodeSegments(node, &segments)
|
||||
}
|
||||
return segments
|
||||
}
|
||||
|
||||
func extractNodeSegments(node *Node, segments *[]textSegment) {
|
||||
if node == nil {
|
||||
return
|
||||
}
|
||||
if node.typ == nodeText {
|
||||
if strings.TrimSpace(node.text) != "" {
|
||||
*segments = append(*segments, textSegment{text: node.text})
|
||||
}
|
||||
return
|
||||
}
|
||||
if ignoredInlineTags[node.tag] || ignoredResourceTags[node.tag] {
|
||||
return
|
||||
}
|
||||
if node.tag == "task" {
|
||||
return
|
||||
}
|
||||
if node.tag == "synced-source" && len(node.children) == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
switch node.tag {
|
||||
case "ul", "ol":
|
||||
sequence := 1
|
||||
for _, child := range node.children {
|
||||
if child.typ == nodeElement && child.tag == "li" {
|
||||
if node.tag == "ul" {
|
||||
*segments = append(*segments, textSegment{text: "•", kind: segmentMarker})
|
||||
} else {
|
||||
marker := sequence
|
||||
if raw := child.attrs["seq"]; raw != "" {
|
||||
if _, err := fmt.Sscanf(raw, "%d", &marker); err == nil {
|
||||
sequence = marker
|
||||
}
|
||||
}
|
||||
*segments = append(*segments, textSegment{text: fmt.Sprintf("%d.", marker)})
|
||||
sequence++
|
||||
}
|
||||
}
|
||||
extractNodeSegments(child, segments)
|
||||
}
|
||||
return
|
||||
case "checkbox":
|
||||
marker := "☐"
|
||||
if node.attrs["done"] == "true" {
|
||||
marker = "☑"
|
||||
}
|
||||
*segments = append(*segments, textSegment{text: marker, kind: segmentMarker})
|
||||
}
|
||||
|
||||
kind := segmentText
|
||||
if node.tag == "pre" || node.tag == "code" && (node.parent == nil || node.parent.tag != "p") {
|
||||
kind = segmentCode
|
||||
}
|
||||
text := visibleInlineText(node)
|
||||
if strings.TrimSpace(text) == "" && !hasBlockChildren(node) {
|
||||
if node.tag == "img" {
|
||||
text = node.attrs["caption"]
|
||||
} else {
|
||||
text = firstNonEmpty(node.attrs["text"], node.attrs["name"], node.attrs["title"], node.attrs["alt"], node.attrs["caption"])
|
||||
}
|
||||
}
|
||||
if strings.TrimSpace(text) != "" {
|
||||
*segments = append(*segments, textSegment{text: text, kind: kind})
|
||||
}
|
||||
|
||||
for _, child := range node.children {
|
||||
if child.typ != nodeElement || isInlineForExtraction(child.tag) {
|
||||
continue
|
||||
}
|
||||
extractNodeSegments(child, segments)
|
||||
}
|
||||
}
|
||||
|
||||
func visibleInlineText(node *Node) string {
|
||||
var out strings.Builder
|
||||
var walk func(*Node)
|
||||
walk = func(current *Node) {
|
||||
if current.typ == nodeText {
|
||||
out.WriteString(current.text)
|
||||
return
|
||||
}
|
||||
if current != node && !isInlineForExtraction(current.tag) {
|
||||
return
|
||||
}
|
||||
if ignoredInlineTags[current.tag] {
|
||||
return
|
||||
}
|
||||
if current.tag == "br" {
|
||||
out.WriteByte('\n')
|
||||
return
|
||||
}
|
||||
if current != node {
|
||||
if display := firstNonEmpty(current.attrs["text"], current.attrs["name"], current.attrs["title"], current.attrs["alt"]); display != "" {
|
||||
out.WriteString(display)
|
||||
return
|
||||
}
|
||||
}
|
||||
for _, child := range current.children {
|
||||
walk(child)
|
||||
}
|
||||
}
|
||||
for _, child := range node.children {
|
||||
walk(child)
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func hasBlockChildren(node *Node) bool {
|
||||
for _, child := range node.children {
|
||||
if child.typ == nodeElement && !isInlineForExtraction(child.tag) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func isInlineForExtraction(tag string) bool {
|
||||
layout := layoutOf(tag)
|
||||
return layout == layoutInline || layout == layoutDual
|
||||
}
|
||||
|
||||
func firstNonEmpty(values ...string) string {
|
||||
for _, value := range values {
|
||||
if value != "" {
|
||||
return value
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
268
shortcuts/doc/internal/docxparse/schema.go
Normal file
268
shortcuts/doc/internal/docxparse/schema.go
Normal file
@@ -0,0 +1,268 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type tagLayout string
|
||||
|
||||
const (
|
||||
layoutBlock tagLayout = "block"
|
||||
layoutInline tagLayout = "inline"
|
||||
layoutDual tagLayout = "dual"
|
||||
layoutStructural tagLayout = "structural"
|
||||
layoutCommand tagLayout = "command"
|
||||
)
|
||||
|
||||
type tagSpec struct {
|
||||
canonical string
|
||||
layout tagLayout
|
||||
}
|
||||
|
||||
var tagSpecs = map[string]tagSpec{}
|
||||
|
||||
// tagAliases mirrors the public compatibility aliases declared by the
|
||||
// LarkOpenCLI SDK. Parsing keeps the caller's XML unchanged; aliases are only
|
||||
// canonicalized in the in-memory tree used for profiling and Markdown output.
|
||||
var tagAliases = map[string]string{
|
||||
"strong": "b",
|
||||
"text": "span",
|
||||
"equation": "latex",
|
||||
"lark-table": "table",
|
||||
"lark-tr": "tr",
|
||||
"lark-td": "td",
|
||||
"image": "img",
|
||||
"reference-synced": "synced_reference",
|
||||
"source-synced": "synced-source",
|
||||
"at": "cite",
|
||||
"chat-card": "chat_card",
|
||||
"folder_manager": "folder-manager",
|
||||
}
|
||||
|
||||
type attributeAliasRule struct {
|
||||
canonical string
|
||||
transform func(string) (string, bool)
|
||||
}
|
||||
|
||||
var commonAttributeAliases = map[string]attributeAliasRule{
|
||||
"color": {canonical: "text-color"},
|
||||
"textcolor": {canonical: "text-color"},
|
||||
"text_color": {canonical: "text-color"},
|
||||
"bgcolor": {canonical: "background-color"},
|
||||
"background_color": {canonical: "background-color"},
|
||||
}
|
||||
|
||||
var tagAttributeAliases = map[string]map[string]attributeAliasRule{
|
||||
"img": {
|
||||
"url": {canonical: "href"},
|
||||
"file_key": {canonical: "img_key"},
|
||||
},
|
||||
"callout": {
|
||||
"color": {canonical: "background-color"},
|
||||
"icon": {canonical: "emoji"},
|
||||
},
|
||||
"column": {
|
||||
"width": {canonical: "width-ratio", transform: normalizeWidthRatio},
|
||||
},
|
||||
"chat_card": {
|
||||
"id": {canonical: "chat-id", transform: requireChatID},
|
||||
},
|
||||
"cite": {
|
||||
"user_id": {canonical: "user-id"},
|
||||
},
|
||||
}
|
||||
|
||||
var rawTagAttributeAliases = map[string]map[string]attributeAliasRule{
|
||||
"at": {
|
||||
"id": {canonical: "user-id"},
|
||||
"user_id": {canonical: "user-id"},
|
||||
},
|
||||
}
|
||||
|
||||
var requiredAttributes = map[string][]string{
|
||||
"task": {"task-id"},
|
||||
}
|
||||
|
||||
var requiredAnyAttributes = map[string][][]string{
|
||||
"img": {{"src", "img_key", "href"}},
|
||||
"whiteboard": {{"token", "type"}},
|
||||
"chat_card": {{"token", "chat-id"}},
|
||||
"bookmark": {{"href", "name"}},
|
||||
}
|
||||
|
||||
func init() {
|
||||
registerTags(layoutBlock,
|
||||
"title", "h1", "h2", "h3", "h4", "h5", "h6", "h7", "h8", "h9", "p",
|
||||
"div", "ul", "ol", "li", "blockquote", "grid", "column", "table", "thead",
|
||||
"tbody", "tfoot", "tr", "hr", "pre", "img", "source", "bitable", "sheet",
|
||||
"mindnote", "whiteboard", "base_refer", "synced_reference", "isv", "html5-block",
|
||||
"view", "synced-source", "readonly-block", "figure", "callout", "checkbox",
|
||||
"chat_card", "okr", "okr-objective", "okr-key-result", "okr-progress", "poll",
|
||||
"agenda", "folder-manager", "sub-page-list", "wiki_catalog", "wiki_recent_update",
|
||||
"chart-embedded", "chart-refer-host-perm", "chart_embedded", "chart_refer_host_perm",
|
||||
"bookmark", "task", "vc-tabs", "vc-summary-tab", "vc-transcribe-tab", "append",
|
||||
)
|
||||
registerTags(layoutInline, "b", "em", "u", "del", "i", "span", "br", "inline-file", "mention-date", "cite", "button", "time", "a")
|
||||
registerTags(layoutDual, "latex", "code")
|
||||
registerTags(layoutStructural, "th", "td", "colgroup", "col", "sub-page")
|
||||
registerTags(layoutCommand,
|
||||
"comment", "block_delete", "str_delete", "str_replace", "block_replace", "block_insert",
|
||||
"block_move", "block_copy_insert_after", "src_block_ids", "create", "answer", "response",
|
||||
"identifier", "genre", "anchor", "type", "revision", "pattern", "replacement",
|
||||
"replace_content", "action", "content", "parameter", "generation", "block_id",
|
||||
)
|
||||
|
||||
}
|
||||
|
||||
func registerTags(layout tagLayout, tags ...string) {
|
||||
for _, tag := range tags {
|
||||
tagSpecs[tag] = tagSpec{canonical: tag, layout: layout}
|
||||
}
|
||||
}
|
||||
|
||||
func lookupTag(raw string) (tagSpec, bool) {
|
||||
key := strings.ToLower(strings.TrimSpace(raw))
|
||||
if canonical, ok := tagAliases[key]; ok {
|
||||
key = canonical
|
||||
}
|
||||
spec, ok := tagSpecs[key]
|
||||
if !ok {
|
||||
return tagSpec{}, false
|
||||
}
|
||||
return spec, true
|
||||
}
|
||||
|
||||
func layoutOf(tag string) tagLayout {
|
||||
spec, ok := lookupTag(tag)
|
||||
if !ok {
|
||||
return ""
|
||||
}
|
||||
return spec.layout
|
||||
}
|
||||
|
||||
var voidTags = map[string]bool{
|
||||
"br": true,
|
||||
"col": true,
|
||||
"hr": true,
|
||||
"img": true,
|
||||
"source": true,
|
||||
"sub-page": true,
|
||||
}
|
||||
|
||||
func isVoidTag(tag string) bool { return voidTags[tag] }
|
||||
|
||||
var preserveSpaceTags = map[string]bool{
|
||||
"title": true, "h1": true, "h2": true, "h3": true, "h4": true,
|
||||
"h5": true, "h6": true, "h7": true, "h8": true, "h9": true,
|
||||
"p": true, "i": true, "b": true, "em": true, "u": true, "del": true,
|
||||
"code": true, "li": true, "a": true, "span": true,
|
||||
}
|
||||
|
||||
var strictPhrasingTags = map[string]bool{
|
||||
"title": true, "span": true, "b": true, "em": true,
|
||||
"u": true, "del": true, "a": true,
|
||||
}
|
||||
|
||||
var autoCloseTags = map[string]map[string]bool{
|
||||
"li": {"li": true},
|
||||
"tr": {"tr": true},
|
||||
"td": {"td": true, "th": true, "tr": true, "tbody": true, "tfoot": true},
|
||||
"th": {"th": true, "td": true, "tr": true, "tbody": true, "tfoot": true},
|
||||
"tbody": {"tbody": true, "tfoot": true},
|
||||
"thead": {"tbody": true, "tfoot": true},
|
||||
"column": {"column": true},
|
||||
}
|
||||
|
||||
var requiredAncestorTags = map[string]map[string]bool{
|
||||
"column": {"grid": true},
|
||||
"thead": {"table": true},
|
||||
"tbody": {"table": true},
|
||||
"tfoot": {"table": true},
|
||||
"tr": {"table": true, "thead": true, "tbody": true, "tfoot": true},
|
||||
"th": {"tr": true},
|
||||
"td": {"tr": true},
|
||||
"colgroup": {"table": true},
|
||||
"col": {"table": true, "colgroup": true},
|
||||
"okr-objective": {"okr": true},
|
||||
"okr-key-result": {"okr": true, "okr-objective": true},
|
||||
"okr-progress": {"okr-objective": true, "okr-key-result": true},
|
||||
"sub-page": {"sub-page-list": true},
|
||||
}
|
||||
|
||||
func shouldAutoClose(openTag, nextTag string) bool {
|
||||
if strictPhrasingTags[openTag] && layoutOf(nextTag) == layoutBlock {
|
||||
return true
|
||||
}
|
||||
return autoCloseTags[openTag] != nil && autoCloseTags[openTag][nextTag]
|
||||
}
|
||||
|
||||
func normalizeAttributes(rawTag, canonical string, attrs map[string]string) map[string]string {
|
||||
rules := make(map[string]attributeAliasRule, len(commonAttributeAliases)+4)
|
||||
for alias, rule := range commonAttributeAliases {
|
||||
rules[alias] = rule
|
||||
}
|
||||
for alias, rule := range tagAttributeAliases[canonical] {
|
||||
rules[alias] = rule
|
||||
}
|
||||
rawKey := strings.ToLower(strings.TrimSpace(rawTag))
|
||||
for alias, rule := range rawTagAttributeAliases[rawKey] {
|
||||
rules[alias] = rule
|
||||
}
|
||||
|
||||
aliases := make([]string, 0, len(rules))
|
||||
for alias := range rules {
|
||||
aliases = append(aliases, alias)
|
||||
}
|
||||
sort.Strings(aliases)
|
||||
for _, alias := range aliases {
|
||||
value, exists := attrs[alias]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
rule := rules[alias]
|
||||
if rule.transform != nil {
|
||||
var ok bool
|
||||
value, ok = rule.transform(value)
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
}
|
||||
if canonicalValue, exists := attrs[rule.canonical]; !exists || strings.TrimSpace(canonicalValue) == "" {
|
||||
if attrs == nil {
|
||||
attrs = map[string]string{}
|
||||
}
|
||||
attrs[rule.canonical] = value
|
||||
}
|
||||
delete(attrs, alias)
|
||||
}
|
||||
|
||||
if rawKey == "at" {
|
||||
if attrs == nil {
|
||||
attrs = map[string]string{}
|
||||
}
|
||||
attrs["type"] = "user"
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
func normalizeWidthRatio(value string) (string, bool) {
|
||||
trimmed := strings.TrimSuffix(strings.TrimSpace(value), "%")
|
||||
if trimmed == "" {
|
||||
return value, false
|
||||
}
|
||||
width, err := strconv.ParseFloat(trimmed, 64)
|
||||
if err != nil {
|
||||
return value, false
|
||||
}
|
||||
return strconv.FormatFloat(width/100, 'f', 6, 64), true
|
||||
}
|
||||
|
||||
func requireChatID(value string) (string, bool) {
|
||||
trimmed := strings.TrimSpace(value)
|
||||
return trimmed, strings.HasPrefix(trimmed, "oc_")
|
||||
}
|
||||
342
shortcuts/doc/internal/docxparse/wordcount.go
Normal file
342
shortcuts/doc/internal/docxparse/wordcount.go
Normal file
@@ -0,0 +1,342 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
// This file implements the LarkOpenCLI document text-counting contract.
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"golang.org/x/text/width"
|
||||
)
|
||||
|
||||
const chinesePunctuation = ",。!?;:、()《》〈〉“”‘’【】「」『』〔〕…—~·¥"
|
||||
const englishPunctuation = `!"#$%&'()*+,-./:;<=>?@[\]^_` + "`" + `{|}~`
|
||||
|
||||
var (
|
||||
urlToken = regexp.MustCompile(`^https?://[!-~]+`)
|
||||
asciiCompoundToken = regexp.MustCompile(`^[A-Za-z0-9]+(?:[._/@:-][A-Za-z0-9]+)+`)
|
||||
)
|
||||
|
||||
type lexemeKind uint8
|
||||
|
||||
const (
|
||||
lexemeNone lexemeKind = iota
|
||||
lexemeEnglish
|
||||
lexemeNumber
|
||||
)
|
||||
|
||||
type textCounter struct {
|
||||
stats TextProfile
|
||||
lexeme lexemeKind
|
||||
lexemeHasDigit bool
|
||||
symbolRunLength int
|
||||
atBoundary bool
|
||||
}
|
||||
|
||||
func newTextCounter() *textCounter {
|
||||
return &textCounter{atBoundary: true}
|
||||
}
|
||||
|
||||
func (c *textCounter) countSegments(segments []textSegment) TextProfile {
|
||||
for _, segment := range segments {
|
||||
c.endUnit()
|
||||
c.atBoundary = true
|
||||
switch segment.kind {
|
||||
case segmentMarker:
|
||||
c.writeMarker(segment.text)
|
||||
case segmentCode:
|
||||
c.writeCode(segment.text)
|
||||
default:
|
||||
c.write(segment.text)
|
||||
}
|
||||
c.endUnit()
|
||||
c.atBoundary = true
|
||||
}
|
||||
c.endUnit()
|
||||
return c.stats
|
||||
}
|
||||
|
||||
func (c *textCounter) write(value string) {
|
||||
for offset := 0; offset < len(value); {
|
||||
if token := matchASCIICompound(value[offset:]); token != "" {
|
||||
c.writeASCIICompound(token)
|
||||
offset += len(token)
|
||||
continue
|
||||
}
|
||||
r, size := utf8.DecodeRuneInString(value[offset:])
|
||||
if r == '/' && isVisibleHanSeparator(value, offset, size) {
|
||||
c.endUnit()
|
||||
c.stats.Breakdown.EnglishPunctuations++
|
||||
c.stats.Breakdown.SymbolWords++
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
offset += size
|
||||
continue
|
||||
}
|
||||
c.writeRune(r)
|
||||
offset += size
|
||||
}
|
||||
}
|
||||
|
||||
func (c *textCounter) writeMarker(value string) {
|
||||
for _, r := range value {
|
||||
if unicode.IsSpace(r) {
|
||||
continue
|
||||
}
|
||||
c.endUnit()
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
}
|
||||
}
|
||||
|
||||
func (c *textCounter) writeCode(value string) {
|
||||
for _, r := range value {
|
||||
c.writeCodeRune(r)
|
||||
}
|
||||
}
|
||||
|
||||
func (c *textCounter) writeCodeRune(r rune) {
|
||||
if unicode.IsSpace(r) {
|
||||
c.endUnit()
|
||||
c.atBoundary = true
|
||||
return
|
||||
}
|
||||
if unicode.Is(unicode.Han, r) {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.HanChars++
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isASCIILetterRune(r) {
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.EnglishLetters++
|
||||
c.stats.CharCount++
|
||||
if c.lexeme == lexemeNone || c.lexeme == lexemeNumber {
|
||||
c.lexeme = lexemeEnglish
|
||||
}
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isASCIIDigitRune(r) {
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.Digits++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isChinesePunctuation(r) {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.ChinesePunctuations++
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isEnglishPunctuation(r) {
|
||||
keepsLexeme := c.lexeme == lexemeEnglish && (r == '\'' || r == '-')
|
||||
if !keepsLexeme {
|
||||
hadLexeme := c.lexeme != lexemeNone
|
||||
c.endLexeme()
|
||||
if !hadLexeme && (c.symbolRunLength > 0 || c.atBoundary) {
|
||||
c.symbolRunLength++
|
||||
}
|
||||
}
|
||||
c.stats.Breakdown.EnglishPunctuations++
|
||||
c.stats.CharCount++
|
||||
if keepsLexeme {
|
||||
c.atBoundary = false
|
||||
}
|
||||
return
|
||||
}
|
||||
if unicode.Is(unicode.Symbol, r) {
|
||||
c.writeSymbol(r)
|
||||
return
|
||||
}
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.atBoundary = false
|
||||
}
|
||||
|
||||
func (c *textCounter) writeRune(r rune) {
|
||||
if unicode.IsSpace(r) {
|
||||
c.endUnit()
|
||||
c.atBoundary = true
|
||||
return
|
||||
}
|
||||
if unicode.Is(unicode.Han, r) {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.HanChars++
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isASCIILetterRune(r) {
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.EnglishLetters++
|
||||
c.stats.CharCount++
|
||||
if c.lexeme == lexemeNone || c.lexeme == lexemeNumber {
|
||||
c.lexeme = lexemeEnglish
|
||||
}
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isASCIIDigitRune(r) {
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.Digits++
|
||||
c.stats.CharCount++
|
||||
c.lexemeHasDigit = true
|
||||
if c.lexeme == lexemeNone {
|
||||
c.lexeme = lexemeNumber
|
||||
}
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isChinesePunctuation(r) {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.stats.Breakdown.ChinesePunctuations++
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount++
|
||||
c.atBoundary = false
|
||||
return
|
||||
}
|
||||
if isEnglishPunctuation(r) {
|
||||
keepsLexeme := c.lexeme == lexemeEnglish && (r == '\'' || r == '-' || c.lexemeHasDigit && r == '.') ||
|
||||
c.lexeme == lexemeNumber && (r == '.' || r == ',' || r == '-')
|
||||
if !keepsLexeme {
|
||||
hadLexeme := c.lexeme != lexemeNone
|
||||
c.endLexeme()
|
||||
if !hadLexeme && (c.symbolRunLength > 0 || c.atBoundary) {
|
||||
c.symbolRunLength++
|
||||
}
|
||||
}
|
||||
c.stats.Breakdown.EnglishPunctuations++
|
||||
c.stats.CharCount++
|
||||
if keepsLexeme {
|
||||
c.atBoundary = false
|
||||
}
|
||||
return
|
||||
}
|
||||
if unicode.Is(unicode.Symbol, r) {
|
||||
c.writeSymbol(r)
|
||||
return
|
||||
}
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
c.atBoundary = false
|
||||
}
|
||||
|
||||
func matchASCIICompound(value string) string {
|
||||
if match := urlToken.FindString(value); match != "" {
|
||||
return match
|
||||
}
|
||||
match := asciiCompoundToken.FindString(value)
|
||||
if match == "" || !strings.ContainsAny(match, "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") {
|
||||
return ""
|
||||
}
|
||||
return match
|
||||
}
|
||||
|
||||
func (c *textCounter) writeASCIICompound(token string) {
|
||||
c.endUnit()
|
||||
c.stats.Breakdown.EnglishWords++
|
||||
c.stats.WordCount++
|
||||
for _, r := range token {
|
||||
switch {
|
||||
case isASCIILetterRune(r):
|
||||
c.stats.Breakdown.EnglishLetters++
|
||||
c.stats.CharCount++
|
||||
case isASCIIDigitRune(r):
|
||||
c.stats.Breakdown.Digits++
|
||||
c.stats.CharCount++
|
||||
case isEnglishPunctuation(r):
|
||||
c.stats.Breakdown.EnglishPunctuations++
|
||||
c.stats.CharCount++
|
||||
}
|
||||
}
|
||||
c.atBoundary = false
|
||||
}
|
||||
|
||||
func (c *textCounter) writeSymbol(r rune) {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(false)
|
||||
units := utf16Units(r)
|
||||
c.stats.Breakdown.SymbolWords++
|
||||
c.stats.Breakdown.SymbolChars += units
|
||||
c.stats.WordCount++
|
||||
c.stats.CharCount += units
|
||||
c.atBoundary = false
|
||||
}
|
||||
|
||||
func (c *textCounter) endUnit() {
|
||||
c.endLexeme()
|
||||
c.endSymbolRun(true)
|
||||
}
|
||||
|
||||
func (c *textCounter) endLexeme() {
|
||||
switch c.lexeme {
|
||||
case lexemeEnglish:
|
||||
c.stats.Breakdown.EnglishWords++
|
||||
c.stats.WordCount++
|
||||
case lexemeNumber:
|
||||
c.stats.Breakdown.NumberWords++
|
||||
c.stats.WordCount++
|
||||
}
|
||||
c.lexeme = lexemeNone
|
||||
c.lexemeHasDigit = false
|
||||
}
|
||||
|
||||
func (c *textCounter) endSymbolRun(countWord bool) {
|
||||
if c.symbolRunLength > 0 && countWord {
|
||||
c.stats.Breakdown.SymbolWords++
|
||||
c.stats.WordCount++
|
||||
}
|
||||
if c.symbolRunLength > 0 {
|
||||
c.atBoundary = false
|
||||
}
|
||||
c.symbolRunLength = 0
|
||||
}
|
||||
|
||||
func isVisibleHanSeparator(value string, offset, size int) bool {
|
||||
if offset == 0 || offset+size >= len(value) {
|
||||
return false
|
||||
}
|
||||
previous, _ := utf8.DecodeLastRuneInString(value[:offset])
|
||||
next, _ := utf8.DecodeRuneInString(value[offset+size:])
|
||||
return unicode.Is(unicode.Han, previous) && unicode.Is(unicode.Han, next)
|
||||
}
|
||||
|
||||
func isASCIILetterRune(r rune) bool { return r >= 'a' && r <= 'z' || r >= 'A' && r <= 'Z' }
|
||||
func isASCIIDigitRune(r rune) bool { return r >= '0' && r <= '9' }
|
||||
|
||||
func isChinesePunctuation(r rune) bool {
|
||||
if strings.ContainsRune(chinesePunctuation, r) {
|
||||
return true
|
||||
}
|
||||
kind := width.LookupRune(r).Kind()
|
||||
return unicode.Is(unicode.Punct, r) && (kind == width.EastAsianWide || kind == width.EastAsianFullwidth)
|
||||
}
|
||||
|
||||
func isEnglishPunctuation(r rune) bool {
|
||||
return r < utf8.RuneSelf && strings.ContainsRune(englishPunctuation, r)
|
||||
}
|
||||
|
||||
func utf16Units(r rune) int {
|
||||
if r > 0xffff {
|
||||
return 2
|
||||
}
|
||||
return 1
|
||||
}
|
||||
572
shortcuts/doc/internal/docxparse/xml.go
Normal file
572
shortcuts/doc/internal/docxparse/xml.go
Normal file
@@ -0,0 +1,572 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"html"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
MaxInputBytes = 20_000_000
|
||||
MaxNestingDepth = 1024
|
||||
)
|
||||
|
||||
var forbiddenXMLDeclaration = regexp.MustCompile(`(?i)<!\s*(?:DOCTYPE|ENTITY)\b`)
|
||||
|
||||
func validateSource(source string) error {
|
||||
if len(source) > MaxInputBytes {
|
||||
return fmt.Errorf("input is too large (%d bytes, limit %d)", len(source), MaxInputBytes)
|
||||
}
|
||||
if forbiddenXMLDeclaration.MatchString(source) {
|
||||
return fmt.Errorf("XML input must not contain DOCTYPE or ENTITY declarations")
|
||||
}
|
||||
if !utf8.ValidString(source) {
|
||||
return fmt.Errorf("input must be valid UTF-8")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseXML(source string) ([]*Node, error) {
|
||||
if err := validateSource(source); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
source = strings.TrimPrefix(source, "\uFEFF")
|
||||
|
||||
root := newElement("__fragment__", nil)
|
||||
stack := []*Node{root}
|
||||
for i := 0; i < len(source); {
|
||||
lt := strings.IndexByte(source[i:], '<')
|
||||
if lt < 0 {
|
||||
if err := validateXMLText(source[i:], i); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
appendText(stack[len(stack)-1], source[i:])
|
||||
break
|
||||
}
|
||||
lt += i
|
||||
if err := validateXMLText(source[i:lt], i); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
appendText(stack[len(stack)-1], source[i:lt])
|
||||
|
||||
token, end, state := scanXMLToken(source, lt)
|
||||
switch state {
|
||||
case tokenComment, tokenProcessingInstruction:
|
||||
i = end
|
||||
continue
|
||||
case tokenCDATA:
|
||||
appendTextValue(stack[len(stack)-1], token.text)
|
||||
i = end
|
||||
continue
|
||||
case tokenInvalid:
|
||||
return nil, fmt.Errorf("invalid XML token at byte %d", lt)
|
||||
case tokenIncomplete:
|
||||
return nil, fmt.Errorf("unterminated XML tag at byte %d", lt)
|
||||
}
|
||||
|
||||
spec, allowed := lookupTag(token.name)
|
||||
if !allowed {
|
||||
return nil, fmt.Errorf("unsupported LarkOpenCLI tag <%s> at byte %d", token.name, lt)
|
||||
}
|
||||
canonical := spec.canonical
|
||||
if token.spacingNormalized {
|
||||
return nil, fmt.Errorf("invalid whitespace in XML tag <%s> at byte %d", token.name, lt)
|
||||
}
|
||||
|
||||
if token.closing {
|
||||
if isVoidTag(canonical) {
|
||||
return nil, fmt.Errorf("void tag <%s/> must not have a closing tag", canonical)
|
||||
}
|
||||
if len(stack) == 1 {
|
||||
return nil, fmt.Errorf("unexpected closing tag </%s> at byte %d", canonical, lt)
|
||||
}
|
||||
open := stack[len(stack)-1].tag
|
||||
if open != canonical {
|
||||
return nil, fmt.Errorf("mismatched closing tag </%s> at byte %d; expected </%s>", canonical, lt, open)
|
||||
}
|
||||
stack = stack[:len(stack)-1]
|
||||
i = end
|
||||
continue
|
||||
}
|
||||
|
||||
if len(stack) > 1 && shouldAutoClose(stack[len(stack)-1].tag, canonical) {
|
||||
return nil, fmt.Errorf("invalid <%s> inside <%s> at byte %d", canonical, stack[len(stack)-1].tag, lt)
|
||||
}
|
||||
attrs := normalizeAttributes(token.name, canonical, token.attrs)
|
||||
node := newElement(canonical, attrs)
|
||||
stack[len(stack)-1].addChild(node)
|
||||
if !token.selfClosing && !isVoidTag(canonical) {
|
||||
if len(stack) > MaxNestingDepth {
|
||||
return nil, fmt.Errorf("XML nesting exceeds limit %d at byte %d", MaxNestingDepth, lt)
|
||||
}
|
||||
stack = append(stack, node)
|
||||
}
|
||||
i = end
|
||||
}
|
||||
|
||||
if len(stack) > 1 {
|
||||
return nil, fmt.Errorf("missing closing tag </%s> at end of input", stack[len(stack)-1].tag)
|
||||
}
|
||||
normalizeParsedLineBreaks(root.children, false, false)
|
||||
for _, child := range root.children {
|
||||
child.parent = nil
|
||||
}
|
||||
return root.children, nil
|
||||
}
|
||||
|
||||
// normalizeParsedLineBreaks removes formatting newlines from ordinary XML,
|
||||
// while source-bearing code/whiteboard blocks keep semantic
|
||||
// line breaks as explicit <br/> nodes. str_replace pattern/replacement payloads
|
||||
// retain raw newlines because their string matching semantics depend on them.
|
||||
func normalizeParsedLineBreaks(nodes []*Node, sourceBlock, stringMutation bool) {
|
||||
for _, node := range nodes {
|
||||
if node == nil || node.typ != nodeElement {
|
||||
continue
|
||||
}
|
||||
nextSourceBlock := sourceBlock || node.tag == "code" || node.tag == "whiteboard"
|
||||
nextStringMutation := stringMutation || node.tag == "str_replace"
|
||||
preserveRaw := nextStringMutation && (node.tag == "pattern" || node.tag == "replacement")
|
||||
if node.tag == "code" || node.tag == "whiteboard" {
|
||||
trimSourceBlockBoundaryNewlines(node.children)
|
||||
}
|
||||
children := make([]*Node, 0, len(node.children))
|
||||
for _, child := range node.children {
|
||||
if child.typ != nodeText || !strings.ContainsAny(child.text, "\r\n") {
|
||||
children = append(children, child)
|
||||
continue
|
||||
}
|
||||
switch {
|
||||
case preserveRaw:
|
||||
children = append(children, child)
|
||||
case nextSourceBlock:
|
||||
for _, replacement := range rawTextWithBreakNodes(child.text) {
|
||||
replacement.parent = node
|
||||
children = append(children, replacement)
|
||||
}
|
||||
default:
|
||||
child.text = strings.NewReplacer("\r", "", "\n", "").Replace(child.text)
|
||||
if child.text != "" {
|
||||
children = append(children, child)
|
||||
}
|
||||
}
|
||||
}
|
||||
node.children = children
|
||||
normalizeParsedLineBreaks(node.children, nextSourceBlock, nextStringMutation)
|
||||
}
|
||||
}
|
||||
|
||||
func trimSourceBlockBoundaryNewlines(children []*Node) {
|
||||
for _, child := range children {
|
||||
if child.typ == nodeText {
|
||||
child.text = strings.TrimLeft(child.text, "\r\n")
|
||||
break
|
||||
}
|
||||
if child.typ == nodeElement {
|
||||
break
|
||||
}
|
||||
}
|
||||
for i := len(children) - 1; i >= 0; i-- {
|
||||
child := children[i]
|
||||
if child.typ == nodeText {
|
||||
child.text = strings.TrimRight(child.text, "\r\n")
|
||||
break
|
||||
}
|
||||
if child.typ == nodeElement {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func rawTextWithBreakNodes(content string) []*Node {
|
||||
if content == "" {
|
||||
return nil
|
||||
}
|
||||
var nodes []*Node
|
||||
start := 0
|
||||
for i := 0; i < len(content); i++ {
|
||||
if content[i] != '\n' && content[i] != '\r' {
|
||||
continue
|
||||
}
|
||||
if i > start {
|
||||
nodes = append(nodes, newText(content[start:i]))
|
||||
}
|
||||
if content[i] == '\r' && i+1 < len(content) && content[i+1] == '\n' {
|
||||
i++
|
||||
}
|
||||
nodes = append(nodes, newElement("br", nil))
|
||||
start = i + 1
|
||||
}
|
||||
if start < len(content) {
|
||||
nodes = append(nodes, newText(content[start:]))
|
||||
}
|
||||
return nodes
|
||||
}
|
||||
|
||||
type tokenState uint8
|
||||
|
||||
const (
|
||||
tokenOK tokenState = iota
|
||||
tokenInvalid
|
||||
tokenIncomplete
|
||||
tokenComment
|
||||
tokenProcessingInstruction
|
||||
tokenCDATA
|
||||
)
|
||||
|
||||
type xmlToken struct {
|
||||
name string
|
||||
attrs map[string]string
|
||||
text string
|
||||
closing bool
|
||||
selfClosing bool
|
||||
spacingNormalized bool
|
||||
}
|
||||
|
||||
func scanXMLToken(source string, start int) (xmlToken, int, tokenState) {
|
||||
if strings.HasPrefix(source[start:], "<![CDATA[") {
|
||||
const marker = "<![CDATA["
|
||||
contentStart := start + len(marker)
|
||||
if closeAt := strings.Index(source[contentStart:], "]]>"); closeAt >= 0 {
|
||||
contentEnd := contentStart + closeAt
|
||||
return xmlToken{text: source[contentStart:contentEnd]}, contentEnd + len("]]>"), tokenCDATA
|
||||
}
|
||||
return xmlToken{}, len(source), tokenIncomplete
|
||||
}
|
||||
if strings.HasPrefix(source[start:], "<!--") {
|
||||
if closeAt := strings.Index(source[start+4:], "-->"); closeAt >= 0 {
|
||||
if strings.Contains(source[start+4:start+4+closeAt], "--") {
|
||||
return xmlToken{}, start + 1, tokenInvalid
|
||||
}
|
||||
return xmlToken{}, start + 4 + closeAt + 3, tokenComment
|
||||
}
|
||||
return xmlToken{}, len(source), tokenIncomplete
|
||||
}
|
||||
if strings.HasPrefix(source[start:], "<?") {
|
||||
if closeAt := strings.Index(source[start+2:], "?>"); closeAt >= 0 {
|
||||
return xmlToken{}, start + 2 + closeAt + 2, tokenProcessingInstruction
|
||||
}
|
||||
return xmlToken{}, len(source), tokenIncomplete
|
||||
}
|
||||
|
||||
quote := byte(0)
|
||||
end := -1
|
||||
for i := start + 1; i < len(source); i++ {
|
||||
switch source[i] {
|
||||
case '\'', '"':
|
||||
if quote == 0 {
|
||||
quote = source[i]
|
||||
} else if quote == source[i] {
|
||||
quote = 0
|
||||
}
|
||||
case '>':
|
||||
if quote == 0 {
|
||||
end = i + 1
|
||||
i = len(source)
|
||||
}
|
||||
case '<':
|
||||
// A second unquoted '<' cannot belong to the current XML tag.
|
||||
// Stop here so a long sequence of invalid tag starts is scanned
|
||||
// once instead of repeatedly searching to a distant '>'.
|
||||
if quote == 0 {
|
||||
return xmlToken{}, start + 1, tokenInvalid
|
||||
}
|
||||
}
|
||||
}
|
||||
if end < 0 {
|
||||
candidate := strings.TrimSpace(source[start+1:])
|
||||
if candidate == "" || !isTagNameStart(candidate[0]) && candidate[0] != '/' {
|
||||
return xmlToken{}, start + 1, tokenInvalid
|
||||
}
|
||||
return xmlToken{}, len(source), tokenIncomplete
|
||||
}
|
||||
|
||||
body := source[start+1 : end-1]
|
||||
if body == "" {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
token := xmlToken{}
|
||||
position := 0
|
||||
for position < len(body) && isXMLSpace(body[position]) {
|
||||
position++
|
||||
}
|
||||
if position > 0 {
|
||||
token.spacingNormalized = true
|
||||
}
|
||||
if position >= len(body) || body[position] == '!' {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
if body[position] == '/' {
|
||||
token.closing = true
|
||||
position++
|
||||
spaceStart := position
|
||||
for position < len(body) && isXMLSpace(body[position]) {
|
||||
position++
|
||||
}
|
||||
if position > spaceStart {
|
||||
token.spacingNormalized = true
|
||||
}
|
||||
}
|
||||
if position >= len(body) || !isTagNameStart(body[position]) {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
nameStart := position
|
||||
position++
|
||||
for position < len(body) && isTagNamePart(body[position]) {
|
||||
position++
|
||||
}
|
||||
token.name = body[nameStart:position]
|
||||
rawRemainder := body[position:]
|
||||
remainder := strings.TrimRightFunc(rawRemainder, unicode.IsSpace)
|
||||
if token.closing {
|
||||
if strings.TrimSpace(remainder) != "" {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
return token, end, tokenOK
|
||||
}
|
||||
if strings.HasSuffix(remainder, "/") {
|
||||
if len(remainder) != len(rawRemainder) {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
token.selfClosing = true
|
||||
remainder = strings.TrimRightFunc(strings.TrimSuffix(remainder, "/"), unicode.IsSpace)
|
||||
}
|
||||
trimmedAttrs := strings.TrimLeftFunc(remainder, unicode.IsSpace)
|
||||
if trimmedAttrs != "" && !isAttributeNameStart(trimmedAttrs[0]) {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
var ok bool
|
||||
token.attrs, ok = parseStrictAttributes(remainder)
|
||||
if !ok {
|
||||
return xmlToken{}, end, tokenInvalid
|
||||
}
|
||||
return token, end, tokenOK
|
||||
}
|
||||
|
||||
func isXMLSpace(ch byte) bool {
|
||||
return ch == ' ' || ch == '\t' || ch == '\r' || ch == '\n'
|
||||
}
|
||||
|
||||
func isTagNameStart(ch byte) bool {
|
||||
return ch >= 'A' && ch <= 'Z' || ch >= 'a' && ch <= 'z'
|
||||
}
|
||||
|
||||
func isTagNamePart(ch byte) bool {
|
||||
return isTagNameStart(ch) || ch >= '0' && ch <= '9' || ch == '_' || ch == '-' || ch == '.' || ch == ':'
|
||||
}
|
||||
|
||||
func isAttributeNameStart(ch byte) bool {
|
||||
return isTagNameStart(ch) || ch == '_' || ch == ':'
|
||||
}
|
||||
|
||||
func parseAttributes(source string) map[string]string {
|
||||
attrs := map[string]string{}
|
||||
for i := 0; i < len(source); {
|
||||
for i < len(source) && unicode.IsSpace(rune(source[i])) {
|
||||
i++
|
||||
}
|
||||
if i >= len(source) {
|
||||
break
|
||||
}
|
||||
start := i
|
||||
for i < len(source) && isAttributeNameByte(source[i]) {
|
||||
i++
|
||||
}
|
||||
if start == i {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
name := source[start:i]
|
||||
for i < len(source) && unicode.IsSpace(rune(source[i])) {
|
||||
i++
|
||||
}
|
||||
value := ""
|
||||
if i < len(source) && source[i] == '=' {
|
||||
i++
|
||||
for i < len(source) && unicode.IsSpace(rune(source[i])) {
|
||||
i++
|
||||
}
|
||||
if i < len(source) && (source[i] == '\'' || source[i] == '"') {
|
||||
quote := source[i]
|
||||
i++
|
||||
start = i
|
||||
for i < len(source) && source[i] != quote {
|
||||
i++
|
||||
}
|
||||
value = source[start:i]
|
||||
if i < len(source) {
|
||||
i++
|
||||
}
|
||||
} else {
|
||||
start = i
|
||||
for i < len(source) && !unicode.IsSpace(rune(source[i])) {
|
||||
i++
|
||||
}
|
||||
value = source[start:i]
|
||||
}
|
||||
}
|
||||
attrs[name] = html.UnescapeString(value)
|
||||
}
|
||||
if len(attrs) == 0 {
|
||||
return nil
|
||||
}
|
||||
return attrs
|
||||
}
|
||||
|
||||
// parseStrictAttributes implements the quoted attribute grammar accepted by
|
||||
// XML. parseAttributes remains intentionally permissive for the Markdown
|
||||
// container extension, whose input is Markdown rather than an XML document.
|
||||
func parseStrictAttributes(source string) (map[string]string, bool) {
|
||||
attrs := map[string]string{}
|
||||
for i := 0; i < len(source); {
|
||||
spaceStart := i
|
||||
for i < len(source) && isXMLSpace(source[i]) {
|
||||
i++
|
||||
}
|
||||
if i >= len(source) {
|
||||
break
|
||||
}
|
||||
if i == spaceStart || !isAttributeNameStart(source[i]) {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
nameStart := i
|
||||
i++
|
||||
for i < len(source) && isTagNamePart(source[i]) {
|
||||
i++
|
||||
}
|
||||
name := source[nameStart:i]
|
||||
if _, exists := attrs[name]; exists {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
for i < len(source) && isXMLSpace(source[i]) {
|
||||
i++
|
||||
}
|
||||
if i >= len(source) || source[i] != '=' {
|
||||
return nil, false
|
||||
}
|
||||
i++
|
||||
for i < len(source) && isXMLSpace(source[i]) {
|
||||
i++
|
||||
}
|
||||
if i >= len(source) || (source[i] != '\'' && source[i] != '"') {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
quote := source[i]
|
||||
i++
|
||||
valueStart := i
|
||||
for i < len(source) && source[i] != quote {
|
||||
if source[i] == '<' {
|
||||
return nil, false
|
||||
}
|
||||
i++
|
||||
}
|
||||
if i >= len(source) {
|
||||
return nil, false
|
||||
}
|
||||
rawValue := normalizeXMLAttributeAmpersands(source[valueStart:i])
|
||||
if invalidXMLEntityAt(rawValue) >= 0 {
|
||||
return nil, false
|
||||
}
|
||||
attrs[name] = html.UnescapeString(rawValue)
|
||||
i++
|
||||
}
|
||||
if len(attrs) == 0 {
|
||||
return nil, true
|
||||
}
|
||||
return attrs, true
|
||||
}
|
||||
|
||||
func isAttributeNameByte(ch byte) bool {
|
||||
return ch > ' ' && ch != '=' && ch != '/' && ch != '>'
|
||||
}
|
||||
|
||||
func appendText(parent *Node, raw string) {
|
||||
if parent == nil || raw == "" {
|
||||
return
|
||||
}
|
||||
appendTextValue(parent, html.UnescapeString(raw))
|
||||
}
|
||||
|
||||
func appendTextValue(parent *Node, text string) {
|
||||
if parent == nil || text == "" {
|
||||
return
|
||||
}
|
||||
if strings.TrimSpace(text) == "" && !preserveSpaceTags[parent.tag] && parent.tag != "whiteboard" {
|
||||
return
|
||||
}
|
||||
if count := len(parent.children); count > 0 && parent.children[count-1].typ == nodeText {
|
||||
parent.children[count-1].text += text
|
||||
return
|
||||
}
|
||||
parent.addChild(newText(text))
|
||||
}
|
||||
|
||||
func validateXMLText(value string, absoluteOffset int) error {
|
||||
if offset := strings.Index(value, "]]>"); offset >= 0 {
|
||||
return fmt.Errorf("invalid ]]> sequence in XML text at byte %d", absoluteOffset+offset)
|
||||
}
|
||||
if offset := invalidXMLEntityAt(value); offset >= 0 {
|
||||
return fmt.Errorf("invalid XML entity at byte %d", absoluteOffset+offset)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func invalidXMLEntityAt(value string) int {
|
||||
for cursor := 0; cursor < len(value); {
|
||||
relative := strings.IndexByte(value[cursor:], '&')
|
||||
if relative < 0 {
|
||||
return -1
|
||||
}
|
||||
start := cursor + relative
|
||||
endRelative := strings.IndexByte(value[start+1:], ';')
|
||||
if endRelative < 0 {
|
||||
return start
|
||||
}
|
||||
end := start + 1 + endRelative
|
||||
if !isValidXMLEntity(value[start+1 : end]) {
|
||||
return start
|
||||
}
|
||||
cursor = end + 1
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
func isValidXMLEntity(entity string) bool {
|
||||
switch entity {
|
||||
case "amp", "lt", "gt", "quot", "apos":
|
||||
return true
|
||||
}
|
||||
|
||||
base := 10
|
||||
digits := ""
|
||||
switch {
|
||||
case strings.HasPrefix(entity, "#x"):
|
||||
base = 16
|
||||
digits = entity[2:]
|
||||
case strings.HasPrefix(entity, "#"):
|
||||
digits = entity[1:]
|
||||
default:
|
||||
return false
|
||||
}
|
||||
if digits == "" {
|
||||
return false
|
||||
}
|
||||
value, err := strconv.ParseUint(digits, base, 32)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
r := rune(value)
|
||||
return r == '\t' || r == '\n' || r == '\r' ||
|
||||
r >= 0x20 && r <= 0xD7FF ||
|
||||
r >= 0xE000 && r <= 0xFFFD ||
|
||||
r >= 0x10000 && r <= utf8.MaxRune
|
||||
}
|
||||
62
shortcuts/doc/internal/docxparse/xml_compat.go
Normal file
62
shortcuts/doc/internal/docxparse/xml_compat.go
Normal file
@@ -0,0 +1,62 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package docxparse
|
||||
|
||||
import "strings"
|
||||
|
||||
// normalizeXMLAttributeAmpersands escapes bare ampersands in an XML attribute
|
||||
// value so local parsing matches the server SDK. Complete entity references
|
||||
// remain untouched for the strict parser to validate.
|
||||
func normalizeXMLAttributeAmpersands(value string) string {
|
||||
firstBare := -1
|
||||
for cursor := 0; cursor < len(value); {
|
||||
relative := strings.IndexByte(value[cursor:], '&')
|
||||
if relative < 0 {
|
||||
break
|
||||
}
|
||||
ampersand := cursor + relative
|
||||
if isBareXMLAttributeAmpersand(value, ampersand) {
|
||||
firstBare = ampersand
|
||||
break
|
||||
}
|
||||
cursor = ampersand + 1
|
||||
}
|
||||
if firstBare < 0 {
|
||||
return value
|
||||
}
|
||||
|
||||
var out strings.Builder
|
||||
out.Grow(len(value))
|
||||
out.WriteString(value[:firstBare])
|
||||
|
||||
for i := firstBare; i < len(value); i++ {
|
||||
if value[i] == '&' && isBareXMLAttributeAmpersand(value, i) {
|
||||
out.WriteString("&")
|
||||
continue
|
||||
}
|
||||
out.WriteByte(value[i])
|
||||
}
|
||||
return out.String()
|
||||
}
|
||||
|
||||
func isBareXMLAttributeAmpersand(value string, start int) bool {
|
||||
if start+1 >= len(value) {
|
||||
return true
|
||||
}
|
||||
if value[start+1] == '#' {
|
||||
return false
|
||||
}
|
||||
if !isTagNameStart(value[start+1]) && value[start+1] != '_' {
|
||||
return true
|
||||
}
|
||||
for i := start + 2; i < len(value); i++ {
|
||||
if value[i] == ';' {
|
||||
return false
|
||||
}
|
||||
if !isTagNamePart(value[i]) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
@@ -33,6 +33,8 @@ func docsSkillReadCommandForShortcut(shortcut string) string {
|
||||
return docsSkillReadCommand + " references/lark-doc-update.md"
|
||||
case "history-list", "history-revert", "history-revert-status":
|
||||
return docsSkillReadCommand + " references/lark-doc-history.md"
|
||||
case "script":
|
||||
return docsSkillReadCommand + " references/lark-doc-script.md"
|
||||
default:
|
||||
return docsSkillReadCommand
|
||||
}
|
||||
@@ -52,6 +54,8 @@ func docsHelpCommandForShortcut(shortcut string) string {
|
||||
return "lark-cli docs +history-revert --help"
|
||||
case "history-revert-status":
|
||||
return "lark-cli docs +history-revert-status --help"
|
||||
case "script":
|
||||
return "lark-cli docs +script --help"
|
||||
default:
|
||||
return "lark-cli docs --help"
|
||||
}
|
||||
@@ -64,6 +68,7 @@ func Shortcuts() []common.Shortcut {
|
||||
DocsCreate,
|
||||
DocsFetch,
|
||||
DocsUpdate,
|
||||
DocsScript,
|
||||
DocsHistoryList,
|
||||
DocsHistoryRevert,
|
||||
DocsHistoryRevertStatus,
|
||||
|
||||
@@ -24,9 +24,12 @@ type batchCreateKR struct {
|
||||
|
||||
// batchCreateObjective represents an objective in the batch create input.
|
||||
type batchCreateObjective struct {
|
||||
Text string `json:"text"`
|
||||
Mention []string `json:"mention,omitempty"`
|
||||
KRs []batchCreateKR `json:"krs,omitempty"`
|
||||
Text string `json:"text"`
|
||||
Mention []string `json:"mention,omitempty"`
|
||||
Notes string `json:"notes,omitempty"`
|
||||
NotesMention []string `json:"notes_mention,omitempty"`
|
||||
CategoryID string `json:"category_id,omitempty"`
|
||||
KRs []batchCreateKR `json:"krs,omitempty"`
|
||||
}
|
||||
|
||||
// createdObjective tracks a created objective and its KR IDs for output.
|
||||
@@ -49,6 +52,25 @@ func parseBatchCreateInput(input string) ([]batchCreateObjective, error) {
|
||||
if strings.TrimSpace(obj.Text) == "" {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "objective[%d].text is required and cannot be empty", i).WithParam("--input")
|
||||
}
|
||||
if obj.Notes != "" && strings.TrimSpace(obj.Notes) == "" {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "objective[%d].notes cannot be blank when provided", i).WithParam("--input")
|
||||
}
|
||||
if obj.Notes == "" && len(obj.NotesMention) > 0 {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "objective[%d].notes is required when notes_mention is provided", i).WithParam("--input")
|
||||
}
|
||||
for j, mention := range obj.NotesMention {
|
||||
if strings.TrimSpace(mention) == "" {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "objective[%d].notes_mention[%d] cannot be empty", i, j).WithParam("--input")
|
||||
}
|
||||
}
|
||||
if obj.CategoryID != "" {
|
||||
if strings.TrimSpace(obj.CategoryID) == "" {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "objective[%d].category_id cannot be blank when provided", i).WithParam("--input")
|
||||
}
|
||||
if id, err := strconv.ParseInt(obj.CategoryID, 10, 64); err != nil || id <= 0 {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "objective[%d].category_id must be a positive int64", i).WithParam("--input")
|
||||
}
|
||||
}
|
||||
for j, kr := range obj.KRs {
|
||||
if strings.TrimSpace(kr.Text) == "" {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "objective[%d].krs[%d].text is required and cannot be empty", i, j).WithParam("--input")
|
||||
@@ -59,11 +81,24 @@ func parseBatchCreateInput(input string) ([]batchCreateObjective, error) {
|
||||
}
|
||||
|
||||
// createObjective calls the API to create an objective.
|
||||
func createObjective(ctx context.Context, runtime *common.RuntimeContext, cycleID, userIDType string, obj batchCreateObjective) (string, error) {
|
||||
func effectiveBatchObjectiveCategoryID(defaultCategoryID string, obj batchCreateObjective) string {
|
||||
if obj.CategoryID != "" {
|
||||
return obj.CategoryID
|
||||
}
|
||||
return defaultCategoryID
|
||||
}
|
||||
|
||||
func createObjective(ctx context.Context, runtime *common.RuntimeContext, cycleID, userIDType, defaultCategoryID string, obj batchCreateObjective) (string, error) {
|
||||
content := BuildContentBlock(obj.Text, obj.Mention)
|
||||
body := map[string]interface{}{
|
||||
"content": content,
|
||||
}
|
||||
if obj.Notes != "" {
|
||||
body["notes"] = BuildContentBlock(obj.Notes, obj.NotesMention)
|
||||
}
|
||||
if categoryID := effectiveBatchObjectiveCategoryID(defaultCategoryID, obj); categoryID != "" {
|
||||
body["category_id"] = categoryID
|
||||
}
|
||||
queryParams := map[string]interface{}{
|
||||
"cycle_id": cycleID,
|
||||
"user_id_type": userIDType,
|
||||
@@ -156,6 +191,7 @@ var OKRBatchCreate = common.Shortcut{
|
||||
Flags: []common.Flag{
|
||||
{Name: "cycle-id", Desc: "OKR cycle ID (int64)", Required: true},
|
||||
{Name: "input", Desc: "JSON array of objectives: [{\"text\":\"...\",\"mention\":[\"...\"],\"krs\":[{\"text\":\"...\",\"mention\":[\"...\"]}]}]", Input: []string{common.File, common.Stdin}, Required: true},
|
||||
{Name: "category-id", Desc: "default objective category ID for objectives that do not set category_id"},
|
||||
{Name: "user-id-type", Default: "open_id", Desc: "user ID type: open_id | union_id | user_id"},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
@@ -171,6 +207,15 @@ var OKRBatchCreate = common.Shortcut{
|
||||
if _, err := parseBatchCreateInput(input); err != nil {
|
||||
return err
|
||||
}
|
||||
categoryID := runtime.Str("category-id")
|
||||
if categoryID != "" {
|
||||
if err := common.RejectDangerousCharsTyped("--category-id", categoryID); err != nil {
|
||||
return err
|
||||
}
|
||||
if id, err := strconv.ParseInt(categoryID, 10, 64); err != nil || id <= 0 {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--category-id must be a positive int64").WithParam("--category-id")
|
||||
}
|
||||
}
|
||||
|
||||
idType := runtime.Str("user-id-type")
|
||||
if idType != "open_id" && idType != "union_id" && idType != "user_id" {
|
||||
@@ -182,6 +227,7 @@ var OKRBatchCreate = common.Shortcut{
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
cycleID := runtime.Str("cycle-id")
|
||||
userIDType := runtime.Str("user-id-type")
|
||||
defaultCategoryID := runtime.Str("category-id")
|
||||
objectives, _ := parseBatchCreateInput(runtime.Str("input"))
|
||||
|
||||
apis := common.NewDryRunAPI()
|
||||
@@ -192,6 +238,12 @@ var OKRBatchCreate = common.Shortcut{
|
||||
objBody := map[string]interface{}{
|
||||
"content": objContent,
|
||||
}
|
||||
if obj.Notes != "" {
|
||||
objBody["notes"] = BuildContentBlock(obj.Notes, obj.NotesMention)
|
||||
}
|
||||
if categoryID := effectiveBatchObjectiveCategoryID(defaultCategoryID, obj); categoryID != "" {
|
||||
objBody["category_id"] = categoryID
|
||||
}
|
||||
objParams := map[string]interface{}{
|
||||
"cycle_id": cycleID,
|
||||
"user_id_type": userIDType,
|
||||
@@ -227,6 +279,7 @@ var OKRBatchCreate = common.Shortcut{
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
cycleID := runtime.Str("cycle-id")
|
||||
userIDType := runtime.Str("user-id-type")
|
||||
defaultCategoryID := runtime.Str("category-id")
|
||||
objectives, err := parseBatchCreateInput(runtime.Str("input"))
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -241,7 +294,7 @@ var OKRBatchCreate = common.Shortcut{
|
||||
}
|
||||
|
||||
// Create objective
|
||||
objectiveID, err := createObjective(ctx, runtime, cycleID, userIDType, obj)
|
||||
objectiveID, err := createObjective(ctx, runtime, cycleID, userIDType, defaultCategoryID, obj)
|
||||
if err != nil {
|
||||
if len(created) == 0 {
|
||||
return err
|
||||
|
||||
@@ -6,6 +6,8 @@ package okr
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -14,6 +16,7 @@ import (
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func batchCreateTestConfig(t *testing.T) *core.CliConfig {
|
||||
@@ -43,6 +46,15 @@ const validBatchCreateInput = `[
|
||||
{"text":"Objective 2","krs":[{"text":"KR 2.1"},{"text":"KR 2.2"}]}
|
||||
]`
|
||||
|
||||
const validBatchCreateInputWithNotes = `[
|
||||
{"text":"Objective 1","notes":"Objective notes","notes_mention":["ou_note"],"krs":[{"text":"KR 1.1"}]}
|
||||
]`
|
||||
|
||||
const validBatchCreateInputWithCategory = `[
|
||||
{"text":"Objective 1","category_id":"222","krs":[{"text":"KR 1.1"}]},
|
||||
{"text":"Objective 2","krs":[]}
|
||||
]`
|
||||
|
||||
// --- Validate tests ---
|
||||
|
||||
func TestBatchCreateValidate_MissingCycleID(t *testing.T) {
|
||||
@@ -197,6 +209,46 @@ func TestBatchCreateValidate_EmptyKRText(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchCreateValidate_EmptyObjectiveNotesMention(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, batchCreateTestConfig(t))
|
||||
err := runBatchCreateShortcut(t, f, stdout, []string{
|
||||
"+batch-create",
|
||||
"--cycle-id", "123",
|
||||
"--input", `[{"text":"Obj 1","notes":"Notes","notes_mention":[" "]}]`,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for empty objective notes mention")
|
||||
}
|
||||
validationErr, ok := err.(*errs.ValidationError)
|
||||
if !ok || validationErr.Param != "--input" {
|
||||
t.Fatalf("expected param --input, got: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "objective[0].notes_mention[0]") {
|
||||
t.Fatalf("expected error to mention objective[0].notes_mention[0], got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchCreateValidate_NotesMentionRequiresNotes(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, batchCreateTestConfig(t))
|
||||
err := runBatchCreateShortcut(t, f, stdout, []string{
|
||||
"+batch-create",
|
||||
"--cycle-id", "123",
|
||||
"--input", `[{"text":"Obj 1","notes_mention":["ou_note"]}]`,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for notes_mention without notes")
|
||||
}
|
||||
validationErr, ok := err.(*errs.ValidationError)
|
||||
if !ok || validationErr.Param != "--input" {
|
||||
t.Fatalf("expected param --input, got: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "objective[0].notes is required when notes_mention is provided") {
|
||||
t.Fatalf("expected error to mention missing notes, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchCreateValidate_InvalidUserIDType(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, batchCreateTestConfig(t))
|
||||
@@ -323,6 +375,49 @@ func TestBatchCreateDryRun(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchCreateDryRun_WithObjectiveNotes(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, batchCreateTestConfig(t))
|
||||
err := runBatchCreateShortcut(t, f, stdout, []string{
|
||||
"+batch-create",
|
||||
"--cycle-id", "123",
|
||||
"--input", validBatchCreateInputWithNotes,
|
||||
"--dry-run",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
output := stdout.String()
|
||||
if !strings.Contains(output, "Objective notes") {
|
||||
t.Fatalf("dry-run output should contain objective notes, got: %s", output)
|
||||
}
|
||||
if !strings.Contains(output, "ou_note") {
|
||||
t.Fatalf("dry-run output should contain objective notes mention, got: %s", output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchCreateDryRun_WithCategoryID(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, batchCreateTestConfig(t))
|
||||
err := runBatchCreateShortcut(t, f, stdout, []string{
|
||||
"+batch-create",
|
||||
"--cycle-id", "123",
|
||||
"--category-id", "111",
|
||||
"--input", validBatchCreateInputWithCategory,
|
||||
"--dry-run",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
output := stdout.String()
|
||||
if got := gjson.Get(output, "data.api.0.body.category_id").String(); got != "222" {
|
||||
t.Fatalf("first objective category_id = %q, want per-objective override 222; output: %s", got, output)
|
||||
}
|
||||
if got := gjson.Get(output, "data.api.2.body.category_id").String(); got != "111" {
|
||||
t.Fatalf("second objective category_id = %q, want default 111; output: %s", got, output)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Execute tests ---
|
||||
|
||||
func TestBatchCreateExecute_Success(t *testing.T) {
|
||||
@@ -380,6 +475,94 @@ func TestBatchCreateExecute_Success(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchCreateExecute_ObjectiveWithNotes(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, batchCreateTestConfig(t))
|
||||
var objectiveBody []byte
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/okr/v2/cycles/123/objectives",
|
||||
OnMatch: func(req *http.Request) {
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read objective request body: %v", err)
|
||||
}
|
||||
objectiveBody = body
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"objective_id": "100",
|
||||
},
|
||||
},
|
||||
})
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/okr/v2/objectives/100/key_results",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"key_result_id": "200",
|
||||
},
|
||||
},
|
||||
})
|
||||
err := runBatchCreateShortcut(t, f, stdout, []string{
|
||||
"+batch-create",
|
||||
"--cycle-id", "123",
|
||||
"--input", validBatchCreateInputWithNotes,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if !gjson.GetBytes(objectiveBody, "notes.blocks.0.paragraph.elements.0.text_run.text").Exists() {
|
||||
t.Fatalf("objective request body missing notes: %s", string(objectiveBody))
|
||||
}
|
||||
if got := gjson.GetBytes(objectiveBody, "notes.blocks.0.paragraph.elements.0.text_run.text").String(); got != "Objective notes" {
|
||||
t.Fatalf("notes text = %q, want Objective notes; body: %s", got, string(objectiveBody))
|
||||
}
|
||||
if got := gjson.GetBytes(objectiveBody, "notes.blocks.0.paragraph.elements.1.mention.user_id").String(); got != "ou_note" {
|
||||
t.Fatalf("notes mention = %q, want ou_note; body: %s", got, string(objectiveBody))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchCreateExecute_ObjectiveWithCategoryID(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, batchCreateTestConfig(t))
|
||||
var objectiveBody []byte
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/okr/v2/cycles/123/objectives",
|
||||
OnMatch: func(req *http.Request) {
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
t.Fatalf("read objective request body: %v", err)
|
||||
}
|
||||
objectiveBody = body
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"objective_id": "100",
|
||||
},
|
||||
},
|
||||
})
|
||||
err := runBatchCreateShortcut(t, f, stdout, []string{
|
||||
"+batch-create",
|
||||
"--cycle-id", "123",
|
||||
"--category-id", "7249339036661170180",
|
||||
"--input", `[{"text":"Obj 1"}]`,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := gjson.GetBytes(objectiveBody, "category_id").String(); got != "7249339036661170180" {
|
||||
t.Fatalf("category_id = %q, want 7249339036661170180; body: %s", got, string(objectiveBody))
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchCreateExecute_APIErrorOnObjective(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, batchCreateTestConfig(t))
|
||||
|
||||
394
shortcuts/okr/okr_create.go
Normal file
394
shortcuts/okr/okr_create.go
Normal file
@@ -0,0 +1,394 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package okr
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
// createParams holds the parsed parameters for single-object create operations.
|
||||
type createParams struct {
|
||||
Level string
|
||||
CycleID string
|
||||
ObjectiveID string
|
||||
Style string
|
||||
Content *ContentBlock
|
||||
Notes *ContentBlock
|
||||
CategoryID string
|
||||
UserIDType string
|
||||
}
|
||||
|
||||
type createContentMultipleJSONValuesError struct{}
|
||||
|
||||
func (createContentMultipleJSONValuesError) Error() string {
|
||||
return "multiple JSON values"
|
||||
}
|
||||
|
||||
var errCreateContentMultipleJSONValues createContentMultipleJSONValuesError
|
||||
|
||||
type okrCreateRequestBody struct {
|
||||
Content *ContentBlock `json:"content"`
|
||||
Notes *ContentBlock `json:"notes,omitempty"`
|
||||
CategoryID string `json:"category_id,omitempty"`
|
||||
}
|
||||
|
||||
type okrCreateObjectiveQuery struct {
|
||||
CycleID string
|
||||
UserIDType string
|
||||
}
|
||||
|
||||
type okrCreateKeyResultQuery struct {
|
||||
ObjectiveID string
|
||||
UserIDType string
|
||||
}
|
||||
|
||||
type okrCreateObjectiveResponse struct {
|
||||
ObjectiveID string
|
||||
}
|
||||
|
||||
type okrCreateKeyResultResponse struct {
|
||||
KeyResultID string
|
||||
}
|
||||
|
||||
type okrCreateObjectiveOutput struct {
|
||||
Level string `json:"level"`
|
||||
ObjectiveID string `json:"objective_id"`
|
||||
}
|
||||
|
||||
type okrCreateKeyResultOutput struct {
|
||||
Level string `json:"level"`
|
||||
ObjectiveID string `json:"objective_id"`
|
||||
KeyResultID string `json:"key_result_id"`
|
||||
}
|
||||
|
||||
func decodeCreateContentStrict(inputStr string, target interface{}, param, message string) error {
|
||||
dec := json.NewDecoder(bytes.NewReader([]byte(inputStr)))
|
||||
dec.DisallowUnknownFields()
|
||||
if err := dec.Decode(target); err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, message, err).
|
||||
WithParam(param).
|
||||
WithCause(err)
|
||||
}
|
||||
var trailing interface{}
|
||||
if err := dec.Decode(&trailing); !errors.Is(err, io.EOF) {
|
||||
if err == nil {
|
||||
err = errCreateContentMultipleJSONValues
|
||||
}
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, message, err).
|
||||
WithParam(param).
|
||||
WithCause(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func parseCreateContentValue(inputStr, param, style string) (*ContentBlock, error) {
|
||||
if style == "simple" {
|
||||
var sp SemiPlainContent
|
||||
if err := decodeCreateContentStrict(inputStr, &sp, param, fmt.Sprintf("%s must be valid semi-plain JSON: {\"text\":\"...\",\"mention\":[\"...\"]}: %%s", param)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(sp.Text) == "" {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "%s text is required and cannot be empty", param).WithParam(param)
|
||||
}
|
||||
for i, mention := range sp.Mention {
|
||||
if strings.TrimSpace(mention) == "" {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "%s mention[%d] cannot be empty", param, i).WithParam(param)
|
||||
}
|
||||
}
|
||||
if len(sp.Docs) > 0 || len(sp.Images) > 0 {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "%s docs and images are not supported in simple style input; use richtext style or remove these fields", param).WithParam(param)
|
||||
}
|
||||
return sp.ToContentBlock(), nil
|
||||
}
|
||||
|
||||
var cb ContentBlock
|
||||
if err := decodeCreateContentStrict(inputStr, &cb, param, fmt.Sprintf("%s must be valid ContentBlock JSON: %%s", param)); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if len(cb.Blocks) == 0 {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "%s must contain at least one block", param).WithParam(param)
|
||||
}
|
||||
|
||||
hasNonEmptyParagraph := false
|
||||
for _, block := range cb.Blocks {
|
||||
if block.Paragraph != nil && len(block.Paragraph.Elements) > 0 {
|
||||
hasNonEmptyParagraph = true
|
||||
break
|
||||
}
|
||||
if block.Gallery != nil && len(block.Gallery.Images) > 0 {
|
||||
hasNonEmptyParagraph = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !hasNonEmptyParagraph {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "%s cannot be empty", param).WithParam(param)
|
||||
}
|
||||
return &cb, nil
|
||||
}
|
||||
|
||||
func projectCreateRequestBody(body okrCreateRequestBody) map[string]interface{} {
|
||||
result := map[string]interface{}{
|
||||
"content": body.Content,
|
||||
}
|
||||
if body.Notes != nil {
|
||||
result["notes"] = body.Notes
|
||||
}
|
||||
if body.CategoryID != "" {
|
||||
result["category_id"] = body.CategoryID
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func projectCreateObjectiveQuery(query okrCreateObjectiveQuery) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"cycle_id": query.CycleID,
|
||||
"user_id_type": query.UserIDType,
|
||||
}
|
||||
}
|
||||
|
||||
func projectCreateKeyResultQuery(query okrCreateKeyResultQuery) map[string]interface{} {
|
||||
return map[string]interface{}{
|
||||
"objective_id": query.ObjectiveID,
|
||||
"user_id_type": query.UserIDType,
|
||||
}
|
||||
}
|
||||
|
||||
func projectCreateObjectiveResponse(data map[string]interface{}) (*okrCreateObjectiveResponse, error) {
|
||||
objectiveID, ok := data["objective_id"].(string)
|
||||
if !ok || objectiveID == "" {
|
||||
return nil, errs.NewInternalError(errs.SubtypeUnknown, "create objective response missing objective_id")
|
||||
}
|
||||
return &okrCreateObjectiveResponse{ObjectiveID: objectiveID}, nil
|
||||
}
|
||||
|
||||
func projectCreateKeyResultResponse(data map[string]interface{}) (*okrCreateKeyResultResponse, error) {
|
||||
keyResultID, ok := data["key_result_id"].(string)
|
||||
if !ok || keyResultID == "" {
|
||||
return nil, errs.NewInternalError(errs.SubtypeUnknown, "create key result response missing key_result_id")
|
||||
}
|
||||
return &okrCreateKeyResultResponse{KeyResultID: keyResultID}, nil
|
||||
}
|
||||
|
||||
// parseCreateParams parses and validates flags from runtime into request-ready parameters.
|
||||
func parseCreateParams(runtime *common.RuntimeContext) (*createParams, error) {
|
||||
p := &createParams{
|
||||
Level: runtime.Str("level"),
|
||||
CycleID: runtime.Str("cycle-id"),
|
||||
ObjectiveID: runtime.Str("objective-id"),
|
||||
Style: runtime.Str("style"),
|
||||
CategoryID: runtime.Str("category-id"),
|
||||
UserIDType: runtime.Str("user-id-type"),
|
||||
}
|
||||
|
||||
contentStr := runtime.Str("content")
|
||||
if contentStr == "" {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--content is required").WithParam("--content")
|
||||
}
|
||||
if err := common.RejectDangerousCharsTyped("--content", contentStr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
content, err := parseCreateContentValue(contentStr, "--content", p.Style)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Content = content
|
||||
|
||||
if notesStr := runtime.Str("notes"); notesStr != "" {
|
||||
if p.Level != "objective" {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--notes is only supported when --level=objective").WithParam("--notes")
|
||||
}
|
||||
if err := common.RejectDangerousCharsTyped("--notes", notesStr); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
notes, err := parseCreateContentValue(notesStr, "--notes", p.Style)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
p.Notes = notes
|
||||
}
|
||||
if p.CategoryID != "" {
|
||||
if p.Level != "objective" {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--category-id is only supported when --level=objective").WithParam("--category-id")
|
||||
}
|
||||
if err := common.RejectDangerousCharsTyped("--category-id", p.CategoryID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if id, err := strconv.ParseInt(p.CategoryID, 10, 64); err != nil || id <= 0 {
|
||||
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument, "--category-id must be a positive int64").WithParam("--category-id")
|
||||
}
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
|
||||
// OKRCreate creates a single objective or key result.
|
||||
var OKRCreate = common.Shortcut{
|
||||
Service: "okr",
|
||||
Command: "+create",
|
||||
Description: "Create a single OKR objective or key result",
|
||||
Risk: "write",
|
||||
Scopes: []string{"okr:okr.content:writeonly"},
|
||||
AuthTypes: []string{"user", "bot"},
|
||||
HasFormat: true,
|
||||
Flags: []common.Flag{
|
||||
{Name: "level", Desc: "create level: objective | key-result", Required: true, Enum: []string{"objective", "key-result"}},
|
||||
{Name: "cycle-id", Desc: "OKR cycle ID (required for level=objective)"},
|
||||
{Name: "objective-id", Desc: "objective ID (required for level=key-result)"},
|
||||
{Name: "style", Default: "simple", Desc: "input style for content: simple (semi-plain text JSON) | richtext (ContentBlock JSON)", Enum: []string{"simple", "richtext"}},
|
||||
{Name: "content", Desc: "content: semi-plain JSON {\"text\":\"...\",\"mention\":[\"...\"]} (simple) or ContentBlock JSON (richtext)", Required: true, Input: []string{common.File, common.Stdin}},
|
||||
{Name: "notes", Desc: "objective notes: semi-plain JSON {\"text\":\"...\",\"mention\":[\"...\"]} (simple) or ContentBlock JSON (richtext)", Input: []string{common.File, common.Stdin}},
|
||||
{Name: "category-id", Desc: "objective category ID; use only when classification is requested or the tenant requires categories"},
|
||||
{Name: "user-id-type", Default: "open_id", Desc: "user ID type: open_id | union_id | user_id"},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
level := runtime.Str("level")
|
||||
if level != "objective" && level != "key-result" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--level must be one of: objective | key-result").WithParam("--level")
|
||||
}
|
||||
|
||||
style := runtime.Str("style")
|
||||
if style != "simple" && style != "richtext" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--style must be one of: simple | richtext").WithParam("--style")
|
||||
}
|
||||
|
||||
idType := runtime.Str("user-id-type")
|
||||
if idType != "open_id" && idType != "union_id" && idType != "user_id" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--user-id-type must be one of: open_id | union_id | user_id").WithParam("--user-id-type")
|
||||
}
|
||||
|
||||
switch level {
|
||||
case "objective":
|
||||
if runtime.Str("objective-id") != "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--objective-id cannot be used when --level=objective").WithParam("--objective-id")
|
||||
}
|
||||
cycleID := runtime.Str("cycle-id")
|
||||
if cycleID == "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--cycle-id is required when --level=objective").WithParam("--cycle-id")
|
||||
}
|
||||
if err := common.RejectDangerousCharsTyped("--cycle-id", cycleID); err != nil {
|
||||
return err
|
||||
}
|
||||
if id, err := strconv.ParseInt(cycleID, 10, 64); err != nil || id <= 0 {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--cycle-id must be a positive int64").WithParam("--cycle-id")
|
||||
}
|
||||
case "key-result":
|
||||
if runtime.Str("cycle-id") != "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--cycle-id cannot be used when --level=key-result").WithParam("--cycle-id")
|
||||
}
|
||||
objectiveID := runtime.Str("objective-id")
|
||||
if objectiveID == "" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--objective-id is required when --level=key-result").WithParam("--objective-id")
|
||||
}
|
||||
if err := common.RejectDangerousCharsTyped("--objective-id", objectiveID); err != nil {
|
||||
return err
|
||||
}
|
||||
if id, err := strconv.ParseInt(objectiveID, 10, 64); err != nil || id <= 0 {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--objective-id must be a positive int64").WithParam("--objective-id")
|
||||
}
|
||||
}
|
||||
|
||||
_, err := parseCreateParams(runtime)
|
||||
return err
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
p, err := parseCreateParams(runtime)
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().
|
||||
POST("").
|
||||
Desc(fmt.Sprintf("Dry-run skipped: %s", err.Error()))
|
||||
}
|
||||
|
||||
body := projectCreateRequestBody(okrCreateRequestBody{Content: p.Content, Notes: p.Notes, CategoryID: p.CategoryID})
|
||||
|
||||
if p.Level == "objective" {
|
||||
params := projectCreateObjectiveQuery(okrCreateObjectiveQuery{
|
||||
CycleID: p.CycleID,
|
||||
UserIDType: p.UserIDType,
|
||||
})
|
||||
return common.NewDryRunAPI().
|
||||
POST("/open-apis/okr/v2/cycles/:cycle_id/objectives").
|
||||
Set("cycle_id", p.CycleID).
|
||||
Params(params).
|
||||
Body(body).
|
||||
Desc("Create OKR objective")
|
||||
}
|
||||
|
||||
params := projectCreateKeyResultQuery(okrCreateKeyResultQuery{
|
||||
ObjectiveID: p.ObjectiveID,
|
||||
UserIDType: p.UserIDType,
|
||||
})
|
||||
return common.NewDryRunAPI().
|
||||
POST("/open-apis/okr/v2/objectives/:objective_id/key_results").
|
||||
Set("objective_id", p.ObjectiveID).
|
||||
Params(params).
|
||||
Body(body).
|
||||
Desc("Create OKR key result")
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
p, err := parseCreateParams(runtime)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
body := projectCreateRequestBody(okrCreateRequestBody{Content: p.Content, Notes: p.Notes, CategoryID: p.CategoryID})
|
||||
|
||||
if p.Level == "objective" {
|
||||
queryParams := projectCreateObjectiveQuery(okrCreateObjectiveQuery{
|
||||
CycleID: p.CycleID,
|
||||
UserIDType: p.UserIDType,
|
||||
})
|
||||
path := fmt.Sprintf("/open-apis/okr/v2/cycles/%s/objectives", p.CycleID)
|
||||
data, err := runtime.CallAPITyped("POST", path, queryParams, body)
|
||||
if err != nil {
|
||||
return wrapOkrNetworkErr(err, "failed to create objective")
|
||||
}
|
||||
resp, err := projectCreateObjectiveResponse(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result := okrCreateObjectiveOutput{
|
||||
Level: p.Level,
|
||||
ObjectiveID: resp.ObjectiveID,
|
||||
}
|
||||
|
||||
runtime.OutFormat(result, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Created OKR objective [%s]\n", resp.ObjectiveID)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
queryParams := projectCreateKeyResultQuery(okrCreateKeyResultQuery{
|
||||
ObjectiveID: p.ObjectiveID,
|
||||
UserIDType: p.UserIDType,
|
||||
})
|
||||
path := fmt.Sprintf("/open-apis/okr/v2/objectives/%s/key_results", p.ObjectiveID)
|
||||
data, err := runtime.CallAPITyped("POST", path, queryParams, body)
|
||||
if err != nil {
|
||||
return wrapOkrNetworkErr(err, "failed to create key result")
|
||||
}
|
||||
resp, err := projectCreateKeyResultResponse(data)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result := okrCreateKeyResultOutput{
|
||||
Level: p.Level,
|
||||
ObjectiveID: p.ObjectiveID,
|
||||
KeyResultID: resp.KeyResultID,
|
||||
}
|
||||
|
||||
runtime.OutFormat(result, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Created OKR key-result [%s] under objective [%s]\n", resp.KeyResultID, p.ObjectiveID)
|
||||
})
|
||||
return nil
|
||||
},
|
||||
}
|
||||
707
shortcuts/okr/okr_create_test.go
Normal file
707
shortcuts/okr/okr_create_test.go
Normal file
@@ -0,0 +1,707 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package okr
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/tidwall/gjson"
|
||||
)
|
||||
|
||||
func createTestConfig(t *testing.T) *core.CliConfig {
|
||||
t.Helper()
|
||||
return &core.CliConfig{
|
||||
AppID: "test-okr-create",
|
||||
AppSecret: patchTestValue(),
|
||||
Brand: core.BrandFeishu,
|
||||
}
|
||||
}
|
||||
|
||||
func runCreateShortcut(t *testing.T, f *cmdutil.Factory, stdout *bytes.Buffer, args []string) error {
|
||||
t.Helper()
|
||||
parent := &cobra.Command{Use: "okr"}
|
||||
OKRCreate.Mount(parent, f)
|
||||
parent.SetArgs(args)
|
||||
parent.SilenceErrors = true
|
||||
parent.SilenceUsage = true
|
||||
if stdout != nil {
|
||||
stdout.Reset()
|
||||
}
|
||||
return parent.Execute()
|
||||
}
|
||||
|
||||
func runCreateShortcutWithStdin(t *testing.T, f *cmdutil.Factory, stdout *bytes.Buffer, stdin string, args []string) error {
|
||||
t.Helper()
|
||||
f.IOStreams.In = strings.NewReader(stdin)
|
||||
return runCreateShortcut(t, f, stdout, args)
|
||||
}
|
||||
|
||||
const (
|
||||
validCreateSimpleJSON = `{"text":"test objective","mention":["ou_123"]}`
|
||||
validCreateRichTextJSON = `{"blocks":[{"block_element_type":"paragraph","paragraph":{"elements":[{"paragraph_element_type":"textRun","text_run":{"text":"test content"}}]}}]}`
|
||||
emptyCreateRichTextJSON = `{"blocks":[]}`
|
||||
blankCreateRichTextJSON = `{"blocks":[{"block_element_type":"paragraph","paragraph":{"elements":[]}}]}`
|
||||
validCreateObjectiveArgs1 = "+create"
|
||||
)
|
||||
|
||||
func TestCreateValidate_MissingLevel(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
validCreateObjectiveArgs1,
|
||||
"--cycle-id", "123",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "level") {
|
||||
t.Fatalf("expected --level required error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_InvalidLevel(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "invalid",
|
||||
"--cycle-id", "123",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected invalid level error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("expected typed invalid argument error, got: %v", err)
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--level" {
|
||||
t.Fatalf("expected param --level, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_MissingCycleIDForObjective(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected missing cycle-id error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("expected typed invalid argument error, got: %v", err)
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--cycle-id" {
|
||||
t.Fatalf("expected param --cycle-id, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_InvalidCycleID(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "abc",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected invalid cycle-id error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("expected typed invalid argument error, got: %v", err)
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--cycle-id" {
|
||||
t.Fatalf("expected param --cycle-id, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_MissingObjectiveIDForKR(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "key-result",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected missing objective-id error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("expected typed invalid argument error, got: %v", err)
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--objective-id" {
|
||||
t.Fatalf("expected param --objective-id, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_RejectObjectiveIDForObjective(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--objective-id", "456",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected objective-id rejection")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--objective-id" {
|
||||
t.Fatalf("expected param --objective-id, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_RejectCycleIDForKeyResult(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "key-result",
|
||||
"--cycle-id", "123",
|
||||
"--objective-id", "456",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected cycle-id rejection")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--cycle-id" {
|
||||
t.Fatalf("expected param --cycle-id, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_RejectNotesForKeyResult(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "key-result",
|
||||
"--objective-id", "456",
|
||||
"--content", validCreateSimpleJSON,
|
||||
"--notes", `{"text":"objective only notes"}`,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected notes rejection for key-result")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--notes" {
|
||||
t.Fatalf("expected param --notes, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_RejectCategoryIDForKeyResult(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "key-result",
|
||||
"--objective-id", "456",
|
||||
"--content", validCreateSimpleJSON,
|
||||
"--category-id", "123",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected category-id rejection for key-result")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--category-id" {
|
||||
t.Fatalf("expected param --category-id, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_ContentAndNotesCannotBothReadStdin(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcutWithStdin(t, f, stdout, `{"text":"stdin content"}`, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--content", "-",
|
||||
"--notes", "-",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected duplicate stdin error")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--notes" {
|
||||
t.Fatalf("expected param --notes, got: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "stdin (-) can only be used by one flag") {
|
||||
t.Fatalf("expected duplicate stdin error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_InvalidObjectiveID(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "key-result",
|
||||
"--objective-id", "0",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected invalid objective-id error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("expected typed invalid argument error, got: %v", err)
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--objective-id" {
|
||||
t.Fatalf("expected param --objective-id, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_InvalidStyle(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--style", "invalid",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected invalid style error")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--style" {
|
||||
t.Fatalf("expected param --style, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_InvalidUserIDType(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--content", validCreateSimpleJSON,
|
||||
"--user-id-type", "invalid",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected invalid user-id-type error")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--user-id-type" {
|
||||
t.Fatalf("expected param --user-id-type, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_MissingContent(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
})
|
||||
if err == nil || !strings.Contains(err.Error(), "content") {
|
||||
t.Fatalf("expected required content error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_InvalidSimpleContentJSON(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--style", "simple",
|
||||
"--content", "not-json",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected invalid simple json error")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--content" {
|
||||
t.Fatalf("expected param --content, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_EmptySimpleText(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--style", "simple",
|
||||
"--content", `{"text":" "}`,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected empty simple text error")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--content" {
|
||||
t.Fatalf("expected param --content, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_EmptySimpleMention(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--style", "simple",
|
||||
"--content", `{"text":"test","mention":[""]}`,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected empty simple mention error")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--content" {
|
||||
t.Fatalf("expected param --content, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_SimpleContentRejectsDocsImages(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--style", "simple",
|
||||
"--content", `{"text":"test","docs":[{"title":"doc","url":"https://example.com"}],"images":["img"]}`,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected docs/images rejection")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--content" {
|
||||
t.Fatalf("expected param --content, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_SimpleContentRejectsUnknownFields(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--style", "simple",
|
||||
"--content", `{"text":"test","mentions":["ou_123"]}`,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected unknown simple content field error")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--content" {
|
||||
t.Fatalf("expected param --content, got: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "unknown field") {
|
||||
t.Fatalf("expected unknown field error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_InvalidRichTextJSON(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--style", "richtext",
|
||||
"--content", "not-json",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected invalid richtext json error")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--content" {
|
||||
t.Fatalf("expected param --content, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_RichTextRejectsUnknownFields(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--style", "richtext",
|
||||
"--content", `{"blocks":[{"block_element_type":"paragraph","paragraph":{"elements":[{"paragraph_element_type":"textRun","text_run":{"text":"test content"}}]}}],"mentions":["ou_123"]}`,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected unknown richtext content field error")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--content" {
|
||||
t.Fatalf("expected param --content, got: %v", err)
|
||||
}
|
||||
if !strings.Contains(err.Error(), "unknown field") {
|
||||
t.Fatalf("expected unknown field error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateValidate_EmptyRichTextContent(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
for _, content := range []string{emptyCreateRichTextJSON, blankCreateRichTextJSON} {
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--style", "richtext",
|
||||
"--content", content,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatalf("expected empty richtext error for %s", content)
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) || ve.Param != "--content" {
|
||||
t.Fatalf("expected param --content, got: %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateDryRun_Objective(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--content", validCreateSimpleJSON,
|
||||
"--dry-run",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
output := stdout.String()
|
||||
if got := gjson.Get(output, "data.api.0.method").String(); got != "POST" {
|
||||
t.Fatalf("dry-run method = %q, want POST; output: %s", got, output)
|
||||
}
|
||||
if got := gjson.Get(output, "data.api.0.url").String(); got != "/open-apis/okr/v2/cycles/123/objectives" {
|
||||
t.Fatalf("dry-run url = %q, want objective create path; output: %s", got, output)
|
||||
}
|
||||
if gjson.Get(output, "data.api.0.params.cycle_id").String() != "123" {
|
||||
t.Fatalf("expected query params in dry-run, got: %s", output)
|
||||
}
|
||||
if gjson.Get(output, "data.api.0.params.user_id_type").String() != "open_id" {
|
||||
t.Fatalf("expected default user-id-type in dry-run, got: %s", output)
|
||||
}
|
||||
if got := gjson.Get(output, "data.api.0.body.content.blocks.0.paragraph.elements.0.text_run.text").String(); got != "test objective" {
|
||||
t.Fatalf("dry-run content text = %q, want test objective; output: %s", got, output)
|
||||
}
|
||||
if got := gjson.Get(output, "data.api.0.body.content.blocks.0.paragraph.elements.1.mention.user_id").String(); got != "ou_123" {
|
||||
t.Fatalf("dry-run mention user_id = %q, want ou_123; output: %s", got, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateDryRun_ObjectiveWithNotes(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--content", validCreateSimpleJSON,
|
||||
"--notes", `{"text":"objective notes","mention":["ou_note"]}`,
|
||||
"--dry-run",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
output := stdout.String()
|
||||
if got := gjson.Get(output, "data.api.0.body.notes.blocks.0.paragraph.elements.0.text_run.text").String(); got != "objective notes" {
|
||||
t.Fatalf("dry-run notes text = %q, want objective notes; output: %s", got, output)
|
||||
}
|
||||
if got := gjson.Get(output, "data.api.0.body.notes.blocks.0.paragraph.elements.1.mention.user_id").String(); got != "ou_note" {
|
||||
t.Fatalf("dry-run notes mention user_id = %q, want ou_note; output: %s", got, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateDryRun_ObjectiveWithCategoryID(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--content", validCreateSimpleJSON,
|
||||
"--category-id", "7249339036661170180",
|
||||
"--dry-run",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
output := stdout.String()
|
||||
if got := gjson.Get(output, "data.api.0.body.category_id").String(); got != "7249339036661170180" {
|
||||
t.Fatalf("dry-run category_id = %q, want 7249339036661170180; output: %s", got, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateDryRun_KeyResult(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "key-result",
|
||||
"--objective-id", "456",
|
||||
"--style", "richtext",
|
||||
"--content", validCreateRichTextJSON,
|
||||
"--user-id-type", "union_id",
|
||||
"--dry-run",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
output := stdout.String()
|
||||
if got := gjson.Get(output, "data.api.0.method").String(); got != "POST" {
|
||||
t.Fatalf("dry-run method = %q, want POST; output: %s", got, output)
|
||||
}
|
||||
if got := gjson.Get(output, "data.api.0.url").String(); got != "/open-apis/okr/v2/objectives/456/key_results" {
|
||||
t.Fatalf("dry-run url = %q, want key result create path; output: %s", got, output)
|
||||
}
|
||||
if gjson.Get(output, "data.api.0.params.objective_id").String() != "456" {
|
||||
t.Fatalf("expected objective-id query param in dry-run, got: %s", output)
|
||||
}
|
||||
if gjson.Get(output, "data.api.0.params.user_id_type").String() != "union_id" {
|
||||
t.Fatalf("expected query params in dry-run, got: %s", output)
|
||||
}
|
||||
if got := gjson.Get(output, "data.api.0.body.content.blocks.0.paragraph.elements.0.text_run.text").String(); got != "test content" {
|
||||
t.Fatalf("dry-run richtext content = %q, want test content; output: %s", got, output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateExecute_ObjectiveSuccess(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/okr/v2/cycles/123/objectives",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"objective_id": "1001",
|
||||
},
|
||||
},
|
||||
})
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
data := decodeEnvelope(t, stdout)
|
||||
level, _ := data["level"].(string)
|
||||
if level != "objective" {
|
||||
t.Fatalf("expected level objective, got %v", data["level"])
|
||||
}
|
||||
if data["objective_id"] != "1001" {
|
||||
t.Fatalf("expected objective_id=1001, got %v", data["objective_id"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateExecute_KeyResultSuccess(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/okr/v2/objectives/456/key_results",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"key_result_id": "2001",
|
||||
},
|
||||
},
|
||||
})
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "key-result",
|
||||
"--objective-id", "456",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
data := decodeEnvelope(t, stdout)
|
||||
level, _ := data["level"].(string)
|
||||
if level != "key-result" {
|
||||
t.Fatalf("expected level key-result, got %v", data["level"])
|
||||
}
|
||||
if data["key_result_id"] != "2001" {
|
||||
t.Fatalf("expected key_result_id=2001, got %v", data["key_result_id"])
|
||||
}
|
||||
if data["objective_id"] != "456" {
|
||||
t.Fatalf("expected objective_id=456, got %v", data["objective_id"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateExecute_ObjectiveAPITypedErrorPassThrough(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "POST",
|
||||
URL: "/open-apis/okr/v2/cycles/123/objectives",
|
||||
Status: 400,
|
||||
Body: map[string]interface{}{
|
||||
"code": 1001001,
|
||||
"msg": "invalid parameters",
|
||||
},
|
||||
})
|
||||
err := runCreateShortcut(t, f, stdout, []string{
|
||||
"+create",
|
||||
"--level", "objective",
|
||||
"--cycle-id", "123",
|
||||
"--content", validCreateSimpleJSON,
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected API error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryAPI {
|
||||
t.Fatalf("expected typed API error, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateExecute_KeyResultRawErrorWrappedAsNetworkError(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, createTestConfig(t))
|
||||
raw := errors.New("dial tcp: i/o timeout")
|
||||
got := wrapOkrNetworkErr(raw, "failed to create key result")
|
||||
problem, ok := errs.ProblemOf(got)
|
||||
if !ok || problem.Category != errs.CategoryNetwork || problem.Subtype != errs.SubtypeNetworkTransport {
|
||||
t.Fatalf("expected network transport error, got: %v", got)
|
||||
}
|
||||
if !errors.Is(got, raw) {
|
||||
t.Fatal("expected wrapped raw error to be preserved")
|
||||
}
|
||||
if stdout.String() != "" || f == nil {
|
||||
// keep the test factory referenced so the helper wiring stays exercised
|
||||
}
|
||||
}
|
||||
@@ -64,6 +64,10 @@ func isCurrentActiveCycle(cycle *Cycle, now time.Time) bool {
|
||||
cycleStart := time.UnixMilli(startMs).UTC()
|
||||
cycleEnd := time.UnixMilli(endMs).UTC()
|
||||
nowUTC := now.UTC()
|
||||
// Month cycles only
|
||||
if cycleStart.AddDate(1, 0, -1) == cycleEnd {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check time range: now must be >= start and <= end
|
||||
if nowUTC.Before(cycleStart) || nowUTC.After(cycleEnd) {
|
||||
@@ -78,6 +82,7 @@ func isCurrentActiveCycle(cycle *Cycle, now time.Time) bool {
|
||||
return status == CycleStatusDefault || status == CycleStatusNormal
|
||||
}
|
||||
|
||||
// OKRListCycles
|
||||
var OKRListCycles = common.Shortcut{
|
||||
Service: "okr",
|
||||
Command: "+cycle-list",
|
||||
@@ -89,7 +94,9 @@ var OKRListCycles = common.Shortcut{
|
||||
Flags: []common.Flag{
|
||||
{Name: "user-id", Desc: "user ID", Required: true},
|
||||
{Name: "user-id-type", Default: "open_id", Desc: "user ID type: open_id | union_id | user_id"},
|
||||
{Name: "time-range", Desc: "specify time range. Use Format as YYYY-MM--YYYY-MM. leave empty to fetch all user cycles."},
|
||||
{Name: "time-range", Desc: "local post-filter applied after the requested page is fetched. Format: YYYY-MM--YYYY-MM. Leave empty to keep the page unfiltered."},
|
||||
{Name: "page-size", Type: "int", Default: "100", Desc: "page size, range 1-100"},
|
||||
{Name: "page-token", Desc: "pagination token from previous response"},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
idType := runtime.Str("user-id-type")
|
||||
@@ -110,18 +117,29 @@ var OKRListCycles = common.Shortcut{
|
||||
return err
|
||||
}
|
||||
}
|
||||
if _, err := common.ValidatePageSizeTyped(runtime, "page-size", 100, 1, 100); err != nil {
|
||||
return err
|
||||
}
|
||||
if pageToken := runtime.Str("page-token"); pageToken != "" {
|
||||
if err := common.RejectDangerousCharsTyped("--page-token", pageToken); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
params := map[string]interface{}{
|
||||
"user_id": runtime.Str("user-id"),
|
||||
"user_id_type": runtime.Str("user-id-type"),
|
||||
"page_size": 100,
|
||||
"page_size": runtime.Int("page-size"),
|
||||
}
|
||||
if pageToken := runtime.Str("page-token"); pageToken != "" {
|
||||
params["page_token"] = pageToken
|
||||
}
|
||||
return common.NewDryRunAPI().
|
||||
GET("/open-apis/okr/v2/cycles").
|
||||
Params(params).
|
||||
Desc("List OKR cycles for user, paginated at 100 per page, filtered by time-range")
|
||||
Desc("List one page of OKR cycles for user; --time-range is a local post-filter on the returned page")
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
userID := runtime.Str("user-id")
|
||||
@@ -140,53 +158,35 @@ var OKRListCycles = common.Shortcut{
|
||||
hasRange = true
|
||||
}
|
||||
|
||||
// Paginated fetch of all cycles
|
||||
queryParams := map[string]interface{}{
|
||||
"user_id": userID,
|
||||
"user_id_type": userIDType,
|
||||
"page_size": "100",
|
||||
"page_size": runtime.Int("page-size"),
|
||||
}
|
||||
if pageToken := runtime.Str("page-token"); pageToken != "" {
|
||||
queryParams["page_token"] = pageToken
|
||||
}
|
||||
|
||||
var allCycles []Cycle
|
||||
page := 0
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if page > 0 {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(500 * time.Millisecond):
|
||||
}
|
||||
}
|
||||
page++
|
||||
|
||||
data, err := runtime.CallAPITyped("GET", "/open-apis/okr/v2/cycles", queryParams, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
itemsRaw, _ := data["items"].([]interface{})
|
||||
for _, item := range itemsRaw {
|
||||
raw, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var cycle Cycle
|
||||
if err := json.Unmarshal(raw, &cycle); err != nil {
|
||||
continue
|
||||
}
|
||||
allCycles = append(allCycles, cycle)
|
||||
}
|
||||
|
||||
hasMore, pageToken := common.PaginationMeta(data)
|
||||
if !hasMore || pageToken == "" {
|
||||
break
|
||||
}
|
||||
queryParams["page_token"] = pageToken
|
||||
data, err := runtime.CallAPITyped("GET", "/open-apis/okr/v2/cycles", queryParams, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
itemsRaw, _ := data["items"].([]interface{})
|
||||
for _, item := range itemsRaw {
|
||||
raw, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var cycle Cycle
|
||||
if err := json.Unmarshal(raw, &cycle); err != nil {
|
||||
continue
|
||||
}
|
||||
allCycles = append(allCycles, cycle)
|
||||
}
|
||||
hasMore, nextPageToken := common.PaginationMeta(data)
|
||||
|
||||
// Filter by time-range overlap
|
||||
var filtered []Cycle
|
||||
for i := range allCycles {
|
||||
@@ -212,7 +212,8 @@ var OKRListCycles = common.Shortcut{
|
||||
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"cycles": respCycles,
|
||||
"total": len(respCycles),
|
||||
"has_more": hasMore,
|
||||
"page_token": nextPageToken,
|
||||
"current_active_cycles": currentActiveCycles,
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Found %d cycle(s)\n", len(respCycles))
|
||||
|
||||
@@ -5,6 +5,8 @@ package okr
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
@@ -12,6 +14,7 @@ import (
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
@@ -120,6 +123,27 @@ func TestCycleListValidate_StartAfterEndTimeRange(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCycleListValidate_InvalidPageSize(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, cycleListTestConfig(t))
|
||||
err := runCycleListShortcut(t, f, stdout, []string{
|
||||
"+cycle-list",
|
||||
"--user-id", "ou-123",
|
||||
"--page-size", "101",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid --page-size")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("expected validation invalid_argument problem, got: %v", err)
|
||||
}
|
||||
validationErr, ok := err.(*errs.ValidationError)
|
||||
if !ok || validationErr.Param != "--page-size" {
|
||||
t.Fatalf("expected param --page-size, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCycleListValidate_ValidNoTimeRange(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, cycleListTestConfig(t))
|
||||
@@ -214,6 +238,9 @@ func TestCycleListDryRun(t *testing.T) {
|
||||
if !strings.Contains(output, "/open-apis/okr/v2/cycles") {
|
||||
t.Fatalf("dry-run output should contain API path, got: %s", output)
|
||||
}
|
||||
if !strings.Contains(output, "\"page_size\": 100") {
|
||||
t.Fatalf("dry-run output should contain default page_size=100, got: %s", output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCycleListDryRun_WithTimeRange(t *testing.T) {
|
||||
@@ -234,6 +261,28 @@ func TestCycleListDryRun_WithTimeRange(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCycleListDryRun_WithPagination(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, cycleListTestConfig(t))
|
||||
err := runCycleListShortcut(t, f, stdout, []string{
|
||||
"+cycle-list",
|
||||
"--user-id", "ou-789",
|
||||
"--page-size", "20",
|
||||
"--page-token", "next-page",
|
||||
"--dry-run",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
output := stdout.String()
|
||||
if !strings.Contains(output, "\"page_size\": 20") {
|
||||
t.Fatalf("dry-run output should contain page_size=20, got: %s", output)
|
||||
}
|
||||
if !strings.Contains(output, "\"page_token\": \"next-page\"") {
|
||||
t.Fatalf("dry-run output should contain page_token, got: %s", output)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Execute tests ---
|
||||
|
||||
func TestCycleListExecute_NoCycles(t *testing.T) {
|
||||
@@ -454,9 +503,11 @@ func TestCycleListExecute_WithCycles(t *testing.T) {
|
||||
if len(cycles) != 2 {
|
||||
t.Fatalf("cycles count = %d, want 2", len(cycles))
|
||||
}
|
||||
total, _ := data["total"].(float64)
|
||||
if int(total) != 2 {
|
||||
t.Fatalf("total = %v, want 2", total)
|
||||
if _, ok := data["total"]; ok {
|
||||
t.Fatal("total should not be present in response")
|
||||
}
|
||||
if hasMore, _ := data["has_more"].(bool); hasMore {
|
||||
t.Fatalf("has_more = %v, want false", hasMore)
|
||||
}
|
||||
|
||||
// Check current_active_cycles - should only contain cycle-active
|
||||
@@ -555,10 +606,13 @@ func TestCycleListExecute_Pagination(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, cycleListTestConfig(t))
|
||||
|
||||
// First page
|
||||
var gotQuery url.Values
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/okr/v2/cycles",
|
||||
OnMatch: func(req *http.Request) {
|
||||
gotQuery = req.URL.Query()
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
@@ -578,38 +632,31 @@ func TestCycleListExecute_Pagination(t *testing.T) {
|
||||
},
|
||||
})
|
||||
|
||||
// Second page
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/okr/v2/cycles",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
"data": map[string]interface{}{
|
||||
"items": []interface{}{
|
||||
map[string]interface{}{
|
||||
"id": "cycle-p2",
|
||||
"start_time": "1738368000000",
|
||||
"end_time": "1743465600000",
|
||||
"cycle_status": 1,
|
||||
"owner": map[string]interface{}{"owner_type": "user", "user_id": "ou-1"},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := runCycleListShortcut(t, f, stdout, []string{
|
||||
"+cycle-list",
|
||||
"--user-id", "ou-123",
|
||||
"--page-size", "1",
|
||||
"--page-token", "start_page",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := gotQuery.Get("page_size"); got != "1" {
|
||||
t.Fatalf("query page_size = %q, want 1", got)
|
||||
}
|
||||
if got := gotQuery.Get("page_token"); got != "start_page" {
|
||||
t.Fatalf("query page_token = %q, want start_page", got)
|
||||
}
|
||||
data := decodeEnvelope(t, stdout)
|
||||
cycles, _ := data["cycles"].([]interface{})
|
||||
if len(cycles) != 2 {
|
||||
t.Fatalf("cycles count = %d, want 2", len(cycles))
|
||||
if len(cycles) != 1 {
|
||||
t.Fatalf("cycles count = %d, want 1", len(cycles))
|
||||
}
|
||||
if hasMore, _ := data["has_more"].(bool); !hasMore {
|
||||
t.Fatalf("has_more = %v, want true", hasMore)
|
||||
}
|
||||
if pageToken, _ := data["page_token"].(string); pageToken != "next_page" {
|
||||
t.Fatalf("page_token = %q, want next_page", pageToken)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -28,6 +28,8 @@ var OKRListProgress = common.Shortcut{
|
||||
{Name: "target-type", Desc: "target type: objective | key_result", Required: true, Enum: []string{"objective", "key_result"}},
|
||||
{Name: "user-id-type", Default: "open_id", Desc: "user ID type: open_id | union_id | user_id"},
|
||||
{Name: "department-id-type", Default: "open_department_id", Desc: "department ID type: department_id | open_department_id"},
|
||||
{Name: "page-size", Type: "int", Default: "100", Desc: "page size, range 1-100"},
|
||||
{Name: "page-token", Desc: "pagination token from previous response"},
|
||||
},
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
targetID := runtime.Str("target-id")
|
||||
@@ -55,6 +57,14 @@ var OKRListProgress = common.Shortcut{
|
||||
if deptIDType != "department_id" && deptIDType != "open_department_id" {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--department-id-type must be one of: department_id | open_department_id").WithParam("--department-id-type")
|
||||
}
|
||||
if _, err := common.ValidatePageSizeTyped(runtime, "page-size", 100, 1, 100); err != nil {
|
||||
return err
|
||||
}
|
||||
if pageToken := runtime.Str("page-token"); pageToken != "" {
|
||||
if err := common.RejectDangerousCharsTyped("--page-token", pageToken); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
@@ -63,7 +73,10 @@ var OKRListProgress = common.Shortcut{
|
||||
params := map[string]interface{}{
|
||||
"user_id_type": runtime.Str("user-id-type"),
|
||||
"department_id_type": runtime.Str("department-id-type"),
|
||||
"page_size": 100,
|
||||
"page_size": runtime.Int("page-size"),
|
||||
}
|
||||
if pageToken := runtime.Str("page-token"); pageToken != "" {
|
||||
params["page_token"] = pageToken
|
||||
}
|
||||
|
||||
switch targetType {
|
||||
@@ -91,7 +104,10 @@ var OKRListProgress = common.Shortcut{
|
||||
queryParams := map[string]interface{}{
|
||||
"user_id_type": userIDType,
|
||||
"department_id_type": deptIDType,
|
||||
"page_size": "100",
|
||||
"page_size": runtime.Int("page-size"),
|
||||
}
|
||||
if pageToken := runtime.Str("page-token"); pageToken != "" {
|
||||
queryParams["page_token"] = pageToken
|
||||
}
|
||||
|
||||
var apiPath string
|
||||
@@ -103,36 +119,29 @@ var OKRListProgress = common.Shortcut{
|
||||
}
|
||||
|
||||
var allProgress []*Progress
|
||||
for {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
data, err := runtime.CallAPITyped("GET", apiPath, queryParams, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
itemsRaw, _ := data["items"].([]interface{})
|
||||
for _, item := range itemsRaw {
|
||||
raw, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var progress Progress
|
||||
if err := json.Unmarshal(raw, &progress); err != nil {
|
||||
continue
|
||||
}
|
||||
allProgress = append(allProgress, &progress)
|
||||
}
|
||||
|
||||
hasMore, pageToken := common.PaginationMeta(data)
|
||||
if !hasMore || pageToken == "" {
|
||||
break
|
||||
}
|
||||
queryParams["page_token"] = pageToken
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
data, err := runtime.CallAPITyped("GET", apiPath, queryParams, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
itemsRaw, _ := data["items"].([]interface{})
|
||||
for _, item := range itemsRaw {
|
||||
raw, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
var progress Progress
|
||||
if err := json.Unmarshal(raw, &progress); err != nil {
|
||||
continue
|
||||
}
|
||||
allProgress = append(allProgress, &progress)
|
||||
}
|
||||
hasMore, pageToken := common.PaginationMeta(data)
|
||||
|
||||
// Convert to response format
|
||||
respProgress := make([]*RespProgress, 0, len(allProgress))
|
||||
for _, p := range allProgress {
|
||||
@@ -141,7 +150,8 @@ var OKRListProgress = common.Shortcut{
|
||||
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"progress_list": respProgress,
|
||||
"total": len(respProgress),
|
||||
"has_more": hasMore,
|
||||
"page_token": pageToken,
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Found %d progress(es)\n", len(respProgress))
|
||||
for _, p := range respProgress {
|
||||
|
||||
@@ -5,11 +5,14 @@ package okr
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/cmdutil"
|
||||
"github.com/larksuite/cli/internal/core"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
@@ -123,6 +126,28 @@ func TestProgressListValidate_InvalidDepartmentIDType(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgressListValidate_InvalidPageSize(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, progressListTestConfig(t))
|
||||
err := runProgressListShortcut(t, f, stdout, []string{
|
||||
"+progress-list",
|
||||
"--target-id", "123",
|
||||
"--target-type", "objective",
|
||||
"--page-size", "0",
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("expected error for invalid --page-size")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("expected validation invalid_argument problem, got: %v", err)
|
||||
}
|
||||
validationErr, ok := err.(*errs.ValidationError)
|
||||
if !ok || validationErr.Param != "--page-size" {
|
||||
t.Fatalf("expected param --page-size, got: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// --- DryRun tests ---
|
||||
|
||||
func TestProgressListDryRun_Objective(t *testing.T) {
|
||||
@@ -144,6 +169,9 @@ func TestProgressListDryRun_Objective(t *testing.T) {
|
||||
if !strings.Contains(output, "GET") {
|
||||
t.Fatalf("dry-run output should contain GET method, got: %s", output)
|
||||
}
|
||||
if !strings.Contains(output, "\"page_size\": 100") {
|
||||
t.Fatalf("dry-run output should contain default page_size=100, got: %s", output)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgressListDryRun_KeyResult(t *testing.T) {
|
||||
@@ -164,14 +192,41 @@ func TestProgressListDryRun_KeyResult(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgressListDryRun_WithPagination(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, _ := cmdutil.TestFactory(t, progressListTestConfig(t))
|
||||
err := runProgressListShortcut(t, f, stdout, []string{
|
||||
"+progress-list",
|
||||
"--target-id", "123456789",
|
||||
"--target-type", "objective",
|
||||
"--page-size", "25",
|
||||
"--page-token", "next-page",
|
||||
"--dry-run",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
output := stdout.String()
|
||||
if !strings.Contains(output, "\"page_size\": 25") {
|
||||
t.Fatalf("dry-run output should contain page_size=25, got: %s", output)
|
||||
}
|
||||
if !strings.Contains(output, "\"page_token\": \"next-page\"") {
|
||||
t.Fatalf("dry-run output should contain page_token, got: %s", output)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Execute tests ---
|
||||
|
||||
func TestProgressListExecute_Success_Objective(t *testing.T) {
|
||||
t.Parallel()
|
||||
f, stdout, _, reg := cmdutil.TestFactory(t, progressListTestConfig(t))
|
||||
var gotQuery url.Values
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/okr/v2/objectives/123456789/progresses",
|
||||
OnMatch: func(req *http.Request) {
|
||||
gotQuery = req.URL.Query()
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "ok",
|
||||
@@ -191,7 +246,8 @@ func TestProgressListExecute_Success_Objective(t *testing.T) {
|
||||
},
|
||||
},
|
||||
},
|
||||
"has_more": false,
|
||||
"has_more": true,
|
||||
"page_token": "next_page",
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -199,15 +255,32 @@ func TestProgressListExecute_Success_Objective(t *testing.T) {
|
||||
"+progress-list",
|
||||
"--target-id", "123456789",
|
||||
"--target-type", "objective",
|
||||
"--page-size", "50",
|
||||
"--page-token", "start_page",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("unexpected error: %v", err)
|
||||
}
|
||||
if got := gotQuery.Get("page_size"); got != "50" {
|
||||
t.Fatalf("query page_size = %q, want 50", got)
|
||||
}
|
||||
if got := gotQuery.Get("page_token"); got != "start_page" {
|
||||
t.Fatalf("query page_token = %q, want start_page", got)
|
||||
}
|
||||
data := decodeEnvelope(t, stdout)
|
||||
records, _ := data["progress_list"].([]interface{})
|
||||
if len(records) != 1 {
|
||||
t.Fatalf("expected 1 progress, got %d", len(records))
|
||||
}
|
||||
if _, ok := data["total"]; ok {
|
||||
t.Fatal("total should not be present in response")
|
||||
}
|
||||
if hasMore, _ := data["has_more"].(bool); !hasMore {
|
||||
t.Fatalf("has_more = %v, want true", hasMore)
|
||||
}
|
||||
if pageToken, _ := data["page_token"].(string); pageToken != "next_page" {
|
||||
t.Fatalf("page_token = %q, want next_page", pageToken)
|
||||
}
|
||||
}
|
||||
|
||||
func TestProgressListExecute_Success_KeyResult(t *testing.T) {
|
||||
|
||||
@@ -18,6 +18,7 @@ func Shortcuts() []common.Shortcut {
|
||||
OKRUpdateProgressRecord,
|
||||
OKRDeleteProgressRecord,
|
||||
OKRUploadImage,
|
||||
OKRCreate,
|
||||
OKRBatchCreate,
|
||||
OKRReorder,
|
||||
OKRWeight,
|
||||
|
||||
@@ -12,6 +12,12 @@ import (
|
||||
func TestShortcutsRegistration(t *testing.T) {
|
||||
convey.Convey("Shortcuts() returns all commands", t, func() {
|
||||
list := Shortcuts()
|
||||
convey.So(len(list), convey.ShouldBeGreaterThan, 0)
|
||||
commands := make([]string, 0, len(list))
|
||||
for _, shortcut := range list {
|
||||
commands = append(commands, shortcut.Command)
|
||||
}
|
||||
convey.So(commands, convey.ShouldContain, "+create")
|
||||
convey.So(commands, convey.ShouldContain, "+batch-create")
|
||||
convey.So(commands, convey.ShouldContain, "+patch")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -3,11 +3,24 @@
|
||||
|
||||
package slides
|
||||
|
||||
import "github.com/larksuite/cli/shortcuts/common"
|
||||
import (
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
var presentationFlagAliases = []string{
|
||||
"presentation-id",
|
||||
"presentation-token",
|
||||
"token",
|
||||
"presentation_id",
|
||||
"xml-presentation-id",
|
||||
"url",
|
||||
}
|
||||
|
||||
// Shortcuts returns all slides shortcuts.
|
||||
func Shortcuts() []common.Shortcut {
|
||||
return []common.Shortcut{
|
||||
all := []common.Shortcut{
|
||||
SlidesCreate,
|
||||
SlidesMediaUpload,
|
||||
SlidesReplaceSlide,
|
||||
@@ -18,4 +31,39 @@ func Shortcuts() []common.Shortcut {
|
||||
SlidesHistoryRevert,
|
||||
SlidesHistoryRevertStatus,
|
||||
}
|
||||
for i := range all {
|
||||
if hasPresentationFlag(all[i].Flags) {
|
||||
all[i].PostMount = withPresentationFlagAliases(all[i].PostMount)
|
||||
}
|
||||
}
|
||||
return all
|
||||
}
|
||||
|
||||
func hasPresentationFlag(flags []common.Flag) bool {
|
||||
for _, flag := range flags {
|
||||
if flag.Name == "presentation" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// withPresentationFlagAliases accepts common agent-generated spellings for
|
||||
// --presentation without registering extra flags. The aliases therefore stay
|
||||
// out of help and completion while resolving to the canonical flag at parse
|
||||
// time, matching the zero-round-trip compatibility used by Sheets.
|
||||
func withPresentationFlagAliases(prev func(cmd *cobra.Command)) func(cmd *cobra.Command) {
|
||||
return func(cmd *cobra.Command) {
|
||||
if prev != nil {
|
||||
prev(cmd)
|
||||
}
|
||||
cmd.Flags().SetNormalizeFunc(func(_ *pflag.FlagSet, name string) pflag.NormalizedName {
|
||||
for _, alias := range presentationFlagAliases {
|
||||
if name == alias {
|
||||
return pflag.NormalizedName("presentation")
|
||||
}
|
||||
}
|
||||
return pflag.NormalizedName(name)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
68
shortcuts/slides/shortcuts_alias_test.go
Normal file
68
shortcuts/slides/shortcuts_alias_test.go
Normal file
@@ -0,0 +1,68 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package slides
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func TestWithPresentationFlagAliases(t *testing.T) {
|
||||
for _, alias := range presentationFlagAliases {
|
||||
t.Run(alias, func(t *testing.T) {
|
||||
cmd := &cobra.Command{Use: "test"}
|
||||
cmd.Flags().String("presentation", "", "presentation reference")
|
||||
withPresentationFlagAliases(nil)(cmd)
|
||||
|
||||
if err := cmd.Flags().Parse([]string{"--" + alias, "presABC"}); err != nil {
|
||||
t.Fatalf("--%s should resolve to --presentation: %v", alias, err)
|
||||
}
|
||||
got, err := cmd.Flags().GetString("presentation")
|
||||
if err != nil {
|
||||
t.Fatalf("read --presentation: %v", err)
|
||||
}
|
||||
if got != "presABC" {
|
||||
t.Fatalf("--%s set --presentation to %q, want presABC", alias, got)
|
||||
}
|
||||
if usage := cmd.Flags().FlagUsages(); strings.Contains(usage, "--"+alias) {
|
||||
t.Fatalf("hidden compatibility alias --%s leaked into help:\n%s", alias, usage)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestShortcutsAttachPresentationFlagAliases(t *testing.T) {
|
||||
count := 0
|
||||
for _, shortcut := range Shortcuts() {
|
||||
if !hasPresentationFlag(shortcut.Flags) {
|
||||
continue
|
||||
}
|
||||
count++
|
||||
if shortcut.PostMount == nil {
|
||||
t.Errorf("%s has --presentation but no compatibility normalizer", shortcut.Command)
|
||||
continue
|
||||
}
|
||||
|
||||
cmd := &cobra.Command{Use: shortcut.Command}
|
||||
cmd.Flags().String("presentation", "", "presentation reference")
|
||||
shortcut.PostMount(cmd)
|
||||
if err := cmd.Flags().Parse([]string{"--token", "presABC"}); err != nil {
|
||||
t.Errorf("%s did not normalize --token: %v", shortcut.Command, err)
|
||||
continue
|
||||
}
|
||||
got, err := cmd.Flags().GetString("presentation")
|
||||
if err != nil {
|
||||
t.Errorf("%s could not read --presentation: %v", shortcut.Command, err)
|
||||
continue
|
||||
}
|
||||
if got != "presABC" {
|
||||
t.Errorf("%s normalized --token to %q, want presABC", shortcut.Command, got)
|
||||
}
|
||||
}
|
||||
if count == 0 {
|
||||
t.Fatal("expected at least one slides shortcut with --presentation")
|
||||
}
|
||||
}
|
||||
@@ -37,9 +37,7 @@ var SlidesScreenshot = common.Shortcut{
|
||||
Command: "+screenshot",
|
||||
Description: "Save up to 10 slide screenshots to local files without printing Base64 image data",
|
||||
Risk: "read",
|
||||
Scopes: []string{},
|
||||
// The screenshot API is allowlist-gated for only a few apps, so do not
|
||||
// advertise/preflight its scope. Let the API fail and let callers degrade.
|
||||
Scopes: []string{"slides:presentation:screenshot"},
|
||||
// wiki:node:read is required only when --presentation is a wiki URL.
|
||||
ConditionalScopes: []string{"wiki:node:read"},
|
||||
AuthTypes: []string{"user", "bot"},
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"encoding/json"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -17,23 +18,19 @@ import (
|
||||
)
|
||||
|
||||
func TestSlidesScreenshotDeclaredScopes(t *testing.T) {
|
||||
if got := SlidesScreenshot.ScopesForIdentity("user"); len(got) != 0 {
|
||||
t.Fatalf("user preflight scopes = %#v, want empty", got)
|
||||
base := []string{"slides:presentation:screenshot"}
|
||||
if got := SlidesScreenshot.ScopesForIdentity("user"); !reflect.DeepEqual(got, base) {
|
||||
t.Fatalf("user preflight scopes = %#v, want %#v", got, base)
|
||||
}
|
||||
if got := SlidesScreenshot.ScopesForIdentity("bot"); len(got) != 0 {
|
||||
t.Fatalf("bot preflight scopes = %#v, want empty", got)
|
||||
if got := SlidesScreenshot.ScopesForIdentity("bot"); !reflect.DeepEqual(got, base) {
|
||||
t.Fatalf("bot preflight scopes = %#v, want %#v", got, base)
|
||||
}
|
||||
|
||||
got := SlidesScreenshot.DeclaredScopesForIdentity("user")
|
||||
want := []string{"wiki:node:read"}
|
||||
if len(got) != len(want) || got[0] != want[0] {
|
||||
want := []string{"slides:presentation:screenshot", "wiki:node:read"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("declared scopes = %#v, want %#v", got, want)
|
||||
}
|
||||
for _, scope := range got {
|
||||
if scope == "slides:presentation:screenshot" {
|
||||
t.Fatalf("declared scopes must not advertise screenshot scope: %#v", got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSlidesScreenshotWritesFilesAndSuppressesBase64(t *testing.T) {
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"regexp"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -100,6 +101,40 @@ func extractTaskGuid(input string) string {
|
||||
return extractTasklistGuid(input)
|
||||
}
|
||||
|
||||
var taskDisplayNumberPattern = regexp.MustCompile(`^t[0-9]+$`)
|
||||
|
||||
func parseTaskGUID(input string) (string, error) {
|
||||
input = strings.TrimSpace(input)
|
||||
invalid := func(format string, args ...interface{}) *errs.ValidationError {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, format, args...).
|
||||
WithParam("--task-id").
|
||||
WithHint("provide the Task OpenAPI GUID or a task applink containing guid=")
|
||||
}
|
||||
|
||||
if input == "" {
|
||||
return "", invalid("task ID is empty")
|
||||
}
|
||||
|
||||
lowerInput := strings.ToLower(input)
|
||||
if strings.HasPrefix(lowerInput, "http://") || strings.HasPrefix(lowerInput, "https://") {
|
||||
u, err := url.Parse(input)
|
||||
if err != nil {
|
||||
return "", invalid("invalid task applink: %v", err).WithCause(err)
|
||||
}
|
||||
guid := strings.TrimSpace(u.Query().Get("guid"))
|
||||
if guid == "" {
|
||||
return "", invalid("task applink is missing a non-empty guid query parameter")
|
||||
}
|
||||
return guid, nil
|
||||
}
|
||||
|
||||
if taskDisplayNumberPattern.MatchString(input) {
|
||||
return "", invalid("task display number %q is not a Task OpenAPI GUID", input)
|
||||
}
|
||||
|
||||
return input, nil
|
||||
}
|
||||
|
||||
func buildTaskCreateBody(runtime *common.RuntimeContext) (map[string]interface{}, error) {
|
||||
body := make(map[string]interface{})
|
||||
|
||||
|
||||
@@ -4,8 +4,11 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/smartystreets/goconvey/convey"
|
||||
)
|
||||
|
||||
@@ -15,3 +18,80 @@ func TestShortcutsRegistration(t *testing.T) {
|
||||
convey.So(len(list), convey.ShouldBeGreaterThan, 0)
|
||||
})
|
||||
}
|
||||
|
||||
func TestParseTaskGUID(t *testing.T) {
|
||||
t.Run("accepts GUIDs and task applinks", func(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
want string
|
||||
}{
|
||||
{name: "opaque GUID", input: "task-guid-123", want: "task-guid-123"},
|
||||
{name: "trimmed GUID", input: " task-guid-123 ", want: "task-guid-123"},
|
||||
{
|
||||
name: "task applink",
|
||||
input: "https://applink.larksuite.com/client/todo/detail?guid=task-guid-123",
|
||||
want: "task-guid-123",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, err := parseTaskGUID(tt.input)
|
||||
if err != nil {
|
||||
t.Fatalf("parseTaskGUID(%q) error = %v", tt.input, err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("parseTaskGUID(%q) = %q, want %q", tt.input, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("rejects unusable task identifiers", func(t *testing.T) {
|
||||
for _, input := range []string{
|
||||
"",
|
||||
"https://applink.larksuite.com/client/todo/detail",
|
||||
"https://%",
|
||||
"t12345",
|
||||
} {
|
||||
t.Run(input, func(t *testing.T) {
|
||||
_, err := parseTaskGUID(input)
|
||||
if err == nil {
|
||||
t.Fatalf("parseTaskGUID(%q) error = nil, want typed validation error", input)
|
||||
}
|
||||
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok {
|
||||
t.Fatalf("parseTaskGUID(%q) error type = %T, want typed error", input, err)
|
||||
}
|
||||
if problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("problem = %s/%s, want %s/%s", problem.Category, problem.Subtype, errs.CategoryValidation, errs.SubtypeInvalidArgument)
|
||||
}
|
||||
if problem.Hint == "" {
|
||||
t.Fatal("problem hint is empty")
|
||||
}
|
||||
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) {
|
||||
t.Fatalf("error type = %T, want *errs.ValidationError", err)
|
||||
}
|
||||
if validationErr.Param != "--task-id" {
|
||||
t.Fatalf("param = %q, want %q", validationErr.Param, "--task-id")
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("preserves applink parse cause", func(t *testing.T) {
|
||||
_, err := parseTaskGUID("https://%")
|
||||
if err == nil {
|
||||
t.Fatal("parseTaskGUID() error = nil, want URL parse error")
|
||||
}
|
||||
|
||||
var urlErr *url.Error
|
||||
if !errors.As(err, &urlErr) {
|
||||
t.Fatalf("error chain = %T %v, want *url.Error cause", err, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -25,45 +25,59 @@ var CompleteTask = common.Shortcut{
|
||||
HasFormat: true,
|
||||
|
||||
Flags: []common.Flag{
|
||||
{Name: "task-id", Desc: "task id", Required: true},
|
||||
{Name: "task-id", Desc: "task GUID or task applink URL", Required: true},
|
||||
},
|
||||
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
_, err := parseTaskGUID(runtime.Str("task-id"))
|
||||
return err
|
||||
},
|
||||
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
body := buildCompleteBody()
|
||||
taskId := url.PathEscape(runtime.Str("task-id"))
|
||||
taskGUID, err := parseTaskGUID(runtime.Str("task-id"))
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
}
|
||||
taskID := url.PathEscape(taskGUID)
|
||||
return common.NewDryRunAPI().
|
||||
GET("/open-apis/task/v2/tasks/" + taskId).
|
||||
GET("/open-apis/task/v2/tasks/" + taskID).
|
||||
Desc("get current task status").
|
||||
Params(map[string]interface{}{"user_id_type": "open_id"}).
|
||||
PATCH("/open-apis/task/v2/tasks/" + taskId).
|
||||
PATCH("/open-apis/task/v2/tasks/" + taskID).
|
||||
Desc("complete task if not completed").
|
||||
Params(map[string]interface{}{"user_id_type": "open_id"}).
|
||||
Body(body)
|
||||
},
|
||||
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
taskId := url.PathEscape(runtime.Str("task-id"))
|
||||
taskGUID, err := parseTaskGUID(runtime.Str("task-id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
taskID := url.PathEscape(taskGUID)
|
||||
|
||||
params := map[string]interface{}{"user_id_type": "open_id"}
|
||||
|
||||
var data map[string]interface{}
|
||||
|
||||
// 1. Get current task status
|
||||
getData, err := callTaskAPITyped(runtime, http.MethodGet, "/open-apis/task/v2/tasks/"+taskId, params, nil)
|
||||
getData, err := callTaskAPITyped(runtime, http.MethodGet, "/open-apis/task/v2/tasks/"+taskID, params, nil)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
taskData, _ := getData["task"].(map[string]interface{})
|
||||
completedAtStr, _ := taskData["completed_at"].(string)
|
||||
alreadyCompleted := completedAtStr != "" && completedAtStr != "0"
|
||||
|
||||
// 2. If already completed, directly return success
|
||||
if completedAtStr != "" && completedAtStr != "0" {
|
||||
if alreadyCompleted {
|
||||
data = getData
|
||||
} else {
|
||||
// 3. Complete the task
|
||||
body := buildCompleteBody()
|
||||
data, err = callTaskAPITyped(runtime, http.MethodPatch, "/open-apis/task/v2/tasks/"+taskId, params, body)
|
||||
data, err = callTaskAPITyped(runtime, http.MethodPatch, "/open-apis/task/v2/tasks/"+taskID, params, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -73,11 +87,19 @@ var CompleteTask = common.Shortcut{
|
||||
guid, _ := task["guid"].(string)
|
||||
urlVal, _ := task["url"].(string)
|
||||
urlVal = truncateTaskURL(urlVal)
|
||||
completedAt, _ := task["completed_at"].(string)
|
||||
status := "todo"
|
||||
if completedAt != "" && completedAt != "0" {
|
||||
status = "done"
|
||||
}
|
||||
|
||||
// Standardized write output: return resource identifiers
|
||||
outData := map[string]interface{}{
|
||||
"guid": guid,
|
||||
"url": urlVal,
|
||||
"guid": guid,
|
||||
"url": urlVal,
|
||||
"status": status,
|
||||
"completed_at": completedAt,
|
||||
"already_completed": alreadyCompleted,
|
||||
}
|
||||
|
||||
runtime.OutFormat(outData, nil, func(w io.Writer) {
|
||||
|
||||
@@ -4,9 +4,12 @@
|
||||
package task
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
)
|
||||
|
||||
@@ -45,6 +48,9 @@ func TestCompleteTask(t *testing.T) {
|
||||
formatFlag: "json",
|
||||
expectedOutput: []string{
|
||||
`"guid": "task-789"`,
|
||||
`"status": "done"`,
|
||||
`"completed_at": "1775174400000"`,
|
||||
`"already_completed": false`,
|
||||
},
|
||||
},
|
||||
}
|
||||
@@ -109,3 +115,98 @@ func TestCompleteTask(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskCompleteAcceptsTaskApplink(t *testing.T) {
|
||||
f, stdout, _, reg := taskShortcutTestFactory(t)
|
||||
warmTenantToken(t, f, reg)
|
||||
|
||||
for _, method := range []string{"GET", "PATCH"} {
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: method,
|
||||
URL: "/open-apis/task/v2/tasks/task-guid-applink",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "success",
|
||||
"data": map[string]interface{}{
|
||||
"task": map[string]interface{}{
|
||||
"guid": "task-guid-applink",
|
||||
"summary": "Applink task",
|
||||
"completed_at": map[string]string{"GET": "0", "PATCH": "1775174400000"}[method],
|
||||
"url": "https://example.com/task-guid-applink",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
err := runMountedTaskShortcut(t, CompleteTask, []string{
|
||||
"+complete",
|
||||
"--task-id", "https://applink.larksuite.com/client/todo/detail?guid=task-guid-applink",
|
||||
"--format", "json",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("CompleteTask error = %v", err)
|
||||
}
|
||||
reg.Verify(t)
|
||||
if !strings.Contains(stdout.String(), `"guid": "task-guid-applink"`) {
|
||||
t.Fatalf("output = %s, want normalized task GUID", stdout.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskCompleteAlreadyCompletedReturnsServerState(t *testing.T) {
|
||||
f, stdout, _, reg := taskShortcutTestFactory(t)
|
||||
warmTenantToken(t, f, reg)
|
||||
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/task/v2/tasks/task-guid-done",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "success",
|
||||
"data": map[string]interface{}{
|
||||
"task": map[string]interface{}{
|
||||
"guid": "task-guid-done",
|
||||
"summary": "Already done",
|
||||
"completed_at": "1775174400000",
|
||||
"url": "https://example.com/task-guid-done",
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
err := runMountedTaskShortcut(t, CompleteTask, []string{
|
||||
"+complete", "--task-id", "task-guid-done", "--format", "json", "--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("CompleteTask error = %v", err)
|
||||
}
|
||||
reg.Verify(t)
|
||||
|
||||
var envelope map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode output: %v\n%s", err, stdout.String())
|
||||
}
|
||||
data, _ := envelope["data"].(map[string]interface{})
|
||||
if data["status"] != "done" || data["completed_at"] != "1775174400000" || data["already_completed"] != true {
|
||||
t.Fatalf("completion state = %#v, want done/already_completed server state", data)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskCompleteRejectsDisplayNumberBeforeRead(t *testing.T) {
|
||||
f, stdout, _, reg := taskShortcutTestFactory(t)
|
||||
warmTenantToken(t, f, reg)
|
||||
|
||||
err := runMountedTaskShortcut(t, CompleteTask, []string{
|
||||
"+complete", "--task-id", "t12345", "--format", "json", "--as", "bot",
|
||||
}, f, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("CompleteTask error = nil, want invalid task ID error")
|
||||
}
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("error = %T %v, want typed invalid-argument error", err, err)
|
||||
}
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || validationErr.Param != "--task-id" {
|
||||
t.Fatalf("error param = %#v, want --task-id", validationErr)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,14 @@ func splitAndTrimCSV(input string) []string {
|
||||
return out
|
||||
}
|
||||
|
||||
func buildSearchPageParams(pageToken string) map[string]interface{} {
|
||||
params := map[string]interface{}{}
|
||||
if pageToken != "" {
|
||||
params["page_token"] = pageToken
|
||||
}
|
||||
return params
|
||||
}
|
||||
|
||||
func parseTimeRangeMillis(input string) (string, string, error) {
|
||||
if strings.TrimSpace(input) == "" {
|
||||
return "", "", nil
|
||||
|
||||
@@ -37,6 +37,31 @@ func TestSplitAndTrimCSV(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildSearchPageParams(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
pageToken string
|
||||
wantToken string
|
||||
wantKey bool
|
||||
}{
|
||||
{name: "first page omits token"},
|
||||
{name: "subsequent page includes token", pageToken: "pt_123", wantToken: "pt_123", wantKey: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
params := buildSearchPageParams(tt.pageToken)
|
||||
got, present := params["page_token"]
|
||||
if present != tt.wantKey {
|
||||
t.Fatalf("page_token present = %v, want %v; params = %#v", present, tt.wantKey, params)
|
||||
}
|
||||
if tt.wantKey && got != tt.wantToken {
|
||||
t.Fatalf("page_token = %v, want %q", got, tt.wantToken)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestOutputTaskSummary(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
|
||||
@@ -44,8 +44,10 @@ var SearchTask = common.Shortcut{
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
}
|
||||
params := buildSearchPageParams(runtime.Str("page-token"))
|
||||
return common.NewDryRunAPI().
|
||||
POST("/open-apis/task/v2/tasks/search").
|
||||
Params(params).
|
||||
Body(body).
|
||||
Desc("Then GET /open-apis/task/v2/tasks/:guid for each search hit to render standard output")
|
||||
},
|
||||
@@ -74,9 +76,9 @@ var SearchTask = common.Shortcut{
|
||||
var lastPageToken string
|
||||
var lastHasMore bool
|
||||
var notice string
|
||||
currentBody := body
|
||||
params := buildSearchPageParams(runtime.Str("page-token"))
|
||||
for page := 0; page < pageLimit; page++ {
|
||||
data, err := callTaskAPITyped(runtime, http.MethodPost, "/open-apis/task/v2/tasks/search", nil, currentBody)
|
||||
data, err := callTaskAPITyped(runtime, http.MethodPost, "/open-apis/task/v2/tasks/search", params, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -90,7 +92,7 @@ var SearchTask = common.Shortcut{
|
||||
if !lastHasMore || lastPageToken == "" {
|
||||
break
|
||||
}
|
||||
currentBody["page_token"] = lastPageToken
|
||||
params["page_token"] = lastPageToken
|
||||
}
|
||||
|
||||
enriched := make([]map[string]interface{}, 0, len(rawItems))
|
||||
@@ -183,9 +185,6 @@ func buildTaskSearchBody(runtime *common.RuntimeContext) (map[string]interface{}
|
||||
if len(filter) > 0 {
|
||||
body["filter"] = filter
|
||||
}
|
||||
if pageToken := runtime.Str("page-token"); pageToken != "" {
|
||||
body["page_token"] = pageToken
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
|
||||
129
shortcuts/task/task_search_pagination_test.go
Normal file
129
shortcuts/task/task_search_pagination_test.go
Normal file
@@ -0,0 +1,129 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package task
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
)
|
||||
|
||||
func TestSearchPaginationUsesQueryToken(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
shortcut common.Shortcut
|
||||
command string
|
||||
url string
|
||||
}{
|
||||
{
|
||||
name: "tasks",
|
||||
shortcut: SearchTask,
|
||||
command: "+search",
|
||||
url: "/open-apis/task/v2/tasks/search",
|
||||
},
|
||||
{
|
||||
name: "tasklists",
|
||||
shortcut: SearchTasklist,
|
||||
command: "+tasklist-search",
|
||||
url: "/open-apis/task/v2/tasklists/search",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f, stdout, _, reg := taskShortcutTestFactory(t)
|
||||
warmTenantToken(t, f, reg)
|
||||
|
||||
var pageTokens []string
|
||||
reg.Register(searchPaginationStub(t, tt.url, "next_pt", true, &pageTokens))
|
||||
reg.Register(searchPaginationStub(t, tt.url, "", false, &pageTokens))
|
||||
|
||||
shortcut := tt.shortcut
|
||||
shortcut.AuthTypes = []string{"bot", "user"}
|
||||
err := runMountedTaskShortcut(t, shortcut, []string{
|
||||
tt.command,
|
||||
"--query", "pagination",
|
||||
"--page-token", "initial_pt",
|
||||
"--page-limit", "2",
|
||||
"--as", "bot",
|
||||
"--format", "json",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("search command failed: %v", err)
|
||||
}
|
||||
|
||||
want := []string{"initial_pt", "next_pt"}
|
||||
if !reflect.DeepEqual(pageTokens, want) {
|
||||
t.Fatalf("search page tokens = %#v, want %#v", pageTokens, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func assertSearchDryRunPageToken(t *testing.T, preview *common.DryRunAPI, want string) {
|
||||
t.Helper()
|
||||
|
||||
data, err := preview.MarshalJSON()
|
||||
if err != nil {
|
||||
t.Fatalf("marshal search dry-run preview: %v", err)
|
||||
}
|
||||
var envelope struct {
|
||||
API []struct {
|
||||
Params map[string]interface{} `json:"params"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal(data, &envelope); err != nil {
|
||||
t.Fatalf("decode search dry-run preview: %v", err)
|
||||
}
|
||||
if len(envelope.API) != 1 {
|
||||
t.Fatalf("search dry-run API call count = %d, want 1; preview = %s", len(envelope.API), data)
|
||||
}
|
||||
call := envelope.API[0]
|
||||
if got, _ := call.Params["page_token"].(string); got != want {
|
||||
t.Fatalf("search dry-run params.page_token = %q, want %q; preview = %s", got, want, data)
|
||||
}
|
||||
if _, present := call.Body["page_token"]; present {
|
||||
t.Fatalf("search dry-run body unexpectedly contains page_token; preview = %s", data)
|
||||
}
|
||||
}
|
||||
|
||||
func searchPaginationStub(t *testing.T, endpoint, responseToken string, hasMore bool, capturedTokens *[]string) *httpmock.Stub {
|
||||
t.Helper()
|
||||
return &httpmock.Stub{
|
||||
Method: http.MethodPost,
|
||||
URL: endpoint,
|
||||
OnMatch: func(req *http.Request) {
|
||||
*capturedTokens = append(*capturedTokens, req.URL.Query().Get("page_token"))
|
||||
|
||||
body, err := io.ReadAll(req.Body)
|
||||
if err != nil {
|
||||
t.Errorf("read search request body: %v", err)
|
||||
return
|
||||
}
|
||||
var payload map[string]interface{}
|
||||
if err := json.Unmarshal(body, &payload); err != nil {
|
||||
t.Errorf("decode search request body: %v", err)
|
||||
return
|
||||
}
|
||||
if _, present := payload["page_token"]; present {
|
||||
t.Errorf("search request body unexpectedly contains page_token: %s", body)
|
||||
}
|
||||
},
|
||||
Body: map[string]interface{}{
|
||||
"code": 0,
|
||||
"msg": "success",
|
||||
"data": map[string]interface{}{
|
||||
"has_more": hasMore,
|
||||
"page_token": responseToken,
|
||||
"items": []interface{}{},
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -37,9 +37,12 @@ func TestBuildTaskSearchBody(t *testing.T) {
|
||||
check: func(t *testing.T, body map[string]interface{}) {
|
||||
filter := body["filter"].(map[string]interface{})
|
||||
dueTime := filter["due_time"].(map[string]interface{})
|
||||
if body["query"] != "release" || body["page_token"] != "pt_123" {
|
||||
if body["query"] != "release" {
|
||||
t.Fatalf("unexpected body: %#v", body)
|
||||
}
|
||||
if _, present := body["page_token"]; present {
|
||||
t.Fatalf("body unexpectedly contains page_token: %#v", body)
|
||||
}
|
||||
if len(filter["creator_ids"].([]string)) != 2 || filter["is_completed"] != true {
|
||||
t.Fatalf("unexpected filter: %#v", filter)
|
||||
}
|
||||
@@ -104,9 +107,10 @@ func TestBuildTaskSearchBody(t *testing.T) {
|
||||
|
||||
func TestSearchTask_DryRun(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setup func(*cobra.Command)
|
||||
wantParts []string
|
||||
name string
|
||||
setup func(*cobra.Command)
|
||||
wantPageToken string
|
||||
wantParts []string
|
||||
}{
|
||||
{
|
||||
name: "valid dry run",
|
||||
@@ -114,7 +118,8 @@ func TestSearchTask_DryRun(t *testing.T) {
|
||||
_ = cmd.Flags().Set("query", "demo")
|
||||
_ = cmd.Flags().Set("page-token", "pt_demo")
|
||||
},
|
||||
wantParts: []string{"POST /open-apis/task/v2/tasks/search", `"query":"demo"`},
|
||||
wantPageToken: "pt_demo",
|
||||
wantParts: []string{`"query":"demo"`},
|
||||
},
|
||||
{
|
||||
name: "dry run error on invalid due",
|
||||
@@ -143,7 +148,11 @@ func TestSearchTask_DryRun(t *testing.T) {
|
||||
t.Fatalf("Validate() error = %v", err)
|
||||
}
|
||||
}
|
||||
out := SearchTask.DryRun(nil, runtime).Format()
|
||||
preview := SearchTask.DryRun(nil, runtime)
|
||||
if tt.wantPageToken != "" {
|
||||
assertSearchDryRunPageToken(t, preview, tt.wantPageToken)
|
||||
}
|
||||
out := preview.Format()
|
||||
for _, want := range tt.wantParts {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Fatalf("dry run output missing %q: %s", want, out)
|
||||
|
||||
@@ -41,8 +41,10 @@ var SearchTasklist = common.Shortcut{
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
}
|
||||
params := buildSearchPageParams(runtime.Str("page-token"))
|
||||
return common.NewDryRunAPI().
|
||||
POST("/open-apis/task/v2/tasklists/search").
|
||||
Params(params).
|
||||
Body(body).
|
||||
Desc("Then GET /open-apis/task/v2/tasklists/:guid for each search hit to render standard output")
|
||||
},
|
||||
@@ -71,9 +73,9 @@ var SearchTasklist = common.Shortcut{
|
||||
var lastPageToken string
|
||||
var lastHasMore bool
|
||||
var notice string
|
||||
currentBody := body
|
||||
params := buildSearchPageParams(runtime.Str("page-token"))
|
||||
for page := 0; page < pageLimit; page++ {
|
||||
data, err := callTaskAPITyped(runtime, http.MethodPost, "/open-apis/task/v2/tasklists/search", nil, currentBody)
|
||||
data, err := callTaskAPITyped(runtime, http.MethodPost, "/open-apis/task/v2/tasklists/search", params, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -87,7 +89,7 @@ var SearchTasklist = common.Shortcut{
|
||||
if !lastHasMore || lastPageToken == "" {
|
||||
break
|
||||
}
|
||||
currentBody["page_token"] = lastPageToken
|
||||
params["page_token"] = lastPageToken
|
||||
}
|
||||
|
||||
tasklists := make([]map[string]interface{}, 0, len(rawItems))
|
||||
@@ -170,9 +172,6 @@ func buildTasklistSearchBody(runtime *common.RuntimeContext) (map[string]interfa
|
||||
if len(filter) > 0 {
|
||||
body["filter"] = filter
|
||||
}
|
||||
if pageToken := runtime.Str("page-token"); pageToken != "" {
|
||||
body["page_token"] = pageToken
|
||||
}
|
||||
return body, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -33,8 +33,8 @@ func TestBuildTasklistSearchBody(t *testing.T) {
|
||||
check: func(t *testing.T, body map[string]interface{}) {
|
||||
filter := body["filter"].(map[string]interface{})
|
||||
createTime := filter["create_time"].(map[string]interface{})
|
||||
if body["page_token"] != "pt_tl" {
|
||||
t.Fatalf("unexpected body: %#v", body)
|
||||
if _, present := body["page_token"]; present {
|
||||
t.Fatalf("body unexpectedly contains page_token: %#v", body)
|
||||
}
|
||||
if filter["user_id"].([]string)[0] != "ou_creator" {
|
||||
t.Fatalf("unexpected filter: %#v", filter)
|
||||
@@ -80,9 +80,10 @@ func TestBuildTasklistSearchBody(t *testing.T) {
|
||||
|
||||
func TestSearchTasklist_DryRun(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
setup func(*cobra.Command)
|
||||
wantParts []string
|
||||
name string
|
||||
setup func(*cobra.Command)
|
||||
wantPageToken string
|
||||
wantParts []string
|
||||
}{
|
||||
{
|
||||
name: "valid dry run",
|
||||
@@ -90,7 +91,8 @@ func TestSearchTasklist_DryRun(t *testing.T) {
|
||||
_ = cmd.Flags().Set("query", "Q2")
|
||||
_ = cmd.Flags().Set("page-token", "pt_tl")
|
||||
},
|
||||
wantParts: []string{"POST /open-apis/task/v2/tasklists/search", `"query":"Q2"`},
|
||||
wantPageToken: "pt_tl",
|
||||
wantParts: []string{`"query":"Q2"`},
|
||||
},
|
||||
{
|
||||
name: "dry run error on invalid create time",
|
||||
@@ -116,7 +118,11 @@ func TestSearchTasklist_DryRun(t *testing.T) {
|
||||
t.Fatalf("Validate() error = %v", err)
|
||||
}
|
||||
}
|
||||
out := SearchTasklist.DryRun(nil, runtime).Format()
|
||||
preview := SearchTasklist.DryRun(nil, runtime)
|
||||
if tt.wantPageToken != "" {
|
||||
assertSearchDryRunPageToken(t, preview, tt.wantPageToken)
|
||||
}
|
||||
out := preview.Format()
|
||||
for _, want := range tt.wantParts {
|
||||
if !strings.Contains(out, want) {
|
||||
t.Fatalf("dry run output missing %q: %s", want, out)
|
||||
|
||||
@@ -27,27 +27,42 @@ var UpdateTask = common.Shortcut{
|
||||
HasFormat: true,
|
||||
|
||||
Flags: []common.Flag{
|
||||
{Name: "task-id", Desc: "task id (comma-separated for multiple)", Required: true},
|
||||
{Name: "task-id", Desc: "task GUID or task applink URL (comma-separated for multiple)", Required: true},
|
||||
{Name: "summary", Desc: "task title"},
|
||||
{Name: "description", Desc: "task description"},
|
||||
{Name: "due", Desc: "due date (ISO 8601 / date:YYYY-MM-DD / relative:+2d / ms timestamp)"},
|
||||
{Name: "data", Desc: "JSON payload for task object"},
|
||||
},
|
||||
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
_, err := parseTaskGUIDs(runtime.Str("task-id"))
|
||||
return err
|
||||
},
|
||||
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
body, err := buildTaskUpdateBody(runtime)
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
}
|
||||
taskIds := strings.Split(runtime.Str("task-id"), ",")
|
||||
taskId := url.PathEscape(strings.TrimSpace(taskIds[0]))
|
||||
return common.NewDryRunAPI().
|
||||
PATCH("/open-apis/task/v2/tasks/" + taskId).
|
||||
Params(map[string]interface{}{"user_id_type": "open_id"}).
|
||||
Body(body)
|
||||
taskIDs, err := parseTaskGUIDs(runtime.Str("task-id"))
|
||||
if err != nil {
|
||||
return common.NewDryRunAPI().Set("error", err.Error())
|
||||
}
|
||||
preview := common.NewDryRunAPI()
|
||||
for _, taskID := range taskIDs {
|
||||
preview.PATCH("/open-apis/task/v2/tasks/" + url.PathEscape(taskID)).
|
||||
Params(map[string]interface{}{"user_id_type": "open_id"}).
|
||||
Body(body)
|
||||
}
|
||||
return preview
|
||||
},
|
||||
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
taskIDs, err := parseTaskGUIDs(runtime.Str("task-id"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
body, err := buildTaskUpdateBody(runtime)
|
||||
if err != nil {
|
||||
// buildTaskUpdateBody already returns a typed validation error;
|
||||
@@ -55,17 +70,11 @@ var UpdateTask = common.Shortcut{
|
||||
return err
|
||||
}
|
||||
|
||||
taskIds := strings.Split(runtime.Str("task-id"), ",")
|
||||
var updatedTasks []map[string]interface{}
|
||||
|
||||
for _, taskId := range taskIds {
|
||||
taskId = strings.TrimSpace(taskId)
|
||||
if taskId == "" {
|
||||
continue
|
||||
}
|
||||
|
||||
for _, taskID := range taskIDs {
|
||||
params := map[string]interface{}{"user_id_type": "open_id"}
|
||||
data, err := callTaskAPITyped(runtime, http.MethodPatch, "/open-apis/task/v2/tasks/"+url.PathEscape(taskId), params, body)
|
||||
data, err := callTaskAPITyped(runtime, http.MethodPatch, "/open-apis/task/v2/tasks/"+url.PathEscape(taskID), params, body)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -76,19 +85,28 @@ var UpdateTask = common.Shortcut{
|
||||
}
|
||||
}
|
||||
|
||||
updateFields, _ := body["update_fields"].([]string)
|
||||
var tasks []map[string]interface{}
|
||||
for _, task := range updatedTasks {
|
||||
guid, _ := task["guid"].(string)
|
||||
urlVal, _ := task["url"].(string)
|
||||
urlVal = truncateTaskURL(urlVal)
|
||||
confirmed := make(map[string]interface{})
|
||||
for _, field := range updateFields {
|
||||
if value, ok := task[field]; ok {
|
||||
confirmed[field] = value
|
||||
}
|
||||
}
|
||||
tasks = append(tasks, map[string]interface{}{
|
||||
"guid": guid,
|
||||
"url": urlVal,
|
||||
"guid": guid,
|
||||
"url": urlVal,
|
||||
"confirmed": confirmed,
|
||||
})
|
||||
}
|
||||
// Standardized write output: return resource identifiers
|
||||
outData := map[string]interface{}{
|
||||
"tasks": tasks,
|
||||
"updated_fields": updateFields,
|
||||
"tasks": tasks,
|
||||
}
|
||||
|
||||
runtime.OutFormat(outData, &output.Meta{Count: len(updatedTasks)}, func(w io.Writer) {
|
||||
@@ -112,6 +130,26 @@ var UpdateTask = common.Shortcut{
|
||||
},
|
||||
}
|
||||
|
||||
func parseTaskGUIDs(input string) ([]string, error) {
|
||||
parts := strings.Split(input, ",")
|
||||
taskGUIDs := make([]string, 0, len(parts))
|
||||
for _, part := range parts {
|
||||
if strings.TrimSpace(part) == "" {
|
||||
continue
|
||||
}
|
||||
guid, err := parseTaskGUID(part)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
taskGUIDs = append(taskGUIDs, guid)
|
||||
}
|
||||
if len(taskGUIDs) == 0 {
|
||||
_, err := parseTaskGUID("")
|
||||
return nil, err
|
||||
}
|
||||
return taskGUIDs, nil
|
||||
}
|
||||
|
||||
func buildTaskUpdateBody(runtime *common.RuntimeContext) (map[string]interface{}, error) {
|
||||
taskObj := make(map[string]interface{})
|
||||
var updateFields []string
|
||||
|
||||
201
shortcuts/task/task_update_test.go
Normal file
201
shortcuts/task/task_update_test.go
Normal file
@@ -0,0 +1,201 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package task
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/internal/httpmock"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
func TestParseTaskGUIDs(t *testing.T) {
|
||||
got, err := parseTaskGUIDs(" task-guid-1, https://applink.larksuite.com/client/todo/detail?guid=task-guid-2 ")
|
||||
if err != nil {
|
||||
t.Fatalf("parseTaskGUIDs() error = %v", err)
|
||||
}
|
||||
want := []string{"task-guid-1", "task-guid-2"}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("parseTaskGUIDs() = %v, want %v", got, want)
|
||||
}
|
||||
|
||||
_, err = parseTaskGUIDs("task-guid-1,t12345")
|
||||
if err == nil {
|
||||
t.Fatal("parseTaskGUIDs() error = nil, want invalid display-number error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskUpdateDryRunPreviewsEveryTaskID(t *testing.T) {
|
||||
cmd := &cobra.Command{}
|
||||
cmd.Flags().String("task-id", "task-guid-1,https://applink.larksuite.com/client/todo/detail?guid=task-guid-2", "")
|
||||
cmd.Flags().String("summary", "updated", "")
|
||||
cmd.Flags().String("description", "", "")
|
||||
cmd.Flags().String("due", "", "")
|
||||
cmd.Flags().String("data", "", "")
|
||||
|
||||
preview := UpdateTask.DryRun(context.Background(), &common.RuntimeContext{Cmd: cmd})
|
||||
payload, err := json.Marshal(preview)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal dry-run preview: %v", err)
|
||||
}
|
||||
|
||||
var got struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Params map[string]interface{} `json:"params"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
if err := json.Unmarshal(payload, &got); err != nil {
|
||||
t.Fatalf("decode dry-run preview: %v", err)
|
||||
}
|
||||
if len(got.API) != 2 {
|
||||
t.Fatalf("dry-run API calls = %d, want 2; payload: %s", len(got.API), payload)
|
||||
}
|
||||
|
||||
wantURLs := []string{
|
||||
"/open-apis/task/v2/tasks/task-guid-1",
|
||||
"/open-apis/task/v2/tasks/task-guid-2",
|
||||
}
|
||||
for i, call := range got.API {
|
||||
if call.Method != "PATCH" {
|
||||
t.Errorf("api[%d].method = %q, want PATCH", i, call.Method)
|
||||
}
|
||||
if call.URL != wantURLs[i] {
|
||||
t.Errorf("api[%d].url = %q, want %q", i, call.URL, wantURLs[i])
|
||||
}
|
||||
if !reflect.DeepEqual(call.Params, map[string]interface{}{"user_id_type": "open_id"}) {
|
||||
t.Errorf("api[%d].params = %#v", i, call.Params)
|
||||
}
|
||||
if !reflect.DeepEqual(call.Body, got.API[0].Body) {
|
||||
t.Errorf("api[%d].body = %#v, want same body as first call %#v", i, call.Body, got.API[0].Body)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskUpdateNormalizesAllIDsAndReturnsConfirmedFields(t *testing.T) {
|
||||
f, stdout, _, reg := taskShortcutTestFactory(t)
|
||||
warmTenantToken(t, f, reg)
|
||||
|
||||
first := &httpmock.Stub{
|
||||
Method: "PATCH",
|
||||
URL: "/open-apis/task/v2/tasks/task-guid-1",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "success",
|
||||
"data": map[string]interface{}{
|
||||
"task": map[string]interface{}{
|
||||
"guid": "task-guid-1",
|
||||
"url": "https://example.com/task-guid-1",
|
||||
"summary": "server summary one",
|
||||
"description": "server description one",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
second := &httpmock.Stub{
|
||||
Method: "PATCH",
|
||||
URL: "/open-apis/task/v2/tasks/task-guid-2",
|
||||
Body: map[string]interface{}{
|
||||
"code": 0, "msg": "success",
|
||||
"data": map[string]interface{}{
|
||||
"task": map[string]interface{}{
|
||||
"guid": "task-guid-2",
|
||||
"url": "https://example.com/task-guid-2",
|
||||
"summary": "server summary two",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
reg.Register(first)
|
||||
reg.Register(second)
|
||||
|
||||
err := runMountedTaskShortcut(t, UpdateTask, []string{
|
||||
"+update",
|
||||
"--task-id", "task-guid-1,https://applink.larksuite.com/client/todo/detail?guid=task-guid-2",
|
||||
"--summary", "requested summary",
|
||||
"--description", "requested description",
|
||||
"--format", "json",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err != nil {
|
||||
t.Fatalf("UpdateTask error = %v", err)
|
||||
}
|
||||
reg.Verify(t)
|
||||
|
||||
var envelope map[string]interface{}
|
||||
if err := json.Unmarshal(stdout.Bytes(), &envelope); err != nil {
|
||||
t.Fatalf("decode output: %v\n%s", err, stdout.String())
|
||||
}
|
||||
data, ok := envelope["data"].(map[string]interface{})
|
||||
if !ok {
|
||||
t.Fatalf("data = %#v, want object", envelope["data"])
|
||||
}
|
||||
if got := stringSlice(data["updated_fields"]); !reflect.DeepEqual(got, []string{"summary", "description"}) {
|
||||
t.Fatalf("updated_fields = %v, want [summary description]", got)
|
||||
}
|
||||
|
||||
tasks, ok := data["tasks"].([]interface{})
|
||||
if !ok || len(tasks) != 2 {
|
||||
t.Fatalf("tasks = %#v, want two tasks", data["tasks"])
|
||||
}
|
||||
firstTask := tasks[0].(map[string]interface{})
|
||||
if firstTask["guid"] != "task-guid-1" || firstTask["url"] != "https://example.com/task-guid-1" {
|
||||
t.Fatalf("first task identifiers = %#v", firstTask)
|
||||
}
|
||||
if got := firstTask["confirmed"]; !reflect.DeepEqual(got, map[string]interface{}{
|
||||
"summary": "server summary one", "description": "server description one",
|
||||
}) {
|
||||
t.Fatalf("first confirmed = %#v", got)
|
||||
}
|
||||
|
||||
secondTask := tasks[1].(map[string]interface{})
|
||||
if got := secondTask["confirmed"]; !reflect.DeepEqual(got, map[string]interface{}{
|
||||
"summary": "server summary two",
|
||||
}) {
|
||||
t.Fatalf("second confirmed = %#v; omitted server fields must not be echoed from the request", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTaskUpdateValidatesEveryIDBeforeFirstWrite(t *testing.T) {
|
||||
f, stdout, _, reg := taskShortcutTestFactory(t)
|
||||
warmTenantToken(t, f, reg)
|
||||
|
||||
err := runMountedTaskShortcut(t, UpdateTask, []string{
|
||||
"+update",
|
||||
"--task-id", "task-guid-1,t12345",
|
||||
"--summary", "must not be written",
|
||||
"--format", "json",
|
||||
"--as", "bot",
|
||||
}, f, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("UpdateTask error = nil, want invalid task ID error")
|
||||
}
|
||||
|
||||
problem, ok := errs.ProblemOf(err)
|
||||
if !ok || problem.Category != errs.CategoryValidation || problem.Subtype != errs.SubtypeInvalidArgument {
|
||||
t.Fatalf("error = %T %v, want typed invalid-argument error", err, err)
|
||||
}
|
||||
var validationErr *errs.ValidationError
|
||||
if !errors.As(err, &validationErr) || validationErr.Param != "--task-id" {
|
||||
t.Fatalf("error param = %#v, want --task-id", validationErr)
|
||||
}
|
||||
}
|
||||
|
||||
func stringSlice(value interface{}) []string {
|
||||
items, _ := value.([]interface{})
|
||||
result := make([]string, 0, len(items))
|
||||
for _, item := range items {
|
||||
if str, ok := item.(string); ok {
|
||||
result = append(result, str)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
@@ -12,6 +12,7 @@ func Shortcuts() []common.Shortcut {
|
||||
return []common.Shortcut{
|
||||
WhiteboardUpdate,
|
||||
WhiteboardUpdateOld,
|
||||
WhiteboardExport,
|
||||
WhiteboardQuery,
|
||||
}
|
||||
}
|
||||
|
||||
728
shortcuts/whiteboard/whiteboard_export.go
Normal file
728
shortcuts/whiteboard/whiteboard_export.go
Normal file
@@ -0,0 +1,728 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
package whiteboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
|
||||
)
|
||||
|
||||
const (
|
||||
// WhiteboardExportAsPreview exports a whiteboard preview image.
|
||||
WhiteboardExportAsPreview = "preview"
|
||||
// WhiteboardExportAsSvg exports a whiteboard as SVG.
|
||||
WhiteboardExportAsSvg = "svg"
|
||||
// WhiteboardExportAsSource exports Mermaid or PlantUML source extracted from the whiteboard.
|
||||
WhiteboardExportAsSource = "source"
|
||||
// WhiteboardExportAsRaw exports the raw whiteboard node payload.
|
||||
WhiteboardExportAsRaw = "raw"
|
||||
|
||||
// Legacy output type names accepted for backward compatibility.
|
||||
WhiteboardQueryAsImage = "image"
|
||||
// WhiteboardQueryAsSvg is deprecated; use WhiteboardExportAsSvg.
|
||||
WhiteboardQueryAsSvg = WhiteboardExportAsSvg
|
||||
WhiteboardQueryAsCode = "code"
|
||||
// WhiteboardQueryAsRaw is deprecated; use WhiteboardExportAsRaw.
|
||||
WhiteboardQueryAsRaw = WhiteboardExportAsRaw
|
||||
)
|
||||
|
||||
// SyntaxType identifies the diagram syntax extracted from whiteboard code blocks.
|
||||
type SyntaxType int
|
||||
|
||||
const (
|
||||
// SyntaxTypePlantUML marks PlantUML code blocks.
|
||||
SyntaxTypePlantUML SyntaxType = 1
|
||||
// SyntaxTypeMermaid marks Mermaid code blocks.
|
||||
SyntaxTypeMermaid SyntaxType = 2
|
||||
)
|
||||
|
||||
// SyntaxTypeNameMap maps whiteboard syntax types to their CLI output names.
|
||||
var SyntaxTypeNameMap = map[SyntaxType]string{
|
||||
SyntaxTypePlantUML: "plantuml",
|
||||
SyntaxTypeMermaid: "mermaid",
|
||||
}
|
||||
|
||||
// SyntaxTypeExtensionMap maps whiteboard syntax types to their default file extensions.
|
||||
var SyntaxTypeExtensionMap = map[SyntaxType]string{
|
||||
SyntaxTypePlantUML: ".puml",
|
||||
SyntaxTypeMermaid: ".mmd",
|
||||
}
|
||||
|
||||
// String returns the CLI-facing name for the syntax type.
|
||||
func (s SyntaxType) String() string {
|
||||
return SyntaxTypeNameMap[s]
|
||||
}
|
||||
|
||||
// ExtensionName returns the default file extension for the syntax type.
|
||||
func (s SyntaxType) ExtensionName() string {
|
||||
return SyntaxTypeExtensionMap[s]
|
||||
}
|
||||
|
||||
// IsValid reports whether the syntax type is one of the supported whiteboard code syntaxes.
|
||||
func (s SyntaxType) IsValid() bool {
|
||||
return s == SyntaxTypePlantUML || s == SyntaxTypeMermaid
|
||||
}
|
||||
|
||||
var wbExportScopes = []string{"board:whiteboard:node:read"}
|
||||
var wbExportAuthTypes = []string{"user", "bot"}
|
||||
var wbExportFlags = []common.Flag{
|
||||
{Name: "whiteboard-token", Desc: "whiteboard token of the whiteboard. You will need read permission to download preview image.", Required: true},
|
||||
{Name: "output-type", Desc: "output whiteboard as: preview | svg | source | raw.", Required: true, Enum: []string{"preview", "svg", "source", "raw"}},
|
||||
{Name: "output", Desc: "output path. It is required when --output-type preview. If not specified when --output-type svg/source/raw, it will output directly.", Required: false},
|
||||
{Name: "overwrite", Desc: "overwrite existing file if it exists", Required: false, Type: "bool"},
|
||||
}
|
||||
|
||||
var wbQueryFlags = []common.Flag{
|
||||
{Name: "whiteboard-token", Desc: "whiteboard token of the whiteboard. You will need read permission to download preview image.", Required: true},
|
||||
{Name: "output_as", Desc: "output whiteboard as: image | svg | code | raw.", Required: true, Enum: []string{"image", "svg", "code", "raw"}},
|
||||
{Name: "output", Desc: "output path. It is required when output as image. If not specified when --output_as svg/code/raw, it will output directly.", Required: false},
|
||||
{Name: "overwrite", Desc: "overwrite existing file if it exists", Required: false, Type: "bool"},
|
||||
}
|
||||
|
||||
func wbExportOutputType(runtime *common.RuntimeContext) (string, string) {
|
||||
normalized, ok := normalizeWhiteboardExportOutputType(runtime.Str("output-type"))
|
||||
if !ok {
|
||||
return "", "--output-type"
|
||||
}
|
||||
return normalized, "--output-type"
|
||||
}
|
||||
|
||||
func wbQueryOutputType(runtime *common.RuntimeContext) (string, string) {
|
||||
normalized, ok := normalizeLegacyWhiteboardExportOutputType(runtime.Str("output_as"))
|
||||
if !ok {
|
||||
return "", "--output_as"
|
||||
}
|
||||
return normalized, "--output_as"
|
||||
}
|
||||
|
||||
func normalizeWhiteboardExportOutputType(outputType string) (string, bool) {
|
||||
switch outputType {
|
||||
case WhiteboardExportAsPreview:
|
||||
return WhiteboardExportAsPreview, true
|
||||
case WhiteboardExportAsSvg:
|
||||
return WhiteboardExportAsSvg, true
|
||||
case WhiteboardExportAsSource:
|
||||
return WhiteboardExportAsSource, true
|
||||
case WhiteboardExportAsRaw:
|
||||
return WhiteboardExportAsRaw, true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
func normalizeLegacyWhiteboardExportOutputType(outputType string) (string, bool) {
|
||||
switch outputType {
|
||||
case WhiteboardQueryAsImage:
|
||||
return WhiteboardExportAsPreview, true
|
||||
case WhiteboardQueryAsCode:
|
||||
return WhiteboardExportAsSource, true
|
||||
default:
|
||||
return normalizeWhiteboardExportOutputType(outputType)
|
||||
}
|
||||
}
|
||||
|
||||
func wbExportOutputTypeError(param string) *errs.ValidationError {
|
||||
if param == "--output_as" {
|
||||
return errs.NewValidationError(
|
||||
errs.SubtypeInvalidArgument,
|
||||
"--output_as flag must be one of: image | svg | code | raw",
|
||||
).WithParam("--output_as")
|
||||
}
|
||||
return errs.NewValidationError(
|
||||
errs.SubtypeInvalidArgument,
|
||||
"--output-type flag must be one of: preview | svg | source | raw",
|
||||
).WithParam("--output-type")
|
||||
}
|
||||
|
||||
func wbExportValidate(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return wbExportValidateWithOutputType(ctx, runtime, wbExportOutputType)
|
||||
}
|
||||
|
||||
func wbQueryValidate(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return wbExportValidateWithOutputType(ctx, runtime, wbQueryOutputType)
|
||||
}
|
||||
|
||||
func wbExportValidateWithOutputType(ctx context.Context, runtime *common.RuntimeContext, outputTypeFn func(*common.RuntimeContext) (string, string)) error {
|
||||
// Check if token contains control characters
|
||||
token := runtime.Str("whiteboard-token")
|
||||
if err := common.RejectDangerousCharsTyped("--whiteboard-token", token); err != nil {
|
||||
return err
|
||||
}
|
||||
outputType, outputTypeParam := outputTypeFn(runtime)
|
||||
if outputType == "" {
|
||||
return wbExportOutputTypeError(outputTypeParam)
|
||||
}
|
||||
|
||||
out := runtime.Str("output")
|
||||
if out != "" {
|
||||
if _, err := runtime.ResolveSavePath(out); err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid output path: %s", err).WithParam("--output").WithCause(err)
|
||||
}
|
||||
}
|
||||
if out == "" && outputType == WhiteboardExportAsPreview {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "need a output path to export whiteboard as preview").WithParam("--output")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func wbExportDryRun(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return wbExportDryRunWithOutputType(ctx, runtime, wbExportOutputType)
|
||||
}
|
||||
|
||||
func wbQueryDryRun(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
return wbExportDryRunWithOutputType(ctx, runtime, wbQueryOutputType)
|
||||
}
|
||||
|
||||
func wbExportDryRunWithOutputType(ctx context.Context, runtime *common.RuntimeContext, outputTypeFn func(*common.RuntimeContext) (string, string)) *common.DryRunAPI {
|
||||
outputType, outputTypeParam := outputTypeFn(runtime)
|
||||
token := runtime.Str("whiteboard-token")
|
||||
switch outputType {
|
||||
case WhiteboardExportAsPreview:
|
||||
return common.NewDryRunAPI().
|
||||
GET(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/download_as_image", common.MaskToken(url.PathEscape(token)))).
|
||||
Desc("Export preview image of given whiteboard")
|
||||
case WhiteboardExportAsSource:
|
||||
return common.NewDryRunAPI().
|
||||
GET(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/nodes", common.MaskToken(url.PathEscape(token)))).
|
||||
Desc("Extract Mermaid/Plantuml source from given whiteboard")
|
||||
case WhiteboardExportAsRaw:
|
||||
return common.NewDryRunAPI().
|
||||
GET(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/nodes", common.MaskToken(url.PathEscape(token)))).
|
||||
Desc("Extract raw nodes structure from given whiteboard")
|
||||
case WhiteboardExportAsSvg:
|
||||
return common.NewDryRunAPI().
|
||||
POST(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/export", common.MaskToken(url.PathEscape(token)))).
|
||||
Body(map[string]string{"export_type": "svg"}).
|
||||
Desc("Export SVG of given whiteboard")
|
||||
default:
|
||||
if outputTypeParam == "--output_as" {
|
||||
return common.NewDryRunAPI().Desc("invalid --output_as flag, must be one of: image | svg | code | raw")
|
||||
}
|
||||
return common.NewDryRunAPI().Desc("invalid --output-type flag, must be one of: preview | svg | source | raw")
|
||||
}
|
||||
}
|
||||
|
||||
func wbExportExecute(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return wbExportExecuteWithOutputType(ctx, runtime, wbExportOutputType)
|
||||
}
|
||||
|
||||
func wbQueryExecute(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
return wbExportExecuteWithOutputType(ctx, runtime, wbQueryOutputType)
|
||||
}
|
||||
|
||||
func wbExportExecuteWithOutputType(ctx context.Context, runtime *common.RuntimeContext, outputTypeFn func(*common.RuntimeContext) (string, string)) error {
|
||||
token := runtime.Str("whiteboard-token")
|
||||
outDir := runtime.Str("output")
|
||||
outputType, outputTypeParam := outputTypeFn(runtime)
|
||||
switch outputType {
|
||||
case WhiteboardExportAsPreview:
|
||||
return exportWhiteboardPreview(ctx, runtime, token, outDir)
|
||||
case WhiteboardExportAsSvg:
|
||||
return exportWhiteboardSvg(runtime, token, outDir)
|
||||
case WhiteboardExportAsSource:
|
||||
return exportWhiteboardCode(runtime, token, outDir)
|
||||
case WhiteboardExportAsRaw:
|
||||
return exportWhiteboardRaw(runtime, token, outDir)
|
||||
default:
|
||||
return wbExportOutputTypeError(outputTypeParam)
|
||||
}
|
||||
}
|
||||
|
||||
const WhiteboardExportDescription = "Export an existing whiteboard as preview image, SVG, source code or raw nodes structure."
|
||||
|
||||
// WhiteboardExport registers the `whiteboard +export` shortcut.
|
||||
var WhiteboardExport = common.Shortcut{
|
||||
Service: "whiteboard",
|
||||
Command: "+export",
|
||||
Description: WhiteboardExportDescription,
|
||||
Risk: "read",
|
||||
Scopes: wbExportScopes,
|
||||
AuthTypes: wbExportAuthTypes,
|
||||
Flags: wbExportFlags,
|
||||
HasFormat: true,
|
||||
Validate: wbExportValidate,
|
||||
DryRun: wbExportDryRun,
|
||||
Execute: wbExportExecute,
|
||||
}
|
||||
|
||||
// WhiteboardQuery registers the hidden, backward-compatible `whiteboard +query` shortcut.
|
||||
var WhiteboardQuery = common.Shortcut{
|
||||
Service: "whiteboard",
|
||||
Command: "+query",
|
||||
Description: WhiteboardExportDescription,
|
||||
Risk: "read",
|
||||
Scopes: wbExportScopes,
|
||||
AuthTypes: wbExportAuthTypes,
|
||||
Flags: wbQueryFlags,
|
||||
HasFormat: true,
|
||||
Hidden: true,
|
||||
Validate: wbQueryValidate,
|
||||
DryRun: wbQueryDryRun,
|
||||
Execute: wbQueryExecute,
|
||||
}
|
||||
|
||||
// exportReq defines the request body for whiteboard export APIs.
|
||||
type exportReq struct {
|
||||
ExportType string `json:"export_type"`
|
||||
}
|
||||
|
||||
// exportResp models the whiteboard export response envelope.
|
||||
type exportResp struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data struct {
|
||||
Content string `json:"content"`
|
||||
MimeType string `json:"mime_type"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// exportWhiteboardSvg exports a whiteboard as SVG and writes it to stdout or a file.
|
||||
func exportWhiteboardSvg(runtime *common.RuntimeContext, wbToken, outDir string) error {
|
||||
reqBody := exportReq{ExportType: "svg"}
|
||||
req := &larkcore.ApiReq{
|
||||
HttpMethod: http.MethodPost,
|
||||
ApiPath: fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/export", url.PathEscape(wbToken)),
|
||||
Body: reqBody,
|
||||
}
|
||||
|
||||
resp, err := runtime.DoAPI(req)
|
||||
if err != nil {
|
||||
return wrapWbNetworkErr(err, "export whiteboard svg failed: %v", err)
|
||||
}
|
||||
|
||||
var exportData exportResp
|
||||
if err := json.Unmarshal(resp.RawBody, &exportData); err == nil {
|
||||
if exportData.Code != 0 {
|
||||
subtype := errs.SubtypeUnknown
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
subtype = errs.SubtypeNotFound
|
||||
}
|
||||
return errs.NewAPIError(subtype, "export whiteboard svg failed: %s", exportData.Msg).WithCode(exportData.Code)
|
||||
}
|
||||
} else if resp.StatusCode == http.StatusOK {
|
||||
return errs.NewInternalError(errs.SubtypeInvalidResponse, "parse export response failed: %v", err).WithCause(err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body := common.TruncateStr(strings.TrimSpace(string(resp.RawBody)), 500)
|
||||
if resp.StatusCode >= 500 {
|
||||
return errs.NewNetworkError(errs.SubtypeNetworkServer, "export whiteboard svg failed: HTTP %d: %s", resp.StatusCode, body).
|
||||
WithCode(resp.StatusCode).
|
||||
WithRetryable()
|
||||
}
|
||||
subtype := errs.SubtypeUnknown
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
subtype = errs.SubtypeNotFound
|
||||
}
|
||||
return errs.NewAPIError(subtype, "export whiteboard svg failed: HTTP %d: %s", resp.StatusCode, body).
|
||||
WithCode(resp.StatusCode)
|
||||
}
|
||||
|
||||
svgBytes, err := base64.StdEncoding.DecodeString(exportData.Data.Content)
|
||||
if err != nil {
|
||||
return errs.NewInternalError(errs.SubtypeInvalidResponse, "decode svg base64 failed: %v", err).WithCause(err)
|
||||
}
|
||||
|
||||
if outDir == "" {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"svg_content": string(svgBytes),
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "%s\n", string(svgBytes))
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
finalPath, size, err := saveOutputFile(outDir, ".svg", wbToken, runtime, bytes.NewReader(svgBytes))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"svg_path": finalPath,
|
||||
"size_bytes": size,
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "SVG saved to %s\n", finalPath)
|
||||
fmt.Fprintf(w, "File size: %d bytes", size)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportWhiteboardPreview(ctx context.Context, runtime *common.RuntimeContext, wbToken, outDir string) error {
|
||||
req := &larkcore.ApiReq{
|
||||
HttpMethod: http.MethodGet,
|
||||
ApiPath: fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/download_as_image", url.PathEscape(wbToken)),
|
||||
}
|
||||
// Execute API request. The preview endpoint streams raw image bytes (not a
|
||||
// JSON envelope), so classify by HTTP status: 5xx is retryable network,
|
||||
// while 4xx remains an API-side rejection.
|
||||
resp, err := runtime.DoAPI(req, larkcore.WithFileDownload())
|
||||
if err != nil {
|
||||
return wrapWbNetworkErr(err, "get whiteboard preview failed: %v", err)
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
body := common.TruncateStr(strings.TrimSpace(string(resp.RawBody)), 500)
|
||||
if resp.StatusCode >= 500 {
|
||||
return errs.NewNetworkError(errs.SubtypeNetworkServer, "get whiteboard preview failed: HTTP %d: %s", resp.StatusCode, body).
|
||||
WithCode(resp.StatusCode).
|
||||
WithRetryable()
|
||||
}
|
||||
subtype := errs.SubtypeUnknown
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
subtype = errs.SubtypeNotFound
|
||||
}
|
||||
return errs.NewAPIError(subtype, "get whiteboard preview failed: HTTP %d: %s", resp.StatusCode, body).
|
||||
WithCode(resp.StatusCode)
|
||||
}
|
||||
|
||||
finalPath, size, err := saveWhiteboardPreviewOutput(outDir, wbToken, runtime, resp.Header, bytes.NewReader(resp.RawBody))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"preview_image_path": finalPath,
|
||||
"size_bytes": size,
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Preview image saved to %s\n", finalPath)
|
||||
fmt.Fprintf(w, "Image size: %d bytes", size)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
type wbNodesResp struct {
|
||||
Data struct {
|
||||
Nodes []interface{} `json:"nodes"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func fetchWhiteboardNodes(runtime *common.RuntimeContext, wbToken string) (*wbNodesResp, error) {
|
||||
data, err := runtime.CallAPITyped(http.MethodGet, fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/nodes", url.PathEscape(wbToken)), nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var nodes wbNodesResp
|
||||
rawNodes, _ := data["nodes"]
|
||||
if rawNodes != nil {
|
||||
var ok bool
|
||||
nodes.Data.Nodes, ok = rawNodes.([]interface{})
|
||||
if !ok {
|
||||
return nil, wbInvalidResponse("get whiteboard nodes failed: data.nodes must be an array")
|
||||
}
|
||||
}
|
||||
return &nodes, nil
|
||||
}
|
||||
|
||||
type syntaxInfo struct {
|
||||
code string
|
||||
syntaxType SyntaxType
|
||||
}
|
||||
|
||||
func exportWhiteboardCode(runtime *common.RuntimeContext, wbToken, outDir string) error {
|
||||
wbNodes, err := fetchWhiteboardNodes(runtime, wbToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if wbNodes == nil || wbNodes.Data.Nodes == nil {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"msg": "whiteboard is empty",
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Whiteboard is empty\n")
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
var syntaxBlocks []syntaxInfo
|
||||
for _, node := range wbNodes.Data.Nodes {
|
||||
nodeMap, ok := node.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
syntax, ok := nodeMap["syntax"]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
syntaxMap, ok := syntax.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
code, _ := syntaxMap["code"].(string)
|
||||
var syntaxType SyntaxType
|
||||
switch v := syntaxMap["syntax_type"].(type) {
|
||||
case json.Number:
|
||||
// runtime.ClassifyAPIResponse decodes the response with UseNumber,
|
||||
// so numeric fields arrive as json.Number rather than float64.
|
||||
if n, err := v.Int64(); err == nil {
|
||||
syntaxType = SyntaxType(n)
|
||||
}
|
||||
case float64:
|
||||
syntaxType = SyntaxType(v)
|
||||
case SyntaxType:
|
||||
syntaxType = v
|
||||
}
|
||||
if code != "" && syntaxType.IsValid() {
|
||||
syntaxBlocks = append(syntaxBlocks, syntaxInfo{code: code, syntaxType: syntaxType})
|
||||
}
|
||||
}
|
||||
|
||||
if len(syntaxBlocks) == 0 {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"msg": "no code blocks found in whiteboard",
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "No code blocks found in whiteboard\n")
|
||||
})
|
||||
return nil
|
||||
}
|
||||
// 目前的标准操作是导出到单一文件,和 Doc 展示画板代码块采用相同的逻辑
|
||||
// 如果有需求,可以调整到导出到多个文件的模式
|
||||
if len(syntaxBlocks) > 1 {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"msg": "multiple code blocks found, cannot export directly",
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Multiple code blocks found, cannot export directly\n")
|
||||
})
|
||||
return nil
|
||||
}
|
||||
block := syntaxBlocks[0]
|
||||
|
||||
if outDir == "" {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"code": block.code,
|
||||
"syntax_type": block.syntaxType.String(),
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "%s\n", block.code)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
finalPath, _, err := saveOutputFile(outDir, block.syntaxType.ExtensionName(), wbToken, runtime, strings.NewReader(block.code))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"output_path": finalPath,
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Whiteboard code saved to %s\n", finalPath)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportWhiteboardRaw(runtime *common.RuntimeContext, wbToken, outDir string) error {
|
||||
wbNodes, err := fetchWhiteboardNodes(runtime, wbToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if wbNodes == nil || wbNodes.Data.Nodes == nil {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"msg": "whiteboard is empty",
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Whiteboard is empty\n")
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
jsonData, err := json.MarshalIndent(wbNodes.Data, "", " ")
|
||||
if err != nil {
|
||||
return errs.NewInternalError(errs.SubtypeInvalidResponse, "cannot marshal whiteboard data: %s", err).WithCause(err)
|
||||
}
|
||||
|
||||
if outDir == "" {
|
||||
runtime.OutFormat(wbNodes.Data, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "%s\n", string(jsonData))
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
finalPath, _, err := saveOutputFile(outDir, ".json", wbToken, runtime, bytes.NewReader(jsonData))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"output_path": finalPath,
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Whiteboard raw node structure saved to %s\n", finalPath)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveOutputFile(outPath, ext, token string, runtime *common.RuntimeContext, data io.Reader) (string, int64, error) {
|
||||
// Step 1: Get final output path
|
||||
info, err := runtime.FileIO().Stat(outPath)
|
||||
var finalPath string
|
||||
if err == nil && info.IsDir() {
|
||||
finalPath = filepath.Join(outPath, fmt.Sprintf("whiteboard_%s%s", token, ext))
|
||||
} else {
|
||||
// Fix extension in path
|
||||
currentExt := filepath.Ext(outPath)
|
||||
if currentExt != ext {
|
||||
if currentExt != "" {
|
||||
outPath = outPath[:len(outPath)-len(currentExt)]
|
||||
}
|
||||
outPath += ext
|
||||
}
|
||||
finalPath = outPath
|
||||
}
|
||||
if _, err := runtime.ResolveSavePath(finalPath); err != nil { // double check
|
||||
return "", 0, errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid output path: %s", err).WithParam("--output").WithCause(err)
|
||||
}
|
||||
|
||||
// Step 2: Check overwrite
|
||||
_, err = runtime.FileIO().Stat(finalPath)
|
||||
if err == nil {
|
||||
if !runtime.Bool("overwrite") {
|
||||
return "", 0, errs.NewValidationError(errs.SubtypeInvalidArgument, "file already exists: %s (use --overwrite to overwrite)", finalPath).WithParam("--overwrite")
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return "", 0, errs.NewInternalError(errs.SubtypeFileIO, "cannot check file existence: %s", err).WithCause(err)
|
||||
}
|
||||
|
||||
// Step 3: Save file
|
||||
var contentType string
|
||||
switch ext {
|
||||
case ".png":
|
||||
contentType = "image/png"
|
||||
case ".jpg", ".jpeg":
|
||||
contentType = "image/jpeg"
|
||||
case ".svg":
|
||||
contentType = "image/svg+xml"
|
||||
case ".json":
|
||||
contentType = "application/json"
|
||||
case ".mmd", ".puml":
|
||||
contentType = "text/plain"
|
||||
}
|
||||
|
||||
savResult, err := runtime.FileIO().Save(finalPath, fileio.SaveOptions{
|
||||
ContentType: contentType,
|
||||
}, data)
|
||||
if err != nil {
|
||||
return "", 0, wbSaveError(err)
|
||||
}
|
||||
|
||||
return finalPath, savResult.Size(), nil
|
||||
}
|
||||
|
||||
var whiteboardPreviewContentTypeExt = map[string]string{
|
||||
"image/jpeg": ".jpg",
|
||||
"image/png": ".png",
|
||||
}
|
||||
|
||||
func saveWhiteboardPreviewOutput(outPath, token string, runtime *common.RuntimeContext, header http.Header, data io.Reader) (string, int64, error) {
|
||||
contentType := header.Get("Content-Type")
|
||||
ext, err := whiteboardPreviewExtFromContentType(contentType)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
finalPath, err := whiteboardPreviewOutputPath(outPath, ext, token, runtime)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
return saveResolvedOutputFile(finalPath, contentType, runtime, data)
|
||||
}
|
||||
|
||||
func whiteboardPreviewExtFromContentType(contentType string) (string, error) {
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
mediaType = strings.TrimSpace(strings.Split(contentType, ";")[0])
|
||||
}
|
||||
if ext, ok := whiteboardPreviewContentTypeExt[strings.ToLower(mediaType)]; ok {
|
||||
return ext, nil
|
||||
}
|
||||
if strings.TrimSpace(contentType) == "" {
|
||||
contentType = "<empty>"
|
||||
}
|
||||
return "", errs.NewInternalError(
|
||||
errs.SubtypeInvalidResponse,
|
||||
"get whiteboard preview failed: expected image/png or image/jpeg response, got Content-Type: %s",
|
||||
contentType,
|
||||
)
|
||||
}
|
||||
|
||||
func whiteboardPreviewOutputPath(outPath, ext, token string, runtime *common.RuntimeContext) (string, error) {
|
||||
info, err := runtime.FileIO().Stat(outPath)
|
||||
if err == nil && info.IsDir() {
|
||||
finalPath := filepath.Join(outPath, fmt.Sprintf("whiteboard_%s%s", token, ext))
|
||||
if _, err := runtime.ResolveSavePath(finalPath); err != nil {
|
||||
return "", errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid output path: %s", err).WithParam("--output").WithCause(err)
|
||||
}
|
||||
return finalPath, nil
|
||||
}
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
return "", errs.NewInternalError(errs.SubtypeFileIO, "cannot check output path: %s", err).WithCause(err)
|
||||
}
|
||||
|
||||
currentExt := strings.ToLower(filepath.Ext(outPath))
|
||||
if currentExt == "" || currentExt == "." {
|
||||
finalPath := strings.TrimSuffix(outPath, ".") + ext
|
||||
if _, err := runtime.ResolveSavePath(finalPath); err != nil {
|
||||
return "", errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid output path: %s", err).WithParam("--output").WithCause(err)
|
||||
}
|
||||
return finalPath, nil
|
||||
}
|
||||
if !isWhiteboardPreviewImageExt(currentExt) {
|
||||
return "", errs.NewValidationError(
|
||||
errs.SubtypeInvalidArgument,
|
||||
"invalid preview output extension %q; use .png, .jpg, .jpeg, a directory, or a path without extension",
|
||||
currentExt,
|
||||
).WithParam("--output")
|
||||
}
|
||||
if !whiteboardPreviewExtMatches(currentExt, ext) {
|
||||
return "", errs.NewValidationError(
|
||||
errs.SubtypeFailedPrecondition,
|
||||
"preview response is %s but output path has extension %s; use a matching extension or omit the extension",
|
||||
ext,
|
||||
currentExt,
|
||||
).WithParam("--output")
|
||||
}
|
||||
if _, err := runtime.ResolveSavePath(outPath); err != nil {
|
||||
return "", errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid output path: %s", err).WithParam("--output").WithCause(err)
|
||||
}
|
||||
return outPath, nil
|
||||
}
|
||||
|
||||
func isWhiteboardPreviewImageExt(ext string) bool {
|
||||
return ext == ".png" || ext == ".jpg" || ext == ".jpeg"
|
||||
}
|
||||
|
||||
func whiteboardPreviewExtMatches(outputExt, responseExt string) bool {
|
||||
if responseExt == ".jpg" {
|
||||
return outputExt == ".jpg" || outputExt == ".jpeg"
|
||||
}
|
||||
return outputExt == responseExt
|
||||
}
|
||||
|
||||
func saveResolvedOutputFile(finalPath, contentType string, runtime *common.RuntimeContext, data io.Reader) (string, int64, error) {
|
||||
_, err := runtime.FileIO().Stat(finalPath)
|
||||
if err == nil {
|
||||
if !runtime.Bool("overwrite") {
|
||||
return "", 0, errs.NewValidationError(errs.SubtypeInvalidArgument, "file already exists: %s (use --overwrite to overwrite)", finalPath).WithParam("--overwrite")
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return "", 0, errs.NewInternalError(errs.SubtypeFileIO, "cannot check file existence: %s", err).WithCause(err)
|
||||
}
|
||||
|
||||
savResult, err := runtime.FileIO().Save(finalPath, fileio.SaveOptions{
|
||||
ContentType: contentType,
|
||||
}, data)
|
||||
if err != nil {
|
||||
return "", 0, wbSaveError(err)
|
||||
}
|
||||
return finalPath, savResult.Size(), nil
|
||||
}
|
||||
@@ -9,6 +9,7 @@ import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
@@ -211,6 +212,73 @@ func TestWhiteboardQuery_Validate_TypedErrors(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestWhiteboardExport_Validate verifies the canonical +export flag spelling
|
||||
// and output type names while legacy +query validation remains covered above.
|
||||
func TestWhiteboardExport_Validate(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
chdirTemp(t)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
flags map[string]string
|
||||
wantErr bool
|
||||
wantParam string
|
||||
}{
|
||||
{
|
||||
name: "valid: preview with output",
|
||||
flags: map[string]string{
|
||||
"whiteboard-token": "test-token-123",
|
||||
"output-type": "preview",
|
||||
"output": "output",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "valid: source without output",
|
||||
flags: map[string]string{
|
||||
"whiteboard-token": "test-token-123",
|
||||
"output-type": "source",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "invalid: preview without output",
|
||||
flags: map[string]string{
|
||||
"whiteboard-token": "test-token-123",
|
||||
"output-type": "preview",
|
||||
},
|
||||
wantErr: true,
|
||||
wantParam: "--output",
|
||||
},
|
||||
{
|
||||
name: "invalid: bad output-type value",
|
||||
flags: map[string]string{
|
||||
"whiteboard-token": "test-token-123",
|
||||
"output-type": "image",
|
||||
},
|
||||
wantErr: true,
|
||||
wantParam: "--output-type",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
err := WhiteboardExport.Validate(ctx, newTestRuntime(tt.flags, nil))
|
||||
if (err != nil) != tt.wantErr {
|
||||
t.Fatalf("WhiteboardExport.Validate() error = %v, wantErr %v", err, tt.wantErr)
|
||||
}
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("error is not *errs.ValidationError: %T", err)
|
||||
}
|
||||
if ve.Param != tt.wantParam {
|
||||
t.Fatalf("Param = %q, want %q", ve.Param, tt.wantParam)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestExportWhiteboardPreview_HTTPError locks the download-path failure
|
||||
// behavior: a failed preview download surfaces as a typed errs.* envelope, not
|
||||
// a flat legacy error.
|
||||
@@ -284,7 +352,7 @@ func TestWhiteboardQuery_DryRun(t *testing.T) {
|
||||
"output": "output.png",
|
||||
},
|
||||
wantMethod: "GET",
|
||||
wantPath: "/open-apis/board/v1/whiteboards/test-token-123/download_as_image",
|
||||
wantPath: "/open-apis/board/v1/whiteboards/test...-123/download_as_image",
|
||||
},
|
||||
{
|
||||
name: "dry run code",
|
||||
@@ -293,7 +361,7 @@ func TestWhiteboardQuery_DryRun(t *testing.T) {
|
||||
"output_as": "code",
|
||||
},
|
||||
wantMethod: "GET",
|
||||
wantPath: "/open-apis/board/v1/whiteboards/test-token-123/nodes",
|
||||
wantPath: "/open-apis/board/v1/whiteboards/test...-123/nodes",
|
||||
},
|
||||
{
|
||||
name: "dry run raw",
|
||||
@@ -302,7 +370,7 @@ func TestWhiteboardQuery_DryRun(t *testing.T) {
|
||||
"output_as": "raw",
|
||||
},
|
||||
wantMethod: "GET",
|
||||
wantPath: "/open-apis/board/v1/whiteboards/test-token-123/nodes",
|
||||
wantPath: "/open-apis/board/v1/whiteboards/test...-123/nodes",
|
||||
},
|
||||
}
|
||||
|
||||
@@ -313,6 +381,29 @@ func TestWhiteboardQuery_DryRun(t *testing.T) {
|
||||
if dryRun == nil {
|
||||
t.Fatalf("WhiteboardQuery.DryRun() returned nil")
|
||||
}
|
||||
var got struct {
|
||||
API []struct {
|
||||
Method string `json:"method"`
|
||||
URL string `json:"url"`
|
||||
Body map[string]interface{} `json:"body"`
|
||||
} `json:"api"`
|
||||
}
|
||||
data, err := json.Marshal(dryRun)
|
||||
if err != nil {
|
||||
t.Fatalf("Marshal() error = %v", err)
|
||||
}
|
||||
if err := json.Unmarshal(data, &got); err != nil {
|
||||
t.Fatalf("Unmarshal() error = %v; data=%s", err, string(data))
|
||||
}
|
||||
if len(got.API) != 1 {
|
||||
t.Fatalf("api len = %d, want 1; data=%s", len(got.API), string(data))
|
||||
}
|
||||
if got.API[0].Method != tt.wantMethod {
|
||||
t.Fatalf("method = %q, want %q; data=%s", got.API[0].Method, tt.wantMethod, string(data))
|
||||
}
|
||||
if got.API[0].URL != tt.wantPath {
|
||||
t.Fatalf("url = %q, want %q; data=%s", got.API[0].URL, tt.wantPath, string(data))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -391,6 +482,32 @@ func TestWhiteboardQuery_ShortcutRegistration(t *testing.T) {
|
||||
if len(WhiteboardQuery.Flags) == 0 {
|
||||
t.Errorf("WhiteboardQuery.Flags is empty, expected at least one flag")
|
||||
}
|
||||
if !WhiteboardQuery.Hidden {
|
||||
t.Errorf("WhiteboardQuery should be hidden because +export is the canonical command")
|
||||
}
|
||||
|
||||
// Verify WhiteboardExport is the visible canonical shortcut.
|
||||
if WhiteboardExport.Command != "+export" {
|
||||
t.Errorf("WhiteboardExport.Command = %q, want \"+export\"", WhiteboardExport.Command)
|
||||
}
|
||||
if WhiteboardExport.Service != "whiteboard" {
|
||||
t.Errorf("WhiteboardExport.Service = %q, want \"whiteboard\"", WhiteboardExport.Service)
|
||||
}
|
||||
if WhiteboardExport.Hidden {
|
||||
t.Errorf("WhiteboardExport should be visible")
|
||||
}
|
||||
if flag := shortcutFlag(WhiteboardExport, "output_as"); flag != nil {
|
||||
t.Errorf("WhiteboardExport --output_as should not be registered; got %#v", *flag)
|
||||
}
|
||||
if flag := shortcutFlag(WhiteboardExport, "output-type"); flag == nil || flag.Hidden {
|
||||
t.Errorf("WhiteboardExport --output-type should exist and be visible")
|
||||
}
|
||||
if flag := shortcutFlag(WhiteboardQuery, "output_as"); flag == nil || flag.Hidden {
|
||||
t.Errorf("WhiteboardQuery --output_as should exist and remain visible on the hidden legacy command")
|
||||
}
|
||||
if flag := shortcutFlag(WhiteboardQuery, "output-type"); flag != nil {
|
||||
t.Errorf("WhiteboardQuery --output-type should not be registered; got %#v", *flag)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSaveOutputFile verifies output saving, overwrite handling, and extension-specific paths.
|
||||
@@ -862,10 +979,11 @@ func TestExportWhiteboardPreview(t *testing.T) {
|
||||
|
||||
// Mock download preview image API response with RawBody
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/board/v1/whiteboards/test-token-preview/download_as_image",
|
||||
Status: 200,
|
||||
RawBody: []byte("fake PNG image data"),
|
||||
Method: "GET",
|
||||
URL: "/open-apis/board/v1/whiteboards/test-token-preview/download_as_image",
|
||||
Status: 200,
|
||||
RawBody: []byte("fake PNG image data"),
|
||||
ContentType: "image/png",
|
||||
})
|
||||
|
||||
args := []string{"+query", "--whiteboard-token", "test-token-preview", "--output_as", "image", "--output", "output", "--overwrite"}
|
||||
@@ -883,6 +1001,158 @@ func TestExportWhiteboardPreview(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestExportWhiteboardPreview_UsesContentTypeExtension verifies preview image
|
||||
// downloads are saved according to the API response Content-Type rather than a
|
||||
// hard-coded PNG suffix.
|
||||
func TestExportWhiteboardPreview_UsesContentTypeExtension(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
chdirTemp(t)
|
||||
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/board/v1/whiteboards/test-token-preview-jpeg/download_as_image",
|
||||
Status: 200,
|
||||
RawBody: []byte("fake JPEG image data"),
|
||||
ContentType: "image/jpeg",
|
||||
})
|
||||
|
||||
args := []string{"+export", "--whiteboard-token", "test-token-preview-jpeg", "--output-type", "preview", "--output", "output", "--overwrite"}
|
||||
if err := runShortcut(t, WhiteboardExport, args, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat("output.png"); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("output.png should not exist when response Content-Type is image/jpeg, stat err=%v", err)
|
||||
}
|
||||
data, err := os.ReadFile("output.jpg")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile() error: %v", err)
|
||||
}
|
||||
if string(data) != "fake JPEG image data" {
|
||||
t.Fatalf("image content = %q, want %q", string(data), "fake JPEG image data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportWhiteboardPreview_RejectsNonImageContentTypeWithoutSiblingOverwrite(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
chdirTemp(t)
|
||||
|
||||
if err := os.WriteFile("report.html", []byte("keep me"), 0644); err != nil {
|
||||
t.Fatalf("WriteFile() error: %v", err)
|
||||
}
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/board/v1/whiteboards/test-token-preview-html/download_as_image",
|
||||
Status: 200,
|
||||
RawBody: []byte("<html>bad gateway</html>"),
|
||||
ContentType: "text/html; charset=utf-8",
|
||||
})
|
||||
|
||||
args := []string{"+export", "--whiteboard-token", "test-token-preview-html", "--output-type", "preview", "--output", "report.png", "--overwrite"}
|
||||
err := runShortcut(t, WhiteboardExport, args, factory, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for non-image preview response")
|
||||
}
|
||||
assertInvalidResponse(t, err)
|
||||
|
||||
data, readErr := os.ReadFile("report.html")
|
||||
if readErr != nil {
|
||||
t.Fatalf("ReadFile() error: %v", readErr)
|
||||
}
|
||||
if string(data) != "keep me" {
|
||||
t.Fatalf("report.html was overwritten: %q", string(data))
|
||||
}
|
||||
if _, statErr := os.Stat("report.png"); !errors.Is(statErr, os.ErrNotExist) {
|
||||
t.Fatalf("report.png should not be written on invalid response, stat err=%v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportWhiteboardPreview_IgnoresContentDispositionExtension(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
chdirTemp(t)
|
||||
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/board/v1/whiteboards/test-token-preview-disposition/download_as_image",
|
||||
Status: 200,
|
||||
RawBody: []byte("fake JPEG image data"),
|
||||
Headers: http.Header{
|
||||
"Content-Type": []string{"image/jpeg"},
|
||||
"Content-Disposition": []string{`attachment; filename="payload.sh"`},
|
||||
},
|
||||
})
|
||||
|
||||
args := []string{"+export", "--whiteboard-token", "test-token-preview-disposition", "--output-type", "preview", "--output", "output", "--overwrite"}
|
||||
if err := runShortcut(t, WhiteboardExport, args, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
|
||||
if _, err := os.Stat("output.sh"); !errors.Is(err, os.ErrNotExist) {
|
||||
t.Fatalf("output.sh should not be created from Content-Disposition, stat err=%v", err)
|
||||
}
|
||||
data, err := os.ReadFile("output.jpg")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile() error: %v", err)
|
||||
}
|
||||
if string(data) != "fake JPEG image data" {
|
||||
t.Fatalf("image content = %q, want %q", string(data), "fake JPEG image data")
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportWhiteboardPreview_RejectsMismatchedExplicitExtension(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
chdirTemp(t)
|
||||
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/board/v1/whiteboards/test-token-preview-mismatch/download_as_image",
|
||||
Status: 200,
|
||||
RawBody: []byte("fake JPEG image data"),
|
||||
ContentType: "image/jpeg",
|
||||
})
|
||||
|
||||
args := []string{"+export", "--whiteboard-token", "test-token-preview-mismatch", "--output-type", "preview", "--output", "report.png", "--overwrite"}
|
||||
err := runShortcut(t, WhiteboardExport, args, factory, stdout)
|
||||
if err == nil {
|
||||
t.Fatal("expected error for mismatched explicit extension")
|
||||
}
|
||||
var ve *errs.ValidationError
|
||||
if !errors.As(err, &ve) {
|
||||
t.Fatalf("error is not *errs.ValidationError: %T (%v)", err, err)
|
||||
}
|
||||
if ve.Subtype != errs.SubtypeFailedPrecondition || ve.Param != "--output" {
|
||||
t.Fatalf("validation details = subtype %q param %q, want %q --output", ve.Subtype, ve.Param, errs.SubtypeFailedPrecondition)
|
||||
}
|
||||
if _, statErr := os.Stat("report.jpg"); !errors.Is(statErr, os.ErrNotExist) {
|
||||
t.Fatalf("report.jpg should not be created when explicit path mismatches, stat err=%v", statErr)
|
||||
}
|
||||
}
|
||||
|
||||
func TestExportWhiteboardPreview_AllowsMatchingExplicitExtension(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
chdirTemp(t)
|
||||
|
||||
reg.Register(&httpmock.Stub{
|
||||
Method: "GET",
|
||||
URL: "/open-apis/board/v1/whiteboards/test-token-preview-matching/download_as_image",
|
||||
Status: 200,
|
||||
RawBody: []byte("fake JPEG image data"),
|
||||
ContentType: "image/jpeg",
|
||||
})
|
||||
|
||||
args := []string{"+export", "--whiteboard-token", "test-token-preview-matching", "--output-type", "preview", "--output", "report.jpeg", "--overwrite"}
|
||||
if err := runShortcut(t, WhiteboardExport, args, factory, stdout); err != nil {
|
||||
t.Fatalf("err=%v", err)
|
||||
}
|
||||
data, err := os.ReadFile("report.jpeg")
|
||||
if err != nil {
|
||||
t.Fatalf("ReadFile() error: %v", err)
|
||||
}
|
||||
if string(data) != "fake JPEG image data" {
|
||||
t.Fatalf("image content = %q, want %q", string(data), "fake JPEG image data")
|
||||
}
|
||||
}
|
||||
|
||||
// TestExportWhiteboardRaw_EmptyNodes verifies raw export reports empty whiteboards.
|
||||
func TestExportWhiteboardRaw_EmptyNodes(t *testing.T) {
|
||||
factory, stdout, reg := newExecuteFactory(t)
|
||||
@@ -1522,3 +1792,12 @@ func chdirTemp(t *testing.T) {
|
||||
}
|
||||
t.Cleanup(func() { os.Chdir(orig) })
|
||||
}
|
||||
|
||||
func shortcutFlag(shortcut common.Shortcut, name string) *common.Flag {
|
||||
for i := range shortcut.Flags {
|
||||
if shortcut.Flags[i].Name == name {
|
||||
return &shortcut.Flags[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -1,494 +0,0 @@
|
||||
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
|
||||
// SPDX-License-Identifier: MIT
|
||||
package whiteboard
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/larksuite/cli/errs"
|
||||
"github.com/larksuite/cli/extension/fileio"
|
||||
"github.com/larksuite/cli/shortcuts/common"
|
||||
larkcore "github.com/larksuite/oapi-sdk-go/v3/core"
|
||||
)
|
||||
|
||||
const (
|
||||
// WhiteboardQueryAsImage exports a whiteboard preview image.
|
||||
WhiteboardQueryAsImage = "image"
|
||||
// WhiteboardQueryAsSvg exports a whiteboard as SVG.
|
||||
WhiteboardQueryAsSvg = "svg"
|
||||
// WhiteboardQueryAsCode exports Mermaid or PlantUML source extracted from the whiteboard.
|
||||
WhiteboardQueryAsCode = "code"
|
||||
// WhiteboardQueryAsRaw exports the raw whiteboard node payload.
|
||||
WhiteboardQueryAsRaw = "raw"
|
||||
)
|
||||
|
||||
// SyntaxType identifies the diagram syntax extracted from whiteboard code blocks.
|
||||
type SyntaxType int
|
||||
|
||||
const (
|
||||
// SyntaxTypePlantUML marks PlantUML code blocks.
|
||||
SyntaxTypePlantUML SyntaxType = 1
|
||||
// SyntaxTypeMermaid marks Mermaid code blocks.
|
||||
SyntaxTypeMermaid SyntaxType = 2
|
||||
)
|
||||
|
||||
// SyntaxTypeNameMap maps whiteboard syntax types to their CLI output names.
|
||||
var SyntaxTypeNameMap = map[SyntaxType]string{
|
||||
SyntaxTypePlantUML: "plantuml",
|
||||
SyntaxTypeMermaid: "mermaid",
|
||||
}
|
||||
|
||||
// SyntaxTypeExtensionMap maps whiteboard syntax types to their default file extensions.
|
||||
var SyntaxTypeExtensionMap = map[SyntaxType]string{
|
||||
SyntaxTypePlantUML: ".puml",
|
||||
SyntaxTypeMermaid: ".mmd",
|
||||
}
|
||||
|
||||
// String returns the CLI-facing name for the syntax type.
|
||||
func (s SyntaxType) String() string {
|
||||
return SyntaxTypeNameMap[s]
|
||||
}
|
||||
|
||||
// ExtensionName returns the default file extension for the syntax type.
|
||||
func (s SyntaxType) ExtensionName() string {
|
||||
return SyntaxTypeExtensionMap[s]
|
||||
}
|
||||
|
||||
// IsValid reports whether the syntax type is one of the supported whiteboard code syntaxes.
|
||||
func (s SyntaxType) IsValid() bool {
|
||||
return s == SyntaxTypePlantUML || s == SyntaxTypeMermaid
|
||||
}
|
||||
|
||||
// WhiteboardQuery registers the `whiteboard +query` shortcut.
|
||||
var WhiteboardQuery = common.Shortcut{
|
||||
Service: "whiteboard",
|
||||
Command: "+query",
|
||||
Description: "Query a existing whiteboard, export it as preview image or raw nodes structure.",
|
||||
Risk: "read",
|
||||
Scopes: []string{"board:whiteboard:node:read"},
|
||||
AuthTypes: []string{"user", "bot"},
|
||||
Flags: []common.Flag{
|
||||
{Name: "whiteboard-token", Desc: "whiteboard token of the whiteboard. You will need read permission to download preview image.", Required: true},
|
||||
{Name: "output_as", Desc: "output whiteboard as: image | svg | code | raw.", Required: true},
|
||||
{Name: "output", Desc: "output directory. It is required when output as image. If not specified when --output_as svg/code/raw, it will output directly.", Required: false},
|
||||
{Name: "overwrite", Desc: "overwrite existing file if it exists", Required: false, Type: "bool"},
|
||||
},
|
||||
HasFormat: true,
|
||||
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
// Check if token contains control characters
|
||||
token := runtime.Str("whiteboard-token")
|
||||
if err := common.RejectDangerousCharsTyped("--whiteboard-token", token); err != nil {
|
||||
return err
|
||||
}
|
||||
out := runtime.Str("output")
|
||||
if out != "" {
|
||||
if _, err := runtime.ResolveSavePath(out); err != nil {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid output path: %s", err).WithParam("--output").WithCause(err)
|
||||
}
|
||||
}
|
||||
if out == "" && runtime.Str("output_as") == WhiteboardQueryAsImage {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "need a output directory to query whiteboard as image").WithParam("--output")
|
||||
}
|
||||
|
||||
as := runtime.Str("output_as")
|
||||
if as != WhiteboardQueryAsImage && as != WhiteboardQueryAsSvg && as != WhiteboardQueryAsCode && as != WhiteboardQueryAsRaw {
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output_as flag must be one of: image | svg | code | raw").WithParam("--output_as")
|
||||
}
|
||||
return nil
|
||||
},
|
||||
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
|
||||
as := runtime.Str("output_as")
|
||||
token := runtime.Str("whiteboard-token")
|
||||
switch as {
|
||||
case WhiteboardQueryAsImage:
|
||||
return common.NewDryRunAPI().
|
||||
GET(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/download_as_image", common.MaskToken(url.PathEscape(token)))).
|
||||
Desc("Export preview image of given whiteboard")
|
||||
case WhiteboardQueryAsCode:
|
||||
return common.NewDryRunAPI().
|
||||
GET(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/nodes", common.MaskToken(url.PathEscape(token)))).
|
||||
Desc("Extract Mermaid/Plantuml code from given whiteboard")
|
||||
case WhiteboardQueryAsRaw:
|
||||
return common.NewDryRunAPI().
|
||||
GET(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/nodes", common.MaskToken(url.PathEscape(token)))).
|
||||
Desc("Extract raw nodes structure from given whiteboard")
|
||||
case WhiteboardQueryAsSvg:
|
||||
return common.NewDryRunAPI().
|
||||
POST(fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/export", common.MaskToken(url.PathEscape(token)))).
|
||||
Body(map[string]string{"export_type": "svg"}).
|
||||
Desc("Export SVG of given whiteboard")
|
||||
default:
|
||||
return common.NewDryRunAPI().Desc("invalid --output_as flag, must be one of: image | svg | code | raw")
|
||||
}
|
||||
},
|
||||
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
|
||||
// 构建 API 请求
|
||||
token := runtime.Str("whiteboard-token")
|
||||
outDir := runtime.Str("output")
|
||||
as := runtime.Str("output_as")
|
||||
switch as {
|
||||
case WhiteboardQueryAsImage:
|
||||
return exportWhiteboardPreview(ctx, runtime, token, outDir)
|
||||
case WhiteboardQueryAsSvg:
|
||||
return exportWhiteboardSvg(runtime, token, outDir)
|
||||
case WhiteboardQueryAsCode:
|
||||
return exportWhiteboardCode(runtime, token, outDir)
|
||||
case WhiteboardQueryAsRaw:
|
||||
return exportWhiteboardRaw(runtime, token, outDir)
|
||||
default:
|
||||
return errs.NewValidationError(errs.SubtypeInvalidArgument, "--output_as flag must be one of: image | svg | code | raw").WithParam("--output_as")
|
||||
}
|
||||
|
||||
},
|
||||
}
|
||||
|
||||
// exportReq defines the request body for whiteboard export APIs.
|
||||
type exportReq struct {
|
||||
ExportType string `json:"export_type"`
|
||||
}
|
||||
|
||||
// exportResp models the whiteboard export response envelope.
|
||||
type exportResp struct {
|
||||
Code int `json:"code"`
|
||||
Msg string `json:"msg"`
|
||||
Data struct {
|
||||
Content string `json:"content"`
|
||||
MimeType string `json:"mime_type"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
// exportWhiteboardSvg exports a whiteboard as SVG and writes it to stdout or a file.
|
||||
func exportWhiteboardSvg(runtime *common.RuntimeContext, wbToken, outDir string) error {
|
||||
reqBody := exportReq{ExportType: "svg"}
|
||||
req := &larkcore.ApiReq{
|
||||
HttpMethod: http.MethodPost,
|
||||
ApiPath: fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/export", url.PathEscape(wbToken)),
|
||||
Body: reqBody,
|
||||
}
|
||||
|
||||
resp, err := runtime.DoAPI(req)
|
||||
if err != nil {
|
||||
return wrapWbNetworkErr(err, "export whiteboard svg failed: %v", err)
|
||||
}
|
||||
|
||||
var exportData exportResp
|
||||
if err := json.Unmarshal(resp.RawBody, &exportData); err == nil {
|
||||
if exportData.Code != 0 {
|
||||
subtype := errs.SubtypeUnknown
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
subtype = errs.SubtypeNotFound
|
||||
}
|
||||
return errs.NewAPIError(subtype, "export whiteboard svg failed: %s", exportData.Msg).WithCode(exportData.Code)
|
||||
}
|
||||
} else if resp.StatusCode == http.StatusOK {
|
||||
return errs.NewInternalError(errs.SubtypeInvalidResponse, "parse export response failed: %v", err).WithCause(err)
|
||||
}
|
||||
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
body := common.TruncateStr(strings.TrimSpace(string(resp.RawBody)), 500)
|
||||
if resp.StatusCode >= 500 {
|
||||
return errs.NewNetworkError(errs.SubtypeNetworkServer, "export whiteboard svg failed: HTTP %d: %s", resp.StatusCode, body).
|
||||
WithCode(resp.StatusCode).
|
||||
WithRetryable()
|
||||
}
|
||||
subtype := errs.SubtypeUnknown
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
subtype = errs.SubtypeNotFound
|
||||
}
|
||||
return errs.NewAPIError(subtype, "export whiteboard svg failed: HTTP %d: %s", resp.StatusCode, body).
|
||||
WithCode(resp.StatusCode)
|
||||
}
|
||||
|
||||
svgBytes, err := base64.StdEncoding.DecodeString(exportData.Data.Content)
|
||||
if err != nil {
|
||||
return errs.NewInternalError(errs.SubtypeInvalidResponse, "decode svg base64 failed: %v", err).WithCause(err)
|
||||
}
|
||||
|
||||
if outDir == "" {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"svg_content": string(svgBytes),
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "%s\n", string(svgBytes))
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
finalPath, size, err := saveOutputFile(outDir, ".svg", wbToken, runtime, bytes.NewReader(svgBytes))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"svg_path": finalPath,
|
||||
"size_bytes": size,
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "SVG saved to %s\n", finalPath)
|
||||
fmt.Fprintf(w, "File size: %d bytes", size)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportWhiteboardPreview(ctx context.Context, runtime *common.RuntimeContext, wbToken, outDir string) error {
|
||||
req := &larkcore.ApiReq{
|
||||
HttpMethod: http.MethodGet,
|
||||
ApiPath: fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/download_as_image", url.PathEscape(wbToken)),
|
||||
}
|
||||
// Execute API request. The preview endpoint streams raw image bytes (not a
|
||||
// JSON envelope), so classify by HTTP status: 5xx is retryable network,
|
||||
// while 4xx remains an API-side rejection.
|
||||
resp, err := runtime.DoAPI(req, larkcore.WithFileDownload())
|
||||
if err != nil {
|
||||
return wrapWbNetworkErr(err, "get whiteboard preview failed: %v", err)
|
||||
}
|
||||
if resp.StatusCode >= 400 {
|
||||
body := common.TruncateStr(strings.TrimSpace(string(resp.RawBody)), 500)
|
||||
if resp.StatusCode >= 500 {
|
||||
return errs.NewNetworkError(errs.SubtypeNetworkServer, "get whiteboard preview failed: HTTP %d: %s", resp.StatusCode, body).
|
||||
WithCode(resp.StatusCode).
|
||||
WithRetryable()
|
||||
}
|
||||
subtype := errs.SubtypeUnknown
|
||||
if resp.StatusCode == http.StatusNotFound {
|
||||
subtype = errs.SubtypeNotFound
|
||||
}
|
||||
return errs.NewAPIError(subtype, "get whiteboard preview failed: HTTP %d: %s", resp.StatusCode, body).
|
||||
WithCode(resp.StatusCode)
|
||||
}
|
||||
|
||||
finalPath, size, err := saveOutputFile(outDir, ".png", wbToken, runtime, bytes.NewReader(resp.RawBody))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"preview_image_path": finalPath,
|
||||
"size_bytes": size,
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Preview image saved to %s\n", finalPath)
|
||||
fmt.Fprintf(w, "Image size: %d bytes", size)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
type wbNodesResp struct {
|
||||
Data struct {
|
||||
Nodes []interface{} `json:"nodes"`
|
||||
} `json:"data"`
|
||||
}
|
||||
|
||||
func fetchWhiteboardNodes(runtime *common.RuntimeContext, wbToken string) (*wbNodesResp, error) {
|
||||
data, err := runtime.CallAPITyped(http.MethodGet, fmt.Sprintf("/open-apis/board/v1/whiteboards/%s/nodes", url.PathEscape(wbToken)), nil, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var nodes wbNodesResp
|
||||
rawNodes, _ := data["nodes"]
|
||||
if rawNodes != nil {
|
||||
var ok bool
|
||||
nodes.Data.Nodes, ok = rawNodes.([]interface{})
|
||||
if !ok {
|
||||
return nil, wbInvalidResponse("get whiteboard nodes failed: data.nodes must be an array")
|
||||
}
|
||||
}
|
||||
return &nodes, nil
|
||||
}
|
||||
|
||||
type syntaxInfo struct {
|
||||
code string
|
||||
syntaxType SyntaxType
|
||||
}
|
||||
|
||||
func exportWhiteboardCode(runtime *common.RuntimeContext, wbToken, outDir string) error {
|
||||
wbNodes, err := fetchWhiteboardNodes(runtime, wbToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if wbNodes == nil || wbNodes.Data.Nodes == nil {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"msg": "whiteboard is empty",
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Whiteboard is empty\n")
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
var syntaxBlocks []syntaxInfo
|
||||
for _, node := range wbNodes.Data.Nodes {
|
||||
nodeMap, ok := node.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
syntax, ok := nodeMap["syntax"]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
syntaxMap, ok := syntax.(map[string]interface{})
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
code, _ := syntaxMap["code"].(string)
|
||||
var syntaxType SyntaxType
|
||||
switch v := syntaxMap["syntax_type"].(type) {
|
||||
case json.Number:
|
||||
// runtime.ClassifyAPIResponse decodes the response with UseNumber,
|
||||
// so numeric fields arrive as json.Number rather than float64.
|
||||
if n, err := v.Int64(); err == nil {
|
||||
syntaxType = SyntaxType(n)
|
||||
}
|
||||
case float64:
|
||||
syntaxType = SyntaxType(v)
|
||||
case SyntaxType:
|
||||
syntaxType = v
|
||||
}
|
||||
if code != "" && syntaxType.IsValid() {
|
||||
syntaxBlocks = append(syntaxBlocks, syntaxInfo{code: code, syntaxType: syntaxType})
|
||||
}
|
||||
}
|
||||
|
||||
if len(syntaxBlocks) == 0 {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"msg": "no code blocks found in whiteboard",
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "No code blocks found in whiteboard\n")
|
||||
})
|
||||
return nil
|
||||
}
|
||||
// 目前的标准操作是导出到单一文件,和 Doc 展示画板代码块采用相同的逻辑
|
||||
// 如果有需求,可以调整到导出到多个文件的模式
|
||||
if len(syntaxBlocks) > 1 {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"msg": "multiple code blocks found, cannot export directly",
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Multiple code blocks found, cannot export directly\n")
|
||||
})
|
||||
return nil
|
||||
}
|
||||
block := syntaxBlocks[0]
|
||||
|
||||
if outDir == "" {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"code": block.code,
|
||||
"syntax_type": block.syntaxType.String(),
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "%s\n", block.code)
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
finalPath, _, err := saveOutputFile(outDir, block.syntaxType.ExtensionName(), wbToken, runtime, strings.NewReader(block.code))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"output_path": finalPath,
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Whiteboard code saved to %s\n", finalPath)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func exportWhiteboardRaw(runtime *common.RuntimeContext, wbToken, outDir string) error {
|
||||
wbNodes, err := fetchWhiteboardNodes(runtime, wbToken)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if wbNodes == nil || wbNodes.Data.Nodes == nil {
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"msg": "whiteboard is empty",
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Whiteboard is empty\n")
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
jsonData, err := json.MarshalIndent(wbNodes.Data, "", " ")
|
||||
if err != nil {
|
||||
return errs.NewInternalError(errs.SubtypeInvalidResponse, "cannot marshal whiteboard data: %s", err).WithCause(err)
|
||||
}
|
||||
|
||||
if outDir == "" {
|
||||
runtime.OutFormat(wbNodes.Data, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "%s\n", string(jsonData))
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
finalPath, _, err := saveOutputFile(outDir, ".json", wbToken, runtime, bytes.NewReader(jsonData))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
runtime.OutFormat(map[string]interface{}{
|
||||
"output_path": finalPath,
|
||||
}, nil, func(w io.Writer) {
|
||||
fmt.Fprintf(w, "Whiteboard raw node structure saved to %s\n", finalPath)
|
||||
})
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func saveOutputFile(outPath, ext, token string, runtime *common.RuntimeContext, data io.Reader) (string, int64, error) {
|
||||
// Step 1: Get final output path
|
||||
info, err := runtime.FileIO().Stat(outPath)
|
||||
var finalPath string
|
||||
if err == nil && info.IsDir() {
|
||||
finalPath = filepath.Join(outPath, fmt.Sprintf("whiteboard_%s%s", token, ext))
|
||||
} else {
|
||||
// Fix extension in path
|
||||
currentExt := filepath.Ext(outPath)
|
||||
if currentExt != ext {
|
||||
if currentExt != "" {
|
||||
outPath = outPath[:len(outPath)-len(currentExt)]
|
||||
}
|
||||
outPath += ext
|
||||
}
|
||||
finalPath = outPath
|
||||
}
|
||||
if _, err := runtime.ResolveSavePath(finalPath); err != nil { // double check
|
||||
return "", 0, errs.NewValidationError(errs.SubtypeInvalidArgument, "invalid output path: %s", err).WithParam("--output").WithCause(err)
|
||||
}
|
||||
|
||||
// Step 2: Check overwrite
|
||||
_, err = runtime.FileIO().Stat(finalPath)
|
||||
if err == nil {
|
||||
if !runtime.Bool("overwrite") {
|
||||
return "", 0, errs.NewValidationError(errs.SubtypeInvalidArgument, "file already exists: %s (use --overwrite to overwrite)", finalPath).WithParam("--overwrite")
|
||||
}
|
||||
} else if !os.IsNotExist(err) {
|
||||
return "", 0, errs.NewInternalError(errs.SubtypeFileIO, "cannot check file existence: %s", err).WithCause(err)
|
||||
}
|
||||
|
||||
// Step 3: Save file
|
||||
var contentType string
|
||||
switch ext {
|
||||
case ".png":
|
||||
contentType = "image/png"
|
||||
case ".svg":
|
||||
contentType = "image/svg+xml"
|
||||
case ".json":
|
||||
contentType = "application/json"
|
||||
case ".mmd", ".puml":
|
||||
contentType = "text/plain"
|
||||
}
|
||||
|
||||
savResult, err := runtime.FileIO().Save(finalPath, fileio.SaveOptions{
|
||||
ContentType: contentType,
|
||||
}, data)
|
||||
if err != nil {
|
||||
return "", 0, wbSaveError(err)
|
||||
}
|
||||
|
||||
return finalPath, savResult.Size(), nil
|
||||
}
|
||||
@@ -255,6 +255,7 @@ func TestShortcutsIncludesExpectedCommands(t *testing.T) {
|
||||
got := Shortcuts()
|
||||
want := []string{
|
||||
"+update",
|
||||
"+export",
|
||||
"+query",
|
||||
}
|
||||
|
||||
|
||||
@@ -28,7 +28,7 @@
|
||||
## 各命令
|
||||
|
||||
### +file-list
|
||||
列出应用文件,支持精确过滤:`--name`(文件名)、`--path`(远端路径)、`--type`(MIME 类型)、`--size-gt`/`--size-lt`(字节)、`--uploaded-since`/`--uploaded-until`(上传时间区间,时间格式见末尾)。分页 `--page-size`(默认 20)/ `--page-token`。列表每项给名称、路径、大小、类型、上传时间(pretty 表格即这 5 列);上传者、下载地址(如有)仅在 JSON 输出里,单文件详情用 `+file-get`。
|
||||
列出应用文件,支持精确过滤:`--name`(文件名)、`--path`(远端路径)、`--type`(MIME 类型)、`--size-gt`/`--size-lt`(字节)、`--uploaded-since`/`--uploaded-until`(上传时间区间,时间格式见末尾)。分页 `--page-size`(默认 20,范围 1..200)/ `--page-token`。列表每项给名称、路径、大小、类型、上传时间(pretty 表格即这 5 列);上传者、下载地址(如有)仅在 JSON 输出里,单文件详情用 `+file-get`。
|
||||
|
||||
```bash
|
||||
lark-cli apps +file-list --app-id app_xxx
|
||||
|
||||
@@ -29,7 +29,7 @@ metadata:
|
||||
## 使用边界
|
||||
|
||||
- Base 业务操作只使用 `lark-cli base +...` shortcut,不使用旧聚合式 `+table / +field / +record / +view / +history / +workspace`。
|
||||
- 本轮 Base 不依赖 `lark-cli schema`。SKILL 只保留路由、风险和复杂 JSON/DSL;简单命令由命令自身的参数、tips 和错误恢复承接。
|
||||
- 执行 update 前必须先查当前 shortcut 的 `--help` 或对应 reference。若命令要求完整配置,首次请求必须基于可信的当前配置执行 read-modify-write:只修改用户明确指定的内容,保留其他仍适用的可写配置,并按命令要求的结构提交。若命令支持局部/delta update,按其契约提交最小合法 payload;不得以不完整请求试错补参。
|
||||
- 用户要把 Excel / CSV / `.base` 导入成 Base 时,先转 `lark-cli drive +import --type bitable`,导入完成后再回到 Base 命令。
|
||||
- 认证、初始化、scope、身份切换、权限不足恢复属于 `lark-shared`;Base 文档只保留会影响 Base 路径选择的权限规则。
|
||||
|
||||
@@ -104,20 +104,18 @@ metadata:
|
||||
|
||||
## 写入前置规则
|
||||
|
||||
- 更新前先看命令说明:需要完整提交时,先读取并补齐当前配置,只改用户指定的内容,再按命令要求提交;支持局部修改时,按命令说明和 reference 提交最小合法 payload。
|
||||
- 优先用写入返回确认结果;返回信息不足或任务明确要求核验时,再读回。
|
||||
- 写记录前先读字段结构;只写存储字段。系统字段、附件字段、`formula`、`lookup` 不作为普通记录写入目标。
|
||||
- 附件上传、下载、删除走专用 `+record-*-attachment` 命令。
|
||||
- 写字段前先读 [lark-base-field-json.md](references/lark-base-field-json.md);涉及 `formula` / `lookup` 时必须读 [formula-field-guide.md](references/formula-field-guide.md) / [lookup-field-guide.md](references/lookup-field-guide.md)。
|
||||
- 表名、字段名、视图名、workflow 配置中的名称必须来自真实返回;跨表场景还要读取目标表结构。
|
||||
- 删除、角色更新、字段更新等高风险操作遵循 CLI 的 confirmation gate;目标不明确时先用 get/list 消歧。
|
||||
- 删除、角色更新、字段更新、表单提交(`+form-submit`)等高风险操作遵循 CLI 的 confirmation gate,必须带 `--yes`;目标不明确时先用 get/list 消歧。
|
||||
- 批量写入单批最多 200 条;连续写同一表时串行执行,遇到 `1254291` 按短暂等待后重试处理。
|
||||
- `+record-batch-update` 使用 `update_records`,按 `record_id -> fields` 映射逐条提交字段值。
|
||||
- select/multiselect 写入未知选项可能触发平台新增选项;不是要新增时,先用 `+field-list` 或 `+field-search-options` 确认可选值。
|
||||
- `select` 字段只支持写入字段中已有的选项;构造 CellValue 前先用 `+field-list` 或 `+field-search-options` 确认目标选项存在。
|
||||
|
||||
## 表单与视图细节
|
||||
|
||||
- `+form-submit` 前必须先跑 `+form-detail`,读取 `questions[].type`、`required`、`filter` 和附件场景需要的 `base_token`;不要填写被 filter 隐藏的问题。
|
||||
- `+form-submit` 是高风险写操作,必须带 `--yes` 确认;调用前必须先跑 `+form-detail`,读取 `questions[].type`、`required`、`filter` 和附件场景需要的 `base_token`;不要填写被 filter 隐藏的问题。
|
||||
- 表单附件不要写进 `fields`,放在 `--json.attachments`;提交附件时必须同时传表单所属 Base 的 `--base-token`。
|
||||
- `+view-set-filter` 是唯一保留的 view reference;sort/group/card/timebar/visible-fields 这类配置先用对应 get 命令读现状,保留未修改字段,只替换用户要求变更的配置。
|
||||
- 视图适合持久化、共享和 UI 复用;一次性筛选/排序可先用 `+record-list` / `+record-search` 的 filter/sort 验证结果,再按需要沉淀为持久视图。
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
- `--json` 必须是 JSON 对象。
|
||||
- `+record-upsert`:顶层直接传字段映射:`{"字段名或字段ID": CellValue}`。
|
||||
- `+record-batch-create`:`rows` 是 `CellValue[][]`,列顺序由 `fields` 决定。
|
||||
- `+record-batch-create`:使用 `create_records`,其每个元素都是 `Map<FieldNameOrID, CellValue>`。
|
||||
- `+record-batch-update`:使用 `update_records`,其每个 value 都是 `Map<FieldNameOrID, CellValue>`。
|
||||
- 一次 payload 里同一字段只用一种 key(字段名或字段 ID),不要重复。
|
||||
- 写入前先 `+field-list` 获取字段 `type/style/multiple`,再构造值。
|
||||
@@ -48,7 +48,7 @@ text 字段的 `style.type` 影响单元格检查逻辑:
|
||||
|
||||
### 2.3 select(单选/多选)
|
||||
|
||||
单选用选项名字符串;多选用选项名数组。选项名建议与字段配置一致;写入未知选项时平台可能自动新增选项,因此不要把自然语言近义词当成已有选项传入。
|
||||
`select` 字段用 `multiple` 区分单选和多选:`multiple=false` 时传选项名字符串,`multiple=true` 时传选项名数组。只支持写入字段中已有的选项;构造 CellValue 前先用 `+field-list` 或 `+field-search-options` 确认目标选项存在。
|
||||
|
||||
```json
|
||||
{
|
||||
|
||||
@@ -87,16 +87,20 @@ POST /open-apis/base/v3/bases/:base_token/tables/:table_id/fields
|
||||
## 返回重点
|
||||
|
||||
- 返回 `field` 和 `created: true`。
|
||||
- 如果返回 `field_get_recommended:false` 且 `next_step:"done"`,表示本次是简单字段创建,通常不需要立刻执行 `+field-get`。
|
||||
- 如果返回 `field_get_recommended:true` 或 `next_step:"field_get"`,按 `verification_hint` 读回字段;`formula`、`lookup`、`link`、`auto_number` 等计算、关联或生成型字段更适合读回确认服务端最终结构。
|
||||
|
||||
## 工作流
|
||||
|
||||
|
||||
1. formula / lookup 字段必须先阅读对应指南;没读之前不要直接创建。
|
||||
2. 创建简单字段时,优先相信命令返回;只有用户要求精确核对额外属性,或返回建议读回时,才继续执行 `+field-get`。
|
||||
|
||||
## 坑点
|
||||
|
||||
- ⚠️ 这是写入操作,执行前必须确认。
|
||||
- ⚠️ 当 `type` 是 `formula` 或 `lookup` 时,先读对应 guide,再创建。
|
||||
- ⚠️ 不要把“每次创建后都 `+field-get`”当作固定流程;按返回里的 `field_get_recommended` 和 `next_step` 决定是否读回。
|
||||
|
||||
## 参考
|
||||
|
||||
|
||||
@@ -180,11 +180,11 @@
|
||||
|
||||
支持字段:`icon`、`min`、`max`
|
||||
|
||||
默认值 / 约束:
|
||||
默认值 / 已知平台范围:
|
||||
- `icon` 默认 `star`
|
||||
- `icon` 可用:`star`、`heart`、`thumbsup`、`fire`、`smile`、`lightning`、`flower`、`number`
|
||||
- `min` 取值 `0..1`,默认 `1`
|
||||
- `max` 取值 `1..10`,默认 `5`
|
||||
- `max` 默认 `5`;常见或已文档化的范围为 `1..10`,但 CLI 不强制上限为 `10`。如果用户明确需要更大评分范围,优先确认平台能力或用 `+field-create/update --dry-run` 检查请求形状;平台拒绝后再建议改用普通数字或进度字段。
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -419,7 +419,7 @@
|
||||
|
||||
### 3.11 auto_number
|
||||
|
||||
自动编号字段;不写 `style.rules` 时使用默认规则:`NO.001`。
|
||||
自动编号字段;创建时不写 `style.rules` 会使用默认规则:`NO.001`。更新已有自动编号字段时应显式提交目标 `style.rules`,因为 `+field-update` 会把新的编号规则重新应用到已有编号。
|
||||
|
||||
最小写法:
|
||||
|
||||
@@ -512,7 +512,7 @@
|
||||
## 4. 创建与更新
|
||||
|
||||
- `+field-create`:按目标字段配置直接构造 `--json`。
|
||||
- `+field-update`:使用同样的 JSON 结构,但语义是 `PUT`;建议先 `+field-get`,再按目标完整状态提交,并带 `--yes`。
|
||||
- `+field-update`:使用同样的 JSON 结构,但语义是 `PUT`;建议先 `+field-get`,再按目标完整状态提交,并带 `--yes`。当 `type` 是 `auto_number` 时,更新编号规则本身就会把新规则应用到已有编号,无需额外参数,也不要在 JSON 里塞额外的底层实现参数。
|
||||
|
||||
## 5. 暂不支持字段
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user