Compare commits

...

27 Commits

Author SHA1 Message Date
zhengzhijie
e450090ef6 fix(sheets): preserve batch scope and cross-sheet chart ranges 2026-07-31 12:34:52 +08:00
zhengzhijie
11205d2f8a feat(sheets): simplify batch chart operations 2026-07-29 12:06:19 +08:00
zhengzhijie
e665fa335c Merge remote-tracking branch 'origin/feat/lark-sheets-develop' into feat/chart-snapshot-detached-header
# Conflicts:
#	shortcuts/sheets/flag_ergonomics.go
#	shortcuts/sheets/flag_ergonomics_test.go
2026-07-29 12:05:26 +08:00
xiongyuanwen-byted
f79908483d fix(sheets): reject path-shaped --csv values instead of writing them into the sheet
A +csv-put --csv value naming a file that doesn't resolve used to be written
into the anchor cell as literal text, with a success exit code — a wrong value
in the sheet that nothing surfaces, which costs more than a rejection. The
common source is an absolute path: @ only reads relative paths, so the caller
drops the @ and retries, and the path string lands in A1 (07-28 root-cause
audit, finding D1). The existing guard only caught values naming a file that
does exist (the forgotten-@ case).

The guard now also rejects a value that is unmistakably path-shaped: no
separator or whitespace, pure ASCII, and either a .csv/.tsv extension or an
explicit ./ ../ / ~/ prefix. All three conditions are required — that is what
keeps prose that merely mentions a filename, N/A, README.md and CJK content
out of it, the misjudgments that retired the previous name-shape heuristic.
This flips one pinned case: a bare "nope.csv" was previously written verbatim
and now errs with the fix inlined.

To make the shape check safe for correct invocations, resolveInputFlags now
records which flags had their value replaced from @file or stdin, exposed as
RuntimeContext.InputResolvedFromSource; the guard skips resolved values
entirely. By Validate time a piped value is indistinguishable from a typed
one, so without the origin bit the guard would re-reject a correct
`--csv @file` whose content happens to look like a path — and stdin, which
the error text prescribes for verbatim writes, would not actually escape it.
The @@ escape stays inline and guarded. This origin bit is the one
common-layer addition; it carries no domain logic.
2026-07-29 12:00:47 +08:00
xiongyuanwen-byted
52b5910fb1 chore(sheets): sync lark-sheets skill and flag data from sheet-skill-spec
Mirrors `npm run sync:cli` output from the spec repo, which is the source of
truth for skill docs and flag data. Two independent changes ride along:

- The border and sheet-selector flag descriptions from spec commit 3dd7f9c,
  matching the help text already committed here in 0b595562 (data/flag-defs.json
  is byte-identical, so `go generate` is a no-op).
- The upstream read-flow work: SKILL.md 3.1.0 to 3.1.1, a longer read-data
  reference, and five read-side helper scripts under skills/lark-sheets/scripts.

The scripts land as machine resources and are not embedded in the binary
(content_embed.go whitelists docs only). make unit-test passes.
2026-07-28 21:06:13 +08:00
xiongyuanwen-byted
0b59556207 feat(sheets): name the enum, the required selector and the missing envelope in errors and help
Second batch from the 07-28 root-cause analysis, all aimed at the retry that
follows a rejection.

Enum-bearing type mismatches now answer with the allowed values instead of a
whole-payload skeleton. --border-styles with weight:1 used to reply "expected
type string, got number; expected shape: {"bottom": {…}, "left": {…}, …}",
which never mentions thin/medium/thick; the skeleton is for container-shape
confusion, so a field that declares an enum falls through to the hint that
names it. The --border-styles help now inlines both vocabularies (style is the
line type, weight the thickness and a string, not a pixel number), spells the
{all:{…}} shorthand, and states that no --border-all / --border-top /
--border-color exist. --word-wrap additionally accepts the Google Sheets
wrapStrategy words wrap and clip.

The sheet selector states that one of the pair is required rather than only
that they are mutually exclusive, in help across all shortcuts that take it,
and the rejection hints where the name comes from: a fresh workbook has one
sheet named Sheet1, any other needs a +workbook-info lookup. Eval traces
recover on the very next call, so the gap was which name to pass.

A --sheets payload written as a bare array now says the top level must be
{"sheets":[…]} instead of quoting Go's "cannot unmarshal array into Go value
of type struct { Sheets []sheets.tableSheetIn }", which names the internal
type rather than the fix. The skeleton hint is unchanged.
2026-07-28 20:47:48 +08:00
xiongyuanwen-byted
91743bba99 fix(sheets): make border vocabulary normalization reachable, prescribe flag and style-field fixes
Three fixes from the 07-28 root-cause analysis of failed agent traces, all
aimed at the first-try success rate rather than the recovery loop.

Border acceptance layer was unreachable on two of its three carrier paths.
expandBorderAllShorthand already moves a weight word out of the style slot
({"style":"thin"} -> style solid + weight thin), but on --border-styles and
typed --cells it ran after parseJSONFlag's schema check, so the enum error
fired first and the rewrite never happened. Move it ahead of validation via
the jsonFlagNormalizers seam; --styles already validated post-expansion and
is unchanged. An explicitly conflicting weight still takes the enum error.

Unknown-flag prescriptions for the names agents reach for most: +cells-set
--values, +dim-freeze --frozen-row-count and siblings, +cells-set-style
--font-bold / --bg-color / --wrap-strategy and the whole --border-* family
(no such flags; borders take one composite --border-styles). +sheet-rename
--new-name / --name alias to --title, matching +sheet-create.

Unsupported cell_styles field names now name the right field instead of the
nearest string: bold / font_bold -> font_weight, text_align ->
horizontal_alignment, a nested openpyxl-style font object -> the flat font_*
fields. Where no prescription applies, the edit-distance fallback is capped
at two edits, so a concept-swap neighbour (font_bold -> font_color, three
edits) stays silent rather than sending the retry the wrong way; a curated
prescription also drops the contradicting machine-readable suggestions.
2026-07-28 20:30:23 +08:00
zhengzhijie
0f93cadc4b fix(sheets): persist chart color theme updates 2026-07-28 17:01:28 +08:00
zhengzhijie
2459a2bb20 fix(sheets): allow chart color theme patches 2026-07-28 16:31:20 +08:00
zhengzhijie
ee71d92d5f feat(sheets): add dedicated chart batch shortcuts 2026-07-28 15:55:54 +08:00
zhengzhijie
f32448536d feat(sheets): improve chart creation dimension handling 2026-07-27 21:13:38 +08:00
zhengzhijie
62a32439f3 feat(sheets): harden chart update workflows 2026-07-27 14:15:14 +08:00
zhengzhijie
78c9653e8e feat(sheets): add chart data update shortcut 2026-07-27 12:00:50 +08:00
zhengzhijie
28d2bdc7a9 fix(sheets): normalize irregular chart ranges 2026-07-27 11:59:49 +08:00
zhengzhijie
69a9210a85 fix(sheets): normalize chart range and flag inputs 2026-07-27 11:59:49 +08:00
zhengzhijie
b9046f9ce9 fix(sheets): prefer semantic chart shortcuts 2026-07-27 11:59:48 +08:00
zhengzhijie
2dd4419d3b feat(sheets): improve semantic chart workflows 2026-07-27 11:59:47 +08:00
zhengzhijie
84c6d23e79 feat(sheets): add semantic chart shortcuts 2026-07-27 11:58:46 +08:00
zhengzhijie
6e20fd6e93 feat(sheets): support partial chart snapshot schemas 2026-07-27 11:58:45 +08:00
xiongyuanwen-byted
ca7135f582 fix(sheets): correct +dim-insert --inherit-style side mapping, drop redundant none
The flag name was inverted relative to actual behavior, and `none` was redundant.

- Map --inherit-style onto the modify_sheet_structure backend so the name
  matches behavior (verified on a live sheet): `before` inherits the preceding
  row/column (side=after, position-1); `after` inherits the following
  (side=before). Insertion always lands before --position.
- Warn only when `before` is used at the first row/column (no preceding
  dimension to copy from); `after` has no such edge.
- Drop the `none` enum value: it was identical to omitting the flag and
  misleadingly implied "no inheritance" (the backend always copies a
  neighbour). Omitting the flag inherits the following row/column; `none` is
  now rejected by enum validation. Clear formats afterwards for a blank one.
- Regenerate flag-defs, update tests and the skill reference.
2026-07-24 19:14:18 +08:00
xiongyuanwen-byted
7b58ba1b1d feat(sheets): batch-update contract hardening and style-vocabulary acceptance (#2028)
* feat(sheets): harden +batch-update sub-op contract (P0-1/2/3/5)

Eval-driven fixes for the top +batch-update error clusters (137 errors
across 7 eval batches, attribution in the optimization plan doc):

- Reject unknown sub-op input keys with did-you-mean + full key contract
  instead of silently ignoring them (silent ignore surfaced as misleading
  'missing required flag' errors — the largest cluster, ~35 hits).
  Habitual spellings are rewritten in place: camelCase -> snake_case,
  commandFlagAliases (new: size -> width/height on the resize pair, the
  pre-July vocabulary and the --styles protocol spelling, 15+ hits),
  single-entry ranges unwraps onto range.
- Aggregate per-op validation errors into one pass (each op's first
  error) instead of fail-fast first-error-only; single-error batches
  keep the standalone-shaped error (contract tests unchanged).
- Precheck cells matrix vs range locally: empty cells (prescribes
  +cells-clear) and row/column count mismatches no longer reach the
  server mid-batch.
- Correct the atomicity story: execution is fail-fast without rollback
  (verified against live batches; docs promised a rollback that does
  not happen). Partial-failure errors now spell out that succeeded
  operations stay applied and prescribe resending only the failed
  tail, preventing double-apply on retry.

* feat(cli): accept @file payload reads from the system temp dir (P0-6)

Agents stage generated payloads (batch operations JSON, CSV) in /tmp as
a matter of course; the relative-to-cwd-only policy pushed every
--operations @/tmp/ops.json through an extra python/stdin round trip
(recurring friction cluster in eval traces).

Scope is deliberately narrow: a new SafeTempAbsInputPath accepts an
absolute READ path only when it resolves (symlinks included) under the
canonical os.TempDir(), and only the @file expansion in
cmdutil.ReadInputFile uses it. SafeInputPath stays strict — uploads,
drive sync and the CI quality gates treat 'absolute paths rejected' as
a load-bearing invariant. Absolute paths outside the temp dir now get
a prescriptive error naming all three options (relative path, temp-dir
path, stdin).

* feat(sheets): add +styles-put, +dim-delete --ranges, freeze in --styles

Batch-B of the +batch-update overhaul (attribution: ~73% of real batch
calls were pure formatting finishers hand-built as operations arrays).

- +styles-put: declarative visual spec for existing spreadsheets.
  Reuses the workbook-create/table-put --styles parser (identical
  vocabulary and aggregate-all-issues errors), expands client-side into
  ONE atomic batch_update per spec: cell_merges -> cell_styles ->
  row_sizes -> col_sizes -> freeze. Style stamps are safe to re-run.
  Verified live: 6/6 sub-ops applied, frozen rows / merges / row
  heights confirmed by read-back.
- freeze section added to the shared --styles pipeline ({rows, cols}),
  so +workbook-create and +table-put gain it too — closes the one gap
  that still forced a separate +dim-freeze call.
- +dim-delete --ranges: scattered row/column ranges in one atomic
  batch, ordered DESCENDING so earlier deletions never shift later
  indexes (the recurring failure of hand-built dim-delete batches);
  same-dimension and non-overlap enforced, nesting inside
  +batch-update rejected with a prescription.
- +cells-batch-set-style enters phase-1 deprecation: kept working,
  docs point at +styles-put, an in-band note steers new usage.

Skill docs regenerated from sheet-skill-spec (new
lark-sheets-styles-put reference, three-way dispatch in guideline 6,
fail-fast-no-rollback wording).

* feat(sheets): accept height/width as one-way aliases for size in --styles row/col_sizes

size stays the canonical dimension key: it keeps row_sizes and col_sizes
items shape-uniform (the array name already carries the dimension), it is
what shipped with workbook-create/table-put and what models demonstrably
converge on, and it matches the dimension-neutral precedent of comparable
APIs. The Excel-vocabulary words are accepted silently only where
unambiguous — height inside row_sizes, width inside col_sizes; the wrong
dimension's word gets a targeted error instead of a rewrite, and giving
both size and the alias is rejected. Shared parser, so +workbook-create /
+table-put / +styles-put all gain it.

* chore(sheets): sync skill docs — +cells-batch-set-style fully exits the skill surface

Regenerated from sheet-skill-spec: the deprecated command no longer
appears anywhere in SKILL.md or the references (multi-range styling
routes to +styles-put); its flag-defs entry is untouched, so the command
and --help keep working for compatibility callers, with the in-band
supersedence note steering them to +styles-put.

* fix(sheets): forgive habitual vocabulary on the --styles payload path

07-20 rerun attribution: the batch-update dispatch worked (calls 105->25,
errors 21->8; +styles-put adopted by 16/35 tasks) but +styles-put itself
hit a 56% stateful error rate — the redesign moved traffic from the flag
path onto the payload path, and the round-2 forgiveness layers (key
aliases, enum-value canonicalization) only existed on the flag path.
Both dominant clusters are fixed in the shared styles pipeline, so
+styles-put / +table-put / +workbook-create / typed --cells all gain it:

- border family folding (largest cluster, up to 88 issues in one retry):
  borders/border objects, border_top..right objects, border_style/color/
  weight scalars, and flattened border_<side>_<attr> keys all fold into
  the canonical nested border_styles; border_style:"thin" reads as a
  thin solid line (weight vocabulary in the style slot).
- enum VALUE canonicalization inside cell_styles (~10 server-side
  round trips: vertical_alignment "center" -> "middle"), sourced from
  the +cells-set-style flag enums; off-enum values now fail client-side
  with a did-you-mean instead of failing the whole batch server-side.
- wrap family: wrap_text/text_wrap -> word_wrap, boolean -> enum.
- bare-string cell_merges entries read as {range, merge_type:all}.
- fore_color gets a prescription (openpyxl fgColor is the FILL color;
  a silent pick could color the wrong thing).

Replayed the eval-failing payload shapes live: 2/2 applied.

* feat(sheets): resize type optional in --styles; acceptance-surface contract tests

- {range, size} in row/col_sizes now means a pixel resize (type stays
  for standard/auto) — the payload path matches the flag path, where
  --width never required --type.
- Two closure tests turn the --styles acceptance surface into a locked
  contract instead of open-ended patching:
  * vocabulary parity — every +cells-set-style flag (iterated from
    flag-defs) must be accepted verbatim by the payload path, so a
    future flag can never again ship without payload-path support;
  * prior corpus — every model spelling observed across the 07-08..07-20
    eval batches must either normalize to canonical or produce a
    targeted prescription; silent ignoring and bare rejection both fail
    the suite. New eval finding -> add a corpus row -> fix -> locked.

Skill docs regenerated: the border shorthand ({style,weight,color} on
all four sides) is now the teaching form, border_styles demoted to
per-side differences; resize examples drop the type ceremony.

* fix(sheets): close the 07-21 rerun residuals — full-form thin, range coalescing, typed-cells style key

Valid rerun (skill injection verified at ~31k chars/task): +styles-put
stateful error rate fell 56.5% -> 34.3% and batch-update stayed at its
post-dispatch low. Three residual clusters, all closed:

- weight vocabulary in the FULL nested form's style slot
  (border_styles.<side>.style:"thin" — 8 tasks, the dominant residual;
  the earlier rewrite only covered the shorthand scalar path). Now
  normalized in expandBorderAllShorthand, the single border touchpoint
  shared by the flag, typed-cells and styles-payload paths.
- per-row specs blowing the 100-op cap (184/203/861-op expansions):
  coalesceStyleStamps fuses identical-style entries into rectangles
  (vertical fixpoint merge on same column span, horizontal on same row
  span) before the cap — a declarative spec describes intent, execution
  shape is the CLI's to optimize. Cap message now also routes
  alternating-row banding to +cond-format-create.
- typed --cells habitual keys (recurring server-side 900015206 in both
  reruns): cells[][].style object rewrites to cell_styles;
  cells[][].type gets a prescription instead of a server round trip.
  The content-in-styles message is also neutral now (was
  workbook-create-specific).

Corpus + coalescing + typed-cells tests added; live replay: full-form
thin accepted and 3 same-style rows fused, all applied.

* refactor(sheets): give the style-vocabulary acceptance layer its own home

Pure mechanical move, zero behavior change (locked by the acceptance
contract tests). The acceptance layer had grown as an accretion across
helpers.go and lark_sheet_workbook.go — deliberate design (one canonical
form + wide acceptance, per the divergent-priors evidence), accidental
placement.

style_vocab.go now holds the whole subsystem — flag-path style builders,
key aliases, enum-value canonicalization, border folding/normalization,
typed-cells cell-object rewrites — under a header that states the design
contract: rewrites must be unambiguous, ambiguity prescribes, silence
and bare rejection are both bugs, closure is enforced by the parity +
prior-corpus tests. helpers.go shrinks back to generic plumbing
(818 -> 542 lines).

The other two acceptance surfaces keep their own homes: cobra flag
ergonomics in flag_ergonomics.go, batch sub-op key vocabulary in
batch_op_dispatch.go.

* fix(sheets): enforce the cells-vs-range match on single-cell ranges too

The precheck deliberately skipped bare single-cell ranges when server
behavior was unverified; the 07-21 rerun supplied the evidence (12 rows
against range "A1" failing server-side with row count 1) — +cells-set
has no anchor semantics, the strict match applies everywhere. Corpus
updated accordingly.

* feat(sheets): make +csv-get --range optional — omitted reads the whole sheet

The tool requires a range but clips past-grid references and reports the
clip in actual_range, so the CLI sends an over-wide whole-columns range
(A:ZZZ) when --range is omitted: one call reads the entire sheet, no
workbook-info pre-flight to size it first. Eval evidence: 'required
flag(s) range not set' was the most-missed required flag on +csv-get
(4 tasks in the 07-21 batch) — the models' intent was always 'read it
all'. Blank --range now means the same as omitting it.

Skill docs updated (quick-reference row, read-data full-read example,
flag desc); round-3 backlog item A5.

* feat(sheets): add editing rule #10 — never fabricate missing values

补齐 / 扩展 / 按原表格式续填时,查不到或无法确定的值一律留空 +
备注注明,禁止用推算 / 估算 / 凭空数据充数;原表已示范缺失值写法时照抄。

Synced from sheet-skill-spec (SoT).

* fix(sheets): accept side-first border word order and wrap_strategy

07-21 evening batch (first run carrying the previous fixes — thin
full-form / style/type keys / csv-get range all at zero): the corpus
loop caught the next spelling permutations. bottom_border /
bottom_border_style (side-first word order, alongside the border_bottom
family already folded) and wrap_strategy (the Google Sheets API word)
now normalize; three corpus rows lock them.

* feat(sheets): universal did-you-mean on unknown style fields; formalize the silent-alias admission bar

The alias table was drifting toward per-permutation entries with fast-
falling marginal value (first aliases covered 15+ errors each, the last
ones 1-2). The asymmetry that matters: rejection is universal, aliases
are per-word. So:

- unknown style fields now reject with did-you-mean + the full canonical
  field list (this error had neither — the actual reason word-order
  permutations turned into multi-issue retry loops). Any future
  permutation costs one self-healing retry, zero new code, and corrects
  the whole session (silent aliases never correct the model in-session).
- the acceptance-layer contract now states the admission bar for silent
  aliases: real external vocabularies only (Excel/openpyxl, CSS, Google
  Sheets API — a finite set), recurring across batches or ≥3 tasks,
  zero ambiguity. Permutations go to the universal rejection. Existing
  permutation aliases are grandfathered.

* feat(sheets): +cells-set --writes — scattered multi-region writes in one atomic call

The last compressible batch-update scenario: eval traces show 'fix all
broken formulas across ranges/sheets' (~6 calls / 3 tasks per batch)
still hand-assembled as +batch-update operations arrays. --writes takes
[{sheet_name|sheet_id, range, cells}, ...] (up to 100 items, cross-sheet)
and fans it into ONE atomic batch_update of set_cell_range ops.

Design decisions:
- the sheet selector LIVES IN EACH ITEM — no top-level fallback, no
  precedence table; same convention models already learned from
  +batch-update sub-ops and +styles-put items. A top-level
  --sheet-name/--sheet-id with --writes is rejected with the fix.
- every item runs the exact standalone pipeline via a per-item flag
  view: key vocabulary (camelCase, aliases, did-you-mean), the style
  acceptance layer for inline cell_styles, matrix precheck, schema
  validation; item errors aggregate so one retry fixes all.
- XOR with --range/--cells/--copy-to-range; top-level --allow-overwrite
  propagates to items that don't override it.
- nesting inside +batch-update rejected (expands into its own batch).
- predictable prior handled: --styles on +cells-set now hints the
  layering (range-level styling -> +styles-put; per-cell styles ride in
  the cells objects) instead of a bare unknown-flag error.

Live smoke: value + formula regions in one call, 2/2 applied.
Expected effect: batch-update calls drop another ~30% to its
heterogeneous-atomic-chain steady state.

* chore(sheets): bump lark-sheets skill version to 3.1.0

Version roll-up for the batch-update optimization series: cells-set
--writes, universal did-you-mean on style fields, border word-order and
wrap_strategy acceptance, editing rule #10, and optional +csv-get
--range.
2026-07-24 13:18:03 +08:00
anunwu-byted
765b097d44 Merge pull request #2027 from larksuite/feat/error-schema-hints
Feat/error schema hints
2026-07-23 16:40:10 +08:00
wuyanchun.anunwu
4a5e2c519a feat(sheets): 校验失败全量收集报错(一次报出所有错误)
为什么:fail-fast 单错报错导致「挤牙膏」修复回路——修一处、重试、
撞下一处。评测实测(turbo 三批 247 次失败)约 32% 的失败轮次是
挤牙膏,其中 local→local 类(39 次)本可一次报出。

怎么改:
- validateAgainstSchema 重构为 collectSchemaErrors 收集器版:命中
  错误后继续遍历,全部问题一次报出(每条带各自的教学信息)
- translateBatchOperations 同步做 op 级聚合:多个坏 op 一条报错
  编号列出,不再 fail-fast 在第一个
- 三条护栏:单错误输出逐字不变(向后兼容);显示 cap 5 条 + 收集
  到 6 即全树短路(病态大数组不爆炸);类型错节点不下钻、oneOf
  用一次性探测器(防级联噪音/误报泄漏)

验证:gofmt/vet 干净,go test -count=1 全过(既有测试零改动,
新增 5 个聚合测试:多错编号、cap 截断、oneOf 不泄漏、batch 双 op
聚合、单 op 保持原文)。
2026-07-20 21:11:00 +08:00
xiongyuanwen-byted
67fc870582 feat(sheets): add --output-path for full-read file offload on cells/csv/table-get
Reads are capped by max_chars (default 500000; the backend tool also truncates
at ~50000 when unset). Add --output-path to +cells-get / +csv-get / +table-get:
when set, the result is written to a cwd-relative path as JSON and the char cap
is lifted to unbounded, so a large sheet lands on disk in full instead of being
clipped for stdout.

+table-get previously never sent max_chars, so it silently dropped rows past the
backend ~50000 default with no signal. It now takes --max-chars (default 500000,
sent explicitly) and surfaces truncated / truncation_warning when the read is
clipped, steering callers to --output-path for a lossless full read.
2026-07-20 11:26:46 +08:00
xiongyuanwen-byted
af8e027269 feat(sheets): support --include truncation on +cells-get
Map the new `truncation` value in --include to include_truncation_info on
the get_cell_ranges tool input, so +cells-get can return per-cell
isRowTruncated / isColTruncated. Flag metadata and reference synced from
sheet-skill-spec; flag_defs_gen.go regenerated.
2026-07-20 11:26:46 +08:00
xiongyuanwen-byted
2efadec335 feat(sheets): cut agent error rate and --help lookups (#1911)
## Background

Round 2 of eval-driven sheets optimization, rebased onto the latest `feat/lark-sheets-develop` (`8897196d`).

## Changes

- **feat(sheets): cut agent error rate and --help lookups (eval round 2)** — targets the top failure modes from round 2 evals, reducing agent error rate and the number of `--help` lookups.
- **chore(sheets): sync skill docs and flag data from sheet-skill-spec** — syncs skill docs and flag data from sheet-skill-spec.

## Notes

- During rebase, the "import mislabeled .xls workbooks by sniffing content" fix already existed on the target branch (identical patch-id), so it was auto-skipped — no duplicate.
- The target branch was force-rewritten and advanced in the meantime; the two new commits were cleanly replayed onto the new tip via `--onto` with no conflicts. One hunk touching the `--type` description in `lark-sheets-workbook.md` was auto-dropped because upstream already has the same end state — no content lost.
2026-07-20 11:26:46 +08:00
wuyanchun.anunwu
5fb70d326a feat(sheets): 校验失败报错内联 schema 提示(报错即教学)
为什么:豆包 Excel Agent 案例中模型 7 次参数错误,报错只说"错了"不说
"怎么改对",模型反复试错并静默降级交付(5 张饼图丢数据标签)。

怎么改:
- strict unexpected-property 报错附该节点合法 key 列表(cap 15 截断)
  + did-you-mean(复用 internal/suggest)
- required-missing 报错附缺失字段的 type/description/enum 一行提示
- 深层 type mismatch 报错附该字段 enum/description 后缀
- +batch-update 顶层 --sheet-id/--sheet-name(含下划线拼写)特判,
  直接指明 per-op locator 契约,不给误导性 fuzzy 建议
- batch sub-op input 拒收 cell_styles/styles/cell_merges 包裹结构,
  报错教学扁平 flags 写法
- 守护测试锁定 wrappedSubOpInputKeys 与 batchOpDispatch 的互斥假设

约束:不改 legacy 报错措辞前缀、保留 --print-schema 指针、不动宽松
AdditionalProperties 设计(内嵌 schema 当前无 strict 节点,该路径为预置)。

验证:gofmt -l 无输出、go vet 干净、go test -count=1 ./shortcuts/sheets/
./internal/suggest/ 全部通过。
2026-07-15 18:13:22 +08:00
66 changed files with 16206 additions and 4139 deletions

View File

@@ -4,6 +4,10 @@
package cmdutil
import (
"os"
"path/filepath"
"strings"
"github.com/larksuite/cli/errs"
)
@@ -14,12 +18,75 @@ import (
// with --yes.
//
// action identifies the operation for the agent (e.g. "mail +send",
// "drive.files.delete"). The envelope does not carry a pre-built retry
// command: agents already know their original invocation and only need to
// append --yes per the hint, which keeps the protocol free of shell-quoting
// pitfalls.
// "drive.files.delete"). When the original invocation can be re-run safely,
// the hint carries the complete retry command with --yes appended — eval
// traces show agents always self-heal by appending --yes, so handing them
// the exact line saves the reconstruction step. The retry line is omitted
// (falling back to the plain hint) when any argument reads stdin (a bare "-",
// as its own token or bundled onto a flag as --flag=-, whose piped data a
// bare re-run would not reproduce) or when the rendered command would be
// unreasonably long to echo back.
func RequireConfirmation(action string) error {
return errs.NewConfirmationRequiredError(errs.RiskHighRiskWrite, action,
"%s requires confirmation", action).
WithHint("add --yes to confirm")
err := errs.NewConfirmationRequiredError(errs.RiskHighRiskWrite, action,
"%s requires confirmation", action)
if retry := retryCommandWithYes(os.Args); retry != "" {
return err.WithHint("add --yes to confirm; re-run: %s", retry)
}
return err.WithHint("add --yes to confirm")
}
// retryCommandMaxLen caps the rendered retry command: past this, echoing the
// full invocation back (e.g. a +batch-update with a large inline JSON)
// costs more context than it saves.
const retryCommandMaxLen = 300
// retryCommandWithYes renders args as a shell-safe command line with --yes
// appended, or "" when a safe rendering isn't possible (see
// RequireConfirmation).
func retryCommandWithYes(args []string) string {
if len(args) == 0 {
return ""
}
parts := make([]string, 0, len(args)+1)
parts = append(parts, filepath.Base(args[0]))
for _, a := range args[1:] {
if argReadsStdin(a) {
return ""
}
parts = append(parts, shellQuoteArg(a))
}
parts = append(parts, "--yes")
line := strings.Join(parts, " ")
if len(line) > retryCommandMaxLen {
return ""
}
return line
}
// argReadsStdin reports whether an argument makes a flag read from stdin — the
// portable bare "-" value, whether passed as its own token (--flag -) or
// bundled onto the flag (--flag=- / -f=-). Piped stdin is one-shot data a bare
// re-run cannot reproduce, so any such argument suppresses the retry line.
func argReadsStdin(a string) bool {
if a == "-" {
return true
}
if strings.HasPrefix(a, "-") {
if i := strings.IndexByte(a, '='); i >= 0 && a[i+1:] == "-" {
return true
}
}
return false
}
// shellQuoteArg single-quotes an argument when it contains any character a
// POSIX shell could interpret, so the retry line is copy-paste safe.
func shellQuoteArg(s string) string {
if s == "" {
return "''"
}
if !strings.ContainsAny(s, " \t\n\"'\\$`!*?[](){}<>|&;#~") {
return s
}
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}

View File

@@ -35,8 +35,11 @@ func TestRequireConfirmation_TypedShape(t *testing.T) {
if !strings.Contains(cre.Message, "drive +delete") || !strings.Contains(cre.Message, "requires confirmation") {
t.Errorf("Message = %q, want it to mention action and 'requires confirmation'", cre.Message)
}
if cre.Hint != "add --yes to confirm" {
t.Errorf("Hint = %q, want 'add --yes to confirm'", cre.Hint)
// The hint may additionally carry a re-run line composed from the live
// os.Args (environment-dependent under `go test`), but the add-yes
// contract always leads.
if !strings.HasPrefix(cre.Hint, "add --yes to confirm") {
t.Errorf("Hint = %q, want prefix 'add --yes to confirm'", cre.Hint)
}
if cre.Risk != errs.RiskHighRiskWrite {
t.Errorf("Risk = %q, want %q", cre.Risk, errs.RiskHighRiskWrite)
@@ -61,8 +64,8 @@ func TestRequireConfirmation_JSONShape(t *testing.T) {
t.Fatalf("unmarshal: %v", err)
}
// No fix_command field leaks into the envelope: the protocol avoids
// shell-quoting hazards by delegating retry to agent-side logic.
// No fix_command field leaks into the envelope: the retry line lives in
// the free-text hint only; the typed protocol stays action-only.
if _, has := back["fix_command"]; has {
t.Errorf("unexpected fix_command present in JSON: %s", raw)
}
@@ -78,3 +81,46 @@ func TestRequireConfirmation_JSONShape(t *testing.T) {
t.Errorf("unexpected upgraded_by present in JSON: %s", raw)
}
}
// TestRetryCommandWithYes pins the retry-line contract: shell-safe quoting,
// basename argv[0], and the two omission guards (stdin args, oversized
// commands).
func TestRetryCommandWithYes(t *testing.T) {
t.Run("quotes what needs quoting and appends --yes", func(t *testing.T) {
got := retryCommandWithYes([]string{
"/usr/local/bin/lark-cli", "sheets", "+cells-clear",
"--url", "https://x.feishu.cn/sheets/tok",
"--range", "A1:B2", "--sheet-name", "第 1 班",
})
want := `lark-cli sheets +cells-clear --url https://x.feishu.cn/sheets/tok --range A1:B2 --sheet-name '第 1 班' --yes`
if got != want {
t.Errorf("got %q, want %q", got, want)
}
})
t.Run("single quotes inside args survive", func(t *testing.T) {
got := retryCommandWithYes([]string{"lark-cli", "x", "--title", "it's"})
if !strings.Contains(got, `'it'\''s'`) {
t.Errorf("got %q", got)
}
})
t.Run("stdin arg omits the retry line", func(t *testing.T) {
if got := retryCommandWithYes([]string{"lark-cli", "sheets", "+batch-update", "--operations", "-"}); got != "" {
t.Errorf("stdin invocation must not render a retry line, got %q", got)
}
})
t.Run("bundled stdin flag omits the retry line", func(t *testing.T) {
// --flag=- reads stdin the same as --flag -; both must suppress the line.
if got := retryCommandWithYes([]string{"lark-cli", "sheets", "+cells-set", "--cells=-"}); got != "" {
t.Errorf("--flag=- stdin invocation must not render a retry line, got %q", got)
}
})
t.Run("oversized command omits the retry line", func(t *testing.T) {
if got := retryCommandWithYes([]string{"lark-cli", "x", "--operations", strings.Repeat("a", 400)}); got != "" {
t.Errorf("oversized invocation must not render a retry line, got %q", got)
}
})
}

View File

@@ -7,9 +7,12 @@ import (
"errors"
"fmt"
"io"
"os"
"path/filepath"
"strings"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/validate"
)
// ResolveInput resolves special input conventions for a raw flag value:
@@ -77,7 +80,25 @@ func ResolveInput(raw string, stdin io.Reader, fileIO fileio.FileIO) (string, er
// ReadInputFile reads path through fileIO. Open/read failures are wrapped with
// path context; fileio.ErrPathValidation remains matchable with errors.Is.
// An absolute path under the system temp dir is read directly instead:
// agents stage generated payloads (@/tmp/ops.json) there as a matter of
// course, and the strict relative-to-cwd policy — load-bearing for uploads
// and drive sync — only cost @file callers a python/stdin detour.
func ReadInputFile(fileIO fileio.FileIO, path string) ([]byte, error) {
resolved, terr := validate.SafeTempAbsInputPath(path)
if terr == nil {
data, err := os.ReadFile(resolved) //nolint:forbidigo // resolved is confined to the system temp dir by SafeTempAbsInputPath
if err != nil {
return nil, wrapInputFileError(path, err)
}
return data, nil
}
if filepath.IsAbs(path) {
// Absolute but outside the temp dir: surface the prescriptive error
// (relative path / temp-dir path / stdin) instead of the generic
// relative-only message the strict validator below would produce.
return nil, fmt.Errorf("invalid file path %q: %w", path, terr)
}
if fileIO == nil {
return nil, fmt.Errorf("file input is not available in this context")
}

View File

@@ -17,6 +17,12 @@ func SafeInputPath(path string) (string, error) {
return localfileio.SafeInputPath(path)
}
// SafeTempAbsInputPath accepts an absolute read path only when it resolves
// under the system temp dir. Delegates to localfileio.SafeTempAbsInputPath.
func SafeTempAbsInputPath(path string) (string, error) {
return localfileio.SafeTempAbsInputPath(path)
}
// SafeEnvDirPath validates an environment-provided application directory path.
// Delegates to localfileio.SafeEnvDirPath.
func SafeEnvDirPath(path, envName string) (string, error) {

View File

@@ -5,6 +5,7 @@ package localfileio
import (
"fmt"
"os"
"path/filepath"
"strings"
@@ -18,10 +19,35 @@ func SafeOutputPath(path string) (string, error) {
}
// SafeInputPath validates an upload/read source path for --file flags.
// Deliberately strict (relative-to-cwd only): several callers — drive sync,
// upload flags, the CI quality gates — treat "absolute paths rejected" as a
// load-bearing invariant. The one deliberate exception is the @file payload
// expansion, which layers SafeTempAbsInputPath on top (see cmdutil).
func SafeInputPath(path string) (string, error) {
return safePath(path, "--file")
}
// SafeTempAbsInputPath accepts an absolute READ path only when it resolves
// under the canonical system temp dir. Agents stage generated payloads
// (batch operations JSON, CSV) in /tmp as a matter of course, and rejecting
// @/tmp/ops.json only pushed them through an extra python/stdin round trip
// (recurring friction cluster in eval traces). Reads under os.TempDir()
// carry no write risk and no project-escape risk. Errors for anything else
// (relative paths included) — callers fall back to SafeInputPath semantics.
func SafeTempAbsInputPath(path string) (string, error) {
if err := charcheck.RejectControlChars(path, "--file"); err != nil {
return "", err
}
if !isAbsolutePath(path) {
return "", fmt.Errorf("--file %q is not an absolute path", path)
}
resolved, ok := absPathUnderTempDir(path)
if !ok {
return "", fmt.Errorf("--file must be a relative path within the current directory, or an absolute path under the system temp dir (%s), got %q (hint: use ./filename or a %s path; flags that support stdin can read any file via '-' instead)", os.TempDir(), path, os.TempDir())
}
return resolved, nil
}
// 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) {
@@ -96,6 +122,26 @@ func safePath(raw, flagName string) (string, error) {
return resolved, nil
}
// absPathUnderTempDir accepts an absolute path only when, after cleaning and
// resolving symlinks (through the nearest existing ancestor for
// not-yet-created files), it still lives under the canonical system temp dir.
// A symlink inside the temp dir pointing outside it resolves outside and is
// rejected.
func absPathUnderTempDir(raw string) (string, bool) {
canonicalTmp, err := filepath.EvalSymlinks(os.TempDir())
if err != nil {
return "", false
}
resolved, err := resolveNearestAncestor(filepath.Clean(raw))
if err != nil {
return "", false
}
if !isUnderDir(resolved, canonicalTmp) || resolved == canonicalTmp {
return "", false
}
return resolved, true
}
func resolveNearestAncestor(path string) (string, error) {
var tail []string
cur := path

View File

@@ -175,7 +175,7 @@ func TestSafeOutputPath_DeepNonExistentPathStaysInCWD(t *testing.T) {
}
}
func TestSafeUploadPath_AllowsTempFileAbsolutePath(t *testing.T) {
func TestSafeUploadPath_RejectsTempFileAbsolutePath(t *testing.T) {
// GIVEN: a real temp file (absolute path under os.TempDir())
f, err := os.CreateTemp("", "upload-test-*.bin")
if err != nil {
@@ -185,15 +185,67 @@ func TestSafeUploadPath_AllowsTempFileAbsolutePath(t *testing.T) {
f.Close()
t.Cleanup(func() { os.Remove(tmpPath) })
// WHEN: SafeUploadPath validates the absolute temp path
// WHEN: SafeInputPath validates the absolute temp path
_, err = SafeInputPath(tmpPath)
// THEN: absolute paths are rejected even in temp dir
// THEN: the strict validator rejects it — uploads / drive sync rely on
// relative-only; temp-dir reads go through SafeTempAbsInputPath instead
if err == nil {
t.Fatal("expected error for absolute temp path, got nil")
}
}
func TestSafeTempAbsInputPath(t *testing.T) {
t.Run("accepts a file under the temp dir", func(t *testing.T) {
f, err := os.CreateTemp("", "payload-*.json")
if err != nil {
t.Fatalf("CreateTemp: %v", err)
}
tmpPath := f.Name()
f.Close()
t.Cleanup(func() { os.Remove(tmpPath) })
resolved, err := SafeTempAbsInputPath(tmpPath)
if err != nil {
t.Fatalf("expected temp path accepted, got %v", err)
}
canonical, err := filepath.EvalSymlinks(tmpPath)
if err != nil {
t.Fatalf("EvalSymlinks: %v", err)
}
if resolved != canonical {
t.Fatalf("resolved = %q, want %q", resolved, canonical)
}
})
t.Run("rejects relative paths", func(t *testing.T) {
if _, err := SafeTempAbsInputPath("./ops.json"); err == nil {
t.Fatal("expected error for relative path, got nil")
}
})
t.Run("rejects absolute paths outside the temp dir", func(t *testing.T) {
if _, err := SafeTempAbsInputPath("/etc/passwd"); err == nil {
t.Fatal("expected error for non-temp absolute path, got nil")
}
})
t.Run("rejects a temp-dir symlink escaping outside", func(t *testing.T) {
dir, err := os.MkdirTemp("", "escape-*")
if err != nil {
t.Fatalf("MkdirTemp: %v", err)
}
t.Cleanup(func() { os.RemoveAll(dir) })
link := filepath.Join(dir, "escape.json")
if err := os.Symlink("/etc/passwd", link); err != nil {
t.Skipf("symlink not supported: %v", err)
}
if _, err := SafeTempAbsInputPath(link); err == nil {
t.Fatal("expected error for symlink escaping the temp dir, got nil")
}
})
}
func TestSafeUploadPath_RejectsNonTempAbsolutePath(t *testing.T) {
for _, tt := range []struct {
name string

View File

@@ -50,6 +50,7 @@ type RuntimeContext struct {
botInfoFunc func() (*BotInfo, error) // sync.OnceValues; lazy bot identity from /bot/v3/info
larkSDK *lark.Client // eagerly initialized in mountDeclarative
stdinConsumed bool // set when an Input flag has consumed stdin (`-`); guards against a second flag also using `-` within the same call
inputResolved map[string]bool // flags whose value was replaced by @file / stdin content in resolveInputFlags; see InputResolvedFromSource
}
// ── Identity ──
@@ -1043,6 +1044,25 @@ func stripUTF8BOM(s string) string {
return strings.TrimPrefix(s, "\uFEFF")
}
// InputResolvedFromSource reports whether the named flag's value was loaded
// from an external source (@file or stdin `-`) by resolveInputFlags, as
// opposed to typed inline on the command line. Domain guards that apply
// shape heuristics to inline values ("this looks like a file path — did you
// forget the @?") must skip resolved values: their content was already read
// from the right place and may legitimately look like anything, including a
// path. Without this bit such a guard re-rejects correct @file / stdin
// invocations, because by the time Validate runs both arrive as plain text.
func (ctx *RuntimeContext) InputResolvedFromSource(name string) bool {
return ctx.inputResolved[name]
}
func (ctx *RuntimeContext) markInputResolved(name string) {
if ctx.inputResolved == nil {
ctx.inputResolved = map[string]bool{}
}
ctx.inputResolved[name] = true
}
// resolveInputFlags resolves @file and - (stdin) for flags with Input sources.
// Must be called before Validate/DryRun/Execute so that runtime.Str() returns resolved content.
func resolveInputFlags(rctx *RuntimeContext, flags []Flag) error {
@@ -1082,6 +1102,7 @@ func resolveInputFlags(rctx *RuntimeContext, flags []Flag) error {
// strip a leading UTF-8 BOM so it can't corrupt the first CSV
// cell or break JSON parsing downstream.
rctx.Cmd.Flags().Set(fl.Name, stripUTF8BOM(string(data)))
rctx.markInputResolved(fl.Name)
continue
}
@@ -1118,6 +1139,7 @@ func resolveInputFlags(rctx *RuntimeContext, flags []Flag) error {
// strip a leading UTF-8 BOM so it
// can't corrupt the first CSV cell or break JSON parsing downstream.
rctx.Cmd.Flags().Set(fl.Name, stripUTF8BOM(string(data)))
rctx.markInputResolved(fl.Name)
continue
}
}

View File

@@ -43,6 +43,9 @@ func TestResolveInputFlags_DirectValue(t *testing.T) {
if got := rctx.Str("markdown"); got != "hello world" {
t.Errorf("expected %q, got %q", "hello world", got)
}
if rctx.InputResolvedFromSource("markdown") {
t.Error("inline value must not be marked as resolved from a source")
}
}
func TestResolveInputFlags_Stdin(t *testing.T) {
@@ -55,6 +58,9 @@ func TestResolveInputFlags_Stdin(t *testing.T) {
if got := rctx.Str("markdown"); got != "content from stdin" {
t.Errorf("expected %q, got %q", "content from stdin", got)
}
if !rctx.InputResolvedFromSource("markdown") {
t.Error("stdin value should be marked as resolved from a source")
}
}
func TestResolveInputFlags_File(t *testing.T) {
@@ -75,6 +81,27 @@ func TestResolveInputFlags_File(t *testing.T) {
if got := rctx.Str("markdown"); got != content {
t.Errorf("expected %q, got %q", content, got)
}
if !rctx.InputResolvedFromSource("markdown") {
t.Error("@file value should be marked as resolved from a source")
}
}
// TestResolveInputFlags_EscapedAtStaysInline pins that the @@ escape is
// inline content (a literal leading @), not an external source — heuristic
// guards keyed on InputResolvedFromSource must still see it.
func TestResolveInputFlags_EscapedAtStaysInline(t *testing.T) {
rctx := newTestRuntimeWithStdin(map[string]string{"markdown": "@@handle"}, "")
flags := []Flag{{Name: "markdown", Input: []string{File, Stdin}}}
if err := resolveInputFlags(rctx, flags); err != nil {
t.Fatalf("unexpected error: %v", err)
}
if got := rctx.Str("markdown"); got != "@handle" {
t.Errorf("expected %q, got %q", "@handle", got)
}
if rctx.InputResolvedFromSource("markdown") {
t.Error("escaped @@ value must not be marked as resolved from a source")
}
}
func TestResolveInputFlags_EmptyFile(t *testing.T) {

View File

@@ -39,6 +39,13 @@ func TestNewRuntimeContextWithBotInfo(cmd *cobra.Command, cfg *core.CliConfig, i
return rctx
}
// TestMarkInputResolved marks a flag as resolved from @file / stdin, so
// domain tests can exercise guards that branch on InputResolvedFromSource
// without wiring the full resolveInputFlags path.
func TestMarkInputResolved(rctx *RuntimeContext, name string) {
rctx.markInputResolved(name)
}
// TestNewRuntimeContextForAPI creates a RuntimeContext ready for HTTP tests:
// sets Cmd, Config, Factory, context, and the requested identity so callers
// can invoke DoAPI / CallAPI directly without wiring through a cobra parent

View File

@@ -0,0 +1,298 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"strings"
"testing"
)
// subOp builds a raw +batch-update sub-op for translateBatchOp tests.
func subOp(shortcut string, input map[string]interface{}) map[string]interface{} {
return map[string]interface{}{"shortcut": shortcut, "input": input}
}
// TestBatchOp_UnknownInputKeyRejected pins the key-vocabulary guard: an
// off-vocabulary sub-op input key must error with a did-you-mean instead of
// being silently ignored (silent ignore surfaced as misleading "missing
// required flag" errors — the top batch error cluster in eval traces).
func TestBatchOp_UnknownInputKeyRejected(t *testing.T) {
t.Parallel()
t.Run("invented key errors with did-you-mean", func(t *testing.T) {
t.Parallel()
_, err := translateBatchOp(subOp("+cells-set", map[string]interface{}{
"sheet_name": "S1",
"rangee": "A1:B2",
"cells": []interface{}{[]interface{}{map[string]interface{}{"value": "x"}}},
}), testToken, 0)
ve := requireValidation(t, err, `unknown input key "rangee"`)
if !strings.Contains(ve.Message, `did you mean "range"`) {
t.Fatalf("message %q missing did-you-mean", ve.Message)
}
if !strings.Contains(ve.Hint, "input keys:") {
t.Fatalf("hint %q missing key contract", ve.Hint)
}
})
t.Run("system flag is not sub-op vocabulary", func(t *testing.T) {
t.Parallel()
_, err := translateBatchOp(subOp("+cells-clear", map[string]interface{}{
"sheet_name": "S1",
"range": "A1:B2",
"dry_run": true,
}), testToken, 0)
requireValidation(t, err, `unknown input key "dry_run"`)
})
t.Run("reserved locators are ignored and top-level token wins", func(t *testing.T) {
t.Parallel()
translated, err := translateBatchOp(subOp("+cells-clear", map[string]interface{}{
"sheet_name": "S1",
"range": "A1:B2",
"spreadsheet-token": "shtXXX",
"excel_id": "shtYYY",
"url": "https://example.invalid/sheets/shtZZZ",
}), testToken, 0)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
input := translated["input"].(map[string]interface{})
if input["excel_id"] != testToken {
t.Fatalf("excel_id = %v, want top-level token %q", input["excel_id"], testToken)
}
if _, has := input["spreadsheet_token"]; has {
t.Fatalf("spreadsheet_token should be dropped: %#v", input)
}
if _, has := input["url"]; has {
t.Fatalf("url should be dropped: %#v", input)
}
})
}
// TestBatchOp_HabitualKeysRewritten pins the silent rewrites: camelCase onto
// the declared flag, and the commandFlagAliases table (size → width/height on
// the resize pair — the pre-2026-07 vocabulary and the styles-protocol
// spelling, the single largest sub-op error cluster).
func TestBatchOp_HabitualKeysRewritten(t *testing.T) {
t.Parallel()
t.Run("camelCase sheetName resolves", func(t *testing.T) {
t.Parallel()
translated, err := translateBatchOp(subOp("+cells-clear", map[string]interface{}{
"sheetName": "S1",
"range": "A1:B2",
}), testToken, 0)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
input := translated["input"].(map[string]interface{})
if input["sheet_name"] != "S1" {
t.Fatalf("sheet_name = %v, want S1", input["sheet_name"])
}
})
t.Run("size aliases to width on +cols-resize", func(t *testing.T) {
t.Parallel()
translated, err := translateBatchOp(subOp("+cols-resize", map[string]interface{}{
"sheet_name": "S1",
"range": "A:C",
"type": "pixel",
"size": float64(120),
}), testToken, 0)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
input := translated["input"].(map[string]interface{})
width, _ := input["resize_width"].(map[string]interface{})
if width["value"] != 120 {
t.Fatalf("resize_width = %v, want value 120", input["resize_width"])
}
})
t.Run("size aliases to height on +rows-resize", func(t *testing.T) {
t.Parallel()
_, err := translateBatchOp(subOp("+rows-resize", map[string]interface{}{
"sheet_name": "S1",
"range": "1:3",
"type": "pixel",
"size": float64(36),
}), testToken, 0)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
})
t.Run("single-entry ranges unwraps onto range", func(t *testing.T) {
t.Parallel()
translated, err := translateBatchOp(subOp("+cells-clear", map[string]interface{}{
"sheet_name": "S1",
"ranges": []interface{}{"A1:B2"},
}), testToken, 0)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
input := translated["input"].(map[string]interface{})
if input["range"] != "A1:B2" {
t.Fatalf("range = %v, want A1:B2", input["range"])
}
})
t.Run("multi-entry ranges prescribes a split", func(t *testing.T) {
t.Parallel()
_, err := translateBatchOp(subOp("+cells-clear", map[string]interface{}{
"sheet_name": "S1",
"ranges": []interface{}{"A1:B2", "C1:D2"},
}), testToken, 0)
requireValidation(t, err, "split them into 2 sub-ops")
})
}
// TestBatchOperations_AggregatesValidationErrors pins the one-pass contract:
// several invalid ops come back in a single error (each with its own
// operations[i] context) instead of the first only — eval traces show
// fix-one-resend loops of up to 7 round trips under first-error-only.
func TestBatchOperations_AggregatesValidationErrors(t *testing.T) {
t.Parallel()
t.Run("two bad ops both reported", func(t *testing.T) {
t.Parallel()
_, err := translateBatchOperations([]interface{}{
subOp("+cells-clear", map[string]interface{}{"range": "A1:B2"}), // missing sheet selector
subOp("+cells-set", map[string]interface{}{"sheet_name": "S1", "range": "A1"}), // missing cells
subOp("+cells-clear", map[string]interface{}{"sheet_name": "S1", "range": "A1:B2"}), // valid
}, testToken)
ve := requireValidation(t, err, "2 of 3 operations failed validation")
for _, want := range []string{"operations[0] (+cells-clear)", "operations[1] (+cells-set)", "--cells is required"} {
if !strings.Contains(ve.Message, want) {
t.Fatalf("message %q missing %q", ve.Message, want)
}
}
})
t.Run("single bad op keeps the standalone-shaped error", func(t *testing.T) {
t.Parallel()
_, err := translateBatchOperations([]interface{}{
subOp("+cells-set", map[string]interface{}{"sheet_name": "S1", "range": "A1"}),
}, testToken)
ve := requireValidation(t, err, "--cells is required")
if strings.Contains(ve.Message, "failed validation") {
t.Fatalf("single-error message must not use the aggregate wrapper: %q", ve.Message)
}
})
}
// TestCellsSetInput_MatrixPrecheck pins the local cells-vs-range guard that
// front-runs the server's mid-batch "does not match range" failures.
func TestCellsSetInput_MatrixPrecheck(t *testing.T) {
t.Parallel()
cases := []struct {
name string
input map[string]interface{}
wantContains string // "" = expect success
}{
{
"empty cells prescribes +cells-clear",
map[string]interface{}{"sheet_name": "S1", "range": "A1:B2", "cells": []interface{}{}},
"+cells-clear",
},
{
"row count mismatch",
map[string]interface{}{"sheet_name": "S1", "range": "A1:B3",
"cells": []interface{}{
[]interface{}{map[string]interface{}{"value": "a"}, map[string]interface{}{"value": "b"}},
}},
"has 1 rows but --range \"A1:B3\" spans 3 rows",
},
{
"column count mismatch",
map[string]interface{}{"sheet_name": "S1", "range": "A1:B1",
"cells": []interface{}{
[]interface{}{map[string]interface{}{"value": "a"}},
}},
"has 1 columns but --range \"A1:B1\" spans 2 columns",
},
{
"matching matrix passes",
map[string]interface{}{"sheet_name": "S1", "range": "A1:B2",
"cells": []interface{}{
[]interface{}{map[string]interface{}{"value": "a"}, map[string]interface{}{"value": "b"}},
[]interface{}{map[string]interface{}{"value": "c"}, map[string]interface{}{"value": "d"}},
}},
"",
},
{
"bare single-cell range enforces the 1x1 match (07-21: server rejects anchors too)",
map[string]interface{}{"sheet_name": "S1", "range": "A1",
"cells": []interface{}{
[]interface{}{map[string]interface{}{"value": "a"}, map[string]interface{}{"value": "b"}},
}},
"has 2 columns but --range \"A1\" spans 1 columns",
},
{
"single-cell range with a single cell passes",
map[string]interface{}{"sheet_name": "S1", "range": "B3",
"cells": []interface{}{
[]interface{}{map[string]interface{}{"value": "a"}},
}},
"",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
_, err := translateBatchOp(subOp("+cells-set", tc.input), testToken, 0)
if tc.wantContains == "" {
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return
}
requireValidation(t, err, tc.wantContains)
})
}
}
// TestFlattenToolErrorMsg_PartialFailureRecovery pins the no-rollback recovery
// prescription appended to server-side "N succeeded, M failed" errors.
func TestFlattenToolErrorMsg_PartialFailureRecovery(t *testing.T) {
t.Parallel()
wrap := func(inner string) string {
return `{"error":` + jsonQuote(inner) + `}`
}
t.Run("single failure prescribes resend-from-index", func(t *testing.T) {
t.Parallel()
msg := flattenToolErrorMsg(wrap(`{"message":"batch_update: 4 succeeded, 1 failed","failures":[{"index":4,"tool_name":"set_cell_range","error":"cells is required"}]}`))
for _, want := range []string{"operations[4] (set_cell_range)", "no rollback", "resend only operations[4:]"} {
if !strings.Contains(msg, want) {
t.Fatalf("msg %q missing %q", msg, want)
}
}
})
t.Run("multiple failures prescribe failed-only resend", func(t *testing.T) {
t.Parallel()
msg := flattenToolErrorMsg(wrap(`{"message":"batch_update: 3 succeeded, 2 failed","failures":[{"index":1,"tool_name":"set_cell_range","error":"e1"},{"index":3,"tool_name":"resize_range","error":"e2"}]}`))
if !strings.Contains(msg, "resend only the failed operations") {
t.Fatalf("msg %q missing failed-only prescription", msg)
}
})
t.Run("zero succeeded gets no note", func(t *testing.T) {
t.Parallel()
msg := flattenToolErrorMsg(wrap(`{"message":"batch_update: 0 succeeded, 1 failed","failures":[{"index":0,"tool_name":"set_cell_range","error":"e"}]}`))
if strings.Contains(msg, "no rollback") {
t.Fatalf("msg %q must not carry the note when nothing was applied", msg)
}
})
}
// jsonQuote wraps s as a JSON string literal (escaping quotes), mirroring how
// the server double-encodes the inner error payload.
func jsonQuote(s string) string {
return `"` + strings.ReplaceAll(strings.ReplaceAll(s, `\`, `\\`), `"`, `\"`) + `"`
}

View File

@@ -205,24 +205,6 @@ func TestBatchOp_BodyMatchesStandalone(t *testing.T) {
args: []string{"--sheet-id", "sh1", "--range", "A2:A4", "--options", `["x","y"]`, "--highlight=false"},
subInput: `{"sheet-id":"sh1","range":"A2:A4","options":["x","y"],"highlight":false}`,
},
{
shortcut: "+chart-create",
sc: ChartCreate,
args: []string{"--sheet-id", "sh1", "--properties", `{"position":{"row":0,"col":"A"},"size":{"width":400,"height":300}}`},
subInput: `{"sheet-id":"sh1","properties":{"position":{"row":0,"col":"A"},"size":{"width":400,"height":300}}}`,
},
{
shortcut: "+chart-update",
sc: ChartUpdate,
args: []string{"--sheet-id", "sh1", "--chart-id", "c1", "--properties", `{"position":{"row":0,"col":"A"},"size":{"width":400,"height":300}}`},
subInput: `{"sheet-id":"sh1","chart-id":"c1","properties":{"position":{"row":0,"col":"A"},"size":{"width":400,"height":300}}}`,
},
{
shortcut: "+chart-delete",
sc: ChartDelete,
args: []string{"--sheet-id", "sh1", "--chart-id", "c1"},
subInput: `{"sheet-id":"sh1","chart-id":"c1"}`,
},
{
shortcut: "+pivot-create",
sc: PivotCreate,
@@ -275,6 +257,42 @@ func TestBatchOp_BodyMatchesStandalone(t *testing.T) {
args: []string{"--sheet-id", "sh1", "--group-id", "g1"},
subInput: `{"sheet-id":"sh1","group-id":"g1"}`,
},
{
shortcut: "+chart-create",
sc: ChartCreate,
args: []string{"--sheet-id", "sh1", "--properties", `{"type":"line","position":{"row":0,"col":"A"},"size":{"width":400,"height":300}}`},
subInput: `{"sheet-id":"sh1","properties":{"type":"line","position":{"row":0,"col":"A"},"size":{"width":400,"height":300}}}`,
},
{
shortcut: "+chart-update",
sc: ChartUpdate,
args: []string{"--sheet-id", "sh1", "--chart-id", "chart-1", "--properties", `{"title":{"text":"Revenue"}}`},
subInput: `{"sheet-id":"sh1","chart-id":"chart-1","properties":{"title":{"text":"Revenue"}}}`,
},
{
shortcut: "+chart-delete",
sc: ChartDelete,
args: []string{"--sheet-id", "sh1", "--chart-id", "chart-1"},
subInput: `{"sheet-id":"sh1","chart-id":"chart-1"}`,
},
{
shortcut: "+chart-create-basic",
sc: ChartCreateBasic,
args: []string{"--sheet-id", "sh1", "--chart-type", "line", "--data-range", "A1:C10", "--title", "Revenue"},
subInput: `{"sheet-id":"sh1","chart-type":"line","data-range":"A1:C10","title":"Revenue"}`,
},
{
shortcut: "+chart-config-update",
sc: ChartConfigUpdate,
args: []string{"--sheet-id", "sh1", "--chart-id", "chart-1", "--title", "Revenue"},
subInput: `{"sheet-id":"sh1","chart-id":"chart-1","title":"Revenue"}`,
},
{
shortcut: "+chart-data-update",
sc: ChartDataUpdate,
args: []string{"--sheet-id", "sh1", "--chart-id", "chart-1", "--data-range", "A1:C10", "--data-direction", "column"},
subInput: `{"sheet-id":"sh1","chart-id":"chart-1","data-range":"A1:C10","data-direction":"column"}`,
},
{
shortcut: "+float-image-create",
sc: FloatImageCreate,
@@ -656,12 +674,6 @@ func TestBatchOp_RejectsBadSubOpInput(t *testing.T) {
`{"sheet-id":"sh1"}`,
"--title is required",
},
{
"+chart-update missing --chart-id",
"+chart-update",
`{"sheet-id":"sh1","properties":{"title":"T"}}`,
"--chart-id is required",
},
{
"+filter-create missing --range",
"+filter-create",
@@ -763,17 +775,9 @@ func TestBatchOp_SchemaValidatesSubOps(t *testing.T) {
{
"+pivot-create summarize_by out of enum",
"+pivot-create",
`{"sheet-id":"sh1","source":"Sheet1!A1:D100","properties":{"values":[{"field":"A","summarize_by":"BOGUS"}]}}`,
`{"target_sheet_id":"sh1","source":"Sheet1!A1:D100","properties":{"values":[{"field":"A","summarize_by":"BOGUS"}]}}`,
"summarize_by",
},
// +chart-create properties.position.row has minimum:0 — P0
// addition; validator must catch -1 even in the batch path.
{
"+chart-create position.row below minimum",
"+chart-create",
`{"sheet-id":"sh1","properties":{"position":{"row":-1,"col":"A"},"size":{"width":400,"height":300}}}`,
"below minimum",
},
// +cells-set --cells is a 2D array of objects per the
// upstream-fixed schema; sub-op passing an object must be
// rejected at the schema layer (not "expected JSON array").

View File

@@ -4,8 +4,11 @@
package sheets
import (
"fmt"
"sort"
"strings"
"github.com/larksuite/cli/internal/suggest"
)
// ─── +batch-update sub-op dispatch ─────────────────────────────────────
@@ -84,7 +87,14 @@ func objDeleteTranslate(spec objectCRUDSpec) batchTranslateFn {
// flag error is identical too (locked by TestBatchOp_ErrorEquivalence).
var batchOpDispatch = map[string]batchOpMapping{
// ─── 单元格内容 ──────────────────────────────────────────────────
"+cells-set": {"set_cell_range", cellsSetInput},
"+cells-set": {"set_cell_range", func(fv flagView, token, sid, sname string) (map[string]interface{}, error) {
// The --writes plural form expands into its own atomic batch and
// cannot nest; sub-ops carry one range+cells each.
if fv.Changed("writes") {
return nil, sheetsValidationForFlag("writes", `"writes" is not supported inside +batch-update (it expands into its own atomic batch); call +cells-set --writes standalone, or give each sub-op a single range + cells`)
}
return cellsSetInput(fv, token, sid, sname)
}},
"+cells-set-style": {"set_cell_range", cellsSetStyleInput},
"+cells-clear": {"clear_cell_range", cellsClearInput},
"+cells-replace": {"replace_data", replaceInput},
@@ -102,6 +112,11 @@ var batchOpDispatch = map[string]batchOpMapping{
// ─── 行列结构 (modify_sheet_structure, operation 区分) ──────────
"+dim-insert": {"modify_sheet_structure", dimInsertInput},
"+dim-delete": {"modify_sheet_structure", func(fv flagView, token, sid, sname string) (map[string]interface{}, error) {
// The --ranges plural form expands into its own atomic batch and
// cannot nest; sub-ops carry one range each.
if fv.Changed("ranges") {
return nil, sheetsValidationForFlag("ranges", `"ranges" is not supported inside +batch-update (it expands into its own atomic batch); call +dim-delete --ranges standalone, or give each sub-op a single "range"`)
}
return dimRangeOpInput(fv, token, sid, sname, "delete")
}},
"+dim-hide": {"modify_sheet_structure", func(fv flagView, token, sid, sname string) (map[string]interface{}, error) {
@@ -168,10 +183,6 @@ var batchOpDispatch = map[string]batchOpMapping{
}},
// ─── 对象族 CRUD (manage_*_object, operation 区分) ─────────────
"+chart-create": {"manage_chart_object", objCreateTranslate(chartSpec)},
"+chart-update": {"manage_chart_object", objUpdateTranslate(chartSpec)},
"+chart-delete": {"manage_chart_object", objDeleteTranslate(chartSpec)},
"+pivot-create": {"manage_pivot_table_object", objCreateTranslate(pivotSpec)},
"+pivot-update": {"manage_pivot_table_object", objUpdateTranslate(pivotSpec)},
"+pivot-delete": {"manage_pivot_table_object", objDeleteTranslate(pivotSpec)},
@@ -192,6 +203,13 @@ var batchOpDispatch = map[string]batchOpMapping{
"+sparkline-update": {"manage_sparkline_object", objUpdateTranslate(sparklineSpec)},
"+sparkline-delete": {"manage_sparkline_object", objDeleteTranslate(sparklineSpec)},
"+chart-create": {"manage_chart_object", objCreateTranslate(chartSpec)},
"+chart-update": {"manage_chart_object", objUpdateTranslate(chartSpec)},
"+chart-delete": {"manage_chart_object", objDeleteTranslate(chartSpec)},
"+chart-create-basic": {"manage_chart_object", chartCreateBasicInput},
"+chart-config-update": {"manage_chart_object", chartConfigUpdateInput},
"+chart-data-update": {"manage_chart_object", chartDataUpdateInput},
"+float-image-create": {"manage_float_image_object", func(fv flagView, token, sid, sname string) (map[string]interface{}, error) {
if err := rejectLocalImageInBatch(fv); err != nil {
return nil, err
@@ -210,8 +228,12 @@ var batchOpDispatch = map[string]batchOpMapping{
// allowedBatchShortcuts lists every shortcut accepted inside +batch-update,
// sorted, for the not-allowed error hint.
func allowedBatchShortcuts() []string {
out := make([]string, 0, len(batchOpDispatch))
for sc := range batchOpDispatch {
return allowedShortcuts(batchOpDispatch)
}
func allowedShortcuts(dispatch map[string]batchOpMapping) []string {
out := make([]string, 0, len(dispatch))
for sc := range dispatch {
out = append(out, sc)
}
sort.Strings(out)
@@ -297,10 +319,139 @@ func sheetMoveBatchInput(fv flagView, token, sheetID, sheetName string) (map[str
}, nil
}
// reservedSubOpKeys 是禁止用户在 sub-op input 里手填的 key —— 它们由
// +batch-update 顶层 --url/--token 统一提供excel_id / spreadsheet_token / url
// reservedSubOpKeys are redundant inside a sub-op: +batch-update supplies the
// spreadsheet locator once at the top level. The translator silently drops
// these keys so an otherwise valid operation is not rejected for harmless
// repetition.
var reservedSubOpKeys = []string{"excel_id", "spreadsheet_token", "url"}
// wrappedSubOpInputKeys are nested MCP-body container keys that must never
// appear at a sub-op input's top level — their presence means the caller
// pasted a shortcut's structured *output* (e.g. a {"cell_styles":{…}} block)
// where the flattened flag keys belong. None of the batch sub-op translators
// read input under these names, so rejecting them is safe.
var wrappedSubOpInputKeys = []string{"cell_styles", "cell_merges", "styles"}
// subOpKeyVocabulary returns the set of hyphen-canonical flag names a sub-op
// input may carry for `sc`: every non-system flag in flag-defs except the
// spreadsheet locators (reserved for the batch top level). Nil when the
// shortcut has no flag-defs entry (vocabulary checks are then skipped).
func subOpKeyVocabulary(sc string) map[string]bool {
defs, _ := loadFlagDefs()
spec, ok := defs[sc]
if !ok {
return nil
}
vocab := make(map[string]bool, len(spec.Flags))
for _, df := range spec.Flags {
if df.Kind == "system" || df.Name == "url" || df.Name == "spreadsheet-token" {
continue
}
vocab[df.Name] = true
}
return vocab
}
// camelToKebab converts a lowerCamelCase key to its kebab form
// (sheetName → sheet-name). Returns "" when the key carries no uppercase
// letter (nothing to convert).
func camelToKebab(key string) string {
if strings.ToLower(key) == key {
return ""
}
var b strings.Builder
for i, r := range key {
if r >= 'A' && r <= 'Z' {
if i > 0 {
b.WriteByte('-')
}
b.WriteRune(r + ('a' - 'A'))
continue
}
b.WriteRune(r)
}
return b.String()
}
// normalizeSubOpInputKeys validates every sub-op input key against the
// shortcut's flag vocabulary, rewriting habitual spellings in place and
// rejecting anything that matches nothing. Eval traces show unknown keys were
// previously ignored silently, which turned "wrong key" (size for width,
// camelCase sheetName, an invented styles object) into misleading
// "missing required flag" errors downstream — the single largest batch error
// cluster. Rewrites applied, in order:
//
// - underscore ↔ hyphen forms of a declared flag (already tolerated by
// mapFlagView — accepted here as-is)
// - lowerCamelCase → the declared flag (sheetName → sheet_name)
// - the command's intuitive-alias table (size → width/height on the resize
// pair) — the same commandFlagAliases the cobra path applies
// - "ranges" with a single-entry array unwraps onto "range"; a multi-entry
// array gets a split-into-sub-ops prescription instead
//
// Anything else errors with a did-you-mean. Returns a bare error; the caller
// wraps it with the operations[i] (<shortcut>) context and key contract.
func normalizeSubOpInputKeys(sc string, input map[string]interface{}) error {
vocab := subOpKeyVocabulary(sc)
if vocab == nil {
return nil
}
keys := make([]string, 0, len(input))
for k := range input {
keys = append(keys, k)
}
sort.Strings(keys)
aliases := commandFlagAliases[sc]
for _, k := range keys {
hv := strings.ReplaceAll(k, "_", "-")
if vocab[hv] {
continue
}
if kebab := camelToKebab(k); kebab != "" && vocab[kebab] {
input[strings.ReplaceAll(kebab, "-", "_")] = input[k]
delete(input, k)
continue
}
if target, ok := aliases[strings.ToLower(hv)]; ok && vocab[target] {
if _, taken := input[target]; !taken {
if _, taken := input[strings.ReplaceAll(target, "-", "_")]; !taken {
input[target] = input[k]
delete(input, k)
continue
}
}
}
if strings.ToLower(hv) == "ranges" && vocab["range"] && !vocab["ranges"] {
if arr, isArr := input[k].([]interface{}); isArr {
if len(arr) == 1 {
if s, isStr := arr[0].(string); isStr {
input["range"] = s
delete(input, k)
continue
}
}
return fmt.Errorf("%s takes a single \"range\" per sub-op, got %d entries in %q — split them into %d sub-ops (one per range)", sc, len(arr), k, len(arr)) //nolint:forbidigo // intermediate error; the batch dispatcher wraps it into a typed operations validation error
}
if s, isStr := input[k].(string); isStr {
input["range"] = s
delete(input, k)
continue
}
}
msg := fmt.Sprintf("unknown input key %q", k)
display := make([]string, 0, len(vocab))
for name := range vocab {
display = append(display, strings.ReplaceAll(name, "-", "_"))
}
sort.Strings(display)
if match := suggest.Closest(strings.ToLower(hv), display, 1); len(match) > 0 {
msg += fmt.Sprintf(" — did you mean %q?", match[0])
}
return fmt.Errorf("%s", msg) //nolint:forbidigo // intermediate error; the batch dispatcher wraps it into a typed operations validation error
}
return nil
}
// translateBatchOp 把一个 CLI 视角的 {shortcut, input} 翻成底层 MCP
// batch_update 的 {tool_name, input}。`index` 用于错误信息定位。input 用
// shortcut 的 CLI flag 名(连字符/下划线均可),经该 shortcut 的 standalone
@@ -311,9 +462,19 @@ var reservedSubOpKeys = []string{"excel_id", "spreadsheet_token", "url"}
// - shortcut 不在 dispatch 表拼写错read 操作;嵌套 fan-out wrapper
// - input 不是 object
// - input 里手填了 operation由 shortcut 名隐含,禁手填以防 mismatch
// - input 里手填了 excel_id / spreadsheet_token / url
// - input 顶层出现 cell_styles / cell_merges / styles误贴 MCP body 包裹结构)
// - 子操作的 translator 报错(如缺必填字段)
func translateBatchOp(raw interface{}, token string, index int) (map[string]interface{}, error) {
return translateBatchOpWithDispatch(raw, token, index, batchOpDispatch, "+batch-update")
}
func translateBatchOpWithDispatch(
raw interface{},
token string,
index int,
dispatch map[string]batchOpMapping,
command string,
) (map[string]interface{}, error) {
op, ok := raw.(map[string]interface{})
if !ok {
return nil, sheetsValidationForFlag("operations", "operations[%d] must be a JSON object", index)
@@ -327,17 +488,16 @@ func translateBatchOp(raw interface{}, token string, index int) (map[string]inte
if !ok || sc == "" {
return nil, sheetsValidationForFlag("operations", "operations[%d]: 'shortcut' must be a non-empty string (got %T)", index, scRaw)
}
mapping, ok := batchOpDispatch[sc]
mapping, ok := dispatch[sc]
if !ok {
// Inline the full allow-list: an agent that guessed a read op or a
// fan-out wrapper can pick the right shortcut immediately instead of
// spending a --print-schema round trip on the operations enum.
return nil, sheetsValidationForFlag(
"operations",
"operations[%d]: shortcut %q not allowed in +batch-update "+
"(read ops / fan-out wrappers like +batch-update / +cells-batch-set-style / +cells-batch-clear / +dropdown-{update,delete} are excluded)",
index, sc,
).WithHint("allowed shortcuts: %s", strings.Join(allowedBatchShortcuts(), ", "))
"operations[%d]: shortcut %q not allowed in %s",
index, sc, command,
).WithHint("allowed shortcuts: %s", strings.Join(allowedShortcuts(dispatch), ", "))
}
inputRaw, hasInput := op["input"]
var input map[string]interface{}
@@ -357,12 +517,29 @@ func translateBatchOp(raw interface{}, token string, index int) (map[string]inte
index, sc,
)
}
// 禁在 sub-op 重复填 spreadsheet 定位 —— 由 +batch-update 顶层 --url/--token 统一提供。
for _, k := range reservedSubOpKeys {
// Ignore repeated spreadsheet locators. The top-level +batch-update
// locator is authoritative, so these fields are harmlessly redundant and
// must never override it. Hyphen and underscore spellings both match.
for userKey := range input {
normalized := strings.ReplaceAll(userKey, "-", "_")
for _, k := range reservedSubOpKeys {
if normalized == k {
delete(input, userKey)
break
}
}
}
// Reject a "wrapped structure" sub-op input: agents copy a shortcut's nested
// output container (e.g. +workbook-create --styles' {"cell_styles":{…}}) into
// the op input, but the op input is the shortcut's own flags flattened into
// JSON keys, not that wrapper. Left unflagged this surfaces far downstream as
// an unrelated "at least one style flag is required" (helpers.go), which never
// points at the real mistake.
for _, k := range wrappedSubOpInputKeys {
if _, has := input[k]; has {
return nil, sheetsValidationForFlag(
"operations",
"operations[%d] (%s): do not pass input.%s — it is already set from +batch-update top-level --url / --token",
`operations[%d] (%s): op input is the shortcut's flags flattened as JSON keys (e.g. "background_color": "#EBF1F8"); do not wrap in %s`,
index, sc, k,
)
}
@@ -373,6 +550,16 @@ func translateBatchOp(raw interface{}, token string, index int) (map[string]inte
return nil, sheetsValidationForFlag("operations", "operations[%d] (%s): unknown top-level key %q (expected only 'shortcut' and 'input')", index, sc, k)
}
}
// Reject / rewrite off-vocabulary input keys BEFORE any value reads: an
// unknown key silently ignored surfaces later as a misleading
// "missing required flag" error (the top batch error cluster in evals).
if err := normalizeSubOpInputKeys(sc, input); err != nil {
verr := sheetsValidationForFlag("operations", "operations[%d] (%s): %v", index, sc, err)
if contract := subOpInputContract(sc); contract != "" {
verr = verr.WithHint("%s input keys: %s", sc, contract)
}
return nil, verr
}
fv := newMapFlagViewForCommand(sc, input)
// operations is skipped by parse-time schema validation, so type-check the
// sub-op's scalar fields here before the translator reads them via
@@ -410,30 +597,96 @@ func translateBatchOp(raw interface{}, token string, index int) (map[string]inte
// matrix, on the operations axis.
const maxBatchOperations = 100
// translateBatchOperations 翻译整个 ops 数组fail-fast遇错立即返回。
func translateBatchOperations(rawOps []interface{}, token string) ([]interface{}, error) {
// batchOpErrorDisplayLimit bounds how many per-op validation failures ride
// on one aggregated --operations error, mirroring the schema validator's
// display cap.
const batchOpErrorDisplayLimit = 5
type batchOpTranslationFailure struct {
Index int
Shortcut string
Err error
}
// collectBatchOperationTranslations translates every locally valid operation
// and preserves its original index. Validation failures are returned alongside
// the valid operations so +batch-update can either aggregate-and-reject
// (strict mode) or submit the valid subset (continue-on-error mode).
func collectBatchOperationTranslations(
rawOps []interface{},
token string,
) ([]interface{}, []int, []batchOpTranslationFailure, error) {
if len(rawOps) == 0 {
return nil, sheetsValidationForFlag("operations", "--operations must be a non-empty JSON array")
return nil, nil, nil, sheetsValidationForFlag("operations", "--operations must be a non-empty JSON array")
}
if len(rawOps) > maxBatchOperations {
batches := (len(rawOps) + maxBatchOperations - 1) / maxBatchOperations
return nil, sheetsValidationForFlag("operations", "--operations accepts at most %d entries; got %d", maxBatchOperations, len(rawOps)).
return nil, nil, nil, sheetsValidationForFlag("operations", "--operations accepts at most %d entries; got %d", maxBatchOperations, len(rawOps)).
WithHint("split the operations into %d separate +batch-update calls of at most %d entries each", batches, maxBatchOperations)
}
out := make([]interface{}, 0, len(rawOps))
originalIndexes := make([]int, 0, len(rawOps))
var totalCells int64
var failures []batchOpTranslationFailure
for i, raw := range rawOps {
translated, err := translateBatchOp(raw, token, i)
if err != nil {
return nil, err
shortcut := ""
if op, ok := raw.(map[string]interface{}); ok {
shortcut, _ = op["shortcut"].(string)
}
failures = append(failures, batchOpTranslationFailure{
Index: i,
Shortcut: shortcut,
Err: err,
})
continue
}
totalCells += translatedCellCount(translated)
if totalCells > maxStampMatrixCells {
return nil, sheetsValidationForFlag("operations",
return nil, nil, nil, sheetsValidationForFlag("operations",
"--operations materialize %d cells total, over the %d-cell safety cap; reduce the number or size of cell operations",
totalCells, maxStampMatrixCells)
}
out = append(out, translated)
originalIndexes = append(originalIndexes, i)
}
return out, originalIndexes, failures, nil
}
func batchOperationFailuresError(failures []batchOpTranslationFailure, total int) error {
switch len(failures) {
case 0:
return nil
case 1:
return failures[0].Err // single failure keeps the historical error byte-for-byte.
}
shown := failures
truncated := false
if len(shown) > batchOpErrorDisplayLimit {
shown = shown[:batchOpErrorDisplayLimit]
truncated = true
}
parts := make([]string, 0, len(shown))
for i, failure := range shown {
parts = append(parts, fmt.Sprintf("%d) %s", i+1, failure.Err.Error()))
}
msg := fmt.Sprintf("%d of %d operations failed validation: %s", len(failures), total, strings.Join(parts, "; "))
if truncated {
msg += fmt.Sprintf("; (%d more not shown — fix these first)", len(failures)-batchOpErrorDisplayLimit)
}
return sheetsValidationForFlag("operations", "%s", msg).WithCause(failures[0].Err)
}
// translateBatchOperations is the strict translation contract used by the
// default atomic mode and existing translator tests.
func translateBatchOperations(rawOps []interface{}, token string) ([]interface{}, error) {
out, _, failures, err := collectBatchOperationTranslations(rawOps, token)
if err != nil {
return nil, err
}
if err := batchOperationFailuresError(failures, len(rawOps)); err != nil {
return nil, err
}
return out, nil
}

View File

@@ -0,0 +1,113 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"strings"
"testing"
)
// TestCellsSetWrites pins the --writes plural form: scattered (cross-sheet)
// regions fan into ONE atomic batch_update, each item self-carrying its
// sheet selector (no top-level fallback — same convention as +batch-update
// sub-ops and +styles-put items), with per-item errors aggregated.
func TestCellsSetWrites(t *testing.T) {
t.Parallel()
writes := func(items string, extra ...string) (string, string, error) {
args := append([]string{
"--url", testURL, "--dry-run", "--writes", items,
}, extra...)
return runShortcutCapturingErr(t, CellsSet, args)
}
t.Run("cross-sheet items expand into one batch", func(t *testing.T) {
t.Parallel()
stdout, _, err := writes(`[
{"sheet_name":"明细","range":"D5","cells":[[{"formula":"=IFERROR(C5/B5,0)"}]]},
{"sheet_name":"汇总","range":"B3","cells":[[{"formula":"=SUM(C:C)"}]]}
]`)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
for _, want := range []string{"batch_update", "明细", "汇总", "IFERROR"} {
if !strings.Contains(stdout, want) {
t.Fatalf("dry-run body missing %q: %s", want, stdout[:min(len(stdout), 400)])
}
}
})
t.Run("item without sheet selector errors", func(t *testing.T) {
t.Parallel()
_, _, err := writes(`[{"range":"A1","cells":[[{"value":"x"}]]}]`)
requireValidation(t, err, "sheet-id or --sheet-name")
})
t.Run("top-level sheet selector rejected with prescription", func(t *testing.T) {
t.Parallel()
_, _, err := writes(`[{"sheet_name":"S1","range":"A1","cells":[[{"value":"x"}]]}]`,
"--sheet-name", "S1")
requireValidation(t, err, "put sheet_name (or sheet_id) inside each writes item")
})
t.Run("writes and range are mutually exclusive", func(t *testing.T) {
t.Parallel()
_, _, err := writes(`[{"sheet_name":"S1","range":"A1","cells":[[{"value":"x"}]]}]`,
"--range", "A1")
requireValidation(t, err, "mutually exclusive")
})
t.Run("per-item errors aggregate", func(t *testing.T) {
t.Parallel()
// Both items pass the --writes schema (range+cells present) but fail
// deeper: item 0 a matrix mismatch, item 1 a missing sheet selector.
_, _, err := writes(`[
{"sheet_name":"S1","range":"A1:B2","cells":[[{"value":"x"}]]},
{"range":"C1","cells":[[{"value":"y"}]]}
]`)
ve := requireValidation(t, err, "--writes has 2 issues")
for _, want := range []string{"--writes[0]", "--writes[1]", "sheet-name"} {
if !strings.Contains(ve.Message, want) {
t.Fatalf("message %q missing %q", ve.Message, want)
}
}
})
t.Run("item keys go through the vocabulary layer", func(t *testing.T) {
t.Parallel()
stdout, _, err := writes(`[{"sheetName":"S1","range":"A1","cells":[[{"value":"x"}]]}]`)
if err != nil {
t.Fatalf("camelCase sheetName must normalize: %v", err)
}
if !strings.Contains(stdout, "S1") {
t.Fatalf("normalized item missing sheet: %s", stdout[:min(len(stdout), 300)])
}
})
t.Run("cannot nest inside batch-update", func(t *testing.T) {
t.Parallel()
_, err := translateBatchOp(subOp("+cells-set", map[string]interface{}{
"writes": []interface{}{map[string]interface{}{
"sheet_name": "S1", "range": "A1", "cells": []interface{}{[]interface{}{map[string]interface{}{"value": "x"}}},
}},
}), testToken, 0)
requireValidation(t, err, "not supported inside +batch-update")
})
t.Run("styles flag gets the layering prescription", func(t *testing.T) {
t.Parallel()
// Ergonomics (FlagErrorFunc hints) mount via the registry, not the
// bare shortcut var — mirror the real CLI wiring.
sc := shortcutFromRegistry(t, "+cells-set")
_, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL, "--dry-run",
"--writes", `[{"sheet_name":"S1","range":"A1","cells":[[{"value":"x"}]]}]`,
"--styles", `{"styles":[]}`,
})
ve := requireValidation(t, err, "unknown flag")
if !strings.Contains(ve.Hint, "+styles-put") || !strings.Contains(ve.Hint, "cell_styles") {
t.Fatalf("want the styles-put layering hint, got hint=%q", ve.Hint)
}
})
}

View File

@@ -0,0 +1,150 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"fmt"
"sort"
"strings"
"github.com/larksuite/cli/shortcuts/common"
"github.com/spf13/cobra"
)
// ─── +chart-create --print-example ─────────────────────────────────────
//
// chart-create's --properties schema is ~1,750 pretty-printed lines; eval
// traces show agents paging through the full --print-schema dump for every
// chart (25 round trips in one 35-task batch) and still missing deep
// required fields. A ready-to-edit minimal template per chart type answers
// the actual question ("what does a valid payload look like") in one local
// call. Wired through PostMount, same pattern as +csv-put's flag-group
// tweaks — no framework change.
//
// Templates mirror the canonical examples in the lark-sheets-chart
// reference (sheet-skill-spec canonical-spec/references/lark_sheet_chart):
// inline headerMode with refs covering the header row, 1-based indices,
// quoted sheet prefix in refs.
var chartExampleTemplates = map[string]string{
"column": chartSimpleExample("column"),
"bar": chartSimpleExample("bar"),
"line": chartSimpleExample("line"),
"area": chartSimpleExample("area"),
"radar": chartSimpleExample("radar"),
"scatter": `{
"position": {"row": 1, "col": "F"},
"size": {"width": 600, "height": 400},
"snapshot": {
"title": {"text": "图表标题"},
"plotArea": {"plot": {"type": "scatter"}},
"data": {
"refs": [{"value": "'Sheet1'!A1:B20"}],
"dim1": {"serie": {"index": 1}},
"dim2": {"series": [{"index": 2}]}
}
}
}`,
"pie": `{
"position": {"row": 1, "col": "F"},
"size": {"width": 600, "height": 450},
"snapshot": {
"title": {"text": "占比标题"},
"plotArea": {"plot": {
"type": "pie",
"series": [{
"index": 1,
"sectors": {"sector": [{"index": 1, "offsetRadius": 0.05}]}
}]
}},
"data": {
"refs": [{"value": "'Sheet1'!A1:B11"}],
"dim1": {"serie": {"index": 1, "aggregate": true}},
"dim2": {"series": [{"index": 2, "aggregateType": "sum"}]}
}
}
}`,
"combo": `{
"position": {"row": 1, "col": "F"},
"size": {"width": 700, "height": 400},
"snapshot": {
"title": {"text": "柱线组合"},
"plotArea": {"plot": {
"type": "combo",
"series": [
{"index": 2, "comboType": "column"},
{"index": 3, "comboType": "line"}
]
}},
"data": {
"refs": [{"value": "'Sheet1'!A1:C13"}],
"dim1": {"serie": {"index": 1}},
"dim2": {"series": [{"index": 2}, {"index": 3}]}
}
}
}`,
}
// chartSimpleExample renders the shared minimal shape for plot types that
// need nothing beyond plot.type (column / bar / line / area / radar).
func chartSimpleExample(typ string) string {
return fmt.Sprintf(`{
"position": {"row": 1, "col": "F"},
"size": {"width": 600, "height": 400},
"snapshot": {
"title": {"text": "图表标题"},
"plotArea": {"plot": {"type": %q}},
"data": {
"refs": [{"value": "'Sheet1'!A1:C10"}],
"dim1": {"serie": {"index": 1}},
"dim2": {"series": [{"index": 2}, {"index": 3}]}
}
}
}`, typ)
}
func chartExampleTypes() []string {
types := make([]string, 0, len(chartExampleTemplates))
for t := range chartExampleTemplates {
types = append(types, t)
}
sort.Strings(types)
return types
}
// withChartPrintExample wraps +chart-create's PostMount so the command grows
// a --print-example flag that short-circuits execution and prints a minimal
// ready-to-edit --properties template — purely local, no identity or
// network. --properties' cobra-level required annotation is relaxed (the
// input builder still enforces it on the real path, same trick as
// +csv-put's --csv).
func withChartPrintExample(prev func(cmd *cobra.Command)) func(cmd *cobra.Command) {
return func(cmd *cobra.Command) {
if prev != nil {
prev(cmd)
}
cmd.Flags().String("print-example", "",
"Print a minimal ready-to-edit --properties template for a chart type ("+strings.Join(chartExampleTypes(), "|")+") and exit")
// Only --properties carries a cobra-level required annotation (the
// locator flags are xor pairs, enforced later); the input builder
// still errors "--properties is required" on the real path.
if fl := cmd.Flags().Lookup("properties"); fl != nil {
delete(fl.Annotations, cobra.BashCompOneRequiredFlag)
}
prevRunE := cmd.RunE
cmd.RunE = func(c *cobra.Command, args []string) error {
typ, _ := c.Flags().GetString("print-example")
if typ == "" {
return prevRunE(c, args)
}
tmpl, ok := chartExampleTemplates[typ]
if !ok {
return common.ValidationErrorf("no example for chart type %q; available: %s",
typ, strings.Join(chartExampleTypes(), ", ")).WithParam("--print-example")
}
fmt.Fprintln(c.OutOrStdout(), tmpl)
return nil
}
}
}

View File

@@ -0,0 +1,63 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"bytes"
"encoding/json"
"strings"
"testing"
)
// TestChartPrintExample pins the --print-example contract: a known type
// prints its template and skips execution entirely; an unknown type lists
// the available ones.
func TestChartPrintExample(t *testing.T) {
t.Parallel()
t.Run("prints template without locator flags", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+chart-create")
parent, _, _, _ := newTestRig(t, sc)
var buf bytes.Buffer
parent.SetOut(&buf) // --print-example writes via cobra's OutOrStdout
parent.SetArgs([]string{sc.Command, "--print-example", "pie"})
if err := parent.Execute(); err != nil {
t.Fatalf("print-example should run standalone, got: %v", err)
}
if !strings.Contains(buf.String(), `"sectors"`) {
t.Errorf("pie template should carry sectors, got %q", buf.String())
}
})
t.Run("unknown type lists available", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+chart-create")
_, _, err := runShortcutCapturingErr(t, sc, []string{"--print-example", "donut"})
ve := requireValidation(t, err, `no example for chart type "donut"`)
if !strings.Contains(ve.Message, "pie") {
t.Errorf("message should list available types, got %q", ve.Message)
}
})
}
// TestChartExampleTemplates_ValidateAgainstSchema drift-guards every
// template against the embedded chart-create properties schema — a template
// the CLI itself would reject is worse than none.
func TestChartExampleTemplates_ValidateAgainstSchema(t *testing.T) {
t.Parallel()
for typ, tmpl := range chartExampleTemplates {
t.Run(typ, func(t *testing.T) {
t.Parallel()
var v interface{}
if err := json.Unmarshal([]byte(tmpl), &v); err != nil {
t.Fatalf("template is not valid JSON: %v", err)
}
fv := newMapFlagViewForCommand("+chart-create", map[string]interface{}{"properties": v})
if err := validateValueAgainstSchema(fv, "properties", v); err != nil {
t.Errorf("template rejected by embedded schema: %v", err)
}
})
}
}

View File

@@ -22,10 +22,8 @@ func newCSVGuardRuntime(csvVal string) *common.RuntimeContext {
return &common.RuntimeContext{Cmd: cmd}
}
// TestGuardCSVValueIsNotFilePath verifies the guard flags a bare --csv value
// only when it names a real file (a forgotten @), while leaving genuine inline
// content alone — including the case the old name-shape heuristic got wrong:
// prose that merely ends in or mentions a filename.
// TestGuardCSVValueIsNotFilePath covers the existing-file tier: a bare --csv
// value naming a real file is a forgotten "@", and the fix is inlined.
func TestGuardCSVValueIsNotFilePath(t *testing.T) {
dir := t.TempDir()
cmdutil.TestChdir(t, dir)
@@ -33,7 +31,6 @@ func TestGuardCSVValueIsNotFilePath(t *testing.T) {
t.Fatal(err)
}
// Bare value naming an existing file → guarded with a fix-it hint.
err := guardCSVValueIsNotFilePath(newCSVGuardRuntime("data.csv"))
ve := requireValidation(t, err, "existing file")
if !strings.Contains(ve.Message, "@data.csv") {
@@ -42,14 +39,78 @@ func TestGuardCSVValueIsNotFilePath(t *testing.T) {
if ve.Param != "--csv" {
t.Errorf("param = %q, want --csv", ve.Param)
}
}
// TestGuardCSVValueIsNotFilePath_MissingButPathShaped covers the second tier.
// A path that doesn't resolve used to pass through and be written into the
// cell verbatim — a wrong value with a success exit code. The common source is
// an absolute path: `@` rejects those, so the caller drops the `@` and retries.
// Since the file can't be read from cwd, the prescription is stdin.
func TestGuardCSVValueIsNotFilePath_MissingButPathShaped(t *testing.T) {
dir := t.TempDir()
cmdutil.TestChdir(t, dir)
// Content that is not a real file must pass through unchanged.
for _, v := range []string{
"改完记得更新config.json", // prose ending in a filename — not a real file
"remember to update data.csv", // mentions the real file but isn't its name
"nope.csv", // relative path from another working directory
"./missing.csv", // explicit relative prefix
"../sibling/x.tsv", // parent-relative
"/tmp/nope.csv", // absolute — the `@`-rejected case
"~/data.tsv", // home-relative
"/var/tmp/export", // no extension, but an unmistakable path prefix
"C:/Users/me/a.csv", // windows-style, still ASCII path shape
} {
err := guardCSVValueIsNotFilePath(newCSVGuardRuntime(v))
ve := requireValidation(t, err, "looks like a file path")
if !strings.Contains(ve.Hint, "--csv @") || !strings.Contains(ve.Hint, "--csv - <") {
t.Errorf("value %q: hint should offer both @file and stdin, got: %q", v, ve.Hint)
}
if !strings.Contains(ve.Hint, v) {
t.Errorf("value %q: hint should echo the path in the stdin example, got: %q", v, ve.Hint)
}
}
}
// TestGuardCSVValueIsNotFilePath_SkipsResolvedInput pins the origin rule that
// makes the shape heuristic safe: a value that arrived via @file / stdin is
// never inspected, however path-shaped its content — so the hint's promise
// that stdin writes such text verbatim actually holds, and a correct
// `--csv @file` invocation can't be re-rejected for its content.
func TestGuardCSVValueIsNotFilePath_SkipsResolvedInput(t *testing.T) {
dir := t.TempDir()
cmdutil.TestChdir(t, dir)
if err := os.WriteFile("data.csv", []byte("a,b\n1,2\n"), 0644); err != nil {
t.Fatal(err)
}
for _, v := range []string{
"nope.csv", // path-shaped, missing — rejected when inline
"data.csv", // names an existing file — rejected when inline
} {
rctx := newCSVGuardRuntime(v)
common.TestMarkInputResolved(rctx, "csv")
if err := guardCSVValueIsNotFilePath(rctx); err != nil {
t.Errorf("resolved value %q must skip the guard, got: %v", v, err)
}
}
}
// TestGuardCSVValueIsNotFilePath_PassesThrough pins what must still reach the
// sheet untouched. The prose cases are why the guard checks a narrow shape
// instead of "contains a filename": an earlier name-shape heuristic rejected
// them. "N/A" and "README.md" pin the two narrowing rules — a slash alone is
// not a path, and a filename alone is not a CSV path.
func TestGuardCSVValueIsNotFilePath_PassesThrough(t *testing.T) {
dir := t.TempDir()
cmdutil.TestChdir(t, dir)
for _, v := range []string{
"改完记得更新config.json", // CJK prose ending in a filename
"remember to update data.csv", // prose mentioning a file
"a,b\n1,2", // multi-cell CSV
"hello world",
"nope.csv", // path-shaped but no such file
"N/A", // slash, but no CSV extension and no path prefix
"README.md", // filename shape, not a CSV one
"report 2026.csv", // has a space: content, not a path
"",
} {
if err := guardCSVValueIsNotFilePath(newCSVGuardRuntime(v)); err != nil {

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@@ -445,6 +445,175 @@ func TestExecute_BatchUpdate_Translated(t *testing.T) {
}
}
func TestExecute_BatchChartCreate_ContinueOnErrorKeepsLocallyValidOperations(t *testing.T) {
t.Parallel()
stub := toolOutputStub(testToken, "write", `{
"total":1,
"succeeded":1,
"failed":0,
"results":[{"index":0,"tool_name":"manage_chart_object","success":true}]
}`)
out, err := runShortcutWithStubs(t, BatchChartCreate, []string{
"--url", testURL,
"--operations", `[
{"sheet-id":"sh1","chart-type":"donut","data-range":"A1:C10"},
{"sheet-id":"sh1","chart-type":"line","data-range":"E1:G10","title":"Trend"}
]`,
"--continue-on-error",
}, stub)
if err != nil {
t.Fatalf("execute failed: %v\nout=%s", err, out)
}
input := decodeToolInput(t, decodeRawEnvelopeBody(t, stub.CapturedBody), "batch_update")
ops, _ := input["operations"].([]interface{})
if len(ops) != 1 {
t.Fatalf("server should receive only the locally valid operation, got %d", len(ops))
}
for _, want := range []string{
`"total": 2`,
`"succeeded": 1`,
`"failed": 1`,
`"index": 0`,
`"index": 1`,
`"stage": "cli_validation"`,
} {
if !strings.Contains(out, want) {
t.Errorf("merged partial result should contain %q, got:\n%s", want, out)
}
}
}
func TestExecute_BatchChartCreate_StrictModeRejectsBeforeWrite(t *testing.T) {
t.Parallel()
_, _, err := runShortcutCapturingErr(t, BatchChartCreate, []string{
"--url", testURL,
"--operations", `[
{"sheet-id":"sh1","chart-type":"donut","data-range":"A1:C10"},
{"sheet-id":"sh1","chart-type":"line","data-range":"E1:G10","title":"Trend"}
]`,
"--continue-on-error=false",
})
requireValidation(t, err, "invalid value \"donut\" for --chart-type")
}
func TestExecute_BatchChartUpdate_PreflightsSnapshots(t *testing.T) {
t.Parallel()
read := toolOutputStub(testToken, "read", `{
"sheets":[{
"sheet_id":"shtSubA",
"charts":[{
"chart_id":"chart-1",
"details":{"snapshot":{
"title":{"text":"Old"},
"plotArea":{"plot":{"type":"line"}}
}}
}]
}]
}`)
write := toolOutputStub(testToken, "write", `{
"total":1,
"succeeded":1,
"failed":0,
"results":[{"index":0,"tool_name":"manage_chart_object","success":true}]
}`)
out, err := runShortcutWithStubs(t, BatchChartUpdate, []string{
"--url", testURL,
"--operations", `[{
"shortcut":"+chart-config-update",
"input":{"sheet-id":"shtSubA","chart-id":"chart-1","title":"New"}
}]`,
}, read, write)
if err != nil {
t.Fatalf("execute failed: %v\nout=%s", err, out)
}
input := decodeToolInput(t, decodeRawEnvelopeBody(t, write.CapturedBody), "batch_update")
ops := input["operations"].([]interface{})
chartInput := ops[0].(map[string]interface{})["input"].(map[string]interface{})
snapshot := chartDryRunSnapshot(t, chartInput)
if snapshot["title"].(map[string]interface{})["text"] != "New" {
t.Fatalf("batch partial title = %#v", snapshot["title"])
}
}
func TestExecute_BatchUpdate_MixesCellsAndSemanticChartUpdate(t *testing.T) {
t.Parallel()
read := toolOutputStub(testToken, "read", `{
"sheets":[{
"sheet_id":"shtSubA",
"charts":[{
"chart_id":"chart-1",
"details":{"snapshot":{
"title":{"text":"Old"},
"plotArea":{"plot":{"type":"line"}}
}}
}]
}]
}`)
write := toolOutputStub(testToken, "write", `{
"total":2,
"succeeded":2,
"failed":0,
"results":[
{"index":0,"tool_name":"set_cell_range","success":true},
{"index":1,"tool_name":"manage_chart_object","success":true}
]
}`)
out, err := runShortcutWithStubs(t, BatchUpdate, []string{
"--url", testURL,
"--operations", `[
{"shortcut":"+cells-set","input":{"sheet-id":"shtSubA","range":"A1","cells":[[{"value":1}]]}},
{"shortcut":"+chart-config-update","input":{"sheet-id":"shtSubA","chart-id":"chart-1","title":"New"}}
]`,
"--yes",
}, read, write)
if err != nil {
t.Fatalf("execute failed: %v\nout=%s", err, out)
}
input := decodeToolInput(t, decodeRawEnvelopeBody(t, write.CapturedBody), "batch_update")
ops := input["operations"].([]interface{})
if len(ops) != 2 || ops[0].(map[string]interface{})["tool_name"] != "set_cell_range" {
t.Fatalf("mixed operations = %#v", ops)
}
chartInput := ops[1].(map[string]interface{})["input"].(map[string]interface{})
snapshot := chartDryRunSnapshot(t, chartInput)
if snapshot["title"].(map[string]interface{})["text"] != "New" {
t.Fatalf("generic batch partial title = %#v", snapshot["title"])
}
}
func TestExecute_BatchUpdate_CompactsChartCreateSnapshot(t *testing.T) {
t.Parallel()
write := toolOutputStub(testToken, "write", `{
"total":1,
"succeeded":1,
"failed":0,
"results":[{
"index":0,
"tool_name":"manage_chart_object",
"success":true,
"data":{"chart_id":"chart-1","snapshot":{"title":{"text":"Large"}}}
}]
}`)
out, err := runShortcutWithStubs(t, BatchUpdate, []string{
"--url", testURL,
"--operations", `[{
"shortcut":"+chart-create-basic",
"input":{"sheet-id":"shtSubA","chart-type":"line","data-range":"A1:C10"}
}]`,
"--yes",
}, write)
if err != nil {
t.Fatalf("execute failed: %v\nout=%s", err, out)
}
if strings.Contains(out, `"snapshot"`) {
t.Fatalf("generic batch create must omit the full chart snapshot: %s", out)
}
if !strings.Contains(out, `"chart_id": "chart-1"`) {
t.Fatalf("generic batch create must retain chart_id: %s", out)
}
}
// TestExecute_BatchUpdate_ContinueOnErrorPrecedence locks the flag-vs-envelope
// precedence: an explicit --continue-on-error=false must keep the strict
// transaction even when the --operations envelope carries continue_on_error:true,
@@ -685,6 +854,107 @@ func TestExecute_ChartCreate(t *testing.T) {
}
}
func TestExecute_ChartConfigUpdate_ReadsSnapshotAndWritesPartialPatch(t *testing.T) {
t.Parallel()
read := toolOutputStub(testToken, "read", `{
"sheets":[{
"sheet_id":"shtSubA",
"charts":[{
"chart_id":"chart-1",
"details":{"snapshot":{
"title":{"text":"Old"},
"plotArea":{
"axes":[
{"type":"x","position":"bottom","title":{"text":"Month"}},
{"type":"y","position":"left","title":{"text":"Amount"}}
],
"plot":{"type":"line","extra":{"smooth":false}}
},
"data":{"direction":"column"}
}}
}]
}]
}`)
write := toolOutputStub(testToken, "write", `{"chart_id":"chart-1"}`)
out, err := runShortcutWithStubs(t, ChartConfigUpdate, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-id", "chart-1",
"--title", "New",
"--y-axis-title", "Revenue",
}, read, write)
if err != nil {
t.Fatalf("execute failed: %v\nout=%s", err, out)
}
readInput := decodeToolInput(t, decodeRawEnvelopeBody(t, read.CapturedBody), "get_chart_objects")
if readInput["chart_id"] != "chart-1" {
t.Fatalf("read chart_id = %#v", readInput["chart_id"])
}
writeInput := decodeToolInput(t, decodeRawEnvelopeBody(t, write.CapturedBody), "manage_chart_object")
snapshot := chartDryRunSnapshot(t, writeInput)
if snapshot["title"].(map[string]interface{})["text"] != "New" {
t.Fatalf("partial title = %#v", snapshot["title"])
}
axes := snapshot["plotArea"].(map[string]interface{})["axes"].([]interface{})
if len(axes) != 2 || axes[0].(map[string]interface{})["title"].(map[string]interface{})["text"] != "Month" ||
axes[1].(map[string]interface{})["title"].(map[string]interface{})["text"] != "Revenue" {
t.Fatalf("partial axes = %#v", axes)
}
data := decodeEnvelopeData(t, out)
viewModel := data["viewModel"].(map[string]interface{})
if _, ok := viewModel["data"]; ok {
t.Fatal("config shortcut output viewModel must not include data")
}
}
func TestExecute_ChartDataUpdate_ReadsSnapshotAndReturnsData(t *testing.T) {
t.Parallel()
read := toolOutputStub(testToken, "read", `{
"sheets":[{
"sheet_id":"shtSubA",
"charts":[{
"chart_id":"chart-1",
"details":{"snapshot":{
"plotArea":{"plot":{"type":"line"}},
"data":{
"isStaticData":false,
"direction":"column",
"refs":[{"value":"A1:C10"}],
"dim1":{"serie":{"index":1}},
"dim2":{"series":[{"index":2},{"index":3}]}
}
}}
}]
}]
}`)
write := toolOutputStub(testToken, "write", `{"chart_id":"chart-1"}`)
out, err := runShortcutWithStubs(t, ChartDataUpdate, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-id", "chart-1",
"--data-range", "A1:D10",
"--dim1-index", "1",
"--dim2-indexes", "2,4",
}, read, write)
if err != nil {
t.Fatalf("execute failed: %v\nout=%s", err, out)
}
writeInput := decodeToolInput(t, decodeRawEnvelopeBody(t, write.CapturedBody), "manage_chart_object")
patchData := chartDryRunSnapshot(t, writeInput)["data"].(map[string]interface{})
series := patchData["dim2"].(map[string]interface{})["series"].([]interface{})
if len(series) != 2 || series[0].(map[string]interface{})["index"] != float64(2) ||
series[1].(map[string]interface{})["index"] != float64(4) {
t.Fatalf("partial data series = %#v", series)
}
data := decodeEnvelopeData(t, out)
returned := data["data"].(map[string]interface{})
if returned["direction"] != "column" {
t.Fatalf("returned data = %#v", returned)
}
}
// TestExecute_SheetCreate hits the workbook write path with all four
// optional flags so the input builder + callTool wiring is exercised.
func TestExecute_SheetCreate(t *testing.T) {

View File

@@ -11,12 +11,32 @@ package sheets
// with `go generate ./shortcuts/sheets/...` after data/flag-defs.json
// changes.
var flagDefs = map[string]commandDef{
"+batch-chart-create": {
Risk: "write",
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "operations", Kind: "own", Type: "string", Required: "required", Desc: "Chart creation operations as JSON; put each target sheet selector and `+chart-create-basic` flag directly on the item, without `shortcut` or `input`. The CLI dispatches every item through `+chart-create-basic` internally. Partial failure is enabled by default: successful charts stay applied and only failed items should be retried", Input: []string{"file", "stdin"}},
{Name: "continue-on-error", Kind: "own", Type: "bool", Required: "optional", Desc: "Continue after an individual chart fails; default true", Default: "true"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional", Desc: "Print the internal MCP request template with no network side effects; tool_name / operation / basic_chart in the output are for inspection only and must not be copied back into --operations"},
},
},
"+batch-chart-update": {
Risk: "write",
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "operations", Kind: "own", Type: "string", Required: "required", Desc: "Chart update operations as JSON; every item uses `+chart-config-update` or `+chart-data-update`, with that command's flags and target sheet selector in input. The CLI reads each current chart snapshot before building partial properties; partial failure is enabled by default", Input: []string{"file", "stdin"}},
{Name: "continue-on-error", Kind: "own", Type: "bool", Required: "optional", Desc: "Continue after an individual chart fails; default true", Default: "true"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional", Desc: "Print the batch update request template and snapshot preflight note with no network side effects"},
},
},
"+batch-update": {
Risk: "high-risk-write",
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet locator (independent from per-operation sheet locator)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet locator (independent from per-operation sheet locator)"},
{Name: "operations", Kind: "own", Type: "string", Required: "required", Desc: "JSON array: [{\"shortcut\":\"+xxx-yyy\",\"input\":{...}}, ...]. shortcut uses CLI names; input is that shortcut's flag set — it includes the per-operation sheet locator (sheet_id or sheet_name) but not the spreadsheet token/url (pass that once at the top level via --url/--spreadsheet-token; +batch-update has no top-level --sheet-id). input keys are the shortcut's flags flattened into JSON (e.g. \"range\":\"A11:B12\"), not another nested layer. For basic flags use lark-cli sheets <shortcut> --help; for composite JSON flags use --print-schema --flag-name <flag>. Do not pass an explicit operation field. Strict transaction by default, pass --continue-on-error for soft batch; no nesting; executed serially.", Input: []string{"file", "stdin"}},
{Name: "operations", Kind: "own", Type: "string", Required: "required", Desc: "JSON array: [{\"shortcut\":\"+xxx-yyy\",\"input\":{...}}, ...]. shortcut uses CLI names; input is that shortcut's flattened flag set, including sheet_id or sheet_name, not an MCP body. Pass the spreadsheet locator once at the top level; repeated excel_id / spreadsheet_token / url fields inside input are ignored and never override the top-level locator. Use --help for basic flags and --print-schema --flag-name <flag> for composite JSON flags. Do not pass operation explicitly. Chart sub-operations are supported, but prefer +batch-chart-create / +batch-chart-update for chart-only work. Fail-fast by default: the first failure aborts the remaining operations and already-applied sub-operations are NOT rolled back (on \"N succeeded, M failed\" resend only the failed tail, not the whole batch); pass --continue-on-error to keep going past failures; no nesting; executed serially.", Input: []string{"file", "stdin"}},
{Name: "continue-on-error", Kind: "own", Type: "bool", Required: "optional", Desc: "Continue with remaining operations when a sub-operation fails; default false (abort on first failure)"},
{Name: "yes", Kind: "system", Type: "bool", Required: "required", Desc: "Confirm high-risk write (exit code 10 without this flag)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional", Desc: "Print the request template for each sub-operation; no network side effects"},
@@ -50,7 +70,7 @@ var flagDefs = map[string]commandDef{
{Name: "vertical-alignment", Kind: "own", Type: "string", Required: "optional", Desc: "Vertical alignment", Enum: []string{"top", "middle", "bottom"}},
{Name: "word-wrap", Kind: "own", Type: "string", Required: "optional", Desc: "Word-wrap strategy", Enum: []string{"overflow", "auto-wrap", "word-clip"}},
{Name: "number-format", Kind: "own", Type: "string", Required: "optional", Desc: "Number format pattern (e.g. text `@`, number `0.00`, currency `$#,##0.00`, date `mm/dd/yyyy`)"},
{Name: "border-styles", Kind: "own", Type: "string", Required: "optional", Desc: "Border config JSON (same shape as in +cells-set-style)", Input: []string{"file", "stdin"}},
{Name: "border-styles", Kind: "own", Type: "string", Required: "optional", Desc: "Border config JSON (same shape as in +cells-set-style): `{ top|bottom|left|right|all: {style,weight,color} }`; style = solid|dashed|dotted|double|none, weight = thin|medium|thick (string), color = hex like #000000", Input: []string{"file", "stdin"}},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
},
@@ -59,8 +79,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Range to clear (A1 notation)"},
{Name: "scope", Kind: "own", Type: "string", Required: "optional", Desc: "Clear scope: `content` (default, values only) / `formats` (formats only) / `all` (values and formats)", Default: "content", Enum: []string{"content", "formats", "all"}},
{Name: "yes", Kind: "system", Type: "bool", Required: "required", Desc: "Confirm destructive write (exit code 10 without this flag); clear is irreversible"},
@@ -72,11 +92,12 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "A1 range, e.g. `A1:F10` (no sheet prefix — use `--sheet-id` / `--sheet-name` to select the sheet)"},
{Name: "include", Kind: "own", Type: "string_slice", Required: "optional", Desc: "Comma-separated info categories to include", Enum: []string{"value", "formula", "style", "comment", "data_validation"}},
{Name: "max-chars", Kind: "own", Type: "int", Required: "optional", Desc: "Max output chars per call; default 500000 (safety cap). Large reads are usually better redirected to a file; only lower it (e.g. 25000) when you want results inline without triggering file offload, paging via has_more", Default: "500000"},
{Name: "include", Kind: "own", Type: "string_slice", Required: "optional", Desc: "Comma-separated info categories to include. `truncation` additionally estimates whether each cell's content is clipped (by row height / col width / font size / wrap) and returns `isRowTruncated` / `isColTruncated` (extra compute; enable only for layout checks or before adjusting row heights / column widths)", Enum: []string{"value", "formula", "style", "comment", "data_validation", "truncation"}},
{Name: "max-chars", Kind: "own", Type: "int", Required: "optional", Desc: "Max output chars per call; default 500000 (safety cap). For a full untruncated read, use --output-path to dump to a file (auto-unlimited); only lower it (e.g. 25000) when you want results inline without a file, paging via has_more.", Default: "500000"},
{Name: "output-path", Kind: "own", Type: "string", Required: "optional", Desc: "Write the full read result to a local path (e.g. `./out.json`); the file holds the data payload as JSON while stdout returns only a small confirmation (output_path, byte count). **When set, the char cap defaults to unlimited** (overriding the --max-chars default), so a large sheet can be dumped in full for later analysis without stdout being truncated by max_chars. Omit it to print to stdout as usual."},
{Name: "skip-hidden", Kind: "own", Type: "bool", Required: "optional", Desc: "Skip hidden rows and columns; default `false`"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -86,8 +107,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Range to merge / unmerge (A1 notation)"},
{Name: "merge-type", Kind: "own", Type: "string", Required: "optional", Desc: "Merge direction (`+cells-merge` only)", Default: "all", Enum: []string{"all", "rows", "columns"}},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -98,8 +119,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "find", Kind: "own", Type: "string", Required: "required", Desc: "Text to find for replacement"},
{Name: "replacement", Kind: "own", Type: "string", Required: "required", Desc: "Replacement text; pass empty string `\"\"` to delete matched content"},
{Name: "range", Kind: "own", Type: "string", Required: "optional", Desc: "Replace range (A1 notation); whole sheet when omitted"},
@@ -115,8 +136,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "find", Kind: "own", Type: "string", Required: "required", Desc: "Text to find (interpreted as regex when `--regex` is set)"},
{Name: "range", Kind: "own", Type: "string", Required: "optional", Desc: "Search range (A1 notation); whole sheet when omitted"},
{Name: "match-case", Kind: "own", Type: "bool", Required: "optional", Desc: "Case-sensitive match"},
@@ -133,10 +154,11 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Write range (A1 notation)"},
{Name: "cells", Kind: "own", Type: "string", Required: "required", Desc: "JSON 2D array `[[{cell},...],...]`, dimensions must match `--range`; each cell may carry `value` / `formula` / `cell_styles` / `note` / `rich_text` (incl. `type=\"embed-image\"` in-cell image); run `--print-schema` for full fields", Input: []string{"file", "stdin"}},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two); not accepted with `--writes` (each writes item carries its own sheet selector)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two); not accepted with `--writes` (each writes item carries its own sheet selector)"},
{Name: "range", Kind: "own", Type: "string", Required: "xor", Desc: "Write range (A1 notation). XOR with `--writes` (single region: --range+--cells; multiple regions: --writes)"},
{Name: "cells", Kind: "own", Type: "string", Required: "xor", Desc: "JSON 2D array `[[{cell},...],...]`, dimensions must match `--range`; each cell may carry `value` / `formula` / `cell_styles` / `note` / `rich_text` (incl. `type=\"embed-image\"` in-cell image); run `--print-schema` for full fields", Input: []string{"file", "stdin"}},
{Name: "writes", Kind: "own", Type: "string", Required: "xor", Desc: "Multi-region write as a JSON array (up to 100 items), each `{sheet_name|sheet_id, range, cells}` — the sheet selector LIVES IN EACH ITEM (same convention as +batch-update sub-ops and +styles-put items; the top-level --sheet-name is rejected). cells has the same shape as `--cells` (2D array; per-cell cell_styles/border_styles allowed). The whole array goes out as ONE atomic batched request, cross-sheet supported; typical use: fixing formulas scattered across ranges/sheets — do not assemble a +batch-update operations array for this. XOR with `--range`+`--cells`; range-level uniform styling stays with +styles-put afterwards", Input: []string{"file", "stdin"}},
{Name: "allow-overwrite", Kind: "own", Type: "bool", Required: "optional", Desc: "Allow overwriting non-empty cells (default true); set false to error if any target cell is non-empty", Default: "true"},
{Name: "max-cells", Kind: "own", Type: "int", Required: "optional", Desc: "Safety cap; default 50000", Default: "50000", Hidden: true},
{Name: "copy-to-range", Kind: "own", Type: "string", Required: "optional", Desc: "Copy-to range (A1 notation): replicate what --cells wrote into --range (values/formulas/styles, per the fields actually passed) to this range; formula refs auto-shift (C2=B2 -> C3=B3). Write a one-row/one-block template then fill a whole column/area. Supports full rows '3:6', full columns 'C:E', to-col-end 'D3:D', to-row-end 'D3:3', and comma-separated multiple targets like 'C1:D2,E5:F6'."},
@@ -148,8 +170,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Target cell (A1 notation; must be a single cell, e.g. `A1`; start and end must be identical)"},
{Name: "image", Kind: "own", Type: "string", Required: "required", Desc: "Local image path (PNG / JPEG / JPG / GIF / BMP / JFIF / EXIF / TIFF / BPG / HEIC)"},
{Name: "name", Kind: "own", Type: "string", Required: "optional", Desc: "Image file name (with extension); defaults to the basename of `--image`"},
@@ -161,8 +183,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Target range (A1 notation, e.g. `A1:B2`)"},
{Name: "background-color", Kind: "own", Type: "string", Required: "optional", Desc: "Background color (hex, e.g. `#ffffff`)"},
{Name: "font-color", Kind: "own", Type: "string", Required: "optional", Desc: "Font color (hex, e.g. `#000000`)"},
@@ -175,7 +197,7 @@ var flagDefs = map[string]commandDef{
{Name: "vertical-alignment", Kind: "own", Type: "string", Required: "optional", Desc: "Vertical alignment", Enum: []string{"top", "middle", "bottom"}},
{Name: "word-wrap", Kind: "own", Type: "string", Required: "optional", Desc: "Word-wrap strategy", Enum: []string{"overflow", "auto-wrap", "word-clip"}},
{Name: "number-format", Kind: "own", Type: "string", Required: "optional", Desc: "Number format pattern (e.g. text `@`, number `0.00`, currency `$#,##0.00`, date `mm/dd/yyyy`)"},
{Name: "border-styles", Kind: "own", Type: "string", Required: "optional", Desc: "Border config JSON: `{ top: {style,color,weight}, bottom: ..., left: ..., right: ... }`; same shape for all 4 sides", Input: []string{"file", "stdin"}},
{Name: "border-styles", Kind: "own", Type: "string", Required: "optional", Desc: "Border config JSON: `{ top: {style,weight,color}, bottom: ..., left: ..., right: ... }`; same shape for all 4 sides. style = line type (solid|dashed|dotted|double|none); weight = thickness (thin|medium|thick — a string, not a pixel number); color = hex like #000000. { all: {...} } sets all four sides at once. This is the only border flag: no --border-all / --border-top / --border-color exist", Input: []string{"file", "stdin"}},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
},
@@ -184,8 +206,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Range to merge / unmerge (A1 notation)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -199,24 +221,100 @@ var flagDefs = map[string]commandDef{
{Name: "end-revision", Kind: "own", Type: "int", Required: "optional", Desc: "End version (CS revision); defaults to the latest revision. Gap (end-start+1) must be <= 20", Default: "-1"},
},
},
"+chart-create": {
"+chart-config-update": {
Risk: "write",
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "chart-id", Kind: "own", Type: "string", Required: "required", Desc: "Target chart reference_id"},
{Name: "title", Kind: "own", Type: "string", Required: "optional", Desc: "Chart title"},
{Name: "subtitle", Kind: "own", Type: "string", Required: "optional", Desc: "Chart subtitle"},
{Name: "legend-position", Kind: "own", Type: "string", Required: "optional", Desc: "Legend position; hidden removes the legend", Enum: []string{"top", "bottom", "left", "right", "hidden"}},
{Name: "x-axis-title", Kind: "own", Type: "string", Required: "optional", Desc: "X-axis title"},
{Name: "y-axis-title", Kind: "own", Type: "string", Required: "optional", Desc: "Left Y-axis title"},
{Name: "secondary-y-axis-title", Kind: "own", Type: "string", Required: "optional", Desc: "Right Y-axis title"},
{Name: "x-axis-label-angle", Kind: "own", Type: "int", Required: "optional", Desc: "X-axis label angle", Enum: []string{"-90", "-45", "0", "45", "90"}},
{Name: "y-axis-label-angle", Kind: "own", Type: "int", Required: "optional", Desc: "Left Y-axis label angle", Enum: []string{"-90", "-45", "0", "45", "90"}},
{Name: "data-labels", Kind: "own", Type: "string", Required: "optional", Desc: "Data label content; none removes labels; category_percentage is normalized to value_percentage", Enum: []string{"none", "value", "percentage", "value_percentage", "category_percentage", "category", "series"}},
{Name: "data-label-position", Kind: "own", Type: "string", Required: "optional", Desc: "Data label position", Enum: []string{"auto", "top", "bottom", "left", "right", "center", "inside", "outside"}},
{Name: "stack", Kind: "own", Type: "string", Required: "optional", Desc: "Stacking mode", Enum: []string{"none", "normal", "percent"}},
{Name: "stacked", Kind: "own", Type: "bool", Required: "optional", Desc: "Compatibility alias for --stack normal", Hidden: true},
{Name: "smooth", Kind: "own", Type: "bool", Required: "optional", Desc: "Use smooth curves; accepts both --smooth=false and --smooth false"},
{Name: "color-palette", Kind: "own", Type: "string", Required: "optional", Desc: "Preset chart-level color palette; mutually exclusive with --colors", Enum: []string{"brandColorSeries@v2", "rainbowColorSeries@v2", "complementaryColorSeries@v2", "converseColorSeries@v2", "primaryColorSeries@v2", "singleColorSeries-B-@v2", "singleColorSeries-W-@v2", "singleColorSeries-G-@v2", "singleColorSeries-Y-@v2", "singleColorSeries-O-@v2", "singleColorSeries-R-@v2", "singleColorSeries-D-@v2"}},
{Name: "colors", Kind: "own", Type: "string_slice", Required: "optional", Desc: "Custom chart-level series colors as a comma-separated list of at least two hex colors; mutually exclusive with --color-palette"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional", Desc: "Print the request template; no side effects"},
},
},
"+chart-create": {
Risk: "write",
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "properties", Kind: "own", Type: "string", Required: "required", Desc: "Full chart config JSON. Top-level keys: `position` / `offset` / `size` / `snapshot` (no top-level `data`, no extra nested `properties`); chart data config lives under `snapshot.data` (`refs` / `headerMode` / `dim1` / `dim2`); must include at least one of `snapshot.data.dim1.serie.index` or `dim2.series[].index`, otherwise the server rejects it. Deeply nested — run `--print-schema --flag-name properties` for the full structure.", Input: []string{"file", "stdin"}},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional", Desc: "Print the request template; no side effects"},
},
},
"+chart-create-basic": {
Risk: "write",
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "chart-type", Kind: "own", Type: "string", Required: "required", Desc: "Chart type", Enum: []string{"column", "bar", "line", "area", "pie", "scatter", "combo", "radar"}},
{Name: "data-range", Kind: "own", Type: "string", Required: "required", Desc: "Data range; include headers unless --header-range is set, in which case pass data only; accepts comma-separated ranges across one or more sheets"},
{Name: "header-range", Kind: "own", Type: "string", Required: "optional", Desc: "Optional detached header range; use one row for column direction or one column for row direction, with one header per data dimension"},
{Name: "data-direction", Kind: "own", Type: "string", Required: "optional", Desc: "Data series direction; column uses the first column as categories, row uses the first row", Default: "column", Enum: []string{"column", "row"}},
{Name: "dim1-index", Kind: "own", Type: "int", Required: "optional", Desc: "1-based category/X-axis dimension index within the data range; defaults to 1"},
{Name: "dim2-indexes", Kind: "own", Type: "string", Required: "optional", Desc: "Comma-separated 1-based value/Y-axis dimension indexes; must exclude dim1, at most 50"},
{Name: "title", Kind: "own", Type: "string", Required: "optional", Desc: "Chart title"},
{Name: "subtitle", Kind: "own", Type: "string", Required: "optional", Desc: "Chart subtitle"},
{Name: "legend-position", Kind: "own", Type: "string", Required: "optional", Desc: "Legend position; hidden removes the legend", Enum: []string{"top", "bottom", "left", "right", "hidden"}},
{Name: "x-axis-title", Kind: "own", Type: "string", Required: "optional", Desc: "X-axis title"},
{Name: "y-axis-title", Kind: "own", Type: "string", Required: "optional", Desc: "Left Y-axis title"},
{Name: "secondary-y-axis-title", Kind: "own", Type: "string", Required: "optional", Desc: "Right Y-axis title"},
{Name: "x-axis-label-angle", Kind: "own", Type: "int", Required: "optional", Desc: "X-axis label angle", Enum: []string{"-90", "-45", "0", "45", "90"}},
{Name: "y-axis-label-angle", Kind: "own", Type: "int", Required: "optional", Desc: "Left Y-axis label angle", Enum: []string{"-90", "-45", "0", "45", "90"}},
{Name: "data-labels", Kind: "own", Type: "string", Required: "optional", Desc: "Data label content; none removes labels; category_percentage is normalized to value_percentage", Enum: []string{"none", "value", "percentage", "value_percentage", "category_percentage", "category", "series"}},
{Name: "data-label-position", Kind: "own", Type: "string", Required: "optional", Desc: "Data label position", Enum: []string{"auto", "top", "bottom", "left", "right", "center", "inside", "outside"}},
{Name: "stack", Kind: "own", Type: "string", Required: "optional", Desc: "Stacking mode", Enum: []string{"none", "normal", "percent"}},
{Name: "stacked", Kind: "own", Type: "bool", Required: "optional", Desc: "Compatibility alias for --stack normal", Hidden: true},
{Name: "smooth", Kind: "own", Type: "bool", Required: "optional", Desc: "Use smooth curves; accepts both --smooth=false and --smooth false"},
{Name: "color-palette", Kind: "own", Type: "string", Required: "optional", Desc: "Preset chart-level color palette; mutually exclusive with --colors", Enum: []string{"brandColorSeries@v2", "rainbowColorSeries@v2", "complementaryColorSeries@v2", "converseColorSeries@v2", "primaryColorSeries@v2", "singleColorSeries-B-@v2", "singleColorSeries-W-@v2", "singleColorSeries-G-@v2", "singleColorSeries-Y-@v2", "singleColorSeries-O-@v2", "singleColorSeries-R-@v2", "singleColorSeries-D-@v2"}},
{Name: "colors", Kind: "own", Type: "string_slice", Required: "optional", Desc: "Custom chart-level series colors as a comma-separated list of at least two hex colors; mutually exclusive with --color-palette"},
{Name: "anchor-cell", Kind: "own", Type: "string", Required: "optional", Desc: "Optional chart anchor cell such as F2; defaults to the right of the data range"},
{Name: "width", Kind: "own", Type: "int", Required: "optional", Desc: "Optional chart width; must be paired with --height"},
{Name: "height", Kind: "own", Type: "int", Required: "optional", Desc: "Optional chart height; must be paired with --width"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional", Desc: "Print the request template; no side effects"},
},
},
"+chart-data-update": {
Risk: "write",
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "chart-id", Kind: "own", Type: "string", Required: "required", Desc: "Target chart reference_id"},
{Name: "data-range", Kind: "own", Type: "string", Required: "required", Desc: "New data range; include headers unless --header-range is set or the chart already uses detached headers; accepts comma-separated ranges across one or more sheets"},
{Name: "header-range", Kind: "own", Type: "string", Required: "optional", Desc: "Optional detached header range; enables detached header mapping, while omission preserves an existing detached mapping"},
{Name: "data-direction", Kind: "own", Type: "string", Required: "optional", Desc: "Data series direction; defaults to the existing chart direction when omitted", Enum: []string{"column", "row"}},
{Name: "dim1-index", Kind: "own", Type: "int", Required: "optional", Desc: "1-based category/X-axis dimension index within the data range; defaults to the first dimension"},
{Name: "dim2-indexes", Kind: "own", Type: "string", Required: "optional", Desc: "Comma-separated 1-based value/Y-axis series indexes within the data range; defaults to all dimensions except dim1"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional", Desc: "Print the request template; no side effects"},
},
},
"+chart-delete": {
Risk: "high-risk-write",
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "chart-id", Kind: "own", Type: "string", Required: "required", Desc: "Target chart reference_id"},
{Name: "yes", Kind: "system", Type: "bool", Required: "required", Desc: "Confirm destructive write (exit code 10 without this flag)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -227,8 +325,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "chart-id", Kind: "own", Type: "string", Required: "optional", Desc: "Filter to a single chart reference_id"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -238,10 +336,10 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "chart-id", Kind: "own", Type: "string", Required: "required", Desc: "Target chart reference_id"},
{Name: "properties", Kind: "own", Type: "string", Required: "required", Desc: "Full or sufficiently complete chart config JSON (read back with `+chart-list` first, then patch)", Input: []string{"file", "stdin"}},
{Name: "properties", Kind: "own", Type: "string", Required: "required", Desc: "Chart config patch JSON; send changed fields only by default; omitted fields are preserved, objects merge recursively, and arrays replace as a whole", Input: []string{"file", "stdin"}},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
},
@@ -250,8 +348,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "width", Kind: "own", Type: "int", Required: "xor", Desc: "Uniform column width in pixels (e.g. 80 / 120 / 200; NOT Excel character units), used with `--range`. Passing --width implies pixel mode; --type may be omitted (or set to `pixel` — equivalent). For per-column widths use `--widths`", Default: "0"},
{Name: "widths", Kind: "own", Type: "string", Required: "xor", Desc: "Per-column width map — set different widths for many columns in one atomic call. Keys: single column (`\"A\"`) or closed range (`\"C:E\"`); values: pixel width (e.g. 80 / 120 / 200) or `\"standard\"` (reset to default). Units are pixels, NOT Excel character units (px ≈ chars × 8 + 16). Mutually exclusive with `--range` / `--width` / `--type`", Input: []string{"file", "stdin"}},
{Name: "type", Kind: "own", Type: "string", Required: "xor", Desc: "Sizing mode: `pixel` (requires `--width`) / `standard` (reset to default column width). Passing --width alone is the common form; `--type standard` cannot be combined with `--width`", Enum: []string{"pixel", "standard"}},
@@ -264,8 +362,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "properties", Kind: "own", Type: "string", Required: "required", Desc: "Rule config JSON: `style` (required, applied on match), `attrs?` (rule-type-dependent params), `has_ref?`. `rule_type` and `ranges` are separate flags", Input: []string{"file", "stdin"}},
{Name: "rule-type", Kind: "own", Type: "string", Required: "required", Desc: "Conditional format rule type; takes precedence over the same-named field inside `--properties`", Enum: []string{"duplicateValues", "uniqueValues", "cellIs", "containsText", "timePeriod", "containsBlanks", "notContainsBlanks", "dataBar", "colorScale", "rank", "aboveAverage", "expression", "iconSet"}},
{Name: "ranges", Kind: "own", Type: "string", Required: "required", Desc: "A1 ranges where the conditional format applies, as a JSON array (e.g. `[\"A1:A100\",\"C2:C50\"]`); takes precedence over the same-named field inside `--properties`", Input: []string{"file", "stdin"}},
@@ -277,8 +375,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "rule-id", Kind: "own", Type: "string", Required: "required", Desc: "Target rule id"},
{Name: "yes", Kind: "system", Type: "bool", Required: "required", Desc: "Confirm destructive write (exit code 10 without this flag); delete is irreversible"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -289,8 +387,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "rule-id", Kind: "own", Type: "string", Required: "optional", Desc: "Filter by rule id"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -300,8 +398,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "rule-id", Kind: "own", Type: "string", Required: "required", Desc: "Target rule id"},
{Name: "properties", Kind: "own", Type: "string", Required: "required", Desc: "Rule config JSON, same shape as `+cond-format-create --properties`; update overwrites the entire rule", Input: []string{"file", "stdin"}},
{Name: "rule-type", Kind: "own", Type: "string", Required: "required", Desc: "Conditional format rule type; takes precedence over the same-named field inside `--properties`", Enum: []string{"duplicateValues", "uniqueValues", "cellIs", "containsText", "timePeriod", "containsBlanks", "notContainsBlanks", "dataBar", "colorScale", "rank", "aboveAverage", "expression", "iconSet"}},
@@ -314,10 +412,11 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "A1 range, e.g. `A1:F30` (no sheet prefix — use `--sheet-id` / `--sheet-name` to select the sheet)"},
{Name: "max-chars", Kind: "own", Type: "int", Required: "optional", Desc: "Max output chars per call; default 500000 (safety cap). Large reads are usually better redirected to a file; only lower it (e.g. 25000) when you want results inline without triggering file offload, paging via has_more", Default: "500000"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "optional", Desc: "A1 range, e.g. `A1:F30` (no sheet prefix — use `--sheet-id` / `--sheet-name` to select the sheet). Optional: when omitted the whole sheet is read (clipped to the actual grid bounds; actual_range in the response names what was read); pair with --max-chars / --output-path on large sheets"},
{Name: "max-chars", Kind: "own", Type: "int", Required: "optional", Desc: "Max output chars per call; default 500000 (safety cap). For a full untruncated read, use --output-path to dump to a file (auto-unlimited); only lower it (e.g. 25000) when you want results inline without a file, paging via has_more.", Default: "500000"},
{Name: "output-path", Kind: "own", Type: "string", Required: "optional", Desc: "Write the full read result to a local path (e.g. `./out.json`); the file holds the data payload as JSON while stdout returns only a small confirmation (output_path, byte count). **When set, the char cap defaults to unlimited** (overriding the --max-chars default), so a large sheet can be dumped in full for later analysis without stdout being truncated by max_chars. Omit it to print to stdout as usual."},
{Name: "include-row-prefix", Kind: "own", Type: "bool", Required: "optional", Desc: "Whether to prefix each row with `[row=N]`; default `true`", Default: "true"},
{Name: "skip-hidden", Kind: "own", Type: "bool", Required: "optional", Desc: "Skip hidden rows and columns; default `false`"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional", Desc: "Print the request path and parameters without executing"},
@@ -328,8 +427,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "start-cell", Kind: "own", Type: "string", Required: "required", Desc: "Top-left A1 anchor (e.g. `A1`, `B5`; no sheet prefix — use `--sheet-id` / `--sheet-name` to select the sheet); must be a single cell, range notation not accepted; the bottom-right is inferred from CSV row/column counts", Default: "A1"},
{Name: "csv", Kind: "own", Type: "string", Required: "required", Desc: "RFC 4180 CSV text; values or formulas (a leading = is evaluated as a formula); no styles / comments / images (use +cells-set for those).", Input: []string{"file", "stdin"}},
{Name: "allow-overwrite", Kind: "own", Type: "bool", Required: "optional", Desc: "Allow overwriting (default true); set false to error if any target cell is non-empty", Default: "true"},
@@ -342,9 +441,10 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Row/column closed range to delete; rows use 1-based numbers like `3:7` or `5` (single row), columns use letters like `C:F` or `C`"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "xor", Desc: "Row/column closed range to delete; rows use 1-based numbers like `3:7` or `5` (single row), columns use letters like `C:F` or `C`. XOR with `--ranges`"},
{Name: "ranges", Kind: "own", Type: "string", Required: "xor", Desc: "Multiple row/column ranges to delete as a JSON array (up to 100 items, e.g. `[\"5:5\",\"8:8\",\"11:13\"]` or `[\"C:C\",\"F:G\"]`); rows and columns cannot be mixed, ranges must not overlap; XOR with `--range`. CLI sorts positions in DESCENDING order into one atomic batch delete — ascending deletion would shift later indexes as earlier rows/columns disappear; the CLI handles the ordering", Input: []string{"file", "stdin"}},
{Name: "yes", Kind: "system", Type: "bool", Required: "required", Desc: "Confirm destructive write (exit code 10 without this flag); row/column deletion is irreversible"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -354,8 +454,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "dimension", Kind: "own", Type: "string", Required: "required", Desc: "Dimension (row or column)", Enum: []string{"row", "column"}},
{Name: "count", Kind: "own", Type: "int", Required: "required", Desc: "Freeze the first N rows/columns; pass 0 to unfreeze"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -366,8 +466,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "depth", Kind: "own", Type: "int", Required: "optional", Desc: "Nesting level for grouping; default 1", Default: "1"},
{Name: "group-state", Kind: "own", Type: "string", Required: "optional", Desc: "Initial group expand state", Default: "expand", Enum: []string{"expand", "fold"}},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Row/column closed range to group; rows use 1-based numbers like `3:7`, columns use letters like `C:F`"},
@@ -379,8 +479,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Row/column closed range to hide; rows use 1-based numbers like `3:7`, columns use letters like `C:F`"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -390,9 +490,9 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "inherit-style", Kind: "own", Type: "string", Required: "optional", Desc: "Style inheritance for the new row/column: `before` (from preceding) / `after` (from following) / `none` (default)", Default: "none", Enum: []string{"before", "after", "none"}},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "inherit-style", Kind: "own", Type: "string", Required: "optional", Desc: "Style inheritance for the new row/column: `before` (from the preceding row/column) / `after` (from the following row/column). Omit the flag to inherit the following row/column (same as `after`) — the backend cannot leave a new row/column unstyled; for a truly blank row/column, clear formats afterwards with +cells-clear --scope formats. Insertion always lands before `--position`; this only selects which side's style is copied.", Enum: []string{"before", "after"}},
{Name: "position", Kind: "own", Type: "string", Required: "required", Desc: "Insert position (1-based row number like `3` or column letter like `C`); new rows/columns are inserted *before* this position"},
{Name: "count", Kind: "own", Type: "int", Required: "required", Desc: "Number of rows/columns to insert (must be > 0)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -403,8 +503,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "source-range", Kind: "own", Type: "string", Required: "required", Desc: "Source row/column closed range to move; rows use 1-based numbers like `3:7`, columns use letters like `C:F`"},
{Name: "target", Kind: "own", Type: "string", Required: "required", Desc: "Destination position (the moved rows/columns are placed *before* this position); rows use 1-based row number like `12`, columns use column letter like `H`. Must match the dimension of --source-range"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -415,8 +515,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "depth", Kind: "own", Type: "int", Required: "optional", Desc: "Group nesting level to ungroup; default 1 (1 = outermost, larger = deeper)", Default: "1"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Row/column closed range to ungroup; rows use 1-based numbers like `3:7`, columns use letters like `C:F`"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -427,8 +527,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Row/column closed range to unhide; rows use 1-based numbers like `3:7`, columns use letters like `C:F`"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -448,8 +548,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Target range in A1 notation, e.g. `A2:A100` (no sheet prefix — use `--sheet-id` / `--sheet-name` to select the sheet)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -459,8 +559,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Target range (A1 notation, e.g. `A2:A100`)"},
{Name: "options", Kind: "own", Type: "string", Required: "xor", Desc: "Options as a JSON array, e.g. `[\"opt1\",\"opt2\"]`. Server enforces no item-count cap and no per-item length cap; values containing commas are accepted (they are escape-encoded on the wire). For very large lists prefer `--source-range`.", Input: []string{"file", "stdin"}},
{Name: "colors", Kind: "own", Type: "string", Required: "optional", Desc: "Per-option pill colors, RGB hex array (e.g. `[\"#1FB6C1\",\"#F006C2\"]`). Length may be shorter than the source (`--options` items / `--source-range` cells) — extras cycle through a 10-color palette — but never longer (CLI Validate rejects: `--colors length (N) must not exceed dropdown source size (M)`). **Applies on its own**; ignored when `--highlight=false`.", Input: []string{"file", "stdin"}},
@@ -489,8 +589,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Filter range (A1 notation, including header row, e.g. `A1:F1000`); do not duplicate the range field inside `--properties`"},
{Name: "properties", Kind: "own", Type: "string", Required: "optional", Desc: "Filter rule JSON: `rules` (per-column rule array), `filtered_columns?` (active column index hint). The flag is optional overall — if provided, `rules` must be non-empty; if omitted, an empty filter is created on `--range` (no column conditions). `range` is a separate flag (do not duplicate inside this JSON)", Input: []string{"file", "stdin"}},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -501,8 +601,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "yes", Kind: "system", Type: "bool", Required: "required", Desc: "Confirm destructive write (exit code 10 without this flag); delete is irreversible"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -512,8 +612,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
},
@@ -522,8 +622,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "properties", Kind: "own", Type: "string", Required: "required", Desc: "Filter rule JSON: `rules` and `filtered_columns?`; update overwrites the entire rule set (pass `rules: []` to clear). `range` is a separate flag", Input: []string{"file", "stdin"}},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Range the filter applies to (A1 notation, e.g. `A1:F1000`); takes precedence over the same-named field inside `--properties`"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -534,8 +634,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "properties", Kind: "own", Type: "string", Required: "required", Desc: "Filter-view rule JSON: `rules?` (per-column rule array), `filtered_columns?`. `range` and `view_name` are separate flags", Input: []string{"file", "stdin"}},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Range the filter view applies to (A1 notation, e.g. `A1:F1000`); takes precedence over the same-named field inside `--properties`; required on create and must cover the header row"},
{Name: "view-name", Kind: "own", Type: "string", Required: "optional", Desc: "Filter-view name; auto-assigned by the server when omitted; takes precedence over the same-named field inside `--properties`"},
@@ -547,8 +647,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "view-id", Kind: "own", Type: "string", Required: "required", Desc: "Target filter-view reference_id"},
{Name: "yes", Kind: "system", Type: "bool", Required: "required", Desc: "Confirm high-risk write (exit code 10 without this flag)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -559,8 +659,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "view-id", Kind: "own", Type: "string", Required: "optional", Desc: "Filter by filter-view reference_id (returns the matching single view)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -570,8 +670,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "view-id", Kind: "own", Type: "string", Required: "required", Desc: "Target filter-view reference_id"},
{Name: "properties", Kind: "own", Type: "string", Required: "required", Desc: "Filter-view rule JSON: `rules?`, `filtered_columns?`; update overwrites the entire rule set (read back with `+filter-view-list` first, then patch; pass `rules: []` to clear). `range` and `view_name` are separate flags", Input: []string{"file", "stdin"}},
{Name: "range", Kind: "own", Type: "string", Required: "optional", Desc: "Range the filter view applies to (A1 notation, e.g. `A1:F1000`); takes precedence over the same-named field inside `--properties`; omit to keep the current range on update"},
@@ -584,8 +684,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "image-name", Kind: "own", Type: "string", Required: "required", Desc: "Image name, including extension (e.g. `logo.png`)"},
{Name: "image-token", Kind: "own", Type: "string", Required: "xor", Desc: "Image file_token (XOR with `--image-uri`). Common source: `image_token` returned by `+float-image-list`"},
{Name: "image-uri", Kind: "own", Type: "string", Required: "xor", Desc: "Image URI handle returned by the upload flow (not a sheet object reference_id; XOR with `--image-token`); converted to file_token automatically"},
@@ -605,8 +705,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "float-image-id", Kind: "own", Type: "string", Required: "required", Desc: "Target float image id"},
{Name: "yes", Kind: "system", Type: "bool", Required: "required", Desc: "Confirm destructive write (exit code 10 without this flag); delete is irreversible"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -617,8 +717,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "float-image-id", Kind: "own", Type: "string", Required: "optional", Desc: "Filter by id; lists all float images on the sheet when omitted"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -628,8 +728,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "float-image-id", Kind: "own", Type: "string", Required: "required", Desc: "Target float image id"},
{Name: "image-name", Kind: "own", Type: "string", Required: "required", Desc: "Image name, including extension (e.g. `logo.png`)"},
{Name: "image-token", Kind: "own", Type: "string", Required: "optional", Desc: "Optional image file_token; mutually exclusive with `--image-uri`; omit both to keep the current image. Common source: `image_token` returned by `+float-image-list`"},
@@ -702,8 +802,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "pivot-table-id", Kind: "own", Type: "string", Required: "required", Desc: "Target pivot table id"},
{Name: "yes", Kind: "system", Type: "bool", Required: "required", Desc: "Confirm destructive write (exit code 10 without this flag); delete is irreversible"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -714,8 +814,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "pivot-table-id", Kind: "own", Type: "string", Required: "optional", Desc: "Filter by id"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -725,8 +825,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "pivot-table-id", Kind: "own", Type: "string", Required: "required", Desc: "Target pivot table id"},
{Name: "properties", Kind: "own", Type: "string", Required: "required", Desc: "Full or sufficiently complete pivot config (read back with `+pivot-list --pivot-table-id <id>` first, then patch)", Input: []string{"file", "stdin"}},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -737,8 +837,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "source-range", Kind: "own", Type: "string", Required: "required", Desc: "Source A1 range"},
{Name: "target-sheet-id", Kind: "own", Type: "string", Required: "optional", Desc: "Destination sub-sheet id; defaults to the same sheet as the source"},
{Name: "target-range", Kind: "own", Type: "string", Required: "required", Desc: "Destination A1 range (anchor cell is enough; size inferred from the source)"},
@@ -751,8 +851,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "source-range", Kind: "own", Type: "string", Required: "required", Desc: "Fill template range (seed cells for the series)"},
{Name: "target-range", Kind: "own", Type: "string", Required: "required", Desc: "Destination fill range (A1 notation)"},
{Name: "series-type", Kind: "own", Type: "string", Required: "optional", Desc: "Fill series type", Default: "auto", Enum: []string{"auto", "linear", "growth", "date", "copy"}},
@@ -764,8 +864,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "source-range", Kind: "own", Type: "string", Required: "required", Desc: "Source A1 range"},
{Name: "target-sheet-id", Kind: "own", Type: "string", Required: "optional", Desc: "Destination sub-sheet id; defaults to the same sheet as the source"},
{Name: "target-range", Kind: "own", Type: "string", Required: "required", Desc: "Destination A1 range (anchor cell is enough; size inferred from the source)"},
@@ -777,8 +877,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "range", Kind: "own", Type: "string", Required: "required", Desc: "Sort range (A1 notation; whether the header is included depends on `--has-header`)"},
{Name: "sort-keys", Kind: "own", Type: "string", Required: "required", Desc: "JSON array: `[{\"column\":\"<col letter>\",\"ascending\":<bool>}, ...]`", Input: []string{"file", "stdin"}},
{Name: "has-header", Kind: "own", Type: "bool", Required: "optional", Desc: "Treat the first row as a header and exclude from sort; default `false`"},
@@ -798,8 +898,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "height", Kind: "own", Type: "int", Required: "xor", Desc: "Uniform row height in pixels (e.g. 30 / 40 / 60; NOT points), used with `--range`. Passing --height implies pixel mode; --type may be omitted (or set to `pixel` — equivalent). For per-row heights use `--heights`", Default: "0"},
{Name: "heights", Kind: "own", Type: "string", Required: "xor", Desc: "Per-row height map — set different heights for many rows in one atomic call. Keys: single row (`\"1\"`) or closed range (`\"2:20\"`); values: pixel height (e.g. 30 / 50), `\"auto\"` (fit content) or `\"standard\"` (reset to default). Units are pixels, NOT points. Mutually exclusive with `--range` / `--height` / `--type`", Input: []string{"file", "stdin"}},
{Name: "type", Kind: "own", Type: "string", Required: "xor", Desc: "Sizing mode: `pixel` (requires `--height`) / `standard` (reset to default row height) / `auto` (fit content). Passing --height alone is the common form; `--type standard` / `--type auto` cannot be combined with `--height`", Enum: []string{"pixel", "standard", "auto"}},
@@ -812,8 +912,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "title", Kind: "own", Type: "string", Required: "optional", Desc: "Copy title; auto-generated by the server when omitted"},
{Name: "index", Kind: "own", Type: "int", Required: "optional", Desc: "Insert position for the copy (0-based); appended to the end when omitted", Default: "-1"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -837,8 +937,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "yes", Kind: "system", Type: "bool", Required: "required", Desc: "Confirm high-risk write (exit code 10 without this flag)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -848,8 +948,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
},
@@ -858,8 +958,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
},
@@ -868,8 +968,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "include", Kind: "own", Type: "string_slice", Required: "optional", Desc: "Comma-separated structure info categories to return", Enum: []string{"merges", "row_heights", "col_widths", "hidden_rows", "hidden_cols", "groups", "frozen"}},
{Name: "range", Kind: "own", Type: "string", Required: "optional", Desc: "Limit structure info to this A1 range; whole sheet when omitted"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -880,8 +980,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "index", Kind: "own", Type: "int", Required: "required", Desc: "Target position (0-based)"},
{Name: "source-index", Kind: "own", Type: "int", Required: "optional", Desc: "Source position (0-based); optional for standalone calls — if omitted, the CLI runtime derives it from the current workbook index of `--sheet-id` / `--sheet-name`. Inside `+batch-update` it must be passed explicitly, since batch cannot issue a structure query mid-run to derive it", Default: "-1"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -892,8 +992,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "title", Kind: "own", Type: "string", Required: "required", Desc: "New title"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -903,8 +1003,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "color", Kind: "own", Type: "string", Required: "required", Desc: "Hex color like `#FF0000`; pass empty string `\"\"` to clear"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -914,8 +1014,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
},
@@ -924,8 +1024,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
},
@@ -934,8 +1034,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "properties", Kind: "own", Type: "string", Required: "required", Desc: "JSON: `{config (shared style), sparklines (array of mini-charts)}`; run `--print-schema` for the full structure", Input: []string{"file", "stdin"}},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -945,8 +1045,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "group-id", Kind: "own", Type: "string", Required: "required", Desc: "Target group id"},
{Name: "yes", Kind: "system", Type: "bool", Required: "required", Desc: "Confirm destructive write (exit code 10 without this flag); delete is irreversible"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
@@ -957,8 +1057,8 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "group-id", Kind: "own", Type: "string", Required: "optional", Desc: "Filter by group_id"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
@@ -968,13 +1068,22 @@ var flagDefs = map[string]commandDef{
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet URL (XOR with `--spreadsheet-token`)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id (XOR with `--sheet-name`)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name (XOR with `--sheet-id`)"},
{Name: "sheet-id", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet reference_id — required: pass this or `--sheet-name` (exactly one of the two)"},
{Name: "sheet-name", Kind: "public", Type: "string", Required: "xor", Desc: "Sheet name — required: pass this or `--sheet-id` (exactly one of the two)"},
{Name: "group-id", Kind: "own", Type: "string", Required: "required", Desc: "Target group id"},
{Name: "properties", Kind: "own", Type: "string", Required: "required", Desc: "JSON: `{config, sparklines}`; read back with `+sparkline-list --group-id <id>` first, then patch; run `--print-schema` for the full structure", Input: []string{"file", "stdin"}},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},
},
"+styles-put": {
Risk: "write",
Flags: []flagDef{
{Name: "url", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet locator (target sheets are named inside --styles items)"},
{Name: "spreadsheet-token", Kind: "public", Type: "string", Required: "xor", Desc: "Spreadsheet token (XOR with `--url`)"},
{Name: "styles", Kind: "own", Type: "string", Required: "required", Desc: "Visual spec JSON applied to an EXISTING spreadsheet: top-level `{styles:[...]}`, one item per target sheet (`name` is the real sheet name), each giving at least one of `cell_styles` / `cell_merges` / `row_sizes` / `col_sizes` / `freeze`. The vocabulary is identical to `--styles` on `+workbook-create` / `+table-put` (cell_styles = A1 range + flat style fields, borders via the `border` shorthand {style,weight,color} applied to all four sides — border_styles only for per-side differences; row/col sizes = row/column range + size in px — type only for standard/auto; merges = cell range; freeze = `{rows:N, cols:N}`). The whole spec expands into one atomic batched request; ranges may target any region of the sheet", Input: []string{"file", "stdin"}},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional", Desc: "Print the batched request template for each expanded operation; no network side effects"},
},
},
"+table-get": {
Risk: "read",
Flags: []flagDef{
@@ -983,6 +1092,8 @@ var flagDefs = map[string]commandDef{
{Name: "sheet-id", Kind: "own", Type: "string", Required: "optional", Desc: "Read only this sheet (by id); omit to read all sheets"},
{Name: "sheet-name", Kind: "own", Type: "string", Required: "optional", Desc: "Read only this sheet (by name); omit to read all sheets"},
{Name: "range", Kind: "own", Type: "string", Required: "optional", Desc: "A1 range to read; omit to read each sheet's full used range (spans internal blank rows/columns, not just the A1 current region)"},
{Name: "max-chars", Kind: "own", Type: "int", Required: "optional", Desc: "Max output chars per call; default 500000 (safety cap). The underlying tool truncates at ~50000 even when unset, so this is sent explicitly to raise it; for a full untruncated read use --output-path (auto-unlimited).", Default: "500000"},
{Name: "output-path", Kind: "own", Type: "string", Required: "optional", Desc: "Write the full read result to a local path (e.g. `./out.json`); the file holds the data payload as JSON while stdout returns only a small confirmation (output_path, byte count). **When set, the char cap defaults to unlimited** (overriding the --max-chars default), so a large sheet can be dumped in full for later analysis without stdout being truncated by max_chars. Omit it to print to stdout as usual."},
{Name: "no-header", Kind: "own", Type: "bool", Required: "optional", Desc: "Treat the first row as data instead of a header (columns get positional names col1, col2, ...)"},
{Name: "dry-run", Kind: "system", Type: "bool", Required: "optional"},
},

View File

@@ -52,7 +52,7 @@ func TestFlagsFor_MapsAllFields(t *testing.T) {
// enum + default
rt := byName("+dim-insert", "inherit-style")
if rt == nil || len(rt.Enum) != 3 || rt.Default != "none" {
if rt == nil || len(rt.Enum) != 2 || rt.Default != "" {
t.Errorf("+dim-insert --inherit-style not mapped: %+v", rt)
}
// required

View File

@@ -38,9 +38,140 @@ func withFlagErgonomics(prev func(cmd *cobra.Command)) func(cmd *cobra.Command)
}
cmd.SetFlagErrorFunc(sheetsFlagErrorFunc)
chainEnumNormalization(cmd)
chainFlagAliases(cmd)
}
}
// ─── intuitive flag names: silent aliases & prescriptions ───────────────
//
// Eval traces show unknown-flag failures cluster on a handful of habitual
// names (--file, --cols, --dimension, --start-cell, --bold, --source…) that
// agents import from generic CLI / Excel vocabulary. Two tiers, mirroring
// the enum-normalization contract above: a name whose value semantics are
// identical to the real flag is rewritten silently (zero round-trips); a
// name whose fix changes the value or moves it into a JSON field gets a
// curated prescription on the unknown-flag error instead — never a silent
// rewrite.
// commandFlagAliases maps, per command, habitual flag names onto the flag
// actually registered. Only pairs with identical value semantics belong
// here: the rewrite is invisible, so it must be safe to apply unread
// (+csv-put --file with a path value still trips the file-path guard, which
// prescribes @file / stdin).
var commandFlagAliases = map[string]map[string]string{
"+csv-put": {"file": "csv"},
"+sheet-create": {"name": "title"},
// The new name is the only name-valued input a rename takes, so the
// habitual spellings are unambiguous (unlike +sheet-copy, where a name
// could mean the copy's title or the source selector and gets a
// prescription instead). 07-28 root-cause report #25: 10/10 wrote
// --new-name, 24 occurrences.
"+sheet-rename": {"name": "title", "new-name": "title"},
// size → width/height: the styles protocol (--styles row_sizes/col_sizes)
// spells the pixel dimension "size", and pre-2026-07 batches accepted it
// here too — the rename is the single largest sub-op error cluster in
// eval traces (15+ hits). Same pixel-count semantics, safe to rewrite.
"+cols-resize": {"cols": "range", "size": "width"},
"+rows-resize": {"rows": "range", "size": "height"},
"+range-fill": {"source": "source-range", "target": "target-range"},
"+range-copy": {"source": "source-range", "target": "target-range"},
"+range-move": {"source": "source-range", "target": "target-range"},
"+chart-create-basic": {"type": "chart-type", "range": "data-range", "x-axis": "x-axis-title", "y-axis": "y-axis-title"},
"+chart-config-update": {"x-axis": "x-axis-title", "y-axis": "y-axis-title"},
"+chart-data-update": {"range": "data-range"},
}
// intuitiveFlagHints carries the prescription for habitual names whose fix
// is not a 1:1 rename — the value belongs to a different flag or to a field
// inside a JSON payload. The hint spells the exact correct form so the
// retry needs no --help round trip.
var intuitiveFlagHints = map[string]map[string]string{
"+sheet-copy": {
"new-sheet-name": "the copy's name goes in --title; --sheet-name / --sheet-id selects the source sheet",
"target-sheet-name": "the copy's name goes in --title; --sheet-name / --sheet-id selects the source sheet",
"new-name": "the copy's name goes in --title; --sheet-name / --sheet-id selects the source sheet",
},
"+dim-insert": {
"dimension": "+dim-insert infers rows vs columns from --position: a row number like 3 inserts rows, a column letter like C inserts columns; pair with --count N",
},
"+dim-freeze": {
"frozen-rows": "freeze the first N rows with --dimension row --count N",
"frozen-cols": "freeze the first N columns with --dimension column --count N",
"frozen-columns": "freeze the first N columns with --dimension column --count N",
"frozen-row-count": "freeze the first N rows with --dimension row --count N",
"frozen-col-count": "freeze the first N columns with --dimension column --count N",
"frozen-column-count": "freeze the first N columns with --dimension column --count N",
},
"+cells-set-style": {
"bold": "use --font-weight bold",
"italic": "use --font-style italic",
"underline": "use --font-line underline",
"font-bold": "use --font-weight bold",
"bg-color": "use --background-color",
// Google Sheets API vocabulary (wrapStrategy).
"wrap-strategy": "use --word-wrap (overflow / auto-wrap / word-clip)",
// The border family: the only border flag is --border-styles (composite
// JSON); color and per-side variants ride inside it.
"border-style": `borders take one composite flag: --border-styles '{"all":{"style":"solid","weight":"thin","color":"#000000"}}' (sides: top/bottom/left/right, or "all" for all four)`,
"border-color": `border color rides inside --border-styles JSON, e.g. --border-styles '{"all":{"style":"solid","weight":"thin","color":"#000000"}}'`,
"border-all": `use --border-styles '{"all":{"style":"solid","weight":"thin","color":"#000000"}}' — the "all" key applies one spec to all four sides`,
"border-top": `per-side borders ride inside --border-styles JSON, e.g. --border-styles '{"top":{"style":"solid","weight":"thin","color":"#000000"}}'`,
"border-bottom": `per-side borders ride inside --border-styles JSON, e.g. --border-styles '{"bottom":{"style":"solid","weight":"thin","color":"#000000"}}'`,
"border-left": `per-side borders ride inside --border-styles JSON, e.g. --border-styles '{"left":{"style":"solid","weight":"thin","color":"#000000"}}'`,
"border-right": `per-side borders ride inside --border-styles JSON, e.g. --border-styles '{"right":{"style":"solid","weight":"thin","color":"#000000"}}'`,
},
"+cells-set": {
// Predictable prior from +table-put --styles: models will try to
// attach range-level styling to a --writes call the same way.
"styles": `range-level styling goes through +styles-put (same {"styles":[...]} vocabulary); per-cell styles ride inside the cells objects as cell_styles`,
// +workbook-create's untyped-data flag, carried over to the write
// command (07-28 root-cause report #9, 63 occurrences; values↔cells
// shares no prefix so edit distance never suggests the fix).
"values": `cell contents go in --cells as a 2D array of cell objects ('[[{"value":…},…],…]'); --values is +workbook-create's flag for untyped initial data`,
},
"+table-put": {
"start-cell": `anchor each sub-sheet via the "start_cell" field inside --sheets (e.g. {"sheets":[{"name":"Sheet1","start_cell":"B2",…}]}); to paste CSV at a cell use +csv-put --start-cell`,
"sheet-name": `+table-put has no sheet selector — each --sheets item carries its own "name" field ({"sheets":[{"name":"Sheet1",…}]})`,
"sheet-id": `+table-put has no sheet selector — each --sheets item carries its own "name" field ({"sheets":[{"name":"Sheet1",…}]})`,
},
"+chart-create-basic": {
"position": "use --anchor-cell F2 for the chart anchor; optionally pair --width and --height for its pixel size",
"show-labels": "use --data-labels value (or percentage/value_percentage/category/series; use none to hide labels)",
},
"+chart-config-update": {
"show-labels": "use --data-labels value (or percentage/value_percentage/category/series; use none to hide labels)",
},
}
// chainFlagAliases composes two rewrites onto the flag-name normalize hook
// (on top of any hook a prior PostMount installed, e.g. --token →
// --spreadsheet-token): the wire-vocabulary underscore form of any flag
// (--sheet_name, --border_styles — no sheets flag has an underscore in its
// canonical name), and the command's intuitive-alias table. Either way a
// habitual name parses as the real flag with zero round trips. Aliases
// never shadow a registered flag and never appear in --help; an alias whose
// target vanished (spec-side rename) is dropped, degrading to the
// unknown-flag prescription.
func chainFlagAliases(cmd *cobra.Command) {
aliases := commandFlagAliases[cmd.Name()]
usable := make(map[string]string, len(aliases))
for alias, target := range aliases {
if cmd.Flags().Lookup(alias) == nil && cmd.Flags().Lookup(target) != nil {
usable[alias] = target
}
}
prev := cmd.Flags().GetNormalizeFunc()
cmd.Flags().SetNormalizeFunc(func(fs *pflag.FlagSet, name string) pflag.NormalizedName {
if strings.Contains(name, "_") {
name = strings.ReplaceAll(name, "_", "-")
}
if target, ok := usable[name]; ok {
name = target
}
return prev(fs, name)
})
}
// sheetsFlagErrorFunc overrides the root FlagErrorFunc for sheets commands.
// It keeps the root behavior (typed error, did-you-mean suggestions, the
// offending flag on params) and additionally inlines the full valid-flag
@@ -50,6 +181,19 @@ func withFlagErgonomics(prev func(cmd *cobra.Command)) func(cmd *cobra.Command)
// immediately.
func sheetsFlagErrorFunc(c *cobra.Command, ferr error) error {
name, isUnknown := unknownFlagFromParseError(ferr)
// Targeted fix for a high-frequency agent mistake: +batch-update carries no
// top-level sheet locator (each sub-op names its own sheet inside its input),
// yet agents reach for --sheet-id / --sheet-name at the top level. An
// edit-distance suggestion would only mislead here, so skip it and name the
// real contract instead. Underscore spellings (--sheet_id) are matched too:
// the error message itself teaches the underscore key names, and sub-op
// inputs accept them, so agents mix the two styles.
locatorName := strings.ReplaceAll(name, "_", "-")
if isUnknown && c.Name() == "+batch-update" && (locatorName == "sheet-id" || locatorName == "sheet-name") {
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"batch-update has no top-level sheet locator; put sheet_id/sheet_name inside each operation's input").
WithParams(errs.InvalidParam{Name: "--" + name, Reason: "unknown flag"})
}
if !isUnknown {
return common.ValidationErrorf("%s", ferr.Error()).
WithHint("run `%s --help` for valid flags", c.CommandPath())
@@ -67,6 +211,19 @@ func sheetsFlagErrorFunc(c *cobra.Command, ferr error) error {
strings.Join(suggestions, ", "), list)
}
}
// A curated prescription beats both: it spells the exact correct form
// for a habitual name whose fix is not a rename (see intuitiveFlagHints).
// Edit-distance candidates are dropped with it — they can contradict the
// prescription (--font-bold ranked --font-color/--font-line/--font-size
// while the fix is --font-weight), and a machine-readable suggestion that
// disagrees with the hint sends agents down the wrong retry.
if rx, ok := intuitiveFlagHints[c.Name()][name]; ok {
hint = rx
if list := inlineFlagList(valid); list != "" {
hint = rx + "; valid flags: " + list
}
suggestions = nil
}
return errs.NewValidationError(errs.SubtypeInvalidArgument,
"unknown flag %q for %q", "--"+name, c.CommandPath()).
WithParams(errs.InvalidParam{Name: "--" + name, Reason: "unknown flag", Suggestions: suggestions}).
@@ -139,6 +296,24 @@ var enumAliases = map[string]string{
"center": "middle", // CSS vertical-align: center → Lark "middle"
"centre": "center",
"middle": "center", // CSS-style middle → Lark horizontal "center"
// Raw Lark OpenAPI merge vocabulary (MERGE_ALL/…) — agents reproduce it
// from the API docs; lowercased by canonicalEnumValue before lookup.
"merge_all": "all",
"merge_rows": "rows",
"merge_columns": "columns",
// Boolean-style word-wrap habits: true unambiguously means wrap on;
// false means "don't wrap", whose Lark default is overflow (word-clip is
// a distinct truncation mode nobody spells "false").
"true": "auto-wrap",
"false": "overflow",
// Combined chart data-label vocabulary emitted by models. The tool enum
// spells the same intent as one value.
"percentage,value": "value_percentage",
"value,percentage": "value_percentage",
// Google Sheets wrapStrategy vocabulary: WRAP / CLIP / OVERFLOW. Only
// the first two need mapping — overflow is spelled the same in both.
"wrap": "auto-wrap",
"clip": "word-clip",
}
// canonicalEnumValue returns the enum entry an off-vocabulary value
@@ -153,7 +328,8 @@ func canonicalEnumValue(val string, enum []string) string {
return allowed
}
}
if target, ok := enumAliases[lower]; ok {
aliasKey := strings.ReplaceAll(lower, " ", "")
if target, ok := enumAliases[aliasKey]; ok {
if slices.Contains(enum, target) {
return target
}

View File

@@ -96,6 +96,55 @@ func TestSheetsFlagErrorFunc_TypoKeepsSuggestion(t *testing.T) {
}
}
// TestSheetsFlagErrorFunc_BatchUpdateSheetLocator pins the targeted fix: a
// top-level --sheet-id / --sheet-name on +batch-update points the caller at
// the per-op locator contract instead of offering a misleading fuzzy guess.
func TestSheetsFlagErrorFunc_BatchUpdateSheetLocator(t *testing.T) {
t.Parallel()
for _, name := range []string{"sheet-id", "sheet-name", "sheet_id", "sheet_name"} {
name := name
t.Run(name, func(t *testing.T) {
t.Parallel()
c := &cobra.Command{Use: "+batch-update"}
c.Flags().String("operations", "", "")
err := sheetsFlagErrorFunc(c, errors.New("unknown flag: --"+name))
var verr *errs.ValidationError
if !errors.As(err, &verr) {
t.Fatalf("expected *errs.ValidationError, got %T", err)
}
if !strings.Contains(verr.Message, "put sheet_id/sheet_name inside each operation's input") {
t.Errorf("message should name the per-op locator contract, got %q", verr.Message)
}
if strings.Contains(verr.Hint, "did you mean") {
t.Errorf("must not offer a fuzzy guess here, got hint %q", verr.Hint)
}
if len(verr.Params) != 1 || verr.Params[0].Name != "--"+name {
t.Errorf("Params should carry the offending flag, got %v", verr.Params)
}
if len(verr.Params[0].Suggestions) != 0 {
t.Errorf("no suggestions expected, got %v", verr.Params[0].Suggestions)
}
})
}
}
// TestSheetsFlagErrorFunc_BatchUpdateOtherUnknownStillSuggests confirms the
// special case is scoped to the two sheet-locator flags: any other unknown
// flag on +batch-update keeps the normal did-you-mean behaviour.
func TestSheetsFlagErrorFunc_BatchUpdateOtherUnknownStillSuggests(t *testing.T) {
t.Parallel()
c := &cobra.Command{Use: "+batch-update"}
c.Flags().String("operations", "", "")
err := sheetsFlagErrorFunc(c, errors.New("unknown flag: --operation"))
var verr *errs.ValidationError
if !errors.As(err, &verr) {
t.Fatalf("expected *errs.ValidationError, got %T", err)
}
if strings.Contains(verr.Message, "no top-level sheet locator") {
t.Errorf("non-locator unknown flag must not hit the special case, got %q", verr.Message)
}
}
func TestSheetsFlagErrorFunc_OtherErrorStaysGeneric(t *testing.T) {
t.Parallel()
c := &cobra.Command{Use: "demo"}
@@ -284,9 +333,9 @@ func TestShortcuts_FlagErgonomicsMounted(t *testing.T) {
_, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--cols", "A:D",
"--col-size", "A:D",
})
ve := requireValidation(t, err, `unknown flag "--cols"`)
ve := requireValidation(t, err, `unknown flag "--col-size"`)
for _, want := range []string{"valid flags:", "--range", "--width", "--widths"} {
if !strings.Contains(ve.Hint, want) {
t.Errorf("hint should contain %q, got %q", want, ve.Hint)
@@ -294,3 +343,282 @@ func TestShortcuts_FlagErgonomicsMounted(t *testing.T) {
}
})
}
// TestShortcuts_IntuitiveFlagAliases verifies the silent-alias tier: a
// habitual name with identical value semantics parses as the real flag on a
// mounted command, costing zero round trips (eval: --cols, --file, --name,
// --source/--target each burned an unknown-flag failure plus a --help call).
func TestShortcuts_IntuitiveFlagAliases(t *testing.T) {
t.Parallel()
t.Run("cols-resize --cols parses as --range", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cols-resize")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--cols", "A:D",
"--width", "100",
"--dry-run",
})
if err != nil {
t.Fatalf("--cols should alias to --range and pass, got: %v", err)
}
if !strings.Contains(stdout, "A:D") {
t.Errorf("dry-run body should carry the aliased range, got %q", stdout)
}
})
t.Run("sheet-create --name parses as --title", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+sheet-create")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--name", "汇总",
"--dry-run",
})
if err != nil {
t.Fatalf("--name should alias to --title and pass, got: %v", err)
}
if !strings.Contains(stdout, "汇总") {
t.Errorf("dry-run body should carry the aliased title, got %q", stdout)
}
})
t.Run("sheet-rename --new-name parses as --title", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+sheet-rename")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--new-name", "授权需求清单",
"--dry-run",
})
if err != nil {
t.Fatalf("--new-name should alias to --title and pass, got: %v", err)
}
if !strings.Contains(stdout, "授权需求清单") {
t.Errorf("dry-run body should carry the aliased title, got %q", stdout)
}
})
t.Run("range-fill --source/--target parse as ranges", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+range-fill")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--source", "B2",
"--target", "B3:B10",
"--dry-run",
})
if err != nil {
t.Fatalf("--source/--target should alias to the -range flags, got: %v", err)
}
for _, want := range []string{"B2", "B3:B10"} {
if !strings.Contains(stdout, want) {
t.Errorf("dry-run body should carry %q, got %q", want, stdout)
}
}
})
t.Run("csv-put --file parses as --csv", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+csv-put")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--start-cell", "A1",
"--file", "a,b\n1,2",
"--dry-run",
})
if err != nil {
t.Fatalf("--file with CSV text should alias to --csv and pass, got: %v", err)
}
if !strings.Contains(stdout, "a,b") {
t.Errorf("dry-run body should carry the CSV text, got %q", stdout)
}
})
t.Run("cols-resize --size parses as --width", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cols-resize")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A:C",
"--size", "120",
"--dry-run",
})
if err != nil {
t.Fatalf("--size should alias to --width (styles-protocol vocabulary), got: %v", err)
}
if !strings.Contains(stdout, "120") {
t.Errorf("dry-run body should carry the pixel width 120, got %q", stdout)
}
})
t.Run("rows-resize --size parses as --height", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+rows-resize")
_, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "1:3",
"--size", "36",
"--dry-run",
})
if err != nil {
t.Fatalf("--size should alias to --height (styles-protocol vocabulary), got: %v", err)
}
})
t.Run("alias never shadows a registered flag", func(t *testing.T) {
t.Parallel()
c := &cobra.Command{Use: "+csv-put"}
c.Flags().String("csv", "", "")
c.Flags().String("file", "", "") // hypothetical real flag wins
chainFlagAliases(c)
if err := c.ParseFlags([]string{"--file", "x"}); err != nil {
t.Fatalf("parse: %v", err)
}
if got, _ := c.Flags().GetString("file"); got != "x" {
t.Errorf("registered --file should keep its own value, got %q", got)
}
if got, _ := c.Flags().GetString("csv"); got != "" {
t.Errorf("--csv must stay empty when --file is a real flag, got %q", got)
}
})
}
// TestShortcuts_IntuitiveFlagHints verifies the prescription tier: habitual
// names whose fix is not a rename answer with the exact correct form, so the
// retry needs no --help round trip (eval: +sheet-copy burned 3/3 post-error
// --help calls, +dim-insert kept failing even after reading help).
func TestShortcuts_IntuitiveFlagHints(t *testing.T) {
t.Parallel()
cases := []struct {
command string
args []string
wrong string
wantHint []string
}{
{
command: "+dim-insert",
args: []string{"--url", testURL, "--sheet-name", "s", "--dimension", "row"},
wrong: "--dimension",
wantHint: []string{"--position", "--count"},
},
{
command: "+dim-freeze",
args: []string{"--url", testURL, "--sheet-name", "s", "--frozen-rows", "2"},
wrong: "--frozen-rows",
wantHint: []string{"--dimension row --count N"},
},
{
command: "+cells-set-style",
args: []string{"--url", testURL, "--sheet-name", "s", "--range", "A1", "--bold", "true"},
wrong: "--bold",
wantHint: []string{"--font-weight bold"},
},
{
command: "+sheet-copy",
args: []string{"--url", testURL, "--sheet-name", "s", "--new-sheet-name", "副本"},
wrong: "--new-sheet-name",
wantHint: []string{"--title", "source sheet"},
},
{
command: "+table-put",
args: []string{"--url", testURL, "--sheets", "{}", "--start-cell", "B2"},
wrong: "--start-cell",
wantHint: []string{`"start_cell"`, "+csv-put"},
},
{
command: "+chart-create-basic",
args: []string{"--url", testURL, "--sheet-name", "s", "--position", "F2"},
wrong: "--position",
wantHint: []string{"--anchor-cell F2", "--width", "--height"},
},
{
command: "+chart-create-basic",
args: []string{"--url", testURL, "--sheet-name", "s", "--show-labels", "true"},
wrong: "--show-labels",
wantHint: []string{"--data-labels value", "value_percentage"},
},
{
command: "+chart-config-update",
args: []string{"--url", testURL, "--sheet-name", "s", "--show-labels", "true"},
wrong: "--show-labels",
wantHint: []string{"--data-labels value", "none"},
},
{
command: "+cells-set",
args: []string{"--url", testURL, "--sheet-name", "s", "--range", "A1", "--values", `[["x"]]`},
wrong: "--values",
wantHint: []string{"--cells", "+workbook-create"},
},
{
command: "+dim-freeze",
args: []string{"--url", testURL, "--sheet-name", "s", "--frozen-row-count", "1"},
wrong: "--frozen-row-count",
wantHint: []string{"--dimension row --count N"},
},
{
command: "+cells-set-style",
args: []string{"--url", testURL, "--sheet-name", "s", "--range", "A1", "--font-bold", "true"},
wrong: "--font-bold",
wantHint: []string{"--font-weight bold"},
},
{
command: "+cells-set-style",
args: []string{"--url", testURL, "--sheet-name", "s", "--range", "A1", "--bg-color", "#FFF"},
wrong: "--bg-color",
wantHint: []string{"--background-color"},
},
{
command: "+cells-set-style",
args: []string{"--url", testURL, "--sheet-name", "s", "--range", "A1", "--wrap-strategy", "overflow"},
wrong: "--wrap-strategy",
wantHint: []string{"--word-wrap"},
},
{
command: "+cells-set-style",
args: []string{"--url", testURL, "--sheet-name", "s", "--range", "A1", "--border-all", "thin"},
wrong: "--border-all",
wantHint: []string{"--border-styles", `"all"`},
},
{
command: "+cells-set-style",
args: []string{"--url", testURL, "--sheet-name", "s", "--range", "A1", "--border-top", "thin"},
wrong: "--border-top",
wantHint: []string{"--border-styles", `"top"`},
},
{
command: "+cells-set-style",
args: []string{"--url", testURL, "--sheet-name", "s", "--range", "A1", "--border-color", "#000"},
wrong: "--border-color",
wantHint: []string{"--border-styles", "color"},
},
}
for _, tc := range cases {
t.Run(tc.command+" "+tc.wrong, func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, tc.command)
_, _, err := runShortcutCapturingErr(t, sc, tc.args)
ve := requireValidation(t, err, "unknown flag \""+tc.wrong+"\"")
for _, want := range tc.wantHint {
if !strings.Contains(ve.Hint, want) {
t.Errorf("hint should contain %q, got %q", want, ve.Hint)
}
}
// A curated prescription must not ship contradicting edit-distance
// candidates (--font-bold used to carry --font-color/--font-line/
// --font-size in params while the fix is --font-weight).
for _, p := range ve.Params {
if len(p.Suggestions) > 0 {
t.Errorf("curated prescription should drop edit-distance suggestions, got %v", p.Suggestions)
}
}
})
}
}

View File

@@ -7,6 +7,7 @@ import (
_ "embed"
"encoding/json"
"sort"
"strings"
"sync"
"github.com/larksuite/cli/errs"
@@ -84,6 +85,13 @@ func commandsWithFlagSchema() map[string]struct{} {
// listing of introspectable flags; otherwise it returns the schema
// subtree JSON for the named flag, or an error if the flag is not
// registered.
//
// flagName also accepts a dotted path (properties.plotArea.axes): the
// first segment names the flag, the rest walk the schema's properties
// (descending through array items implicitly), returning just that
// subtree. Large schemas — chart-create's properties is ~1,750 pretty
// lines — otherwise force agents to page through the full dump for one
// nested field; eval traces show 25 such round trips in one batch.
func printFlagSchemaFor(command string) func(flagName string) ([]byte, error) {
return func(flagName string) ([]byte, error) {
idx, err := loadFlagSchemas()
@@ -103,10 +111,19 @@ func printFlagSchemaFor(command string) func(flagName string) ([]byte, error) {
return json.MarshalIndent(map[string]interface{}{
"shortcut": command,
"introspectable_flags": flags,
"hint": "run again with --flag-name <name> to dump the JSON Schema for that flag",
"hint": "run again with --flag-name <name> to dump that flag's JSON Schema, or a dotted path like <name>.plotArea.axes to dump just one subtree",
}, "", " ")
}
schema, ok := entry[flagName]
name, path := splitSchemaPath(flagName)
schema, ok := entry[name]
if !ok {
// Tolerate the wire-vocabulary underscore form (--flag-name
// border_styles for border-styles) — agents copy field names out
// of JSON payloads where underscores are canonical.
if alt := strings.ReplaceAll(name, "_", "-"); alt != name {
schema, ok = entry[alt]
}
}
if !ok {
flags := make([]string, 0, len(entry))
for f := range entry {
@@ -114,14 +131,133 @@ func printFlagSchemaFor(command string) func(flagName string) ([]byte, error) {
}
sort.Strings(flags)
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument,
"no JSON Schema registered for %s --%s; available: %v", command, flagName, flags).
"no JSON Schema registered for %s --%s; available: %v", command, name, flags).
WithParam("--flag-name")
}
// Reformat for readability — schema files store compact JSON.
var pretty interface{}
if err := json.Unmarshal(schema, &pretty); err != nil {
return nil, err
}
if len(path) > 0 {
pretty, err = sliceSchemaByPath(pretty, name, path)
if err != nil {
return nil, err
}
}
// Reformat for readability — schema files store compact JSON.
return json.MarshalIndent(pretty, "", " ")
}
}
// splitSchemaPath splits a --flag-name value into the flag name and the
// optional dotted schema path after it.
func splitSchemaPath(flagName string) (string, []string) {
parts := strings.Split(flagName, ".")
return parts[0], parts[1:]
}
// sliceSchemaByPath walks a decoded JSON Schema along dotted path segments.
// Each segment matches a key under "properties"; array levels are descended
// implicitly through "items" (an explicit "items" segment also works), and
// oneOf / anyOf branches are searched for the first one carrying the key. A miss
// errors with the keys actually available at that level so the caller can
// re-issue the path without a full dump.
func sliceSchemaByPath(schema interface{}, flagName string, path []string) (interface{}, error) {
node := schema
walked := flagName
for _, seg := range path {
next, ok := schemaChild(node, seg)
if !ok {
return nil, errs.NewValidationError(errs.SubtypeInvalidArgument,
"no %q under %s; available keys: %v", seg, walked, schemaChildKeys(node)).
WithParam("--flag-name")
}
node = next
walked += "." + seg
}
return node, nil
}
// schemaChild resolves one path segment against a schema node, descending
// through items / oneOf / anyOf wrappers as needed.
func schemaChild(node interface{}, seg string) (interface{}, bool) {
for depth := 0; depth < 8; depth++ {
m, ok := node.(map[string]interface{})
if !ok {
return nil, false
}
if seg == "items" {
if items, ok := m["items"]; ok {
return items, true
}
}
if props, ok := m["properties"].(map[string]interface{}); ok {
if child, ok := props[seg]; ok {
return child, true
}
}
if items, ok := m["items"]; ok {
node = items
continue
}
if branches, ok := m["oneOf"].([]interface{}); ok {
for _, b := range branches {
if child, ok := schemaChild(b, seg); ok {
return child, true
}
}
}
if branches, ok := m["anyOf"].([]interface{}); ok {
for _, b := range branches {
if child, ok := schemaChild(b, seg); ok {
return child, true
}
}
}
return nil, false
}
return nil, false
}
// schemaChildKeys lists the property keys reachable at a schema node (through
// items / oneOf / anyOf wrappers), for the path-miss error.
func schemaChildKeys(node interface{}) []string {
seen := map[string]struct{}{}
var collect func(n interface{}, depth int)
collect = func(n interface{}, depth int) {
if depth > 8 {
return
}
m, ok := n.(map[string]interface{})
if !ok {
return
}
if props, ok := m["properties"].(map[string]interface{}); ok {
for k := range props {
seen[k] = struct{}{}
}
return
}
if items, ok := m["items"]; ok {
collect(items, depth+1)
return
}
if branches, ok := m["oneOf"].([]interface{}); ok {
for _, b := range branches {
collect(b, depth+1)
}
}
if branches, ok := m["anyOf"].([]interface{}); ok {
for _, b := range branches {
collect(b, depth+1)
}
}
}
collect(node, 0)
keys := make([]string, 0, len(seen))
for k := range seen {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}

View File

@@ -9,6 +9,8 @@ import (
"fmt"
"sort"
"strings"
"github.com/larksuite/cli/internal/suggest"
)
// ─── schema-driven flag validation ────────────────────────────────────
@@ -94,7 +96,15 @@ func validateValueAgainstSchema(fv flagView, name string, value interface{}) err
}
var schema schemaProperty
json.Unmarshal(raw, &schema)
if vErr := validateAgainstSchema(value, &schema, ""); vErr != nil {
c := &schemaErrorCollector{}
collectSchemaErrors(value, &schema, "", c)
if len(c.errs) == 0 {
return nil
}
vErr := c.errs[0]
if len(c.errs) == 1 {
// Single failure keeps the historical message byte-for-byte.
//
// Composite-JSON shape errors (e.g. +cells-set --cells, chart
// --properties) are the highest-frequency usage-layer failure for
// sheets, and agents often burn several retries guessing the shape.
@@ -106,19 +116,69 @@ func validateValueAgainstSchema(fv flagView, name string, value interface{}) err
// exact JSON Schema for this (command, flag) pair; reaching this
// branch means entry[name] resolved a schema from the embedded
// index, so the suggested command is guaranteed to print it.
// An enum-bearing field states its own contract far better than a
// whole-payload skeleton, at any depth: --border-styles with
// weight:1 used to answer with {"bottom": {…}, "left": {…}, …},
// which says nothing about thin/medium/thick. Let those fall
// through to the hintSuffix path below, which names the enum.
var tm *typeMismatchError
if errors.As(vErr, &tm) && pathDepth(tm.path) <= skeletonPathDepthLimit {
isTypeMismatch := errors.As(vErr, &tm)
if isTypeMismatch && len(tm.enum) == 0 && pathDepth(tm.path) <= skeletonPathDepthLimit {
if sk := schemaSkeleton(&schema, skeletonMaxDepth); sk != "" {
return sheetsValidationForFlag(name,
"--%s: %s; expected shape: %s (run `lark-cli sheets %s --print-schema --flag-name %s` for the full JSON Schema)",
name, vErr.Error(), sk, command, name).WithCause(vErr)
}
}
// Deep type mismatches don't get a whole-shape skeleton (it wouldn't
// address the actual field), but if the field itself carries an enum /
// description, append that one line — same "fix on first retry" goal.
msg := vErr.Error()
if isTypeMismatch {
if suffix := tm.hintSuffix(); suffix != "" {
msg += "; " + suffix
}
}
return sheetsValidationForFlag(name,
"--%s: %s; run `lark-cli sheets %s --print-schema --flag-name %s` to see the expected JSON Schema",
name, vErr.Error(), command, name).WithCause(vErr)
name, msg, command, name).WithCause(vErr)
}
return nil
// Multiple failures: report them all at once (numbered, each with its
// own inline teaching hint) so the agent fixes the whole payload in one
// retry instead of the fail-fast "fix one, hit the next" loop.
return sheetsValidationForFlag(name,
"--%s: %s; run `lark-cli sheets %s --print-schema --flag-name %s` to see the expected JSON Schema",
name, formatSchemaErrorList(c.errs), command, name).WithCause(vErr)
}
// formatSchemaErrorList renders collected failures as a numbered one-line
// list: "N validation errors: 1) …; 2) …". Type-mismatch entries carry
// their enum/description suffix just like the single-error path. Entries
// beyond schemaErrorDisplayLimit collapse into a "(more …)" tail — the
// collector stops at cap, so the exact total is unknown by design.
func formatSchemaErrorList(errs []error) string {
shown := errs
truncated := false
if len(shown) > schemaErrorDisplayLimit {
shown = shown[:schemaErrorDisplayLimit]
truncated = true
}
parts := make([]string, 0, len(shown))
for i, e := range shown {
msg := e.Error()
var tm *typeMismatchError
if errors.As(e, &tm) {
if suffix := tm.hintSuffix(); suffix != "" {
msg += "; " + suffix
}
}
parts = append(parts, fmt.Sprintf("%d) %s", i+1, msg))
}
out := fmt.Sprintf("%d validation errors: %s", len(shown), strings.Join(parts, "; "))
if truncated {
out = fmt.Sprintf("%d+ validation errors: %s; (more errors not shown — fix these first)", schemaErrorDisplayLimit, strings.Join(parts, "; "))
}
return out
}
// validateInputAgainstSchema validates input[flag] for every flag the
@@ -187,8 +247,10 @@ var inputSchemaSkip = map[string]struct{}{
}
// schemaProperty mirrors the JSON Schema subset used by
// data/flag-schemas.json. Unknown keys (description, …) are dropped —
// they're documentation.
// data/flag-schemas.json. Description is retained (not just documentation)
// so a required-missing or type-mismatch error can inline the one-line
// field doc — the agent then fixes the input without a --print-schema round
// trip. Other unknown keys stay dropped.
//
// Minimum / Maximum / MinItems / MaxItems use *float64 / *int because
// 0 is a meaningful bound (e.g. chart row >= 0); nil distinguishes
@@ -204,6 +266,7 @@ var inputSchemaSkip = map[string]struct{}{
// map<string, array<string>> fields (groups / collapse).
type schemaProperty struct {
Type string `json:"type"`
Description string `json:"description"`
Nullable bool `json:"nullable"`
Enum []interface{} `json:"enum"`
Properties map[string]*schemaProperty `json:"properties"`
@@ -242,20 +305,66 @@ func (a *additionalProps) UnmarshalJSON(data []byte) error {
return nil
}
// schemaErrorCollector accumulates validation failures during one full
// traversal so the caller can report every problem in a single reply
// instead of the fail-fast "fix one, retry, hit the next" loop. Capacity
// is bounded (collectSchemaErrorsCap) so a pathological payload — e.g. a
// 5000-row --cells array where every cell is malformed — cannot balloon
// the error message or the traversal cost: once full, collection
// short-circuits everywhere via full().
type schemaErrorCollector struct {
errs []error
}
// collectSchemaErrorsCap bounds how many errors one traversal gathers:
// schemaErrorDisplayLimit entries are rendered; one extra is collected
// only to know that truncation happened.
const (
schemaErrorDisplayLimit = 5
collectSchemaErrorsCap = schemaErrorDisplayLimit + 1
)
func (c *schemaErrorCollector) add(err error) {
if len(c.errs) < collectSchemaErrorsCap {
c.errs = append(c.errs, err)
}
}
func (c *schemaErrorCollector) full() bool { return len(c.errs) >= collectSchemaErrorsCap }
// validateAgainstSchema recursively checks `value` against `schema`,
// prefixing any failure with the JSON path navigated so far.
// prefixing any failure with the JSON path navigated so far. It reports
// only the first failure — callers that want the full list (the
// error-as-teaching aggregate path) use collectSchemaErrors directly.
func validateAgainstSchema(value interface{}, schema *schemaProperty, path string) error {
if schema == nil {
return nil // defensive — current callers always pass &schema, but
// keeps validator safe for future programmatic construction.
c := &schemaErrorCollector{}
collectSchemaErrors(value, schema, path, c)
if len(c.errs) == 0 {
return nil
}
return c.errs[0]
}
// collectSchemaErrors is the traversal engine behind validateAgainstSchema:
// same checks, same messages, same deterministic order, but it keeps
// walking after a failure and appends every problem to the collector
// (until cap). Two deliberate exceptions to "keep walking":
// - a type mismatch stops descent into that node (its children would
// produce cascading nonsense against the wrong-typed value);
// - oneOf alternatives are probed with throwaway collectors (a failed
// alternative is not an error when a later one matches).
func collectSchemaErrors(value interface{}, schema *schemaProperty, path string, c *schemaErrorCollector) {
if schema == nil || c.full() {
return
}
if value == nil && schema.Nullable {
return nil
return
}
if schema.Type != "" {
if !matchesJSONType(value, schema.Type) {
return &typeMismatchError{path: path, expected: schema.Type, got: jsType(value)}
c.add(&typeMismatchError{path: path, expected: schema.Type, got: jsType(value), enum: schema.Enum, description: schema.Description})
return // wrong container type — descending would cascade nonsense.
}
}
@@ -263,20 +372,20 @@ func validateAgainstSchema(value interface{}, schema *schemaProperty, path strin
// already reported above). Apply to both `number` and `integer` types.
if num, ok := value.(float64); ok {
if schema.Minimum != nil && num < *schema.Minimum {
return fmt.Errorf("%svalue %v is below minimum %v", pathPrefix(path), num, *schema.Minimum) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
c.add(fmt.Errorf("%svalue %v is below minimum %v", pathPrefix(path), num, *schema.Minimum)) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
}
if schema.Maximum != nil && num > *schema.Maximum {
return fmt.Errorf("%svalue %v is above maximum %v", pathPrefix(path), num, *schema.Maximum) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
c.add(fmt.Errorf("%svalue %v is above maximum %v", pathPrefix(path), num, *schema.Maximum)) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
}
}
// Array length bounds — only checked when value is an array.
if arr, ok := value.([]interface{}); ok {
if schema.MinItems != nil && len(arr) < *schema.MinItems {
return fmt.Errorf("%sarray has %d items, minimum is %d", pathPrefix(path), len(arr), *schema.MinItems) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
c.add(fmt.Errorf("%sarray has %d items, minimum is %d", pathPrefix(path), len(arr), *schema.MinItems)) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
}
if schema.MaxItems != nil && len(arr) > *schema.MaxItems {
return fmt.Errorf("%sarray has %d items, maximum is %d", pathPrefix(path), len(arr), *schema.MaxItems) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
c.add(fmt.Errorf("%sarray has %d items, maximum is %d", pathPrefix(path), len(arr), *schema.MaxItems)) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
}
}
@@ -294,20 +403,22 @@ func validateAgainstSchema(value interface{}, schema *schemaProperty, path strin
if hint := suggestEnumForError(value, schema.Enum); hint != "" {
msg += fmt.Sprintf(` (did you mean %q?)`, hint)
}
return fmt.Errorf("%s", msg) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
c.add(fmt.Errorf("%s", msg)) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
}
}
if len(schema.OneOf) > 0 {
matched := false
for _, sub := range schema.OneOf {
if validateAgainstSchema(value, sub, path) == nil {
probe := &schemaErrorCollector{}
collectSchemaErrors(value, sub, path, probe)
if len(probe.errs) == 0 {
matched = true
break
}
}
if !matched {
return fmt.Errorf("%svalue does not match any of oneOf alternatives", pathPrefix(path)) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
c.add(fmt.Errorf("%svalue does not match any of oneOf alternatives", pathPrefix(path))) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
}
}
@@ -316,8 +427,18 @@ func validateAgainstSchema(value interface{}, schema *schemaProperty, path strin
// the schema also describes their per-key shape via `properties`.
if obj, ok := value.(map[string]interface{}); ok {
for _, key := range schema.Required {
if c.full() {
return
}
if _, present := obj[key]; !present {
return fmt.Errorf("required property %q is missing at %s", key, pathOrRoot(path)) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
msg := fmt.Sprintf("required property %q is missing at %s", key, pathOrRoot(path))
// Inline the missing field's type / one-line description / enum so
// the agent supplies a correctly-shaped value on the first retry
// instead of fetching the full schema.
if hint := schemaFieldHint(schema.Properties[key]); hint != "" {
msg += "; expected " + hint
}
c.add(fmt.Errorf("%s", msg)) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
}
}
if schema.Properties != nil {
@@ -327,6 +448,9 @@ func validateAgainstSchema(value interface{}, schema *schemaProperty, path strin
}
sort.Strings(keys)
for _, key := range keys {
if c.full() {
return
}
sub := schema.Properties[key]
v, present := obj[key]
if !present {
@@ -350,14 +474,12 @@ func validateAgainstSchema(value interface{}, schema *schemaProperty, path strin
if path != "" {
child = path + "." + key
}
if err := validateAgainstSchema(v, sub, child); err != nil {
return err
}
collectSchemaErrors(v, sub, child, c)
}
}
// additionalProperties: enforce only when explicitly declared.
// Absent means lenient (matches the file header's stance). Sort
// extras so the first rejection is deterministic across runs.
// extras so rejection order is deterministic across runs.
if schema.AdditionalProperties != nil {
extras := make([]string, 0)
for key := range obj {
@@ -368,17 +490,29 @@ func validateAgainstSchema(value interface{}, schema *schemaProperty, path strin
}
sort.Strings(extras)
for _, key := range extras {
if c.full() {
return
}
if schema.AdditionalProperties.Strict {
return fmt.Errorf("%sunexpected property %q (not declared in schema)", pathPrefix(path), key) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
msg := fmt.Sprintf("%sunexpected property %q (not declared in schema)", pathPrefix(path), key)
// Inline the node's declared keys (and a did-you-mean when the
// unknown key is a near miss) so the agent renames it in one
// retry instead of a --print-schema round trip.
if legal := sortedSchemaPropertyKeys(schema.Properties); len(legal) > 0 {
if guess := suggest.Closest(key, legal, 1); len(guess) > 0 {
msg += fmt.Sprintf(` (did you mean %q?)`, guess[0])
}
msg += "; valid properties: " + formatPropertyKeyList(legal)
}
c.add(fmt.Errorf("%s", msg)) //nolint:forbidigo // intermediate error; validateFlagAgainstSchema wraps it into a typed flag validation error with a --print-schema hint
continue
}
if schema.AdditionalProperties.Schema != nil {
child := key
if path != "" {
child = path + "." + key
}
if err := validateAgainstSchema(obj[key], schema.AdditionalProperties.Schema, child); err != nil {
return err
}
collectSchemaErrors(obj[key], schema.AdditionalProperties.Schema, child, c)
}
}
}
@@ -387,33 +521,50 @@ func validateAgainstSchema(value interface{}, schema *schemaProperty, path strin
if schema.Type == "array" && schema.Items != nil {
arr, ok := value.([]interface{})
if !ok {
return nil // type mismatch already reported above.
return // type mismatch already reported above.
}
for i, item := range arr {
child := fmt.Sprintf("%s[%d]", path, i)
if err := validateAgainstSchema(item, schema.Items, child); err != nil {
return err
if c.full() {
return
}
child := fmt.Sprintf("%s[%d]", path, i)
collectSchemaErrors(item, schema.Items, child, c)
}
}
return nil
}
// typeMismatchError is the type-check branch of validateAgainstSchema
// as a typed error, so validateValueAgainstSchema can recognize shape
// confusion (vs. deep value errors) and inline a skeleton of the
// expected shape. Error() keeps the exact legacy wording.
// expected shape. Error() keeps the exact legacy wording; enum /
// description ride alongside for the deep-mismatch hintSuffix, so they
// never leak into the shallow-skeleton message.
type typeMismatchError struct {
path string
expected string
got string
path string
expected string
got string
enum []interface{}
description string
}
func (e *typeMismatchError) Error() string {
return fmt.Sprintf("%sexpected type %q, got %q", pathPrefix(e.path), e.expected, e.got)
}
// hintSuffix renders the field's description / enum as a one-line tail for
// the deep type-mismatch fallback (type is already stated by Error()).
// Empty when the field declares neither.
func (e *typeMismatchError) hintSuffix() string {
var parts []string
if d := oneLineDescription(e.description); d != "" {
parts = append(parts, "description: "+d)
}
if len(e.enum) > 0 {
parts = append(parts, "one of "+formatEnum(e.enum))
}
return strings.Join(parts, ", ")
}
// pathDepth counts how many levels below the flag root a JSON path
// points at: "" → 0, "[0]" → 1, "[0][3]" → 2, "[0][3].value" → 3,
// "legend" → 1, "snapshot.axes" → 2. Every "[" and "." starts a new
@@ -605,6 +756,70 @@ func joinFormatted(values []interface{}) string {
return strings.Join(parts, ", ")
}
// schemaFieldHint renders a compact one-line "type X, description: …, one of
// […]" sketch of a single field's schema, used to enrich a required-missing
// error so the agent supplies a correctly-shaped value without --print-schema.
// Empty when the field declares none of type / description / enum.
func schemaFieldHint(s *schemaProperty) string {
if s == nil {
return ""
}
var parts []string
if s.Type != "" {
parts = append(parts, fmt.Sprintf("type %q", s.Type))
}
if d := oneLineDescription(s.Description); d != "" {
parts = append(parts, "description: "+d)
}
if len(s.Enum) > 0 {
parts = append(parts, "one of "+formatEnum(s.Enum))
}
return strings.Join(parts, ", ")
}
// sortedSchemaPropertyKeys returns the declared property names in a stable
// (sorted) order so the valid-property list in a strict unexpected-property
// error is deterministic across runs.
func sortedSchemaPropertyKeys(props map[string]*schemaProperty) []string {
keys := make([]string, 0, len(props))
for k := range props {
keys = append(keys, k)
}
sort.Strings(keys)
return keys
}
// propertyKeyDisplayLimit caps how many declared property names ride inline on
// a strict unexpected-property error, so a wide object doesn't bury the actual
// error under a wall of keys. Overflow is summarised as "(N more)".
const propertyKeyDisplayLimit = 15
func formatPropertyKeyList(keys []string) string {
if len(keys) <= propertyKeyDisplayLimit {
return "[" + strings.Join(keys, ", ") + "]"
}
shown := keys[:propertyKeyDisplayLimit]
return fmt.Sprintf("[%s, … (%d more)]", strings.Join(shown, ", "), len(keys)-propertyKeyDisplayLimit)
}
// descriptionMaxLen bounds an inlined field description to one reasonable line;
// schema descriptions can run several sentences, which would swamp the error.
const descriptionMaxLen = 120
// oneLineDescription collapses a (possibly multi-line) schema description into
// a single whitespace-normalised line, truncated to descriptionMaxLen runes.
// Returns "" for an empty / whitespace-only description.
func oneLineDescription(s string) string {
collapsed := strings.Join(strings.Fields(s), " ")
if collapsed == "" {
return ""
}
if r := []rune(collapsed); len(r) > descriptionMaxLen {
return string(r[:descriptionMaxLen]) + "…"
}
return collapsed
}
// suggestEnumMatch returns the canonical enum entry when the user's
// value unambiguously means one — casing ("SUM" vs "sum", "True" vs
// "true") or a cross-vocabulary alias (CSS "center" for Lark's vertical

View File

@@ -5,6 +5,8 @@ package sheets
import (
"encoding/json"
"errors"
"fmt"
"strings"
"testing"
)
@@ -438,6 +440,373 @@ func TestValidateValueAgainstSchema_ShapeSkeletonOnShallowTypeMismatch(t *testin
}
}
// TestValidateAgainstSchema_StrictUnexpectedPropertyListsKeys pins the strict
// additionalProperties:false enhancement: the error lists the node's legal
// property keys (sorted, capped at 15 with an "(N more)" overflow) and, when
// the unknown key is a near miss, appends a did-you-mean.
func TestValidateAgainstSchema_StrictUnexpectedPropertyListsKeys(t *testing.T) {
t.Parallel()
t.Run("lists legal keys and suggests a near miss", func(t *testing.T) {
t.Parallel()
schema := parseSchema(t, `{
"type":"object",
"additionalProperties":false,
"properties":{
"background_color":{"type":"string"},
"font_weight":{"type":"string"},
"font_size":{"type":"integer"}
}
}`)
err := validateAgainstSchema(map[string]interface{}{"background_colour": "#fff"}, schema, "")
if err == nil {
t.Fatal("unknown key under strict schema must fail")
}
msg := err.Error()
if !strings.Contains(msg, `unexpected property "background_colour"`) {
t.Errorf("want the offending key named; got %q", msg)
}
if !strings.Contains(msg, `did you mean "background_color"?`) {
t.Errorf("want a did-you-mean for the near miss; got %q", msg)
}
for _, want := range []string{"valid properties:", "background_color", "font_size", "font_weight"} {
if !strings.Contains(msg, want) {
t.Errorf("want valid-property list to contain %q; got %q", want, msg)
}
}
})
t.Run("no did-you-mean for an unrelated key", func(t *testing.T) {
t.Parallel()
schema := parseSchema(t, `{
"type":"object",
"additionalProperties":false,
"properties":{"background_color":{"type":"string"}}
}`)
err := validateAgainstSchema(map[string]interface{}{"zzzzzzzz": 1}, schema, "")
if err == nil {
t.Fatal("unknown key must fail")
}
if strings.Contains(err.Error(), "did you mean") {
t.Errorf("unrelated key should get no suggestion; got %q", err.Error())
}
if !strings.Contains(err.Error(), "valid properties: [background_color]") {
t.Errorf("want the valid-property list; got %q", err.Error())
}
})
t.Run("wide object truncates the key list with overflow", func(t *testing.T) {
t.Parallel()
props := make([]string, 0, 20)
for i := 0; i < 20; i++ {
props = append(props, fmt.Sprintf(`"k%02d":{"type":"string"}`, i))
}
schema := parseSchema(t, `{"type":"object","additionalProperties":false,"properties":{`+strings.Join(props, ",")+`}}`)
err := validateAgainstSchema(map[string]interface{}{"nope": 1}, schema, "")
if err == nil {
t.Fatal("unknown key must fail")
}
if !strings.Contains(err.Error(), "(5 more)") { // 20 keys, cap 15
t.Errorf("want overflow marker '(5 more)'; got %q", err.Error())
}
})
}
// TestValidateAgainstSchema_RequiredMissingInlinesFieldHint pins that a
// required-property-missing error inlines the field's type / one-line
// description / enum when the schema describes that field.
func TestValidateAgainstSchema_RequiredMissingInlinesFieldHint(t *testing.T) {
t.Parallel()
schema := parseSchema(t, `{
"type":"object",
"required":["operation"],
"properties":{
"operation":{
"type":"string",
"description":"Which mutation to run.",
"enum":["insert","delete","move"]
}
}
}`)
err := validateAgainstSchema(map[string]interface{}{}, schema, "")
if err == nil {
t.Fatal("missing required property must fail")
}
msg := err.Error()
for _, want := range []string{
`required property "operation"`,
`type "string"`,
"description: Which mutation to run.",
`one of ["insert", "delete", "move"]`,
} {
if !strings.Contains(msg, want) {
t.Errorf("want %q in required-missing error; got %q", want, msg)
}
}
}
// TestValidateAgainstSchema_RequiredMissingNoSchemaStaysPlain pins that a
// missing required key with no describing schema keeps the plain legacy
// message (no trailing "expected ...").
func TestValidateAgainstSchema_RequiredMissingNoSchemaStaysPlain(t *testing.T) {
t.Parallel()
schema := parseSchema(t, `{"type":"object","required":["a"]}`)
err := validateAgainstSchema(map[string]interface{}{}, schema, "")
if err == nil {
t.Fatal("missing required must fail")
}
if strings.Contains(err.Error(), "; expected") {
t.Errorf("no field schema → no inlined hint; got %q", err.Error())
}
}
// TestValidateValueAgainstSchema_DeepTypeMismatchAppendsEnum pins that a deep
// type mismatch (past the skeleton depth limit) still gets no whole-shape
// skeleton, but appends the field's enum / description one-liner.
func TestValidateValueAgainstSchema_DeepTypeMismatchAppendsEnum(t *testing.T) {
t.Parallel()
// A wrong-typed value three levels deep where the field is an enum string.
schema := parseSchema(t, `{
"type":"array",
"items":{"type":"array","items":{"type":"object","properties":{
"align":{"type":"string","description":"Text alignment.","enum":["left","center","right"]}
}}}
}`)
deep := parseValue(t, `[[{"align":42}]]`)
err := validateAgainstSchema(deep, schema, "")
if err == nil {
t.Fatal("wrong type for align must fail")
}
var tm *typeMismatchError
if !errors.As(err, &tm) {
t.Fatalf("want *typeMismatchError, got %T", err)
}
suffix := tm.hintSuffix()
for _, want := range []string{"description: Text alignment.", `one of ["left", "center", "right"]`} {
if !strings.Contains(suffix, want) {
t.Errorf("want %q in hintSuffix; got %q", want, suffix)
}
}
}
// TestSchemaFieldHint covers the single-field sketch used by
// required-missing errors: each of type / description / enum contributes
// its own segment, absent parts are simply skipped, and a nil / empty
// schema yields no hint at all.
func TestSchemaFieldHint(t *testing.T) {
t.Parallel()
cases := []struct {
name string
schema *schemaProperty
want string
}{
{"nil schema", nil, ""},
{"empty schema", &schemaProperty{}, ""},
{"type only", &schemaProperty{Type: "string"}, `type "string"`},
{"description only", &schemaProperty{Description: "Cell note."}, "description: Cell note."},
{"enum only", &schemaProperty{Enum: []interface{}{"a", "b"}}, `one of ["a", "b"]`},
{
"all three",
&schemaProperty{Type: "string", Description: "段类型", Enum: []interface{}{"text", "link"}},
`type "string", description: 段类型, one of ["text", "link"]`,
},
}
for _, tc := range cases {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
if got := schemaFieldHint(tc.schema); got != tc.want {
t.Errorf("schemaFieldHint = %q, want %q", got, tc.want)
}
})
}
}
// TestFormatPropertyKeyList_Boundaries pins the display cap edges: exactly
// at the cap nothing is folded, one past the cap folds into "(1 more)".
func TestFormatPropertyKeyList_Boundaries(t *testing.T) {
t.Parallel()
keys := make([]string, 0, propertyKeyDisplayLimit+1)
for i := 0; i < propertyKeyDisplayLimit; i++ {
keys = append(keys, fmt.Sprintf("k%02d", i))
}
if got := formatPropertyKeyList(keys); strings.Contains(got, "more)") {
t.Errorf("exactly %d keys must not fold, got %q", propertyKeyDisplayLimit, got)
}
keys = append(keys, "overflow")
if got := formatPropertyKeyList(keys); !strings.Contains(got, "(1 more)") {
t.Errorf("%d keys should fold into '(1 more)', got %q", propertyKeyDisplayLimit+1, got)
}
}
// TestTypeMismatchHintSuffix_EmptyWhenUndeclared pins that a field with
// neither enum nor description adds no suffix — the deep-mismatch fallback
// message must stay byte-identical to the legacy wording in that case.
func TestTypeMismatchHintSuffix_EmptyWhenUndeclared(t *testing.T) {
t.Parallel()
tm := &typeMismatchError{path: "a.b", expected: "string", got: "number"}
if got := tm.hintSuffix(); got != "" {
t.Errorf("no enum/description → empty suffix, got %q", got)
}
}
// TestValidateAgainstSchema_StrictUnexpectedProperty_CaseOnlyTypo pins the
// did-you-mean for a key that differs from a legal one only in casing /
// underscore style — a high-frequency LLM slip.
func TestValidateAgainstSchema_StrictUnexpectedProperty_CaseOnlyTypo(t *testing.T) {
t.Parallel()
schema := parseSchema(t, `{
"type":"object",
"additionalProperties":false,
"properties":{"background_color":{"type":"string"}}
}`)
err := validateAgainstSchema(map[string]interface{}{"Background_Color": "#fff"}, schema, "")
if err == nil {
t.Fatal("case-typo key under strict schema must fail")
}
if !strings.Contains(err.Error(), `did you mean "background_color"?`) {
t.Errorf("want case-insensitive did-you-mean; got %q", err.Error())
}
}
// TestValidateValueAgainstSchema_RequiredMissingRealSchema replays 场景3
// of the doubao case against the real embedded flag-schemas.json: a
// rich_text segment without "type" must inline the field's type, enum and
// description while keeping the --print-schema pointer.
func TestValidateValueAgainstSchema_RequiredMissingRealSchema(t *testing.T) {
t.Parallel()
fv := mapFlagView{command: "+cells-set"}
value := parseValue(t, `[[{"rich_text":[{"text":"x"}]}]]`)
err := validateValueAgainstSchema(fv, "cells", value)
if err == nil {
t.Fatal("rich_text without type must fail against the embedded schema")
}
msg := err.Error()
for _, want := range []string{
`required property "type" is missing`,
`expected type "string"`,
"one of [",
`"text"`,
"--print-schema",
} {
if !strings.Contains(msg, want) {
t.Errorf("want %q in real-schema required-missing error; got %q", want, msg)
}
}
}
// TestValidateValueAgainstSchema_DeepMismatchRealSchema replays 场景4: a
// numeric rich_text "type" three levels deep gets the field's enum inline
// (no whole-shape skeleton), still with the --print-schema pointer.
func TestValidateValueAgainstSchema_DeepMismatchRealSchema(t *testing.T) {
t.Parallel()
fv := mapFlagView{command: "+cells-set"}
value := parseValue(t, `[[{"rich_text":[{"type":42,"text":"x"}]}]]`)
err := validateValueAgainstSchema(fv, "cells", value)
if err == nil {
t.Fatal("numeric rich_text type must fail against the embedded schema")
}
msg := err.Error()
for _, want := range []string{
`expected type "string", got "number"`,
"one of [",
`"text"`,
"--print-schema",
} {
if !strings.Contains(msg, want) {
t.Errorf("want %q in real-schema deep-mismatch error; got %q", want, msg)
}
}
if strings.Contains(msg, "expected shape:") {
t.Errorf("deep mismatch must not inline a skeleton; got %q", msg)
}
}
// TestValidateValueAgainstSchema_AggregatesMultipleErrors pins the
// aggregate path: a payload with several independent problems reports them
// all in one numbered reply (each with its own teaching hint) instead of
// the fail-fast fix-one-retry-hit-the-next loop.
func TestValidateValueAgainstSchema_AggregatesMultipleErrors(t *testing.T) {
t.Parallel()
fv := mapFlagView{command: "+cells-set"}
// Two independent problems in one --cells payload: cell[0][0].rich_text[0]
// misses required "type"; cell[0][1].note has the wrong type.
value := parseValue(t, `[[{"rich_text":[{"text":"x"}]},{"note":12.5}]]`)
err := validateValueAgainstSchema(fv, "cells", value)
if err == nil {
t.Fatal("payload with two problems must fail")
}
msg := err.Error()
for _, want := range []string{
"2 validation errors:",
`1) required property "type" is missing`,
`one of ["text"`, // teaching hint rides along in aggregate mode too
`2) [0][1].note: expected type "string"`,
"--print-schema",
} {
if !strings.Contains(msg, want) {
t.Errorf("want %q in aggregated error; got %q", want, msg)
}
}
}
// TestValidateValueAgainstSchema_AggregateCapTruncates pins the display
// cap: a pathological payload reports schemaErrorDisplayLimit entries and
// an explicit truncation tail, never the full flood.
func TestValidateValueAgainstSchema_AggregateCapTruncates(t *testing.T) {
t.Parallel()
fv := mapFlagView{command: "+cells-set"}
// Seven cells all missing required rich_text "type" → 7 independent errors.
row := make([]string, 0, 7)
for i := 0; i < 7; i++ {
row = append(row, `{"rich_text":[{"text":"x"}]}`)
}
value := parseValue(t, `[[`+strings.Join(row, ",")+`]]`)
err := validateValueAgainstSchema(fv, "cells", value)
if err == nil {
t.Fatal("payload with seven problems must fail")
}
msg := err.Error()
if !strings.Contains(msg, "5+ validation errors:") {
t.Errorf("want capped header '5+ validation errors:'; got %q", msg)
}
if !strings.Contains(msg, "more errors not shown") {
t.Errorf("want truncation tail; got %q", msg)
}
if strings.Contains(msg, "6)") {
t.Errorf("must not render entries beyond the display limit; got %q", msg)
}
}
// TestCollectSchemaErrors_OneOfProbeDoesNotLeak pins that failed oneOf
// alternatives don't leak probe errors into the caller's collector when a
// later alternative matches.
func TestCollectSchemaErrors_OneOfProbeDoesNotLeak(t *testing.T) {
t.Parallel()
schema := parseSchema(t, `{"oneOf":[{"type":"string"},{"type":"number"}]}`)
c := &schemaErrorCollector{}
collectSchemaErrors(42.0, schema, "", c)
if len(c.errs) != 0 {
t.Errorf("number matches the second oneOf alternative; want no errors, got %v", c.errs)
}
}
func TestOneLineDescription(t *testing.T) {
t.Parallel()
if got := oneLineDescription(" "); got != "" {
t.Errorf("whitespace-only → empty, got %q", got)
}
if got := oneLineDescription("line one\n line two"); got != "line one line two" {
t.Errorf("multi-line collapse = %q", got)
}
long := strings.Repeat("x", 200)
got := oneLineDescription(long)
if !strings.HasSuffix(got, "…") || len([]rune(got)) != descriptionMaxLen+1 {
t.Errorf("long description should truncate to %d runes + ellipsis, got %d", descriptionMaxLen, len([]rune(got)))
}
}
func TestPathDepth(t *testing.T) {
t.Parallel()
cases := []struct {

View File

@@ -13,6 +13,8 @@ package sheets
// on --print-schema or when validating a command that is in this set. Do not
// hand-edit; regenerate with `go generate ./shortcuts/sheets/...`.
var commandsWithSchema = map[string]struct{}{
"+batch-chart-create": {},
"+batch-chart-update": {},
"+batch-update": {},
"+cells-batch-set-style": {},
"+cells-set": {},
@@ -34,6 +36,7 @@ var commandsWithSchema = map[string]struct{}{
"+rows-resize": {},
"+sparkline-create": {},
"+sparkline-update": {},
"+styles-put": {},
"+table-put": {},
"+workbook-create": {},
}

View File

@@ -133,6 +133,16 @@ func (m mapFlagView) lookupRawWithKey(name string) (string, interface{}, bool) {
return key, v, true
}
}
for alias, target := range commandFlagAliases[m.command] {
if target != name {
continue
}
for _, key := range []string{alias, strings.ReplaceAll(alias, "-", "_")} {
if v, ok := m.raw[key]; ok {
return key, v, true
}
}
}
return "", nil, false
}

View File

@@ -11,7 +11,6 @@ import (
"context"
"encoding/json"
"errors"
"fmt"
neturl "net/url"
"strings"
@@ -302,7 +301,12 @@ func requireSheetSelector(sheetID, sheetName string) error {
sheetID = strings.TrimSpace(sheetID)
sheetName = strings.TrimSpace(sheetName)
if sheetID == "" && sheetName == "" {
// Eval traces show every occurrence recovering on the next call, so
// the gap is knowing WHICH name to pass, not that one is needed: a
// just-created workbook has a single sheet named Sheet1, and any
// other workbook needs one +workbook-info lookup.
return common.ValidationErrorf("specify at least one of --sheet-id or --sheet-name").
WithHint("a freshly created workbook has one sheet named Sheet1 (`--sheet-name Sheet1`); otherwise list the real sheets with `lark-cli sheets +workbook-info --url <URL>`").
WithParams(
sheetsInvalidParam("sheet-id", "required; specify at least one"),
sheetsInvalidParam("sheet-name", "required; specify at least one"),
@@ -407,6 +411,13 @@ func parseJSONFlag(runtime flagView, name string) (interface{}, error) {
}
return nil, sheetsValidationForFlag(name, "--%s: invalid JSON: %v", name, err).WithCause(err)
}
// Unambiguous habitual shapes are rewritten onto the wire contract
// before validation (see jsonFlagNormalizers). Runs on the parsed value,
// so both the standalone cobra path and +batch-update sub-ops (whose
// mapFlagView.Str re-encodes composites through here) get the rewrite.
if norm := jsonFlagNormalizers[runtime.Command()][name]; norm != nil {
out = norm(out)
}
// Schema-driven flag validation at the user-input boundary. Skips
// --properties (validated at the input-builder tail after enhance
// hooks fill in flat-flag-derived fields) and any flag without an
@@ -417,6 +428,94 @@ func parseJSONFlag(runtime flagView, name string) (interface{}, error) {
return out, nil
}
// jsonFlagNormalizers rewrites, per (command, flag), unambiguous habitual
// input shapes onto the wire contract before schema validation — same
// contract as enum normalization: only a shape whose meaning is beyond
// doubt may be rewritten; anything ambiguous must fail with a prescription
// instead. Applied to the parsed JSON value inside parseJSONFlag.
var jsonFlagNormalizers = map[string]map[string]func(interface{}) interface{}{
"+cells-set": {"cells": normalizeCellsFlagValue},
"+cells-set-style": {"border-styles": normalizeBorderStylesFlagValue},
"+cells-batch-set-style": {"border-styles": normalizeBorderStylesFlagValue},
"+chart-create": {"properties": normalizeChartHexColors},
"+chart-update": {"properties": normalizeChartHexColors},
}
// normalizeChartHexColors walks a chart properties payload and prefixes bare
// 6/8-digit hex values on color keys with '#' (4472C4 → #4472C4 — the
// Excel-habit form the chart backend rejects with "expected rgba() or
// #RRGGBB/#RRGGBBAA"). In-place, recursive; anything not unambiguously a
// bare hex color is untouched.
func normalizeChartHexColors(v interface{}) interface{} {
switch t := v.(type) {
case map[string]interface{}:
for k, val := range t {
if s, ok := val.(string); ok && isColorKey(k) && isBareHexColor(s) {
t[k] = "#" + s
continue
}
normalizeChartHexColors(val)
}
case []interface{}:
for _, e := range t {
normalizeChartHexColors(e)
}
}
return v
}
func isColorKey(k string) bool {
return k == "color" || strings.HasSuffix(k, "_color") || strings.HasSuffix(k, "Color")
}
func isBareHexColor(s string) bool {
if len(s) != 6 && len(s) != 8 {
return false
}
for _, r := range s {
switch {
case r >= '0' && r <= '9', r >= 'a' && r <= 'f', r >= 'A' && r <= 'F':
default:
return false
}
}
return true
}
// cellObjectKeys pins the property vocabulary of a single cell in the
// +cells-set --cells schema ([[{…}]]). Drift against the embedded schema is
// guarded by TestCellObjectKeys_MatchEmbeddedSchema.
var cellObjectKeys = map[string]struct{}{
"border_styles": {},
"cell_styles": {},
"data_validation": {},
"formula": {},
"multiple_values": {},
"note": {},
"rich_text": {},
"value": {},
}
// wrapLoneCellObject rewrites a bare cell object into the [[cell]] the
// --cells contract expects. Eval traces show agents writing a single cell
// routinely pass {"value":…} without the two array layers; when every key
// belongs to the cell vocabulary the meaning is a 1×1 write and the wrap is
// safe. Anything else (unknown keys, arrays — one bracket layer could be a
// row or a column) is returned untouched for the schema validator to
// prescribe.
func wrapLoneCellObject(v interface{}) interface{} {
obj, ok := v.(map[string]interface{})
if !ok || len(obj) == 0 {
return v
}
for k := range obj {
if _, known := cellObjectKeys[k]; !known {
return v
}
}
return []interface{}{[]interface{}{obj}}
}
// requireJSONObject is parseJSONFlag + a type assertion to map[string]interface{}.
func requireJSONObject(runtime flagView, name string) (map[string]interface{}, error) {
v, err := parseJSONFlag(runtime, name)
@@ -448,146 +547,3 @@ func requireJSONArray(runtime flagView, name string) ([]interface{}, error) {
}
return a, nil
}
// ─── style flags (shared by +cells-set-style and +cells-batch-set-style) ─
// buildCellStyleFromFlags reads the 12 flat style flags and returns the
// cell_styles map expected by set_cell_range. Skips any flag the user
// didn't set so partial styles work.
func buildCellStyleFromFlags(runtime flagView) map[string]interface{} {
style := map[string]interface{}{}
if v := runtime.Str("background-color"); v != "" {
style["background_color"] = v
}
if v := runtime.Str("font-color"); v != "" {
style["font_color"] = v
}
if v := runtime.Str("font-family"); v != "" {
style["font_family"] = v
}
if runtime.Changed("font-size") && runtime.Float64("font-size") > 0 {
style["font_size"] = runtime.Float64("font-size")
}
if v := runtime.Str("font-style"); v != "" {
style["font_style"] = v
}
if v := runtime.Str("font-weight"); v != "" {
style["font_weight"] = v
}
if v := runtime.Str("font-line"); v != "" {
style["font_line"] = v
}
if v := runtime.Str("horizontal-alignment"); v != "" {
style["horizontal_alignment"] = v
}
if v := runtime.Str("vertical-alignment"); v != "" {
style["vertical_alignment"] = v
}
if v := runtime.Str("word-wrap"); v != "" {
style["word_wrap"] = v
}
if v := runtime.Str("number-format"); v != "" {
style["number_format"] = v
}
return style
}
// cellStyleAliases maps shorthand cell_styles field names that models commonly
// hallucinate (Excel / openpyxl / CSS conventions) onto the canonical field
// names the backend expects. Only the unambiguous alignment shorthands are
// aliased — they are the high-frequency miss; ambiguous guesses (e.g. "color",
// "bg_color", "text_align") are intentionally left out so a wrong guess still
// surfaces as an error rather than being silently reinterpreted.
var cellStyleAliases = []struct{ alias, canonical string }{
{"horizontal_align", "horizontal_alignment"},
{"halign", "horizontal_alignment"},
{"vertical_align", "vertical_alignment"},
{"valign", "vertical_alignment"},
}
// normalizeCellStyleAliases renames known shorthand keys in a single
// cell_styles map to their canonical equivalents, in place, so a model that
// writes e.g. "horizontal_align" instead of "horizontal_alignment" still
// applies the style instead of hitting an "unsupported field" error (--styles)
// or having the field silently dropped by the backend (typed --cells). If both
// the shorthand and its canonical key are present it returns a validation error
// rather than picking one. path labels the map for the error message.
func normalizeCellStyleAliases(style map[string]interface{}, path string) error {
if len(style) == 0 {
return nil
}
for _, a := range cellStyleAliases {
v, ok := style[a.alias]
if !ok {
continue
}
if _, exists := style[a.canonical]; exists {
return common.ValidationErrorf("%s.%s conflicts with %s; pass only %s", path, a.alias, a.canonical, a.canonical)
}
style[a.canonical] = v
delete(style, a.alias)
}
return nil
}
// normalizeTypedCellsStyleAliases walks a typed --cells 2D array and applies
// normalizeCellStyleAliases to every cell's inline cell_styles object, so the
// alignment shorthands are accepted on +cells-set the same as on --styles.
// Structure is checked leniently to match the pass-through contract: any
// element that isn't the expected shape is skipped, not rejected.
func normalizeTypedCellsStyleAliases(cells []interface{}, path string) error {
for r, rowRaw := range cells {
row, ok := rowRaw.([]interface{})
if !ok {
continue
}
for c, cellRaw := range row {
cell, ok := cellRaw.(map[string]interface{})
if !ok {
continue
}
st, ok := cell["cell_styles"].(map[string]interface{})
if !ok {
continue
}
if err := normalizeCellStyleAliases(st, fmt.Sprintf("%s[%d][%d].cell_styles", path, r, c)); err != nil {
return err
}
}
}
return nil
}
// borderStylesFromFlag parses --border-styles as a JSON object (top/bottom/
// left/right with style sub-objects). Returns nil when the flag is empty.
func borderStylesFromFlag(runtime flagView) (map[string]interface{}, error) {
if runtime.Str("border-styles") == "" {
return nil, nil
}
v, err := parseJSONFlag(runtime, "border-styles")
if err != nil {
return nil, err
}
m, ok := v.(map[string]interface{})
if !ok {
return nil, sheetsValidationForFlag("border-styles", "--border-styles must be a JSON object")
}
return m, nil
}
// requireAnyStyleFlag ensures at least one style-defining flag (style or
// border) is set — otherwise the request would do nothing.
func requireAnyStyleFlag(runtime flagView) error {
if len(buildCellStyleFromFlags(runtime)) > 0 {
return nil
}
if runtime.Str("border-styles") != "" {
return nil
}
return common.ValidationErrorf("at least one style flag is required (e.g. --background-color, --font-weight, --border-styles)").
WithParams(
sheetsInvalidParam("background-color", "required; specify at least one style flag"),
sheetsInvalidParam("font-weight", "required; specify at least one style flag"),
sheetsInvalidParam("border-styles", "required; specify at least one style flag"),
)
}

View File

@@ -144,6 +144,13 @@ func TestSheetHelpersValidationMetadata(t *testing.T) {
if validationErr.Params[0].Name != "--sheet-id" || validationErr.Params[1].Name != "--sheet-name" {
t.Fatalf("params = %#v, want --sheet-id/--sheet-name", validationErr.Params)
}
// Eval traces recover on the very next call, so the missing piece is
// which name to pass — the hint has to name Sheet1 and the lookup.
for _, want := range []string{"Sheet1", "+workbook-info"} {
if !strings.Contains(validationErr.Hint, want) {
t.Errorf("hint should mention %q, got %q", want, validationErr.Hint)
}
}
})
t.Run("spreadsheet url shape reports url param", func(t *testing.T) {

View File

@@ -0,0 +1,312 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"encoding/json"
"strings"
"testing"
)
// TestWrapLoneCellObject pins the auto-wrap contract: a bare cell object —
// the classic missing-[[…]] shape agents produce for a 1×1 write — is
// rewritten to [[cell]]; anything whose meaning is not beyond doubt stays
// untouched for the schema validator to prescribe.
func TestWrapLoneCellObject(t *testing.T) {
t.Parallel()
cases := []struct {
name string
in string
wrapped bool
}{
{"lone value cell", `{"value":"hi"}`, true},
{"lone formula cell with styles", `{"formula":"=SUM(A1:A3)","cell_styles":{"font_weight":"bold"}}`, true},
{"unknown key stays", `{"value":"hi","range":"A1"}`, false},
{"array of cells stays (row vs column ambiguous)", `[{"value":"a"},{"value":"b"}]`, false},
{"proper 2D array stays", `[[{"value":"a"}]]`, false},
{"empty object stays", `{}`, false},
{"scalar stays", `"hi"`, false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
var v interface{}
if err := json.Unmarshal([]byte(tc.in), &v); err != nil {
t.Fatalf("bad fixture: %v", err)
}
out := wrapLoneCellObject(v)
_, isWrapped := out.([]interface{})
_, wasArray := v.([]interface{})
if tc.wrapped && (!isWrapped || wasArray) {
t.Errorf("expected wrap to [[cell]], got %#v", out)
}
if !tc.wrapped && !wasArray && isWrapped {
t.Errorf("expected no wrap, got %#v", out)
}
if tc.wrapped {
rows, _ := out.([]interface{})
if len(rows) != 1 {
t.Fatalf("want 1 row, got %d", len(rows))
}
cells, _ := rows[0].([]interface{})
if len(cells) != 1 {
t.Fatalf("want 1 cell, got %d", len(cells))
}
}
})
}
}
// TestCellObjectKeys_MatchEmbeddedSchema drift-guards the hardcoded cell
// vocabulary against the embedded +cells-set --cells schema: if the spec
// repo adds or removes a cell property, this fails and cellObjectKeys must
// be updated (an outdated set only narrows the auto-wrap, but silently
// narrowing is still drift).
func TestCellObjectKeys_MatchEmbeddedSchema(t *testing.T) {
t.Parallel()
idx, err := loadFlagSchemas()
if err != nil {
t.Fatalf("loadFlagSchemas: %v", err)
}
raw, ok := idx.Flags["+cells-set"]["cells"]
if !ok {
t.Fatal("embedded schema for +cells-set --cells missing")
}
var schema schemaProperty
if err := json.Unmarshal(raw, &schema); err != nil {
t.Fatalf("unmarshal schema: %v", err)
}
cell := schema.Items
if cell != nil && cell.Items != nil {
cell = cell.Items
}
if cell == nil || len(cell.Properties) == 0 {
t.Fatal("schema shape changed: expected array→array→object with properties")
}
for k := range cell.Properties {
if _, ok := cellObjectKeys[k]; !ok {
t.Errorf("schema property %q missing from cellObjectKeys", k)
}
}
for k := range cellObjectKeys {
if _, ok := cell.Properties[k]; !ok {
t.Errorf("cellObjectKeys has %q which the schema no longer declares", k)
}
}
}
// TestCellsSet_LoneCellObjectAutoWraps runs the mounted path end-to-end: the
// eval-trace failure shape (--cells with a bare object) now dry-runs clean
// instead of failing "expected type array, got object".
func TestCellsSet_LoneCellObjectAutoWraps(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cells-set")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1",
"--cells", `{"value":"hello"}`,
"--dry-run",
})
if err != nil {
t.Fatalf("lone cell object should auto-wrap to [[cell]], got: %v", err)
}
if !strings.Contains(stdout, "hello") {
t.Errorf("dry-run body should carry the cell value, got %q", stdout)
}
}
// TestCellsSetStyle_BorderWeightWordInStyleNormalizes pins the reachability
// fix for the border acceptance layer on the --border-styles flag path: the
// eval-trace failure shape ({"style":"thin"} — 07-28 root-cause report #2,
// 173 occurrences) must normalize to style:solid + weight:thin BEFORE the
// schema enum check, instead of dying on `value "thin" is not in enum`.
func TestCellsSetStyle_BorderWeightWordInStyleNormalizes(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cells-set-style")
t.Run("full nested form with weight word in style", func(t *testing.T) {
t.Parallel()
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1:B2",
"--border-styles", `{"top":{"style":"thin","color":"#B4B4B4"},"bottom":{"style":"thin","color":"#B4B4B4"}}`,
"--dry-run",
})
if err != nil {
t.Fatalf("weight word in style slot should normalize, got: %v", err)
}
for _, want := range []string{`"style": "solid"`, `"weight": "thin"`} {
if !strings.Contains(stdout, want) {
t.Errorf("dry-run body should carry %s, got %q", want, stdout)
}
}
})
t.Run("all shorthand with weight word in style", func(t *testing.T) {
t.Parallel()
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1",
"--border-styles", `{"all":{"style":"medium","color":"#000000"}}`,
"--dry-run",
})
if err != nil {
t.Fatalf("all shorthand + weight word should normalize, got: %v", err)
}
for _, want := range []string{`"top"`, `"bottom"`, `"weight": "medium"`, `"style": "solid"`} {
if !strings.Contains(stdout, want) {
t.Errorf("dry-run body should carry %s, got %q", want, stdout)
}
}
})
t.Run("explicit conflicting weight keeps the enum error", func(t *testing.T) {
t.Parallel()
_, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1",
"--border-styles", `{"top":{"style":"thin","weight":"thick"}}`,
"--dry-run",
})
requireValidation(t, err, "not in enum")
})
}
// TestCellsSet_BorderWeightWordInStyleNormalizes pins the same reachability
// fix on the typed --cells carrier (07-28 root-cause report #10, 58
// occurrences): border_styles inside a cell object normalizes before the
// enum check.
func TestCellsSet_BorderWeightWordInStyleNormalizes(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cells-set")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1",
"--cells", `[[{"value":"x","border_styles":{"top":{"style":"thin","color":"#000000"}}}]]`,
"--dry-run",
})
if err != nil {
t.Fatalf("weight word in style slot should normalize on --cells, got: %v", err)
}
for _, want := range []string{`"style": "solid"`, `"weight": "thin"`} {
if !strings.Contains(stdout, want) {
t.Errorf("dry-run body should carry %s, got %q", want, stdout)
}
}
}
// TestTablePut_SheetsDecodeHints pins the two decode-failure prescriptions:
// wrong JSON kind inlines the expected shape; mangled JSON steers to
// stdin/@file.
func TestTablePut_SheetsDecodeHints(t *testing.T) {
t.Parallel()
t.Run("type mismatch inlines skeleton", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+table-put")
_, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheets", `{"sheets":[{"name":"s","columns":[{"name":"a"}],"data":[]}]}`,
"--dry-run",
})
ve := requireValidation(t, err, "--sheets: invalid JSON")
for _, want := range []string{"expected shape:", `"columns":["City","Revenue"]`, `"dtypes":{"Revenue":"float64"}`} {
if !strings.Contains(ve.Hint, want) {
t.Errorf("hint should contain %q, got %q", want, ve.Hint)
}
}
})
t.Run("bare array names the missing envelope", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+table-put")
_, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheets", `[{"name":"s","columns":["a"],"data":[["x"]]}]`,
"--dry-run",
})
// The Go unmarshal text names the internal struct, not the fix
// (07-28 root-cause report #4, 84 occurrences).
ve := requireValidation(t, err, `top level must be the object {"sheets":[…]}`)
if strings.Contains(ve.Message, "cannot unmarshal") {
t.Errorf("message should not leak the Go unmarshal wording, got %q", ve.Message)
}
if !strings.Contains(ve.Hint, "expected shape:") {
t.Errorf("hint should still inline the skeleton, got %q", ve.Hint)
}
})
t.Run("syntax error steers to stdin or @file", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+table-put")
_, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheets", `{"sheets":[)`,
"--dry-run",
})
ve := requireValidation(t, err, "--sheets: invalid JSON")
for _, want := range []string{"stdin", "@./payload.json"} {
if !strings.Contains(ve.Hint, want) {
t.Errorf("hint should contain %q, got %q", want, ve.Hint)
}
}
})
}
// TestNormalizeChartHexColors pins the '#' prefixing on bare hex color
// values (eval V2U024: bars.color "4472C4" rejected server-side) and the
// pass-through of everything else, including the parseJSONFlag wiring for
// the batch sub-op path.
func TestNormalizeChartHexColors(t *testing.T) {
t.Parallel()
props := map[string]interface{}{
"plotArea": map[string]interface{}{
"plot": map[string]interface{}{
"series": []interface{}{
map[string]interface{}{"bars": map[string]interface{}{"color": "4472C4"}},
map[string]interface{}{"line": map[string]interface{}{"color": "#ED7D31"}},
map[string]interface{}{"area": map[string]interface{}{"color": "rgba(1,2,3,0.5)"}},
map[string]interface{}{"font_color": "ED7D31AA", "label": "not a color 4472C4"},
},
},
},
}
normalizeChartHexColors(props)
series := props["plotArea"].(map[string]interface{})["plot"].(map[string]interface{})["series"].([]interface{})
if got := series[0].(map[string]interface{})["bars"].(map[string]interface{})["color"]; got != "#4472C4" {
t.Errorf("bare hex should gain #, got %v", got)
}
if got := series[1].(map[string]interface{})["line"].(map[string]interface{})["color"]; got != "#ED7D31" {
t.Errorf("already-prefixed color must not change, got %v", got)
}
if got := series[2].(map[string]interface{})["area"].(map[string]interface{})["color"]; got != "rgba(1,2,3,0.5)" {
t.Errorf("rgba color must not change, got %v", got)
}
last := series[3].(map[string]interface{})
if got := last["font_color"]; got != "#ED7D31AA" {
t.Errorf("8-digit hex on a *_color key should gain #, got %v", got)
}
if got := last["label"]; got != "not a color 4472C4" {
t.Errorf("non-color key must not change, got %v", got)
}
// Wiring: a +chart-create sub-op style view routes through parseJSONFlag
// and picks up the normalizer.
fv := newMapFlagViewForCommand("+chart-create", map[string]interface{}{
"properties": map[string]interface{}{"title": map[string]interface{}{"font_color": "112233"}},
})
out, err := parseJSONFlag(fv, "properties")
if err != nil {
t.Fatalf("parseJSONFlag: %v", err)
}
title := out.(map[string]interface{})["title"].(map[string]interface{})
if title["font_color"] != "#112233" {
t.Errorf("parseJSONFlag should apply the chart color normalizer, got %v", title["font_color"])
}
}

View File

@@ -5,6 +5,8 @@ package sheets
import (
"context"
"fmt"
"sort"
"strings"
"github.com/larksuite/cli/shortcuts/common"
@@ -29,10 +31,14 @@ import (
// The tool's contract (post-translation):
// { excel_id, operations: [{tool_name, input}, ...], continue_on_error? }
//
// continue_on_error defaults to false (strict transaction): any failure
// rolls back the whole batch. CLI leaves the default in place for the
// three "fan-out" shortcuts since they're meant to be all-or-nothing;
// only +batch-update lets callers flip it via --continue-on-error.
// continue_on_error defaults to false (fail-fast): execution stops at the
// first failing sub-op, but sub-ops already applied are NOT rolled back —
// the server reports "N succeeded, M failed" and the N stay in the sheet
// (verified against live batches; earlier docs wrongly promised a rollback,
// which made agents resend whole batches and double-apply the successes).
// CLI leaves the default in place for the fan-out shortcuts since they're
// idempotent stamps; only +batch-update lets callers flip it via
// --continue-on-error.
// BatchUpdate accepts a CLI-shape operations array (each item
// {shortcut, input}); on Validate / DryRun / Execute we translate each
@@ -40,14 +46,15 @@ import (
// {tool_name, input(+operation)} form before calling the underlying
// batch_update tool.
var BatchUpdate = common.Shortcut{
Service: "sheets",
Command: "+batch-update",
Description: "Execute a batch of write shortcuts as a single atomic request (rolls back on failure by default).",
Risk: "high-risk-write",
Scopes: []string{"sheets:spreadsheet:write_only"},
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+batch-update"),
Service: "sheets",
Command: "+batch-update",
Description: "Execute a batch of write shortcuts in one request; fail-fast on the first failing sub-op (already-applied sub-ops are NOT rolled back).",
Risk: "high-risk-write",
Scopes: []string{"sheets:spreadsheet:write_only"},
ConditionalScopes: []string{"sheets:spreadsheet:read"},
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+batch-update"),
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
token, err := resolveSpreadsheetToken(runtime)
if err != nil {
@@ -56,72 +63,617 @@ var BatchUpdate = common.Shortcut{
// Run the full translation in Validate so shape errors surface before
// DryRun / Execute. Translator is pure (no network), so re-running it
// in DryRun / Execute below is fine.
if _, err := batchUpdateInput(runtime, token); err != nil {
if _, err := buildBatchUpdatePlan(runtime, token); err != nil {
return err
}
return nil
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
token, _ := resolveSpreadsheetToken(runtime)
input, _ := batchUpdateInput(runtime, token)
return invokeToolDryRun(token, ToolKindWrite, "batch_update", input)
plan, _ := buildBatchUpdatePlan(runtime, token)
dryRun := invokeToolDryRun(token, ToolKindWrite, "batch_update", plan.input)
if batchContainsSemanticChartUpdate(runtime) {
dryRun.Set("preflight", "execution reads each target chart snapshot before building its partial properties patch")
}
if len(plan.localFailures) > 0 {
dryRun.Set("local_validation_failures", plan.localFailures)
}
if batchNeedsDimInsertBeforeStyleWarning(runtime) {
dryRun.Set("warning_message", dimInsertBeforeStyleWarning)
}
return dryRun
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
token, err := resolveSpreadsheetTokenExec(runtime)
if err != nil {
return err
}
input, err := batchUpdateInput(runtime, token)
rawOps, err := parseBatchOperationsFlag(runtime)
if err != nil {
return err
}
out, err := callTool(ctx, runtime, token, ToolKindWrite, "batch_update", input)
plan, err := buildBatchUpdatePlan(runtime, token)
if err != nil {
return err
}
if err := prepareBatchChartUpdates(ctx, runtime, token, rawOps, plan); err != nil {
return err
}
if batchNeedsDimInsertBeforeStyleWarning(runtime) {
fmt.Fprintln(runtime.IO().ErrOut, dimInsertBeforeStyleWarning)
}
out, err := callTool(ctx, runtime, token, ToolKindWrite, "batch_update", plan.input)
if err != nil {
return err
}
if len(plan.localFailures) > 0 {
out = mergeBatchUpdatePartialOutput(out, plan)
}
runtime.Out(compactBatchChartCreateOutput(out), nil)
return nil
},
Tips: []string{
"high-risk-write: always pass --yes (or --dry-run to preview) — without it the call exits 10 asking for confirmation.",
"Execution is fail-fast, NOT transactional: on \"N succeeded, M failed\" the succeeded sub-ops stay applied (no rollback) — fix the failure and resend ONLY the operations from the first failed index onward; resending the whole batch re-applies the succeeded ones. Pass --continue-on-error to keep going past failures instead.",
"Each sub-op is {shortcut, input}. Do NOT pass input.operation (implied by shortcut name). Repeated input.excel_id / input.spreadsheet_token / input.url fields are ignored; the top-level locator wins.",
"Chart operations are supported, but prefer +batch-chart-create / +batch-chart-update for chart-only work because their contracts and partial-failure recovery are simpler.",
},
}
var chartCreateBatchDispatch = map[string]batchOpMapping{
"+chart-create-basic": {"manage_chart_object", chartCreateBasicInput},
}
var chartUpdateBatchDispatch = map[string]batchOpMapping{
"+chart-config-update": {"manage_chart_object", chartConfigUpdateInput},
"+chart-data-update": {"manage_chart_object", chartDataUpdateInput},
}
var BatchChartCreate = common.Shortcut{
Service: "sheets",
Command: "+batch-chart-create",
Description: "Create multiple independent basic charts through one batch request; valid charts continue when another chart fails.",
Risk: "write",
Scopes: []string{"sheets:spreadsheet:write_only"},
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+batch-chart-create"),
Tips: []string{
"Each operation directly contains +chart-create-basic flags such as sheet_name, chart_type, and data_range; do not wrap it in shortcut/input. The legacy wrapped shape remains accepted for compatibility.",
"--dry-run prints the translated internal MCP body (tool_name / operation / basic_chart) for inspection only; never copy that body back into --operations.",
"Inspect succeeded, failed, and results after execution. Keep successful charts, retry only failed indexes, then call +chart-list once per affected sheet and repair mismatches with +batch-chart-update instead of deleting/recreating charts.",
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
token, err := resolveSpreadsheetToken(runtime)
if err != nil {
return err
}
_, err = buildChartBatchPlan(runtime, token, chartCreateBatchDispatch, "+batch-chart-create")
return err
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
token, _ := resolveSpreadsheetToken(runtime)
plan, _ := buildChartBatchPlan(runtime, token, chartCreateBatchDispatch, "+batch-chart-create")
dryRun := invokeToolDryRun(token, ToolKindWrite, "batch_update", plan.input)
if len(plan.localFailures) > 0 {
dryRun.Set("local_validation_failures", plan.localFailures)
}
return dryRun
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
token, err := resolveSpreadsheetTokenExec(runtime)
if err != nil {
return err
}
plan, err := buildChartBatchPlan(runtime, token, chartCreateBatchDispatch, "+batch-chart-create")
if err != nil {
return err
}
out, err := callTool(ctx, runtime, token, ToolKindWrite, "batch_update", plan.input)
if err != nil {
return err
}
if len(plan.localFailures) > 0 {
out = mergeBatchUpdatePartialOutput(out, plan)
}
runtime.Out(compactBatchChartCreateOutput(out), nil)
return nil
},
}
var BatchChartUpdate = common.Shortcut{
Service: "sheets",
Command: "+batch-chart-update",
Description: "Update multiple independent chart configurations or data sources through one batch request.",
Risk: "write",
Scopes: []string{"sheets:spreadsheet:read", "sheets:spreadsheet:write_only"},
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+batch-chart-update"),
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
token, err := resolveSpreadsheetToken(runtime)
if err != nil {
return err
}
_, err = buildChartBatchPlan(runtime, token, chartUpdateBatchDispatch, "+batch-chart-update")
return err
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
token, _ := resolveSpreadsheetToken(runtime)
plan, _ := buildChartBatchPlan(runtime, token, chartUpdateBatchDispatch, "+batch-chart-update")
dryRun := invokeToolDryRun(token, ToolKindWrite, "batch_update", plan.input)
dryRun.Set("preflight", "execution reads each target chart snapshot before building its partial properties patch")
if len(plan.localFailures) > 0 {
dryRun.Set("local_validation_failures", plan.localFailures)
}
return dryRun
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
token, err := resolveSpreadsheetTokenExec(runtime)
if err != nil {
return err
}
rawOps, err := parseBatchOperationsFlag(runtime)
if err != nil {
return err
}
plan, err := buildChartBatchPlan(runtime, token, chartUpdateBatchDispatch, "+batch-chart-update")
if err != nil {
return err
}
if err := prepareBatchChartUpdates(ctx, runtime, token, rawOps, plan); err != nil {
return err
}
out, err := callTool(ctx, runtime, token, ToolKindWrite, "batch_update", plan.input)
if err != nil {
return err
}
if len(plan.localFailures) > 0 {
out = mergeBatchUpdatePartialOutput(out, plan)
}
runtime.Out(out, nil)
return nil
},
Tips: []string{
"Default is strict transaction — any sub-tool failure rolls the whole batch back. Pass --continue-on-error to keep partial successes.",
"Each sub-op is {shortcut, input}. Do NOT pass input.operation (implied by shortcut name) or input.excel_id / input.url (set at the +batch-update top level).",
},
}
func buildChartBatchPlan(
runtime *common.RuntimeContext,
token string,
dispatch map[string]batchOpMapping,
command string,
) (*batchUpdatePlan, error) {
rawOps, err := parseBatchOperationsFlag(runtime)
if err != nil {
return nil, err
}
if command == "+batch-chart-create" {
rawOps, err = normalizeChartCreateBatchOperations(rawOps)
if err != nil {
return nil, err
}
}
if len(rawOps) == 0 {
return nil, sheetsValidationForFlag("operations", "--operations must be a non-empty JSON array")
}
if len(rawOps) > maxBatchOperations {
return nil, sheetsValidationForFlag(
"operations",
"--operations accepts at most %d entries; got %d",
maxBatchOperations,
len(rawOps),
)
}
continueOnError := true
if runtime.Changed("continue-on-error") {
continueOnError = runtime.Bool("continue-on-error")
}
translated := make([]interface{}, 0, len(rawOps))
originalIndexes := make([]int, 0, len(rawOps))
failures := make([]batchOpTranslationFailure, 0)
for index, raw := range rawOps {
item, translateErr := translateBatchOpWithDispatch(raw, token, index, dispatch, command)
if translateErr != nil {
shortcut := ""
if object, ok := raw.(map[string]interface{}); ok {
shortcut, _ = object["shortcut"].(string)
}
failures = append(failures, batchOpTranslationFailure{
Index: index,
Shortcut: shortcut,
Err: translateErr,
})
continue
}
translated = append(translated, item)
originalIndexes = append(originalIndexes, index)
}
if !continueOnError {
if err := batchOperationFailuresError(failures, len(rawOps)); err != nil {
return nil, err
}
}
if len(translated) == 0 {
return nil, batchOperationFailuresError(failures, len(rawOps))
}
localFailures := make([]batchLocalValidationFailure, 0, len(failures))
for _, failure := range failures {
localFailures = append(localFailures, batchLocalValidationFailure{
Index: failure.Index,
Shortcut: failure.Shortcut,
Success: false,
Stage: "cli_validation",
Error: failure.Err.Error(),
})
}
return &batchUpdatePlan{
input: map[string]interface{}{
"excel_id": token,
"operations": translated,
"continue_on_error": continueOnError,
},
originalIndexes: originalIndexes,
localFailures: localFailures,
total: len(rawOps),
}, nil
}
func normalizeChartCreateBatchOperations(rawOps []interface{}) ([]interface{}, error) {
normalized := make([]interface{}, 0, len(rawOps))
for index, raw := range rawOps {
op, ok := raw.(map[string]interface{})
if !ok {
return nil, sheetsValidationForFlag("operations", "operations[%d] must be a JSON object", index)
}
_, hasShortcut := op["shortcut"]
_, hasInput := op["input"]
if hasShortcut && hasInput {
normalized = append(normalized, op)
continue
}
input := make(map[string]interface{}, len(op))
for key, value := range op {
if key != "shortcut" && key != "input" {
input[key] = value
}
}
if hasInput {
rawInput := op["input"]
var inputObject map[string]interface{}
if rawInput != nil {
inputObject, ok = rawInput.(map[string]interface{})
if !ok {
return nil, sheetsValidationForFlag("operations", "operations[%d]: 'input' must be a JSON object (got %T)", index, rawInput)
}
}
input = inputObject
}
shortcut := "+chart-create-basic"
if hasShortcut {
value, ok := op["shortcut"].(string)
if !ok || strings.TrimSpace(value) == "" {
return nil, sheetsValidationForFlag("operations", "operations[%d]: 'shortcut' must be a non-empty string", index)
}
shortcut = value
}
normalized = append(normalized, map[string]interface{}{
"shortcut": shortcut,
"input": input,
})
}
return normalized, nil
}
func prepareBatchChartUpdates(
ctx context.Context,
runtime *common.RuntimeContext,
token string,
rawOps []interface{},
plan *batchUpdatePlan,
) error {
translated, _ := plan.input["operations"].([]interface{})
continueOnError, _ := plan.input["continue_on_error"].(bool)
prepared := make([]interface{}, 0, len(translated))
preparedIndexes := make([]int, 0, len(translated))
for remoteIndex, rawIndex := range plan.originalIndexes {
raw, _ := rawOps[rawIndex].(map[string]interface{})
shortcut, _ := raw["shortcut"].(string)
if shortcut != "+chart-config-update" && shortcut != "+chart-data-update" {
prepared = append(prepared, translated[remoteIndex])
preparedIndexes = append(preparedIndexes, rawIndex)
continue
}
input, _ := raw["input"].(map[string]interface{})
fv := newMapFlagViewForCommand(shortcut, input)
sheetID := strings.TrimSpace(fv.Str("sheet-id"))
sheetName := strings.TrimSpace(fv.Str("sheet-name"))
chartID := strings.TrimSpace(fv.Str("chart-id"))
snapshot, err := fetchChartSnapshot(ctx, runtime, token, sheetID, sheetName, chartID)
if err != nil {
if !continueOnError {
return err
}
plan.localFailures = append(plan.localFailures, batchLocalValidationFailure{
Index: rawIndex,
Shortcut: shortcut,
Success: false,
Stage: "cli_preflight",
Error: err.Error(),
})
continue
}
var body map[string]interface{}
switch shortcut {
case "+chart-config-update":
body, _, err = chartConfigUpdateInputFromSnapshot(fv, token, sheetID, sheetName, snapshot)
case "+chart-data-update":
body, _, _, _, err = chartDataUpdateInputFromSnapshot(fv, token, sheetID, sheetName, snapshot)
}
if err != nil {
if !continueOnError {
return err
}
plan.localFailures = append(plan.localFailures, batchLocalValidationFailure{
Index: rawIndex,
Shortcut: shortcut,
Success: false,
Stage: "cli_preflight",
Error: err.Error(),
})
continue
}
item, _ := translated[remoteIndex].(map[string]interface{})
item["input"] = body
prepared = append(prepared, item)
preparedIndexes = append(preparedIndexes, rawIndex)
}
if len(prepared) == 0 {
return sheetsValidationForFlag("operations", "all chart updates failed CLI preflight; no write request was sent")
}
plan.input["operations"] = prepared
plan.originalIndexes = preparedIndexes
return nil
}
func batchContainsSemanticChartUpdate(runtime *common.RuntimeContext) bool {
rawOps, err := parseBatchOperationsFlag(runtime)
if err != nil {
return false
}
for _, raw := range rawOps {
op, _ := raw.(map[string]interface{})
shortcut, _ := op["shortcut"].(string)
if shortcut == "+chart-config-update" || shortcut == "+chart-data-update" {
return true
}
}
return false
}
func compactBatchChartCreateOutput(out interface{}) interface{} {
root, ok := out.(map[string]interface{})
if !ok {
return out
}
results, _ := root["results"].([]interface{})
for _, raw := range results {
item, _ := raw.(map[string]interface{})
data, _ := item["data"].(map[string]interface{})
delete(data, "snapshot")
}
return root
}
// batchUpdateInput translates the user-supplied CLI-shape operations array
// into the MCP batch_update payload. Returns ValidationErrorf-typed errors
// (errs.ValidationError) on any per-op shape problem (translator validates
// each entry).
type batchLocalValidationFailure struct {
Index int `json:"index"`
Shortcut string `json:"shortcut,omitempty"`
Success bool `json:"success"`
Stage string `json:"stage"`
Error string `json:"error"`
}
type batchUpdatePlan struct {
input map[string]interface{}
originalIndexes []int
localFailures []batchLocalValidationFailure
total int
}
func batchUpdateInput(runtime *common.RuntimeContext, token string) (map[string]interface{}, error) {
plan, err := buildBatchUpdatePlan(runtime, token)
if err != nil {
return nil, err
}
return plan.input, nil
}
func buildBatchUpdatePlan(runtime *common.RuntimeContext, token string) (*batchUpdatePlan, error) {
rawOps, err := parseBatchOperationsFlag(runtime)
if err != nil {
return nil, err
}
translated, err := translateBatchOperations(rawOps, token)
continueOnError := batchContinueOnError(runtime)
translated, originalIndexes, failures, err := collectBatchOperationTranslations(rawOps, token)
if err != nil {
return nil, err
}
if !continueOnError {
if err := batchOperationFailuresError(failures, len(rawOps)); err != nil {
return nil, err
}
}
if len(translated) == 0 {
return nil, batchOperationFailuresError(failures, len(rawOps))
}
input := map[string]interface{}{
"excel_id": token,
"operations": translated,
}
if continueOnError {
input["continue_on_error"] = true
}
localFailures := make([]batchLocalValidationFailure, 0, len(failures))
for _, failure := range failures {
localFailures = append(localFailures, batchLocalValidationFailure{
Index: failure.Index,
Shortcut: failure.Shortcut,
Success: false,
Stage: "cli_validation",
Error: failure.Err.Error(),
})
}
return &batchUpdatePlan{
input: input,
originalIndexes: originalIndexes,
localFailures: localFailures,
total: len(rawOps),
}, nil
}
func batchContinueOnError(runtime *common.RuntimeContext) bool {
if runtime.Changed("continue-on-error") {
// An explicit --continue-on-error always wins over the envelope, so
// --continue-on-error=false keeps the strict-transaction default even
// when the --operations envelope carries continue_on_error:true.
if runtime.Bool("continue-on-error") {
input["continue_on_error"] = true
}
} else if envelope, _ := parseJSONFlag(runtime, "operations"); envelope != nil {
// No explicit flag: honor an inline override when --operations is an
// envelope object rather than a bare operations array.
// An explicit false wins over the envelope.
return runtime.Bool("continue-on-error")
}
if envelope, _ := parseJSONFlag(runtime, "operations"); envelope != nil {
if m, ok := envelope.(map[string]interface{}); ok {
if v, ok := m["continue_on_error"].(bool); ok && v {
input["continue_on_error"] = true
if v, ok := m["continue_on_error"].(bool); ok {
return v
}
}
}
return input, nil
return false
}
// mergeBatchUpdatePartialOutput restores original operation indexes after the
// CLI omitted locally invalid operations from the server request, then appends
// the local failures to the same result list. The command exits successfully
// when the server preserved at least one valid operation, but the output still
// makes every failed operation explicit.
func mergeBatchUpdatePartialOutput(out interface{}, plan *batchUpdatePlan) interface{} {
merged := map[string]interface{}{}
if remote, ok := out.(map[string]interface{}); ok {
for key, value := range remote {
merged[key] = value
}
} else if out != nil {
merged["tool_output"] = out
}
results := make([]interface{}, 0, plan.total)
if remoteResults, ok := merged["results"].([]interface{}); ok {
for _, raw := range remoteResults {
item, ok := raw.(map[string]interface{})
if !ok {
results = append(results, raw)
continue
}
copied := make(map[string]interface{}, len(item))
for key, value := range item {
copied[key] = value
}
if remoteIndex, ok := batchResultIndex(copied["index"]); ok &&
remoteIndex >= 0 && remoteIndex < len(plan.originalIndexes) {
copied["index"] = plan.originalIndexes[remoteIndex]
}
results = append(results, copied)
}
}
for _, failure := range plan.localFailures {
results = append(results, map[string]interface{}{
"index": failure.Index,
"shortcut": failure.Shortcut,
"success": false,
"stage": failure.Stage,
"error": failure.Error,
})
}
sort.SliceStable(results, func(i, j int) bool {
left, leftOK := batchResultItemIndex(results[i])
right, rightOK := batchResultItemIndex(results[j])
return leftOK && rightOK && left < right
})
succeeded := batchResultCount(merged["succeeded"])
remoteFailed := batchResultCount(merged["failed"])
failed := remoteFailed + len(plan.localFailures)
merged["total"] = plan.total
merged["succeeded"] = succeeded
merged["failed"] = failed
merged["results"] = results
merged["local_validation_failures"] = plan.localFailures
merged["message"] = fmt.Sprintf("batch_update: %d succeeded, %d failed", succeeded, failed)
return merged
}
func batchResultIndex(value interface{}) (int, bool) {
switch typed := value.(type) {
case int:
return typed, true
case int64:
return int(typed), true
case float64:
return int(typed), typed == float64(int(typed))
default:
return 0, false
}
}
func batchResultItemIndex(value interface{}) (int, bool) {
item, ok := value.(map[string]interface{})
if !ok {
return 0, false
}
return batchResultIndex(item["index"])
}
func batchResultCount(value interface{}) int {
count, _ := batchResultIndex(value)
return count
}
// batchNeedsDimInsertBeforeStyleWarning reports whether any +dim-insert sub-op
// requests --inherit-style before at the first row/column, where the
// preceding-side style cannot be copied (no preceding row/column exists).
func batchNeedsDimInsertBeforeStyleWarning(runtime *common.RuntimeContext) bool {
rawOps, err := parseBatchOperationsFlag(runtime)
if err != nil {
return false
}
for _, raw := range rawOps {
op, ok := raw.(map[string]interface{})
if !ok {
continue
}
sc, _ := op["shortcut"].(string)
if sc != "+dim-insert" {
continue
}
input, _ := op["input"].(map[string]interface{})
isBefore := false
for _, key := range []string{"inherit-style", "inherit_style", "inheritStyle"} {
if v, _ := input[key].(string); strings.EqualFold(v, "before") {
isBefore = true
break
}
}
if !isBefore {
continue
}
posRaw, hasPos := input["position"]
if !hasPos {
continue
}
// Warn only at the first row/column (idx 0).
if _, idx, err := parseA1Position(strings.TrimSpace(fmt.Sprintf("%v", posRaw))); err == nil && idx == 0 {
return true
}
}
return false
}
// parseBatchOperationsFlag accepts --operations as either a JSON array (the
@@ -160,6 +712,11 @@ var CellsBatchSetStyle = common.Shortcut{
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+cells-batch-set-style"),
Tips: []string{
"DEPRECATED: superseded by +styles-put, whose one spec also covers merges, row/col sizes and freeze — prefer it for new work.",
`Example: lark-cli sheets +cells-batch-set-style --url <URL> --ranges '["Sheet1!A1:B2","汇总!C1:C9"]' --font-weight bold`,
"Every range carries its sheet-NAME prefix (Sheet1!A1:B2, not a sheet_id) — there is no --sheet-id / --sheet-name flag here.",
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
if _, err := resolveSpreadsheetToken(runtime); err != nil {
return err
@@ -189,6 +746,10 @@ var CellsBatchSetStyle = common.Shortcut{
if err != nil {
return err
}
// Phase-1 deprecation (docs already point at +styles-put): keep the
// command working, steer new usage to the superset in-band.
fmt.Fprintln(runtime.IO().ErrOut,
"note: +cells-batch-set-style is superseded by +styles-put (one spec covers styles + merges + row/col sizes + freeze); prefer +styles-put for new work")
out, err := callTool(ctx, runtime, token, ToolKindWrite, "batch_update", input)
if err != nil {
return err

View File

@@ -5,10 +5,22 @@ package sheets
import (
"encoding/json"
"reflect"
"strings"
"testing"
)
func TestBatchUpdate_Scopes(t *testing.T) {
t.Parallel()
if got, want := BatchUpdate.Scopes, []string{"sheets:spreadsheet:write_only"}; !reflect.DeepEqual(got, want) {
t.Fatalf("unconditional scopes = %v, want %v", got, want)
}
if got, want := BatchUpdate.ConditionalScopes, []string{"sheets:spreadsheet:read"}; !reflect.DeepEqual(got, want) {
t.Fatalf("conditional scopes = %v, want %v", got, want)
}
}
// TestBatchUpdate_TranslatesShortcutToToolName verifies +batch-update
// translates each CLI-shape sub-op ({shortcut, input}) to the MCP-shape
// ({tool_name, input(+operation, +excel_id)}) before threading into
@@ -58,6 +70,39 @@ func TestBatchUpdate_TranslatesShortcutToToolName(t *testing.T) {
}
}
func TestBatchUpdate_DimInsertInheritAfterCopiesFollowingStyle(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, BatchUpdate, []string{
"--url", testURL,
"--operations", `[
{"shortcut":"+dim-insert","input":{"sheet_id":"sh1","position":"D","count":1,"inherit_style":"after"}}
]`,
"--yes",
})
input := decodeToolInput(t, body, "batch_update")
ops, _ := input["operations"].([]interface{})
if len(ops) != 1 {
t.Fatalf("operations length = %d, want 1", len(ops))
}
op := ops[0].(map[string]interface{})
if op["tool_name"] != "modify_sheet_structure" {
t.Fatalf("tool_name = %v, want modify_sheet_structure", op["tool_name"])
}
in, _ := op["input"].(map[string]interface{})
// inherit_style=after copies the following column's style via a plain
// before-insert at the same position (the backend anchors on the following
// column), so position stays D with side=before.
assertInputEquals(t, in, map[string]interface{}{
"excel_id": testToken,
"sheet_id": "sh1",
"operation": "insert",
"position": "D",
"count": float64(1),
"side": "before",
})
}
func TestBatchUpdate_HighRiskWriteRequiresYes(t *testing.T) {
t.Parallel()
stdout, stderr, err := runShortcutCapturingErr(t, BatchUpdate, []string{
@@ -327,7 +372,7 @@ func TestValidateDropdownRanges_RejectsMalformedRange(t *testing.T) {
// TestBatchUpdate_TranslatorRejects covers per-op shape errors caught by
// translateBatchOp: unknown shortcut, missing shortcut, banned (read /
// fan-out / legacy v2) shortcuts, hand-filled reserved keys, etc.
// fan-out / legacy v2) shortcuts, malformed wrapper keys, etc.
func TestBatchUpdate_TranslatorRejects(t *testing.T) {
t.Parallel()
cases := []struct {
@@ -380,16 +425,6 @@ func TestBatchUpdate_TranslatorRejects(t *testing.T) {
opsJSON: `[{"shortcut":"+dim-insert","input":{"operation":"delete","position":"1","count":1}}]`,
wantMatch: "do not pass input.operation",
},
{
name: "user filled excel_id",
opsJSON: `[{"shortcut":"+cells-set","input":{"excel_id":"shtcnX","range":"A1"}}]`,
wantMatch: "do not pass input.excel_id",
},
{
name: "user filled url",
opsJSON: `[{"shortcut":"+cells-set","input":{"url":"https://x.feishu.cn/sheets/sh","range":"A1"}}]`,
wantMatch: "do not pass input.url",
},
{
name: "extra top-level key",
opsJSON: `[{"shortcut":"+cells-set","input":{"range":"A1"},"tool_name":"oops"}]`,
@@ -405,6 +440,21 @@ func TestBatchUpdate_TranslatorRejects(t *testing.T) {
opsJSON: `[{"shortcut":"+cells-set","input":"not-an-object"}]`,
wantMatch: "'input' must be a JSON object",
},
{
name: "wrapped cell_styles structure",
opsJSON: `[{"shortcut":"+cells-set-style","input":{"sheet_name":"s","range":"A1","cell_styles":{"background_color":"#EBF1F8"}}}]`,
wantMatch: "do not wrap in cell_styles",
},
{
name: "wrapped styles structure",
opsJSON: `[{"shortcut":"+cells-set-style","input":{"sheet_name":"s","range":"A1","styles":{"font_weight":"bold"}}}]`,
wantMatch: "do not wrap in styles",
},
{
name: "wrapped cell_merges structure",
opsJSON: `[{"shortcut":"+cells-set-style","input":{"sheet_name":"s","range":"A1","cell_merges":[{"range":"A1:B1"}]}}]`,
wantMatch: "do not wrap in cell_merges",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
@@ -420,6 +470,99 @@ func TestBatchUpdate_TranslatorRejects(t *testing.T) {
}
}
// TestBatchUpdate_FlattenedStyleKeysNotMistakenForWrapper guards the
// wrapped-structure rejection against overreach: the same style fields in
// their correct flattened form must translate cleanly — only the wrapper
// container keys (cell_styles / styles / cell_merges) are rejected.
func TestBatchUpdate_FlattenedStyleKeysNotMistakenForWrapper(t *testing.T) {
t.Parallel()
got, err := translateBatchOp(map[string]interface{}{
"shortcut": "+cells-set-style",
"input": map[string]interface{}{
"sheet_name": "s",
"range": "A1",
"background_color": "#EBF1F8",
"font_weight": "bold",
},
}, testToken, 0)
if err != nil {
t.Fatalf("flattened style keys must pass the wrapper check, got %v", err)
}
input := got["input"].(map[string]interface{})
cells := input["cells"].([][]interface{})
style := cells[0][0].(map[string]interface{})["cell_styles"].(map[string]interface{})
if style["background_color"] != "#EBF1F8" || style["font_weight"] != "bold" {
t.Fatalf("translated style = %#v", style)
}
}
// TestBatchUpdate_WrapperKeysDisjointFromSubOpFlags locks the static
// assumption wrappedSubOpInputKeys relies on: no shortcut registered in
// batchOpDispatch declares a flag named cell_styles / cell_merges / styles.
// If a future dispatch-table addition (e.g. +table-put) carries one of these
// flags, its legitimate input would be silently rejected by the wrapper
// check — this test turns that silent breakage into a build-time failure.
func TestBatchUpdate_WrapperKeysDisjointFromSubOpFlags(t *testing.T) {
t.Parallel()
wrapped := make(map[string]struct{}, len(wrappedSubOpInputKeys))
for _, k := range wrappedSubOpInputKeys {
wrapped[k] = struct{}{}
}
for shortcut := range batchOpDispatch {
for _, f := range flagsFor(shortcut) {
key := strings.ReplaceAll(f.Name, "-", "_")
if _, clash := wrapped[key]; clash {
t.Errorf("%s declares flag --%s which collides with wrappedSubOpInputKeys; "+
"exempt this shortcut from the wrapper check before adding it to batchOpDispatch",
shortcut, f.Name)
}
}
}
}
// TestBatchUpdate_AggregatesMultipleOpErrors pins op-level aggregation: when
// several operations are invalid, one reply names them all (numbered, with
// each op's own error) instead of failing on the first bad op only. A single
// bad op keeps the historical single-error message (no aggregate wrapper).
func TestBatchUpdate_AggregatesMultipleOpErrors(t *testing.T) {
t.Parallel()
t.Run("two bad ops reported together", func(t *testing.T) {
t.Parallel()
_, _, err := runShortcutCapturingErr(t, BatchUpdate, []string{
"--url", testURL,
"--operations", `[
{"shortcut":"+cells-set-magic","input":{}},
{"shortcut":"+cells-set","input":{"sheet_name":"s","range":"A1"}},
{"shortcut":"+cells-clear","input":{"sheet_name":"s","range":"A1"}}
]`,
"--yes", "--dry-run",
})
requireValidation(t, err, "2 of 3 operations failed validation")
for _, want := range []string{"1) ", "2) ", "operations[0]", "operations[1]"} {
if !strings.Contains(err.Error(), want) {
t.Errorf("aggregated op error should contain %q, got %q", want, err.Error())
}
}
})
t.Run("single bad op keeps plain message", func(t *testing.T) {
t.Parallel()
_, _, err := runShortcutCapturingErr(t, BatchUpdate, []string{
"--url", testURL,
"--operations", `[
{"shortcut":"+cells-set-magic","input":{}},
{"shortcut":"+cells-clear","input":{"sheet_name":"s","range":"A1"}}
]`,
"--yes", "--dry-run",
})
requireValidation(t, err, "not allowed in +batch-update")
if strings.Contains(err.Error(), "operations failed validation") {
t.Errorf("single bad op must not get the aggregate wrapper, got %q", err.Error())
}
})
}
// TestBatchUpdate_PrescriptiveHints pins the recovery hints that ride on the
// highest-frequency batch failures, so an agent can repair its payload in a
// single retry without --help / --print-schema round trips.

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,597 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"strings"
"testing"
)
func chartDryRunSnapshot(t *testing.T, input map[string]interface{}) map[string]interface{} {
t.Helper()
properties, ok := input["properties"].(map[string]interface{})
if !ok {
t.Fatalf("input.properties = %#v, want object", input["properties"])
}
snapshot, ok := properties["snapshot"].(map[string]interface{})
if !ok {
t.Fatalf("input.properties.snapshot = %#v, want object", properties["snapshot"])
}
return snapshot
}
func TestChartCreateBasic_AllTypes(t *testing.T) {
t.Parallel()
types := []string{"column", "bar", "line", "area", "pie", "scatter", "combo", "radar"}
for _, chartType := range types {
chartType := chartType
t.Run(chartType, func(t *testing.T) {
t.Parallel()
rangeValue := "A1:C4"
if chartType == "combo" {
rangeValue = "A1:D4"
}
body := parseDryRunBody(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", chartType,
"--data-range", rangeValue,
})
input := decodeToolInput(t, body, "manage_chart_object")
if input["operation"] != "create" {
t.Fatalf("operation = %v, want create", input["operation"])
}
if _, ok := input["properties"]; ok {
t.Fatal("semantic create must not send properties")
}
basic, _ := input["basic_chart"].(map[string]interface{})
if basic["chart_type"] != chartType || basic["data_range"] != rangeValue {
t.Fatalf("basic_chart = %#v", basic)
}
})
}
}
func TestChartCreateBasic_ConfigAndPlacement(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", "line",
"--data-range", "A1:C4",
"--anchor-cell", "f2",
"--width", "640",
"--height", "360",
"--title", "Trend",
"--legend-position", "bottom",
"--smooth=false",
"--data-direction", "row",
"--color-palette", "brandColorSeries@v2",
})
input := decodeToolInput(t, body, "manage_chart_object")
basic, _ := input["basic_chart"].(map[string]interface{})
position, _ := basic["position"].(map[string]interface{})
size, _ := basic["size"].(map[string]interface{})
if position["col"] != "F" || position["row"] != float64(1) {
t.Errorf("position = %#v, want F2 as zero-based row 1", position)
}
if size["width"] != float64(640) || size["height"] != float64(360) {
t.Errorf("size = %#v", size)
}
if basic["title"] != "Trend" || basic["legend_position"] != "bottom" || basic["smooth"] != false ||
basic["data_direction"] != "row" || basic["color_palette"] != "brandColorSeries@v2" {
t.Errorf("semantic config = %#v", basic)
}
}
func TestChartCreateBasic_MultipleAlignedRanges(t *testing.T) {
t.Parallel()
rangeValue := "'Data, 2026'!A1:A10,'Data, 2026'!K1:L10"
body := parseDryRunBody(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", "line",
"--data-range", rangeValue,
})
input := decodeToolInput(t, body, "manage_chart_object")
basic := input["basic_chart"].(map[string]interface{})
if basic["data_range"] != rangeValue {
t.Fatalf("basic_chart.data_range = %v, want %q", basic["data_range"], rangeValue)
}
}
func TestChartCreateBasic_DetachedHeaderRange(t *testing.T) {
t.Parallel()
dataRange := "'Sheet1'!A2:A10,'Sheet1'!K2:L10"
headerRange := "'Sheet1'!A1,'Sheet1'!K1:L1"
body := parseDryRunBody(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", "line",
"--data-range", dataRange,
"--header-range", headerRange,
})
input := decodeToolInput(t, body, "manage_chart_object")
basic := input["basic_chart"].(map[string]interface{})
if basic["data_range"] != dataRange || basic["header_range"] != headerRange {
t.Fatalf("basic_chart = %#v", basic)
}
}
func TestChartCreateBasic_MergesMisalignedOrOverlappingRanges(t *testing.T) {
t.Parallel()
tests := []struct {
name string
input string
expected string
}{
{name: "separated rows", input: "'Sheet1'!A1:M1,'Sheet1'!A3:M3", expected: "'Sheet1'!A1:M3"},
{name: "overlapping columns", input: "A1:B10,B1:C10", expected: "A1:C10"},
}
for _, tt := range tests {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", "line",
"--data-range", tt.input,
})
input := decodeToolInput(t, body, "manage_chart_object")
basic := input["basic_chart"].(map[string]interface{})
if basic["data_range"] != tt.expected {
t.Fatalf("basic_chart.data_range = %v, want %q", basic["data_range"], tt.expected)
}
})
}
}
func TestChartCreateBasic_PreservesAlignedCrossSheetRanges(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", "line",
"--data-range", "'A'!A1:A10,'B'!A1:B10",
})
input := decodeToolInput(t, body, "manage_chart_object")
basic := input["basic_chart"].(map[string]interface{})
if got, want := basic["data_range"], "'A'!A1:A10,'B'!A1:B10"; got != want {
t.Fatalf("basic_chart.data_range = %v, want %q", got, want)
}
}
func TestChartSemanticShortcuts_InDedicatedBatch(t *testing.T) {
body := parseDryRunBody(t, BatchChartCreate, []string{
"--url", testURL,
"--operations", `[
{"sheet-id":"sh1","chart-type":"column","data-range":"A1:C10","title":"Sales"},
{"sheet-id":"sh1","chart-type":"line","data-range":"E1:G10","title":"Trend"}
]`,
})
input := decodeToolInput(t, body, "batch_update")
ops := input["operations"].([]interface{})
if len(ops) != 2 {
t.Fatalf("operations len = %d, want 2", len(ops))
}
for i, op := range ops {
item := op.(map[string]interface{})
if item["tool_name"] != "manage_chart_object" {
t.Fatalf("operations[%d].tool_name = %v", i, item["tool_name"])
}
chartInput := item["input"].(map[string]interface{})
if chartInput["operation"] != "create" {
t.Fatalf("operations[%d].input.operation = %v", i, chartInput["operation"])
}
if _, ok := chartInput["basic_chart"].(map[string]interface{}); !ok {
t.Fatalf("operations[%d].input.basic_chart = %#v", i, chartInput["basic_chart"])
}
}
}
func TestBatchChartCreate_LegacyWrappedInputStillAccepted(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, BatchChartCreate, []string{
"--url", testURL,
"--operations", `[{
"shortcut":"+chart-create-basic",
"input":{"sheet_id":"sh1","chart_type":"line","data_range":"A1:C10"}
}]`,
})
input := decodeToolInput(t, body, "batch_update")
ops := input["operations"].([]interface{})
if len(ops) != 1 || ops[0].(map[string]interface{})["tool_name"] != "manage_chart_object" {
t.Fatalf("legacy wrapped operation was not translated: %#v", ops)
}
}
func TestChartConfigUpdate_PartialFields(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, ChartConfigUpdate, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-id", "chart-1",
"--y-axis-title", "Revenue",
"--stack", "percent",
"--smooth=false",
"--colors", "#112233,#445566",
})
input := decodeToolInput(t, body, "manage_chart_object")
if input["operation"] != "update" || input["chart_id"] != "chart-1" {
t.Fatalf("input = %#v", input)
}
snapshot := chartDryRunSnapshot(t, input)
plotArea := snapshot["plotArea"].(map[string]interface{})
plot := plotArea["plot"].(map[string]interface{})
extra := plot["extra"].(map[string]interface{})
if extra["smooth"] != false || extra["stack"].(map[string]interface{})["percentage"] != true {
t.Errorf("plot extra = %#v", extra)
}
style, _ := snapshot["style"].(map[string]interface{})
colors, _ := style["colorTheme"].([]interface{})
if len(colors) != 2 || colors[0] != "#112233" || colors[1] != "#445566" {
t.Errorf("snapshot.style.colorTheme = %#v", style["colorTheme"])
}
axes := plotArea["axes"].([]interface{})
if axes[0].(map[string]interface{})["title"].(map[string]interface{})["text"] != "Revenue" {
t.Errorf("axes = %#v", axes)
}
}
func TestChartConfigUpdate_SpacedSmoothBool(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, ChartConfigUpdate, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-id", "chart-1",
"--smooth", "false",
})
input := decodeToolInput(t, body, "manage_chart_object")
plot := chartDryRunSnapshot(t, input)["plotArea"].(map[string]interface{})["plot"].(map[string]interface{})
if plot["extra"].(map[string]interface{})["smooth"] != false {
t.Fatalf("snapshot smooth = %v, want false", plot)
}
}
func TestChartSemanticShortcuts_CompatibleAliases(t *testing.T) {
t.Parallel()
chartCreateBasic := shortcutFromRegistry(t, "+chart-create-basic")
chartConfigUpdate := shortcutFromRegistry(t, "+chart-config-update")
body := parseDryRunBody(t, chartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--type", "line",
"--range", "A1:C10",
"--x-axis", "Month",
"--y-axis", "Revenue",
})
basic := decodeToolInput(t, body, "manage_chart_object")["basic_chart"].(map[string]interface{})
if basic["chart_type"] != "line" || basic["data_range"] != "A1:C10" ||
basic["x_axis_title"] != "Month" || basic["y_axis_title"] != "Revenue" {
t.Fatalf("chart create aliases = %#v", basic)
}
body = parseDryRunBody(t, chartConfigUpdate, []string{
"--url", testURL, "--sheet-id", testSheetID, "--chart-id", "chart-1", "--stacked",
})
snapshot := chartDryRunSnapshot(t, decodeToolInput(t, body, "manage_chart_object"))
extra := snapshot["plotArea"].(map[string]interface{})["plot"].(map[string]interface{})["extra"].(map[string]interface{})
if extra["stack"].(map[string]interface{})["percentage"] != false {
t.Fatalf("--stacked normalized stack = %#v, want non-percentage stack", extra["stack"])
}
body = parseDryRunBody(t, chartConfigUpdate, []string{
"--url", testURL, "--sheet-id", testSheetID, "--chart-id", "chart-1", "--data-labels", "category_percentage",
})
snapshot = chartDryRunSnapshot(t, decodeToolInput(t, body, "manage_chart_object"))
labels := snapshot["plotArea"].(map[string]interface{})["plot"].(map[string]interface{})["labels"].(map[string]interface{})
if labels["value"] != true || labels["percentage"] != true {
t.Fatalf("data-labels normalized value = %#v, want value+percentage", labels)
}
body = parseDryRunBody(t, chartConfigUpdate, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-id", "chart-1",
"--x-axis", "Month",
"--y-axis", "Revenue",
"--data-labels", "percentage,value",
})
snapshot = chartDryRunSnapshot(t, decodeToolInput(t, body, "manage_chart_object"))
plotArea := snapshot["plotArea"].(map[string]interface{})
axes := plotArea["axes"].([]interface{})
labels = plotArea["plot"].(map[string]interface{})["labels"].(map[string]interface{})
if axes[0].(map[string]interface{})["title"].(map[string]interface{})["text"] != "Month" ||
axes[1].(map[string]interface{})["title"].(map[string]interface{})["text"] != "Revenue" ||
labels["value"] != true || labels["percentage"] != true {
t.Fatalf("chart config aliases = %#v", snapshot)
}
}
func TestChartSemanticShortcuts_CompatibleAliasesInBatch(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, BatchChartUpdate, []string{
"--url", testURL,
"--operations", `[{"shortcut":"+chart-config-update","input":{"sheet_id":"sh1","chart_id":"chart-1","stacked":true,"x_axis":"Month","y_axis":"Revenue","data_labels":"value,percentage","smooth":false}}]`,
})
input := decodeToolInput(t, body, "batch_update")
ops := input["operations"].([]interface{})
chartInput := ops[0].(map[string]interface{})["input"].(map[string]interface{})
snapshot := chartDryRunSnapshot(t, chartInput)
plotArea := snapshot["plotArea"].(map[string]interface{})
plot := plotArea["plot"].(map[string]interface{})
labels := plot["labels"].(map[string]interface{})
extra := plot["extra"].(map[string]interface{})
if labels["value"] != true || labels["percentage"] != true || extra["smooth"] != false ||
extra["stack"].(map[string]interface{})["percentage"] != false {
t.Fatalf("batch config patch = %#v", snapshot)
}
}
func TestChartSemanticShortcuts_SingleCustomColorIsExpanded(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", "line",
"--data-range", "A1:C10",
"--colors", "#112233",
})
basic := decodeToolInput(t, body, "manage_chart_object")["basic_chart"].(map[string]interface{})
colors := basic["colors"].([]interface{})
if len(colors) != 2 || colors[0] != "#112233" || colors[1] != "#112233" {
t.Fatalf("standalone colors = %#v", colors)
}
body = parseDryRunBody(t, BatchChartCreate, []string{
"--url", testURL,
"--operations", `[{
"sheet_id":"sh1","type":"line","range":"A1:C10","colors":["#445566"]
}]`,
})
input := decodeToolInput(t, body, "batch_update")
ops := input["operations"].([]interface{})
basic = ops[0].(map[string]interface{})["input"].(map[string]interface{})["basic_chart"].(map[string]interface{})
colors = basic["colors"].([]interface{})
if len(colors) != 2 || colors[0] != "#445566" || colors[1] != "#445566" {
t.Fatalf("batch array colors = %#v", colors)
}
}
func TestChartCreateBasic_RejectsMoreThanFiftySeries(t *testing.T) {
t.Parallel()
_, _, err := runShortcutCapturingErr(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", "line",
"--data-range", "A2:DV7",
"--data-direction", "column",
})
requireValidation(t, err, "create 125 series")
if !strings.Contains(err.Error(), "current limit of 50") ||
!strings.Contains(err.Error(), "compact summary table") {
t.Fatalf("series limit error is not actionable: %v", err)
}
}
func TestChartCreateBasic_SelectsDimensionsAtCreation(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", "line",
"--data-range", "A1:DV7",
"--dim1-index", "3",
"--dim2-indexes", "2,6,8",
})
basic := decodeToolInput(t, body, "manage_chart_object")["basic_chart"].(map[string]interface{})
if basic["dim1_index"] != float64(3) {
t.Fatalf("basic_chart.dim1_index = %#v", basic["dim1_index"])
}
indexes := basic["dim2_indexes"].([]interface{})
if len(indexes) != 3 || indexes[0] != float64(2) || indexes[1] != float64(6) || indexes[2] != float64(8) {
t.Fatalf("basic_chart.dim2_indexes = %#v", indexes)
}
}
func TestChartCreateBasic_SelectsDimensionsInBatch(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, BatchChartCreate, []string{
"--url", testURL,
"--operations", `[{
"sheet_id":"sh1","chart_type":"line","data_range":"A1:DV7","dim1_index":3,"dim2_indexes":[2,6,8]
}]`,
})
input := decodeToolInput(t, body, "batch_update")
ops := input["operations"].([]interface{})
basic := ops[0].(map[string]interface{})["input"].(map[string]interface{})["basic_chart"].(map[string]interface{})
if basic["dim1_index"] != float64(3) {
t.Fatalf("batch basic_chart.dim1_index = %#v", basic["dim1_index"])
}
indexes := basic["dim2_indexes"].([]interface{})
if len(indexes) != 3 || indexes[0] != float64(2) || indexes[1] != float64(6) || indexes[2] != float64(8) {
t.Fatalf("batch basic_chart.dim2_indexes = %#v", indexes)
}
}
func TestChartCreateBasic_RejectsHorizontalHeaderForRowDirection(t *testing.T) {
t.Parallel()
_, _, err := runShortcutCapturingErr(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", "line",
"--data-range", "'Sheet1'!A3:M3,'Sheet1'!A5:M5",
"--header-range", "'Sheet1'!A1:M1",
"--data-direction", "row",
})
requireValidation(t, err, "looks like a category row")
if !strings.Contains(err.Error(), "include it in --data-range") {
t.Fatalf("header-range error is not actionable: %v", err)
}
}
func TestChartCreateBasic_SuggestsRowDirectionForHorizontalCategories(t *testing.T) {
t.Parallel()
_, _, err := runShortcutCapturingErr(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", "line",
"--data-range", "'Sheet1'!A1:M1",
})
requireValidation(t, err, "--data-direction row")
}
func TestChartDataUpdate_MapsToPartialProperties(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, ChartDataUpdate, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-id", "chart-1",
"--data-range", "'Sheet1'!A1:M6",
})
input := decodeToolInput(t, body, "manage_chart_object")
if input["operation"] != "update" || input["chart_id"] != "chart-1" {
t.Fatalf("input = %#v", input)
}
data := chartDryRunSnapshot(t, input)["data"].(map[string]interface{})
refs := data["refs"].([]interface{})
if refs[0].(map[string]interface{})["value"] != "'Sheet1'!A1:M6" {
t.Errorf("data patch = %#v", data)
}
if _, ok := data["direction"]; ok {
t.Errorf("omitted --data-direction must be resolved from the current snapshot during execution: %#v", data)
}
}
func TestChartDataUpdate_ExplicitDirectionAndMultipleRanges(t *testing.T) {
t.Parallel()
dataRange := "'Sheet1'!A1:A10,'Sheet2'!A1:B10"
body := parseDryRunBody(t, ChartDataUpdate, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-id", "chart-1",
"--data-range", dataRange,
"--data-direction", "column",
})
input := decodeToolInput(t, body, "manage_chart_object")
data := chartDryRunSnapshot(t, input)["data"].(map[string]interface{})
refs := data["refs"].([]interface{})
if data["direction"] != "column" || len(refs) != 2 {
t.Errorf("data patch = %#v", data)
}
if refs[0].(map[string]interface{})["value"] != "'Sheet1'!A1:A10" ||
refs[1].(map[string]interface{})["value"] != "'Sheet2'!A1:B10" {
t.Errorf("cross-sheet refs = %#v, want %q", refs, dataRange)
}
}
func TestChartDataUpdate_DetachedHeaderRange(t *testing.T) {
t.Parallel()
dataRange := "'Sheet1'!A2:A10,'Sheet1'!K2:L10"
headerRange := "'Sheet1'!A1,'Sheet1'!K1:L1"
body := parseDryRunBody(t, ChartDataUpdate, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-id", "chart-1",
"--data-range", dataRange,
"--header-range", headerRange,
})
input := decodeToolInput(t, body, "manage_chart_object")
data := chartDryRunSnapshot(t, input)["data"].(map[string]interface{})
if data["headerMode"] != "detached" {
t.Fatalf("data patch = %#v", data)
}
dim1 := data["dim1"].(map[string]interface{})["serie"].(map[string]interface{})
if dim1["nameRef"] != "'Sheet1'!A1" {
t.Fatalf("detached dim1 = %#v", dim1)
}
}
func TestChartDataUpdate_ExplicitSeriesIndexes(t *testing.T) {
t.Parallel()
body := parseDryRunBody(t, ChartDataUpdate, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-id", "chart-1",
"--data-range", "'Sheet1'!A1:M6",
"--dim1-index", "1",
"--dim2-indexes", "4, 8",
})
input := decodeToolInput(t, body, "manage_chart_object")
data := chartDryRunSnapshot(t, input)["data"].(map[string]interface{})
dim1 := data["dim1"].(map[string]interface{})["serie"].(map[string]interface{})
if dim1["index"] != float64(1) {
t.Errorf("data.dim1 = %#v", dim1)
}
series := data["dim2"].(map[string]interface{})["series"].([]interface{})
if len(series) != 2 || series[0].(map[string]interface{})["index"] != float64(4) ||
series[1].(map[string]interface{})["index"] != float64(8) {
t.Errorf("data.dim2 = %#v", series)
}
}
func TestChartSemanticShortcuts_Validation(t *testing.T) {
t.Parallel()
tests := []struct {
name string
args []string
}{
{name: "unsupported type", args: []string{"--url", testURL, "--sheet-id", testSheetID, "--chart-type", "donut", "--data-range", "A1:C4"}},
{name: "invalid semantic enum", args: []string{"--url", testURL, "--sheet-id", testSheetID, "--chart-type", "line", "--data-range", "A1:C4", "--legend-position", "diagonal"}},
{name: "range too small", args: []string{"--url", testURL, "--sheet-id", testSheetID, "--chart-type", "line", "--data-range", "A1:A4"}},
{name: "combo needs two series", args: []string{"--url", testURL, "--sheet-id", testSheetID, "--chart-type", "combo", "--data-range", "A1:B4"}},
{name: "invalid direction", args: []string{"--url", testURL, "--sheet-id", testSheetID, "--chart-type", "line", "--data-range", "A1:C4", "--data-direction", "horizontal"}},
{name: "colors cannot be empty", args: []string{"--url", testURL, "--sheet-id", testSheetID, "--chart-type", "line", "--data-range", "A1:C4", "--colors", ""}},
{name: "palette and colors are exclusive", args: []string{"--url", testURL, "--sheet-id", testSheetID, "--chart-type", "line", "--data-range", "A1:C4", "--color-palette", "brandColorSeries@v2", "--colors", "#112233,#445566"}},
{name: "size must be paired", args: []string{"--url", testURL, "--sheet-id", testSheetID, "--chart-type", "line", "--data-range", "A1:C4", "--width", "640"}},
{name: "misaligned cross-sheet ranges", args: []string{"--url", testURL, "--sheet-id", testSheetID, "--chart-type", "line", "--data-range", "'A'!A1:A4,'B'!B2:C4"}},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
_, _, err := runShortcutCapturingErr(t, ChartCreateBasic, tt.args)
if err == nil {
t.Fatal("expected validation error")
}
})
}
body := parseDryRunBody(t, ChartCreateBasic, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-type", "line",
"--data-range", "A2:C4",
"--header-range", "'A'!A1,'B'!B1:C1",
})
input := decodeToolInput(t, body, "manage_chart_object")
basic := input["basic_chart"].(map[string]interface{})
if got, want := basic["header_range"], "'A'!A1,'B'!B1:C1"; got != want {
t.Fatalf("basic_chart.header_range = %v, want %q", got, want)
}
_, _, err := runShortcutCapturingErr(t, ChartConfigUpdate, []string{
"--url", testURL,
"--sheet-id", testSheetID,
"--chart-id", "chart-1",
})
if err == nil {
t.Fatal("expected config update with no changed field to fail")
}
for _, args := range [][]string{
{"--url", testURL, "--sheet-id", testSheetID, "--data-range", "A1:C4"},
{"--url", testURL, "--sheet-id", testSheetID, "--chart-id", "chart-1"},
{"--url", testURL, "--sheet-id", testSheetID, "--chart-id", "chart-1", "--data-range", "A1:C4", "--data-direction", "horizontal"},
{"--url", testURL, "--sheet-id", testSheetID, "--chart-id", "chart-1", "--data-range", "A1:C4", "--dim1-index", "0"},
{"--url", testURL, "--sheet-id", testSheetID, "--chart-id", "chart-1", "--data-range", "A1:C4", "--dim2-indexes", "2,2"},
{"--url", testURL, "--sheet-id", testSheetID, "--chart-id", "chart-1", "--data-range", "A1:C4", "--dim2-indexes", "1,2"},
} {
_, _, err = runShortcutCapturingErr(t, ChartDataUpdate, args)
if err == nil {
t.Fatalf("expected chart data update validation error for args %#v", args)
}
}
}

View File

@@ -67,7 +67,7 @@ var CellsClear = common.Shortcut{
return nil
},
Tips: []string{
"high-risk-write — always preview with --dry-run; clear is not undoable.",
"high-risk-write — pass --yes to confirm (exit 10 without it), or preview with --dry-run first; clear is not undoable.",
"Can't delete an embedded pivot/chart by clearing cells — remove the object itself with +pivot-delete / +chart-delete.",
},
}
@@ -266,9 +266,13 @@ var ColsResize = common.Shortcut{
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+cols-resize"),
Validate: validateViaResize("column"),
DryRun: resizeDryRun("column"),
Execute: resizeExecute("column"),
Tips: []string{
"Example: lark-cli sheets +cols-resize --url <URL> --sheet-name Sheet1 --range A:C --width 120",
`Different widths per column in one atomic call: --widths '{"A":80,"C:E":120}'. Widths are pixels (px ≈ chars × 8 + 16), not Excel character units.`,
},
Validate: validateViaResize("column"),
DryRun: resizeDryRun("column"),
Execute: resizeExecute("column"),
}
// resizeDryRun / resizeExecute route a resize shortcut through resizeToolCall

View File

@@ -69,8 +69,7 @@ var CellsGet = common.Shortcut{
if err != nil {
return err
}
runtime.Out(out, nil)
return nil
return emitReadResult(runtime, out)
},
}
@@ -88,17 +87,19 @@ func cellsGetInput(runtime *common.RuntimeContext, token, sheetID, sheetName str
// read cap. Pin cell_limit very high so the tool's own default never binds
// before max_chars.
input["cell_limit"] = unboundedReadLimit
if n := runtime.Int("max-chars"); n > 0 {
if n, ok := maxCharsInput(runtime); ok {
input["max_chars"] = n
}
return input
}
// applyIncludeToCellsGet maps the fine-grained --include vocabulary to the
// tool's two coarse switches:
// tool's switches:
//
// - include_styles (bool) — toggled by "style" presence
// - value_render_option (enum) — "formula" → formula; otherwise omitted
// - include_truncation_info (bool) — toggled by "truncation" presence; makes
// the tool estimate and return per-cell isRowTruncated / isColTruncated
//
// "value", "comment", and "data_validation" are always returned by the tool
// per the schema; they have no dedicated knob today but are accepted in
@@ -119,6 +120,9 @@ func applyIncludeToCellsGet(input map[string]interface{}, include []string) {
if want["formula"] {
input["value_render_option"] = "formula"
}
if want["truncation"] {
input["include_truncation_info"] = true
}
}
// CsvGet wraps get_range_as_csv: pull one range as RFC 4180 CSV with optional
@@ -139,9 +143,6 @@ var CsvGet = common.Shortcut{
if _, _, err := resolveSheetSelector(runtime); err != nil {
return err
}
if strings.TrimSpace(runtime.Str("range")) == "" {
return sheetsValidationForFlag("range", "--range is required")
}
return nil
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
@@ -165,16 +166,25 @@ var CsvGet = common.Shortcut{
if !runtime.Bool("include-row-prefix") {
out = stripRowPrefixFromCsvOutput(out)
}
runtime.Out(out, nil)
return nil
return emitReadResult(runtime, out)
},
}
// csvGetFullSheetRange is the range sent when --range is omitted: the tool
// requires one, but clips anything past the grid bounds and reports the clip
// in actual_range — so an over-wide whole-columns range reads the entire
// sheet in one call, with no workbook-info pre-flight. Eval traces show
// "read the whole sheet" as a recurring intent (--range was the single most
// missed required flag once the rest of the surface was fixed).
const csvGetFullSheetRange = "A:ZZZ"
func csvGetInput(runtime *common.RuntimeContext, token, sheetID, sheetName string) map[string]interface{} {
input := map[string]interface{}{"excel_id": token}
sheetSelectorForToolInput(input, sheetID, sheetName)
if r := strings.TrimSpace(runtime.Str("range")); r != "" {
input["range"] = r
} else {
input["range"] = csvGetFullSheetRange
}
if runtime.Bool("skip-hidden") {
input["skip_hidden"] = true
@@ -183,7 +193,7 @@ func csvGetInput(runtime *common.RuntimeContext, token, sheetID, sheetName strin
// read cap. Pin max_rows very high so the tool's own default never binds
// before max_chars.
input["max_rows"] = unboundedReadLimit
if n := runtime.Int("max-chars"); n > 0 {
if n, ok := maxCharsInput(runtime); ok {
input["max_chars"] = n
}
return input

View File

@@ -34,6 +34,22 @@ func TestReadDataShortcuts_DryRun(t *testing.T) {
"cell_limit": float64(unboundedReadLimit), // pinned high; --max-chars is the only cap
},
},
{
// --include truncation toggles include_truncation_info so the tool
// estimates and returns per-cell isRowTruncated / isColTruncated.
name: "+cells-get include=truncation",
sc: CellsGet,
args: []string{"--url", testURL, "--sheet-id", testSheetID, "--range", "A1:B2", "--include", "truncation"},
toolName: "get_cell_ranges",
wantInput: map[string]interface{}{
"excel_id": testToken,
"sheet_id": testSheetID,
"ranges": []interface{}{"A1:B2"},
"include_styles": false,
"include_truncation_info": true,
"cell_limit": float64(unboundedReadLimit),
},
},
{
// Canonical form: --sheet-id + bare --range. Aligned with
// +cells-get / +csv-get; before the e2e BUG-019 fix this
@@ -92,7 +108,9 @@ func TestDropdownGet_RequiresSheetSelector(t *testing.T) {
// TestReadData_RequiresRange covers the trim-based --range guard on the
// single-range readers (--range "" slips past cobra's MarkFlagRequired but
// must still be rejected by Validate).
// must still be rejected by Validate). +csv-get is deliberately absent:
// its --range is optional — omitted/blank means a whole-sheet read (see
// TestCsvGet_RangeOptionalDefaultsToFullSheet).
func TestReadData_RequiresRange(t *testing.T) {
t.Parallel()
cases := []struct {
@@ -100,7 +118,6 @@ func TestReadData_RequiresRange(t *testing.T) {
sc common.Shortcut
}{
{"+cells-get", CellsGet},
{"+csv-get", CsvGet},
{"+dropdown-get", DropdownGet},
}
for _, c := range cases {
@@ -114,6 +131,23 @@ func TestReadData_RequiresRange(t *testing.T) {
}
}
// TestCsvGet_RangeOptionalDefaultsToFullSheet pins the whole-sheet default:
// with --range omitted the request carries the over-wide clip range, so a
// full read needs no workbook-info pre-flight (eval: --range was the most
// missed required flag on +csv-get once the rest of the surface settled).
func TestCsvGet_RangeOptionalDefaultsToFullSheet(t *testing.T) {
t.Parallel()
stdout, _, err := runShortcutCapturingErr(t, CsvGet, []string{
"--url", testURL, "--sheet-id", testSheetID, "--dry-run",
})
if err != nil {
t.Fatalf("rangeless +csv-get must pass validation, got: %v", err)
}
if !strings.Contains(stdout, csvGetFullSheetRange) {
t.Fatalf("dry-run body should carry the full-sheet range %q, got %q", csvGetFullSheetRange, stdout)
}
}
// TestInfoTypeFromInclude exercises the fine-grained → coarse mapping
// directly (white-box).
func TestInfoTypeFromInclude(t *testing.T) {

View File

@@ -6,6 +6,7 @@ package sheets
import (
"context"
"fmt"
"sort"
"strconv"
"strings"
@@ -128,12 +129,20 @@ var DimInsert = common.Shortcut{
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+dim-insert"),
Validate: validateViaInput(dimInsertInput),
Tips: []string{
"Example: lark-cli sheets +dim-insert --url <URL> --sheet-name Sheet1 --position 3 --count 2 --inherit-style before",
"Rows vs columns comes from --position alone: a row number (3) inserts rows, a column letter (C) inserts columns — there is no --dimension flag.",
},
Validate: validateViaInput(dimInsertInput),
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
token, _ := resolveSpreadsheetToken(runtime)
sheetID, sheetName, _ := resolveSheetSelector(runtime)
input, _ := dimInsertInput(runtime, token, sheetID, sheetName)
return invokeToolDryRun(token, ToolKindWrite, "modify_sheet_structure", input)
dr := invokeToolDryRun(token, ToolKindWrite, "modify_sheet_structure", input)
if dimInsertNeedsBeforeStyleWarning(runtime) {
dr.Set("warning_message", dimInsertBeforeStyleWarning)
}
return dr
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
token, err := resolveSpreadsheetTokenExec(runtime)
@@ -148,6 +157,9 @@ var DimInsert = common.Shortcut{
if err != nil {
return err
}
if dimInsertNeedsBeforeStyleWarning(runtime) {
fmt.Fprintln(runtime.IO().ErrOut, dimInsertBeforeStyleWarning)
}
out, err := callTool(ctx, runtime, token, ToolKindWrite, "modify_sheet_structure", input)
if err != nil {
return err
@@ -157,8 +169,31 @@ var DimInsert = common.Shortcut{
},
}
// dimInsertBeforeStyleWarning fires only when the preceding-side style cannot
// be copied: --inherit-style before at the first row/column, where no
// preceding row/column exists. The row/column is still inserted before
// --position, just without style inheritance. (--inherit-style after has no
// such edge — a plain before-insert always has a following row/column.)
const dimInsertBeforeStyleWarning = "warning: --inherit-style before cannot copy the preceding row/column's style at the first row/column (no preceding row/column exists); inserting before --position without style inheritance. Copy styles separately if needed."
func dimInsertNeedsBeforeStyleWarning(runtime flagView) bool {
if !runtime.Changed("inherit-style") || runtime.Str("inherit-style") != "before" {
return false
}
// Only the first row/column (idx 0) has no preceding row/column.
_, idx, err := parseA1Position(strings.TrimSpace(runtime.Str("position")))
return err == nil && idx == 0
}
// dimInsertInput passes --position (1-based row number "3" or column letter
// "C") straight to the tool's `position` field; --count maps to `count`.
// "C") to the tool's `position` field; --count maps to `count`.
//
// +dim-insert's public contract is always "insert before --position";
// --inherit-style only selects which side's style the new row/column copies,
// never the insertion side. The sheet-ai tool always copies the *anchor*
// column's style (the target passed as position), regardless of side — so
// --inherit-style before is emulated by anchoring one unit earlier. See the
// switch below.
func dimInsertInput(runtime flagView, token, sheetID, sheetName string) (map[string]interface{}, error) {
if err := requireSheetSelector(sheetID, sheetName); err != nil {
return nil, err
@@ -184,11 +219,27 @@ func dimInsertInput(runtime flagView, token, sheetID, sheetName string) (map[str
"count": count,
}
sheetSelectorForToolInput(input, sheetID, sheetName)
// --inherit-style selects which side's style the blank row/column copies;
// the insertion always lands *before* --position. Empirically the addCol
// backend copies the *anchor* column's style (the target passed as
// position), regardless of side — side only decides whether the blank lands
// before or after that anchor (verified live, see
// TestDimInsertInheritStyleSideMapping):
// after → side=before at P: the blank lands at P and anchor P becomes the
// *following* neighbour, so the blank copies it. Position unchanged.
// before → side=after at P-1: the blank still lands at P (insert-after-(P-1)
// == insert-before-P) and anchor P-1 becomes the *preceding*
// neighbour, so the blank copies it.
switch runtime.Str("inherit-style") {
case "before":
input["side"] = "before"
case "after":
input["side"] = "after"
input["side"] = "before"
case "before":
if prev, ok := a1PositionBefore(position); ok {
input["side"] = "after"
input["position"] = prev
}
// First row/column: no preceding row/column exists, so fall back to a
// plain before-insert (dimInsertNeedsBeforeStyleWarning surfaces this).
}
return input, nil
}
@@ -203,10 +254,34 @@ var DimDelete = common.Shortcut{
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+dim-delete"),
Validate: validateDimRangeOp("delete"),
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
if runtime.Changed("ranges") {
if runtime.Changed("range") {
return sheetsValidationForFlag("ranges", "--range and --ranges are mutually exclusive; put every range into --ranges")
}
token, err := resolveSpreadsheetToken(runtime)
if err != nil {
return err
}
sheetID, sheetName, err := resolveSheetSelector(runtime)
if err != nil {
return err
}
_, err = dimDeleteRangesOps(runtime, token, sheetID, sheetName)
return err
}
return validateDimRangeOp("delete")(ctx, runtime)
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
token, _ := resolveSpreadsheetToken(runtime)
sheetID, sheetName, _ := resolveSheetSelector(runtime)
if runtime.Changed("ranges") {
ops, _ := dimDeleteRangesOps(runtime, token, sheetID, sheetName)
return invokeToolDryRun(token, ToolKindWrite, "batch_update", map[string]interface{}{
"excel_id": token,
"operations": ops,
})
}
input, _ := dimRangeOpInput(runtime, token, sheetID, sheetName, "delete")
return invokeToolDryRun(token, ToolKindWrite, "modify_sheet_structure", input)
},
@@ -219,6 +294,21 @@ var DimDelete = common.Shortcut{
if err != nil {
return err
}
if runtime.Changed("ranges") {
ops, err := dimDeleteRangesOps(runtime, token, sheetID, sheetName)
if err != nil {
return err
}
out, err := callTool(ctx, runtime, token, ToolKindWrite, "batch_update", map[string]interface{}{
"excel_id": token,
"operations": ops,
})
if err != nil {
return err
}
runtime.Out(out, nil)
return nil
}
input, err := dimRangeOpInput(runtime, token, sheetID, sheetName, "delete")
if err != nil {
return err
@@ -232,9 +322,76 @@ var DimDelete = common.Shortcut{
},
Tips: []string{
"Row/column deletion is irreversible. Always preview with --dry-run first.",
`Scattered ranges: --ranges '["5:5","8:8","11:13"]' deletes them in one atomic call — the CLI orders positions descending, so indexes never shift under you.`,
},
}
// dimDeleteRangesOps parses --ranges into one atomic batch of
// modify_sheet_structure delete ops, ordered DESCENDING by start position:
// deleting an earlier row shifts every later index up, so ascending
// execution deletes the wrong rows — the recurring failure of hand-built
// dim-delete batches in eval traces. Same-dimension and non-overlap are
// enforced up front.
func dimDeleteRangesOps(runtime flagView, token, sheetID, sheetName string) ([]interface{}, error) {
if err := requireSheetSelector(sheetID, sheetName); err != nil {
return nil, err
}
raw, err := requireJSONArray(runtime, "ranges")
if err != nil {
return nil, err
}
if len(raw) == 0 {
return nil, sheetsValidationForFlag("ranges", "--ranges must be a non-empty JSON array")
}
if len(raw) > maxBatchRanges {
return nil, sheetsValidationForFlag("ranges", "--ranges accepts at most %d entries; got %d", maxBatchRanges, len(raw))
}
type span struct {
raw string
start, end int
}
spans := make([]span, 0, len(raw))
dimension := ""
for i, v := range raw {
s, ok := v.(string)
if !ok {
return nil, sheetsValidationForFlag("ranges", "--ranges[%d] must be a string", i)
}
dim, start, end, err := parseA1Range(s)
if err != nil {
return nil, sheetsValidationForFlag("ranges", "--ranges[%d] %q: %v", i, s, err)
}
if dimension == "" {
dimension = dim
} else if dim != dimension {
return nil, sheetsValidationForFlag("ranges", "--ranges[%d] %q is a %s range but earlier entries are %s ranges; one call deletes rows OR columns, not both", i, s, dim, dimension)
}
spans = append(spans, span{raw: strings.TrimSpace(s), start: start, end: end})
}
sort.Slice(spans, func(i, j int) bool { return spans[i].start > spans[j].start })
for i := 1; i < len(spans); i++ {
// Descending order: spans[i-1] starts at or after spans[i]. Overlap
// (or duplicate) makes the later delete hit already-shifted positions.
if spans[i].end >= spans[i-1].start {
return nil, sheetsValidationForFlag("ranges", "--ranges entries %q and %q overlap; merge them into one range", spans[i].raw, spans[i-1].raw)
}
}
ops := make([]interface{}, 0, len(spans))
for _, sp := range spans {
input := map[string]interface{}{
"excel_id": token,
"operation": "delete",
"range": sp.raw,
}
sheetSelectorForToolInput(input, sheetID, sheetName)
ops = append(ops, map[string]interface{}{
"tool_name": "modify_sheet_structure",
"input": input,
})
}
return ops, nil
}
// validateDimRangeOp returns a Validate closure that delegates to
// dimRangeOpInput for shortcuts (delete/hide/unhide) whose builder takes an
// extra `op` argument. Token check happens here; the rest is the builder.
@@ -292,7 +449,10 @@ var DimFreeze = common.Shortcut{
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+dim-freeze"),
Validate: validateViaInput(dimFreezeInput),
Tips: []string{
"Example: lark-cli sheets +dim-freeze --url <URL> --sheet-name Sheet1 --dimension row --count 2 (freezes the first 2 rows; --count 0 unfreezes)",
},
Validate: validateViaInput(dimFreezeInput),
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
token, _ := resolveSpreadsheetToken(runtime)
sheetID, sheetName, _ := resolveSheetSelector(runtime)
@@ -557,6 +717,23 @@ func columnIndexToLetter(idx int) string {
return string(out)
}
// a1PositionBefore returns the A1 position one unit before s ("6" → "5",
// "C" → "B"), preserving row/column form. ok is false when s is the first
// row/column (row 1 / column A) — no earlier position — or is not a valid A1
// position. Callers validate via parseA1Position first, so in practice ok is
// false only at the first row/column.
func a1PositionBefore(s string) (pos string, ok bool) {
dimension, idx, err := parseA1Position(s)
if err != nil || idx == 0 {
return "", false
}
if dimension == "row" {
// idx is 0-based; the 1-based number one row earlier is idx itself.
return strconv.Itoa(idx), true
}
return columnIndexToLetter(idx - 1), true
}
// ─── +dim-move (native v3 move_dimension, cli_status: cli-only) ──────
//
// Moves a contiguous block of rows or columns to a new index in the same

View File

@@ -48,6 +48,8 @@ func TestSheetStructureShortcuts_DryRun(t *testing.T) {
},
},
{
// --inherit-style before copies the preceding row: anchor row 5 and
// insert after it (side=after), so the blank still lands before row 6.
name: "+dim-insert row position=6 count=3 inherit-before",
sc: DimInsert,
args: []string{"--url", testURL, "--sheet-id", testSheetID, "--position", "6", "--count", "3", "--inherit-style", "before"},
@@ -56,9 +58,9 @@ func TestSheetStructureShortcuts_DryRun(t *testing.T) {
"excel_id": testToken,
"operation": "insert",
"sheet_id": testSheetID,
"position": "6",
"position": "5",
"count": float64(3),
"side": "before",
"side": "after",
},
},
{
@@ -169,6 +171,93 @@ func TestSheetStructureShortcuts_DryRun(t *testing.T) {
}
}
func TestDimInsertInheritStyleSideMapping(t *testing.T) {
t.Parallel()
cases := []struct {
name string
position string
inherit string
wantPosition string
wantSide string
wantSideSet bool
}{
{
name: "after copies the following style with a plain before-insert, position unchanged",
position: "D",
inherit: "after",
wantPosition: "D",
wantSide: "before",
wantSideSet: true,
},
{
name: "before anchors one column earlier (side=after) to copy the preceding style",
position: "D",
inherit: "before",
wantPosition: "C",
wantSide: "after",
wantSideSet: true,
},
{
name: "before on a row anchors one row earlier",
position: "6",
inherit: "before",
wantPosition: "5",
wantSide: "after",
wantSideSet: true,
},
{
name: "before at the first column falls back to a plain before-insert",
position: "A",
inherit: "before",
wantPosition: "A",
wantSideSet: false,
},
{
name: "after at the first column still works (before-insert anchors the following)",
position: "A",
inherit: "after",
wantPosition: "A",
wantSide: "before",
wantSideSet: true,
},
{
name: "default (flag omitted) omits side, backend inherits the following row/column",
position: "D",
wantPosition: "D",
wantSideSet: false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
args := []string{"--url", testURL, "--sheet-id", testSheetID, "--position", tc.position, "--count", "1"}
if tc.inherit != "" {
args = append(args, "--inherit-style", tc.inherit)
}
body := parseDryRunBody(t, DimInsert, args)
got := decodeToolInput(t, body, "modify_sheet_structure")
assertInputEquals(t, got, map[string]interface{}{
"excel_id": testToken,
"operation": "insert",
"sheet_id": testSheetID,
"position": tc.wantPosition,
"count": float64(1),
})
gv, ok := got["side"]
if ok != tc.wantSideSet {
t.Fatalf("side presence = %v, want %v (input=%#v)", ok, tc.wantSideSet, got)
}
if ok && gv != tc.wantSide {
t.Fatalf("side = %v, want %q", gv, tc.wantSide)
}
})
}
}
// TestDimRange_Validation covers the A1 range parser's edge cases routed
// through +dim-hide (any --range shortcut works; we just need to exercise
// the validator).

View File

@@ -0,0 +1,272 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/larksuite/cli/shortcuts/common"
)
// ─── +styles-put ──────────────────────────────────────────────────────
//
// Declarative visual spec for EXISTING spreadsheets. Eval attribution
// showed ~73% of real +batch-update calls were pure formatting finishers
// (style stamps + merges + resizes + freeze) hand-assembled as imperative
// operations arrays — the top error surface. +styles-put replaces that
// with the {styles:[...]} protocol already shared by +workbook-create /
// +table-put --styles (identical vocabulary, parsed by the same
// parseWorkbookCreateStyleItem), applied to a live workbook and expanded
// client-side into ONE atomic batch_update.
//
// Per-sheet expansion order (server behavior verified live: style stamps
// over merged regions are allowed — the top-left-only restriction applies
// to value writes, not styles):
//
// cell_merges → cell_styles → row_sizes → col_sizes → freeze
var StylesPut = common.Shortcut{
Service: "sheets",
Command: "+styles-put",
Description: "Apply one declarative visual spec (styles/merges/row-col sizes/freeze) to existing sheets in one atomic batch.",
Risk: "write",
Scopes: []string{"sheets:spreadsheet:write_only"},
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+styles-put"),
Tips: []string{
`Example: lark-cli sheets +styles-put --url <URL> --styles '{"styles":[{"name":"Sheet1","cell_styles":[{"range":"A1:F1","font_weight":"bold"}],"freeze":{"rows":1}}]}'`,
"Same --styles vocabulary as +workbook-create / +table-put; one item per target sheet, name = the real sheet name.",
"Style stamps are safe to re-run; the whole spec goes out as one atomic batch.",
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
token, err := resolveSpreadsheetToken(runtime)
if err != nil {
return err
}
_, err = stylesPutOperations(runtime, token)
return err
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
token, _ := resolveSpreadsheetToken(runtime)
ops, _ := stylesPutOperations(runtime, token)
return invokeToolDryRun(token, ToolKindWrite, "batch_update", map[string]interface{}{
"excel_id": token,
"operations": ops,
})
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
token, err := resolveSpreadsheetTokenExec(runtime)
if err != nil {
return err
}
ops, err := stylesPutOperations(runtime, token)
if err != nil {
return err
}
out, err := callTool(ctx, runtime, token, ToolKindWrite, "batch_update", map[string]interface{}{
"excel_id": token,
"operations": ops,
})
if err != nil {
return err
}
runtime.Out(out, nil)
return nil
},
}
// stylesPutOperations parses --styles ({styles:[...]}, one item per target
// sheet) and expands it into the MCP batch_update operations array. Reuses
// the shared workbook-create style item parser, so field validation, alias
// normalization (border "all" shorthand, style vocabulary) and the
// aggregate-all-issues error shape are identical across the three --styles
// carriers.
func stylesPutOperations(runtime flagView, token string) ([]interface{}, error) {
if strings.TrimSpace(runtime.Str("styles")) == "" {
return nil, sheetsValidationForFlag("styles", "--styles is required")
}
v, err := parseJSONFlag(runtime, "styles")
if err != nil {
return nil, err
}
items, err := parseWorkbookCreateStylesItems(v)
if err != nil {
return nil, err
}
if len(items) == 0 {
return nil, sheetsValidationForFlag("styles", "--styles.styles must be a non-empty array (one item per target sheet)")
}
var probs []error
type sheetSpec struct {
name string
payload *workbookCreateStylePayload
}
specs := make([]sheetSpec, 0, len(items))
seenName := map[string]bool{}
for i, item := range items {
path := fmt.Sprintf("--styles.styles[%d]", i)
name, _ := item["name"].(string)
name = strings.TrimSpace(name)
if name == "" {
probs = append(probs, common.ValidationErrorf("%s.name is required (the real sheet name; check +workbook-info)", path))
continue
}
if seenName[name] {
probs = append(probs, common.ValidationErrorf("%s.name %q appears twice; merge the two items", path, name))
continue
}
seenName[name] = true
payload, itemProbs := parseWorkbookCreateStyleItem(item, path)
if len(itemProbs) > 0 {
probs = append(probs, itemProbs...)
continue
}
specs = append(specs, sheetSpec{name: name, payload: payload})
}
if err := joinStyleValidationErrors(probs); err != nil {
return nil, err
}
ops := make([]interface{}, 0, len(specs)*4)
var totalCells int64
appendVisual := func(name string, op workbookCreateStyleOp) {
input, toolName := workbookCreateVisualOpInput(token, "", name, op)
if toolName == "" {
return
}
ops = append(ops, map[string]interface{}{"tool_name": toolName, "input": input})
}
for _, spec := range specs {
// merges first so subsequent style stamps see the final grid.
for _, m := range spec.payload.CellMerges {
appendVisual(spec.name, workbookCreateStyleOp{Kind: "cell_merge", Range: m.Range, MergeType: m.MergeType})
}
for _, cs := range coalesceStyleStamps(spec.payload.CellStyles) {
rows, cols, err := rangeDimensions(cs.Range)
if err != nil {
return nil, sheetsValidationForFlag("styles", "cell_styles range %q: %v", cs.Range, err)
}
if err := checkStampMatrixBudget("styles", cs.Range, rows, cols); err != nil {
return nil, err
}
totalCells += int64(rows) * int64(cols)
if err := checkBatchStampBudget(totalCells); err != nil {
return nil, err
}
ops = append(ops, map[string]interface{}{
"tool_name": "set_cell_range",
"input": map[string]interface{}{
"excel_id": token,
"sheet_name": spec.name,
"range": stripSheetPrefix(cs.Range),
"cells": fillCellsMatrix(rows, cols, cs.Style),
},
})
}
for _, rs := range spec.payload.RowSizes {
appendVisual(spec.name, workbookCreateStyleOp{Kind: "row_size", Range: rs.Range, ResizeType: rs.ResizeType, Size: rs.Size})
}
for _, csz := range spec.payload.ColSizes {
appendVisual(spec.name, workbookCreateStyleOp{Kind: "col_size", Range: csz.Range, ResizeType: csz.ResizeType, Size: csz.Size})
}
if f := spec.payload.Freeze; f != nil {
if f.Rows > 0 {
appendVisual(spec.name, workbookCreateStyleOp{Kind: "freeze_rows", Size: f.Rows})
}
if f.Cols > 0 {
appendVisual(spec.name, workbookCreateStyleOp{Kind: "freeze_cols", Size: f.Cols})
}
}
}
if len(ops) > maxBatchOperations {
return nil, sheetsValidationForFlag("styles",
"--styles expands to %d operations even after merging adjacent same-style ranges, over the %d cap; split the spec into several +styles-put calls — and for alternating-row banding or value-dependent coloring use +cond-format-create instead of per-row stamps",
len(ops), maxBatchOperations)
}
return ops, nil
}
// coalesceStyleStamps merges cell_styles entries that carry the IDENTICAL
// style into larger rectangles: same column span + contiguous/overlapping
// rows fuse vertically, same row span + contiguous columns fuse
// horizontally, iterated to a fixpoint. Models routinely emit one entry per
// row (07-21 rerun: specs expanding to 184/203/861 operations against the
// 100-op cap); a declarative spec describes intent, so execution shape is
// the CLI's to optimize. Entries with unparsable ranges pass through
// untouched (the per-op validation reports them with proper context).
func coalesceStyleStamps(ops []workbookCreateCellStyleOp) []workbookCreateCellStyleOp {
if len(ops) < 2 {
return ops
}
type rect struct{ c1, r1, c2, r2 int }
type group struct {
style map[string]interface{}
rects []rect
}
var order []string
groups := map[string]*group{}
out := make([]workbookCreateCellStyleOp, 0, len(ops))
for _, op := range ops {
c1, r1, c2, r2, err := workbookCreateStyleRangeBounds(op.Range)
key, jerr := json.Marshal(op.Style) // map keys marshal sorted → canonical
if err != nil || jerr != nil {
out = append(out, op)
continue
}
g, ok := groups[string(key)]
if !ok {
g = &group{style: op.Style}
groups[string(key)] = g
order = append(order, string(key))
}
g.rects = append(g.rects, rect{c1, r1, c2, r2})
}
for _, key := range order {
g := groups[key]
rects := g.rects
for changed := true; changed; {
changed = false
for i := 0; i < len(rects) && !changed; i++ {
for j := i + 1; j < len(rects); j++ {
a, b := rects[i], rects[j]
var merged rect
switch {
case a.c1 == b.c1 && a.c2 == b.c2 && b.r1 <= a.r2+1 && a.r1 <= b.r2+1:
merged = rect{a.c1, min(a.r1, b.r1), a.c2, max(a.r2, b.r2)}
case a.r1 == b.r1 && a.r2 == b.r2 && b.c1 <= a.c2+1 && a.c1 <= b.c2+1:
merged = rect{min(a.c1, b.c1), a.r1, max(a.c2, b.c2), a.r2}
default:
continue
}
rects[i] = merged
rects = append(rects[:j], rects[j+1:]...)
changed = true
break
}
}
}
for _, rc := range rects {
out = append(out, workbookCreateCellStyleOp{
Range: fmt.Sprintf("%s%d:%s%d",
columnIndexToLetter(rc.c1), rc.r1+1,
columnIndexToLetter(rc.c2), rc.r2+1),
Style: g.style,
})
}
}
return out
}
// stripSheetPrefix drops an optional "Sheet!"-style prefix from an A1 range:
// the target sheet is already carried by the spec item's name, and the
// batch sub-op input names the sheet separately.
func stripSheetPrefix(rangeStr string) string {
if idx := strings.Index(rangeStr, "!"); idx >= 0 {
return strings.TrimSpace(rangeStr[idx+1:])
}
return strings.TrimSpace(rangeStr)
}

View File

@@ -0,0 +1,347 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"strings"
"testing"
)
func stylesPutView(spec map[string]interface{}) mapFlagView {
return newMapFlagViewForCommand("+styles-put", map[string]interface{}{"styles": spec})
}
// TestStylesPutOperations_ExpansionOrder pins the per-sheet expansion:
// cell_merges → cell_styles → row_sizes → col_sizes → freeze, all inside one
// batch_update operations array (server-side order dependence verified live).
func TestStylesPutOperations_ExpansionOrder(t *testing.T) {
t.Parallel()
ops, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{
"name": "Sheet1",
"cell_merges": []interface{}{map[string]interface{}{"range": "A5:A8"}},
"cell_styles": []interface{}{map[string]interface{}{"range": "A1:B1", "font_weight": "bold"}},
"row_sizes": []interface{}{map[string]interface{}{"range": "1:1", "type": "pixel", "size": float64(36)}},
"col_sizes": []interface{}{map[string]interface{}{"range": "A:B", "type": "pixel", "size": float64(120)}},
"freeze": map[string]interface{}{"rows": float64(1), "cols": float64(2)},
}},
}), testToken)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
wantTools := []string{"merge_cells", "set_cell_range", "resize_range", "resize_range", "modify_sheet_structure", "modify_sheet_structure"}
if len(ops) != len(wantTools) {
t.Fatalf("got %d ops, want %d", len(ops), len(wantTools))
}
for i, want := range wantTools {
op := ops[i].(map[string]interface{})
if op["tool_name"] != want {
t.Fatalf("ops[%d].tool_name = %v, want %s", i, op["tool_name"], want)
}
input := op["input"].(map[string]interface{})
if input["sheet_name"] != "Sheet1" {
t.Fatalf("ops[%d] missing sheet_name: %v", i, input)
}
if input["excel_id"] != testToken {
t.Fatalf("ops[%d] missing excel_id", i)
}
}
// The style stamp carries a cells matrix matching the range (1×2).
stamp := ops[1].(map[string]interface{})["input"].(map[string]interface{})
cells := stamp["cells"].([][]interface{})
if len(cells) != 1 || len(cells[0]) != 2 {
t.Fatalf("style stamp matrix = %dx%d, want 1x2", len(cells), len(cells[0]))
}
// Freeze ops carry the freeze counts.
fr := ops[4].(map[string]interface{})["input"].(map[string]interface{})
if fr["operation"] != "freeze" || fr["freeze_rows"] != 1 {
t.Fatalf("freeze rows op = %v", fr)
}
fc := ops[5].(map[string]interface{})["input"].(map[string]interface{})
if fc["freeze_columns"] != 2 {
t.Fatalf("freeze cols op = %v", fc)
}
}
// TestStylesPutOperations_Validation pins the aggregate error shape and the
// section/name requirements.
func TestStylesPutOperations_Validation(t *testing.T) {
t.Parallel()
t.Run("missing name and empty item aggregate", func(t *testing.T) {
t.Parallel()
_, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{
map[string]interface{}{"cell_styles": []interface{}{map[string]interface{}{"range": "A1", "font_weight": "bold"}}},
map[string]interface{}{"name": "S2"},
},
}), testToken)
ve := requireValidation(t, err, "name is required")
if !strings.Contains(ve.Message, "at least one of cell_styles/row_sizes/col_sizes/cell_merges/freeze") {
t.Fatalf("message %q missing empty-item issue", ve.Message)
}
})
t.Run("duplicate sheet name rejected", func(t *testing.T) {
t.Parallel()
item := map[string]interface{}{"name": "S1", "freeze": map[string]interface{}{"rows": float64(1)}}
item2 := map[string]interface{}{"name": "S1", "freeze": map[string]interface{}{"rows": float64(2)}}
_, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{item, item2},
}), testToken)
requireValidation(t, err, "appears twice")
})
t.Run("freeze-only item is valid", func(t *testing.T) {
t.Parallel()
ops, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{"name": "S1", "freeze": map[string]interface{}{"rows": float64(1)}}},
}), testToken)
if err != nil || len(ops) != 1 {
t.Fatalf("ops=%d err=%v", len(ops), err)
}
})
t.Run("all-zero freeze rejected", func(t *testing.T) {
t.Parallel()
_, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{"name": "S1", "freeze": map[string]interface{}{"rows": float64(0)}}},
}), testToken)
requireValidation(t, err, "at least one dimension")
})
}
// TestStylesPayloadVocabularyForgiveness pins the 07-20 rerun fixes: the
// payload path (--styles cell_styles objects) accepts the same habitual
// vocabulary the flag path already normalized — border family folding, wrap
// aliases, and enum VALUE canonicalization (CSS center → Lark middle etc.).
func TestStylesPayloadVocabularyForgiveness(t *testing.T) {
t.Parallel()
stamp := func(styleFields map[string]interface{}) ([]interface{}, error) {
item := map[string]interface{}{"range": "A1:B1"}
for k, v := range styleFields {
item[k] = v
}
return stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{
"name": "S1",
"cell_styles": []interface{}{item},
}},
}), testToken)
}
cellProto := func(t *testing.T, ops []interface{}) map[string]interface{} {
t.Helper()
input := ops[0].(map[string]interface{})["input"].(map[string]interface{})
cells := input["cells"].([][]interface{})
return cells[0][0].(map[string]interface{})
}
t.Run("vertical_alignment center canonicalizes to middle", func(t *testing.T) {
t.Parallel()
ops, err := stamp(map[string]interface{}{"vertical_alignment": "center", "font_weight": "BOLD"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
cs := cellProto(t, ops)["cell_styles"].(map[string]interface{})
if cs["vertical_alignment"] != "middle" || cs["font_weight"] != "bold" {
t.Fatalf("cell_styles = %v, want middle/bold", cs)
}
})
t.Run("off-enum value rejected client-side with did-you-mean", func(t *testing.T) {
t.Parallel()
_, err := stamp(map[string]interface{}{"vertical_alignment": "botom"})
requireValidation(t, err, `did you mean "bottom"`)
})
t.Run("boolean wrap_text folds to word_wrap auto-wrap", func(t *testing.T) {
t.Parallel()
ops, err := stamp(map[string]interface{}{"wrap_text": true})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
cs := cellProto(t, ops)["cell_styles"].(map[string]interface{})
if cs["word_wrap"] != "auto-wrap" {
t.Fatalf("word_wrap = %v, want auto-wrap", cs["word_wrap"])
}
})
t.Run("borders object folds into border_styles", func(t *testing.T) {
t.Parallel()
ops, err := stamp(map[string]interface{}{
"borders": map[string]interface{}{"style": "solid", "color": "#000000"},
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
bs := cellProto(t, ops)["border_styles"].(map[string]interface{})
top, _ := bs["top"].(map[string]interface{})
if top == nil || top["style"] != "solid" {
t.Fatalf("border_styles = %v, want all-sides solid", bs)
}
})
t.Run("flattened border_bottom and border_top_color fold per side", func(t *testing.T) {
t.Parallel()
ops, err := stamp(map[string]interface{}{
"border_bottom": map[string]interface{}{"style": "solid"},
"border_top_color": "#FF0000",
})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
bs := cellProto(t, ops)["border_styles"].(map[string]interface{})
bottom, _ := bs["bottom"].(map[string]interface{})
topSide, _ := bs["top"].(map[string]interface{})
if bottom["style"] != "solid" || topSide["color"] != "#FF0000" {
t.Fatalf("border_styles = %v", bs)
}
})
t.Run("border_style thin means thin solid line", func(t *testing.T) {
t.Parallel()
ops, err := stamp(map[string]interface{}{"border_style": "thin"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
bs := cellProto(t, ops)["border_styles"].(map[string]interface{})
top, _ := bs["top"].(map[string]interface{})
if top["weight"] != "thin" || top["style"] != "solid" {
t.Fatalf("border_styles.top = %v, want thin solid", top)
}
})
t.Run("fore_color prescribes instead of guessing", func(t *testing.T) {
t.Parallel()
_, err := stamp(map[string]interface{}{"fore_color": "#FF0000"})
requireValidation(t, err, "fore_color is ambiguous")
})
t.Run("bare string cell_merges accepted", func(t *testing.T) {
t.Parallel()
ops, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{
"name": "S1",
"cell_merges": []interface{}{"A5:B6"},
}},
}), testToken)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
input := ops[0].(map[string]interface{})["input"].(map[string]interface{})
if input["range"] != "A5:B6" || input["merge_type"] != "all" {
t.Fatalf("merge op = %v", input)
}
})
}
// TestStylesResizeSizeAliases pins the one-way Excel-vocabulary aliases on
// the shared styles resize parser: height in row_sizes / width in col_sizes
// resolve to size silently; the wrong dimension's word is a targeted error.
func TestStylesResizeSizeAliases(t *testing.T) {
t.Parallel()
t.Run("height aliases to size in row_sizes", func(t *testing.T) {
t.Parallel()
ops, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{
"name": "S1",
"row_sizes": []interface{}{map[string]interface{}{"range": "1:1", "type": "pixel", "height": float64(36)}},
}},
}), testToken)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
input := ops[0].(map[string]interface{})["input"].(map[string]interface{})
block := input["resize_height"].(map[string]interface{})
if block["value"] != 36 {
t.Fatalf("resize_height = %v, want value 36", block)
}
})
t.Run("width aliases to size in col_sizes", func(t *testing.T) {
t.Parallel()
_, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{
"name": "S1",
"col_sizes": []interface{}{map[string]interface{}{"range": "A:C", "type": "pixel", "width": float64(120)}},
}},
}), testToken)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
})
t.Run("wrong-dimension word is a targeted error", func(t *testing.T) {
t.Parallel()
_, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{
"name": "S1",
"row_sizes": []interface{}{map[string]interface{}{"range": "1:1", "type": "pixel", "width": float64(36)}},
}},
}), testToken)
requireValidation(t, err, "does not apply to this array")
})
t.Run("size plus alias together rejected", func(t *testing.T) {
t.Parallel()
_, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{
"name": "S1",
"row_sizes": []interface{}{map[string]interface{}{"range": "1:1", "type": "pixel", "size": float64(36), "height": float64(40)}},
}},
}), testToken)
requireValidation(t, err, "either size or height")
})
}
// TestDimDeleteRangesOps pins the descending-order expansion and the
// same-dimension / non-overlap guards.
func TestDimDeleteRangesOps(t *testing.T) {
t.Parallel()
view := func(ranges ...interface{}) mapFlagView {
return newMapFlagViewForCommand("+dim-delete", map[string]interface{}{"ranges": ranges})
}
t.Run("rows execute descending", func(t *testing.T) {
t.Parallel()
ops, err := dimDeleteRangesOps(view("5:5", "11:13", "8:8"), testToken, "", "S1")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
var got []string
for _, op := range ops {
got = append(got, op.(map[string]interface{})["input"].(map[string]interface{})["range"].(string))
}
want := []string{"11:13", "8:8", "5:5"}
for i := range want {
if got[i] != want[i] {
t.Fatalf("order = %v, want %v", got, want)
}
}
})
t.Run("mixed dimensions rejected", func(t *testing.T) {
t.Parallel()
_, err := dimDeleteRangesOps(view("5:5", "C:C"), testToken, "", "S1")
requireValidation(t, err, "rows OR columns")
})
t.Run("overlap rejected", func(t *testing.T) {
t.Parallel()
_, err := dimDeleteRangesOps(view("5:8", "7:9"), testToken, "", "S1")
requireValidation(t, err, "overlap")
})
t.Run("ranges cannot nest inside batch", func(t *testing.T) {
t.Parallel()
_, err := translateBatchOp(subOp("+dim-delete", map[string]interface{}{
"sheet_name": "S1",
"ranges": []interface{}{"5:5", "8:8"},
}), testToken, 0)
requireValidation(t, err, "not supported inside +batch-update")
})
}

View File

@@ -88,6 +88,7 @@ var TablePut = common.Shortcut{
return tablePutWrite(ctx, runtime, token, payload, styles)
},
Tips: []string{
`Example: lark-cli sheets +table-put --url <URL> --sheets '{"sheets":[{"name":"S1","columns":["City","Rev"],"dtypes":{"Rev":"float64"},"data":[["SH",1234.5]]}]}'`,
"Writes into an existing spreadsheet — pass --url or --spreadsheet-token. To create a new workbook first, use +workbook-create, then point --spreadsheet-token here.",
"Payload sheets are matched to existing sub-sheets by name (created when absent). Date columns take ISO yyyy-mm-dd strings — converted to real dates (serial + date format).",
"--styles applies number formats, colors, merges, and row/col sizes in the same call (same shape as +workbook-create's --styles): one styles item per written sheet, name-matched. Skips the separate +cells-set-style round-trip.",
@@ -241,6 +242,11 @@ func decoderExpectEOF(dec *json.Decoder) error {
return nil
}
// tablePutSheetsSkeleton is the one-line --sheets shape inlined on a decode
// error, so the retry needs no --print-schema round trip. Field vocabulary
// mirrors tableSheetIn.
const tablePutSheetsSkeleton = `{"sheets":[{"name":"Sheet1","columns":["City","Revenue"],"dtypes":{"Revenue":"float64"},"data":[["SH",123.4],["BJ",56.7]],"start_cell":"A1"}]}`
// parseTablePutPayload reads --sheets (JSON, supports @file / stdin) into a
// validated payload. UseNumber keeps numeric cells as json.Number so large
// integers (order IDs, etc.) survive without precision loss or scientific
@@ -259,7 +265,29 @@ func parseTablePutPayload(runtime flagView) (*tablePayload, error) {
Sheets []tableSheetIn `json:"sheets"`
}
if err := dec.Decode(&wire); err != nil {
return nil, common.ValidationErrorf("--sheets: invalid JSON: %v", err).WithCause(err)
// Eval traces show two distinct decode failures that each burned
// retries: a field with the wrong JSON kind (columns as objects,
// dtypes as an array) — fixed by seeing the expected shape once —
// and shell-mangled JSON, fixed by moving the payload to stdin/@file.
verr := common.ValidationErrorf("--sheets: invalid JSON: %v", err).WithCause(err)
var ute *json.UnmarshalTypeError
if errors.As(err, &ute) {
// A mismatch with no field path is the missing envelope: the
// payload IS the sub-sheet list, written without the wrapper.
// Say that in the message — the Go unmarshal text ("cannot
// unmarshal array into Go value of type struct { Sheets …}")
// names the internal type, not the fix.
if ute.Field == "" {
verr = common.ValidationErrorf(
`--sheets: top level must be the object {"sheets":[…]}, got a bare JSON %s; wrap the sub-sheet list in a "sheets" key`,
ute.Value).WithCause(err)
}
return nil, verr.WithHint(
"expected shape: %s (columns is a flat string array; dtypes/formats are column-name-keyed maps; data is row-major)",
tablePutSheetsSkeleton)
}
return nil, verr.WithHint(
"if the payload contains formulas / quotes / commas, pass it via stdin (`--sheets - < file`) or a relative @file (`--sheets @./payload.json`)")
}
// Reject trailing non-whitespace after the first JSON value: json.Decoder
// accepts it silently (unlike json.Unmarshal), so e.g. `--sheets '{...} oops'`
@@ -1208,8 +1236,7 @@ var TableGet = common.Shortcut{
}
sheets = append(sheets, spec)
}
runtime.Out(map[string]interface{}{"sheets": sheets}, nil)
return nil
return emitReadResult(runtime, map[string]interface{}{"sheets": sheets})
},
Tips: []string{
"Output is the same shape +table-put consumes — pipe it back in, or load sheets[].rows into a DataFrame keyed by columns[].name.",
@@ -1354,11 +1381,18 @@ func readSheetAsSpec(ctx context.Context, runtime *common.RuntimeContext, token
"value_render_option": "raw_value",
"cell_limit": unboundedReadLimit,
}
// --max-chars binds the char budget (default 500000); --output-path lifts it
// to unbounded. Without this the tool applied its own ~50000 default and
// silently dropped rows past it with no signal in the +table-get output.
if n, ok := maxCharsInput(runtime); ok {
input["max_chars"] = n
}
sheetSelectorForToolInput(input, t.id, t.name)
out, err := callTool(ctx, runtime, token, ToolKindRead, "get_cell_ranges", input)
if err != nil {
return nil, err
}
truncated := cellRangesTruncated(out)
grid := extractCellGrid(out)
if len(grid) == 0 {
return emptySpec(), nil
@@ -1433,9 +1467,38 @@ func readSheetAsSpec(ctx context.Context, runtime *common.RuntimeContext, token
if len(formats) > 0 {
spec["formats"] = formats
}
// The tool clipped the read at max_chars: rows past the cap are missing from
// data. Surface it so the caller doesn't mistake a partial read for the whole
// sheet — re-run with --output-path (unlimited) or a higher --max-chars.
if truncated {
spec["truncated"] = true
spec["truncation_warning"] = "Result truncated by max_chars; rows past the cap were not returned. Best: re-run with --output-path to dump the whole sheet in one lossless pass (no cap). Alternatively raise --max-chars, or continue-read the remaining rows by passing --range for them — but that needs --no-header and you must reattach the header row and reconcile per-chunk dtypes yourself (this chunk's types were inferred from the rows returned here)."
}
return spec, nil
}
// cellRangesTruncated reports whether a get_cell_ranges response was clipped by
// max_chars — either the top-level has_more flag or the first range's truncated
// flag. Used by +table-get, whose spec output otherwise drops both signals.
func cellRangesTruncated(out interface{}) bool {
m, ok := out.(map[string]interface{})
if !ok {
return false
}
if hm, ok := m["has_more"].(bool); ok && hm {
return true
}
ranges, _ := m["ranges"].([]interface{})
if len(ranges) > 0 {
if r0, ok := ranges[0].(map[string]interface{}); ok {
if t, ok := r0["truncated"].(bool); ok {
return t
}
}
}
return false
}
// sheetCurrentRegion returns the A1 range covering the sheet's existing data,
// or "" for an empty sheet.
//

View File

@@ -13,6 +13,7 @@ import (
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/internal/suggest"
"github.com/larksuite/cli/internal/util"
"github.com/larksuite/cli/shortcuts/common"
"github.com/larksuite/cli/shortcuts/drive"
@@ -405,7 +406,11 @@ var SheetCopy = common.Shortcut{
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+sheet-copy"),
Validate: validateViaInput(sheetCopyInput),
Tips: []string{
"Example: lark-cli sheets +sheet-copy --url <URL> --sheet-name 数据源 --title 数据源-副本",
"--sheet-name / --sheet-id selects the SOURCE sheet; the copy's new name goes in --title.",
},
Validate: validateViaInput(sheetCopyInput),
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
token, _ := resolveSpreadsheetToken(runtime)
sheetID, sheetName, _ := resolveSheetSelector(runtime)
@@ -914,6 +919,14 @@ type workbookCreateStylePayload struct {
RowSizes []workbookCreateResizeOp
ColSizes []workbookCreateResizeOp
CellMerges []workbookCreateMergeOp
Freeze *workbookCreateFreezeOp
}
// workbookCreateFreezeOp freezes the first Rows rows / Cols columns.
// Zero means "leave that dimension alone".
type workbookCreateFreezeOp struct {
Rows int
Cols int
}
type workbookCreateCellStyleOp struct {
@@ -965,7 +978,11 @@ func parseWorkbookCreateStyles(runtime flagView) (*workbookCreateStylePayload, e
if len(items) != 1 {
return nil, common.ValidationErrorf("--styles.styles must contain exactly one item when using --values")
}
return parseWorkbookCreateStyleItem(items[0], "--styles.styles[0]")
payload, probs := parseWorkbookCreateStyleItem(items[0], "--styles.styles[0]")
if err := joinStyleValidationErrors(probs); err != nil {
return nil, err
}
return payload, nil
}
// parseWorkbookCreateSheetStyles parses --styles for the typed --sheets path.
@@ -988,21 +1005,28 @@ func parseWorkbookCreateSheetStyles(runtime flagView, payload *tablePayload) (*w
}
out := &workbookCreateSheetStyles{ByName: map[string]*workbookCreateStylePayload{}}
out.ByIndex = make([]*workbookCreateStylePayload, len(payload.Sheets))
var probs []error
for i, item := range items {
name, _ := item["name"].(string)
if strings.TrimSpace(name) == "" {
return nil, common.ValidationErrorf("--styles.styles[%d].name is required", i)
probs = append(probs, common.ValidationErrorf("--styles.styles[%d].name is required", i))
continue
}
if name != payload.Sheets[i].Name {
return nil, common.ValidationErrorf("--styles.styles[%d].name %q must match --sheets.sheets[%d].name %q", i, name, i, payload.Sheets[i].Name)
probs = append(probs, common.ValidationErrorf("--styles.styles[%d].name %q must match --sheets.sheets[%d].name %q", i, name, i, payload.Sheets[i].Name))
continue
}
style, err := parseWorkbookCreateStyleItem(item, fmt.Sprintf("--styles.styles[%d]", i))
if err != nil {
return nil, err
style, itemProbs := parseWorkbookCreateStyleItem(item, fmt.Sprintf("--styles.styles[%d]", i))
if len(itemProbs) > 0 {
probs = append(probs, itemProbs...)
continue
}
out.ByIndex[i] = style
out.ByName[name] = style
}
if err := joinStyleValidationErrors(probs); err != nil {
return nil, err
}
return out, nil
}
@@ -1030,182 +1054,337 @@ func parseWorkbookCreateStylesItems(v interface{}) ([]map[string]interface{}, er
return items, nil
}
func parseWorkbookCreateStyleItem(item map[string]interface{}, path string) (*workbookCreateStylePayload, error) {
// parseWorkbookCreateStyleItem parses one --styles item. All four sections
// are validated even after one fails, and every issue is returned in the
// slice: eval traces show agents fixing --styles errors one round trip per
// error (border side, then row_sizes.type, then size…) because only the
// first was ever reported.
func parseWorkbookCreateStyleItem(item map[string]interface{}, path string) (*workbookCreateStylePayload, []error) {
payload := &workbookCreateStylePayload{}
var err error
var probs []error
if raw, ok := item["cell_styles"]; ok {
payload.CellStyles, err = parseWorkbookCreateCellStyleOps(raw, path+".cell_styles")
if err != nil {
return nil, err
}
var errsHere []error
payload.CellStyles, errsHere = parseWorkbookCreateCellStyleOps(raw, path+".cell_styles")
probs = append(probs, errsHere...)
}
if raw, ok := item["row_sizes"]; ok {
payload.RowSizes, err = parseWorkbookCreateResizeOps(raw, path+".row_sizes", "row")
if err != nil {
return nil, err
}
var errsHere []error
payload.RowSizes, errsHere = parseWorkbookCreateResizeOps(raw, path+".row_sizes", "row")
probs = append(probs, errsHere...)
}
if raw, ok := item["col_sizes"]; ok {
payload.ColSizes, err = parseWorkbookCreateResizeOps(raw, path+".col_sizes", "column")
if err != nil {
return nil, err
}
var errsHere []error
payload.ColSizes, errsHere = parseWorkbookCreateResizeOps(raw, path+".col_sizes", "column")
probs = append(probs, errsHere...)
}
if raw, ok := item["cell_merges"]; ok {
payload.CellMerges, err = parseWorkbookCreateMergeOps(raw, path+".cell_merges")
var errsHere []error
payload.CellMerges, errsHere = parseWorkbookCreateMergeOps(raw, path+".cell_merges")
probs = append(probs, errsHere...)
}
if raw, ok := item["freeze"]; ok {
freeze, err := parseWorkbookCreateFreezeOp(raw, path+".freeze")
if err != nil {
return nil, err
probs = append(probs, err)
} else {
payload.Freeze = freeze
}
}
if len(payload.CellStyles) == 0 && len(payload.RowSizes) == 0 && len(payload.ColSizes) == 0 && len(payload.CellMerges) == 0 {
return nil, common.ValidationErrorf("%s must include at least one of cell_styles/row_sizes/col_sizes/cell_merges", path)
if len(probs) > 0 {
return nil, probs
}
if len(payload.CellStyles) == 0 && len(payload.RowSizes) == 0 && len(payload.ColSizes) == 0 && len(payload.CellMerges) == 0 && payload.Freeze == nil {
return nil, []error{common.ValidationErrorf("%s must include at least one of cell_styles/row_sizes/col_sizes/cell_merges/freeze", path)}
}
return payload, nil
}
func parseWorkbookCreateCellStyleOps(v interface{}, path string) ([]workbookCreateCellStyleOp, error) {
// parseWorkbookCreateFreezeOp parses a {rows, cols} freeze section. At least
// one dimension must be positive — an all-zero freeze is a no-op the caller
// almost certainly didn't mean.
func parseWorkbookCreateFreezeOp(raw interface{}, path string) (*workbookCreateFreezeOp, error) {
obj, ok := raw.(map[string]interface{})
if !ok {
return nil, common.ValidationErrorf("%s must be an object like {\"rows\":1} or {\"rows\":1,\"cols\":2}", path)
}
out := &workbookCreateFreezeOp{}
for k, v := range obj {
n, isNum := v.(float64)
if !isNum || n != float64(int(n)) || n < 0 {
return nil, common.ValidationErrorf("%s.%s must be a non-negative integer", path, k)
}
switch k {
case "rows":
out.Rows = int(n)
case "cols", "columns":
out.Cols = int(n)
default:
return nil, common.ValidationErrorf("%s.%s is not a supported field (want rows/cols)", path, k)
}
}
if out.Rows == 0 && out.Cols == 0 {
return nil, common.ValidationErrorf("%s must freeze at least one dimension (rows or cols > 0)", path)
}
return out, nil
}
// joinStyleValidationErrors folds the issues collected across one --styles
// parse into a single typed error that lists them all, so the caller can fix
// the whole payload in one retry instead of one error per round trip.
func joinStyleValidationErrors(probs []error) error {
switch len(probs) {
case 0:
return nil
case 1:
return probs[0]
}
const maxShown = 8
msgs := make([]string, 0, len(probs))
for _, e := range probs {
if p, ok := errs.ProblemOf(e); ok {
msgs = append(msgs, p.Message)
continue
}
msgs = append(msgs, e.Error())
}
suffix := ""
if len(msgs) > maxShown {
suffix = fmt.Sprintf(" (+%d more)", len(msgs)-maxShown)
msgs = msgs[:maxShown]
}
return common.ValidationErrorf("--styles has %d issues: %s%s", len(probs), strings.Join(msgs, " | "), suffix)
}
func parseWorkbookCreateCellStyleOps(v interface{}, path string) ([]workbookCreateCellStyleOp, []error) {
arr, ok := v.([]interface{})
if !ok {
return nil, common.ValidationErrorf("%s must be an array", path)
return nil, []error{common.ValidationErrorf("%s must be an array", path)}
}
ops := make([]workbookCreateCellStyleOp, 0, len(arr))
var probs []error
for i, raw := range arr {
op, ok := raw.(map[string]interface{})
if !ok {
return nil, common.ValidationErrorf("%s[%d] must be an object", path, i)
}
rangeStr, err := requireWorkbookCreateRange(op, fmt.Sprintf("%s[%d]", path, i))
op, err := parseWorkbookCreateCellStyleOp(raw, fmt.Sprintf("%s[%d]", path, i))
if err != nil {
return nil, err
probs = append(probs, err)
continue
}
if _, _, _, _, err := workbookCreateStyleRangeBounds(rangeStr); err != nil {
return nil, common.ValidationErrorf("%s[%d].range %q: %v", path, i, rangeStr, err)
}
styleObj := make(map[string]interface{}, len(op)-1)
for k, v := range op {
if k == "range" {
continue
}
styleObj[k] = v
}
style, err := normalizeWorkbookCreateStyleObject(styleObj, fmt.Sprintf("%s[%d]", path, i))
if err != nil {
return nil, err
}
if len(style) == 0 {
return nil, common.ValidationErrorf("%s[%d] must include at least one style field", path, i)
}
ops = append(ops, workbookCreateCellStyleOp{Range: rangeStr, Style: style})
ops = append(ops, op)
}
return ops, nil
return ops, probs
}
func parseWorkbookCreateMergeOps(v interface{}, path string) ([]workbookCreateMergeOp, error) {
func parseWorkbookCreateCellStyleOp(raw interface{}, path string) (workbookCreateCellStyleOp, error) {
op, ok := raw.(map[string]interface{})
if !ok {
return workbookCreateCellStyleOp{}, common.ValidationErrorf("%s must be an object", path)
}
rangeStr, err := requireWorkbookCreateRange(op, path)
if err != nil {
return workbookCreateCellStyleOp{}, err
}
if _, _, _, _, err := workbookCreateStyleRangeBounds(rangeStr); err != nil {
return workbookCreateCellStyleOp{}, common.ValidationErrorf("%s.range %q: %v", path, rangeStr, err)
}
styleObj := make(map[string]interface{}, len(op)-1)
for k, v := range op {
if k == "range" {
continue
}
styleObj[k] = v
}
style, err := normalizeWorkbookCreateStyleObject(styleObj, path)
if err != nil {
return workbookCreateCellStyleOp{}, err
}
if len(style) == 0 {
return workbookCreateCellStyleOp{}, common.ValidationErrorf("%s must include at least one style field", path)
}
return workbookCreateCellStyleOp{Range: rangeStr, Style: style}, nil
}
func parseWorkbookCreateMergeOps(v interface{}, path string) ([]workbookCreateMergeOp, []error) {
arr, ok := v.([]interface{})
if !ok {
return nil, common.ValidationErrorf("%s must be an array", path)
return nil, []error{common.ValidationErrorf("%s must be an array", path)}
}
ops := make([]workbookCreateMergeOp, 0, len(arr))
var probs []error
for i, raw := range arr {
op, ok := raw.(map[string]interface{})
if !ok {
return nil, common.ValidationErrorf("%s[%d] must be an object", path, i)
}
rangeStr, err := requireWorkbookCreateRange(op, fmt.Sprintf("%s[%d]", path, i))
op, err := parseWorkbookCreateMergeOp(raw, fmt.Sprintf("%s[%d]", path, i))
if err != nil {
return nil, err
probs = append(probs, err)
continue
}
if _, _, _, _, err := workbookCreateStyleRangeBounds(rangeStr); err != nil {
return nil, common.ValidationErrorf("%s[%d].range %q: %v", path, i, rangeStr, err)
}
mergeType := "all"
if raw, ok := op["merge_type"]; ok {
v, ok := raw.(string)
if !ok || strings.TrimSpace(v) == "" {
return nil, common.ValidationErrorf("%s[%d].merge_type must be a non-empty string", path, i)
}
mergeType = strings.TrimSpace(v)
}
switch mergeType {
case "all", "rows", "columns":
default:
return nil, common.ValidationErrorf("%s[%d].merge_type %q is invalid (want all/rows/columns)", path, i, mergeType)
}
if err := rejectUnexpectedWorkbookStyleFields(op, fmt.Sprintf("%s[%d]", path, i), "range", "merge_type"); err != nil {
return nil, err
}
ops = append(ops, workbookCreateMergeOp{Range: rangeStr, MergeType: mergeType})
ops = append(ops, op)
}
return ops, nil
return ops, probs
}
func parseWorkbookCreateResizeOps(v interface{}, path, dimension string) ([]workbookCreateResizeOp, error) {
func parseWorkbookCreateMergeOp(raw interface{}, path string) (workbookCreateMergeOp, error) {
// A bare range string means {range: s, merge_type: all} — the only
// possible reading (07-20 eval hit).
if s, ok := raw.(string); ok && strings.TrimSpace(s) != "" {
raw = map[string]interface{}{"range": strings.TrimSpace(s)}
}
op, ok := raw.(map[string]interface{})
if !ok {
return workbookCreateMergeOp{}, common.ValidationErrorf("%s must be an object", path)
}
rangeStr, err := requireWorkbookCreateRange(op, path)
if err != nil {
return workbookCreateMergeOp{}, err
}
if _, _, _, _, err := workbookCreateStyleRangeBounds(rangeStr); err != nil {
return workbookCreateMergeOp{}, common.ValidationErrorf("%s.range %q: %v", path, rangeStr, err)
}
mergeType := "all"
if raw, ok := op["merge_type"]; ok {
v, ok := raw.(string)
if !ok || strings.TrimSpace(v) == "" {
return workbookCreateMergeOp{}, common.ValidationErrorf("%s.merge_type must be a non-empty string", path)
}
mergeType = normalizeMergeType(strings.TrimSpace(v))
}
switch mergeType {
case "all", "rows", "columns":
default:
return workbookCreateMergeOp{}, common.ValidationErrorf("%s.merge_type %q is invalid (want all/rows/columns)", path, mergeType)
}
if err := rejectUnexpectedWorkbookStyleFields(op, path, "range", "merge_type"); err != nil {
return workbookCreateMergeOp{}, err
}
return workbookCreateMergeOp{Range: rangeStr, MergeType: mergeType}, nil
}
// normalizeMergeType maps the raw OpenAPI merge vocabulary (MERGE_ALL /
// MERGE_ROWS / MERGE_COLUMNS — which agents reproduce from the Lark API
// docs) onto the CLI's all/rows/columns. Unknown values pass through for
// the caller's enum check to reject.
func normalizeMergeType(v string) string {
lower := strings.ToLower(v)
lower = strings.TrimPrefix(lower, "merge_")
switch lower {
case "all", "rows", "columns":
return lower
}
return v
}
func parseWorkbookCreateResizeOps(v interface{}, path, dimension string) ([]workbookCreateResizeOp, []error) {
arr, ok := v.([]interface{})
if !ok {
return nil, common.ValidationErrorf("%s must be an array", path)
return nil, []error{common.ValidationErrorf("%s must be an array", path)}
}
ops := make([]workbookCreateResizeOp, 0, len(arr))
var probs []error
for i, raw := range arr {
op, ok := raw.(map[string]interface{})
if !ok {
return nil, common.ValidationErrorf("%s[%d] must be an object", path, i)
}
rangeStr, err := requireWorkbookCreateRange(op, fmt.Sprintf("%s[%d]", path, i))
op, err := parseWorkbookCreateResizeOp(raw, fmt.Sprintf("%s[%d]", path, i), dimension)
if err != nil {
return nil, err
probs = append(probs, err)
continue
}
parsedDim, _, _, err := parseA1Range(rangeStr)
if err != nil {
want := "row numbers like 2:10"
if dimension == "column" {
want = "column letters like A:E"
}
return nil, common.ValidationErrorf("%s[%d].range %q must use %s: %v", path, i, rangeStr, want, err)
ops = append(ops, op)
}
return ops, probs
}
// resizeOpExample renders a complete valid op for the dimension, inlined on
// every type/size error: eval traces show the field errors chaining (type
// "custom" → fixed to pixel → "pixel requires size"), each costing a round
// trip, because no error ever showed a whole valid op at once.
func resizeOpExample(dimension string) string {
if dimension == "column" {
return `{"range":"A:C","type":"pixel","size":120} (or {"range":"A:C","type":"standard"} to reset)`
}
return `{"range":"2:10","type":"pixel","size":32} (or "type":"auto" to fit content)`
}
func parseWorkbookCreateResizeOp(raw interface{}, path, dimension string) (workbookCreateResizeOp, error) {
op, ok := raw.(map[string]interface{})
if !ok {
return workbookCreateResizeOp{}, common.ValidationErrorf("%s must be an object", path)
}
rangeStr, err := requireWorkbookCreateRange(op, path)
if err != nil {
return workbookCreateResizeOp{}, err
}
parsedDim, _, _, err := parseA1Range(rangeStr)
if err != nil {
want := "row numbers like 2:10"
if dimension == "column" {
want = "column letters like A:E"
}
if parsedDim != dimension {
want := "row numbers like 2:10"
if dimension == "column" {
want = "column letters like A:E"
}
return nil, common.ValidationErrorf("%s[%d].range %q must use %s", path, i, rangeStr, want)
}
typeHint := "pixel/standard"
if dimension == "row" {
typeHint = "pixel/standard/auto"
}
resizeType, _ := op["type"].(string)
resizeType = strings.TrimSpace(resizeType)
if resizeType == "" {
return nil, common.ValidationErrorf("%s[%d].type is required (%s)", path, i, typeHint)
return workbookCreateResizeOp{}, common.ValidationErrorf("%s.range %q must use %s: %v", path, rangeStr, want, err)
}
if parsedDim != dimension {
want := "row numbers like 2:10"
if dimension == "column" {
want = "column letters like A:E"
}
return workbookCreateResizeOp{}, common.ValidationErrorf("%s.range %q must use %s", path, rangeStr, want)
}
typeHint := "pixel/standard"
if dimension == "row" {
typeHint = "pixel/standard/auto"
}
resizeType, _ := op["type"].(string)
resizeType = strings.TrimSpace(resizeType)
if resizeType != "" {
if dimension == "column" && resizeType == "auto" {
return nil, common.ValidationErrorf("%s[%d].type auto is rows-only", path, i)
return workbookCreateResizeOp{}, common.ValidationErrorf("%s.type auto is rows-only", path)
}
switch resizeType {
case "pixel", "standard", "auto":
default:
return nil, common.ValidationErrorf("%s[%d].type %q is invalid (want %s)", path, i, resizeType, typeHint)
return workbookCreateResizeOp{}, common.ValidationErrorf("%s.type %q is invalid (want %s), e.g. %s", path, resizeType, typeHint, resizeOpExample(dimension))
}
size := 0
if raw, ok := op["size"]; ok {
n, ok := util.ToFloat64(raw)
if !ok || n <= 0 {
return nil, common.ValidationErrorf("%s[%d].size must be a positive number", path, i)
}
size = int(n)
}
if resizeType == "pixel" && size <= 0 {
return nil, common.ValidationErrorf("%s[%d].type pixel requires size", path, i)
}
if resizeType != "pixel" && size > 0 {
return nil, common.ValidationErrorf("%s[%d].size is only valid with type pixel", path, i)
}
if err := rejectUnexpectedWorkbookStyleFields(op, fmt.Sprintf("%s[%d]", path, i), "range", "type", "size"); err != nil {
return nil, err
}
ops = append(ops, workbookCreateResizeOp{Range: normalizeWorkbookResizeRange(rangeStr), ResizeType: resizeType, Size: size})
}
return ops, nil
// size is the canonical dimension key (uniform across row_sizes and
// col_sizes — the array name already carries the dimension). The Excel-
// vocabulary alias (height on rows, width on columns) is accepted
// silently; the WRONG dimension's word is a targeted error, never a
// silent rewrite.
alias, wrongDim := "height", "width"
if dimension == "column" {
alias, wrongDim = "width", "height"
}
if _, has := op[wrongDim]; has {
return workbookCreateResizeOp{}, common.ValidationErrorf("%s.%s does not apply to this array (the array name carries the dimension); use size, e.g. %s", path, wrongDim, resizeOpExample(dimension))
}
sizeRaw, hasSize := op["size"]
if aliasRaw, hasAlias := op[alias]; hasAlias {
if hasSize {
return workbookCreateResizeOp{}, common.ValidationErrorf("%s: give either size or %s, not both", path, alias)
}
sizeRaw, hasSize = aliasRaw, true
}
size := 0
if hasSize {
n, ok := util.ToFloat64(sizeRaw)
if !ok || n <= 0 {
return workbookCreateResizeOp{}, common.ValidationErrorf("%s.size must be a positive number", path)
}
size = int(n)
}
// type is optional ceremony when a pixel size is given: {range, size}
// means a pixel resize, exactly as --width/--height without --type does
// on the flag path. Explicit standard/auto still needs type.
if resizeType == "" {
if size <= 0 {
return workbookCreateResizeOp{}, common.ValidationErrorf("%s needs size (px) or type (%s), e.g. %s", path, typeHint, resizeOpExample(dimension))
}
resizeType = "pixel"
}
if resizeType == "pixel" && size <= 0 {
return workbookCreateResizeOp{}, common.ValidationErrorf("%s.type pixel requires size, e.g. %s", path, resizeOpExample(dimension))
}
if resizeType != "pixel" && size > 0 {
return workbookCreateResizeOp{}, common.ValidationErrorf("%s.size is only valid with type pixel", path)
}
if err := rejectUnexpectedWorkbookStyleFields(op, path, "range", "type", "size", alias); err != nil {
return workbookCreateResizeOp{}, err
}
return workbookCreateResizeOp{Range: normalizeWorkbookResizeRange(rangeStr), ResizeType: resizeType, Size: size}, nil
}
func requireWorkbookCreateRange(op map[string]interface{}, path string) (string, error) {
@@ -1245,6 +1424,9 @@ func normalizeWorkbookCreateStyleObject(in map[string]interface{}, path string)
if len(in) == 0 {
return nil, nil
}
if err := foldBorderFamilyAliases(in, path); err != nil {
return nil, err
}
if err := normalizeCellStyleAliases(in, path); err != nil {
return nil, err
}
@@ -1259,15 +1441,33 @@ func normalizeWorkbookCreateStyleObject(in map[string]interface{}, path string)
if !ok {
return nil, common.ValidationErrorf("%s.border_styles must be a JSON object", path)
}
expandBorderAllShorthand(m)
if err := validateWorkbookBorderStyles(m, path); err != nil {
return nil, err
}
out["border_styles"] = m
case "value", "formula", "rich_text", "multiple_values", "note", "data_validation":
return nil, common.ValidationErrorf("%s is for styles only; put content in --values or use --sheets for typed cell objects", path)
return nil, common.ValidationErrorf("%s.%s is a content field — a styles spec carries no cell content; write values/formulas via +cells-set or +table-put", path, k)
default:
if !workbookCreateCellStyleField(k) {
return nil, common.ValidationErrorf("%s.%s is not a supported style field", path, k)
// Universal rejection with the full field list: this is the
// mechanism that absorbs the infinite tail of spelling
// permutations at a fixed one-retry cost — silent aliases are
// reserved for high-frequency words from real external
// vocabularies (see the style_vocab.go contract). A curated
// prescription wins over did-you-mean; without one, the
// distance match must be a near-typo (≤2 edits) — a
// concept-swap neighbor (font_bold → font_color, distance 3)
// misleads worse than silence.
msg := fmt.Sprintf("%s.%s is not a supported style field", path, k)
lower := strings.ToLower(k)
if rx, ok := styleFieldPrescriptions[lower]; ok {
msg += " — " + rx
} else if match := suggest.Closest(lower, workbookCreateCellStyleFieldList, 1); len(match) > 0 && suggest.Levenshtein(lower, match[0]) <= 2 {
msg += fmt.Sprintf(" — did you mean %q?", match[0])
}
msg += "; supported: " + strings.Join(workbookCreateCellStyleFieldList, ", ")
return nil, common.ValidationErrorf("%s", msg)
}
cellStyle[k] = v
}
@@ -1278,6 +1478,14 @@ func normalizeWorkbookCreateStyleObject(in map[string]interface{}, path string)
return out, nil
}
// workbookCreateCellStyleFieldList is the canonical style vocabulary plus the
// two border carriers, in display order for the unknown-field hint.
var workbookCreateCellStyleFieldList = []string{
"font_color", "font_family", "font_size", "font_weight", "font_style", "font_line",
"background_color", "horizontal_alignment", "vertical_alignment",
"number_format", "word_wrap", "border", "border_styles",
}
func workbookCreateCellStyleField(name string) bool {
switch name {
case "font_color", "font_family", "font_size", "font_weight", "font_style", "font_line",
@@ -1299,7 +1507,7 @@ func validateWorkbookBorderStyles(m map[string]interface{}, path string) error {
switch side {
case "top", "bottom", "left", "right":
default:
return common.ValidationErrorf("%s.border_styles.%s is not a valid side (want top/bottom/left/right)", path, side)
return common.ValidationErrorf("%s.border_styles.%s is not a valid side (want top/bottom/left/right; a horizontal line is the top/bottom side of its range, a vertical line is left/right)", path, side)
}
spec, ok := raw.(map[string]interface{})
if !ok {
@@ -1516,7 +1724,7 @@ func workbookCreateVisualOps(styles *workbookCreateStylePayload) []workbookCreat
if styles == nil {
return nil
}
ops := make([]workbookCreateStyleOp, 0, len(styles.CellMerges)+len(styles.RowSizes)+len(styles.ColSizes))
ops := make([]workbookCreateStyleOp, 0, len(styles.CellMerges)+len(styles.RowSizes)+len(styles.ColSizes)+2)
for _, op := range styles.CellMerges {
ops = append(ops, workbookCreateStyleOp{Kind: "cell_merge", Range: op.Range, MergeType: op.MergeType})
}
@@ -1526,6 +1734,14 @@ func workbookCreateVisualOps(styles *workbookCreateStylePayload) []workbookCreat
for _, op := range styles.ColSizes {
ops = append(ops, workbookCreateStyleOp{Kind: "col_size", Range: op.Range, ResizeType: op.ResizeType, Size: op.Size})
}
if styles.Freeze != nil {
if styles.Freeze.Rows > 0 {
ops = append(ops, workbookCreateStyleOp{Kind: "freeze_rows", Size: styles.Freeze.Rows})
}
if styles.Freeze.Cols > 0 {
ops = append(ops, workbookCreateStyleOp{Kind: "freeze_cols", Size: styles.Freeze.Cols})
}
}
return ops
}
@@ -1564,6 +1780,18 @@ func workbookCreateVisualOpInput(token, sheetID, sheetName string, op workbookCr
input["resize_width"] = block
}
return input, "resize_range"
case "freeze_rows", "freeze_cols":
input := map[string]interface{}{
"excel_id": token,
"operation": "freeze",
}
sheetSelectorForToolInput(input, sheetID, sheetName)
if op.Kind == "freeze_rows" {
input["freeze_rows"] = op.Size
} else {
input["freeze_columns"] = op.Size
}
return input, "modify_sheet_structure"
default:
return nil, ""
}

View File

@@ -14,6 +14,7 @@ import (
"path/filepath"
"strconv"
"strings"
"unicode"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/validate"
@@ -38,7 +39,11 @@ import (
// CellsSet wraps set_cell_range: caller provides the cells matrix via --cells
// (JSON), with an optional --copy-to-range to replicate the written block
// across a larger area (formula refs auto-shift).
// across a larger area (formula refs auto-shift). The plural form --writes
// ([{sheet_name, range, cells}, …]) fans scattered regions — cross-sheet
// allowed — into ONE atomic batch_update: eval traces show "fix all broken
// formulas across ranges/sheets" as the dominant homogeneous scenario still
// hand-assembled as +batch-update operations arrays.
var CellsSet = common.Shortcut{
Service: "sheets",
Command: "+cells-set",
@@ -48,9 +53,31 @@ var CellsSet = common.Shortcut{
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+cells-set"),
Validate: validateViaInput(cellsSetInput),
Tips: []string{
`Example: lark-cli sheets +cells-set --url <URL> --sheet-name Sheet1 --range A1:B1 --cells '[[{"value":"名称"},{"formula":"=SUM(B2:B9)"}]]'`,
`--cells is always a 2D array (rows × cells), even for one cell: [[{"value":…}]].`,
`Scattered regions (e.g. fixing formulas across ranges/sheets): --writes '[{"sheet_name":…,"range":…,"cells":[[…]]}, …]' — one atomic call, sheet selector inside each item.`,
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
if runtime.Changed("writes") {
token, err := resolveSpreadsheetToken(runtime)
if err != nil {
return err
}
_, err = cellsSetWritesOps(runtime, token)
return err
}
return validateViaInput(cellsSetInput)(ctx, runtime)
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
token, _ := resolveSpreadsheetToken(runtime)
if runtime.Changed("writes") {
ops, _ := cellsSetWritesOps(runtime, token)
return invokeToolDryRun(token, ToolKindWrite, "batch_update", map[string]interface{}{
"excel_id": token,
"operations": ops,
})
}
sheetID, sheetName, _ := resolveSheetSelector(runtime)
input, _ := cellsSetInput(runtime, token, sheetID, sheetName)
return invokeToolDryRun(token, ToolKindWrite, "set_cell_range", input)
@@ -60,6 +87,21 @@ var CellsSet = common.Shortcut{
if err != nil {
return err
}
if runtime.Changed("writes") {
ops, err := cellsSetWritesOps(runtime, token)
if err != nil {
return err
}
out, err := callTool(ctx, runtime, token, ToolKindWrite, "batch_update", map[string]interface{}{
"excel_id": token,
"operations": ops,
})
if err != nil {
return err
}
runtime.Out(out, nil)
return nil
}
sheetID, sheetName, err := resolveSheetSelector(runtime)
if err != nil {
return err
@@ -77,6 +119,108 @@ var CellsSet = common.Shortcut{
},
}
// cellsSetWritesOps parses --writes ([{sheet_name|sheet_id, range, cells}, …])
// and expands it into set_cell_range operations for ONE atomic batch_update.
// Single source of truth per item: the sheet selector LIVES IN THE ITEM (same
// convention as +batch-update sub-ops and +styles-put items — no top-level
// fallback, no precedence table to remember). Every item runs through the
// exact standalone pipeline (key vocabulary, style acceptance layer, matrix
// precheck, schema validation) via a per-item flag view, and item errors are
// aggregated so one retry fixes them all.
func cellsSetWritesOps(runtime *common.RuntimeContext, token string) ([]interface{}, error) {
for _, conflicting := range []string{"range", "cells", "copy-to-range"} {
if runtime.Changed(conflicting) {
return nil, sheetsValidationForFlag("writes", "--writes and --%s are mutually exclusive: single region → --range + --cells; multiple regions → --writes alone", conflicting)
}
}
if strings.TrimSpace(runtime.Str("sheet-name")) != "" || strings.TrimSpace(runtime.Str("sheet-id")) != "" {
return nil, sheetsValidationForFlag("writes", "--writes does not accept a top-level sheet selector — put sheet_name (or sheet_id) inside each writes item, same as +batch-update sub-ops")
}
raw, err := requireJSONArray(runtime, "writes")
if err != nil {
return nil, err
}
if len(raw) == 0 {
return nil, sheetsValidationForFlag("writes", "--writes must be a non-empty JSON array of {sheet_name, range, cells} items")
}
if len(raw) > maxBatchOperations {
return nil, sheetsValidationForFlag("writes", "--writes accepts at most %d items; got %d — merge adjacent regions or split into several calls", maxBatchOperations, len(raw))
}
topLevelOverwrite := runtime.Bool("allow-overwrite")
ops := make([]interface{}, 0, len(raw))
var probs []error
var totalCells int64
for i, v := range raw {
item, ok := v.(map[string]interface{})
if !ok {
probs = append(probs, common.ValidationErrorf("--writes[%d] must be an object like {\"sheet_name\":…,\"range\":…,\"cells\":[[…]]}", i))
continue
}
if err := normalizeSubOpInputKeys("+cells-set", item); err != nil {
probs = append(probs, common.ValidationErrorf("--writes[%d]: %v", i, err))
continue
}
if topLevelOverwrite {
if _, has := item["allow_overwrite"]; !has {
item["allow_overwrite"] = true
}
}
fv := newMapFlagViewForCommand("+cells-set", item)
sheetID := strings.TrimSpace(fv.Str("sheet-id"))
sheetName := strings.TrimSpace(fv.Str("sheet-name"))
input, err := cellsSetInput(fv, token, sheetID, sheetName)
if err != nil {
probs = append(probs, common.ValidationErrorf("--writes[%d]: %v", i, err))
continue
}
if cells, ok := input["cells"].([]interface{}); ok {
for _, row := range cells {
if r, ok := row.([]interface{}); ok {
totalCells += int64(len(r))
}
}
}
if err := checkBatchStampBudget(totalCells); err != nil {
return nil, err
}
ops = append(ops, map[string]interface{}{
"tool_name": "set_cell_range",
"input": input,
})
}
if err := joinWritesValidationErrors(probs); err != nil {
return nil, err
}
return ops, nil
}
// joinWritesValidationErrors mirrors joinStyleValidationErrors for --writes:
// every item's first error in one message, so the whole payload is fixed in
// a single retry.
func joinWritesValidationErrors(probs []error) error {
switch len(probs) {
case 0:
return nil
case 1:
return probs[0]
}
const maxShown = 8
msgs := make([]string, 0, len(probs))
for _, e := range probs {
if p, ok := errs.ProblemOf(e); ok {
msgs = append(msgs, p.Message)
continue
}
msgs = append(msgs, e.Error())
}
suffix := ""
if len(msgs) > maxShown {
suffix = fmt.Sprintf(" (+%d more)", len(msgs)-maxShown)
msgs = msgs[:maxShown]
}
return common.ValidationErrorf("--writes has %d issues: %s%s", len(probs), strings.Join(msgs, " | "), suffix)
}
func cellsSetInput(runtime flagView, token, sheetID, sheetName string) (map[string]interface{}, error) {
if err := requireSheetSelector(sheetID, sheetName); err != nil {
return nil, err
@@ -91,9 +235,13 @@ func cellsSetInput(runtime flagView, token, sheetID, sheetName string) (map[stri
if err := normalizeTypedCellsStyleAliases(cells, "--cells"); err != nil {
return nil, err
}
rangeStr := strings.TrimSpace(runtime.Str("range"))
if err := checkCellsMatchRange(cells, rangeStr); err != nil {
return nil, err
}
input := map[string]interface{}{
"excel_id": token,
"range": strings.TrimSpace(runtime.Str("range")),
"range": rangeStr,
"cells": cells,
}
sheetSelectorForToolInput(input, sheetID, sheetName)
@@ -124,7 +272,11 @@ var CellsSetStyle = common.Shortcut{
AuthTypes: []string{"user", "bot"},
HasFormat: true,
Flags: flagsFor("+cells-set-style"),
Validate: validateViaInput(cellsSetStyleInput),
Tips: []string{
`Example: lark-cli sheets +cells-set-style --url <URL> --sheet-name Sheet1 --range A1:D1 --font-weight bold --background-color "#F0F0F0" --horizontal-alignment center`,
`Borders take JSON: --border-styles '{"top":{"style":"solid","weight":"thin","color":"#000000"}}' (sides: top/bottom/left/right).`,
},
Validate: validateViaInput(cellsSetStyleInput),
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
token, _ := resolveSpreadsheetToken(runtime)
sheetID, sheetName, _ := resolveSheetSelector(runtime)
@@ -310,33 +462,89 @@ func csvPutWriteRangeFromInput(input map[string]interface{}) (string, bool) {
// guardCSVValueIsNotFilePath catches the common slip of passing a CSV file path
// to --csv without the "@" that reads it (e.g. `--csv data.csv` instead of
// `--csv @data.csv`). Because any string is a valid one-cell CSV, the mistake
// would otherwise be written silently as the literal text "data.csv". It runs
// in +csv-put's Validate, after resolveInputFlags so an @file / stdin value is
// already its contents (a real CSV blob, never a path) and only a bare value
// reaches here unchanged. It flags the value only when it actually names an
// existing file in the cwd subtree; checking real existence (not name shape)
// means inline content that merely ends in a filename ("see config.json") is
// never misjudged. Fails open: any Stat error or a directory leaves the value
// untouched. Scoped to --csv only — no other flag is affected.
// would otherwise be written silently as the literal text "data.csv" — a wrong
// value in the sheet plus a success exit code, which costs more than a
// rejection because nothing surfaces it. It runs in +csv-put's Validate, after
// resolveInputFlags — so an @file / stdin value is already its contents (a real
// CSV blob, never a path) and only a bare value reaches here unchanged.
//
// Two tiers, because the fix differs:
//
// - the value names an existing file in the cwd subtree → a forgotten "@";
// - the file does not exist but the value is unmistakably path-shaped →
// usually an absolute path (which "@" rejects) that the caller retried
// without the "@", or a stale relative path from another working
// directory. Same silent-write outcome, different prescription: stdin.
//
// Everything else passes through. Existence alone can't carry tier two, so
// shape does — but only the narrow shape defined by csvValueLooksLikePath,
// which is what keeps prose that merely mentions a filename out of it.
// Fails open: any Stat error or a directory falls through to the shape check.
// Scoped to --csv only — no other flag is affected.
//
// A value that arrived via @file / stdin is skipped entirely
// (InputResolvedFromSource): its content was already read from the right
// place and may legitimately look like anything, including a path. That
// also makes stdin the guard-proof way to write such text verbatim.
func guardCSVValueIsNotFilePath(runtime *common.RuntimeContext) error {
if runtime.InputResolvedFromSource("csv") {
return nil
}
raw := strings.TrimSpace(runtime.Str("csv"))
if raw == "" {
return nil
}
fio := runtime.FileIO()
if fio == nil {
if fio := runtime.FileIO(); fio != nil {
info, err := fio.Stat(raw)
if err == nil && info != nil && !info.IsDir() {
return sheetsValidationForFlag("csv",
"--csv value %q is an existing file, not inline CSV; to read it use --csv @%s, or pass the literal text via stdin (--csv -)",
raw, raw,
)
}
}
if !csvValueLooksLikePath(raw) {
return nil
}
info, err := fio.Stat(raw)
if err != nil || info == nil || info.IsDir() {
return nil //nolint:nilerr // fail-open: a missing/unreadable path is treated as inline content, not a forgotten @
}
return sheetsValidationForFlag("csv",
"--csv value %q is an existing file, not inline CSV; to read it use --csv @%s, or pass the literal text via stdin (--csv -)",
raw, raw,
"--csv value %q looks like a file path, not inline CSV, and no such file exists under the current directory",
raw,
).WithHint(
"to read a file: --csv @<path> (relative to the current directory; @ rejects absolute paths, so for one of those pipe the file in instead: --csv - < %s). To write this text into the cell verbatim, pass it on stdin the same way (--csv -); values arriving via stdin or @file skip this check",
raw,
)
}
// csvValueLooksLikePath reports whether a --csv value is unmistakably a path
// rather than CSV content. Deliberately narrow: the guard rejects on it, so a
// false positive blocks a legitimate write, and an earlier name-shape
// heuristic was replaced by an existence check precisely because it misjudged
// prose ("改完记得更新config.json"). Three conditions, all required:
//
// no comma / newline / whitespace — real CSV has separators, prose has spaces
// pure ASCII — CJK text is content, never a path here
// a .csv/.tsv extension, or an explicit ./ ../ / ~/ prefix
//
// The extension-or-prefix rule is what keeps ordinary single-cell values safe:
// "N/A" contains a slash but neither, and "README.md" is a filename but not a
// CSV one. A caller who genuinely means such a literal still has stdin.
func csvValueLooksLikePath(s string) bool {
if strings.ContainsAny(s, ", \t\r\n\"") {
return false
}
for _, r := range s {
if r > unicode.MaxASCII {
return false
}
}
lower := strings.ToLower(s)
if strings.HasSuffix(lower, ".csv") || strings.HasSuffix(lower, ".tsv") {
return true
}
return strings.HasPrefix(s, "./") || strings.HasPrefix(s, "../") ||
strings.HasPrefix(s, "/") || strings.HasPrefix(s, "~/")
}
func csvPutInput(runtime flagView, token, sheetID, sheetName string) (map[string]interface{}, error) {
if err := requireSheetSelector(sheetID, sheetName); err != nil {
return nil, err
@@ -625,6 +833,43 @@ func warnDropdownSourceRangeHighlight(runtime *common.RuntimeContext) {
// and returns its row / column counts. Errors on non-rectangular forms like
// "A:C" (whole-column) or "3:6" (whole-row) — those need a row/col total
// from get_sheet_structure, outside the scope of pure local parsing.
// checkCellsMatchRange rejects, before any network call, the cells-vs-range
// mismatches the server would otherwise fail mid-batch ("cells row count (N)
// does not match range row count (M)" — a recurring server-side error cluster
// in eval traces, and the failure leaves earlier batch sub-ops applied).
// Single-cell ranges are checked too: the server enforces the same strict
// match on a bare "A1" (07-21 rerun, 12 rows against range row count 1) —
// there is no anchor semantics on +cells-set. An unparsable range is the
// range validator's job, not ours.
func checkCellsMatchRange(cells []interface{}, rangeStr string) error {
if len(cells) == 0 {
return sheetsValidationForFlag("cells",
"--cells is empty; to clear values use +cells-clear --scope content (needs --yes), or pass a non-empty 2D array")
}
rows, cols, err := rangeDimensions(rangeStr)
if err != nil {
return nil //nolint:nilerr // an unparsable range is reported by the range validation path with proper context
}
if len(cells) != rows {
return sheetsValidationForFlag("cells",
"--cells has %d rows but --range %q spans %d rows; make them equal (e.g. write N rows to an N-row range)",
len(cells), rangeStr, rows)
}
for r, rowRaw := range cells {
row, ok := rowRaw.([]interface{})
if !ok {
return sheetsValidationForFlag("cells",
"--cells[%d] must be an array (one row of cells) — --cells is always a 2D array, a single cell is [[{…}]]", r)
}
if len(row) != cols {
return sheetsValidationForFlag("cells",
"--cells[%d] has %d columns but --range %q spans %d columns; every row must match the range width",
r, len(row), rangeStr, cols)
}
}
return nil
}
func rangeDimensions(rangeStr string) (rows, cols int, err error) {
if idx := strings.Index(rangeStr, "!"); idx >= 0 {
rangeStr = rangeStr[idx+1:]

View File

@@ -0,0 +1,71 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"bytes"
"encoding/json"
"strings"
"github.com/larksuite/cli/extension/fileio"
"github.com/larksuite/cli/shortcuts/common"
)
// ─── lark_sheet read → file offload ───────────────────────────────────
//
// Shared plumbing for +cells-get / +csv-get / +table-get behind the
// --output-path flag: when a caller redirects a read to a file, the char cap
// should default to unlimited so the whole sheet lands on disk instead of being
// clipped by the stdout-oriented max_chars safety cap.
// readOutputPath returns the trimmed --output-path flag value ("" when unset).
func readOutputPath(runtime *common.RuntimeContext) string {
return strings.TrimSpace(runtime.Str("output-path"))
}
// maxCharsInput resolves the max_chars value to send to the underlying read
// tool. With --output-path set the cap is lifted (unbounded sentinel) so the
// full result is written to the file; otherwise the --max-chars value binds.
// The second return is false when nothing should be sent (max-chars <= 0), in
// which case the tool's own default applies. Note the tool truncates at ~50000
// even when max_chars is omitted, so callers that want an explicit cap should
// pass a positive default.
func maxCharsInput(runtime *common.RuntimeContext) (int, bool) {
if readOutputPath(runtime) != "" {
return unboundedReadLimit, true
}
if n := runtime.Int("max-chars"); n > 0 {
return n, true
}
return 0, false
}
// emitReadResult delivers a read shortcut's result. When --output-path is set it
// writes the data payload to that path as pretty JSON and prints a small
// confirmation envelope to stdout (path + byte count); otherwise it prints the
// full result envelope to stdout as usual.
func emitReadResult(runtime *common.RuntimeContext, out interface{}) error {
path := readOutputPath(runtime)
if path == "" {
runtime.Out(out, nil)
return nil
}
b, err := json.MarshalIndent(out, "", " ")
if err != nil {
return err
}
b = append(b, '\n')
if _, err := runtime.FileIO().Save(path, fileio.SaveOptions{}, bytes.NewReader(b)); err != nil {
return err
}
resolved, err := runtime.FileIO().ResolvePath(path)
if err != nil {
resolved = path
}
runtime.Out(map[string]interface{}{
"output_path": resolved,
"bytes_written": len(b),
}, nil)
return nil
}

View File

@@ -7,6 +7,7 @@ import (
"context"
"encoding/json"
"fmt"
"strings"
"github.com/larksuite/cli/errs"
"github.com/larksuite/cli/internal/util"
@@ -83,7 +84,7 @@ func callTool(
code, _ := util.ToFloat64(envelope["code"])
if code != 0 {
msg, _ := envelope["msg"].(string)
return nil, errs.NewAPIError(errs.SubtypeServerError, "tool %q failed: [%d] %s", toolName, int(code), msg).
return nil, errs.NewAPIError(errs.SubtypeServerError, "tool %q failed: [%d] %s", toolName, int(code), flattenToolErrorMsg(msg)).
WithCode(int(code))
}
data, _ := envelope["data"].(map[string]interface{})
@@ -100,6 +101,66 @@ func callTool(
return out, nil
}
// flattenToolErrorMsg unwraps the nested-escaped-JSON error payload some
// sheet-ai tools put in msg — batch_update in particular wraps its result as
// {"error":"{\"message\":\"batch_update: N succeeded, M failed\",
// \"failures\":[…]}","errorType":…,"data":{…}} — into one readable line
// naming each failed operation. Eval traces show agents (and even the eval
// aggregator) failing to extract the real cause from the double-escaped
// form. Anything that doesn't match the nested shape passes through
// untouched.
func flattenToolErrorMsg(msg string) string {
trimmed := strings.TrimSpace(msg)
if !strings.HasPrefix(trimmed, "{") {
return msg
}
var outer struct {
Error string `json:"error"`
}
if json.Unmarshal([]byte(trimmed), &outer) != nil || strings.TrimSpace(outer.Error) == "" {
return msg
}
inner := strings.TrimSpace(outer.Error)
var detail struct {
Message string `json:"message"`
Failures []struct {
Index int `json:"index"`
ToolName string `json:"tool_name"`
Error string `json:"error"`
} `json:"failures"`
}
if strings.HasPrefix(inner, "{") && json.Unmarshal([]byte(inner), &detail) == nil && detail.Message != "" {
if len(detail.Failures) == 0 {
return detail.Message
}
parts := make([]string, 0, len(detail.Failures))
firstFailed := detail.Failures[0].Index
for _, f := range detail.Failures {
parts = append(parts, fmt.Sprintf("operations[%d] (%s): %s", f.Index, f.ToolName, f.Error))
if f.Index < firstFailed {
firstFailed = f.Index
}
}
out := detail.Message + " — " + strings.Join(parts, "; ")
// Partial failure is NOT rolled back server-side: the succeeded sub-ops
// stay applied. Spell out the recovery so agents don't resend the whole
// batch and double-apply the successes (observed in eval traces). With
// one failure (fail-fast) everything before it succeeded and nothing
// after it ran — resend from that index; with several (continue-on-error)
// only the listed failures need resending.
if strings.Contains(detail.Message, "succeeded") &&
!strings.Contains(detail.Message, " 0 succeeded") {
if len(detail.Failures) == 1 {
out += fmt.Sprintf("; note: succeeded operations stay applied (no rollback) — fix the failure and resend only operations[%d:] onward, do not resend the whole batch", firstFailed)
} else {
out += "; note: succeeded operations stay applied (no rollback) — fix and resend only the failed operations listed above, do not resend the whole batch"
}
}
return out
}
return inner
}
// invokeToolDryRun renders the One-OpenAPI request the shortcut would send.
// The wire-format body (with input serialized to a JSON string) is preserved
// for fidelity, and a decoded tool_input map is surfaced alongside so humans

View File

@@ -0,0 +1,57 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"strings"
"testing"
)
// TestFlattenToolErrorMsg pins the unwrap of batch_update's double-escaped
// error payload (the exact shape from eval V2U038/V2U013 traces) and the
// pass-through of everything else.
func TestFlattenToolErrorMsg(t *testing.T) {
t.Parallel()
t.Run("batch failures flatten to one line", func(t *testing.T) {
t.Parallel()
msg := `{"error":"{\"message\":\"batch_update: 0 succeeded, 1 failed\",\"succeeded\":0,\"failed\":1,\"failures\":[{\"index\":0,\"tool_name\":\"manage_chart_object\",\"error\":\"invalid snapshot.data.dim1.serie.index: 0, must be >= 1 (index is 1-based)\",\"errorType\":\"param_error\"}]}","errorType":"param_error","data":{"total":2,"succeeded":0,"failed":1}}`
got := flattenToolErrorMsg(msg)
for _, want := range []string{
"batch_update: 0 succeeded, 1 failed",
"operations[0] (manage_chart_object): invalid snapshot.data.dim1.serie.index",
} {
if !strings.Contains(got, want) {
t.Errorf("flattened msg should contain %q, got %q", want, got)
}
}
if strings.Contains(got, `\"`) {
t.Errorf("flattened msg must not carry escaped JSON, got %q", got)
}
})
t.Run("plain-string inner error unwraps", func(t *testing.T) {
t.Parallel()
got := flattenToolErrorMsg(`{"error":"sheet \"s\" not found","errorType":"param_error"}`)
if got != `sheet "s" not found` {
t.Errorf("got %q", got)
}
})
t.Run("non-JSON msg passes through", func(t *testing.T) {
t.Parallel()
msg := `cell at row 0, col 1 is inside a merged region (top-left: A1)`
if got := flattenToolErrorMsg(msg); got != msg {
t.Errorf("got %q", got)
}
})
t.Run("JSON without error field passes through", func(t *testing.T) {
t.Parallel()
msg := `{"detail":"x"}`
if got := flattenToolErrorMsg(msg); got != msg {
t.Errorf("got %q", got)
}
})
}

View File

@@ -35,6 +35,11 @@ func Shortcuts() []common.Shortcut {
if hasFlag(all[i].Flags, "spreadsheet-token") {
all[i].PostMount = withTokenAlias(all[i].PostMount)
}
// +chart-create grows --print-example (minimal per-type --properties
// templates) — the biggest --print-schema consumer in eval traces.
if all[i].Command == "+chart-create" {
all[i].PostMount = withChartPrintExample(all[i].PostMount)
}
// Sheets-scoped flag ergonomics (unknown-flag hints with the valid
// flags inlined, enum vocabulary normalization) ride the same
// PostMount composition, so no other domain's behavior shifts.
@@ -146,6 +151,7 @@ func shortcutList() []common.Shortcut {
// Object CRUD (3 per skill)
ChartCreate, ChartUpdate, ChartDelete,
ChartCreateBasic, ChartConfigUpdate, ChartDataUpdate,
PivotCreate, PivotUpdate, PivotDelete,
CondFormatCreate, CondFormatUpdate, CondFormatDelete,
FilterCreate, FilterUpdate, FilterDelete,
@@ -153,8 +159,13 @@ func shortcutList() []common.Shortcut {
SparklineCreate, SparklineUpdate, SparklineDelete,
FloatImageCreate, FloatImageUpdate, FloatImageDelete,
// lark_sheet_styles_put
StylesPut,
// lark_sheet_batch_update
BatchUpdate,
BatchChartCreate,
BatchChartUpdate,
CellsBatchSetStyle,
CellsBatchClear,
DropdownUpdate,

View File

@@ -0,0 +1,521 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"fmt"
"slices"
"strings"
"github.com/larksuite/cli/shortcuts/common"
)
// ─── style vocabulary acceptance layer ────────────────────────────────
//
// The single home for how the sheets domain ACCEPTS style vocabulary, across
// all three carrier paths that end in set_cell_range bodies:
//
// flag path +cells-set-style / +cells-batch-set-style flat flags
// typed cells +cells-set --cells cell objects (incl. batch sub-ops)
// styles payload --styles on +workbook-create / +table-put / +styles-put
//
// Design contract (established in the 2026-07 batch-update overhaul; see the
// acceptance tests in styles_acceptance_test.go):
//
// - ONE canonical form, documented; a WIDE acceptance layer, undocumented.
// Model priors are divergent (one eval batch produced six different
// border spellings), so no canonical structure can make first tries
// succeed — acceptance is normalized here instead, never per-call-site.
// - Every rewrite must be unambiguous; ambiguous guesses (fore_color) get
// a targeted prescription, never a silent pick. Silent ignoring and
// bare rejection are both bugs.
// - SILENT-ALIAS ADMISSION BAR (2026-07-21): only words from REAL external
// vocabularies (Excel/openpyxl, CSS, Google Sheets API), recurring
// across batches or ≥3 tasks in one, with zero semantic ambiguity.
// Spelling/word-order permutations do NOT get aliases — they are
// absorbed by the universal did-you-mean rejection (one self-healing
// retry, zero per-variant code). Real vocabularies are a finite set;
// permutations are not. Earlier permutation aliases are grandfathered.
// - Closure is enforced by two test properties: vocabulary parity (every
// flag-path style must be accepted on the payload paths) and the prior
// corpus (every observed model spelling either normalizes or
// prescribes). New eval finding → corpus row → fix HERE → locked.
// ─── style flags (shared by +cells-set-style and +cells-batch-set-style) ─
// buildCellStyleFromFlags reads the 12 flat style flags and returns the
// cell_styles map expected by set_cell_range. Skips any flag the user
// didn't set so partial styles work.
func buildCellStyleFromFlags(runtime flagView) map[string]interface{} {
style := map[string]interface{}{}
if v := runtime.Str("background-color"); v != "" {
style["background_color"] = v
}
if v := runtime.Str("font-color"); v != "" {
style["font_color"] = v
}
if v := runtime.Str("font-family"); v != "" {
style["font_family"] = v
}
if runtime.Changed("font-size") && runtime.Float64("font-size") > 0 {
style["font_size"] = runtime.Float64("font-size")
}
if v := runtime.Str("font-style"); v != "" {
style["font_style"] = v
}
if v := runtime.Str("font-weight"); v != "" {
style["font_weight"] = v
}
if v := runtime.Str("font-line"); v != "" {
style["font_line"] = v
}
if v := runtime.Str("horizontal-alignment"); v != "" {
style["horizontal_alignment"] = v
}
if v := runtime.Str("vertical-alignment"); v != "" {
style["vertical_alignment"] = v
}
if v := runtime.Str("word-wrap"); v != "" {
style["word_wrap"] = v
}
if v := runtime.Str("number-format"); v != "" {
style["number_format"] = v
}
return style
}
// cellStyleAliases maps shorthand cell_styles field names that models commonly
// hallucinate (Excel / openpyxl / CSS conventions) onto the canonical field
// names the backend expects. Only the unambiguous alignment shorthands are
// aliased — they are the high-frequency miss; ambiguous guesses (e.g. "color",
// "bg_color", "text_align") are intentionally left out so a wrong guess still
// surfaces as an error rather than being silently reinterpreted.
var cellStyleAliases = []struct{ alias, canonical string }{
{"horizontal_align", "horizontal_alignment"},
{"halign", "horizontal_alignment"},
{"vertical_align", "vertical_alignment"},
{"valign", "vertical_alignment"},
// wrap family: word_wrap is the sole wrap concept, no ambiguity. 07-20
// eval: wrap_text alone produced an 88-issue retry loop on --styles;
// wrap_strategy (the Google Sheets API word) followed on 07-21.
{"wrap_text", "word_wrap"},
{"text_wrap", "word_wrap"},
{"wrap_strategy", "word_wrap"},
}
// styleFieldPrescriptions carries the exact fix for high-frequency
// unsupported cell_styles field names where the edit-distance suggester is
// actively misleading (07-28 root-cause report: font_bold drew "did you mean
// font_color?" and nested font drew "font_line" — an agent that follows
// either burns a second failed round trip). Keyed by lowercased field name;
// the text replaces the did-you-mean on the unsupported-field error. These
// stay prescriptions, not silent aliases: bold/text_align are on the
// deliberate no-alias list above.
var styleFieldPrescriptions = map[string]string{
"bold": `bold text is font_weight:"bold"`,
"font_bold": `bold text is font_weight:"bold"`,
"italic": `italic text is font_style:"italic"`,
"underline": `underline is font_line:"underline"`,
"text_align": "horizontal text alignment is horizontal_alignment (left/center/right)",
"font": `cell_styles has no nested font object — use the flat font_* fields (font:{"bold":true,"size":18,"color":"#000"} becomes font_weight:"bold", font_size:18, font_color:"#000")`,
}
// cellStyleEnumFields sources the enum vocabulary for enum-bearing
// cell_styles fields from the +cells-set-style flag-defs, so the payload path
// (--styles / typed --cells) validates and canonicalizes values the same way
// the cobra flag path does. 07-20 eval: "vertical_alignment":"center" (CSS
// vocabulary; Lark spells it "middle") passed the CLI and burned a
// server-side round trip ~10 times — the flag path had normalized it since
// round 2, the payload path never did.
func cellStyleEnumFields() map[string][]string {
defs, err := loadFlagDefs()
if err != nil {
return nil
}
spec, ok := defs["+cells-set-style"]
if !ok {
return nil
}
out := map[string][]string{}
for _, df := range spec.Flags {
if df.Kind != "own" || df.Type != "string" || len(df.Enum) == 0 {
continue
}
out[strings.ReplaceAll(df.Name, "-", "_")] = df.Enum
}
return out
}
// normalizeCellStyleAliases renames known shorthand keys in a single
// cell_styles map to their canonical equivalents, in place, so a model that
// writes e.g. "horizontal_align" instead of "horizontal_alignment" still
// applies the style instead of hitting an "unsupported field" error (--styles)
// or having the field silently dropped by the backend (typed --cells). If both
// the shorthand and its canonical key are present it returns a validation error
// rather than picking one. It then canonicalizes enum VALUES (casing + known
// cross-vocabulary aliases like CSS "center" → Lark "middle"; boolean
// word_wrap → the enum) and rejects off-enum values client-side instead of
// letting the server fail the whole batch. path labels the map for errors.
func normalizeCellStyleAliases(style map[string]interface{}, path string) error {
if len(style) == 0 {
return nil
}
for _, a := range cellStyleAliases {
v, ok := style[a.alias]
if !ok {
continue
}
if _, exists := style[a.canonical]; exists {
return common.ValidationErrorf("%s.%s conflicts with %s; pass only %s", path, a.alias, a.canonical, a.canonical)
}
style[a.canonical] = v
delete(style, a.alias)
}
// fore_color is deliberately NOT aliased: in openpyxl vocabulary fgColor
// is the FILL color while a plain reading suggests the font color — a
// silent pick could color the wrong thing. Prescribe both options.
if _, has := style["fore_color"]; has {
return common.ValidationErrorf("%s.fore_color is ambiguous — use font_color for text color or background_color for the cell fill", path)
}
// Boolean wrap habit: true unambiguously means wrap on, false means off.
if b, isBool := style["word_wrap"].(bool); isBool {
if b {
style["word_wrap"] = "auto-wrap"
} else {
style["word_wrap"] = "overflow"
}
}
for field, enum := range cellStyleEnumFields() {
raw, has := style[field]
if !has {
continue
}
val, isStr := raw.(string)
if !isStr || val == "" || slices.Contains(enum, val) {
continue
}
if canon := canonicalEnumValue(val, enum); canon != "" {
style[field] = canon
continue
}
msg := fmt.Sprintf("%s.%s value %q is invalid (allowed: %s)", path, field, val, strings.Join(enum, ", "))
if match := closestEnumValue(val, enum); match != "" {
msg += fmt.Sprintf("; did you mean %q?", match)
}
return common.ValidationErrorf("%s", msg)
}
return nil
}
// normalizeTypedCellsStyleAliases walks a typed --cells 2D array and applies
// normalizeCellStyleAliases to every cell's inline cell_styles object, so the
// alignment shorthands are accepted on +cells-set the same as on --styles.
// It also expands the border "all" shorthand and intercepts border_styles
// mis-nested inside cell_styles — both server-rejected shapes that eval
// traces show surviving CLI validation and costing a full network round
// trip. Structure is checked leniently to match the pass-through contract:
// any element that isn't the expected shape is skipped, not rejected.
func normalizeTypedCellsStyleAliases(cells []interface{}, path string) error {
for r, rowRaw := range cells {
row, ok := rowRaw.([]interface{})
if !ok {
continue
}
for c, cellRaw := range row {
cell, ok := cellRaw.(map[string]interface{})
if !ok {
continue
}
// cells[][].style is the habitual spelling of cell_styles (recurring
// server-side 900015206 in eval traces) — rewrite when unambiguous.
if styleObj, isObj := cell["style"].(map[string]interface{}); isObj {
if _, has := cell["cell_styles"]; has {
return common.ValidationErrorf("%s[%d][%d].style conflicts with cell_styles; pass only cell_styles", path, r, c)
}
cell["cell_styles"] = styleObj
delete(cell, "style")
}
// cells[][].type is not a cell field; the value type is whatever the
// JSON value is. Reject with the fix instead of a server round trip.
if _, has := cell["type"]; has {
return common.ValidationErrorf("%s[%d][%d].type is not a cell field — the value type is inferred from the JSON value; control display format via cell_styles.number_format", path, r, c)
}
if bs, ok := cell["border_styles"].(map[string]interface{}); ok {
expandBorderAllShorthand(bs)
}
st, ok := cell["cell_styles"].(map[string]interface{})
if !ok {
continue
}
if _, misNested := st["border_styles"]; misNested {
return common.ValidationErrorf(
"%s[%d][%d].cell_styles.border_styles is not valid — border_styles is a top-level cell field, a sibling of cell_styles; move it up one level",
path, r, c)
}
if err := normalizeCellStyleAliases(st, fmt.Sprintf("%s[%d][%d].cell_styles", path, r, c)); err != nil {
return err
}
}
}
return nil
}
// expandBorderAllShorthand rewrites the "all" side shorthand — habitual from
// Excel / openpyxl vocabulary, rejected by the backend — into the four
// explicit sides, in place. An explicitly set side wins over the shorthand.
// Applied on both the typed --cells path and the --styles path, so batch
// sub-ops get the same rewrite as standalone calls.
func expandBorderAllShorthand(border map[string]interface{}) {
if all, ok := border["all"]; ok {
for _, side := range []string{"top", "bottom", "left", "right"} {
if _, exists := border[side]; !exists {
border[side] = all
}
}
delete(border, "all")
}
// Weight vocabulary in the style slot ("thin"/"medium"/"thick" are the
// habitual Excel words; the largest residual styles cluster in the 07-21
// rerun wrote them into border_styles.<side>.style of the FULL nested
// form). A thin border always means a thin solid line: move the word to
// weight and default style to solid. Only when weight is absent — an
// explicit conflicting weight keeps the enum error path.
for _, raw := range border {
side, ok := raw.(map[string]interface{})
if !ok {
continue
}
s, _ := side["style"].(string)
switch strings.ToLower(s) {
case "thin", "medium", "thick":
if _, hasWeight := side["weight"]; !hasWeight {
side["weight"] = strings.ToLower(s)
side["style"] = "solid"
}
}
}
}
// normalizeBorderStylesFlagValue runs the border vocabulary rewrites on the
// parsed --border-styles value BEFORE schema validation (jsonFlagNormalizers
// seam in parseJSONFlag). Without it the enum check fires first and rejects
// the weight-word-in-style habit ({"style":"thin"}) that
// expandBorderAllShorthand exists to absorb — the acceptance layer was
// unreachable on this path (07-28 root-cause report #2, 173 occurrences).
// Non-object shapes pass through for the validator to prescribe.
func normalizeBorderStylesFlagValue(v interface{}) interface{} {
if m, ok := v.(map[string]interface{}); ok {
expandBorderAllShorthand(m)
}
return v
}
// normalizeCellsFlagValue is the +cells-set --cells pre-validation pipeline:
// wrap a lone cell object into [[cell]], then run the border vocabulary
// rewrites on each cell's border_styles so weight words in the style slot
// normalize before the enum check — same reachability fix as
// normalizeBorderStylesFlagValue, for the typed-cells carrier (07-28
// root-cause report #10, 58 occurrences). Structure is checked leniently:
// anything that isn't the expected shape is left for the validator.
func normalizeCellsFlagValue(v interface{}) interface{} {
v = wrapLoneCellObject(v)
rows, ok := v.([]interface{})
if !ok {
return v
}
for _, rowRaw := range rows {
row, ok := rowRaw.([]interface{})
if !ok {
continue
}
for _, cellRaw := range row {
cell, ok := cellRaw.(map[string]interface{})
if !ok {
continue
}
if bs, ok := cell["border_styles"].(map[string]interface{}); ok {
expandBorderAllShorthand(bs)
}
}
}
return v
}
// borderStylesFromFlag parses --border-styles as a JSON object (top/bottom/
// left/right with style sub-objects), expanding the "all" side shorthand the
// same as the typed --cells and --styles paths so +cells-set-style /
// +cells-batch-set-style don't ship {"all":…} for the backend to reject.
// The expansion normally already ran inside parseJSONFlag (see
// normalizeBorderStylesFlagValue); the call here is an idempotent safety net
// for entry paths that bypass the normalizer table.
// Returns nil when the flag is empty.
func borderStylesFromFlag(runtime flagView) (map[string]interface{}, error) {
if runtime.Str("border-styles") == "" {
return nil, nil
}
v, err := parseJSONFlag(runtime, "border-styles")
if err != nil {
return nil, err
}
m, ok := v.(map[string]interface{})
if !ok {
return nil, sheetsValidationForFlag("border-styles", "--border-styles must be a JSON object")
}
expandBorderAllShorthand(m)
return m, nil
}
// requireAnyStyleFlag ensures at least one style-defining flag (style or
// border) is set — otherwise the request would do nothing.
func requireAnyStyleFlag(runtime flagView) error {
if len(buildCellStyleFromFlags(runtime)) > 0 {
return nil
}
if runtime.Str("border-styles") != "" {
return nil
}
return common.ValidationErrorf("at least one style flag is required (e.g. --background-color, --font-weight, --border-styles)").
WithParams(
sheetsInvalidParam("background-color", "required; specify at least one style flag"),
sheetsInvalidParam("font-weight", "required; specify at least one style flag"),
sheetsInvalidParam("border-styles", "required; specify at least one style flag"),
)
}
// foldBorderFamilyAliases rewrites the habitual flattened border vocabulary
// (Excel / openpyxl conventions) into the canonical nested border_styles
// object, in place. 07-20 eval: the border family alone accounted for the
// largest --styles error cluster (borders / border / border_bottom /
// border_style / border_top_color / …), each burning a full payload retry.
// Accepted rewrites, all unambiguous:
//
// borders / border (object) → border_styles (side-keyed) or border_styles.all (attr-keyed)
// border_top|bottom|left|right (object) → border_styles.<side>
// border_style|color|weight (scalar) → border_styles.all.<attr>
// border_<side>_<style|color|weight> (scalar) → border_styles.<side>.<attr>
//
// A border_style value from the WEIGHT vocabulary (thin/medium/thick — the
// habitual Excel word) sets weight and defaults style to solid: a "thin
// border" always means a thin solid line. Conflicts with an explicitly given
// border_styles error out instead of picking a side.
func foldBorderFamilyAliases(in map[string]interface{}, path string) error {
sides := map[string]bool{"top": true, "bottom": true, "left": true, "right": true, "all": true}
attrs := map[string]bool{"style": true, "color": true, "weight": true}
borderWeights := map[string]bool{"thin": true, "medium": true, "thick": true}
ensureBorder := func() map[string]interface{} {
bs, ok := in["border_styles"].(map[string]interface{})
if !ok {
bs = map[string]interface{}{}
in["border_styles"] = bs
}
return bs
}
setSideAttr := func(side, attr string, v interface{}, from string) error {
bs := ensureBorder()
sideObj, ok := bs[side].(map[string]interface{})
if !ok {
if _, exists := bs[side]; exists {
return common.ValidationErrorf("%s.%s conflicts with border_styles.%s; keep one form", path, from, side)
}
sideObj = map[string]interface{}{}
bs[side] = sideObj
}
if _, exists := sideObj[attr]; exists {
return common.ValidationErrorf("%s.%s conflicts with border_styles.%s.%s; keep one form", path, from, side, attr)
}
sideObj[attr] = v
return nil
}
setSide := func(side string, v interface{}, from string) error {
obj, ok := v.(map[string]interface{})
if !ok {
return common.ValidationErrorf("%s.%s must be an object like {\"style\":\"solid\",\"color\":\"#000000\"}", path, from)
}
for attr, av := range obj {
if !attrs[attr] {
return common.ValidationErrorf("%s.%s.%s is not a border attribute (want style/weight/color)", path, from, attr)
}
if err := setSideAttr(side, attr, av, from); err != nil {
return err
}
}
return nil
}
// border_style with a weight-vocabulary value means "thin solid line".
setAllScalar := func(attr string, v interface{}, from string) error {
if attr == "style" {
if s, ok := v.(string); ok && borderWeights[strings.ToLower(s)] {
if err := setSideAttr("all", "weight", strings.ToLower(s), from); err != nil {
return err
}
return setSideAttr("all", "style", "solid", from)
}
}
return setSideAttr("all", attr, v, from)
}
for _, key := range []string{"borders", "border"} {
v, has := in[key]
if !has {
continue
}
obj, ok := v.(map[string]interface{})
if !ok {
return common.ValidationErrorf("%s.%s must be an object — either side-keyed ({\"top\":{…},\"bottom\":{…}} / {\"all\":{…}}) or attribute-keyed ({\"style\":\"solid\",\"color\":\"#000\"} = all four sides)", path, key)
}
sideKeyed := false
for k := range obj {
if sides[k] {
sideKeyed = true
break
}
}
if sideKeyed {
for side, sv := range obj {
if !sides[side] {
return common.ValidationErrorf("%s.%s.%s is not a valid side (want top/bottom/left/right/all)", path, key, side)
}
if err := setSide(side, sv, key); err != nil {
return err
}
}
} else if err := setSide("all", v, key); err != nil {
return err
}
delete(in, key)
}
for _, side := range []string{"top", "bottom", "left", "right"} {
// Both word orders appear in the wild: border_bottom (07-20 eval) and
// bottom_border (07-21), same for the flattened attribute triples.
for _, key := range []string{"border_" + side, side + "_border"} {
if v, has := in[key]; has {
if err := setSide(side, v, key); err != nil {
return err
}
delete(in, key)
}
}
for attr := range attrs {
for _, key := range []string{"border_" + side + "_" + attr, side + "_border_" + attr} {
if v, has := in[key]; has {
if err := setSideAttr(side, attr, v, key); err != nil {
return err
}
delete(in, key)
}
}
}
}
for attr := range attrs {
key := "border_" + attr
if v, has := in[key]; has {
if err := setAllScalar(attr, v, key); err != nil {
return err
}
delete(in, key)
}
}
return nil
}

View File

@@ -0,0 +1,410 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"fmt"
"strings"
"testing"
)
// ─── styles acceptance contract ───────────────────────────────────────
//
// Two closure properties that turn the --styles acceptance surface from
// "endless patching" into a locked contract (07-20 rerun lesson: the
// redesign moved traffic onto the payload path while the flag path's
// forgiveness layers stayed behind):
//
// 1. Vocabulary parity — every style the flag path (+cells-set-style)
// can express must be accepted verbatim by the payload path.
// 2. Prior corpus — every model spelling observed in eval traces must
// either normalize to the canonical form or produce a targeted
// prescription. Silent ignoring and bare rejection are both bugs.
// New eval finding → add a corpus row → fix → locked forever.
// acceptStyleItem runs one cell_styles item through the styles-put pipeline
// and returns the emitted cell prototype (cell_styles/border_styles) or the
// error.
func acceptStyleItem(t *testing.T, fields map[string]interface{}) (map[string]interface{}, error) {
t.Helper()
item := map[string]interface{}{"range": "A1:B2"}
for k, v := range fields {
item[k] = v
}
ops, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{
"name": "S1",
"cell_styles": []interface{}{item},
}},
}), testToken)
if err != nil {
return nil, err
}
input := ops[0].(map[string]interface{})["input"].(map[string]interface{})
cells := input["cells"].([][]interface{})
return cells[0][0].(map[string]interface{}), nil
}
// TestStylesAcceptance_VocabularyParity locks property 1: iterate the
// +cells-set-style flag vocabulary from flag-defs and assert the payload
// path accepts each field with a valid value and emits it.
func TestStylesAcceptance_VocabularyParity(t *testing.T) {
t.Parallel()
defs, err := loadFlagDefs()
if err != nil {
t.Fatalf("loadFlagDefs: %v", err)
}
spec, ok := defs["+cells-set-style"]
if !ok {
t.Fatal("no +cells-set-style flag defs")
}
sample := func(df flagDef) interface{} {
if len(df.Enum) > 0 {
return df.Enum[0]
}
switch df.Type {
case "float64", "int":
return float64(12)
}
switch df.Name {
case "font-family":
return "Arial"
case "number-format":
return "0.00"
default: // colors and any future string field
return "#112233"
}
}
for _, df := range spec.Flags {
if df.Kind != "own" || df.Name == "range" {
continue
}
df := df
t.Run(df.Name, func(t *testing.T) {
t.Parallel()
field := strings.ReplaceAll(df.Name, "-", "_")
var value interface{}
if df.Name == "border-styles" {
value = map[string]interface{}{"all": map[string]interface{}{"style": "solid"}}
} else {
value = sample(df)
}
proto, err := acceptStyleItem(t, map[string]interface{}{field: value})
if err != nil {
t.Fatalf("payload path rejects flag-path field %s: %v", field, err)
}
if df.Name == "border-styles" {
if _, ok := proto["border_styles"].(map[string]interface{}); !ok {
t.Fatalf("border_styles not emitted: %v", proto)
}
return
}
cs, _ := proto["cell_styles"].(map[string]interface{})
if cs == nil || cs[field] == nil {
t.Fatalf("field %s silently dropped: %v", field, proto)
}
})
}
}
// stylesPriorCorpus is the observed-model-spelling corpus (source: eval
// batches 2026-07-08 → 07-20). Every row must either normalize (checked via
// wantCell) or produce a targeted prescription (wantErr). Add a row for every
// new spelling an eval surfaces — never let one be silently ignored.
var stylesPriorCorpus = []struct {
name string
fields map[string]interface{}
wantErr string // "" = must be accepted
check func(proto map[string]interface{}) string // "" = ok, else failure detail
}{
// border family (07-20: largest cluster)
{name: "borders attr-keyed means all sides",
fields: map[string]interface{}{"borders": map[string]interface{}{"style": "solid", "color": "#DDDDDD"}},
check: wantBorder("top", "style", "solid")},
{name: "border side-keyed",
fields: map[string]interface{}{"border": map[string]interface{}{"top": map[string]interface{}{"style": "solid"}}},
check: wantBorder("top", "style", "solid")},
{name: "border_bottom object",
fields: map[string]interface{}{"border_bottom": map[string]interface{}{"style": "solid"}},
check: wantBorder("bottom", "style", "solid")},
{name: "border_style weight-vocabulary means thin solid",
fields: map[string]interface{}{"border_style": "thin"},
check: wantBorder("top", "weight", "thin")},
{name: "border_style style-vocabulary",
fields: map[string]interface{}{"border_style": "dashed"},
check: wantBorder("top", "style", "dashed")},
{name: "border_color scalar",
fields: map[string]interface{}{"border_color": "#FF0000"},
check: wantBorder("top", "color", "#FF0000")},
{name: "border_top_color flattened",
fields: map[string]interface{}{"border_top_color": "#FF0000"},
check: wantBorder("top", "color", "#FF0000")},
{name: "border_left_weight flattened",
fields: map[string]interface{}{"border_left_weight": "thin"},
check: wantBorder("left", "weight", "thin")},
{name: "border_styles invalid side prescribed",
fields: map[string]interface{}{"border_styles": map[string]interface{}{"outer": map[string]interface{}{"style": "solid"}}},
wantErr: "not a valid side"},
// wrap family
{name: "wrap_text boolean", fields: map[string]interface{}{"wrap_text": true}, check: wantStyle("word_wrap", "auto-wrap")},
{name: "text_wrap string", fields: map[string]interface{}{"text_wrap": "auto-wrap"}, check: wantStyle("word_wrap", "auto-wrap")},
{name: "word_wrap false", fields: map[string]interface{}{"word_wrap": false}, check: wantStyle("word_wrap", "overflow")},
// alignment family
{name: "horizontal_align shorthand", fields: map[string]interface{}{"horizontal_align": "center"}, check: wantStyle("horizontal_alignment", "center")},
{name: "valign shorthand", fields: map[string]interface{}{"valign": "top"}, check: wantStyle("vertical_alignment", "top")},
{name: "CSS center for vertical", fields: map[string]interface{}{"vertical_alignment": "center"}, check: wantStyle("vertical_alignment", "middle")},
{name: "casing normalized", fields: map[string]interface{}{"font_weight": "BOLD"}, check: wantStyle("font_weight", "bold")},
// weight vocabulary in the FULL nested form's style slot (07-21 rerun:
// the dominant residual — 8 tasks wrote border_styles.<side>.style:"thin")
{name: "full-form thin in style slot",
fields: map[string]interface{}{"border_styles": map[string]interface{}{"top": map[string]interface{}{"style": "thin"}}},
check: wantBorder("top", "weight", "thin")},
{name: "full-form all-shorthand medium in style slot",
fields: map[string]interface{}{"border_styles": map[string]interface{}{"all": map[string]interface{}{"style": "medium"}}},
check: wantBorder("bottom", "weight", "medium")},
// side-first word order + Google Sheets wrap word (07-21 evening batch)
{name: "side-first bottom_border object",
fields: map[string]interface{}{"bottom_border": map[string]interface{}{"style": "solid"}},
check: wantBorder("bottom", "style", "solid")},
{name: "side-first bottom_border_style scalar",
fields: map[string]interface{}{"bottom_border_style": "solid"},
check: wantBorder("bottom", "style", "solid")},
{name: "wrap_strategy aliases to word_wrap",
fields: map[string]interface{}{"wrap_strategy": "auto-wrap"},
check: wantStyle("word_wrap", "auto-wrap")},
// prescriptions (ambiguous / unsupported / typo)
{name: "fore_color prescribed", fields: map[string]interface{}{"fore_color": "#F00"}, wantErr: "ambiguous"},
{name: "indent rejected not ignored", fields: map[string]interface{}{"indent": float64(2)}, wantErr: "not a supported style field"},
{name: "unknown field carries did-you-mean and the field list",
fields: map[string]interface{}{"fontcolor": "#000000"}, wantErr: `did you mean "font_color"`},
{name: "enum typo gets did-you-mean", fields: map[string]interface{}{"vertical_alignment": "botom"}, wantErr: "did you mean"},
}
func wantStyle(field, want string) func(map[string]interface{}) string {
return func(proto map[string]interface{}) string {
cs, _ := proto["cell_styles"].(map[string]interface{})
if cs == nil || cs[field] != want {
return fmt.Sprintf("cell_styles.%s = %v, want %q", field, cs[field], want)
}
return ""
}
}
func wantBorder(side, attr, want string) func(map[string]interface{}) string {
return func(proto map[string]interface{}) string {
bs, _ := proto["border_styles"].(map[string]interface{})
sideObj, _ := bs[side].(map[string]interface{})
if sideObj == nil || sideObj[attr] != want {
return fmt.Sprintf("border_styles.%s.%s = %v, want %q", side, attr, sideObj[attr], want)
}
return ""
}
}
func TestStylesAcceptance_PriorCorpus(t *testing.T) {
t.Parallel()
for _, tc := range stylesPriorCorpus {
tc := tc
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
proto, err := acceptStyleItem(t, tc.fields)
if tc.wantErr != "" {
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
t.Fatalf("want prescription containing %q, got err=%v", tc.wantErr, err)
}
return
}
if err != nil {
t.Fatalf("corpus spelling rejected: %v", err)
}
if detail := tc.check(proto); detail != "" {
t.Fatal(detail)
}
})
}
}
// TestStylesPut_CoalescesSameStyleRanges pins the declarative-spec
// optimization: per-row entries with the identical style fuse into one
// rectangle, so row-by-row specs (07-21 rerun: 184/203/861-op expansions
// against the 100-op cap) no longer hit the cap.
func TestStylesPut_CoalescesSameStyleRanges(t *testing.T) {
t.Parallel()
t.Run("150 same-style rows fuse into one stamp", func(t *testing.T) {
t.Parallel()
entries := make([]interface{}, 0, 150)
for r := 1; r <= 150; r++ {
entries = append(entries, map[string]interface{}{
"range": fmt.Sprintf("A%d:F%d", r, r), "font_weight": "bold",
})
}
ops, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{"name": "S1", "cell_styles": entries}},
}), testToken)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if len(ops) != 1 {
t.Fatalf("got %d ops, want 1 fused stamp", len(ops))
}
input := ops[0].(map[string]interface{})["input"].(map[string]interface{})
if input["range"] != "A1:F150" {
t.Fatalf("range = %v, want A1:F150", input["range"])
}
})
t.Run("different styles stay separate", func(t *testing.T) {
t.Parallel()
ops, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{"name": "S1", "cell_styles": []interface{}{
map[string]interface{}{"range": "A1:F1", "font_weight": "bold"},
map[string]interface{}{"range": "A2:F2", "background_color": "#EEEEEE"},
}}},
}), testToken)
if err != nil || len(ops) != 2 {
t.Fatalf("ops=%d err=%v, want 2", len(ops), err)
}
})
t.Run("horizontal fuse with same rows", func(t *testing.T) {
t.Parallel()
ops, err := stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{"name": "S1", "cell_styles": []interface{}{
map[string]interface{}{"range": "A1:C5", "font_weight": "bold"},
map[string]interface{}{"range": "D1:F5", "font_weight": "bold"},
}}},
}), testToken)
if err != nil || len(ops) != 1 {
t.Fatalf("ops=%d err=%v, want 1", len(ops), err)
}
input := ops[0].(map[string]interface{})["input"].(map[string]interface{})
if input["range"] != "A1:F5" {
t.Fatalf("range = %v, want A1:F5", input["range"])
}
})
}
// TestTypedCellsHabitualKeys pins the typed --cells cell-object fixes
// (recurring server-side 900015206 across 07-20/07-21 reruns).
func TestTypedCellsHabitualKeys(t *testing.T) {
t.Parallel()
t.Run("style object rewrites to cell_styles through batch", func(t *testing.T) {
t.Parallel()
translated, err := translateBatchOp(subOp("+cells-set", map[string]interface{}{
"sheet_name": "S1", "range": "A1",
"cells": []interface{}{[]interface{}{map[string]interface{}{
"value": "x", "style": map[string]interface{}{"font_weight": "bold"},
}}},
}), testToken, 0)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
input := translated["input"].(map[string]interface{})
cell := input["cells"].([]interface{})[0].([]interface{})[0].(map[string]interface{})
cs, _ := cell["cell_styles"].(map[string]interface{})
if cs == nil || cs["font_weight"] != "bold" {
t.Fatalf("cell = %v, want cell_styles.font_weight bold", cell)
}
if _, has := cell["style"]; has {
t.Fatalf("style key must be renamed, got %v", cell)
}
})
t.Run("type key gets a prescription", func(t *testing.T) {
t.Parallel()
_, err := translateBatchOp(subOp("+cells-set", map[string]interface{}{
"sheet_name": "S1", "range": "A1",
"cells": []interface{}{[]interface{}{map[string]interface{}{
"value": "x", "type": "text",
}}},
}), testToken, 0)
requireValidation(t, err, "not a cell field")
})
}
// TestStylesAcceptance_ResizeAndMergeCorpus extends the corpus to the
// row/col_sizes and cell_merges sections.
func TestStylesAcceptance_ResizeAndMergeCorpus(t *testing.T) {
t.Parallel()
runSection := func(section string, entry interface{}) ([]interface{}, error) {
return stylesPutOperations(stylesPutView(map[string]interface{}{
"styles": []interface{}{map[string]interface{}{
"name": "S1",
section: []interface{}{entry},
}},
}), testToken)
}
pixelValue := func(t *testing.T, ops []interface{}, key string) interface{} {
t.Helper()
input := ops[0].(map[string]interface{})["input"].(map[string]interface{})
block, _ := input[key].(map[string]interface{})
if block == nil || block["type"] != "pixel" {
t.Fatalf("%s = %v, want pixel block", key, input[key])
}
return block["value"]
}
t.Run("size alone implies pixel", func(t *testing.T) {
t.Parallel()
ops, err := runSection("row_sizes", map[string]interface{}{"range": "1:1", "size": float64(36)})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if v := pixelValue(t, ops, "resize_height"); v != 36 {
t.Fatalf("value = %v, want 36", v)
}
})
t.Run("width alone implies pixel on col_sizes", func(t *testing.T) {
t.Parallel()
ops, err := runSection("col_sizes", map[string]interface{}{"range": "A:C", "width": float64(120)})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if v := pixelValue(t, ops, "resize_width"); v != 120 {
t.Fatalf("value = %v, want 120", v)
}
})
t.Run("type auto still works on rows", func(t *testing.T) {
t.Parallel()
if _, err := runSection("row_sizes", map[string]interface{}{"range": "1:1", "type": "auto"}); err != nil {
t.Fatalf("unexpected error: %v", err)
}
})
t.Run("neither size nor type prescribed", func(t *testing.T) {
t.Parallel()
_, err := runSection("row_sizes", map[string]interface{}{"range": "1:1"})
requireValidation(t, err, "needs size (px) or type")
})
t.Run("wrong-dimension word prescribed", func(t *testing.T) {
t.Parallel()
_, err := runSection("col_sizes", map[string]interface{}{"range": "A:C", "height": float64(36)})
requireValidation(t, err, "does not apply")
})
t.Run("raw OpenAPI merge_type accepted", func(t *testing.T) {
t.Parallel()
ops, err := runSection("cell_merges", map[string]interface{}{"range": "A1:B2", "merge_type": "MERGE_ALL"})
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
input := ops[0].(map[string]interface{})["input"].(map[string]interface{})
if input["merge_type"] != "all" {
t.Fatalf("merge_type = %v, want all", input["merge_type"])
}
})
t.Run("bare string merge accepted", func(t *testing.T) {
t.Parallel()
if _, err := runSection("cell_merges", "A1:B2"); err != nil {
t.Fatalf("unexpected error: %v", err)
}
})
}

View File

@@ -0,0 +1,347 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT
package sheets
import (
"strings"
"testing"
)
// TestTablePut_StylesErrorsAggregate pins the one-retry contract for
// --styles: every issue across sections and ops is reported in a single
// error (eval V2U032 burned three round trips fixing a border side, then
// row_sizes.type, then size — each surfaced only after the previous fix).
func TestTablePut_StylesErrorsAggregate(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+table-put")
_, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheets", `{"sheets":[{"name":"s","columns":["a"],"data":[["x"]]}]}`,
"--styles", `{"styles":[{"name":"s",
"cell_styles":[{"range":"A1:A1","border_styles":{"horizontal":{"style":"solid"}}}],
"row_sizes":[{"range":"1:1","type":"custom"}],
"col_sizes":[{"range":"A:A","type":"pixel"}]}]}`,
"--dry-run",
})
ve := requireValidation(t, err, "--styles has 3 issues")
for _, want := range []string{
"border_styles.horizontal is not a valid side",
`row_sizes[0].type "custom" is invalid`,
"col_sizes[0].type pixel requires size",
} {
if !strings.Contains(ve.Message, want) {
t.Errorf("aggregated message should contain %q, got %q", want, ve.Message)
}
}
// D2: each type/size error inlines a complete valid op.
if !strings.Contains(ve.Message, `{"range":"2:10","type":"pixel","size":32}`) {
t.Errorf("row_sizes error should inline a full valid example, got %q", ve.Message)
}
if !strings.Contains(ve.Message, `{"range":"A:C","type":"pixel","size":120}`) {
t.Errorf("col_sizes error should inline a full valid example, got %q", ve.Message)
}
}
// TestTablePut_StylesFieldPrescriptions pins the curated fixes for the
// high-frequency unsupported cell_styles field names, and the near-typo
// guard on the did-you-mean fallback (07-28 root-cause report #14/#21/#27:
// font_bold used to draw "did you mean font_color?" and nested font drew
// "font_line" — concept-swap neighbors that mislead worse than silence).
func TestTablePut_StylesFieldPrescriptions(t *testing.T) {
t.Parallel()
cases := []struct {
name string
field string // JSON fragment inside the cell_styles item
want []string
notSuggest []string // must NOT appear as a did-you-mean
}{
{"bold", `"bold":true`, []string{`font_weight:"bold"`}, nil},
{"font_bold", `"font_bold":true`, []string{`font_weight:"bold"`}, []string{"font_color"}},
{"text_align", `"text_align":"center"`, []string{"horizontal_alignment"}, nil},
{"nested font", `"font":{"bold":true,"size":18}`, []string{"flat font_*", `font_weight:"bold"`}, []string{"font_line"}},
{"near-typo still suggests", `"font_colour":"#FFF"`, []string{`did you mean "font_color"`}, nil},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+table-put")
_, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheets", `{"sheets":[{"name":"s","columns":["a"],"data":[["x"]]}]}`,
"--styles", `{"styles":[{"name":"s","cell_styles":[{"range":"A1:A1",` + tc.field + `}]}]}`,
"--dry-run",
})
ve := requireValidation(t, err, "is not a supported style field")
for _, want := range tc.want {
if !strings.Contains(ve.Message, want) {
t.Errorf("message should contain %q, got %q", want, ve.Message)
}
}
for _, bad := range tc.notSuggest {
if strings.Contains(ve.Message, `did you mean "`+bad+`"`) {
t.Errorf("message must not suggest %q, got %q", bad, ve.Message)
}
}
})
}
}
// TestTablePut_StylesBorderAllExpands verifies the "all" shorthand is
// rewritten to four explicit sides instead of being rejected (or worse,
// passed through for the server to reject, as happened on the typed-cells
// path in eval V2U013/V2U021).
func TestTablePut_StylesBorderAllExpands(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+table-put")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheets", `{"sheets":[{"name":"s","columns":["a"],"data":[["x"]]}]}`,
"--styles", `{"styles":[{"name":"s","cell_styles":[{"range":"A1:A1","border_styles":{"all":{"style":"solid","weight":"thin"}}}]}]}`,
"--dry-run",
})
if err != nil {
t.Fatalf("border all should expand to four sides and pass, got: %v", err)
}
// table-put's dry-run body carries the tool input as an escaped JSON
// string, so match the escaped key form.
for _, side := range []string{`\"top\"`, `\"bottom\"`, `\"left\"`, `\"right\"`} {
if !strings.Contains(stdout, side) {
t.Errorf("dry-run body should carry expanded side %s, got %q", side, stdout)
}
}
if strings.Contains(stdout, `\"all\"`) {
t.Errorf("dry-run body must not carry the raw all shorthand, got %q", stdout)
}
}
// TestCellsSet_BorderAllAndMisNestedBorder covers the typed --cells path:
// the "all" shorthand expands CLI-side, and border_styles mis-nested inside
// cell_styles is intercepted with a move-it prescription instead of a
// server-side 900015206.
func TestCellsSet_BorderAllAndMisNestedBorder(t *testing.T) {
t.Parallel()
t.Run("border all expands", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cells-set")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1",
"--cells", `[[{"value":"x","border_styles":{"all":{"style":"solid"}}}]]`,
"--dry-run",
})
if err != nil {
t.Fatalf("border all should expand and pass, got: %v", err)
}
if strings.Contains(stdout, `"all"`) || !strings.Contains(stdout, `"top"`) {
t.Errorf("dry-run body should carry expanded sides, got %q", stdout)
}
})
t.Run("mis-nested border_styles intercepted", func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cells-set")
_, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1",
"--cells", `[[{"value":"x","cell_styles":{"font_weight":"bold","border_styles":{"top":{"style":"solid"}}}}]]`,
"--dry-run",
})
ve := requireValidation(t, err, "cell_styles.border_styles is not valid")
if !strings.Contains(ve.Message, "sibling of cell_styles") {
t.Errorf("message should prescribe moving it up one level, got %q", ve.Message)
}
})
}
// TestCellsSetStyle_BorderAllExpands covers the --border-styles flag path
// (+cells-set-style / +cells-batch-set-style go through borderStylesFromFlag,
// not the typed --cells or --styles walkers): the "all" shorthand must expand
// CLI-side here too, or the backend rejects {"all":…}.
func TestCellsSetStyle_BorderAllExpands(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cells-set-style")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1:A1",
"--border-styles", `{"all":{"style":"solid","weight":"thin"}}`,
"--dry-run",
})
if err != nil {
t.Fatalf("border all should expand to four sides and pass, got: %v", err)
}
for _, side := range []string{`"top"`, `"bottom"`, `"left"`, `"right"`} {
if !strings.Contains(stdout, side) {
t.Errorf("dry-run body should carry expanded side %s, got %q", side, stdout)
}
}
if strings.Contains(stdout, `"all"`) {
t.Errorf("dry-run body must not carry the raw all shorthand, got %q", stdout)
}
}
// TestCellsMerge_RawAPIVocabularyNormalizes pins MERGE_ALL → all (the raw
// OpenAPI enum agents copy from Lark API docs) via the enum alias table.
func TestCellsMerge_RawAPIVocabularyNormalizes(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cells-merge")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1:B2",
"--merge-type", "MERGE_ALL",
"--dry-run",
})
if err != nil {
t.Fatalf("MERGE_ALL should normalize to all and pass, got: %v", err)
}
if !strings.Contains(stdout, `"all"`) {
t.Errorf("dry-run body should carry the normalized merge type, got %q", stdout)
}
}
// TestCellsSetStyle_WordWrapBooleanNormalizes pins --word-wrap true →
// auto-wrap (eval V2U029).
func TestCellsSetStyle_WordWrapBooleanNormalizes(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cells-set-style")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1:A1",
"--word-wrap", "true",
"--dry-run",
})
if err != nil {
t.Fatalf("--word-wrap true should normalize to auto-wrap, got: %v", err)
}
if !strings.Contains(stdout, "auto-wrap") {
t.Errorf("dry-run body should carry auto-wrap, got %q", stdout)
}
}
// TestCellsSetStyle_WordWrapGoogleVocabularyNormalizes pins the Google
// Sheets wrapStrategy words (WRAP / CLIP) onto the Lark enum — the flag
// name --wrap-strategy already prescribes --word-wrap, so the value
// vocabulary has to land too or the retry fails a second time.
func TestCellsSetStyle_WordWrapGoogleVocabularyNormalizes(t *testing.T) {
t.Parallel()
for word, want := range map[string]string{"wrap": "auto-wrap", "WRAP": "auto-wrap", "clip": "word-clip"} {
t.Run(word, func(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cells-set-style")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1:A1",
"--word-wrap", word,
"--dry-run",
})
if err != nil {
t.Fatalf("--word-wrap %s should normalize to %s, got: %v", word, want, err)
}
if !strings.Contains(stdout, want) {
t.Errorf("dry-run body should carry %s, got %q", want, stdout)
}
})
}
}
// TestCellsSetStyle_BorderWeightNumberNamesEnum pins the enum-over-skeleton
// rule: a type mismatch on an enum-bearing field answers with the allowed
// values, not a whole-payload skeleton ({"bottom": {…}, "left": {…}, …}
// told the caller nothing about thin/medium/thick — 07-28 root-cause
// report #5, 75 occurrences).
func TestCellsSetStyle_BorderWeightNumberNamesEnum(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cells-set-style")
_, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet-name", "s",
"--range", "A1",
"--border-styles", `{"top":{"style":"solid","weight":1}}`,
"--dry-run",
})
ve := requireValidation(t, err, `expected type "string", got "number"`)
for _, want := range []string{`"thin"`, `"medium"`, `"thick"`} {
if !strings.Contains(ve.Message, want) {
t.Errorf("message should name the weight enum %s, got %q", want, ve.Message)
}
}
if strings.Contains(ve.Message, "expected shape:") {
t.Errorf("enum-bearing mismatch should not fall back to the shape skeleton, got %q", ve.Message)
}
}
// TestUnderscoreFlagFormsParse pins the wire-vocabulary underscore rewrite:
// --sheet_name / --border_styles parse as their hyphen forms (agents copy
// field names out of JSON payloads where underscores are canonical).
func TestUnderscoreFlagFormsParse(t *testing.T) {
t.Parallel()
sc := shortcutFromRegistry(t, "+cells-set-style")
stdout, _, err := runShortcutCapturingErr(t, sc, []string{
"--url", testURL,
"--sheet_name", "s",
"--range", "A1:A1",
"--font_weight", "bold",
"--dry-run",
})
if err != nil {
t.Fatalf("underscore flag forms should parse as hyphen forms, got: %v", err)
}
if !strings.Contains(stdout, "bold") {
t.Errorf("dry-run body should carry the style, got %q", stdout)
}
}
// TestPrintFlagSchema_UnderscoreFlagName pins --flag-name border_styles
// resolving the border-styles schema (eval V2U013 burned a retry on this).
func TestPrintFlagSchema_UnderscoreFlagName(t *testing.T) {
t.Parallel()
print := printFlagSchemaFor("+cells-set-style")
out, err := print("border_styles")
if err != nil {
t.Fatalf("underscore flag-name should resolve the hyphen schema, got: %v", err)
}
if len(out) == 0 {
t.Fatal("expected schema output")
}
}
// TestPrintFlagSchema_DottedPathSlices pins the schema sub-path slicing
// contract on the real embedded chart schema: a dotted --flag-name returns
// just that subtree, and a path miss lists the keys actually available.
func TestPrintFlagSchema_DottedPathSlices(t *testing.T) {
t.Parallel()
print := printFlagSchemaFor("+chart-create")
t.Run("slices a nested subtree", func(t *testing.T) {
t.Parallel()
out, err := print("properties.snapshot.plotArea.axes")
if err != nil {
t.Fatalf("dotted path should slice, got: %v", err)
}
full, err2 := print("properties")
if err2 != nil {
t.Fatalf("full dump: %v", err2)
}
if len(out) == 0 || len(out) >= len(full) {
t.Errorf("slice should be non-empty and smaller than the full schema (%d vs %d bytes)", len(out), len(full))
}
})
t.Run("path miss lists available keys", func(t *testing.T) {
t.Parallel()
_, err := print("properties.snapshot.nosuchkey")
if err == nil {
t.Fatal("expected error for unknown path segment")
}
if !strings.Contains(err.Error(), "available keys:") {
t.Errorf("error should list available keys, got %v", err)
}
})
}

View File

@@ -1,6 +1,6 @@
---
name: lark-sheets
version: 3.0.2
version: 3.1.1
description: "飞书电子表格:创建和操作电子表格。支持创建表格、管理工作表与行列结构(增删/合并/调整尺寸/隐藏/冻结)、读写单元格(值/公式/样式/批注/单元格图片)、查找替换、多操作原子批量更新,以及图表、透视表、条件格式、筛选器、迷你图、浮动图片等对象的创建与维护。当用户需要创建电子表格、管理工作表、批量读写或编辑数据、统计汇总与可视化、表格美化、公式计算(含 Excel 公式迁移)、金融/财务建模DCF、三张表、预算、Sensitivity 等)等任务时使用。若用户是想按名称或关键词搜索云空间(云盘/云存储)里的表格文件,请改用 lark-drive 的 drive +search 先定位资源。当用户给出 doubao.com 的 /sheets/ URL/token 时,也应直接使用本 skill不要因为域名不是飞书而回退到 WebFetch路由依据是 URL 路径模式和 token而不是域名。"
metadata:
requires:
@@ -15,13 +15,7 @@ metadata:
## 术语约定
下列词在本 skill 各文档中可能交替出现,但**指同一对象**;解析用户口语时按此映射,不要当成不同概念:
| 标准用语 | 同义 / 口语(均指同一对象) | 说明 |
| --- | --- | --- |
| 工作表sheet | 子表、tab、标签页 | spreadsheet 内的单张表;`sheet_id` 是其稳定标识 |
| 电子表格spreadsheet | 工作簿、表格 | 顶层容器;由 `--url``--spreadsheet-token` 定位 |
| reference_id | id | **表内对象**的稳定标识,即各对象主键 flag 接受的值(见下表)。⚠️ 与 `lark-sheets-float-image``--image-uri`(图片上传句柄)不是一回事,后者不属于 reference_id |
同一对象的交替说法,按此映射解析用户口语:**工作表sheet**= 子表 / tab / 标签页(`sheet_id` 是稳定标识);**电子表格spreadsheet**= 工作簿 / 表格(顶层容器,由 `--url``--spreadsheet-token` 定位);**reference_id** = 表内对象的稳定标识,即各对象主键 flag 接受的值(与 `--image-uri` 图片上传句柄不是一回事)。
每类对象用各自的主键 flag 定位(命名不统一,按此表对照,不要凭直觉拼):
@@ -34,32 +28,33 @@ metadata:
## 飞书表格编辑准则(动手前必守,所有编辑类任务一律生效)
下列准则横切所有飞书表格任务,**动手前先过一遍**——即使你是被索引直接路由进某个工具参考也一律生效。每条只给一句话纲要,展开与边界见括注的 reference。
下列准则横切所有任务,**动手前先过一遍**——被索引直接路由进某个工具参考也一律生效展开与边界见括注的 reference。
1. **最小改动**:除任务要改的单元格 / 列外原表其它单元格、行列结构、Sheet 名、合并区、格式 1:1 保持;中间结果放原数据右侧或新建空白 Sheet**禁止删 / 改名 / 隐藏 / 移动已存在 Sheet**;改写类任务精确圈定行列,不该转的原值 1:1 保留。
2. **真实写回 + 回读校验**:交付必须是对在线表格的真实写入,写完用 `+csv-get` / `+cells-get` / `+<对象>-list` 回读确认实际生效——**写操作返回 `ok` 只代表请求被接受、不代表结果符合预期**;写公式后查错误码、筛选 / 排序后核对前几行、删除 / 清空后确认已空。禁止只在文本里声称"已完成"。
3. **读全再写**:批量填充 / 补齐 / 修正类任务先确认真实数据末行再写,只探前 N 行会漏写表尾(确定末行流程见 `lark-sheets-read-data`)。
4. **公式优先于硬编码**:能用公式表达的计算(总计 / 占比 / 增长率 / 提取 / 查找)一律写公式而非静态值**凡可由表内其它单元格推导的派生值默认用公式,即使用户没说"联动 / 自动更新"**;写任何飞书公式前先读 `lark-sheets-formula-translation`而且**只要公式真实写入表格,收尾默认就要继续跑 `lark-sheets-formula-verify``+formula-verify`直到 `status='success'`**。
4. **公式优先于硬编码**:能用公式表达的计算(总计 / 占比 / 提取 / 查找)一律写公式而非静态值——**凡可由表内其它单元格推导的派生值默认用公式,即使用户没说"联动"**;写公式前先读 `lark-sheets-formula-translation`**公式落表后收尾必跑 `+formula-verify` 直到 `status='success'`**。
5. **续写 / 扩展继承样式**:续写、补齐、复制区块、新增行列时禁止只读值只写值,必须连带 `cell_styles` + `border_styles` + 合并 + 行高一起继承(清单见 `lark-sheets-write-cells`,四边框最易漏)。
6. **多步写入合并 `+batch-update`**:多个连续写入、或同一工具对多区域重复调用,合并为单次原子 `+batch-update`语义见 `lark-sheets-batch-update`)。
6. **多步写入分流**:美化收尾(样式 / 合并 / 行高列宽 / 冻结的任意组合)→ 一次 `+styles-put` 声明式规格交付(见 `lark-sheets-styles-put`**同一个写操作**打多个区域 → 用该命令自身的复数形态(`--ranges` / map 入参);只有**跨类型的原子操作链**(如插列 → 写表头 → 回填数据)才用 `+batch-update`high-risk-write**调用必带 `--yes`**fail-fast 不回滚;语义见 `lark-sheets-batch-update`)。
7. **分组汇总用透视表**"按 X 统计 Y / 分组汇总 / 各类数量金额"用 `+pivot-{create|update|delete}`,禁止用 SUMIF / 本地脚本拼一张假透视表。
8. **拆成可验证 checklist**:落地前把指令拆成所有"独立可验证子要点",逐点 `assert` 全过才交付(多维排序每维一点、多目标每目标一点、范围类核起 / 末 / 边界);只做第一个要点属违规。
9. **全量处理前置断言条数**:翻译 / 打标 / 批量公式落地等逐条任务,先把预期条数硬编码再 `assert actual == expected`,禁止输出"已完成前 N 条,剩余继续"的半成品。
10. **缺失值不编造**:补齐 / 扩展 / 按原表格式续填时,查不到或无法确定的值一律留空 + 备注注明("暂未发布 / 未知 / 待核实"),禁止用推算值 / 估算值 / 凭空数据充数;原表若已示范缺失值写法(空值 + 备注),照抄该约定。宁可留空标注,不填不可靠的数。
> 上述准则的实操展开——读取路径、原生工具优先级、脚本配合、易漏陷阱——见下方「执行要点」节;端到端工作流:了解结构(`+workbook-info`)→ 读数据 → 理解语义 → 原生工具优先 → 写入 → 回读验证。
> 端到端工作流:了解结构(`scripts/lark_inspect_workbook.py` / `+workbook-info`)→ 读数据 → 理解语义 → 原生工具优先 → 写入 → 回读验证;实操展开见下方「执行要点」
## 场景 → 命令速查(拿不准命令名先查这里,别按直觉拼)
把高频意图映射到**真实存在**的 shortcut / flagagent 常从 Excel / Google Sheets / 飞书 OpenAPI 误迁移命令名或 flag先对照本表避免一次必然失败的试错。完整 shortcut 见各工具参考。**选定命令后别急着写——先读「动手前读」列指向的 reference 再动手**命令名对得上不代表用法对,写入 / 清除 / 透视类尤其容易漏掉 reference 里的防错、类型与样式继承规则
把高频意图映射到**真实存在**的 shortcut / flagagent 常从 Excel / Google Sheets / OpenAPI 误迁移命令名。**选定命令后先读「动手前读」列指向的 reference 再动手**——命令名对得上不代表用法对。
| 你要做的事 | ✅ 正确写法 | 动手前读 | ❌ 不存在(会被 cobra 拒) |
| --- | --- | --- | --- |
| 读数据(纯值 / CSV | `+csv-get`范围用 `--range` | `lark-sheets-read-data` | `+get-range``+range-get``+cells-read` |
| 读数据(纯值 / CSV | `+csv-get``--range` 可省略 = 读整个子表,无需先探行列;限定范围才传 | `lark-sheets-read-data` | `+get-range``+range-get``+cells-read` |
| 读值 + 公式 / 样式 / 批注 | `+cells-get --include value,formula,style,comment,data_validation` | `lark-sheets-read-data` | `+get-cell``+cell-get``--with-styles``--with-merges``--include-merged-cells` |
| 写纯文本值(整块 CSV 平铺;列里**没有**需字面保真的数值 / 日期标签 / 编号——点分日期 `12.10`、编号 `001` 会被 csv-put 数值化,不算纯文本 | `+csv-put`(定位用 `--start-cell`,单个左上角锚点格也接受 `--range` 别名,区间自动取左上角 | `lark-sheets-write-cells` | 把含点分日期(`12.10`)/编号(`001`)的列裸灌 `+csv-put`——会被数值化(`12.10``12.1``001``1`,尾零/前导零丢失),改用 `+table-put` 声明 `dtypes:object` |
| 写带类型的数据到**已有**表(列里有数字 / 金额 / 百分比 / 日期 / 计数等**本质是量值**的数据——不看当下要不要排序 / 求和,量值一律走这里) | `+table-put --sheets` 完整 payload `{"sheets":[{...}]}`(列名走 `columns`、二维数据走 `data`、列 pandas dtype 走 `dtypes`、列展示格式走 `formats`;来源不限 DataFrame——Counter / dict / list 同理;要同时美化加 `--styles` 一步带样式(区域底色 / 边框 / 列宽 / 行高 / 合并不必事后再刷payload 里不存在的 sheet 名会自动建子表,详见 write-cells | `lark-sheets-write-cells` | 在本地把数字拼成 `"$1,234"` / `"30.5%"` 字符串再 `+csv-put`落成文本、丢计算能力;常见借口见下方 ⚠️) |
| 写纯文本值(整块 CSV 平铺;列里没有需字面保真的编号 / 点分日期 | `+csv-put`(定位用 `--start-cell` 左上角锚点格也接受 `--range` 别名) | `lark-sheets-write-cells` | 把含点分日期(`12.10`)/编号(`001`)的列裸灌 `+csv-put`——会被数值化(`12.10``12.1``001``1`),改用 `+table-put` 声明 `dtypes:object` |
| 写带类型的数据到**已有**表(列里有数字 / 金额 / 百分比 / 日期等**量值**——不看当下要不要排序求和,量值一律走这里) | `+table-put --sheets '{"sheets":[{"name":…,"columns":[…],"dtypes":{…},"formats":{…},"data":[[…]]}]}'`(不存在的 sheet 名自动建子表;同时美化加 `--styles` 一步带样式,详见 write-cells | `lark-sheets-write-cells` | 在本地把数字拼成 `"$1,234"` / `"30.5%"` 字符串再 `+csv-put`(落成文本、丢计算能力见下方 ⚠️) |
| **新建**电子表格并写带类型的数据(类型保真需求同上,但目标表还不存在) | `+workbook-create --sheets`(协议与 `+table-put` 同构、一步建表 + typed 写入,无需先建空表再 `+table-put`date / number 不丢;`--styles` 同样可在建表同一步带全套样式,详见 workbook | `lark-sheets-workbook` | 用 `--values` 灌日期 / 数字(会落成文本、丢类型) |
| 写公式 / 富写入(样式 · 批注 · 图片 · 富文本),或需精确矩形定位的值 | `+cells-set`定位用 `--range`;批注 / 图片 / 富文本只能用它,公式也可;**公式落表后继续 `+formula-verify` 收尾** | `lark-sheets-write-cells` | — |
| 写公式 / 富写入(样式 · 批注 · 图片 · 富文本),或需精确矩形定位的值 | `+cells-set`单区域 `--range`+`--cells`**散布多处 / 跨表用 `--writes` 一次原子交付**,每项自带 sheet_name公式落表后继续 `+formula-verify` 收尾) | `lark-sheets-write-cells` | — |
| 插图:图片**绑定到某条记录**、随行走(凭证 / 证件照 / 商品图 / 头像 / 二维码 / 每行配图) | `+cells-set-image`(单格 `--range`,嵌入单元格内) | `lark-sheets-write-cells` | — |
| 插图:**自由摆放、不绑数据**的装饰 / 标识logo / 水印 / 封面大图 / banner | `+float-image-create`(浮动图片,自由定位 + 尺寸 + 层级) | `lark-sheets-float-image` | — |
| 查找 / 替换文本 | `+cells-search`(找,关键字用 `--find`)、`+cells-replace`(替换) | `lark-sheets-search-replace` | `+cells-find``+find``--query` |
@@ -68,37 +63,53 @@ metadata:
| 复核某次AI编辑改了什么 / 取两个版本间的变更 | `+changeset-get --start-revision <编辑前版本>`(省略 `--end-revision` 取到最新;版本差 ≤ 20 | `lark-sheets-changeset` | — |
| 取当前文档 revision版本号 | `+revision-get` | `lark-sheets-workbook` | — |
| 导出 xlsx / 单表 csv | `+workbook-export` | `lark-sheets-workbook` | — |
| 导入本地 xlsx/xls/csv 文件为飞书电子表格 | `+workbook-import --file ./x.xlsx`本地表格文件 → 飞书电子表格的正解;仅要导成多维表格 bitable 时才用 `drive +import --type bitable` | `lark-sheets-workbook` | `drive +import`导电子表格时绕了 drive 通道、还要多给 `--type`,应直接用 `+workbook-import`)、把 .xlsx 在本地读成数据再 `+workbook-create` 重灌(多此一举,应直接 `+workbook-import`)、要把文件并入某个**已有在线工作簿**(给它加子表)却用它——import 只会新建独立表,加子表`+sheet-copy` / `+sheet-create` |
| 参考某个**已有在线表**、把多个本地文件 / 数据各作为一张子表**追加**进去(不另起独立表) | 先 `+workbook-info` 拿模板子表 `sheet_id``+sheet-copy` 逐张复制模板子表(公式 / 合并 / 分组底色 / 列宽 / 条件格式全继承)再 `+cells-*` 只改数据;无模板可继承时 `+sheet-create` 建空子表 + `+table-put --sheets/--styles` 写入 | `lark-sheets-workbook` | 把文件 `+workbook-import` / `+workbook-create` 另起一张**独立新表**(目标是并入已有工作簿时就跑偏了;这两条只产新表、不接受已有表定位) |
| 清除内容 / 格式 | `+cells-clear`(范围维度用 `--scope`,取值 content / formats / all | `lark-sheets-range-operations` | `--type` |
| 批量清除多区域 | `+cells-batch-clear``--scope` | `lark-sheets-batch-update` | `--target` |
| 调整列宽 / 行高 | `+cols-resize` / `+rows-resize`(行、列是两个独立命令) | `lark-sheets-range-operations` | `--dimension`(无此 flag |
| 导入本地 xlsx/xls/csv 文件为飞书电子表格 | `+workbook-import --file ./x.xlsx`(仅要导成多维表格 bitable 时才用 `drive +import --type bitable` | `lark-sheets-workbook` | `drive +import`绕路)、本地读 .xlsx 再 `+workbook-create` 重灌(多此一举)、想并入**已有工作簿**却用它import 只会另起新表,加子表走 `+sheet-copy` / `+sheet-create` |
| 参考某个**已有在线表**、把多数据各作为一张子表**追加**进去 | 先 `+workbook-info``+sheet-copy` 复制模板子表(公式 / 合并 / 底色 / 列宽全继承)再 `+cells-*` 只改数据;无模板可继承时 `+sheet-create` + `+table-put --sheets/--styles` | `lark-sheets-workbook` | `+workbook-import` / `+workbook-create` 另起独立新表(这两条只产新表、不接受已有表定位) |
| **已有**表美化收尾(样式 / 边框 / 合并 / 行高列宽 / 冻结的任意组合,单表或多表) | `+styles-put --styles '{"styles":[{"name":…,"cell_styles":[…],"cell_merges":[…],"row_sizes":[…],"col_sizes":[…],"freeze":{…}}]}'`(一份规格一次原子交付,词汇同 `+table-put --styles` | `lark-sheets-styles-put` | 拼 `+batch-update``--operations` 子操作数组做美化、逐区域多次 `+cells-set-style` |
| 清除内容 / 格式 | `+cells-clear --yes`(需确认;范围维度用 `--scope`,取值 content / formats / all | `lark-sheets-range-operations` | `--type` |
| 批量清除多区域 | `+cells-batch-clear --yes`(需确认;`--scope` | `lark-sheets-batch-update` | `--target` |
| 调整列宽 / 行高 | `+cols-resize` / `+rows-resize`(行、列是两个独立命令;连同样式一起调时并入 `+styles-put``row_sizes` / `col_sizes` | `lark-sheets-range-operations` | `--dimension`(无此 flag |
| 分组汇总 / 透视 | `+pivot-create`(默认不传落点 flag → 自动新建子表,零覆盖) | `lark-sheets-pivot-table` | 用 SUMIF / 本地脚本拼一张假透视表 |
| 画图表 / 可视化(柱 / 折线 / 饼 / 条 / 散点 / 组合…) | `+chart-create` | `lark-sheets-chart` | matplotlib / 本地画图再贴图(原生图表可交互、随数据更新) |
| 画图表 / 可视化(柱 / 折线 / 饼 / 条 / 散点 / 组合…) | 先读 `lark-sheets-chart`;普通图用 `+chart-create-basic`,多图用扁平输入的 `+batch-chart-create`,已有图的数据源用 `+chart-data-update`、常用配置用 `+chart-config-update`;只有单系列 / 单数据点 / 高级引擎字段才用完整 `+chart-create` / `+chart-update` snapshot | `lark-sheets-chart` | matplotlib / 本地画图再贴图(原生图表可交互、随数据更新) |
| 条件高亮 / 数据条 / 色阶 / 重复值标记 | `+cond-format-create` | `lark-sheets-conditional-format` | `+highlight``+conditional-format`、逐格 `+cells-set-style` 硬凑 |
| 筛选 / 只看符合条件的行 | `+filter-create` | `lark-sheets-filter` | pandas filter 后覆盖写回(会毁原数据;要保存多份筛选状态用 `+filter-view-create` |
> ⚠️ **动手前的触发式必读(按动作判定,不看主场景)**本次操作只要**涉及样式 / 美化**(底色 / 边框 / 字号 / 对齐 / 数字格式 / 汇总行 / 配色 / 列宽行高),动手前先读 `lark-sheets-visual-standards`只要**要写飞书公式**,动手前先读 `lark-sheets-formula-translation`(飞书函数与 Excel 有差异,凭直觉迁移易错),**写完后再读 `lark-sheets-formula-verify` 并执行 `+formula-verify` 收尾**。哪怕主任务是"建表 / 展开数据 / 录入",只要动作里含美化或写公式就适用——别因"这不算专门的美化 / 公式任务"而跳过
> ⚠️ **两种图片别选错**:图**绑定某条记录、随行排序 / 筛选 / 增删**(凭证 / 证件照 / 每行配图,话里带「对应 / 每行 / 这列」等绑定词)→ 单元格图片 `+cells-set-image`只是自由摆放的装饰logo / 水印 / 封面)→ 浮动图片 `+float-image-create`。别因「浮动图更好控制 / 更熟」默认选浮动图。
> ⚠️ **纯文本还是数值语义(看数据本质,不看当下用途)**:金额 / 百分比 / 比率 / 计数 / 日期等**本质是量值**的数据 → 一律数值写入常规二维表用 `+table-put``dtypes` 声明类型 + `formats` 设展示格式),版式装不下(多级 / 合并表头的宽表 leaderboard 等)改用 `+cells-set` 传数字(百分比传小数 `0.4`+ `number_format`,照样显示 `40%` 且数值无损。只有编号 / 身份证 / 单据号这类**本质是标识符**、要字面保真的才用 `+csv-put` 平铺。**几个常见借口都不成立**——"只是 leaderboard / 报表展示不用算""版式复杂""样式以后再刷、先铺文本"都不是把百分比写成 `"40%"` 字符串灌 `+csv-put` 的理由(展示不改变它是数值;类型不能后补,落成文本就回不来)。判据与操作展开见 `lark-sheets-write-cells`「数字还是文本」。
> ⚠️ **要新建子表 / 整表美化 → 别默认「`+csv-put` 写值再事后刷样式」**`+table-put` / `+workbook-create` 的 `--styles` 在写数据**同一步**带全套样式(区域底色 / 边框 / 列宽 / 行高 / 合并),且 `+table-put` 的 payload 里 sheet 名不在工作簿中会自动建子表——**纯文本表要新建子表 + 美化时同样走这里**`--styles` 与列是否 typed 无关),比「`+csv-put` 写值 + 多次 `+cells-batch-set-style` / `+*-resize` 刷样式」少好几次调用(冻结行列等 sheet 级属性仍需 `+dim-freeze` 单独一步)。
> ⚠️ **定位 flag**`+cells-get` / `+cells-set` / `+csv-get` 用 `--range``+csv-put` 规范用 `--start-cell`单个左上角锚点格),也接受 `--range` 别名区间自动取左上角),二者择一即可
> ⚠️ **读取附加信息**一律走 `+cells-get --include …`**没有** `--with-styles` 这类 flag**看合并单元格**用 `+sheet-info` 的 `merged_cells`,不要在 `+cells-get` 里找 merge flag
> ⚠️ **动手前的触发式必读(按动作判定,不看主场景)**动作里**含样式 / 美化**(底色 / 边框 / 字号 / 对齐 / 数字格式 / 配色 / 列宽行高)先读 `lark-sheets-visual-standards`**要写飞书公式**先读 `lark-sheets-formula-translation`,写完跑 `+formula-verify` 收尾(见 `lark-sheets-formula-verify`)。主任务是建表 / 录入也一样适用
> ⚠️ **两种图片别选错**:图**绑定某条记录、随行**(凭证 / 证件照 / 每行配图)→ `+cells-set-image`自由摆放的装饰logo / 水印 / 封面)→ `+float-image-create`。别因「浮动图更熟」默认选浮动图。
> ⚠️ **纯文本还是数值语义(看数据本质,不看当下用途)**:金额 / 百分比 / 日期 / 计数等**量值**一律数值写入——常规二维表用 `+table-put``dtypes` + `formats`),宽表 / 合并表头版式用 `+cells-set` 传数字(百分比传小数 `0.4`+ `number_format`。只有编号 / 身份证等**标识符**才 `+csv-put` 平铺。"只是展示不用算 / 样式以后再刷"不构成把量值写成字符串的理由——类型不能后补。判据见 `lark-sheets-write-cells`「数字还是文本」。
> ⚠️ **要新建子表 / 整表美化 → 别「`+csv-put` 写值再事后刷样式」**`+table-put` / `+workbook-create` 的 `--styles` 在写数据**同一步**带全套样式(底色 / 边框 / 列宽行高 / 合并 / 冻结payload 里不存在的 sheet 名自动建子表,纯文本表同样适用;比事后多次刷样式少好几次调用。存量表事后美化则一次 `+styles-put` 交付(同一份 `--styles` 词汇)。
> ⚠️ **定位 flag**`+cells-get` / `+cells-set` / `+csv-get` 用 `--range``+csv-put` 用 `--start-cell`(也接受 `--range` 别名区间取左上角)。
> ⚠️ **读取附加信息**一律走 `+cells-get --include …`(无 `--with-styles` 这类 flag**看合并单元格**用 `+sheet-info` 的 `merged_cells`。
💡 **高频写命令签名(照抄改参即可;各命令 `--help` 的 Tips 段有同款示例)**
```bash
lark-cli sheets +cells-set --url <U> --sheet-name S1 --range A1:B1 --cells '[[{"value":"名称"},{"formula":"=SUM(B2:B9)"}]]' # --cells 恒为二维数组 [[…]],单格也是 [[{…}]]
lark-cli sheets +cells-set-style --url <U> --sheet-name S1 --range A1:D1 --font-weight bold --background-color "#F0F0F0" --horizontal-alignment center
lark-cli sheets +styles-put --url <U> --styles - <<'JSON'
{"styles":[{"name":"S1","cell_styles":[{"range":"A1:D1","font_weight":"bold","background_color":"#F0F0F0"}],"col_sizes":[{"range":"A:D","type":"pixel","size":120}],"freeze":{"rows":1}}]}
JSON
lark-cli sheets +batch-update --url <U> --yes --operations - <<'JSON'
[{"shortcut":"+cells-set","input":{"sheet_name":"S1","range":"A1","cells":[[{"value":"x"}]]}}]
JSON
lark-cli sheets +dim-freeze --url <U> --sheet-name S1 --dimension row --count 2
lark-cli sheets +dim-insert --url <U> --sheet-name S1 --position 3 --count 2 --inherit-style before # 行/列由 --position 决定:数字=行、字母=列,无 --dimension
lark-cli sheets +cols-resize --url <U> --sheet-name S1 --range A:C --width 120 # 像素;分列不同宽用 --widths '{"A":80,"C:E":120}'
lark-cli sheets +sheet-copy --url <U> --sheet-name 源表名 --title 副本名 # --sheet-name=源表、--title=新表名
```
## 执行要点(读取 / 原生工具 / 陷阱)
准则的实操展开。端到端工作流:了解结构 → 读数据 → 理解语义 → 原生工具优先 → 写入 → 回读验证。
### 读取:按需求选路径(细则见 `lark-sheets-read-data`
| 用户需求 | 读取路径 |
|---|---|
| "完善 / 补齐 / 填空 / 修正所有 XX"、分析 / 清洗 / 大数据 | 原生优先(公式 / `+pivot` / `+filter`);表达不了再分批 `+csv-get` 导出 + 脚本处理 + 分批回写(默认覆盖所有对应数据行,不以用户选区为准 |
| "查一下 / 看看 / 统计 / 汇总"等只读 | `+csv-get` 读到上下文 |
| "完善 / 补齐 / 修正所有 XX"、分析 / 清洗 / 大数据 | `scripts/lark_profile_table.py` 确认目标区域与字段画像,再原生优先(公式 / `+pivot` / `+filter`);表达不了再分批 `+csv-get` 导出 + 脚本处理 + 分批回写(默认覆盖所有对应数据行) |
| "查一下 / 统计 / 汇总"等只读 | 小表 `+csv-get` 读到上下文;大表先 `+workbook-info` + 小窗口 `+csv-get` 定边界,再对未截断窗口跑 `scripts/lark_detect_subtables.py` / `scripts/lark_profile_table.py` |
| 需要公式 / 样式 / 批注 | `+cells-get` |
| 续写 / 扩展已有内容 | `+csv-get` 看结构 + `+cells-get` 读源区样式 + `+sheet-info --include row_heights,merges`(见准则 5 |
> "补齐 / 填空"类用只读路径探 10 行就写会漏写表尾——写入前先按 `lark-sheets-read-data` 确认真实数据末行(准则 3
> "补齐 / 填空"类只探前 10 行就写会漏写表尾——先按 `lark-sheets-read-data` 确认真实数据末行(准则 3
### 计算:原生工具优先,代码兜底(强化准则 7
@@ -116,22 +127,23 @@ metadata:
### 用脚本配合 CLI 时
- **只读 stdout**CLI 数据走 stdout、诊断走 stderr解析 JSON 别 `2>&1`(警告混入会解析失败),用管道或单独重定向 stdout。
- **读表理解优先用 `scripts/lark_*.py`**`lark_inspect_workbook.py` / `lark_detect_subtables.py` / `lark_profile_table.py` 是只读脚本,用来把在线表格整理成结构摘要。它们不替代写入类 shortcut确认目标区域后写入仍按对应 reference 执行。
- **喂 CLI 的 CSV / JSON 用 UTF-8 无 BOM**;临时文件放系统临时目录、勿落项目目录。
- **命令失败先读 stderr 再调整**,别原样重发。
- **回写纯单元格值**:剥离 `值(V-Align: bottom)` 这类"值(样式)"串与残留引号再写;排序优先 `+range-sort` 原生工具,别"读出本地排完再整列写回"。
### 易漏陷阱
- **`+dim-insert` 不继承行高**:只继承值 / 公式 / 边框,新行回落默认高度截断长文本;插行填长文本前读相邻行 `row_height`,用 `+batch-update``+rows-resize` 补齐。
- **公式容错**:日期 / 查找 / 数值转换公式用 `IFERROR` 包裹;写完读结果列首末各 5 行`#VALUE!` / `#REF!` / `#DIV/0!`,然后继续`+formula-verify` `status='success'`;同一方案试错上限 3 次。
- **`+dim-insert` 不继承行高**:只继承值 / 公式 / 边框;插行填长文本前读相邻行 `row_height`,用 `+batch-update``+rows-resize` 补齐。
- **公式容错**:日期 / 查找 / 转换公式用 `IFERROR` 包裹;写完首末各 5 行错误码,再`+formula-verify``status='success'`;同一方案试错上限 3 次。
- **循环引用**:聚合公式引用范围不能含目标 cell 自身或其传递依赖。
- **隐藏行列**`+csv-get` 默认含隐藏行列;`--skip-hidden=true` 只看可见,但返回行序号与实际行号不再对应
- **跨 sheet 对象**:图表 / 条件格式 / 透视表 / 浮动图片可能分布在多个子表,操作前`+workbook-info` 掌握全局。
- **NLP 任务分批**:语义理解 / 翻译 / 改写 / 分类等用 NLP 处理(代码只做分批 / 行号映射 / 写回);数据量大必须分批(通常 30 行 / 批),每批处理完即时写回,单批生成通常 ≤ 300 行,多批用 `+batch-update`
- **隐藏行列**`+csv-get` 默认含隐藏行列;`--skip-hidden=true` 只看可见,真实行号会跳空——禁止按返回数组下标推导行号,用 `annotated_csv``[row=N]``row_indices`
- **跨 sheet 对象**:图表 / 条件格式 / 透视表 / 浮动图片可能分布在多个子表,先 `+workbook-info` 掌握全局。
- **NLP 任务分批**:语义理解 / 翻译 / 打标用 NLP 处理(代码只做分批 / 行号映射 / 写回);数据量分批( 30 行 / 批)即时写回,多批用 `+batch-update`
## References
本 skill 的 reference 分两组:先读**通用方法与规范**(横切所有任务的样式公式规则,不含具体 shortcut它们规定了"怎么做对"再按操作对象进入**工具参考**查具体 shortcut 与调用细节。编辑类任务务必先过一遍通用方法与规范,连同上方「飞书表格编辑准则」对所有工具参考一律生效。
reference 分两组:先读**通用方法与规范**(横切所有任务的样式 / 公式规则,再按操作对象进入**工具参考**查具体 shortcut。编辑类任务务必先过通用方法与规范连同上方「飞书表格编辑准则」对所有工具参考一律生效。
### 通用方法与规范(先读,横切所有任务,不含具体 shortcut
@@ -151,6 +163,7 @@ metadata:
| [Lark Sheet Search & Replace](references/lark-sheets-search-replace.md) | 在飞书表格中搜索和替换文本,支持限定范围、大小写匹配、精确匹配、正则表达式。当用户需要"查找"、"搜索"、"定位"某个值,或"替换"、"批量修改文本"、"把 A 改成 B"时使用。不要用于理解表格结构(应读取数据)、不要用于数据分析(应读取数据后计算)、不要把用户操作动作中的关键词(如"汇总金额""统计数量")当作搜索词。 |
| [Lark Sheet Write Cells](references/lark-sheets-write-cells.md) | 向飞书表格的指定区域批量写入值、公式、样式、批注或单元格图片。适用场景:填写数据、设置公式、修改格式、添加批注、嵌入单元格图片(如需操作浮动图片,请使用 lark-sheets-float-image若只需把一块 CSV 批量铺到表格上(值或公式,不带样式/批注),直接使用 `+csv-put` 更短更快。追加数据需先通过 lark-sheets-sheet-structure 插入行列。只要这次写入真实落了公式,收尾默认继续执行 `lark-sheets-formula-verify`。 |
| [Lark Sheet Range Operations](references/lark-sheets-range-operations.md) | 对飞书表格中指定区域执行结构性操作(不涉及写入单元格数据值)。适用场景:清除内容或格式("清空"、"删除内容"、"去掉格式")、合并/取消合并单元格、调整行高列宽("加宽列"、"自适应列宽")、移动/复制/填充/排序数据("移动数据"、"复制到"、"自动填充"、"按某列排序")。写入单元格数据请使用 lark-sheets-write-cells。 |
| [Lark Sheet Styles Put](references/lark-sheets-styles-put.md) | 把一份声明式视觉规格(样式/边框/合并/行高列宽/冻结)一次性应用到已有飞书表格的多个子表,整份规格原子提交。当任务是对存量表做美化收尾、批量刷样式、统一版式时使用。样式取值标准见 lark-sheets-visual-standards建新表带样式走 lark-sheets-workbook+workbook-create --styles、写数据同步带样式走 lark-sheets-write-cells+table-put --styles三者共用同一份 --styles 词汇。仅针对飞书表格。 |
| [Lark Sheet Batch Update](references/lark-sheets-batch-update.md) | 将多个飞书表格写入操作合并为一次批量执行,按顺序依次完成。适合需要连续执行多个写入操作的场景(如先修改结构再写入数据)。 |
| [Lark Sheet Chart](references/lark-sheets-chart.md) | 管理飞书表格中的图表(柱形图、折线图、饼图、条形图、面积图、散点图、组合图、雷达图等)。当用户需要创建图表、修改图表样式或数据源、查看已有图表配置、删除图表时使用。也适用于用户提到"数据可视化"、"画个图"、"趋势分析"、"对比图"、"占比分析"、"做个图表"等数据可视化相关场景。 |
| [Lark Sheet Pivot Table](references/lark-sheets-pivot-table.md) | 管理飞书表格中的数据透视表。当用户需要创建透视表、修改透视表的行列字段/聚合方式/筛选条件、查看已有透视表配置、删除透视表时使用。也适用于用户提到"分组汇总"、"交叉分析"、"按XXX统计"、"按字段分组"、"再分下组"、"多维分析"、"数据透视"等场景。 |
@@ -164,42 +177,22 @@ metadata:
## 公共 flag 速查
各 reference 的每个 shortcut 标题下用一行徽章标注该 shortcut 支持的公共 / 系统 flag,例如
- `_公共四件套 · 系统:--dry-run_` — URL/token + sheet 定位(两组各**必给一个**,详见下方「公共 flag」`--dry-run`
- `_公共URL/token无 sheet 定位) · 系统:--yes、--dry-run_` — 只接 URL/token常见于 `+batch-update` 等不强制 sheet 定位的 shortcut
徽章里只列名字。type / 必填 / 描述都在本段统一声明:
各 reference 的 shortcut 标题下用一行徽章标注支持的公共 / 系统 flag(如 `_公共四件套 · 系统:--dry-run_``_公共URL/token无 sheet 定位…_` 表示只接 URL/token。type / 必填 / 描述在本段统一声明
### 公共 flag定位资源
**公共四件套** = `--url` / `--spreadsheet-token` / `--sheet-id` / `--sheet-name`,分成两组 XOR**每组都必须给且只能给一个**XOR = 二选一必填,不是"可选"
1. **spreadsheet 定位(必填)**`--url` `--spreadsheet-token` 二选一**必须给其中之一**。两个都不给 → 校验报错 `specify at least one of --url or --spreadsheet-token`;两个都给 → 互斥冲突
- **`--url` 解析 `/sheets/``/spreadsheets/``/wiki/` 三种链接**(从路径里抽出 token也可以直接把裸 token 传给 `--spreadsheet-token`)。其它形态的链接不会被解析成表格 token
- **`/wiki/` 知识库链接可直接传 `--url`**:会自动定位到链接背后的电子表格;若该链接背后不是电子表格(而是文档 / 多维表格等),则报错
- **例外**`+workbook-create`(新建表 + 可选写入数据)与 `+workbook-import`(把本地文件导入为新表)都产出一张**还不存在**的表格,**不接受任何 spreadsheet / sheet 定位 flag**——`+workbook-create` 只有 `--title` / `--folder-token` / `--values` / `--styles` / `--sheets``+workbook-import` 只有 `--file`(必填)/ `--folder-token` / `--name`
2. **sheet 定位(公共四件套 shortcut 必填)**`--sheet-id``--sheet-name` 二选一,**必须给其中之一**。两个都不给 → 校验报错 `specify at least one of --sheet-id or --sheet-name`
- ⚠️ **不确定 sheet 名时禁止直接猜 `Sheet1`**:除非用户对话明确说出 sheet 名 / id或上下文之前的工具调用 / URL 锚点 `?sheet=xxx`)已经出现过具体值,否则**第一步先调 `+workbook-info --url "..."`**(或 `--spreadsheet-token`)拿 `sheets[].sheet_id` / `sheets[].title` 列表再选。中文环境下子表常叫"数据" / "Sheet"(无数字)/ "工作表 1" / 业务名,猜 `Sheet1` 大概率撞 `sheet not found`,比先查多耗一次失败调用 + 重试
- ⚠️ **`--range` 里的 `Sheet1!` 前缀不能替代 sheet 定位**:即使写了 `--range 'Sheet1!A1:B2'`,仍**必须**额外传 `--sheet-id``--sheet-name`,否则照样报上面的错。
- ⚠️ **A1 reference 含 `!`**`--source` / `--range` / `--ranges`**:整段用单引号包裹**,如 `--range 'Sheet1!A1:B2'`——单引号能挡住 bash 的 history expansion`!` 被拦成 `event not found`;双引号挡不住;别改用 `set +H`,原因见下方「复合 JSON / 大入参」。sheet 名含特殊字符(`-` / 空格 / 非 ASCII需在内部按 A1 标准再包一层单引号时,用 `'\''` 转义保持外层单引号,如 `--source ''\''Sales-2025'\''!A1:D100'`
- **例外**:徽章标为 `_公共URL/token无 sheet 定位…_` 的 shortcut`+workbook-info` / `+workbook-export` / `+batch-update` / `+dropdown-update|delete` / `+cells-batch-set-style` / `+cells-batch-clear` / `+sheet-create`**不接受也不需要** sheet 定位,只给一组 spreadsheet 定位即可。`+pivot-create``--target-sheet-id` / `--target-sheet-name`XOR可都不传落点细节见 `lark-sheets-pivot-table`)。
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--url` | string | 二选一必填(与 `--spreadsheet-token` | spreadsheet 或 wiki URL |
| `--spreadsheet-token` | string | 二选一必填(与 `--url` | spreadsheet token |
| `--sheet-id` | string | 二选一必填(与 `--sheet-name`;仅公共四件套 shortcut | 工作表 reference_id |
| `--sheet-name` | string | 二选一必填(与 `--sheet-id`;仅公共四件套 shortcut | 工作表名称 |
**统一调用范式**(公共四件套 shortcut 的所有示例都遵循此形状,两组定位缺一不可):
1. **spreadsheet 定位(必填)**`--url`(解析 `/sheets/``/spreadsheets/``/wiki/` 三种链接wiki 链接自动定位背后的电子表格)`--spreadsheet-token`(裸 token二选一**例外**`+workbook-create` / `+workbook-import` 产出**还不存在**的表,不接受任何定位 flag
2. **sheet 定位(公共四件套 shortcut 必填)**`--sheet-id``--sheet-name` 二选一
- ⚠️ **不确定 sheet 名时禁止猜 `Sheet1`**:除非对话或上下文已出现具体值,第一步先 `+workbook-info``sheets[].sheet_id/title` 再选——中文表的子表常叫"数据"/"工作表 1"/业务名,猜名大概率撞 `sheet not found`
- ⚠️ **`--range` 里的 `Sheet1!` 前缀不能替代 sheet 定位**:仍必须传 `--sheet-id` / `--sheet-name`
- ⚠️ **A1 引用含 `!` 时整段用单引号包裹**`--range 'Sheet1!A1:B2'`,挡 bash history expansion别用 `set +H`sh/dash 下非法。sheet 名含 `-`/空格需内层再包单引号时用 `'\''` 转义:`--source ''\''Sales-2025'\''!A1:D100'`
- **例外**:徽章标 `_公共URL/token无 sheet 定位…_` 的 shortcut`+workbook-info` / `+workbook-export` / `+batch-update` / `+styles-put` / `+dropdown-update|delete` / `+cells-batch-clear` / `+sheet-create`)不接受 sheet 定位。`+pivot-create``--target-sheet-id/name`XOR可都不传
```bash
lark-cli sheets <shortcut> <workbook 定位> <sheet 定位> <其它 flag>
# workbook 定位:--url "..." 或 --spreadsheet-token "..." (二选一,必给)
# sheet 定位: --sheet-id "$SID" 或 --sheet-name "<真实表名>" (二选一,必给;占位符不要原样填)
# 例lark-cli sheets +csv-get --url "https://.../sheets/shtXXX" --sheet-name "<真实表名>" --range "A1:F30"
# 注意:真实表名不要直接填 "Sheet1"——大多数表的子表不叫这个;先 +workbook-info 拿 sheets[].title 再代入。
# 统一调用范式:两组定位缺一不可(占位符别原样填;表名先 +workbook-info 查)
lark-cli sheets +csv-get --url "https://.../sheets/shtXXX" --sheet-name "<真实表名>" --range "A1:F30"
```
### 系统 flag
@@ -208,27 +201,27 @@ lark-cli sheets <shortcut> <workbook 定位> <sheet 定位> <其它 flag>
| --- | --- | --- | --- |
| `--dry-run` | bool | 否 | 零副作用:仅打印请求路径与参数模板,不发起调用;多步操作会输出每个子操作的请求模板 |
| `--yes` | bool | 是(仅 `high-risk-write` | 二次确认;不带时退出码 10。详见 [`../lark-shared/SKILL.md`](../lark-shared/SKILL.md) 高风险审批协议 |
| `--print-schema` | bool | 否 | 本地打印复合 JSON flag 的 JSON Schema 并退出,不发起任何调用、不需要其它 required flag。 `--flag-name <name>` 搭配指定查哪个 flag省略 `--flag-name` 时列出该 shortcut 所有可查询的 flag。**仅在 shortcut 含复合 JSON flag 时有效**——判断方法:该 shortcut 的 Flags 表里出现类型标注为「复合 JSON」的 flag`--cells` / `--properties` / `--operations` / `--border-styles` / `--sort-keys` / `--options`)即支持;纯标量 flag 的 shortcut 不支持。 |
| `--flag-name` | string | 否 | 配合 `--print-schema` 使用,指定要打印 JSON Schema 的 flag 名不带 `--` 前缀,如 `cells` / `properties` / `operations`。 |
| `--print-schema` | bool | 否 | 本地打印复合 JSON flag 的 JSON Schema 并退出,不发起调用、不需要其它 required flag。搭配 `--flag-name` 指定查哪个 flag省略时列出该 shortcut 可查询的 flag。仅对含复合 JSON flag 的 shortcut 有效。 |
| `--flag-name` | string | 否 | 配合 `--print-schema`flag 名不带 `--` 前缀`cells` / `properties`)。**支持点分路径切片**`--flag-name properties.snapshot.plotArea.axes` 只打印该子树,大 schemachart 的 properties 约 1700 行)按需取,别整篇翻页。 |
**Agent 使用提示**:写复合 JSON flag`--cells` / `--properties` / `--operations` / `--border-styles` / `--sort-keys` / `--options` 等)时,如果对结构不确定,先跑 `lark-cli sheets <shortcut> --print-schema --flag-name <name>` 把完整 JSON Schema 读出来再构造 payload比靠 reference 的速查表更精确也避免因为字段拼写或缺失被服务端拒绝。reference 的 `## Schemas` 段只给一层结构,深层只能靠 `--print-schema``## Examples` 的真实示例
> ⚠️ **high-risk-write 命令清单(首次调用就带 `--yes`,别等 exit 10 再补;或先 `--dry-run` 预览)**`+batch-update`、`+cells-clear`、`+cells-batch-clear`、`+sheet-delete`、`+dim-delete`、`+dropdown-delete`,以及各对象删除 `+chart-delete` / `+pivot-delete` / `+cond-format-delete` / `+filter-delete` / `+filter-view-delete` / `+sparkline-delete` / `+float-image-delete`
**Agent 使用提示**:写复合 JSON flag 前对结构不确定时,先 `--print-schema --flag-name <name>`(深层字段用点分路径切片)再构造 payload。图表任务必须先读 `lark-sheets-chart`:能用 `+chart-create-basic` / `+chart-data-update` / `+chart-config-update` 的语义参数就不得探查 schema 或构造 snapshot互不依赖的多图创建用 `+batch-chart-create`(每项直接填写 `+chart-create-basic` flags不套 `shortcut` / `input`),多图更新用 `+batch-chart-update``--dry-run` 展示的 `tool_name` / `operation` / `basic_chart` / `properties` 是内部 MCP body只能检查不能复制回 operations。只有单系列、单数据点或高级引擎字段无语义参数时才用 `+chart-create --print-example <type>` 或点分 schema 构造完整 snapshot。reference 的 `## Schemas` 段只给一层结构。
### flag 内容类型与输出约定(术语速记)
- flag 表里 JSON 类入参三类:**复合 JSON** = 深层嵌套对象(`--print-schema` 取完整结构**简单 JSON** = 一维 / 二维标量数组(如 `["sheet1!A1:B2",...]` / `[["alice",95]]`,结构简单无需 print-schema**非 JSON 文本** = 原样文本(如 CSV`--print-schema` 只对**复合 JSON** flag 有效(同一 shortcut 的简单 JSON flag 如 `--colors` 不在此列)
- **envelope**:所有 shortcut 返回统一外层结构 `{ok, identity, data, ...}`。正文里 `envelope.data` 指业务数据层(如 `+csv-get``annotated_csv`;写操作不会自动回读,如需校验自行调用对应的 `+*-list` / `+*-get` / `+cells-get`
- JSON 类入参三类:**复合 JSON** = 深层嵌套对象(`--print-schema` 可查**简单 JSON** = 一二维标量数组;**非 JSON 文本** = 原样文本(如 CSV`--print-schema` 只对复合 JSON flag 有效。
- **envelope**:所有 shortcut 返回统一外层 `{ok, identity, data, ...}`;写操作不会自动回读,校验自行调用 `+*-list` / `+*-get` / `+cells-get`
## 复合 JSON / 大入参:优先 stdin
flag 帮助里标注支持 **Stdin** 的入参,当 payload 较大、含换行 / 引号等特殊字符,或已经落在某个文件里时,优先用 stdin`-`)传入,避免命令行超长与 shell 转义问题
推荐写法payload 写到用户项目目录之外的临时文件(放系统临时目录,避免污染项目),再用 stdin 喂进去:
大 payload`--operations` / `--cells` / `--sheets` / `--styles` / `--properties`…)、或含换行 / 引号 / `!` 等特殊字符时,优先 heredoc stdin`-`)传入,避免命令行超长与 shell 转义问题
```bash
# TMPFILE 指向系统临时目录下的 payload 文件(脚本里用 tempfile.gettempdir() / os.tmpdir() 等取临时目录)
lark-cli sheets +cells-set --url "..." --sheet-name "Sheet1" --range "A1:B2" --cells - < "$TMPFILE"
lark-cli sheets +batch-update --url "..." --yes --operations - <<'JSON'
[{"shortcut":"+cells-set","input":{...}}]
JSON
```
**参数含特殊字符(`!` / 引号 / 空格 / 非 ASCII用单引号包裹该参数即可不要起手 `set +H` 之类的 shell 开关来防转义。** `set +H`(关 bash history expansion`sh` / `dash` 下是非法选项(`set: Illegal option -H`)、会让整条命令直接失败;而单引号挡得住 `!` 的 history expansion否则报 `event not found`),对 bash 与 `sh` / `dash` 一致安全。参数本身含单引号、或 payload 较大时,按上文走 stdin
**`@file` 接绝对路径会被拒,且被拒后不要照报错提示做。** `@file` 出于安全只接受 cwd 下的相对路径,传 cwd 之外的绝对路径会被拒。此时报错会建议"先 cd 到目标目录,或改用相对路径"——**两条都不要照做**cd 过去、或把临时文件写进用户项目目录,都会污染工作目录。正解是改用 stdin`--<flag> - < 文件`)。
- **stdin 每次调用只能给一个 flag**`+table-put` 同时传 `--sheets``--styles` 两个大 JSON 时,一个走 `-`、另一个走 `@./styles.json``@file` 只接受 cwd 下相对路径,**绝对路径会被拒**;正解是 stdin别 cd、别把临时文件写进用户项目目录
- **参数含特殊字符时用单引号包裹即可,不要 `set +H`**sh/dash 下非法直接报错);参数本身含单引号或 payload 大时走 stdin。

View File

@@ -5,25 +5,31 @@
`+batch-update` 把多次写入打包成单次请求,但每个子操作仍受编辑类任务硬性默认规则约束:
1. **目标 range 必须落在用户授权范围内**:除用户明示要修改的区域外,子操作禁止扩张到无关单元格 / 列 / Sheet。规划 range 时先确认每个子操作的边界。
2. **批次完成后必须回读校验**:整个 `+batch-update` 执行成功后,用 `+csv-get``+cells-get` 抽样回读受影响区域,至少校验 3-5 个代表性单元格(首 / 中 / 末),与本地脚本预先计算的预期值对照
3. **预期条数前置断言**:涉及"批量填充 N 行""对 M 个区域分别写入"时,先把 N、M 硬编码进代码,回读后断言实际等于预期;不一致就再发一轮 `+batch-update` 补齐,禁止交付半成品。
2. **批次完成后必须回读并比对预期值**:整个 `+batch-update` 执行成功后,单元格写入`+csv-get``+cells-get` 抽样回读受影响区域,至少 3-5 个代表性单元格(首 / 中 / 末),逐项与执行前清单中的预期值或预期公式比较;请求成功、单元格非空都不能替代值比对。发现不一致时,先定位对应子操作,只修复并重试失败或不一致的子集,禁止整批重发
3. **预期条数前置断言**:涉及"批量填充 N 行""对 M 个区域分别写入"或“每个 / 每天 / 分别各建一张图”时,先从数据数出 N、M 并写进清单;图表场景要断言 operations 中的创建数 = 独立实体图数 + 汇总图数。回读后断言实际等于预期,禁止用一张多系列汇总图替代多张独立图,也禁止交付半成品。
若本次 `+batch-update` 的任一子操作写入了公式、复制了公式模板、或导入了含公式的数据块,**回读校验之后还必须继续执行 `+formula-verify`**。`+batch-update` 的原子提交只保证写入动作执行了,不保证整批公式运行结果 zero-error。
若本次 `+batch-update` 的任一子操作写入了公式、复制了公式模板、或导入了含公式的数据块,**回读校验之后还必须继续执行 `+formula-verify`**。`+batch-update` 只保证"写入动作按序执行了",不保证整批公式运行结果 zero-error。
## 使用场景
写入。批量执行多个写入工具操作。将多个工具调用合并为一次请求,按顺序依次执行。适合需要连续执行多个写入操作的场景(如先修改结构再写入数据)。注意:不支持嵌套 `+batch-update`
写入。把**跨类型、有顺序依赖**的多个写入操作合并为一次请求按序执行(如插列 → 写表头 → 回填数据)。注意:不支持嵌套 `+batch-update`
**不可放进 `--operations` 的写 shortcut**`shortcut` 枚举不含它们,强行写入会被校验拒):`+cells-set-image`(需本地上传图片)、`+dropdown-update` / `+dropdown-delete` / `+cells-batch-set-style` / `+cells-batch-clear`(自身已是批量入口,不可再嵌套)、`+dim-move`。这些操作需在 `+batch-update` 之外单独调用
**先分流再动手(按操作组合选入口)**:美化收尾(样式 / 合并 / 行高列宽 / 冻结的任意组合)→ 一次 `+styles-put`(声明式规格,见 `lark-sheets-styles-put`),不要拼 `--operations` 子操作数组;**同一个写操作**打多个区域 → 用该命令自身的复数形态(`+cells-set --writes` / `+cells-batch-clear` / `+dim-delete --ranges` / resize 的 map 形态等);只有跨类型的原子操作链才用本命令
**图表可以放进 `--operations`,但要有明确理由**`+chart-{create|update|delete}``+chart-create-basic``+chart-config-update``+chart-data-update` 都受支持。只有图表与其它写入存在同一批次的顺序依赖时才放进通用 batch例如“先写辅助数据再创建引用这些数据的图表”。纯图表任务仍优先使用 `+batch-chart-create` / `+batch-chart-update`:输入更短、默认允许部分成功、失败项恢复路径也更清楚。
**不可放进 `--operations` 的写 shortcut**`shortcut` 枚举不含它们,强行写入会被校验拒):`+cells-set-image`(需本地上传图片)、`+styles-put` / `+dropdown-update` / `+dropdown-delete` / `+cells-batch-clear`(自身已是批量入口,不可再嵌套)、`+dim-move`。这些操作需走对应专用入口。
**⚠️ 何时必须使用 `+batch-update`(硬性要求)**
- 需要对**多个**不同区域执行 `+cells-{merge|unmerge}` 时(如按分组合并多列相同内容)
- 需要先插入行列再写入数据时(`+dim-{insert|delete|hide|unhide|freeze|group|ungroup}` + `+cells-set`
- 需要对多个区域执行不同写入操作时(多次 `+cells-set` + `+cells-clear` 等组合)
**行高列宽批量不走这里**:多行 / 多列不同尺寸直接`+rows-resize --heights` / `+cols-resize --widths` 的 map 形态(`--widths '{"A":100,"C:E":120}'``lark-sheets-range-operations`,一次调用原子完成map 形态不可作为 `--operations` 子操作嵌入(子操作里仍可用单区间形态 `range` + `height`/`width`)。
**行高列宽批量不走这里**:多行 / 多列不同尺寸用 `+styles-put``row_sizes` / `col_sizes`(可与样式同批),或 `+rows-resize --heights` / `+cols-resize --widths` 的 map 形态(见 `lark-sheets-range-operations`map 形态不可作为 `--operations` 子操作嵌入(子操作里仍可用单区间形态 `range` + `height`/`width`)。
当同一工具需要对多个区域重复调用时,**必须**改用 `+batch-update` 合并为单次请求——`+batch-update` 是原子提交(要么全成功要么整批回滚);逐个调用非原子,中途失败会留下半成品
**执行语义fail-fast不回滚**:默认首个失败的子操作即中断剩余操作,但**已执行成功的子操作不回滚**——服务端报 "N succeeded, M failed" 时前 N 个已实际生效。修复失败项后**只重发失败起的剩余子集**,整批重发会把已成功的操作(如插行)重复应用。传 `--continue-on-error` 则遇失败仍继续执行剩余操作。正因如此,含结构变更(插删行列 / 移动)的批次失败后要先回读确认现状再续发
互不依赖的多图表创建或更新分别使用 `+batch-chart-create` / `+batch-chart-update`;默认继续执行其它图表,保留成功项并根据逐项错误只重试失败项。
**公式相关批处理的默认闭环**
- 写前:先读 `lark-sheets-formula-translation`,把公式改写成飞书可执行语义。
@@ -37,7 +43,8 @@
| Shortcut | Risk | 分组 |
| --- | --- | --- |
| `+batch-update` | high-risk-write | 批量 |
| `+cells-batch-set-style` | write | 批量 |
| `+batch-chart-create` | write | 批量 |
| `+batch-chart-update` | write | 批量 |
| `+dropdown-update` | write | 对象 |
| `+dropdown-delete` | high-risk-write | 对象 |
| `+cells-batch-clear` | high-risk-write | 批量 |
@@ -50,28 +57,26 @@ _公共URL/token无 sheet 定位) · 系统:`--yes`、`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--operations` | string + File + Stdin复合 JSON | required | JSON 数组:[{"shortcut":"+xxx-yyy","input":{...}}, ...]。shortcut 用 CLI 名input 是该 shortcut 的入参集——含子表定位 sheet_id或 sheet_name但不含 spreadsheet token/url(后者只在顶层 --url/--spreadsheet-token 给一次;+batch-update 顶层没有 --sheet-idinput 的键是该 shortcut 的 flag 展平成 JSON如 "range":"A11:B12"),不是再套一层嵌套。基础 flag 查 --help复合 JSON flag 查 --print-schema --flag-name <flag>;不要手填 operation 字段(由 CLI 按 shortcut 自动注入)。默认严格事务(首个失败即整批中断),传 --continue-on-error 切换为软批量(遇失败仍继续;不支持嵌套;按数组顺序串行执行 |
| `--operations` | string + File + Stdin复合 JSON | required | JSON 数组:[{"shortcut":"+xxx-yyy","input":{...}}, ...]。shortcut 用 CLI 名input 是该 shortcut 的 flag 展平集合,含子表定位 sheet_id或 sheet_name不是底层 MCP body。spreadsheet token/url 只需在顶层给一次;子项重复出现 excel_id / spreadsheet_token / url 时会被忽略,始终以顶层定位为准。基础 flag 查 --help复合 JSON flag 查 --print-schema --flag-name <flag>;不要手填 operation 字段(由 CLI 按 shortcut 自动注入)。图表子操作可用,但纯图表任务优先使用 +batch-chart-create / +batch-chart-update。默认 fail-fast首个失败即中断剩余操作**已执行的子操作不回滚**(服务端报 "N succeeded, M failed" 时 N 个已生效,修复后只重发失败起的剩余子集,不要整批重发);传 --continue-on-error 遇失败仍继续;不支持嵌套;按数组顺序串行执行 |
| `--continue-on-error` | bool | optional | 遇子操作失败时继续执行剩余操作;默认 false首个失败即整批中断 |
### `+cells-batch-set-style`
### `+batch-chart-create`
_公共URL/token无 sheet 定位) · 系统:`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--ranges` | string + File + Stdin简单 JSON | required | 目标范围 JSON 数组(最多 100 个),每项必须带 sheet 前缀(如 `["Sheet1!A1:B2","Sheet2!D1:D10"]`,前缀裸写不加引号);前缀必须与 sheet 真实显示名完全一致(含大小写),不接受 sheet reference_id支持跨 sheet所有 range 应用同一组 style |
| `--background-color` | string | optional | 背景颜色(十六进制,如 `#ffffff` |
| `--font-color` | string | optional | 字体颜色(十六进制,如 `#000000` |
| `--font-family` | string | optional | 字体名称(如 `Arial``微软雅黑` |
| `--font-size` | float64 | optional | 字体大小px10、12、14 |
| `--font-style` | string | optional | 字体样式(可选值:`normal` / `italic` |
| `--font-weight` | string | optional | 字重(可选值:`normal` / `bold` |
| `--font-line` | string | optional | 字体线条样式(可选值:`none` / `underline` / `line-through` |
| `--horizontal-alignment` | string | optional | 水平对齐(可选值:`left` / `center` / `right` |
| `--vertical-alignment` | string | optional | 垂直对齐(可选值:`top` / `middle` / `bottom` |
| `--word-wrap` | string | optional | 换行策略(可选值:`overflow` / `auto-wrap` / `word-clip` |
| `--number-format` | string | optional | 数字格式(例:文本 `@`、数字 `0.00`、货币 `$#,##0.00`、日期 `mm/dd/yyyy` |
| `--border-styles` | string + File + Stdin复合 JSON | optional | 边框配置 JSON结构同 +cells-set-style |
| `--operations` | string + File + Stdin复合 JSON | required | 图表创建操作 JSON 数组;每项直接填写 `+chart-create-basic` 的 flag 和目标 sheet 定位,不要再套 `shortcut` / `input`。CLI 内部固定使用 `+chart-create-basic`。默认允许部分失败,成功图表保留,只重试失败项 |
| `--continue-on-error` | bool | optional | 单个图表失败后是否继续;默认 true |
### `+batch-chart-update`
_公共URL/token无 sheet 定位) · 系统:`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--operations` | string + File + Stdin复合 JSON | required | 图表更新操作 JSON 数组;每项使用 `+chart-config-update` `+chart-data-update`input 传对应命令的 flag 集合和目标 sheet 定位。CLI 会先读取各图表当前快照,再生成 partial properties默认允许部分失败 |
| `--continue-on-error` | bool | optional | 单个图表失败后是否继续;默认 true |
### `+dropdown-update`
@@ -112,18 +117,30 @@ _公共URL/token无 sheet 定位) · 系统:`--yes`、`--dry-run`_
_要批量执行的 CLI shortcut 操作列表,按声明顺序串行执行;任一失败立即中断_
**数组项**(类型 object
- `shortcut` (enum) — CLI shortcut 名(不是底层 MCP tool 名) [+cells-set / +cells-set-style / +cells-clear / +cells-merge / +cells-unmerge / +cells-replace / +csv-put / +dropdown-set / +dim-insert / +dim-delete / +dim-hide / +dim-unhide / +dim-freeze / +dim-group / +dim-ungroup / +rows-resize / +cols-resize / +range-move / +range-copy / +range-fill / +range-sort / +sheet-create / +sheet-delete / +sheet-rename / +sheet-move / +sheet-copy / +sheet-hide / +sheet-unhide / +sheet-set-tab-color / +sheet-show-gridline / +sheet-hide-gridline / +chart-create / +chart-update / +chart-delete / +pivot-create / +pivot-update / +pivot-delete / +cond-format-create / +cond-format-update / +cond-format-delete / +filter-create / +filter-update / +filter-delete / +filter-view-create / +filter-view-update / +filter-view-delete / +sparkline-create / +sparkline-update / +sparkline-delete / +float-image-create / +float-image-update / +float-image-delete]
- `input` (object) — 该 shortcut 的入参集——含子表定位 sheet_id或 sheet_name,但不含 spreadsheet token/url后者只在顶层 …
- `shortcut` (enum) — CLI shortcut 名(不是底层 MCP tool 名) [+cells-set / +cells-set-style / +cells-clear / +cells-merge / +cells-unmerge / +cells-replace / +csv-put / +dropdown-set / +dim-insert / +dim-delete / +dim-hide / +dim-unhide / +dim-freeze / +dim-group / +dim-ungroup / +rows-resize / +cols-resize / +range-move / +range-copy / +range-fill / +range-sort / +sheet-create / +sheet-delete / +sheet-rename / +sheet-move / +sheet-copy / +sheet-hide / +sheet-unhide / +sheet-set-tab-color / +sheet-show-gridline / +sheet-hide-gridline / +pivot-create / +pivot-update / +pivot-delete / +cond-format-create / +cond-format-update / +cond-format-delete / +filter-create / +filter-update / +filter-delete / +filter-view-create / +filter-view-update / +filter-view-delete / +sparkline-create / +sparkline-update / +sparkline-delete / +chart-create / +chart-update / +chart-delete / +chart-create-basic / +chart-config-update / +chart-data-update / +float-image-create / +float-image-update / +float-image-delete]
- `input` (object) — 该 shortcut 的入参集——含子表定位 sheet_id或 sheet_name
### `+cells-batch-set-style` `--border-styles`
### `+batch-chart-create` `--operations`
_单元格边框配置,含 top/bottom/left/right 四个方向,每个方向的结构相同(见 top_
**顶层字段**
- `top` (object?) { style?: enum, weight?: enum, color?: string }
- `bottom` (object?) { style?: enum, weight?: enum, color?: string }
- `left` (object?) { style?: enum, weight?: enum, color?: string }
- `right` (object?) { style?: enum, weight?: enum, color?: string }
**数组项**(类型 object
- `sheet_id` (string?) — 目标子表 ID与 sheet_name 二选一
- `sheet_name` (string?) — 目标子表名;与 sheet_id 二选一
- `chart_type` (enum) [column / bar / line / area / pie / scatter / combo / radar]
- `data_range` (string)
- `header_range` (string?)
- `data_direction` (enum?) [row / column]
- `dim1_index` (integer?)
- `dim2_indexes` (oneOf?)
- `title` (string?)
- `anchor_cell` (string?)
### `+batch-chart-update` `--operations`
**数组项**(类型 object
- `shortcut` (enum) [+chart-config-update / +chart-data-update]
- `input` (object) — 对应图表更新 shortcut 的 flag 集合;包含 sheet_id 或 sheet_name不包含 spreadsheet token/url
### `+dropdown-update` `--options`
@@ -152,9 +169,10 @@ lark-cli sheets +batch-update --url "https://example.feishu.cn/sheets/shtXXX" --
```
> ⚠️ **子操作定位规则**
> - spreadsheet 定位(`--url` / `--spreadsheet-token`**只在顶层给一次**`+batch-update` 顶层**没有** `--sheet-id` / `--sheet-name`,在顶层传不生效。
> - spreadsheet 定位(`--url` / `--spreadsheet-token`**只在顶层给一次**`+batch-update` 顶层**没有** `--sheet-id` / `--sheet-name`,在顶层传不生效。子操作里若重复出现 `excel_id` / `spreadsheet_token` / `url`CLI 会直接忽略,始终以顶层定位为准。
> - **每个子操作的子表定位 `sheet_id`(或 `sheet_name`)写进它自己的 `input`**(见上方 ops.json 每个 item
> - `input` 的键是该 shortcut 的 flag **展平**成 JSON`"range":"A11:B12"`、`"position":11`),不要把整组 `--operations` 再套一层嵌套 JSON。
> - `--dry-run` 显示的是翻译后的内部 MCP 请求体,其中会出现 `tool_name`、`operation`、`basic_chart`、`properties` 等字段。这些只用于核对最终请求,**不能复制回 `--operations`**;下一次输入仍使用 CLI shortcut + flags。
> **常见组合:插列 + 写表头 + 整列回填**——一次原子提交,不要拆成 N 次独立调用。批量回填同一列 **只需一次** `+cells-set`range 写整列范围、cells 写 N×1 矩阵),不需要逐行循环。
>
@@ -169,6 +187,19 @@ lark-cli sheets +batch-update --url "https://example.feishu.cn/sheets/shtXXX" --
> ]
> ```
> **多图表组合**:先完成全部辅助数据,再把每张图的输入放进 `+batch-chart-create`;每项同时记录精确表头范围、数据方向和预期系列数。批次完成后,每个受影响的 sheet 各调用一次 `+chart-list`。已有图表的批量修正改用 `+batch-chart-update`。
>
> ```json
> [
> {"sheet_name":"Sheet1","chart_type":"column","data_range":"'Sheet1'!A1:C10","title":"分类对比","anchor_cell":"F2"},
> {"sheet_name":"Sheet1","chart_type":"line","data_range":"'Sheet1'!E1:G10","title":"趋势变化","anchor_cell":"F18"}
> ]
> ```
>
> ```bash
> lark-cli sheets +batch-chart-create --url "..." --operations @ops.json
> ```
### `+cells-batch-set-style`
多 range 应用同一组 style服务端走 `+batch-update` 原子事务):
@@ -195,6 +226,6 @@ lark-cli sheets +cells-batch-clear --url "..." \
### Validate / DryRun / Execute 约束
- `Validate``+batch-update``--operations` 必须合法 JSON且为非空数组逐个子操作 `shortcut` / `input` 字段必填校验;**禁止嵌套 `+batch-update`**。`+cells-batch-set-style``--ranges` 必须 JSON 数组、每项带 sheet 前缀;样式 flag 至少一个非空(或带 `--border-styles``+cells-batch-clear``--ranges` 同样必须 JSON 数组、每项带 sheet 前缀,`high-risk-write` 强制 `--yes``--dry-run``--scope` 默认 `content`
- `DryRun`:按顺序输出每个子操作的目标 API + 请求 body 模板;首个失败则整批 fail-fast不实际执行任何后续
- `Execute`按声明顺序串行执行;任一子操作失败立即中断并回滚到该子操作前状态(具体回滚能力取决于子操作类型,沿用 `+batch-update` 的语义)
- `Validate``+batch-update``--operations` 必须合法 JSON且为非空数组逐个子操作校验 `shortcut` / `input` 和该 shortcut 的 flag 词汇表;通用 batch 支持图表 shortcut。`+batch-chart-create` 的每一项直接填写 `+chart-create-basic` flags`+batch-chart-update` 只接受 `+chart-config-update` / `+chart-data-update``+cells-batch-clear``--ranges` 必须 JSON 数组、每项带 sheet 前缀,`high-risk-write` 强制 `--yes``--dry-run`
- `DryRun`:按顺序输出每个子操作翻译后的内部 MCP 请求 body不发起调用。该 body 是输出协议,不是下一次 `--operations` 的输入协议
- `Execute`通用 `+batch-update` 默认 fail-fast图表专用 batch 默认 continue-on-error。两者都不回滚已成功项

View File

@@ -2,18 +2,40 @@
## 真对象硬约束
当用户要求"画个图 / 数据可视化 / 趋势图 / 对比图 / 占比图"时,**必须**通过 `+chart-{create|update|delete}` 创建真实的图表对象。**禁止**用本地脚本调 matplotlib / seaborn 生成图片再插入到表格代替——静态图片无法随源数据更新,且失去交互能力。判断标准:交付后 `+chart-list` 必须能返回该对象。
当用户要求"画个图 / 数据可视化 / 趋势图 / 对比图 / 占比图"时,**必须**通过图表创建命令创建真实的图表对象。**禁止**用本地脚本调 matplotlib / seaborn 生成图片再插入到表格代替——静态图片无法随源数据更新,且失去交互能力。判断标准:交付后 `+chart-list` 必须能返回该对象。
## 使用场景
读写图表对象。本 reference 覆盖 4 个 shortcut
读写图表对象。基础创建和常用更新优先用语义 shortcut只在高级配置时使用原始 snapshot
| 操作需求 | 使用工具 | 说明 |
|---------|---------|------|
| 查看已有图表 | `+chart-list` | 获取图表的类型、数据源和样式配置 |
| 创建/更新/删除图表 | `+chart-{create|update|delete}` | 对图表对象执行写入操作 |
| 按类型和范围创建基础图 | `+chart-create-basic` | 支持 column/bar/line/area/pie/scatter/combo/radar、行/列方向与整图配色;无需构造 snapshot |
| 修正已有图表的数据范围或方向 | `+chart-data-update` | CLI 读取当前快照并只回写 data patch保留其它配置 |
| 批量创建多个独立图表 | `+batch-chart-create` | 保留成功图表,并逐项返回失败原因;只重试失败项 |
| 批量更新多个独立图表 | `+batch-chart-update` | 逐图读取当前快照并生成 partial properties |
| 更新标题、轴、图例、标签、堆叠、平滑或整图配色 | `+chart-config-update` | CLI 读取当前快照并只回写配置 patch |
| 高级创建/更新、删除图表 | `+chart-{create|update|delete}` | 按系列/数据点精细设置等高级需求才使用原始 properties |
典型工作流:先读取现有图表了解配置 → 执行创建/更新/删除 → 再次读取验证结果
典型工作流:先确认表头和精确数据范围,用 `+chart-create-basic` 一次创建并尽量在同次调用中带上已知标题/轴/标签要求;创建后用返回的完整 `snapshot` 检查范围、方向与系列,再按需用 `+chart-list` 验证。已有图表的数据范围或方向错误时用 `+chart-data-update`,常用配置修正用 `+chart-config-update`。只有用户要求单个系列、数据点或高级引擎字段时,才读取现有 snapshot 并调 `+chart-update --properties`。不要为了常用配置先输出整份 schema也不要删除重建已经创建成功的图表
**多图表工作流**:先完成所有辅助数据和表头,列出每张目标图的类型、精确数据范围、标题和落点;确认清单后,用一次 `+batch-chart-create` 批量创建。它的每个 operation 直接填写 `+chart-create-basic` flagsCLI 内部固定按 `+chart-create-basic` 执行,不要再套 `shortcut` / `input`。图表之间独立时允许部分成功:按返回的逐项结果定位失败图表,只重试失败项。批量 create 的逐项结果不返回完整 snapshot批次后每个受影响的 sheet 各调用一次 `+chart-list`。已经成功创建的图表有数据源或配置差异时,用 `+batch-chart-update` 批量执行对应的语义更新,不要删除重建。
**图表错误处理工作流(必须按顺序)**
1. 创建前先用 `--dry-run` 检查数量、sheet、范围、类型和落点`dry-run` 输出中的 `tool_name` / `operation` / `basic_chart` / `properties` 是 CLI 翻译后的内部 MCP body**只能读,不能复制回 operations**。
2. 执行后同时检查 `succeeded``failed` 和逐项 `results[index]`;命令退出成功或顶层 `ok=true` 不代表每张图都成功。
3. 有失败时保留成功图表,按原始 `index` 只重试失败项。禁止整批重发,否则会重复创建已经成功的图表。
4. 对成功项,每个受影响 sheet 只调用一次 `+chart-list` 获取完整快照并核对总数、标题、范围、方向与系列。
5. 快照不符合预期时原地修复:数据源、方向、维度/系列、分离表头用 `+chart-data-update`;标题、轴、图例、标签、堆叠、平滑、配色用 `+chart-config-update`;只有高级字段才用 `+chart-update --properties`。不要删除重建。
**数量词必须展开**:用户说“每个 / 每天 / 分别 / 逐一 / 各一张图”时,先从数据中数出实体数 `N`,把这 `N` 张图逐项写进清单,再加上其它汇总图得到目标总数 `M`;一个包含全部实体的多系列图不能替代这 `N` 张独立图。批次前断言 operations 中恰有 `M` 个图表创建,批次后断言图表总数、逐图标题与实体集合一致。
**范围与系列前置校验(创建前必做)**:清单中同时记录每张图的表头范围、纳入维度、明确排除维度、数据方向和预期系列数。当前每张图**最多 50 个数值系列**;按列组织时通常为“所选数值列数”,按行组织时通常为“所选数值行数”。创建时就用 `+chart-create-basic --dim1-index ... --dim2-indexes ...` 显式选择类别与不超过 50 个数值系列;如果业务要求展示超过 50 个系列,应先建立紧凑汇总表或 Top-N而不是反复删除重建。创建前根据实际表头确认索引和边界不凭字母猜范围创建后范围、方向或系列数不符时使用 `+chart-data-update` 修正CLI 会读取当前快照、重建 `refs` / `dim1` / `dim2.series` 并只提交 data patch不要删除后重建。
**横向类别行配方**:当日期/月份等类别横向排列在一行、目标数值在另一行时,把“类别行 + 数值行”一起放进 `--data-range` 并传 `--data-direction row`,例如 `--data-range "'Sheet1'!A1:M1,'Sheet1'!A3:M3" --data-direction row`。此时类别行属于数据映射,**不要**传给 `--header-range``--header-range` 仅表示与纯数据分离的“维度/系列名称”column 方向必须是一行row 方向必须是一列。row 方向却传入多列表头,通常说明把类别行误当成了分离表头。
**整图配色优先走语义参数**:只要求统一主题或一组系列颜色时,在创建时传 `--color-palette``--colors`,已有图表用 `+chart-config-update` 更新;二者互斥。`--colors` 接受逗号分隔字符串;批量 operation 的 `colors` 同时接受字符串或字符串数组。只传一个自定义颜色时会自动用于全部系列。只有指定某个系列或某个数据点的颜色时才使用原始 snapshot。
## 需求→图表类型映射(创建前必查)
@@ -27,7 +49,9 @@
**多图表需求**:当用户同时提到多种分析(如"统计占比 + 对比数量"),必须创建多个图表,每个对应一种类型,不要只做一个。
**`--properties` 结构锚点(构造前必读)**`--properties` 顶层只有 `position` / `offset` / `size` / `snapshot` 四个字段,**没有**顶层 `data`,也没有再嵌一层 `properties`。图表数据配置全部挂在 `snapshot.data` 下——下文及示例里出现的 `refs` / `headerMode` / `dim1` / `dim2` / `nameRef` 一律指 `snapshot.data.refs` / `snapshot.data.headerMode` / `snapshot.data.dim1` / `snapshot.data.dim2`(及其下的 `serie.nameRef` / `series[].nameRef`);样式 / 堆叠 / 数据标签等在 `snapshot.plotArea` 下。完整结构以 `lark-cli sheets +chart-create --print-schema --flag-name properties` 为准。
**`--properties` 结构锚点(构造前必读)**`--properties` 顶层只有 `position` / `offset` / `size` / `snapshot` 四个字段,**没有**顶层 `data`,也没有再嵌一层 `properties`。图表数据配置全部挂在 `snapshot.data` 下——下文及示例里出现的 `refs` / `headerMode` / `dim1` / `dim2` / `nameRef` 一律指 `snapshot.data.refs` / `snapshot.data.headerMode` / `snapshot.data.dim1` / `snapshot.data.dim2`(及其下的 `serie.nameRef` / `series[].nameRef`);样式 / 堆叠 / 数据标签等在 `snapshot.plotArea` 下。**构造起点优先用 `lark-cli sheets +chart-create --print-example <column|bar|line|area|pie|scatter|radar|combo>` 拿最小可用模板改参**(本地即时返回);查深层字段用点分路径切片 `--print-schema --flag-name properties.snapshot.plotArea.axes`,别整篇 dump 翻页。完整结构以 `--print-schema --flag-name properties` 为准。
**`+chart-update` 局部更新硬规则(更新前必读)**:默认只在 `--properties` 中传实际变化的字段,未传字段保持不变;不要复制并回写完整 snapshot。`snapshot` 内普通对象递归合并,`refs` / `axes` / `series` 等数组整体替换——修改数组中的一项时,应先读取当前数组、改好后只回写该完整数组,不需要携带 snapshot 的其它字段。`snapshot.data.isStaticData` 不能通过 update 改变;需要切换静态/非静态数据时删除后重建。
**常见配置错误(必须注意)**
- **图表类型选择错误**:用户说"堆积柱形图/百分比堆积"时,应在 `properties.snapshot.plotArea.plot.extra.stack` 中配置堆叠;百分比堆叠需在该 stack 下设置 `percentage: true`。用户说"占比/比例"时,优先考虑饼图或百分比堆积图。注意区分 `column`(柱形图,纵向)与 `bar`(条形图,横向)是两个不同的 type 取值,"对比/各 XX" 类纵向柱默认用 `column`
@@ -104,6 +128,9 @@
| Shortcut | Risk | 分组 |
| --- | --- | --- |
| `+chart-list` | read | 对象 |
| `+chart-create-basic` | write | 对象 |
| `+chart-config-update` | write | 对象 |
| `+chart-data-update` | write | 对象 |
| `+chart-create` | write | 对象 |
| `+chart-update` | write | 对象 |
| `+chart-delete` | high-risk-write | 对象 |
@@ -118,6 +145,73 @@ _公共四件套 · 系统:`--dry-run`_
| --- | --- | --- | --- |
| `--chart-id` | string | optional | 指定单个图表 reference_id 过滤 |
### `+chart-create-basic`
_公共四件套 · 系统:`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--chart-type` | string | required | 图表类型(可选值:`column` / `bar` / `line` / `area` / `pie` / `scatter` / `combo` / `radar` |
| `--data-range` | string | required | 数据范围;未传 --header-range 时须包含表头,传入时只传纯数据;支持逗号分隔及跨子表多范围 |
| `--header-range` | string | optional | 可选的分离表头范围column 方向须为一行、row 方向须为一列,表头数须等于数据维度数 |
| `--data-direction` | string | optional | 数据系列方向column 表示首列为类别row 表示首行为类别(可选值:`column` / `row`)(默认 `column` |
| `--dim1-index` | int | optional | 类别/X 轴维度在数据范围中的 1-based 索引;默认 1 |
| `--dim2-indexes` | string | optional | 值/Y 轴系列的 1-based 索引列表,逗号分隔;不能包含 dim1最多 50 个 |
| `--title` | string | optional | 图表标题 |
| `--subtitle` | string | optional | 图表副标题 |
| `--legend-position` | string | optional | 图例位置hidden 隐藏图例(可选值:`top` / `bottom` / `left` / `right` / `hidden` |
| `--x-axis-title` | string | optional | X 轴标题 |
| `--y-axis-title` | string | optional | 左 Y 轴标题 |
| `--secondary-y-axis-title` | string | optional | 右 Y 轴标题 |
| `--x-axis-label-angle` | int | optional | X 轴标签旋转角度(可选值:`-90` / `-45` / `0` / `45` / `90` |
| `--y-axis-label-angle` | int | optional | 左 Y 轴标签旋转角度(可选值:`-90` / `-45` / `0` / `45` / `90` |
| `--data-labels` | string | optional | 数据标签内容none 隐藏标签;兼容 category_percentage 并自动按 value_percentage 处理(可选值:`none` / `value` / `percentage` / `value_percentage` / `category_percentage` / `category` / `series` |
| `--data-label-position` | string | optional | 数据标签位置(可选值:`auto` / `top` / `bottom` / `left` / `right` / `center` / `inside` / `outside` |
| `--stack` | string | optional | 堆叠模式(可选值:`none` / `normal` / `percent` |
| `--stacked` | bool | optional | 兼容别名;等价于 --stack normal隐藏 flag不在 `--help` 列出,但可正常传入) |
| `--smooth` | bool | optional | 是否使用平滑曲线;支持 --smooth=false 和 --smooth false |
| `--color-palette` | string | optional | 预设整图配色主题;与 --colors 互斥(可选值:`brandColorSeries@v2` / `rainbowColorSeries@v2` / `complementaryColorSeries@v2` / `converseColorSeries@v2` / `primaryColorSeries@v2` / `singleColorSeries-B-@v2` / `singleColorSeries-W-@v2` / `singleColorSeries-G-@v2` / `singleColorSeries-Y-@v2` / `singleColorSeries-O-@v2` / `singleColorSeries-R-@v2` / `singleColorSeries-D-@v2` |
| `--colors` | string_slice | optional | 自定义整图系列颜色,逗号分隔且至少 2 个十六进制色值;与 --color-palette 互斥 |
| `--anchor-cell` | string | optional | 可选图表锚点单元格,如 F2省略时放到数据范围右侧 |
| `--width` | int | optional | 可选图表宽度;必须与 --height 同时传 |
| `--height` | int | optional | 可选图表高度;必须与 --width 同时传 |
### `+chart-config-update`
_公共四件套 · 系统:`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--chart-id` | string | required | 目标图表 reference_id |
| `--title` | string | optional | 图表标题 |
| `--subtitle` | string | optional | 图表副标题 |
| `--legend-position` | string | optional | 图例位置hidden 隐藏图例(可选值:`top` / `bottom` / `left` / `right` / `hidden` |
| `--x-axis-title` | string | optional | X 轴标题 |
| `--y-axis-title` | string | optional | 左 Y 轴标题 |
| `--secondary-y-axis-title` | string | optional | 右 Y 轴标题 |
| `--x-axis-label-angle` | int | optional | X 轴标签旋转角度(可选值:`-90` / `-45` / `0` / `45` / `90` |
| `--y-axis-label-angle` | int | optional | 左 Y 轴标签旋转角度(可选值:`-90` / `-45` / `0` / `45` / `90` |
| `--data-labels` | string | optional | 数据标签内容none 隐藏标签;兼容 category_percentage 并自动按 value_percentage 处理(可选值:`none` / `value` / `percentage` / `value_percentage` / `category_percentage` / `category` / `series` |
| `--data-label-position` | string | optional | 数据标签位置(可选值:`auto` / `top` / `bottom` / `left` / `right` / `center` / `inside` / `outside` |
| `--stack` | string | optional | 堆叠模式(可选值:`none` / `normal` / `percent` |
| `--stacked` | bool | optional | 兼容别名;等价于 --stack normal隐藏 flag不在 `--help` 列出,但可正常传入) |
| `--smooth` | bool | optional | 是否使用平滑曲线;支持 --smooth=false 和 --smooth false |
| `--color-palette` | string | optional | 预设整图配色主题;与 --colors 互斥(可选值:`brandColorSeries@v2` / `rainbowColorSeries@v2` / `complementaryColorSeries@v2` / `converseColorSeries@v2` / `primaryColorSeries@v2` / `singleColorSeries-B-@v2` / `singleColorSeries-W-@v2` / `singleColorSeries-G-@v2` / `singleColorSeries-Y-@v2` / `singleColorSeries-O-@v2` / `singleColorSeries-R-@v2` / `singleColorSeries-D-@v2` |
| `--colors` | string_slice | optional | 自定义整图系列颜色,逗号分隔且至少 2 个十六进制色值;与 --color-palette 互斥 |
### `+chart-data-update`
_公共四件套 · 系统:`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--chart-id` | string | required | 目标图表 reference_id |
| `--data-range` | string | required | 新数据范围;未传 --header-range 时须包含表头,传入或原图已使用分离表头时只传纯数据;支持逗号分隔及跨子表多范围 |
| `--header-range` | string | optional | 可选的分离表头范围;提供后自动使用 detached 表头映射,省略时保留原图已有的 detached 映射 |
| `--data-direction` | string | optional | 数据系列方向;省略时沿用现有图表方向(可选值:`column` / `row` |
| `--dim1-index` | int | optional | 类别/X 轴维度在数据范围中的 1-based 索引;省略时使用第 1 个维度 |
| `--dim2-indexes` | string | optional | 值/Y 轴系列在数据范围中的 1-based 索引,逗号分隔;省略时使用除 dim1 外的全部维度 |
### `+chart-create`
_公共四件套 · 系统:`--dry-run`_
@@ -133,7 +227,7 @@ _公共四件套 · 系统:`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--chart-id` | string | required | 目标图表 reference_id |
| `--properties` | string + File + Stdin复合 JSON | required | 完整或足够完整的图表配置 JSON(先 `+chart-list` 回读再 patch |
| `--properties` | string + File + Stdin复合 JSON | required | 图表配置补丁 JSON;默认只传变化字段,未传字段保持不变;普通对象递归合并,数组整体替换 |
### `+chart-delete`
@@ -155,7 +249,7 @@ _创建/更新的图表属性_
- `position` (object?) — 必填 { row: number, col: string }
- `offset` (object?) — 可选 { row_offset?: number, col_offset?: number }
- `size` (object?) — 必填 { width: number, height: number }
- `snapshot` (object?) — 图表快照配置 { title?: object, subTitle?: object, style?: object, legend?: oneOf, plotArea: object, …共 6 项 }
- `snapshot` (oneOf?) — 图表快照配置
## Examples
@@ -165,6 +259,118 @@ _创建/更新的图表属性_
输出契约:返回按工作表分组的图表列表,每个图表含 `chart_id` / `position` / `details.snapshot` 等。
### `+chart-create-basic`
默认使用第 1 个维度作为类别/X 轴,其余维度作为数值系列;可在创建时用 1-based 的 `--dim1-index` 和逗号分隔的 `--dim2-indexes` 精确选择。饼图只允许一个数值系列;组合图至少需要两个数值系列;所有图表最多选择 50 个数值系列。默认让 `--data-range` 包含真实表头;只有“维度/系列名称”与纯数据分离时,才让 `--data-range` 只传纯数据,并用 `--header-range` 传对应的一行column或一列row表头。类别维度与数值维度不连续时范围参数可传逗号分隔的多范围也支持来自多个子表沿数据点轴对齐的跨子表范围会保留独立引用同一子表内错行、错列或重叠时合并为最小包围矩形跨子表范围无法对齐时会报错。单独调用成功后返回完整 `snapshot`,可直接检查创建结果并继续修改。参数名使用 `--anchor-cell`(不是 `--position`)和 `--data-labels`(不是 `--show-labels`)。兼容调用中,`--type` / `--range` 会分别按 `--chart-type` / `--data-range` 处理,`--x-axis` / `--y-axis` 会按轴标题处理;新调用仍优先使用规范参数名。
```bash
# 柱形图:默认放在数据范围右侧
lark-cli sheets +chart-create-basic --url "..." --sheet-name "Sheet1" \
--chart-type column --data-range "'Sheet1'!A1:C10" \
--title "销售额对比" --x-axis-title "品类" --y-axis-title "销售额" \
--legend-position bottom --data-labels value --data-label-position top
# 双轴组合图:首个数值列为左轴柱,其余数值列为右轴折线
lark-cli sheets +chart-create-basic --url "..." --sheet-name "Sheet1" \
--chart-type combo --data-range "'Sheet1'!A1:D13" \
--title "价格与效率" --y-axis-title "价格" --secondary-y-axis-title "效率" \
--anchor-cell F2 --width 700 --height 400
# 表头与数据分离data-range 只传纯数据header-range 按相同维度顺序传表头
lark-cli sheets +chart-create-basic --url "..." --sheet-name "Sheet1" \
--chart-type line \
--data-range "'Sheet1'!A2:A10,'Sheet1'!K2:L10" \
--header-range "'Sheet1'!A1,'Sheet1'!K1:L1"
# 横向类别行 + 一行数值:类别行也属于 data-range不要放进 header-range
lark-cli sheets +chart-create-basic --url "..." --sheet-name "Sheet1" \
--chart-type line \
--data-range "'Sheet1'!A1:M1,'Sheet1'!A3:M3" \
--data-direction row --dim1-index 1 --dim2-indexes 2
```
多张基础图一次创建。先把所有数据准备完成,再生成 `ops.json`
```json
[
{
"sheet_name": "Sheet1",
"chart_type": "column",
"data_range": "'Sheet1'!A1:C10",
"title": "分类对比",
"anchor_cell": "F2"
},
{
"sheet_name": "Sheet1",
"chart_type": "line",
"data_range": "'Sheet1'!E1:G10",
"title": "趋势变化",
"anchor_cell": "F18"
}
]
```
```bash
lark-cli sheets +batch-chart-create --url "..." --operations @ops.json
lark-cli sheets +chart-list --url "..." --sheet-name "Sheet1"
```
`ops.json` 不接受 MCP body。不要把 `--dry-run` 输出里的以下结构反抄回来:
```json
{"tool_name":"manage_chart_object","input":{"operation":"create","basic_chart":{}}}
```
批量创建的公开输入就是上面的扁平 `+chart-create-basic` flags。为了兼容旧调用CLI 仍能读取历史 `{shortcut:"+chart-create-basic",input:{...}}` 结构,但新任务不要生成旧格式。
批量修正已有图表时operations 只放配置或数据更新CLI 会先读取每张目标图的当前快照,再把对应 partial properties 合并进一次 `batch_update`
```json
[
{"shortcut":"+chart-config-update","input":{"sheet_name":"Sheet1","chart_id":"chrA","title":"新标题"}},
{"shortcut":"+chart-data-update","input":{"sheet_name":"Sheet1","chart_id":"chrB","data_range":"'Sheet1'!A1:D10"}}
]
```
```bash
lark-cli sheets +batch-chart-update --url "..." --operations @updates.json
```
### `+chart-data-update`
当创建后发现漏列、范围过宽、辅助分类列发生变化、系列选择错误或数据方向错误时,只更新数据源。`--data-direction` 省略时沿用现有图表方向。默认让新范围包含表头;表头在范围外时用 `--header-range` 单独传入。原图已经使用 detached 表头且表头不变时可省略 `--header-range`,工具会保留现有映射。默认使用第 1 个维度作为 dim1、其余维度作为 dim2需要精确选择时用 1-based 的 `--dim1-index` 和逗号分隔的 `--dim2-indexes`。工具返回更新后的 `data` 和实际采用的 `normalized_data_ranges`
```bash
# 把遗漏的最后一列纳入原折线图,保留标题、配色、图例和落点
lark-cli sheets +chart-data-update --url "..." --sheet-id "$SID" --chart-id "chrXXX" \
--data-range "'Sheet1'!A1:M6"
# 改用按行组织的数据源
lark-cli sheets +chart-data-update --url "..." --sheet-id "$SID" --chart-id "chrXXX" \
--data-range "'Sheet1'!A1:M6" --data-direction row
# 第 1 列作为类别,只使用第 4、8 列作为数值系列
lark-cli sheets +chart-data-update --url "..." --sheet-id "$SID" --chart-id "chrXXX" \
--data-range "'Sheet1'!A1:M6" --dim1-index 1 --dim2-indexes "4,8"
# 改为分离表头的数据源
lark-cli sheets +chart-data-update --url "..." --sheet-id "$SID" --chart-id "chrXXX" \
--data-range "'Sheet1'!A2:A10,'Sheet1'!K2:L10" \
--header-range "'Sheet1'!A1,'Sheet1'!K1:L1"
```
### `+chart-config-update`
只传需要改的字段,成功后返回更新后的 `viewModel``--data-labels none` 会删除数据标签;`--legend-position hidden` 会隐藏图例;`--smooth=false``--smooth false` 都可显式关闭平滑曲线。为减少参数重试,`--stacked` 自动按 `--stack normal` 处理,`--data-labels category_percentage``percentage,value``value,percentage` 都自动按 `value_percentage` 处理,`--x-axis` / `--y-axis` 自动按 `--x-axis-title` / `--y-axis-title` 处理;新调用仍优先使用规范参数。
```bash
lark-cli sheets +chart-config-update --url "..." --sheet-id "$SID" --chart-id "chrXXX" \
--title "新标题" --x-axis-label-angle -45 --legend-position right
lark-cli sheets +chart-config-update --url "..." --sheet-id "$SID" --chart-id "chrXXX" \
--data-labels value_percentage --data-label-position outside --stack percent
```
### `+chart-create`
> **`snapshot.data` 必填 `dim1.serie.index` 或 `dim2.series[].index` 之一**1-based对应 `refs.value` 范围内的列序。schema 允许传空 `{}` 但 server 运行时强制:缺则被拒为 `snapshot.data.dim1.serie.index and dim2.series[].index are both missing; at least one must be set`,即便侥幸通过也只会渲染空图。
@@ -292,22 +498,23 @@ JSON
### `+chart-update`
**Update 三步法**(缺一步会丢字段
1. `+chart-list --chart-id <id>` 拿到完整 snapshot
2. 在拿到的 snapshot 上**局部**修改要改的字段,其余保持不变
3. 把**完整 snapshot** 整个回写到 `--properties.snapshot`
默认提交**最小 patch**。例如只修改标题时,只传标题字段:
```bash
lark-cli sheets +chart-update --url "..." --sheet-id "$SID" --chart-id "chrXXX" \
--properties '{
"position":{"row":0,"col":"A"},
"size":{"width":480,"height":320},
"snapshot": <完整快照(由 +chart-list 取回后局部修改)>
"snapshot":{"title":{"text":"新的图表标题"}}
}'
```
> 关键:**不能只提交局部 snapshot**,否则未传字段会被还原为默认值。`+chart-update` 的语义是 PUT整体覆盖不是 PATCH。
只调整尺寸时,不需要传 `snapshot`
```bash
lark-cli sheets +chart-update --url "..." --sheet-id "$SID" --chart-id "chrXXX" \
--properties '{"size":{"width":640,"height":360}}'
```
> 数组采用整体替换语义。比如只修改一个坐标轴时,先用 `+chart-list --chart-id <id>` 取得当前 `snapshot.plotArea.axes`,修改目标项后,仅回写 `{"snapshot":{"plotArea":{"axes":[...]}}}`;不要同时回写标题、数据源、图例等未变化字段。
### `+chart-delete`
@@ -325,8 +532,8 @@ lark-cli sheets +chart-delete --url "https://example.feishu.cn/sheets/shtXXX" --
### Validate / DryRun / Execute 约束
- `Validate`XOR 公共四件套;`+chart-create` / `+chart-update``--properties` 必须能解析为合法 JSON`+chart-delete`high-risk-write校验 `--yes``--dry-run` 至少一个。
- `DryRun``+chart-create` / `+chart-update` 输出"将要 POST 的 body 模板"`+chart-delete` 输出"将要删除的 chart_id 及隶属 sheet",零网络副作用。
- `Validate`XOR 公共四件套;`+chart-data-update` 要求 `--chart-id``--data-range`,并校验 `--dim1-index` / `--dim2-indexes` 是正整数索引;`+chart-create` / `+chart-update``--properties` 必须能解析为合法 JSON`+chart-delete`high-risk-write校验 `--yes``--dry-run` 至少一个。
- `DryRun``+chart-data-update` / `+chart-create` / `+chart-update` 输出"将要 POST 的 body 模板"`+chart-delete` 输出"将要删除的 chart_id 及隶属 sheet",零网络副作用。
- `Execute`:写操作执行后不自动回读;如需确认,自行调用 `+chart-list` 比对结果。
> `+chart-create` / `+chart-update` 是 write 级别,按需可用 `--dry-run` 预览,不要求 `--yes`。只有 `+chart-delete`high-risk-write必须 `--yes`。

View File

@@ -32,7 +32,68 @@
- 需要公式/样式/批注 → `+cells-get`
- 只想知道某区域下拉框有哪些选项 → `+dropdown-get`
⚠️ **大数据优先落盘、别灌进上下文**`+csv-get` / `+cells-get` 都受调用方 Bash / 终端的单命令 stdout 输出上限约束(常见默认约 30000 字符,超过会被截断或转存为文件)。纯值分析优先 `+csv-get --format csv``--range` 行窗口(`A1:Z500` / `A501:Z1000` …)分批重定向到文件 + 本地脚本处理 + `+csv-put` 分批回写;若确实要让结果直接进上下文又不想触发转存,给任一命令把 `--max-chars`(默认 500000调小到略低于该上限`25000`CLI 改为优雅截断 + `has_more` 分页。
## 读表理解脚本Agent 优先入口)
当目标是"先理解表格内容 / 结构 / 子表边界",优先使用 `scripts/lark_*.py` 这组只读脚本,再决定是否直接调用上述 shortcut。脚本是默认捷径不是唯一入口如果任务很小或需要公式 / 样式 / 批注 / 精确原始值等脚本未覆盖的信息,可以直接用 CLI 做等价或更精细读取。
| 脚本 | 底层 shortcut | 适用场景 |
| --- | --- | --- |
| `scripts/lark_inspect_workbook.py` | `+workbook-info` / `+sheet-info` / `+csv-get` | 在线表格第一步预检:拿 sheet 清单、布局、预览、`current_region` |
| `scripts/lark_detect_subtables.py` | `+workbook-info` / `+sheet-info --include merges,hidden_rows,hidden_cols` / 小窗口 `+csv-get` | 同一 sheet 可能有多个表格区域、汇总块、备注块时,在**已知且未截断的窗口**内识别候选子表 range |
| `scripts/lark_profile_table.py` | `+csv-get` / `+sheet-info --include hidden_rows,hidden_cols`(默认包含隐藏行列时;必要时再手工 `+cells-get` / `+table-get` | 对**已确认且未截断的候选 range**做表头、数据范围、列类型、特殊行画像,并输出 `summary` / `field_map` / `risk_warnings` / `write_hints` |
`lark_profile_table.py` 是**启发式画像**,不是最终判定器:它能降低手工数行列和漏看特殊行的风险,但表头、多行标题、数据末行、列类型、特殊行和追加列都可能需要二次确认。批量写入、公式、排序、筛选、去重、透视/图表等操作前,不能只凭 profile 结果直接写;必须把 profile 输出与任务语义、样本值、必要的 CLI 补读一起核对。
`lark_profile_table.py` 的使用口径:
| 任务类型 | 建议 |
| --- | --- |
| 只读取或修改用户明确指定的单个单元格 / 很小范围,且不需要理解整表 | 可直接用 CLI |
| 批量写入、公式 / 计算、排序、筛选、删除、仅保留、去重、lookup / 匹配、条件高亮、透视表、图表、汇总 | 优先对目标区域运行 `lark_profile_table.py`;若已用等价 CLI 明确确认表头、数据范围、字段列、列类型和特殊行,可跳过脚本。去重 / lookup 若目标列含 `long_numeric_like_id`、前导 0 或格式化数字profile 只能定位列,比较值必须改用 `+cells-get``+table-get` |
| 多块表、表头不确定、存在合并 / 汇总 / 空行 / 备注块、选区是单格但任务语义是整表 | 先 `lark_detect_subtables.py` 或补充 CLI 确认候选范围,再对目标 range 跑 `lark_profile_table.py` |
| 需要公式、样式、批注、数据验证、精确原始值、长数字 ID 精确比较 | 先用脚本形成结构化理解,再按需补 `+cells-get` / `+table-get` / 分批 `+csv-get` |
推荐链路(大表先定窗口,脚本不接受截断结果):
```bash
python scripts/lark_inspect_workbook.py --url "<表格URL>"
# 先用 +workbook-info 和小窗口 +csv-get 确认真实 sheet、列边界和起始区域大表按行窗口推进。
python scripts/lark_detect_subtables.py --url "<表格URL>" --sheet-name "<子表名>" --range "A1:H200"
python scripts/lark_profile_table.py --url "<表格URL>" --sheet-name "<子表名>" --range "A1:H200"
```
`lark_detect_subtables.py` / `lark_profile_table.py``+csv-get` 命中 `has_more` 会以错误退出并报告已读取的 `actual_range`,绝不基于半截数据给出候选范围或画像。遇到此错误,以 `actual_range` 为已完成窗口,缩小列数或从其末行之后继续读;跨窗口的候选范围、汇总行和写入落点必须再用 CLI 核对,不能把单个窗口结果当整表结论。
脚本只读,不做任何写入。它们的输出用于降低 token 和定位错误;后续需要公式、样式、批注、精确原始值时,仍按本文件规则直接调用 `+cells-get` / `+table-get` / `+csv-get`。写入前如果使用了 `lark_profile_table.py`,至少读取并使用这些字段:`summary.header_row``summary.data_range``summary.data_row_segments``field_map``risk_warnings``visibility``write_hints.safe_append_col``special_rows`。仅当 `risk_warnings` 不含 `data_range_has_gaps` 时,才可把 `data_range` 当连续写入范围;有缺口时按 `data_row_segments` 分段读写。
脚本关键 flag
| Flag | 脚本 / 默认 | 何时调整 |
| --- | --- | --- |
| `--skip-hidden` | profile / detect关闭默认包含隐藏行列 | 只分析可见数据时开启;此时必须使用 profile 的 `data_row_segments`,不要把连续 `data_range` 直接用于写入。 |
| `--max-chars` | inspect `8000`profile / detect `25000` | 输出过大时缩小范围或降低值profile / detect 若截断会报错并给 `actual_range`,按窗口继续。 |
| `--header-scan-rows` | profile `20` | 表头前有多行标题、说明或空行时提高;过大时结合 `possible_multi_row_header` 补读确认,不要仅凭评分结果写入。 |
| `--max-sheets` | inspect `3` | 未指定 sheet 时仅前 N 个 sheet 带 layout / preview其余仍返回摘要并在 warnings 说明。 |
| `--max-merge-components` | detect `2000` | 超限会跳过 gap 合并并告警;需缩小窗口或人工复核子表边界。 |
| `--gap-rows` / `--gap-cols` | detect `1` / `0` | 子表被切碎或粘连时调整;每次调整后复核候选范围。 |
detect 最多确认 10 个跨窗口合并锚点;超限会在 `warnings` 中说明跳过的数量。遇到该 warning缩小扫描窗口后再复核受影响的子表边界。
`lark_profile_table.py` 输出触发补读的规则:
- `risk_warnings` 非空时,不要把画像当最终事实;按下表补读或调整,不在表内的 warning 也先保守复核。
| Warning | 必做动作 |
| --- | --- |
| `mixed_value_types` / `long_numeric_like_id` / `formula_or_value_errors` | 补 `+cells-get``+table-get`,确认原始值、类型和公式。 |
| `duplicate_headers` / `unnamed_columns` / `header_not_detected` / `header_row_not_first` / `many_empty_cells` | 补 `+csv-get` 读取表头附近和空值样本,确认真正表头与字段列。 |
| `data_range_not_detected` / `special_rows_present` / `empty_rows_present` | 补 `+csv-get` 读取尾部和特殊行样本,确认有效数据末行。 |
| `possible_multi_row_header` | 补读表头上下各 1-2 行;必要时 `+sheet-info --include merges` 核对跨列合并。 |
| `hidden_rows_in_range` / `hidden_columns_in_range` | 写入前用 `+sheet-info --include hidden_rows,hidden_cols` 确认是覆盖还是跳过隐藏内容。 |
| `data_range_has_gaps` | 不按连续 `data_range` 写;用 `summary.data_row_segments` 对每个实际读取行段单独读写。 |
- `write_hints.safe_append_col` 只是候选追加列,不代表绝对安全。新增列或覆盖区域前,必须用 `+csv-get` / `+cells-get` / `+sheet-info` 核对该列为空、没有隐藏列/公式/样式/对象依赖,且符合用户要求的落点。
⚠️ **大数据优先落盘、别灌进上下文**`+csv-get` / `+cells-get` 都受调用方 Bash / 终端的单命令 stdout 输出上限约束(常见默认约 30000 字符,超过会被截断或转存为文件)。纯值分析优先用 `+csv-get``--range` 行窗口(`A1:Z500` / `A501:Z1000` …)分批重定向到文件 + 本地脚本处理 + `+csv-put` 分批回写;若确实要让结果直接进上下文又不想触发转存,给任一命令把 `--max-chars`(默认 500000调小到略低于该上限`25000`CLI 改为优雅截断 + `has_more` 分页。
**`+csv-get` 返回值核心设计**
- `annotated_csv`**CSV 数据唯一入口**。每一逻辑行前加 `[row=N] ` 前缀N = 真实表格行号)。任何需要行号的下游操作(合并、写入、清空、格式化、插入/删除、条件格式、筛选、图表/透视表范围、搜索替换等),**行号一律直接从 `[row=N]` 读取**。若需要纯 CSV如喂给本地脚本做解析去前缀即可`line.replace(/^\[row=\d+\] /, '')`
@@ -44,6 +105,7 @@
- `+csv-get``+cells-get` 支持分页/截断,注意检查 `has_more` / `truncated` 标志;两者在处理返回数据之前都必须先读 `warning_message`(上游 schema 要求先读它再用其它字段,内含定位与截断续读提示),`+cells-get` 还要用每个 range 的 `actual_range` / `row_indices` / `col_indices` 判断真实位置
- 隐藏行列默认包含在返回结果中(`--skip-hidden=false`),如需只看可见数据设为 `true`。读取原语本身不标注哪些行列被隐藏:若要识别隐藏区间(以决定是否过滤、或如何解读混入的隐藏数据),用 `+sheet-info --include hidden_rows,hidden_cols` 取隐藏行列集合,再结合 `+csv-get` / `+cells-get` 返回的 `row_indices` / `col_indices` 判断每行 / 每列是否隐藏
- 要判断单元格内容是否被行高列宽挤到显示不全(排版检查、调整行高列宽前),给 `+cells-get``--include truncation`:会按字号 / 自动换行 / 行高列宽估算并返回被截断单元格的 `isRowTruncated` / `isColTruncated`(未返回视为未截断)。有额外计算开销,仅需要时才开
**常见配置错误(必须注意)**
- **全量读取导致上下文溢出**:不要对大表(数百行以上)直接用 `+csv-get``+cells-get` 读取全部数据到上下文。大表场景必须分批读取:用 `--range` 切行窗口逐块读(`+csv-get` / `+cells-get` 单次返回量由 `--max-chars` 自动兜底,截断时返回 `has_more`);过大时考虑导出到本地文件后用脚本处理再分批回写
@@ -99,8 +161,9 @@ _公共四件套 · 系统:`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--range` | string | required | A1 范围,如 `A1:F10`(不带 sheet 前缀;用 `--sheet-id` / `--sheet-name` 指定 sheet |
| `--include` | string_slice | optional | 要返回的信息类别,逗号分隔多个(可选值:`value` / `formula` / `style` / `comment` / `data_validation` |
| `--max-chars` | int | optional | 单次返回字符上限,默认 500000兜底防爆大数据通常宜重定向落盘做分析;仅当要让结果直接进上下文、又不触发文件转存时才调小(如 25000 has_more 分页 |
| `--include` | string_slice | optional | 要返回的信息类别,逗号分隔多个`truncation` 会额外按行高列宽 / 字号 / 自动换行估算每个单元格是否被截断显示,返回 `isRowTruncated` / `isColTruncated`(有额外计算开销,仅排版检查 / 调整行高列宽前才开)(可选值:`value` / `formula` / `style` / `comment` / `data_validation` / `truncation` |
| `--max-chars` | int | optional | 单次返回字符上限,默认 500000兜底防爆要整表无截断直接用 --output-path 落盘(自动放开为无限);仅当要让结果直接进上下文、又不落盘时才调小(如 25000 has_more 分页 |
| `--output-path` | string | optional | 把完整读取结果写入本地路径(如 `./out.json`),文件内容为 data 载荷的 JSONstdout 只回一个含 output_path/字节数的确认信息。**一旦设置,字符上限默认放开为无限**(覆盖 --max-chars 默认),适合大表整表落盘再分析,避免 stdout 被 max_chars 截断。省略时按常规把结果打到 stdout。 |
| `--skip-hidden` | bool | optional | 跳过隐藏行列,默认 `false` |
### `+dropdown-get`
@@ -117,8 +180,9 @@ _公共四件套 · 系统:`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--range` | string | required | A1 范围,如 `A1:F30`(不带 sheet 前缀;用 `--sheet-id` / `--sheet-name` 指定 sheet |
| `--max-chars` | int | optional | 单次返回字符上限,默认 500000兜底防爆大数据通常宜重定向落盘做分析;仅当要让结果直接进上下文、又不触发文件转存时才调小(如 25000 has_more 分页 |
| `--range` | string | optional | A1 范围,如 `A1:F30`(不带 sheet 前缀;用 `--sheet-id` / `--sheet-name` 指定 sheet。**可省略:缺省读取整个子表**(按表格实际边界裁剪,返回的 actual_range 标注实际读取范围);大表配合 --max-chars / --output-path 控制体量 |
| `--max-chars` | int | optional | 单次返回字符上限,默认 500000兜底防爆要整表无截断直接用 --output-path 落盘(自动放开为无限);仅当要让结果直接进上下文、又不落盘时才调小(如 25000 has_more 分页 |
| `--output-path` | string | optional | 把完整读取结果写入本地路径(如 `./out.json`),文件内容为 data 载荷的 JSONstdout 只回一个含 output_path/字节数的确认信息。**一旦设置,字符上限默认放开为无限**(覆盖 --max-chars 默认),适合大表整表落盘再分析,避免 stdout 被 max_chars 截断。省略时按常规把结果打到 stdout。 |
| `--include-row-prefix` | bool | optional | 是否在每行前加 `[row=N]` 前缀,默认 `true` |
| `--skip-hidden` | bool | optional | 跳过隐藏行列,默认 `false` |
@@ -131,6 +195,8 @@ _公共URL/token无 sheet 定位) · 系统:`--dry-run`_
| `--sheet-id` | string | optional | 只读该子表(按 id省略则读所有子表 |
| `--sheet-name` | string | optional | 只读该子表(按名);省略则读所有子表 |
| `--range` | string | optional | 读取的 A1 范围;省略则读每个子表的完整 used range会跨过表中部的整行空行 / 整列空列,不会被截断) |
| `--max-chars` | int | optional | 单次返回字符上限,默认 500000兜底防爆。底层工具即使不传也有约 50000 的默认截断,故此处显式发送以放宽;要整表无截断请用 --output-path 落盘(自动放开为无限)。 |
| `--output-path` | string | optional | 把完整读取结果写入本地路径(如 `./out.json`),文件内容为 data 载荷的 JSONstdout 只回一个含 output_path/字节数的确认信息。**一旦设置,字符上限默认放开为无限**(覆盖 --max-chars 默认),适合大表整表落盘再分析,避免 stdout 被 max_chars 截断。省略时按常规把结果打到 stdout。 |
| `--no-header` | bool | optional | 把第一行当数据而非表头(列名取 col1/col2 …) |
## Examples
@@ -147,6 +213,10 @@ lark-cli sheets +csv-get --url "https://example.feishu.cn/sheets/shtXXX" --sheet
# 用 sheet-name 模糊定位(运行时框架会先解析到 sheet-id
lark-cli sheets +csv-get --spreadsheet-token shtXXX --sheet-name "销售明细" --range "A1:F30"
# 全量读:省略 --range 即读整个子表(按实际边界裁剪,返回 actual_range 标注实读范围),
# 无需先 +workbook-info 探行列再拼 range大表配合 --max-chars / --output-path
lark-cli sheets +csv-get --spreadsheet-token shtXXX --sheet-name "销售明细"
```
输出契约envelope.data

View File

@@ -23,7 +23,7 @@
- 当表格存在合并单元格时,应结合返回的 `merged_cells` 判断表头、分组标题和区域语义
- 不要把合并区域中非左上角的空白单元格理解为"无内容";通常应将左上角单元格的内容视为整个合并区域的语义内容
- 插入用 `+dim-insert``--position`(插入位置;行用 1-based 行号如 `3`,列用字母如 `C`,新行/列插在此位置**之前**+ `--count`(插入数量,>0。新行/列样式继承用 `--inherit-style``before`/`after`/`none`
- 插入用 `+dim-insert``--position`(插入位置;行用 1-based 行号如 `3`,列用字母如 `C`,新行/列插在此位置**之前**+ `--count`(插入数量,>0。新行/列样式继承用 `--inherit-style``before` 继承前一行/列 / `after` 继承后一行/列);它只决定继承哪一侧的样式,**插入位置始终在 `--position` 之前,不改变插入方向**。⚠️ 不传时默认继承**后一行/列**(同 `after`);底层无法插入"无格式"行/列,要真正的纯空白行/列,插入后再用 `+cells-clear --scope formats` 清除新行/列的格式。
- 例如"在第 20 行后新增 116 行"`--position 21 --count 116`"第 20 行后"即 1-based 行号 21
**区间表达统一为 A1 风格**:所有涉及"一段连续行/列"的 shortcut 都用同一套 A1 闭区间字符串语法,**不存在 inclusive / exclusive / 0-based / 1-based 跨命令差异**
@@ -40,7 +40,7 @@
- **插入列直接用字母**`+dim-insert``--position` 在列场景直接传字母(如 `C`),不要把列字母换算成 0-based 索引
- **插入后引用偏移**:插入行/列后,原有数据的行号 / 列字母会发生偏移。如果插入后还需要对原有区域执行写入操作,必须重新计算偏移后的位置
- **删除行列前先确认范围**:删除操作不可逆,执行前应确认 `--range` 精确无误。可先用 `+csv-get` 读取目标区域验证内容(`+csv-get` / `+cells-get``lark-sheets-read-data`
- **"在 D 列左侧新增一列"的正确写法**`--position D --count 1`(新列插在 D 列之前);要继承左侧列样式加 `--inherit-style before`
- **"在 D 列左侧新增一列"的正确写法**`--position D --count 1`(新列插在 D 列之前);要继承左侧列样式加 `--inherit-style before`。不要把 `--inherit-style after` 当成“插到 D 列右侧”,它不是插入方向参数。
- **`+dim-move` 同维度约束**`--source-range` 是行区间时 `--target` 必须是行号(数字),是列区间时 `--target` 必须是列字母——不可一行一列混用
- **插入列后必须检查多行表头合并区域**:很多表格有 2-3 行的合并表头。插入列后,原有的合并区域不会自动扩展到新列。必须先用 `+sheet-info --include merges` 读取合并区域,插入后将跨越插入位置的合并区域重新设置(用 `+cells-{merge|unmerge}`),否则新列的表头会是空的、格式不连续
- **公式写入范围跳过表头行**:写入公式时从数据行开始(不是第 1 行)。先确认表头占几行(可能 1-3 行),公式的起始行 = 表头行数 + 1
@@ -76,7 +76,7 @@ _公共四件套 · 系统:`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--inherit-style` | string | optional | 新行/列样式继承策略 enum`before`(继承前一行/列)/ `after`(继承后一行/列)/ `none`(默认)(可选值:`before` / `after` / `none` |
| `--inherit-style` | string | optional | 新行/列样式继承 enum`before`(继承前一行/列)/ `after`(继承后一行/列);不传时默认继承后一行/列(同 `after`),底层无法插入无格式行/列。只决定继承哪侧样式、不改变插入方向(始终插在 `--position` 之前);要纯空白行/列请插入后用 `+cells-clear --scope formats`(可选值:`before` / `after` |
| `--position` | string | required | 插入位置(在此行/列**之前**插入):行用 1-based 行号如 `3`;列用字母如 `C` |
| `--count` | int | required | 插入数量(>0 |
@@ -86,7 +86,8 @@ _公共四件套 · 系统:`--yes`、`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--range` | string | required | 要删除的行/列闭区间;行用 1-based 数字如 `3:7` 或单行 `5`,列用字母如 `C:F` 或单列 `C` |
| `--range` | string | xor | 要删除的行/列闭区间;行用 1-based 数字如 `3:7` 或单行 `5`,列用字母如 `C:F` 或单列 `C`。与 `--ranges` 二选一 |
| `--ranges` | string + File + Stdin简单 JSON | xor | 要删除的多个行/列区间 JSON 数组(最多 100 个,如 `["5:5","8:8","11:13"]``["C:C","F:G"]`),全行或全列不可混用,区间不可重叠;与 `--range` 二选一。CLI 按位置**从大到小逆序**合成一次原子批量删除——正序删除会因前面的行/列被删导致后续索引前移错位,逆序由 CLI 代劳,无需自行排序 |
### `+dim-hide`
@@ -168,6 +169,11 @@ lark-cli sheets +dim-delete --url "..." --sheet-id "$SID" --range "5:7" --yes
# 删除 D-F 列
lark-cli sheets +dim-delete --url "..." --sheet-id "$SID" --range "D:F" --yes
# 删除多个散布区间(如按查重结果删行):--ranges 一次原子交付。
# CLI 自动按位置从大到小逆序执行——正序会因前面的行被删导致后续索引前移错位;
# 无需自行排序,也不要为此拼 +batch-update 的子操作数组
lark-cli sheets +dim-delete --url "..." --sheet-id "$SID" --ranges '["5:5","8:8","11:13"]' --yes
```
### `+dim-hide` / `+dim-unhide`
@@ -207,6 +213,6 @@ lark-cli sheets +dim-freeze --url "..." --sheet-id "$SID" --dimension row --coun
### Validate / DryRun / Execute 约束
- `Validate`XOR 公共四件套;`--range` / `--source-range` 必须是合法 A1 闭区间(行用数字、列用字母,不可混用);`+dim-insert``--count` > 0`+dim-move``--target` 必须与 `--source-range` 同维度(行 vs 列);`+dim-delete` 强制 `--yes``--dry-run``+rows-resize` / `+cols-resize` 的统一形态(`--range` + `--height`/`--width``--type`)与 map 形态(`--heights`/`--widths`)二选一、不可混用;详见 `lark-sheets-range-operations.md`
- `Validate`XOR 公共四件套;`--range` / `--source-range` 必须是合法 A1 闭区间(行用数字、列用字母,不可混用);`+dim-insert``--count` > 0`+dim-move``--target` 必须与 `--source-range` 同维度(行 vs 列);`+dim-delete` 强制 `--yes``--dry-run``--range``--ranges` 二选一、`--ranges` 各区间同维度且不可重叠≤100 个)`+rows-resize` / `+cols-resize` 的统一形态(`--range` + `--height`/`--width``--type`)与 map 形态(`--heights`/`--widths`)二选一、不可混用;详见 `lark-sheets-range-operations.md`
- `DryRun`:写操作输出"将要 PATCH 的目标范围 + 目标参数"。
- `Execute`:写后不自动回读;如需确认,自行调用 `+sheet-info --include row_heights,col_widths,hidden_rows,hidden_cols,groups,frozen` 查看受影响的范围。

View File

@@ -0,0 +1,91 @@
# Lark Sheet Styles Put+styles-put
> **本文定位**:对**已有**表格做美化收尾的默认入口——样式 / 边框 / 合并 / 行高列宽 / 冻结写成一份声明式规格,一次调用原子交付。样式**取什么值**(配色 / 字号 / 对齐 / 数字格式标准)以 `lark-sheets-visual-standards` 为唯一权威,本文只讲**怎么落地**。
>
> **边界(三分流判定,按操作组合选入口)**:目标是**样式 / 合并 / 行高列宽 / 冻结**的任意组合 → 本命令;**同一个写操作**打多个区域(如多区域清除、批量下拉)→ 用该命令自身的复数形态(`--ranges` / map 入参);操作链**跨类型且有顺序依赖**(如插列 → 写表头 → 回填数据)→ `+batch-update`。美化收尾不需要也不应该拼 `--operations` 子操作数组。
## 使用场景
写入。对存量表格的多个子表批量应用视觉规格:新表美化、加汇总行后统一版式、按分组合并同类单元格、调列宽行高、冻结表头。整份规格展开为一次原子批量提交,全部生效或全部不生效;纯样式盖章可安全重放(同一份规格重发无副作用)。
**词汇三处同构**`--styles` 的字段词汇与 `+workbook-create --styles`(建新表同步美化)、`+table-put --styles`(写数据同步美化)完全一致——`cell_styles` / `cell_merges` / `row_sizes` / `col_sizes` / `freeze` 学一次三处通用。区别只有两点:本命令作用于**已有**表格(顶层 `--url` / `--spreadsheet-token` 定位),且 `cell_styles` 的 range 不受「本次写入区域」限制、可指向表内任意区域。
**规格要点**
- 顶层 `{styles:[...]}`,每项对应一个目标子表,`name` 必须是真实子表名(不确定先 `+workbook-info` 查,禁止猜 `Sheet1`)。
- 每个子表项按固定顺序执行:`cell_merges``cell_styles``row_sizes``col_sizes``freeze`;样式盖章允许覆盖含合并区的区域(合并区限制只针对值写入,样式不受限)。
- `row_sizes` / `col_sizes` 只需 `{range, size}`px即像素尺寸`standard` / 行的 `auto` 才需显式 `type`)。尺寸键统一是 `size`
- 加边框用 `border` 简写:`{"style":"solid","color":"#DDDDDD"}` 应用到四边;只有分侧不同样式才用 `border_styles` 完整形态。
- `freeze``{rows:N, cols:N}` 冻结前 N 行 / 列0 或省略表示该维度不冻结。
**回读校验**:整份规格执行成功后按编辑准则抽样回读受影响区域(`+cells-get --include style``+sheet-info` 看合并 / 行高列宽 / 冻结),确认关键样式实际生效。
## Shortcuts
| Shortcut | Risk | 分组 |
| --- | --- | --- |
| `+styles-put` | write | 批量 |
## Flags
### `+styles-put`
_公共URL/token无 sheet 定位) · 系统:`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--styles` | string + File + Stdin复合 JSON | required | 对**已有**表格应用的视觉规格 JSON顶层 `{styles:[...]}`,每项对应一个目标子表(`name` 用真实子表名),并至少给 `cell_styles` / `cell_merges` / `row_sizes` / `col_sizes` / `freeze` 之一。字段词汇与 `+workbook-create` / `+table-put``--styles` 完全同构cell_styles 用 A1 range + 扁平样式字段,边框用 `border` 简写 {style,weight,color} 四边同款、分侧才用 border_stylesrow/col sizes 用行/列范围 + sizepx 即像素standard/auto 才需 typemerges 用单元格 rangefreeze 用 `{rows:N, cols:N}` 冻结前 N 行/列。整份规格展开为一次原子批量提交range 不受「本次写入区域」限制,可指向表内任意区域 |
## Schemas
> 复合 JSON flag 字段速查(只列顶层 + 一层嵌套)。深层结构看下方 `## Examples`,或用 `--print-schema` 读完整 JSON Schema用法见 SKILL.md「公共 flag 速查」与「Agent 使用提示」)。
### `+styles-put` `--styles`
**数组项**(类型 object
- `cell_merges` (array<object>?) — 单元格合并操作数组range 使用 A1 单元格范围merge_type 默认 all each: { merge_type?: enum, range: string }
- `cell_styles` (array<object>?) — 单元格样式操作数组;每项用 A1 单元格 range 指定范围,字段名与 +cells-set-style 对齐 each: { background_color?: string, border?: object, border_styles?: object, font_color?: string, font_family?: string, …共 14 项 }
- `col_sizes` (array<object>?) — 列宽操作数组range 使用列范围如 A:C给 sizepx即像素列宽type 可省略type 为 standard 时不带 size each: { range: string, size?: number, type?: enum }
- `freeze` (object?) — 冻结行列rows = 冻结前 N 行cols = 冻结前 N 列0 或省略 = 该维度不冻结) { cols?: integer, rows?: integer }
- `name` (string) — 子表名
- `row_sizes` (array<object>?) — 行高操作数组range 使用行范围如 1:3给 sizepx即像素行高type 可省略type 为 standard/auto 时不带 size each: { range: string, size?: number, type?: enum }
## Examples
### `+styles-put`
表头美化 + 按组合并 + 列宽 + 冻结首行,一次交付:
```bash
lark-cli sheets +styles-put --url "https://example.feishu.cn/sheets/shtXXX" --styles - <<'JSON'
{"styles":[{
"name": "Sheet1",
"cell_merges": [{"range":"A5:A8"},{"range":"A9:A12"}],
"cell_styles": [
{"range":"A1:F1","font_weight":"bold","background_color":"#1E5BC6","font_color":"#FFFFFF","horizontal_alignment":"center"},
{"range":"A2:F30","border":{"style":"solid","color":"#DDDDDD"}}
],
"row_sizes": [{"range":"1:1","size":36}],
"col_sizes": [{"range":"A:C","size":120}],
"freeze": {"rows":1}
}]}
JSON
```
多子表同一批交付(每个子表一个 styles 项):
```bash
lark-cli sheets +styles-put --url "..." --styles - <<'JSON'
{"styles":[
{"name":"明细","cell_styles":[{"range":"A1:H1","font_weight":"bold","background_color":"#F0F0F0"}],"freeze":{"rows":1}},
{"name":"汇总","cell_styles":[{"range":"A1:D1","font_weight":"bold"}],"col_sizes":[{"range":"A:D","type":"pixel","size":140}]}
]}
JSON
```
### Validate / DryRun / Execute 约束
- `Validate``--styles` 必须是合法 JSON、`styles` 非空数组;每项 `name` 必填、至少给 `cell_merges` / `cell_styles` / `row_sizes` / `col_sizes` / `freeze` 之一;`cell_styles` 每项至少一个样式字段展开后受子操作数100与总格数预算约束超限报错给拆分建议。
- `DryRun`:输出展开后每个子操作的请求模板,不发起调用。
- `Execute`:整份规格合成一次批量请求按序执行;失败时报错会注明已生效的子操作区间与续发方式。

View File

@@ -197,10 +197,11 @@ _一个或多个子表的 typed 数据,每个数组元素写入一张子表;
**数组项**(类型 object
- `cell_merges` (array<object>?) — 单元格合并操作数组range 使用 A1 单元格范围merge_type 默认 all each: { merge_type?: enum, range: string }
- `cell_styles` (array<object>?) — 单元格样式操作数组;每项用 A1 单元格 range 指定范围,字段名与 +cells-set-style 对齐 each: { background_color?: string, border_styles?: object, font_color?: string, font_family?: string, font_line?: enum, …共 13 项 }
- `col_sizes` (array<object>?) — 列宽操作数组range 使用列范围如 A:Ctype 为 pixel/standardpixel 需要 size each: { range: string, size?: number, type: enum }
- `cell_styles` (array<object>?) — 单元格样式操作数组;每项用 A1 单元格 range 指定范围,字段名与 +cells-set-style 对齐 each: { background_color?: string, border?: object, border_styles?: object, font_color?: string, font_family?: string, …共 14 项 }
- `col_sizes` (array<object>?) — 列宽操作数组range 使用列范围如 A:C给 sizepx即像素列宽type 可省略);type 为 standard 时不带 size each: { range: string, size?: number, type?: enum }
- `freeze` (object?) — 冻结行列rows = 冻结前 N 行cols = 冻结前 N 列0 或省略 = 该维度不冻结) { cols?: integer, rows?: integer }
- `name` (string) — 子表名
- `row_sizes` (array<object>?) — 行高操作数组range 使用行范围如 1:3type 为 pixel/standard/autopixel 需要 size each: { range: string, size?: number, type: enum }
- `row_sizes` (array<object>?) — 行高操作数组range 使用行范围如 1:3给 sizepx即像素行高type 可省略);type 为 standard/auto 时不带 size each: { range: string, size?: number, type?: enum }
## Examples

View File

@@ -73,7 +73,7 @@
> 以下是用 `+cells-set`(及 `+cells-set-style`)做富写入时的常用模式与准则;选哪个 shortcut 见上方「使用场景」。
`+cells-set` 为一块区域设置值 / 公式 / 批注 / 样式,也支持 `rich_text``type: "embed-image"` 嵌入单元格图片。**关键:`cells` 二维数组行列维度必须与 `range`(闭区间)严格一致,否则触发 `InvalidCellRangeError`**——维度计算示例见文末 `## Schemas``--cells`
`+cells-set` 为一块区域设置值 / 公式 / 批注 / 样式,也支持 `rich_text``type: "embed-image"` 嵌入单元格图片。**关键:`--cells` 恒为二维数组(行 × 格),单格也是 `[[{"value":…}]]`;且行列维度必须与 `range`(闭区间)严格一致,否则触发 `InvalidCellRangeError`**——维度计算示例见文末 `## Schemas``--cells`
> **单元格图片 vs 浮动图片(最易选错)**:图若**属于某条记录、要随那行排序 / 筛选 / 增删**(凭证 / 证件照 / 每行配图,话里带「对应 / 每行 / 这列」等绑定词)→ **单元格图片**(本工具):用 `+cells-set-image`(最短)或 `+cells-set` 的 `rich_text` + `type: "embed-image"`。只是自由摆放的装饰logo / 水印 / 封面)→ 浮动图片,见 lark-sheets-float-image。别因「浮动图更好控制 / 更熟」默认选浮动图——它承载"对应某记录"的图会随增删行 / 排序错位。
@@ -89,6 +89,19 @@
⚠️ **逐行写入公式是常见低效写法**:对每一行单独调用 `+cells-set` 写公式(如 26 次)既慢又易错,且不会自动平移公式引用。正确做法是 1 次模板写入 + 1 次 `--copy-to-range`(公式引用自动平移)。
💡 **多个不连续区域写入(批量修公式的正解)**:散布多处(可跨 sheet的值 / 公式写入,用 `--writes` 一次原子交付——每项 `{sheet_name, range, cells}`sheet 定位必须写在每项里),不要为此拼 `+batch-update``--operations`,也不要逐区域多次调用(非原子):
```bash
lark-cli sheets +cells-set --url "..." --writes - <<'JSON'
[
{"sheet_name":"明细","range":"D5","cells":[[{"formula":"=IFERROR(C5/B5,0)"}]]},
{"sheet_name":"汇总","range":"B3","cells":[[{"formula":"=SUM(明细!C:C)"}]]}
]
JSON
```
范围级统一样式不在 `--writes` 里做cells 逐格 `cell_styles` 仅用于逐格差异化),写完接 `+styles-put`
💡 **写入公式前先按迁移规则改写**:如果公式来自 Excel 或包含数组场景,先读取并遵循 `lark-sheets-formula-translation` 的规则完成改写,再把最终公式写入 `formula` 字段。
💡 **内容与样式分离写入(推荐)**:当需要同时写入内容和样式时,`cells` 中每个单元格都带上 `cell_styles` / `border_styles` 会导致入参非常冗长。由于同一区域的样式通常高度重复(如整列统一背景色、统一边框),推荐拆成两步:
@@ -102,7 +115,7 @@ Step 2: `+cells-set` — range="A2", cells 含 value + cell_styles + border_styl
```
这比在 99 个单元格中都重复写样式 JSON 高效得多。
💡 **样式更新是「部分合并」,不是整体覆盖**`+cells-set-style` / `+cells-batch-set-style`(以及 `+cells-set``cell_styles` / `border_styles`)只改你**显式传入**的样式属性,未传的属性保留原值。两个实用推论:
💡 **样式更新是「部分合并」,不是整体覆盖**`+cells-set-style` / `+styles-put`(以及 `+cells-set``cell_styles` / `border_styles`)只改你**显式传入**的样式属性,未传的属性保留原值。两个实用推论:
- **可分层叠加**:对同一区域先刷字体色、再单独刷背景色、再单独刷边框,后一步不会清掉前一步——美化已有区域时无需一次带齐所有字段,可拆成多次窄调用。
- **`border_styles` 按边合并**:只传 `{"top":{...}}` 只更新上边框,`bottom` / `left` / `right` 保留原状;不必为了「只改一条边」而把四边全部重传。(例外见上方「新增行的边框/样式禁止用 `{}` 跳过」:**全新行**底子里没有边框,仍需把要显示的边都显式传出。)
@@ -236,7 +249,7 @@ lark-cli sheets +dropdown-set \
> ⚠️ **`--source-range` 必须带 sheet 前缀**(即使跟 `--range` 同 sheet。注意一个坑回读这种 listFromRange 下拉单元格时,`data_validation.range` 看起来不带 sheet 前缀(形如 `$T$1:$T$3`),如果要把读出来的 range 反过来写回 `--source-range`**必须自己重新补上 sheet 前缀**,否则会被拒。
>
> ⚠️ **`--ranges` 类批量 flag 的 sheet 前缀必须「裸写」**——`+cells-batch-set-style` / `+cells-batch-clear` / `+dropdown-update` / `+dropdown-delete` 的 `--ranges` 解析器不接受引号:表名含点或空格(如 `2025.9`、`一月份`)也直接写 `2025.9!A1`,写成 `'2025.9'!A1` 会被当成表名一部分、报 `sheet not found`。**但 `--source-range`、透视表 `--source`、`--range` 走 A1 标准**sheet 名带单引号(如 `'Sheet1'!A1:B2`)是标准写法、裸写也接受,回读统一返回带引号形式——别把 `--ranges` 的裸写要求套到这些 flag 上。
> ⚠️ **`--ranges` 类批量 flag 的 sheet 前缀必须「裸写」**——`+cells-batch-clear` / `+dropdown-update` / `+dropdown-delete` 的 `--ranges` 解析器不接受引号:表名含点或空格(如 `2025.9`、`一月份`)也直接写 `2025.9!A1`,写成 `'2025.9'!A1` 会被当成表名一部分、报 `sheet not found`。**但 `--source-range`、透视表 `--source`、`--range` 走 A1 标准**sheet 名带单引号(如 `'Sheet1'!A1:B2`)是标准写法、裸写也接受,回读统一返回带引号形式——别把 `--ranges` 的裸写要求套到这些 flag 上。
`+dropdown-update`(多 range 批量更新)的所有 flag 语义与 `+dropdown-set` 完全一致;只是目标 `--ranges` 由单值变成 JSON 数组(每项带 sheet 前缀),同一份选项 + 配色应用到所有 range。
@@ -259,8 +272,9 @@ _公共四件套 · 系统:`--dry-run`_
| Flag | Type | 必填 | 说明 |
| --- | --- | --- | --- |
| `--range` | string | required | 写入区域A1 格式) |
| `--cells` | string + File + Stdin复合 JSON | required | JSON2D 数组 `[[{cell},...],...]`,维度与 `--range` 完全一致;每个 cell 可含 `value` / `formula` / `cell_styles` / `note` / `rich_text`(含 `type="embed-image"` 单元格嵌图)等,完整字段跑 `--print-schema` |
| `--range` | string | xor | 写入区域A1 格式)。与 `--writes` 二选一(单区域用 --range+--cells多区域用 --writes |
| `--cells` | string + File + Stdin复合 JSON | xor | JSON2D 数组 `[[{cell},...],...]`,维度与 `--range` 完全一致;每个 cell 可含 `value` / `formula` / `cell_styles` / `note` / `rich_text`(含 `type="embed-image"` 单元格嵌图)等,完整字段跑 `--print-schema` |
| `--writes` | string + File + Stdin复合 JSON | xor | 多区域写入 JSON 数组(最多 100 项),每项 `{sheet_name\|sheet_id, range, cells}`——**sheet 定位必须写在每项里**(与 +batch-update 子操作、+styles-put 项同惯例,不认顶层 --sheet-namecells 结构同 `--cells`(二维数组,可逐格带 cell_styles/border_styles。整批展开为**单次原子批量提交**,支持跨 sheet典型场景批量修复散布多处的公式、跨表同构写入——不要为此拼 +batch-update 的 --operations。与 `--range`+`--cells` 二选一;范围级统一样式不在此做,写完接 +styles-put |
| `--allow-overwrite` | bool | optional | 允许覆盖非空 cell默认 true设为 false 时遇非空 cell 报错 |
| `--max-cells` | int | optional | 防爆,默认 50000隐藏 flag不在 `--help` 列出,但可正常传入) |
| `--copy-to-range` | string | optional | 复制范围A1 表示法):把 --range 中 --cells 写入的内容(值/公式/样式,取决于实际传入字段)复制到该区域,公式引用自动平移(如 C2=B2 → C3=B3。适合先写一行/一块模板再扩展填充整列/整区域(如 --range A1:G1 写模板、--copy-to-range A1:G100 填充 100 行)。支持整行 3:6、整列 C:E、到列尾 D3:D、到行尾 D3:3支持英文逗号分隔多个目标区域如 C1:D2,E5:F6 |
@@ -283,7 +297,7 @@ _公共四件套 · 系统:`--dry-run`_
| `--vertical-alignment` | string | optional | 垂直对齐(可选值:`top` / `middle` / `bottom` |
| `--word-wrap` | string | optional | 换行策略(可选值:`overflow` / `auto-wrap` / `word-clip` |
| `--number-format` | string | optional | 数字格式(例:文本 `@`、数字 `0.00`、货币 `$#,##0.00`、日期 `mm/dd/yyyy` |
| `--border-styles` | string + File + Stdin复合 JSON | optional | 边框配置 JSON`{ top: {style,color,weight}, bottom: ..., left: ..., right: ... }`4 方向结构相同 |
| `--border-styles` | string + File + Stdin复合 JSON | optional | 边框配置 JSON`{ top: {style,weight,color}, bottom: ..., left: ..., right: ... }`4 方向结构相同。style = 线型solid\|dashed\|dotted\|double\|noneweight = 粗细thin\|medium\|thick —— 字符串不是像素数字color = 十六进制如 #000000`{ all: {...} }` 一次设置四边。边框只有这一个 flag不存在 --border-all / --border-top / --border-color |
### `+cells-set-image`
@@ -346,6 +360,16 @@ _【维度】行列数必须与 range 完全一致:'A1:C2'→[[_,_,_],[_,_,_]]
- `multiple_values` (array<object>?) — 多值内容,用于支持多选的列表验证单元格 each: { value: oneOf, format?: string }
- `data_validation` (object?) — 数据验证配置 { type: enum, items?: array<string>, range?: string, operator?: enum, values?: array<oneOf>, …共 9 项 }
### `+cells-set` `--writes`
_多区域写入项数组(最多 100 项),整批单次原子提交;支持跨 sheet_
**数组项**(类型 object
- `sheet_id` (string?) — 目标子表 reference_id与 sheet_name 二选一,必须写在每一项里(不认顶层 sheet 定位)
- `sheet_name` (string?) — 目标子表名;与 sheet_id 二选一,必须写在每一项里
- `range` (string) — A1 矩形范围,行列维度必须与 cells 严格一致(同 --range
- `cells` (array) — 二维单元格数组,结构同 --cellsvalue / formula / cell_styles / border_styles 等,见 set_cell_…
### `+cells-set-style` `--border-styles`
_单元格边框配置,含 top/bottom/left/right 四个方向,每个方向的结构相同(见 top_
@@ -383,10 +407,11 @@ _一个或多个子表的 typed 数据,每个数组元素写入一张子表;
**数组项**(类型 object
- `cell_merges` (array<object>?) — 单元格合并操作数组range 使用 A1 单元格范围merge_type 默认 all each: { merge_type?: enum, range: string }
- `cell_styles` (array<object>?) — 单元格样式操作数组;每项用 A1 单元格 range 指定范围,字段名与 +cells-set-style 对齐 each: { background_color?: string, border_styles?: object, font_color?: string, font_family?: string, font_line?: enum, …共 13 项 }
- `col_sizes` (array<object>?) — 列宽操作数组range 使用列范围如 A:Ctype 为 pixel/standardpixel 需要 size each: { range: string, size?: number, type: enum }
- `cell_styles` (array<object>?) — 单元格样式操作数组;每项用 A1 单元格 range 指定范围,字段名与 +cells-set-style 对齐 each: { background_color?: string, border?: object, border_styles?: object, font_color?: string, font_family?: string, …共 14 项 }
- `col_sizes` (array<object>?) — 列宽操作数组range 使用列范围如 A:C给 sizepx即像素列宽type 可省略);type 为 standard 时不带 size each: { range: string, size?: number, type?: enum }
- `freeze` (object?) — 冻结行列rows = 冻结前 N 行cols = 冻结前 N 列0 或省略 = 该维度不冻结) { cols?: integer, rows?: integer }
- `name` (string) — 子表名
- `row_sizes` (array<object>?) — 行高操作数组range 使用行范围如 1:3type 为 pixel/standard/autopixel 需要 size each: { range: string, size?: number, type: enum }
- `row_sizes` (array<object>?) — 行高操作数组range 使用行范围如 1:3给 sizepx即像素行高type 可省略);type 为 standard/auto 时不带 size each: { range: string, size?: number, type?: enum }
## Examples
@@ -401,7 +426,7 @@ _一个或多个子表的 typed 数据,每个数组元素写入一张子表;
| 只改**已有 cell 的样式**,不动 value/formula | `+cells-set-style` | `+cells-set`(会触发不必要的值写入) |
| 把**单张图片嵌入**到某个 cell | `+cells-set-image` | `+cells-set`(参数更繁琐) |
| **插行/列 + 写入** 这种多步组合,且要原子 | `+batch-update`(见 lark-sheets-batch-update | 多次独立 `+cells-set`(非原子;插入会扰动后续 range |
| 在**多个不连续 range** 上应用同一组样式 | `+cells-batch-set-style`见 lark-sheets-batch-update | 多次 `+cells-set-style`(非原子) |
| 在**多个不连续 range** 上应用同一组样式 | `+styles-put`cell_styles 多项即多区域,见 lark-sheets-styles-put | 多次 `+cells-set-style`(非原子) |
### `+cells-set`
@@ -511,6 +536,8 @@ lark-cli sheets +csv-put --spreadsheet-token shtXXX --sheet-id "$SID" \
python export.py | lark-cli sheets +table-put --url "<表URL>" --sheets -
# 某 sheet 带 "mode":"append" 追加到已有数据末尾、默认不重复表头
lark-cli sheets +table-put --spreadsheet-token "<token>" --sheets @payload.json
# --sheets 与 --styles 都是大 JSON 时stdin 每次调用只能给一个 flag一个走 -、另一个走 @cwd 相对路径
lark-cli sheets +table-put --url "<表URL>" --sheets - --styles @styles.json < sheets.json
```
每个 sheet 还可带 `"allow_overwrite": false`(遇非空拒写、保护原数据)、`"header": false`(只写数据不写表头)。完整字段跑 `+table-put --print-schema --flag-name sheets`

View File

@@ -0,0 +1,539 @@
#!/usr/bin/env python3
"""Detect occupied subtable regions in a Lark sheet."""
from __future__ import annotations
import argparse
import csv
import io
import re
from collections import deque
from dataclasses import dataclass
from typing import Any
from lark_sheet_range import RangeBounds, col_to_index, format_range, index_to_col, parse_range, range_union
from lark_sheet_read_cli import (
LarkCliError,
add_spreadsheet_args,
emit_error,
emit_success,
envelope_data,
resolve_target_sheets,
run_sheets,
sheet_identifier,
sheet_locator,
sheet_title,
)
ACTION = "detect_subtables"
ROW_PREFIX_RE = re.compile(r"^\[row=(\d+)\]\s?(.*)$")
MAX_EXTERNAL_MERGE_ANCHOR_CHECKS = 10
@dataclass
class CsvGrid:
row_numbers: list[int]
col_letters: list[str]
values: list[list[str]]
row_numbers_inferred: bool = False
@dataclass
class Component:
bounds: RangeBounds
occupied_count: int
def parse_annotated_csv(
text: str,
col_indices: list[str] | None = None,
row_indices: list[int] | None = None,
source_range: str | None = None,
) -> CsvGrid:
row_numbers: list[int] = []
values: list[list[str]] = []
max_cols = 0
lines = (text or "").splitlines()
row_numbers_inferred = False
has_authoritative_rows = isinstance(row_indices, list) and len(row_indices) > 0
if any(ROW_PREFIX_RE.match(line) for line in lines):
records = []
current_lines: list[str] | None = None
current_row_number: int | None = None
for line in lines:
match = ROW_PREFIX_RE.match(line)
if match:
if current_lines is not None and current_row_number is not None:
records.append("\n".join(current_lines))
row_numbers.append(current_row_number)
current_row_number = int(match.group(1))
current_lines = [match.group(2)]
elif current_lines is not None:
current_lines.append(line)
if current_lines is not None and current_row_number is not None:
records.append("\n".join(current_lines))
row_numbers.append(current_row_number)
for record in records:
parsed = next(csv.reader([record]))
values.append(parsed)
max_cols = max(max_cols, len(parsed))
else:
reader = csv.reader(io.StringIO(text or ""))
fallback_start = 1
if source_range:
fallback_start = parse_range(
source_range,
max_row=1_048_576,
max_col=18_278,
).start_row
for offset, row in enumerate(reader):
row_num = None
if has_authoritative_rows and offset < len(row_indices):
try:
row_num = int(row_indices[offset])
except (TypeError, ValueError):
pass
if row_num is None:
row_numbers_inferred = True
row_numbers.append(row_num if row_num is not None else fallback_start + offset)
values.append(row)
max_cols = max(max_cols, len(row))
if col_indices:
col_letters = [str(col) for col in col_indices[:max_cols]]
while len(col_letters) < max_cols:
next_col = col_to_index(col_letters[-1]) + 1 if col_letters else len(col_letters) + 1
col_letters.append(index_to_col(next_col))
else:
col_letters = [index_to_col(i) for i in range(1, max_cols + 1)]
for row in values:
row.extend([""] * (len(col_letters) - len(row)))
inferred = bool(values) and not any(ROW_PREFIX_RE.match(line) for line in lines) and (
row_numbers_inferred or not has_authoritative_rows
)
return CsvGrid(
row_numbers=row_numbers,
col_letters=col_letters,
values=values,
row_numbers_inferred=inferred,
)
def _merged_ranges(layout: dict[str, Any]) -> list[str]:
merges = layout.get("merged_cells") or layout.get("merges") or []
result = []
for item in merges:
if isinstance(item, str):
result.append(item)
elif isinstance(item, dict):
value = item.get("range") or item.get("a1_range") or item.get("range_ref")
if isinstance(value, str):
result.append(value)
return result
def _scan_bounds(grid: CsvGrid) -> RangeBounds | None:
col_numbers = [col_to_index(col) for col in grid.col_letters]
if grid.row_numbers and grid.col_letters:
return RangeBounds(
min(grid.row_numbers),
min(col_numbers),
max(grid.row_numbers),
max(col_numbers),
)
return None
def _external_merge_anchors(grid: CsvGrid, layout: dict[str, Any]) -> dict[str, str]:
scan_bounds = _scan_bounds(grid)
if scan_bounds is None:
return {}
result = {}
for merge_ref in _merged_ranges(layout):
try:
bounds = parse_range(merge_ref)
except ValueError:
continue
intersects = not (
bounds.end_row < scan_bounds.start_row
or bounds.start_row > scan_bounds.end_row
or bounds.end_col < scan_bounds.start_col
or bounds.start_col > scan_bounds.end_col
)
anchor_in_scan = (
scan_bounds.start_row <= bounds.start_row <= scan_bounds.end_row
and scan_bounds.start_col <= bounds.start_col <= scan_bounds.end_col
)
if intersects and not anchor_in_scan:
result[merge_ref] = format_range(
bounds.start_row, bounds.start_col, bounds.start_row, bounds.start_col
)
return result
def _has_value(grid: CsvGrid) -> bool:
return any(value.strip() for row in grid.values for value in row)
def build_occupancy(
grid: CsvGrid,
layout: dict[str, Any],
*,
confirmed_external_merges: set[str] | None = None,
) -> set[tuple[int, int]]:
col_numbers = [col_to_index(col) for col in grid.col_letters]
occupied: set[tuple[int, int]] = set()
for row_idx, row_num in enumerate(grid.row_numbers):
for col_idx, value in enumerate(grid.values[row_idx]):
if value.strip():
occupied.add((row_num, col_numbers[col_idx]))
scan_bounds = _scan_bounds(grid)
for merge_ref in _merged_ranges(layout):
try:
bounds = parse_range(merge_ref)
except ValueError:
continue
if scan_bounds is None:
continue
anchor_in_scan = (
scan_bounds.start_row <= bounds.start_row <= scan_bounds.end_row
and scan_bounds.start_col <= bounds.start_col <= scan_bounds.end_col
)
if anchor_in_scan and (bounds.start_row, bounds.start_col) not in occupied:
continue
if not anchor_in_scan and merge_ref not in (confirmed_external_merges or set()):
continue
sr = max(bounds.start_row, scan_bounds.start_row)
er = min(bounds.end_row, scan_bounds.end_row)
sc = max(bounds.start_col, scan_bounds.start_col)
ec = min(bounds.end_col, scan_bounds.end_col)
if sr > er or sc > ec:
continue
for row in range(sr, er + 1):
for col in range(sc, ec + 1):
occupied.add((row, col))
return occupied
def _raw_components(
occupied: set[tuple[int, int]],
*,
adjacent_rows: dict[int, set[int]] | None = None,
) -> list[Component]:
remaining = set(occupied)
components = []
while remaining:
start = remaining.pop()
queue = deque([start])
cells = [start]
while queue:
row, col = queue.popleft()
vertical_rows = adjacent_rows.get(row, set()) if adjacent_rows else {row - 1, row + 1}
neighbors = [(neighbor_row, col) for neighbor_row in vertical_rows]
neighbors.extend(((row, col - 1), (row, col + 1)))
for neighbor in neighbors:
if neighbor in remaining:
remaining.remove(neighbor)
queue.append(neighbor)
cells.append(neighbor)
rows = [cell[0] for cell in cells]
cols = [cell[1] for cell in cells]
components.append(
Component(
RangeBounds(min(rows), min(cols), max(rows), max(cols)),
len(cells),
)
)
return components
def _box_gap_mergeable(a: RangeBounds, b: RangeBounds, gap_rows: int, gap_cols: int) -> bool:
cols_overlap = not (a.end_col < b.start_col or b.end_col < a.start_col)
rows_overlap = not (a.end_row < b.start_row or b.end_row < a.start_row)
vertical_gap = max(b.start_row - a.end_row - 1, a.start_row - b.end_row - 1, 0)
horizontal_gap = max(b.start_col - a.end_col - 1, a.start_col - b.end_col - 1, 0)
return (cols_overlap and vertical_gap <= gap_rows) or (
rows_overlap and horizontal_gap <= gap_cols
)
def merge_components(
components: list[Component], *, gap_rows: int = 1, gap_cols: int = 0
) -> list[Component]:
merged = components[:]
changed = True
while changed:
changed = False
next_components: list[Component] = []
used = [False] * len(merged)
for i, comp in enumerate(merged):
if used[i]:
continue
current = Component(comp.bounds, comp.occupied_count)
used[i] = True
for j in range(i + 1, len(merged)):
if used[j]:
continue
other = merged[j]
if _box_gap_mergeable(current.bounds, other.bounds, gap_rows, gap_cols):
current = Component(
range_union(current.bounds, other.bounds),
current.occupied_count + other.occupied_count,
)
used[j] = True
changed = True
next_components.append(current)
merged = next_components
return merged
def _row_values(grid: CsvGrid, bounds: RangeBounds, row_num: int) -> list[str]:
if row_num not in grid.row_numbers:
return []
row = grid.values[grid.row_numbers.index(row_num)]
values = []
for col_idx, col_letter in enumerate(grid.col_letters):
col_num = col_to_index(col_letter)
if bounds.start_col <= col_num <= bounds.end_col:
values.append(row[col_idx] if col_idx < len(row) else "")
return values
def header_candidates(grid: CsvGrid, bounds: RangeBounds) -> list[int]:
candidates = []
for row in range(bounds.start_row, min(bounds.end_row, bounds.start_row + 4) + 1):
values = _row_values(grid, bounds, row)
non_empty = [value for value in values if value.strip()]
if len(non_empty) >= max(1, min(2, bounds.col_count)):
candidates.append(row)
return candidates
def kind_guess(bounds: RangeBounds, density: float) -> str:
if bounds.row_count >= 3 and bounds.col_count >= 2 and density >= 0.25:
return "data_table"
if bounds.row_count <= 2 or bounds.col_count <= 1:
return "note_or_label"
if density < 0.25:
return "sparse_block"
return "summary_block"
def summarize_components(grid: CsvGrid, components: list[Component], min_cells: int) -> list[dict[str, Any]]:
result = []
for idx, comp in enumerate(
sorted(components, key=lambda item: (item.bounds.start_row, item.bounds.start_col)),
start=1,
):
if comp.occupied_count < min_cells:
continue
area = comp.bounds.row_count * comp.bounds.col_count
density = comp.occupied_count / area if area else 0
samples = []
for row in range(comp.bounds.start_row, min(comp.bounds.end_row, comp.bounds.start_row + 2) + 1):
samples.append(_row_values(grid, comp.bounds, row))
result.append(
{
"id": f"T{idx}",
"range": format_range(
comp.bounds.start_row,
comp.bounds.start_col,
comp.bounds.end_row,
comp.bounds.end_col,
),
"rows": comp.bounds.row_count,
"cols": comp.bounds.col_count,
"occupied_cells": comp.occupied_count,
"density": round(density, 4),
"header_candidates": header_candidates(grid, comp.bounds),
"kind_guess": kind_guess(comp.bounds, density),
"sample": samples,
}
)
return result
def detect_subtables(args) -> tuple[dict[str, Any], list[str]]:
warnings: list[str] = []
workbook = envelope_data(
run_sheets(
"+workbook-info",
url=args.url,
spreadsheet_token=args.spreadsheet_token,
timeout=args.timeout,
)
)
sheet = resolve_target_sheets(
workbook,
sheet_id=args.sheet_id,
sheet_name=args.sheet_name,
require_one=True,
)[0]
sid = sheet_identifier(sheet)
title = sheet_title(sheet)
locator = sheet_locator(sheet)
col_count = min(int(sheet.get("column_count") or args.max_scan_cols), args.max_scan_cols)
row_count = min(int(sheet.get("row_count") or args.max_scan_rows), args.max_scan_rows)
scan_range = args.range or f"A1:{index_to_col(max(1, col_count))}{max(1, row_count)}"
if not args.range:
if int(sheet.get("column_count") or 0) > args.max_scan_cols:
warnings.append(f"scan clipped to first {args.max_scan_cols} columns")
if int(sheet.get("row_count") or 0) > args.max_scan_rows:
warnings.append(f"scan clipped to first {args.max_scan_rows} rows")
layout = envelope_data(
run_sheets(
"+sheet-info",
url=args.url,
spreadsheet_token=args.spreadsheet_token,
**locator,
flags={"include": "merges,hidden_rows,hidden_cols"},
timeout=args.timeout,
)
)
csv_data = envelope_data(
run_sheets(
"+csv-get",
url=args.url,
spreadsheet_token=args.spreadsheet_token,
**locator,
flags={
"range": scan_range,
"max_chars": args.max_chars,
"skip_hidden": True if args.skip_hidden else None,
},
timeout=args.timeout,
)
)
actual_range = str(csv_data.get("actual_range") or scan_range)
if csv_data.get("has_more"):
raise LarkCliError(
f"+csv-get truncated the scan range at {actual_range}; narrow --range before detecting subtables"
)
grid = parse_annotated_csv(
csv_data.get("annotated_csv", ""),
csv_data.get("col_indices"),
csv_data.get("row_indices"),
actual_range,
)
if grid.row_numbers_inferred:
warnings.append("CSV row numbers were inferred from the requested range")
hidden_rows_raw = layout.get("hidden_rows") or []
hidden_row_indexes = {
int(value) + 1
for value in hidden_rows_raw
if isinstance(value, (int, str)) and str(value).isdigit()
}
hidden_columns_raw = layout.get("hidden_cols") or layout.get("hidden_columns") or []
hidden_col_letters = set()
for value in hidden_columns_raw if isinstance(hidden_columns_raw, list) else []:
if isinstance(value, str) and value.isalpha():
hidden_col_letters.add(value.upper())
elif isinstance(value, (int, str)) and str(value).isdigit():
hidden_col_letters.add(index_to_col(int(value) + 1))
hidden_rows = sorted(row for row in grid.row_numbers if row in hidden_row_indexes)
hidden_columns = [col for col in grid.col_letters if col.upper() in hidden_col_letters]
if hidden_rows or hidden_columns:
warnings.append("scan includes hidden rows or columns; pass --skip-hidden to exclude them")
confirmed_external_merges = set()
external_merge_anchors = list(_external_merge_anchors(grid, layout).items())
if len(external_merge_anchors) > MAX_EXTERNAL_MERGE_ANCHOR_CHECKS:
warnings.append(
f"skipped confirmation for {len(external_merge_anchors) - MAX_EXTERNAL_MERGE_ANCHOR_CHECKS} "
f"external merge anchors (limit: {MAX_EXTERNAL_MERGE_ANCHOR_CHECKS})"
)
for merge_ref, anchor in external_merge_anchors[:MAX_EXTERNAL_MERGE_ANCHOR_CHECKS]:
try:
anchor_data = envelope_data(
run_sheets(
"+csv-get",
url=args.url,
spreadsheet_token=args.spreadsheet_token,
**locator,
flags={
"range": anchor,
"max_chars": 1024,
"skip_hidden": True if args.skip_hidden else None,
},
timeout=args.timeout,
)
)
anchor_grid = parse_annotated_csv(
anchor_data.get("annotated_csv", ""),
anchor_data.get("col_indices"),
anchor_data.get("row_indices"),
anchor,
)
if _has_value(anchor_grid):
confirmed_external_merges.add(merge_ref)
except LarkCliError as exc:
warnings.append(f"could not confirm merge anchor {anchor}: {exc}")
occupied = build_occupancy(
grid,
layout,
confirmed_external_merges=confirmed_external_merges,
)
adjacent_rows = None
if args.skip_hidden:
adjacent_rows = {}
for previous, current in zip(grid.row_numbers, grid.row_numbers[1:]):
adjacent_rows.setdefault(previous, set()).add(current)
adjacent_rows.setdefault(current, set()).add(previous)
raw_components = _raw_components(occupied, adjacent_rows=adjacent_rows)
if len(raw_components) > args.max_merge_components:
warnings.append(
f"skipped gap-based component merging for {len(raw_components)} components "
f"(limit: {args.max_merge_components})"
)
components = raw_components
else:
components = merge_components(
raw_components,
gap_rows=args.gap_rows,
gap_cols=args.gap_cols,
)
subtables = summarize_components(grid, components, args.min_cells)
return {
"sheet_id": sid,
"sheet": title,
"scan_range": scan_range,
"actual_range": actual_range,
"visibility": {
"skip_hidden": args.skip_hidden,
"hidden_rows_in_range": hidden_rows,
"hidden_columns_in_range": hidden_columns,
},
"subtables": subtables,
}, warnings
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_spreadsheet_args(parser, require_sheet=True, allow_sheet=True)
parser.add_argument("--range")
parser.add_argument("--max-scan-rows", type=int, default=5000)
parser.add_argument("--max-scan-cols", type=int, default=200)
parser.add_argument("--gap-rows", type=int, default=1)
parser.add_argument("--gap-cols", type=int, default=0)
parser.add_argument("--min-cells", type=int, default=2)
parser.add_argument("--max-merge-components", type=int, default=2000)
parser.add_argument("--max-chars", type=int, default=25000)
parser.add_argument("--skip-hidden", action="store_true")
parser.add_argument("--timeout", type=int, default=60)
args = parser.parse_args()
try:
data, warnings = detect_subtables(args)
except (LarkCliError, ValueError, TypeError) as exc:
emit_error(ACTION, str(exc))
emit_success(ACTION, data, warnings)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,168 @@
#!/usr/bin/env python3
"""Inspect a Lark spreadsheet and emit a compact workbook profile."""
from __future__ import annotations
import argparse
from typing import Any
from lark_sheet_range import index_to_col
from lark_sheet_read_cli import (
LarkCliError,
add_spreadsheet_args,
emit_error,
emit_success,
envelope_data,
resolve_target_sheets,
run_sheets,
sheet_identifier,
sheet_locator,
sheet_title,
)
ACTION = "inspect_workbook"
LAYOUT_INCLUDE = "merges,row_heights,col_widths,hidden_rows,hidden_cols,groups,frozen"
def _sheet_summary(sheet: dict[str, Any]) -> dict[str, Any]:
return {
"sheet_id": sheet_identifier(sheet),
"title": sheet_title(sheet),
"index": sheet.get("index"),
"row_count": sheet.get("row_count"),
"column_count": sheet.get("column_count"),
"is_hidden": sheet.get("is_hidden"),
"merged_cells_count": sheet.get("merged_cells_count"),
"chart_count": sheet.get("chart_count"),
"pivot_table_count": sheet.get("pivot_table_count"),
"float_image_count": sheet.get("float_image_count"),
}
def _list_count(value: Any) -> int:
return len(value) if isinstance(value, list) else 0
def _layout_summary(layout: dict[str, Any]) -> dict[str, Any]:
"""Retain layout signals without serializing unbounded per-cell metadata."""
merges = layout.get("merged_cells") or layout.get("merges") or []
groups = layout.get("groups") if isinstance(layout.get("groups"), dict) else {}
row_groups = layout.get("row_groups") or groups.get("rows", [])
col_groups = layout.get("column_groups") or groups.get("columns", [])
return {
"merge_count": _list_count(merges),
"row_heights_count": _list_count(layout.get("row_heights")),
"column_widths_count": _list_count(layout.get("col_widths")),
"hidden_rows_count": _list_count(layout.get("hidden_rows")),
"hidden_columns_count": _list_count(
layout.get("hidden_cols") or layout.get("hidden_columns")
),
"row_groups_count": _list_count(row_groups),
"column_groups_count": _list_count(col_groups),
"frozen": layout.get("frozen"),
}
def inspect_workbook(args) -> tuple[dict[str, Any], list[str]]:
warnings: list[str] = []
workbook = envelope_data(
run_sheets(
"+workbook-info",
url=args.url,
spreadsheet_token=args.spreadsheet_token,
timeout=args.timeout,
)
)
target_sheets = resolve_target_sheets(
workbook,
sheet_id=args.sheet_id,
sheet_name=args.sheet_name,
)
if args.max_sheets < 1:
raise LarkCliError("--max-sheets must be at least 1")
inspect_count = len(target_sheets)
if not args.sheet_id and not args.sheet_name:
inspect_count = min(len(target_sheets), args.max_sheets)
if inspect_count < len(target_sheets):
warnings.append(
f"layout and preview skipped for {len(target_sheets) - inspect_count} sheets; "
f"pass --sheet-id or --sheet-name to inspect one"
)
profiles = []
for position, sheet in enumerate(target_sheets):
sid = sheet_identifier(sheet)
title = sheet_title(sheet)
profile = _sheet_summary(sheet)
if position >= inspect_count:
profiles.append(profile)
continue
locator = sheet_locator(sheet)
col_count = int(sheet.get("column_count") or args.max_preview_cols)
preview_cols = min(col_count, args.max_preview_cols)
if col_count > args.max_preview_cols:
warnings.append(
f"{title or sid}: preview clipped to first {args.max_preview_cols} columns"
)
end_col = index_to_col(max(1, preview_cols))
preview_range = f"A1:{end_col}{args.preview_rows}"
layout = envelope_data(
run_sheets(
"+sheet-info",
url=args.url,
spreadsheet_token=args.spreadsheet_token,
**locator,
flags={"include": LAYOUT_INCLUDE},
timeout=args.timeout,
)
)
preview = envelope_data(
run_sheets(
"+csv-get",
url=args.url,
spreadsheet_token=args.spreadsheet_token,
**locator,
flags={"range": preview_range, "max_chars": args.max_chars},
timeout=args.timeout,
)
)
if preview.get("has_more"):
warnings.append(f"{title or sid}: preview range {preview_range} was truncated")
profiles.append(
{
**profile,
"layout": _layout_summary(layout),
"preview": {
"range": preview_range,
"current_region": preview.get("current_region"),
"row_indices": preview.get("row_indices"),
"col_indices": preview.get("col_indices"),
"annotated_csv": preview.get("annotated_csv"),
"has_more": preview.get("has_more"),
},
}
)
return {"sheet_count": len(target_sheets), "sheets": profiles}, warnings
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_spreadsheet_args(parser, require_sheet=False, allow_sheet=True)
parser.add_argument("--preview-rows", type=int, default=15)
parser.add_argument("--max-preview-cols", type=int, default=100)
parser.add_argument("--max-chars", type=int, default=8000)
parser.add_argument("--max-sheets", type=int, default=3)
parser.add_argument("--timeout", type=int, default=60)
args = parser.parse_args()
try:
data, warnings = inspect_workbook(args)
except (LarkCliError, ValueError, TypeError) as exc:
emit_error(ACTION, str(exc))
emit_success(ACTION, data, warnings)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,518 @@
#!/usr/bin/env python3
"""Profile a candidate table range in a Lark sheet."""
from __future__ import annotations
import argparse
import re
from typing import Any
from lark_sheet_range import col_to_index, format_range, index_to_col, parse_range
from lark_sheet_read_cli import (
LarkCliError,
add_spreadsheet_args,
emit_error,
emit_success,
envelope_data,
run_sheets,
)
from lark_detect_subtables import CsvGrid, parse_annotated_csv
ACTION = "profile_table"
ERROR_VALUES = ("#VALUE!", "#DIV/0!", "#REF!", "#NAME?", "#NULL!", "#NUM!", "#N/A")
TOTAL_KEYWORDS = ("合计", "总计", "小计", "汇总", "累计")
TOTAL_EN_RE = re.compile(r"\b(?:grand total|subtotal|total)\b", re.IGNORECASE)
SIGNATURE_KEYWORDS = ("编制人", "审核人", "审批人", "负责人", "经理", "签名")
def _is_number(value: str) -> bool:
text = value.strip().replace(",", "")
if text.endswith("%"):
text = text[:-1]
try:
float(text)
return True
except ValueError:
return False
def _is_date_like(value: str) -> bool:
text = value.strip()
if re.match(r"^\d{4}[-/]\d{1,2}[-/]\d{1,2}(?:\s+\d{1,2}:\d{2}(:\d{2})?)?$", text):
return True
if re.match(r"^\d{8}$", text):
year = int(text[:4])
month = int(text[4:6])
day = int(text[6:8])
return 1900 <= year <= 2100 and 1 <= month <= 12 and 1 <= day <= 31
if re.match(r"^\d{6}$", text):
year = int(text[:4])
month = int(text[4:6])
return 1900 <= year <= 2100 and 1 <= month <= 12
return False
def _classify_value(value: str) -> str:
text = value.strip()
if not text:
return "empty"
if any(err in text for err in ERROR_VALUES):
return "error"
if re.match(r"^0\d+$", text) or re.match(r"^\d{11,}$", text):
return "string_id"
if _is_date_like(text):
return "date"
if _is_number(text):
return "number"
if text.lower() in {"true", "false", "yes", "no"}:
return "bool"
return "string"
def _row_values(grid: CsvGrid, row_index: int) -> list[str]:
return grid.values[row_index]
def _header_score(row: list[str]) -> tuple[int, int]:
non_empty = [value for value in row if value.strip()]
if not non_empty:
return 0, 0
strings = sum(1 for value in non_empty if _classify_value(value) in {"string", "string_id"})
data_like = sum(
1 for value in non_empty if _classify_value(value) in {"number", "date", "bool"}
)
return strings * 2 + len(non_empty) - data_like * 3, len(non_empty)
def _header_candidate_score(grid: CsvGrid, index: int) -> int:
score, _ = _header_score(grid.values[index])
following = grid.values[index + 1 : index + 4]
following_non_empty = [value for row in following for value in row if value.strip()]
following_data_like = sum(
1 for value in following_non_empty if _classify_value(value) in {"number", "date", "bool"}
)
# A schema row is usually followed by data-shaped values; use this as a
# small tie-breaker while preferring earlier candidates with equal evidence.
score += min(3, following_data_like)
return score - index // 2
def detect_header_row(grid: CsvGrid, scan_rows: int = 20) -> int | None:
best_row = None
best_score = None
for idx, row in enumerate(grid.values[:scan_rows]):
_, non_empty_count = _header_score(row)
if not non_empty_count:
continue
score = _header_candidate_score(grid, idx)
if best_score is None or score > best_score:
best_score = score
best_row = grid.row_numbers[idx]
return best_row
def _possible_multi_row_header(grid: CsvGrid, header_row: int | None) -> bool:
if header_row is None or header_row not in grid.row_numbers:
return False
header_index = grid.row_numbers.index(header_row)
if header_index + 1 >= len(grid.values):
return False
header_score, header_non_empty = _header_score(grid.values[header_index])
next_score, next_non_empty = _header_score(grid.values[header_index + 1])
if header_non_empty < 2 or next_non_empty < 2:
return False
return next_score >= max(4, (header_score * 3 + 3) // 4)
def _header_row_not_first(grid: CsvGrid, header_row: int | None) -> bool:
if header_row is None:
return False
first_non_empty = next(
(
row_num
for row_num, row in zip(grid.row_numbers, grid.values)
if any(value.strip() for value in row)
),
None,
)
return first_non_empty is not None and first_non_empty != header_row
def detect_special_rows(grid: CsvGrid, header_row: int | None) -> list[dict[str, Any]]:
specials = []
for idx, row in enumerate(grid.values):
row_num = grid.row_numbers[idx]
if header_row is not None and row_num <= header_row:
continue
joined = " ".join(value.strip() for value in row if value.strip())
if not joined:
specials.append({"row": row_num, "reason": "empty_row", "sample": ""})
continue
if any(keyword in joined for keyword in TOTAL_KEYWORDS) or TOTAL_EN_RE.search(joined):
specials.append({"row": row_num, "reason": "total_row", "sample": joined[:120]})
elif any(keyword in joined for keyword in SIGNATURE_KEYWORDS):
specials.append({"row": row_num, "reason": "signature_row", "sample": joined[:120]})
return specials
def _last_data_row(grid: CsvGrid, header_row: int | None, specials: list[dict[str, Any]]) -> int | None:
special_rows = {item["row"] for item in specials if item["reason"] != "empty_row"}
for idx in range(len(grid.row_numbers) - 1, -1, -1):
row_num = grid.row_numbers[idx]
if header_row is not None and row_num <= header_row:
continue
if row_num in special_rows:
continue
if any(value.strip() for value in grid.values[idx]):
return row_num
return None
def _column_values(grid: CsvGrid, col_index: int, start_row: int, end_row: int | None) -> list[str]:
values = []
for idx, row_num in enumerate(grid.row_numbers):
if row_num < start_row:
continue
if end_row is not None and row_num > end_row:
continue
row = grid.values[idx]
values.append(row[col_index] if col_index < len(row) else "")
return values
def _type_guess(type_counts: dict[str, int]) -> str:
non_empty_counts = {key: value for key, value in type_counts.items() if key != "empty" and value}
if not non_empty_counts:
return "empty"
if len(non_empty_counts) == 1:
return next(iter(non_empty_counts))
if "error" in non_empty_counts:
return "mixed_with_errors"
if "string_id" in non_empty_counts and set(non_empty_counts) <= {"string_id", "string"}:
return "string_id"
return "mixed"
def profile_columns(
grid: CsvGrid,
*,
header_row: int | None,
data_start_row: int,
data_end_row: int | None,
) -> list[dict[str, Any]]:
header_values = []
if header_row in grid.row_numbers:
header_values = _row_values(grid, grid.row_numbers.index(header_row))
profiles = []
for idx, col in enumerate(grid.col_letters):
name = ""
if idx < len(header_values):
name = header_values[idx].strip()
if not name:
name = f"unnamed_{col}"
values = _column_values(grid, idx, data_start_row, data_end_row)
type_counts: dict[str, int] = {}
examples = []
error_count = 0
for value in values:
value_type = _classify_value(value)
type_counts[value_type] = type_counts.get(value_type, 0) + 1
if value_type == "error":
error_count += 1
if value.strip() and len(examples) < 5:
examples.append(value)
non_empty = len(values) - type_counts.get("empty", 0)
warnings = []
if type_counts.get("string_id"):
warnings.append("long_numeric_like_id")
if error_count:
warnings.append("formula_or_value_errors")
if non_empty and type_counts.get("empty", 0) / len(values) > 0.5:
warnings.append("many_empty_cells")
if _type_guess(type_counts) == "mixed":
warnings.append("mixed_value_types")
profiles.append(
{
"name": name,
"col": col,
"non_empty": non_empty,
"empty": type_counts.get("empty", 0),
"type_guess": _type_guess(type_counts),
"type_distribution": type_counts,
"examples": examples,
"warnings": warnings,
}
)
return profiles
def _field_map(columns: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]:
result: dict[str, list[dict[str, Any]]] = {}
for column in columns:
name = column["name"]
result.setdefault(name, []).append(
{
"col": column["col"],
"type_guess": column["type_guess"],
"warnings": column["warnings"],
}
)
return result
def _risk_warnings(
*,
columns: list[dict[str, Any]],
special_rows: list[dict[str, Any]],
header_row: int | None,
data_range: str | None,
possible_multi_row_header: bool,
header_row_not_first: bool,
data_range_has_gaps: bool,
hidden_rows: list[int],
hidden_columns: list[str],
) -> list[str]:
warnings = {warning for column in columns for warning in column["warnings"]}
names = [column["name"] for column in columns]
if len(names) != len(set(names)):
warnings.add("duplicate_headers")
if any(name.startswith("unnamed_") for name in names):
warnings.add("unnamed_columns")
if header_row is None:
warnings.add("header_not_detected")
if data_range is None:
warnings.add("data_range_not_detected")
if any(item["reason"] != "empty_row" for item in special_rows):
warnings.add("special_rows_present")
if any(item["reason"] == "empty_row" for item in special_rows):
warnings.add("empty_rows_present")
if possible_multi_row_header:
warnings.add("possible_multi_row_header")
if header_row_not_first:
warnings.add("header_row_not_first")
if data_range_has_gaps:
warnings.add("data_range_has_gaps")
if hidden_rows:
warnings.add("hidden_rows_in_range")
if hidden_columns:
warnings.add("hidden_columns_in_range")
return sorted(warnings)
def _row_segments(row_numbers: list[int]) -> list[list[int]]:
if not row_numbers:
return []
segments = []
start = end = row_numbers[0]
for row in row_numbers[1:]:
if row == end + 1:
end = row
continue
segments.append([start, end])
start = end = row
segments.append([start, end])
return segments
def _write_hints(grid: CsvGrid, *, header_row: int | None, data_start: int, bounds) -> dict[str, Any]:
last_non_empty_col = None
for idx, col in enumerate(grid.col_letters):
if any(idx < len(row) and row[idx].strip() for row in grid.values):
last_non_empty_col = col_to_index(col)
safe_col_num = (last_non_empty_col + 1) if last_non_empty_col else bounds.start_col
safe_col = index_to_col(safe_col_num)
return {
"last_non_empty_col": index_to_col(last_non_empty_col) if last_non_empty_col else None,
"safe_append_col": safe_col,
"safe_append_header_cell": f"{safe_col}{header_row}" if header_row else None,
"safe_append_data_start_cell": f"{safe_col}{data_start}",
}
def profile_grid(
grid: CsvGrid,
source_range: str,
*,
skip_hidden: bool = False,
hidden_rows: list[int] | None = None,
hidden_columns: list[str] | None = None,
header_scan_rows: int = 20,
) -> dict[str, Any]:
max_row = max(grid.row_numbers, default=1)
max_col = max((col_to_index(col) for col in grid.col_letters), default=1)
bounds = parse_range(source_range, max_row=max_row, max_col=max_col)
header_row = detect_header_row(grid, header_scan_rows)
data_start = (header_row + 1) if header_row else bounds.start_row
specials = detect_special_rows(grid, header_row)
data_end = _last_data_row(grid, header_row, specials)
data_range = None
if data_end is not None and data_end >= data_start:
data_range = format_range(data_start, bounds.start_col, data_end, bounds.end_col)
columns = profile_columns(
grid,
header_row=header_row,
data_start_row=data_start,
data_end_row=data_end,
)
data_row_numbers = []
if data_end is not None and data_end >= data_start:
data_row_numbers = [
row for row in grid.row_numbers if data_start <= row <= data_end
]
data_row_segments = _row_segments(data_row_numbers)
data_range_has_gaps = bool(data_row_numbers) and (
data_row_numbers[0] != data_start or len(data_row_segments) > 1
)
data_rows = len(data_row_numbers)
hidden_rows = hidden_rows or []
hidden_columns = hidden_columns or []
possible_multi_row_header = _possible_multi_row_header(grid, header_row)
header_row_not_first = _header_row_not_first(grid, header_row)
return {
"summary": {
"range": source_range,
"header_row": header_row,
"data_range": data_range,
"data_rows": data_rows,
"data_row_segments": data_row_segments,
"column_count": len(columns),
"special_rows_count": len(specials),
},
"range": source_range,
"header_row": header_row,
"data_range": data_range,
"data_row_segments": data_row_segments,
"columns": columns,
"field_map": _field_map(columns),
"risk_warnings": _risk_warnings(
columns=columns,
special_rows=specials,
header_row=header_row,
data_range=data_range,
possible_multi_row_header=possible_multi_row_header,
header_row_not_first=header_row_not_first,
data_range_has_gaps=data_range_has_gaps,
hidden_rows=hidden_rows,
hidden_columns=hidden_columns,
),
"visibility": {
"skip_hidden": skip_hidden,
"hidden_rows_in_range": hidden_rows,
"hidden_columns_in_range": hidden_columns,
},
"write_hints": _write_hints(grid, header_row=header_row, data_start=data_start, bounds=bounds),
"special_rows": specials,
}
def _hidden_rows_and_columns(grid: CsvGrid, layout: dict[str, Any]) -> tuple[list[int], list[str]]:
def indexes(key: str) -> set[int]:
values = layout.get(key)
if not isinstance(values, list):
return set()
result = set()
for value in values:
try:
result.add(int(value) + 1) # +sheet-info uses zero-based indices.
except (TypeError, ValueError):
continue
return result
hidden_row_indexes = indexes("hidden_rows")
hidden_columns = layout.get("hidden_cols") or layout.get("hidden_columns") or []
hidden_column_letters = set()
for value in hidden_columns if isinstance(hidden_columns, list) else []:
if isinstance(value, str) and value.isalpha():
hidden_column_letters.add(value.upper())
else:
try:
hidden_column_letters.add(index_to_col(int(value) + 1))
except (TypeError, ValueError):
continue
rows = sorted(row for row in grid.row_numbers if row in hidden_row_indexes)
columns = [col for col in grid.col_letters if col.upper() in hidden_column_letters]
return rows, columns
def profile_table(args) -> tuple[dict[str, Any], list[str]]:
warnings = []
if args.header_scan_rows < 1:
raise ValueError("--header-scan-rows must be at least 1")
csv_data = envelope_data(
run_sheets(
"+csv-get",
url=args.url,
spreadsheet_token=args.spreadsheet_token,
sheet_id=args.sheet_id,
sheet_name=args.sheet_name,
flags={
"range": args.range,
"max_chars": args.max_chars,
"skip_hidden": True if args.skip_hidden else None,
},
timeout=args.timeout,
)
)
source_range = str(csv_data.get("actual_range") or args.range)
if csv_data.get("has_more"):
raise LarkCliError(
f"+csv-get truncated the requested range at {source_range}; narrow --range before profiling"
)
grid = parse_annotated_csv(
csv_data.get("annotated_csv", ""),
csv_data.get("col_indices"),
csv_data.get("row_indices"),
source_range,
)
if grid.row_numbers_inferred:
warnings.append("CSV row numbers were inferred from the requested range")
hidden_rows: list[int] = []
hidden_columns: list[str] = []
if not args.skip_hidden:
try:
layout = envelope_data(
run_sheets(
"+sheet-info",
url=args.url,
spreadsheet_token=args.spreadsheet_token,
sheet_id=args.sheet_id,
sheet_name=args.sheet_name,
flags={"include": "hidden_rows,hidden_cols"},
timeout=args.timeout,
)
)
hidden_rows, hidden_columns = _hidden_rows_and_columns(grid, layout)
except LarkCliError as exc:
warnings.append(f"hidden row/column detection unavailable: {exc}")
return profile_grid(
grid,
source_range,
skip_hidden=args.skip_hidden,
hidden_rows=hidden_rows,
hidden_columns=hidden_columns,
header_scan_rows=args.header_scan_rows,
), warnings
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__)
add_spreadsheet_args(parser, require_sheet=True, allow_sheet=True)
parser.add_argument("--range", required=True)
parser.add_argument("--max-chars", type=int, default=25000)
parser.add_argument("--header-scan-rows", type=int, default=20)
parser.add_argument("--skip-hidden", action="store_true")
parser.add_argument("--timeout", type=int, default=60)
args = parser.parse_args()
try:
data, warnings = profile_table(args)
except (LarkCliError, ValueError, TypeError) as exc:
emit_error(ACTION, str(exc))
emit_success(ACTION, data, warnings)
if __name__ == "__main__":
main()

View File

@@ -0,0 +1,174 @@
"""Range and coordinate helpers for Lark Sheet scripts."""
from __future__ import annotations
import re
from dataclasses import dataclass
CELL_RE = re.compile(r"^\$?([A-Za-z]+)\$?([1-9][0-9]*)$")
ROW_RE = re.compile(r"^\$?([1-9][0-9]*)$")
COLUMN_RE = re.compile(r"^\$?([A-Za-z]+)$")
@dataclass(frozen=True)
class RangeBounds:
start_row: int
start_col: int
end_row: int
end_col: int
@property
def row_count(self) -> int:
return self.end_row - self.start_row + 1
@property
def col_count(self) -> int:
return self.end_col - self.start_col + 1
def col_to_index(col: str) -> int:
value = 0
for char in col.strip().upper():
if not ("A" <= char <= "Z"):
raise ValueError(f"Invalid column: {col}")
value = value * 26 + (ord(char) - ord("A") + 1)
if value <= 0:
raise ValueError(f"Invalid column: {col}")
return value
def index_to_col(index: int) -> str:
if index < 1:
raise ValueError(f"Column index must be >= 1: {index}")
chars = []
n = index
while n:
n, rem = divmod(n - 1, 26)
chars.append(chr(ord("A") + rem))
return "".join(reversed(chars))
def parse_cell(cell_ref: str) -> tuple[int, int]:
match = CELL_RE.match(cell_ref.strip())
if not match:
raise ValueError(f"Invalid cell reference: {cell_ref}")
col, row = match.groups()
return int(row), col_to_index(col)
def _parse_endpoint(endpoint: str) -> tuple[str, int, int] | tuple[str, int]:
cell = CELL_RE.match(endpoint)
if cell:
col, row = cell.groups()
return "cell", int(row), col_to_index(col)
row = ROW_RE.match(endpoint)
if row:
return "row", int(row.group(1))
column = COLUMN_RE.match(endpoint)
if column:
return "column", col_to_index(column.group(1))
raise ValueError(f"Invalid A1 range endpoint: {endpoint}")
def parse_range(
range_ref: str,
*,
max_row: int | None = None,
max_col: int | None = None,
) -> RangeBounds:
"""Parse the A1 range forms accepted by ``+csv-get``.
Open-ended forms need the caller's actual returned grid dimensions. This
keeps generated ranges finite without guessing a spreadsheet-wide limit.
"""
ref = range_ref.strip()
if "!" in ref:
_, ref = ref.rsplit("!", 1)
if not ref:
raise ValueError(f"Invalid A1 range: {range_ref}")
parts = ref.split(":")
if len(parts) > 2:
raise ValueError(f"Invalid A1 range: {range_ref}")
start = _parse_endpoint(parts[0])
end = _parse_endpoint(parts[-1])
if len(parts) == 1:
if start[0] != "cell":
raise ValueError(f"A1 range must include a cell or ':' separator: {range_ref}")
_, row, col = start
return RangeBounds(row, col, row, col)
if start[0] == end[0] == "cell":
_, start_row, start_col = start
_, end_row, end_col = end
elif start[0] == end[0] == "row":
_, start_row = start
_, end_row = end
start_col = 1
if max_col is None:
raise ValueError(f"Range needs a maximum column: {range_ref}")
end_col = max_col
elif start[0] == end[0] == "column":
_, start_col = start
_, end_col = end
start_row = 1
if max_row is None:
raise ValueError(f"Range needs a maximum row: {range_ref}")
end_row = max_row
elif start[0] == "cell" and end[0] == "column":
_, start_row, start_col = start
_, end_col = end
if max_row is None:
raise ValueError(f"Range needs a maximum row: {range_ref}")
end_row = max(start_row, max_row)
elif start[0] == "cell" and end[0] == "row":
_, start_row, start_col = start
_, end_row = end
if max_col is None:
raise ValueError(f"Range needs a maximum column: {range_ref}")
end_col = max(start_col, max_col)
else:
raise ValueError(f"Invalid A1 range: {range_ref}")
return RangeBounds(min(start_row, end_row), min(start_col, end_col), max(start_row, end_row), max(start_col, end_col))
def format_cell(row: int, col: int) -> str:
if row < 1:
raise ValueError(f"Row must be >= 1: {row}")
return f"{index_to_col(col)}{row}"
def format_range(start_row: int, start_col: int, end_row: int, end_col: int) -> str:
bounds = RangeBounds(
min(start_row, end_row),
min(start_col, end_col),
max(start_row, end_row),
max(start_col, end_col),
)
start = format_cell(bounds.start_row, bounds.start_col)
end = format_cell(bounds.end_row, bounds.end_col)
return start if start == end else f"{start}:{end}"
def iter_cells(bounds: RangeBounds):
for row in range(bounds.start_row, bounds.end_row + 1):
for col in range(bounds.start_col, bounds.end_col + 1):
yield row, col
def ranges_intersect(a: RangeBounds, b: RangeBounds) -> bool:
return not (
a.end_row < b.start_row
or b.end_row < a.start_row
or a.end_col < b.start_col
or b.end_col < a.start_col
)
def range_union(a: RangeBounds, b: RangeBounds) -> RangeBounds:
return RangeBounds(
min(a.start_row, b.start_row),
min(a.start_col, b.start_col),
max(a.end_row, b.end_row),
max(a.end_col, b.end_col),
)

View File

@@ -0,0 +1,182 @@
"""Read-only Lark Sheet subset wrapper for the helper scripts."""
from __future__ import annotations
import json
import subprocess
import sys
from typing import Any
class LarkCliError(RuntimeError):
def __init__(self, message: str, *, cmd: list[str] | None = None):
super().__init__(message)
self.cmd = cmd or []
def add_spreadsheet_args(
parser,
*,
require_sheet: bool = False,
allow_sheet: bool = True,
) -> None:
spreadsheet = parser.add_mutually_exclusive_group(required=True)
spreadsheet.add_argument("--url")
spreadsheet.add_argument("--spreadsheet-token")
if allow_sheet:
sheet = parser.add_mutually_exclusive_group(required=require_sheet)
sheet.add_argument("--sheet-id")
sheet.add_argument("--sheet-name")
def _append_flag(cmd: list[str], name: str, value: Any) -> None:
flag = f"--{name.replace('_', '-')}"
if value is None:
return
if isinstance(value, bool):
cmd.append(flag if value else f"{flag}=false")
return
cmd.extend([flag, str(value)])
def run_sheets(
shortcut: str,
*,
url: str | None = None,
spreadsheet_token: str | None = None,
sheet_id: str | None = None,
sheet_name: str | None = None,
flags: dict[str, Any] | None = None,
timeout: int = 60,
) -> dict[str, Any]:
if bool(url) == bool(spreadsheet_token):
raise LarkCliError("Pass exactly one of --url or --spreadsheet-token")
if sheet_id and sheet_name:
raise LarkCliError("Pass only one of --sheet-id or --sheet-name")
cmd = ["lark-cli", "sheets", shortcut]
_append_flag(cmd, "url", url)
_append_flag(cmd, "spreadsheet_token", spreadsheet_token)
_append_flag(cmd, "sheet_id", sheet_id)
_append_flag(cmd, "sheet_name", sheet_name)
for key, value in (flags or {}).items():
_append_flag(cmd, key, value)
try:
completed = subprocess.run(
cmd,
capture_output=True,
text=True,
timeout=timeout,
check=False,
)
except FileNotFoundError as exc:
raise LarkCliError("lark-cli not found", cmd=cmd) from exc
except subprocess.TimeoutExpired as exc:
raise LarkCliError(f"lark-cli timed out after {timeout}s", cmd=cmd) from exc
if completed.returncode != 0:
detail = (completed.stderr or completed.stdout or "").strip()
raise LarkCliError(detail or f"lark-cli exited with {completed.returncode}", cmd=cmd)
try:
envelope = json.loads(completed.stdout)
except json.JSONDecodeError as exc:
snippet = completed.stdout[:500].replace("\n", "\\n")
raise LarkCliError(f"lark-cli stdout was not JSON: {snippet}", cmd=cmd) from exc
if isinstance(envelope, dict) and envelope.get("ok") is False:
raise LarkCliError(json.dumps(envelope, ensure_ascii=False), cmd=cmd)
if not isinstance(envelope, dict):
raise LarkCliError("lark-cli returned a non-object JSON payload", cmd=cmd)
return envelope
def envelope_data(envelope: dict[str, Any]) -> dict[str, Any]:
data = envelope.get("data")
return data if isinstance(data, dict) else envelope
def emit_success(action: str, data: dict[str, Any], warnings: list[str] | None = None) -> None:
print(
json.dumps(
{
"ok": True,
"engine": "lark",
"action": action,
"data": data,
"warnings": warnings or [],
},
ensure_ascii=False,
indent=2,
)
)
def emit_error(action: str, message: str, warnings: list[str] | None = None) -> None:
print(
json.dumps(
{
"ok": False,
"engine": "lark",
"action": action,
"error": message,
"warnings": warnings or [],
},
ensure_ascii=False,
indent=2,
)
)
sys.exit(1)
def sheet_title(sheet: dict[str, Any]) -> str:
return str(sheet.get("title") or sheet.get("sheet_name") or sheet.get("name") or "")
def sheet_identifier(sheet: dict[str, Any]) -> str:
return str(sheet.get("sheet_id") or sheet.get("id") or "")
def sheet_locator(sheet: dict[str, Any]) -> dict[str, str]:
sid = sheet_identifier(sheet)
if sid:
return {"sheet_id": sid}
title = sheet_title(sheet)
if title:
return {"sheet_name": title}
return {}
def extract_sheets(workbook_data: dict[str, Any]) -> list[dict[str, Any]]:
sheets = workbook_data.get("sheets")
if isinstance(sheets, list):
return [sheet for sheet in sheets if isinstance(sheet, dict)]
workbook = workbook_data.get("workbook")
if isinstance(workbook, dict) and isinstance(workbook.get("sheets"), list):
return [sheet for sheet in workbook["sheets"] if isinstance(sheet, dict)]
return []
def resolve_target_sheets(
workbook_data: dict[str, Any],
*,
sheet_id: str | None = None,
sheet_name: str | None = None,
require_one: bool = False,
) -> list[dict[str, Any]]:
sheets = extract_sheets(workbook_data)
if sheet_id:
matches = [sheet for sheet in sheets if sheet_identifier(sheet) == sheet_id]
elif sheet_name:
matches = [sheet for sheet in sheets if sheet_title(sheet) == sheet_name]
else:
matches = sheets
if require_one:
if len(matches) == 1:
return matches
if not matches:
raise LarkCliError("No matching sheet found")
raise LarkCliError("Multiple sheets matched; pass --sheet-id or --sheet-name")
return matches

View File

@@ -255,3 +255,36 @@ func TestSheets_SheetShortcutsDryRun(t *testing.T) {
})
}
}
func TestSheets_DimInsertDryRunInheritAfterKeepsBeforePosition(t *testing.T) {
setSheetsDryRunEnv(t)
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
t.Cleanup(cancel)
result, err := clie2e.RunCmd(ctx, clie2e.Request{
Args: []string{
"sheets", "+dim-insert",
"--spreadsheet-token", "shtDryRun",
"--sheet-id", "sheet1",
"--position", "D",
"--count", "1",
"--inherit-style", "after",
"--dry-run",
},
DefaultAs: "user",
})
require.NoError(t, err)
result.AssertExitCode(t, 0)
out := result.Stdout
require.Equal(t, "/open-apis/sheet_ai/v2/spreadsheets/shtDryRun/tools/invoke_write", clie2e.DryRunGet(out, "api.0.url").String(), "stdout:\n%s", out)
require.Equal(t, "modify_sheet_structure", clie2e.DryRunGet(out, "tool_name").String(), "stdout:\n%s", out)
require.Equal(t, "insert", clie2e.DryRunGet(out, "tool_input.operation").String(), "stdout:\n%s", out)
// inherit-style=after copies the following column's style via a plain
// before-insert at the same position (the backend anchors on the following
// column), so position stays D with side=before — the blank lands before D.
require.Equal(t, "D", clie2e.DryRunGet(out, "tool_input.position").String(), "stdout:\n%s", out)
require.Equal(t, int64(1), clie2e.DryRunGet(out, "tool_input.count").Int(), "stdout:\n%s", out)
require.Equal(t, "before", clie2e.DryRunGet(out, "tool_input.side").String(), "inherit-style=after copies the following-side style via side=before; stdout:\n%s", out)
}