Compare commits
47
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5f7db84d47 | ||
|
|
a023a2956a | ||
|
|
867bb44586 | ||
|
|
4bbd42cc25 | ||
|
|
2cc24de505 | ||
|
|
e023be1444 | ||
|
|
6575301a3a | ||
|
|
43121f1d8f | ||
|
|
cd02fe71e6 | ||
|
|
93a2071837 | ||
|
|
33730337f3 | ||
|
|
6be12655dc | ||
|
|
cf3bcb380f | ||
|
|
89e8bd7015 | ||
|
|
5de36d783a | ||
|
|
2bc4ded969 | ||
|
|
468f9200f6 | ||
|
|
6f61183732 | ||
|
|
332b74e8ce | ||
|
|
10bb2ec205 | ||
|
|
ac0125e468 | ||
|
|
7cc8db4eb0 | ||
|
|
f06a24ec2e | ||
|
|
8f135ecde6 | ||
|
|
a2e51f2b86 | ||
|
|
3d6e62fc08 | ||
|
|
c6094e291e | ||
|
|
e026c754e0 | ||
|
|
18030f1018 | ||
|
|
a097d57510 | ||
|
|
b566afe3e2 | ||
|
|
7405825294 | ||
|
|
7eb39ad5d6 | ||
|
|
eb73b944a1 | ||
|
|
ecaa375be8 | ||
|
|
dbecf23bc4 | ||
|
|
d73e199d97 | ||
|
|
7c9687094f | ||
|
|
05d8c86177 | ||
|
|
115dad3b82 | ||
|
|
b8ac9810f4 | ||
|
|
c1a90c0194 | ||
|
|
0bb2b6ce98 | ||
|
|
ea7c66b190 | ||
|
|
a3773c4384 | ||
|
|
4110330575 | ||
|
|
2bd6b297b0 |
@@ -6,6 +6,43 @@ The format is inspired by [Keep a Changelog](https://keepachangelog.com/) and th
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Fixed
|
||||
|
||||
- **Fail-closed devapp list pagination** (#917) — the paginated `dws devapp`
|
||||
list shortcuts (`+list`, `+permission-list`, `+event-list`, and
|
||||
`+version-list`) now preserve `hasMore` and `nextCursor` with each single-page
|
||||
result, forward opaque cursors byte-for-byte (including surrounding or
|
||||
whitespace-only values), normalize deployed providers' terminal missing,
|
||||
null, empty, or last-observed cursor to `nextCursor: ""`, and reject malformed
|
||||
or ambiguous pagination pages and unprojectable app items instead of emitting
|
||||
terminal-looking partial results.
|
||||
|
||||
## [1.0.58-beta.2] - 2026-08-10
|
||||
|
||||
### Added
|
||||
|
||||
- **`dws sheet create-with-data`(新命令)** — 建表并写入初始数据与样式:`--values`(二维数组写默认表)/ `--sheets`(typed table 多工作表,二者必须给一个)/ `--styles`(`cell_styles` / `row_sizes` / `col_sizes` / `cell_merges`,顶层键对齐飞书 snake_case、列表项内字段兼容 camelCase)。所有结构、字段类型与枚举在创建文档之前校验,非法配置不会留下白建的空文档:`--sheets` 按 `table_put` 的输入契约逐字段校验(`columns` 必填且列名非空不重复、`data` 为二维且行宽与 `columns` 一致、单元格仅限字符串/数字/布尔/null、`dtypes`/`formats` 的键须是列名、`mode`/`header`/`allowOverwrite`/`startCell` 类型与取值、单表 30000 单元格上限),并拒绝未知键、snake_case 变体、`{"sheets":"bad"}` 这类畸形包装与 `sheetId`(服务端会静默丢弃写错的键,导致"只写了表头却报成功"的静默丢数据);`--values` 校验单元格为标量并受 30000 单元格 / 2000000 字符上限约束;`--styles` 的顶层键与列表项内字段同样拒绝未知键,避免样式只应用一半。写入后回读校验按 `startCell` / `header` / `mode` 推算的首个预期非空单元格,而非固定 A1。该命令是多步编排(建文档 → 探活 → 定位默认工作表 → 写数据 → 回读 → 可选样式),因此如实声明为独立叶子 `sheet.create_with_data` + `interface_mode: composite`(附评审 reason,按契约不带 `interface_ref`);**`dws sheet create` 保持原样不变**——仍是一次 `create_workspace_sheet` 直连(`interface_mode: mcp`),不新增 flag,避免让 Schema 消费者把编排步骤的参数误当成该 RPC 的入参。
|
||||
- **`dws sheet export-csv`(新命令)** — 同步导出单个工作表为 RFC4180 CSV,支持 `--sheet-id` 选表、`--range` 限定范围、`--value-render-option` 选取值模式;`--output` 落盘(为目录时按 `sheet-export.csv` 命名,落盘走 `AtomicWrite` 原子替换,写入失败时已有文件保持原样;父目录不存在按错误处理,不会自动创建),不传则把纯 CSV 打到 stdout(警告只走 stderr)。数据超出单次读取上限时默认报错、既不输出也不写文件,需 `--allow-truncated` 显式接受不完整结果。响应缺 `csv` 字段或类型不对一律报错,不会用 0 字节覆盖已有文件。该分支读的是 `get_range_as_csv`、与 xlsx 的异步导出任务毫无关系,因此独立成叶子 `sheet.export_csv` 并如实声明 `interface_mode: mcp` + `interface_ref: get_range_as_csv`;**`dws sheet export` 保持原样不变**——仍只导 xlsx(`interface_ref: submit_export_job`),flag 面仍是 `--node` / `--output`,csv 专属 flag 不会出现在它上面(此前挂在同一条命令上时,漏写 `--export-format csv` 会让 `--range` 被静默丢弃而导出整篇工作簿)。
|
||||
- **`sheet update-dimension --size-type`** — `pixel` / `standard`(恢复默认行高列宽)/ `auto`(按内容自适应行高,仅 ROWS)。
|
||||
- **`sheet replace --match-formula`** — 在公式文本中查找替换。
|
||||
- **`sheet range set-style` 扩展样式维度** — 新增 `--font-style`(斜体)/ `--font-line`(下划线、删除线)/ `--font-family` / `--border-styles-json`(四边边框;每条边只接受 `style` / `color`,未知键与非字符串 `color` 直接报错,不再静默忽略而画出无颜色的边框,`set-style` / `batch-set-style` / `create-with-data --styles` 三条路径同源校验)。
|
||||
- **`sheet range batch-set-style --ranges`** — 一组样式刷多个带工作表前缀的区域,组装为一次原子 `batch_update`。
|
||||
|
||||
### Changed
|
||||
|
||||
- **Chat message post-send ID handoff** (#897) — CLI Help and bundled Skills
|
||||
now document the `send` → `query-send-status` → `edit`/`recall` workflow,
|
||||
so callers can reuse returned task, message, and conversation IDs instead
|
||||
of searching message history by content.
|
||||
- **Sheet mono/multi Skill alignment** — replaces the oversized mono Sheet
|
||||
reference with the progressive routing layout, aligns all 20 Sheet topic
|
||||
references across the mono and multi bundles, and adds a content-policy guard
|
||||
that prevents the paired topic trees from drifting again.
|
||||
- **`sheet range set-style` 后端切换为 `set_cell_range`** — 样式统一走 cellStyles 路径(仅设样式、保留原值),这是斜体/下划线删除线/字体族/边框唯一可用的通道。`interface_ref` 由 `update_range` 变为 `set_cell_range`,12 个样式 flag 改为 reviewed mapping exclusion。CLI 用法向后兼容、无 flag 删除;schema-compatibility 经 reviewed 豁免判定为兼容(0 changed fields)。
|
||||
- **`sheet range batch-set-style` 改为单次原子提交** — 由本地循环多次 `update_range` 改为一次 `batch_update`,任一项失败默认整批回滚;`--continue-on-error` 由本地控制改为透传服务端。新增批量上限:最多 100 个区域且累计不超过 200000 个单元格。
|
||||
- **`sheet range batch-clear` / `batch-set-style` 的 `--ranges` 拒绝空白工作表前缀**(用户可见行为变更)— 此前只按原始串里 `!` 的位置判断,`" !A1:B2"` 修剪后工作表名成了空串,操作却照样带着 `sheetId: ""` 提交:服务端要么让整批 `batch_update` 失败,要么更糟——落到默认工作表而不是用户指定的那张表,且命令报成功。现在工作表名与范围都必须在修剪之后仍非空,否则在发起任何请求之前报错。`batch-set-style --batch` 的纯空白 `sheetId` / `range` 同样拒绝(此前只挡空字符串);`--batch` 下发仍用原值不替用户修剪,因为 `sheetId` 可以是允许带首尾空格的工作表**名**。两条 `--ranges` 路径现在共用同一个拆分器。
|
||||
- **`sheet insert-dimension` / `delete-dimension` / `update-dimension` 的 `--length` 严格校验**(用户可见行为变更)— 解析由 `fmt.Sscanf("%d")` 改为 `strconv.Atoi`。此前只消费前缀数字,`--length 2x` / `3foo` 会被静默当成 `2` / `3` 并对错误的行列数执行操作(删除方向不可回滚);现在整个值必须是合法正整数,否则报错「`--length` 必须为正整数(>= 1)」且不发起任何请求。**升级影响**:原先依赖这种宽松解析、在传畸形 `--length` 的脚本会开始报错,请把参数修正为纯数字。合法数字值行为不变,上限仍为 5000。`add-dimension` 的 `--length` 是 `Int` 类型 flag,一直由 cobra 严格校验,不受影响。
|
||||
- **CLI 接口兼容门禁支持 reviewed flag 类型豁免**(无用户可见变更)— `authoritative-interface-integrity` 与 `check-command-compatibility.sh` 此前一律拒绝历史命令的 flag 类型变更,即使新类型只是把同一套校验从 RunE 前移到解析期,也没有任何评审通道。现在两道门禁各带一张精确豁免表:命令路径 + flag 名 + 旧类型 → 新类型四元组全等才命中、方向敏感(`string`→`int` 与 `int`→`string` 是两个不同的键,只有被评审的方向可用),且仅当该 flag 的其他契约(shorthand / required / hidden / no-opt / scope)纹丝不动时才放行,因此豁免夹带不了别的破坏。首条也是目前唯一一条登记的是 `dws minutes permission apply --policy` 的 `string` → `int`(配合 #912):旧实现在 RunE 里做 `strconv.ParseInt(v, 10, 64)` 再校验 `[2,4]`,新实现由 pflag 以 `strconv.ParseInt(s, 0, 64)` 解析后仍校验 `[2,4]`,**历史上能成功的调用集是新调用集的子集**(base 0 额外接受 `0x3` 这类写法,只放宽不收紧),非法值依然失败、只是报错文案与时机前移;flag 默认值由 `""` 变 `"0"` 是类型的必然结果,两道门禁都不比较默认值,且该 flag 必须显式给出、默认值不可达。两张表必须逐字一致并有守卫测试锚定漂移——重复是被迫的而非选择:`check-authoritative-interface-baselines.sh` 会把整个 `scripts/policy/interface-baseline` 目录复制进检出历史版本的 worktree 再编译,那份拷贝不能 import 本分支新增的包。
|
||||
## [1.0.58-beta.1] - 2026-08-07
|
||||
|
||||
### Added
|
||||
|
||||
@@ -1,33 +1,33 @@
|
||||
class DingtalkWorkspaceCliBeta < Formula
|
||||
desc "Automate DingTalk workspace tasks from the terminal (beta channel)"
|
||||
homepage "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli"
|
||||
version "1.0.57-beta.4"
|
||||
version "1.0.58-beta.2"
|
||||
license "Apache-2.0"
|
||||
keg_only "it is the beta channel and conflicts with dingtalk-workspace-cli"
|
||||
|
||||
on_macos do
|
||||
if Hardware::CPU.arm?
|
||||
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.57-beta.4/dws-darwin-arm64.tar.gz"
|
||||
sha256 "ff363e258d463732e4dc02aa71ac1b5b1f05c25107c32ddcc5ae11d14931a782"
|
||||
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.58-beta.2/dws-darwin-arm64.tar.gz"
|
||||
sha256 "1b2b6953f7f1ae1ca6ecb0702424ac0e1a976a6a5ff91e8ffc3b5ae495d98c7c"
|
||||
else
|
||||
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.57-beta.4/dws-darwin-amd64.tar.gz"
|
||||
sha256 "3eafcc4c27931b8457f3611a12ce4ae727f7bd65356fbef80958699defa09acf"
|
||||
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.58-beta.2/dws-darwin-amd64.tar.gz"
|
||||
sha256 "a1c1b3c58b48e04c0ae520062f9d6ab0dc961eddb635497bdb9b4345316e45f6"
|
||||
end
|
||||
end
|
||||
|
||||
on_linux do
|
||||
if Hardware::CPU.arm?
|
||||
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.57-beta.4/dws-linux-arm64.tar.gz"
|
||||
sha256 "49eabb4d2c419d8d1fb0fcf71d9c318ef49cf3d198431df1bcbaa71589e11383"
|
||||
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.58-beta.2/dws-linux-arm64.tar.gz"
|
||||
sha256 "7f35e3c4734f17b125a8c32f3c95e05d1410f683cf6956be857ee9349f8e4d36"
|
||||
else
|
||||
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.57-beta.4/dws-linux-amd64.tar.gz"
|
||||
sha256 "fb3903485fe494e1fadb67ec87b2fef19cf575c72b7df25f0b93f80f8b36273f"
|
||||
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.58-beta.2/dws-linux-amd64.tar.gz"
|
||||
sha256 "37beb9e39790563cf0584ac23376f713bf2eb2c50cff4222965e831ac9adbb0e"
|
||||
end
|
||||
end
|
||||
|
||||
resource "skills" do
|
||||
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.57-beta.4/dws-skills.zip"
|
||||
sha256 "6bd11363dbd2ce79627f49bc80b8a92f9c79fca083a6bd3ff9bc5c4833594fb9"
|
||||
url "https://github.com/DingTalk-Real-AI/dingtalk-workspace-cli/releases/download/v1.0.58-beta.2/dws-skills.zip"
|
||||
sha256 "7e10fead4192059c98d596c5b1886f77fd550526de5cd18c425cdad6fd64cd3a"
|
||||
end
|
||||
|
||||
def install
|
||||
|
||||
@@ -101,5 +101,5 @@ skills/mono/
|
||||
## 7. 变更流程
|
||||
|
||||
1. 改 / 增内容 → 更新 `skills/content-qa/mono-multi-coverage.yaml`(coverage 或 omit)
|
||||
2. 跑 `make skill-mono-multi-content`(或 `make policy`)
|
||||
2. 跑 `make skill-mono-multi-content`(该独立门禁不包含在默认 `make policy` 中)
|
||||
3. 失败则修内容或更新 reviewed omit(disposition + 原因),**禁止**用安装默认值绕过
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
> 对照基准:`skills/mono`(单 skill)。被测主体:`skills/multi`。
|
||||
> 机读合同:`skills/content-qa/mono-multi-coverage.yaml`。
|
||||
> 执行:`make skill-mono-multi-content`(已挂入 `make policy`)。
|
||||
> 执行:`make skill-mono-multi-content`(独立门禁;默认 `make policy` 按设计不包含该检查)。
|
||||
|
||||
## 1. 质检矩阵
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
| **G1 形状** | 结构 | `skills/multi/*` | 仅 `dingtalk-*`(含必选 `dingtalk-shared`);每目录有 `SKILL.md` |
|
||||
| **G2 结构** | 结构 | 各 `SKILL.md` frontmatter | `name`==目录名;非空 `description`;`category`∈{product,shared};`requires.bins` 含 `dws` |
|
||||
| **G3 覆盖** | 覆盖 | mono `references/products/*` 顶层 stem | 每 stem ∈ `coverage` 或 `omit_coverage`;coverage 目标 skill/refs 存在 |
|
||||
| **G4 漂移** | 漂移 | scripts、成对文件、全局协议 | orphan 脚本 ∈ allowlist;paired 一致;全局协议存在或 ∈ `omit_global` |
|
||||
| **G4 漂移** | 漂移 | scripts、成对文件、全局协议 | orphan 脚本 ∈ allowlist;paired 内容一致(允许合同声明的布局链接替换);全局协议存在或 ∈ `omit_global` |
|
||||
| **G5 链接** | 可达性 | 合同覆盖的 paired Markdown | 内联相对链接目标文件或目录存在且不逃出仓库;外链、纯锚点和锚点内容不在检查范围 |
|
||||
|
||||
已有门禁(继续复用,不替代本矩阵):`check-skill-commands`、`check-skill-context-budget`、`check-multi-im-skill-chain`、`skill_docs_policy`、whiteboard 成对测试。
|
||||
|
||||
@@ -37,6 +38,16 @@ orphan_scripts_allowlist:
|
||||
- path: dingtalk-misc/scripts/report_received_today.py
|
||||
disposition: defer
|
||||
reason: "pending report.md reference"
|
||||
|
||||
paired_files:
|
||||
- mono: references/products/sheet.md
|
||||
multi: dingtalk-misc/references/sheet.md
|
||||
mode: link-normalized
|
||||
link_substitutions:
|
||||
- mono: "../url-patterns.md"
|
||||
multi: "../../dingtalk-shared/references/url-patterns.md"
|
||||
- mono: "../intent-guide.md"
|
||||
multi: "sheet-intent-guide.md"
|
||||
```
|
||||
|
||||
**处置原则**:质检失败 → 修**内容**或更新 reviewed omit;**不**改安装/升级默认。
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
> 合同短文:[skill-content-framework.md](skill-content-framework.md)
|
||||
> 质检规格:[skill-mono-multi-qa.md](skill-mono-multi-qa.md)
|
||||
> 机读合同:`skills/content-qa/mono-multi-coverage.yaml`
|
||||
> 门禁:`make skill-mono-multi-content`(已入 `make policy`)
|
||||
> 门禁:`make skill-mono-multi-content`(独立门禁;默认 `make policy` 按设计不包含该检查)
|
||||
>
|
||||
> 撰写 / 收窄 / 质检增补 / 执行:2026-08-05
|
||||
> 工作树:`/Users/john/GolandProjects/open-source/dws-multi-skill-align`
|
||||
|
||||
@@ -0,0 +1,233 @@
|
||||
// Copyright 2026 Alibaba Group
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package app
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/executor"
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/helpers"
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/testseam"
|
||||
)
|
||||
|
||||
func executeDevAppListRoot(t *testing.T, args ...string) (string, string, error) {
|
||||
return executeDevAppRoot(t, "+list", args...)
|
||||
}
|
||||
|
||||
func executeDevAppRoot(t *testing.T, command string, args ...string) (string, string, error) {
|
||||
t.Helper()
|
||||
helpers.InitDepsForTest(t, helpers.GetCaller())
|
||||
root := NewRootCommand()
|
||||
var stdout bytes.Buffer
|
||||
var stderr bytes.Buffer
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&stderr)
|
||||
root.SetArgs(append([]string{"devapp", command}, args...))
|
||||
err := root.Execute()
|
||||
return stdout.String(), stderr.String(), err
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageDevAppPaginatedShortcutsMock(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
command string
|
||||
collection string
|
||||
args []string
|
||||
}{
|
||||
{name: "apps", command: "+list", collection: "apps"},
|
||||
{name: "permissions", command: "+permission-list", collection: "permissions", args: []string{"--unified-app-id", "X"}},
|
||||
{name: "events", command: "+event-list", collection: "events", args: []string{"--unified-app-id", "X"}},
|
||||
{name: "versions", command: "+version-list", collection: "versions", args: []string{"--unified-app-id", "X"}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
args := append(append([]string(nil), test.args...), "--mock", "--format", "json")
|
||||
stdout, stderr, err := executeDevAppRoot(t, test.command, args...)
|
||||
if err != nil {
|
||||
t.Fatalf("mock %s error = %v, stderr=%q", test.command, err, stderr)
|
||||
}
|
||||
if stderr != "" {
|
||||
t.Fatalf("mock %s stderr = %q", test.command, stderr)
|
||||
}
|
||||
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
|
||||
t.Fatalf("decode mock %s output: %v, output=%q", test.command, err, stdout)
|
||||
}
|
||||
items, ok := payload[test.collection].([]any)
|
||||
if len(payload) != 4 || !ok || len(items) != 0 || payload["count"] != float64(0) ||
|
||||
payload["hasMore"] != false || payload["nextCursor"] != "" {
|
||||
t.Fatalf("mock %s payload = %#v", test.command, payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageDevAppListMockPaginationFormats(t *testing.T) {
|
||||
for _, format := range []string{"json", "raw", "ndjson", "pretty"} {
|
||||
t.Run(format, func(t *testing.T) {
|
||||
if format == "pretty" {
|
||||
t.Setenv("NO_COLOR", "1")
|
||||
}
|
||||
stdout, stderr, err := executeDevAppListRoot(t, "--mock", "--format", format)
|
||||
if err != nil {
|
||||
t.Fatalf("mock list error = %v, stderr=%q", err, stderr)
|
||||
}
|
||||
if stderr != "" {
|
||||
t.Fatalf("mock list stderr = %q", stderr)
|
||||
}
|
||||
if format == "pretty" {
|
||||
values := map[string]string{}
|
||||
lines := strings.Split(strings.TrimSuffix(stdout, "\n"), "\n")
|
||||
if len(lines) != 4 {
|
||||
t.Fatalf("pretty mock lines = %d, want four: %q", len(lines), stdout)
|
||||
}
|
||||
for _, line := range lines {
|
||||
parts := strings.SplitN(line, ":", 2)
|
||||
if len(parts) != 2 {
|
||||
t.Fatalf("pretty mock line is not key/value: %q", line)
|
||||
}
|
||||
values[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
|
||||
}
|
||||
if len(values) != 4 || values["apps"] != "[]" || values["count"] != "0" ||
|
||||
values["hasMore"] != "false" || values["nextCursor"] != "" {
|
||||
t.Fatalf("pretty mock values = %#v, output=%q", values, stdout)
|
||||
}
|
||||
return
|
||||
}
|
||||
if format == "ndjson" && len(strings.Split(strings.TrimSuffix(stdout, "\n"), "\n")) != 1 {
|
||||
t.Fatalf("ndjson mock output expanded envelope: %q", stdout)
|
||||
}
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal([]byte(stdout), &payload); err != nil {
|
||||
t.Fatalf("decode mock output: %v, output=%q", err, stdout)
|
||||
}
|
||||
apps, ok := payload["apps"].([]any)
|
||||
if len(payload) != 4 || !ok || len(apps) != 0 || payload["count"] != float64(0) ||
|
||||
payload["hasMore"] != false || payload["nextCursor"] != "" {
|
||||
t.Fatalf("mock pagination payload = %#v", payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
type devAppListFixtureRunner struct {
|
||||
response string
|
||||
}
|
||||
|
||||
func (r devAppListFixtureRunner) Run(
|
||||
_ context.Context,
|
||||
invocation executor.Invocation,
|
||||
) (executor.Result, error) {
|
||||
return executor.Result{
|
||||
Invocation: invocation,
|
||||
Response: map[string]any{
|
||||
"content": []any{map[string]any{"type": "text", "text": r.response}},
|
||||
},
|
||||
}, nil
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageDevAppListInvalidContractJSONError(t *testing.T) {
|
||||
helpers.InitDepsForTest(t, helpers.GetCaller())
|
||||
testseam.Swap(t, &rootNewCommandRunnerWithFlags, func(*GlobalFlags) executor.Runner {
|
||||
return devAppListFixtureRunner{response: `{
|
||||
"apps":[{"unifiedAppId":"would-be-partial"},"payload-do-not-leak"],
|
||||
"hasMore":false,
|
||||
"nextCursor":""
|
||||
}`}
|
||||
})
|
||||
|
||||
root := NewRootCommand()
|
||||
var stdout bytes.Buffer
|
||||
var cobraStderr bytes.Buffer
|
||||
root.SetOut(&stdout)
|
||||
root.SetErr(&cobraStderr)
|
||||
root.SetArgs([]string{"devapp", "+list", "--cursor", "cursor-do-not-leak", "--format", "json"})
|
||||
err := root.Execute()
|
||||
if err == nil {
|
||||
t.Fatal("invalid pagination contract unexpectedly succeeded")
|
||||
}
|
||||
if stdout.Len() != 0 || cobraStderr.Len() != 0 {
|
||||
t.Fatalf("invalid contract leaked command output: stdout=%q stderr=%q", stdout.String(), cobraStderr.String())
|
||||
}
|
||||
if code := apperrors.ExitCode(err); code != 1 {
|
||||
t.Fatalf("exit code = %d, want 1", code)
|
||||
}
|
||||
|
||||
var machineStderr bytes.Buffer
|
||||
if printErr := printExecutionError(root, &stdout, &machineStderr, err); printErr != nil {
|
||||
t.Fatalf("print JSON error: %v", printErr)
|
||||
}
|
||||
if stdout.Len() != 0 {
|
||||
t.Fatalf("JSON error wrote stdout: %q", stdout.String())
|
||||
}
|
||||
decoder := json.NewDecoder(strings.NewReader(machineStderr.String()))
|
||||
var payload map[string]any
|
||||
if err := decoder.Decode(&payload); err != nil {
|
||||
t.Fatalf("decode stderr JSON: %v, stderr=%q", err, machineStderr.String())
|
||||
}
|
||||
if err := decoder.Decode(&map[string]any{}); err != io.EOF {
|
||||
t.Fatalf("stderr contained more than one JSON value: %v, stderr=%q", err, machineStderr.String())
|
||||
}
|
||||
errorPayload, ok := payload["error"].(map[string]any)
|
||||
message, messageOK := errorPayload["message"].(string)
|
||||
if len(payload) != 1 || !ok || len(errorPayload) != 4 ||
|
||||
errorPayload["category"] != "api" || errorPayload["code"] != float64(1) ||
|
||||
errorPayload["reason"] != "devapp_pagination_contract_invalid" ||
|
||||
!messageOK || strings.TrimSpace(message) == "" {
|
||||
t.Fatalf("JSON error contract = %#v", payload)
|
||||
}
|
||||
if strings.Contains(machineStderr.String(), "cursor-do-not-leak") ||
|
||||
strings.Contains(machineStderr.String(), "payload-do-not-leak") ||
|
||||
strings.Contains(machineStderr.String(), "would-be-partial") {
|
||||
t.Fatalf("JSON error leaked request or response data: %q", machineStderr.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageDevAppListMockIsolation(t *testing.T) {
|
||||
helpers.InitDepsForTest(t, helpers.GetCaller())
|
||||
runner := newCommandRunnerWithFlags(&GlobalFlags{Mock: true})
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
product string
|
||||
tool string
|
||||
}{
|
||||
{name: "other devapp tool", product: "devapp", tool: "get_dev_app"},
|
||||
{name: "other product", product: "contact", tool: "list_contacts"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
invocation := executor.NewHelperInvocation(
|
||||
"mock.isolation", test.product, test.tool, map[string]any{},
|
||||
)
|
||||
result, err := runner.Run(context.Background(), invocation)
|
||||
if err != nil {
|
||||
t.Fatalf("mock invocation error = %v", err)
|
||||
}
|
||||
content, ok := result.Response["content"].(map[string]any)
|
||||
if !ok {
|
||||
t.Fatalf("mock content = %#v", result.Response["content"])
|
||||
}
|
||||
mockResult, ok := content["result"].([]any)
|
||||
if !ok || len(mockResult) != 0 {
|
||||
t.Fatalf("non-target mock result changed = %#v", content["result"])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+17
-1
@@ -589,13 +589,29 @@ func (r *runtimeRunner) executeInvocation(ctx context.Context, endpoint string,
|
||||
// Mock mode: return predefined mock response without network call.
|
||||
if r.globalFlags != nil && r.globalFlags.Mock {
|
||||
invocation.Implemented = true
|
||||
result := any([]any{})
|
||||
if invocation.CanonicalProduct == "devapp" {
|
||||
collectionKey := map[string]string{
|
||||
"list_dev_app": "apps",
|
||||
"list_dev_app_permissions": "items",
|
||||
"list_dev_app_events": "events",
|
||||
"list_dev_app_versions": "items",
|
||||
}[invocation.Tool]
|
||||
if collectionKey != "" {
|
||||
result = map[string]any{
|
||||
collectionKey: []any{},
|
||||
"hasMore": false,
|
||||
"nextCursor": "",
|
||||
}
|
||||
}
|
||||
}
|
||||
return executor.Result{
|
||||
Invocation: invocation,
|
||||
Response: map[string]any{
|
||||
"endpoint": transport.RedactURL(endpoint),
|
||||
"content": map[string]any{
|
||||
"success": true,
|
||||
"result": []any{},
|
||||
"result": result,
|
||||
"_mock": true,
|
||||
"_tool": invocation.Tool,
|
||||
},
|
||||
|
||||
@@ -34,7 +34,12 @@ func TestReviewedRoutedInterfacesReachFinalSchema(t *testing.T) {
|
||||
{
|
||||
canonical: "sheet.range_batch_set_style",
|
||||
mode: "composite",
|
||||
reason: "The CLI reads a local batch file and performs multiple sheet/update_range calls with local continue-on-error control; the workflow has no single direct MCP interface.",
|
||||
reason: "The CLI assembles style cell matrices locally from --ranges or a local batch file and submits them as one sheet/batch_update operations array; no single direct MCP interface represents the wrapper input shape.",
|
||||
},
|
||||
{
|
||||
canonical: "sheet.create_with_data",
|
||||
mode: "composite",
|
||||
reason: "Reviewed composite workflow: the command calls sheet/create_workspace_sheet, waits for the new document to become writable, resolves the default worksheet, writes the initial data through sheet/set_range_from_csv or sheet/table_put, reads it back with sheet/get_range_as_csv, and optionally applies sheet/set_cell_range, sheet/update_dimension and sheet/merge_cells; no single pinned RPC represents the workflow.",
|
||||
},
|
||||
{
|
||||
canonical: "sheet.range_read",
|
||||
|
||||
@@ -592,10 +592,26 @@ var reviewedSchemaParameterMappingExclusions = map[string]string{
|
||||
"sheet.range_batch_clear --node": "Reviewed unpinned adapter: sheet.range_batch_clear has no singular pinned interface_ref; --node is a CLI wrapper input and does not publish a direct interface property.",
|
||||
"sheet.range_batch_clear --ranges": "Reviewed unpinned adapter: sheet.range_batch_clear has no singular pinned interface_ref; --ranges is a CLI wrapper input and does not publish a direct interface property.",
|
||||
"sheet.range_batch_clear --type": "Reviewed unpinned adapter: sheet.range_batch_clear has no singular pinned interface_ref; --type is a CLI wrapper input and does not publish a direct interface property.",
|
||||
"sheet.range_batch_set_style --batch": "Composite wrapper reads this local JSON file and performs zero or more update_range calls; the filesystem path is not a direct RPC property.",
|
||||
"sheet.range_batch_set_style --continue-on-error": "Composite wrapper consumes this flag in its local multi-call error loop and never sends it to update_range.",
|
||||
"sheet.range_batch_set_style --batch": "Composite wrapper reads this local JSON file and assembles it into a single sheet/batch_update operations array; the filesystem path is not a direct RPC property.",
|
||||
"sheet.range_batch_set_style --continue-on-error": "Reviewed unpinned adapter: sheet.range_batch_set_style has no singular pinned interface_ref; --continue-on-error is forwarded to sheet/batch_update as continueOnError and does not publish a direct interface property.",
|
||||
"sheet.range_read --range": "Reviewed unpinned adapter: sheet.range_read has no singular pinned interface_ref; --range is a CLI wrapper input and does not publish a direct interface property.",
|
||||
"sheet.range_read --sheet-id": "Reviewed unpinned adapter: sheet.range_read has no singular pinned interface_ref; --sheet-id is a CLI wrapper input and does not publish a direct interface property.",
|
||||
"sheet.range_set_style --bg-color": "Composite stamp wrapper: set-style expands this flag into cells[][].cellStyles.backgroundColor across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --bg-colors-json": "Composite stamp wrapper: set-style expands this per-cell matrix into cells[][].cellStyles.backgroundColor across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --border-styles-json": "Composite stamp wrapper: set-style attaches this object as cells[][].borderStyles on every cell of the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --font-color": "Composite stamp wrapper: set-style expands this flag into cells[][].cellStyles.fontColor across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --font-colors-json": "Composite stamp wrapper: set-style expands this per-cell matrix into cells[][].cellStyles.fontColor across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --font-family": "Composite stamp wrapper: set-style expands this flag into cells[][].cellStyles.fontFamily across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --font-line": "Composite stamp wrapper: set-style expands this single-choice flag into the cells[][].cellStyles.textUnderline and textLineThrough booleans of the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --font-size": "Composite stamp wrapper: set-style expands this flag into cells[][].cellStyles.fontSize across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --font-sizes-json": "Composite stamp wrapper: set-style expands this per-cell matrix into cells[][].cellStyles.fontSize across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --font-style": "Composite stamp wrapper: set-style expands this flag into cells[][].cellStyles.fontStyle across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --font-weight": "Composite stamp wrapper: set-style expands this flag into cells[][].cellStyles.fontWeight across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --font-weights-json": "Composite stamp wrapper: set-style expands this per-cell matrix into cells[][].cellStyles.fontWeight across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --h-align": "Composite stamp wrapper: set-style expands this flag into cells[][].cellStyles.horizontalAlignment across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --h-aligns-json": "Composite stamp wrapper: set-style expands this per-cell matrix into cells[][].cellStyles.horizontalAlignment across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --v-align": "Composite stamp wrapper: set-style expands this flag into cells[][].cellStyles.verticalAlignment across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.range_set_style --v-aligns-json": "Composite stamp wrapper: set-style expands this per-cell matrix into cells[][].cellStyles.verticalAlignment across the set_cell_range matrix; it has no top-level RPC property.",
|
||||
"sheet.reply_sheet_comment --comment-key": "Reviewed unpinned adapter: sheet.reply_sheet_comment has no singular pinned interface_ref; --comment-key is a CLI wrapper input and does not publish a direct interface property.",
|
||||
"sheet.reply_sheet_comment --content": "Reviewed unpinned adapter: sheet.reply_sheet_comment has no singular pinned interface_ref; --content is a CLI wrapper input and does not publish a direct interface property.",
|
||||
"sheet.reply_sheet_comment --emoji": "Reviewed unpinned adapter: sheet.reply_sheet_comment has no singular pinned interface_ref; --emoji is a CLI wrapper input and does not publish a direct interface property.",
|
||||
|
||||
@@ -2042,6 +2042,11 @@ func newChatCommand() *cobra.Command {
|
||||
纯文本 / Markdown 消息(默认):
|
||||
无需指定 --msg-type,直接传消息内容即可。推荐使用 --text flag 传递内容(尤其当内容含换行、引号等特殊字符时),也支持位置参数。可选 --title 作为消息标题。
|
||||
|
||||
返回值与后续操作:
|
||||
发送后会返回 openTaskId。如需编辑或撤回刚发送的消息,使用
|
||||
dws chat message query-send-status --open-task-id <openTaskId>
|
||||
获取 openMessageId 和 openConversationId,无需再按消息内容反查。
|
||||
|
||||
本地图片 / 文件消息:
|
||||
统一使用 --msg-type file --file-path <本地路径>。CLI 会完成上传并按 file 消息发送;
|
||||
.png/.jpg 也会显示为可下载的文件附件,不会生成 mediaId 或渲染成内联图片。
|
||||
@@ -3304,7 +3309,10 @@ func newChatCommand() *cobra.Command {
|
||||
chatMessageQuerySendStatusCmd := &cobra.Command{
|
||||
Use: "query-send-status",
|
||||
Short: "查询消息发送状态",
|
||||
Long: `查询以当前用户身份发送的消息的发送状态。需要传入发送消息时返回的 openTaskId。`,
|
||||
Long: `查询以当前用户身份发送的消息的发送状态。需要传入 chat message send 返回的 openTaskId。
|
||||
|
||||
发送成功后,查询结果会返回 openMessageId 和 openConversationId,可直接作为
|
||||
chat message edit 或 chat message recall 的 --msg-id 和 --conversation-id。`,
|
||||
Example: ` dws chat message query-send-status --open-task-id <openTaskId>
|
||||
# openTaskId 由 dws chat message send 返回`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
@@ -3351,8 +3359,11 @@ func newChatCommand() *cobra.Command {
|
||||
Short: "撤回用户发送的消息",
|
||||
Long: `撤回当前用户发送的消息。需要指定会话 ID 和消息 ID。`,
|
||||
Example: ` dws chat message recall --conversation-id <openConversationId> --msg-id <openMessageId>
|
||||
# 查询会话 ID: dws chat search --query "群名"
|
||||
# 消息 ID 可通过 dws chat message list 获取`,
|
||||
|
||||
# 发送后撤回:send -> query-send-status -> recall
|
||||
dws chat message send --group <openConversationId> --text "待撤回的内容"
|
||||
dws chat message query-send-status --open-task-id <上一步返回的openTaskId>
|
||||
dws chat message recall --conversation-id <上一步返回的openConversationId> --msg-id <上一步返回的openMessageId>`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if err := validateRequiredFlagWithAliases(cmd, "conversation-id", "group", "id", "chat"); err != nil {
|
||||
return err
|
||||
@@ -3409,12 +3420,16 @@ func newChatCommand() *cobra.Command {
|
||||
推荐使用 --text 和可选 --title,CLI 会按 Markdown 消息规则生成 content:{"title":"标题","text":"正文"}。
|
||||
也可以直接使用 --content 传入完整 Markdown content JSON。--text 和 --content 二选一。`,
|
||||
Example: ` dws chat message edit --conversation-id <openConversationId> --msg-id <openMessageId> --text "更新后的内容"
|
||||
|
||||
# 发送后编辑:send -> query-send-status -> edit
|
||||
dws chat message send --group <openConversationId> --text "原始内容"
|
||||
dws chat message query-send-status --open-task-id <上一步返回的openTaskId>
|
||||
dws chat message edit --conversation-id <上一步返回的openConversationId> --msg-id <上一步返回的openMessageId> --text "更新后的内容"
|
||||
|
||||
dws chat message edit --group <openConversationId> --msg-id <openMessageId> --title "标题" --text "更新后的内容"
|
||||
dws chat message edit --group <openConversationId> --msg-id <openMessageId> --text "<@all> 请查看" --at-all
|
||||
dws chat message edit --group <openConversationId> --msg-id <openMessageId> --text "<@openDingTalkId1> 请查看" --at-open-dingtalk-ids <openDingTalkId1>
|
||||
dws chat message edit --group <openConversationId> --msg-id <openMessageId> --content '{"title":"标题","text":"更新后的内容"}'
|
||||
# 查询会话 ID: dws chat search --query "群名"
|
||||
# 消息 ID 可通过 dws chat message list 获取`,
|
||||
dws chat message edit --group <openConversationId> --msg-id <openMessageId> --content '{"title":"标题","text":"更新后的内容"}'`,
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
if err := validateRequiredFlagWithAliases(cmd, "conversation-id", "group", "id", "chat"); err != nil {
|
||||
return err
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
// Copyright 2026 Alibaba Group
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCrossPlatformCoverageChatMessageHelpDocumentsPostSendIDChain(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
command string
|
||||
contains []string
|
||||
notContain string
|
||||
}{
|
||||
{
|
||||
name: "send returns task ID",
|
||||
command: "send",
|
||||
contains: []string{
|
||||
"openTaskId",
|
||||
"query-send-status --open-task-id <openTaskId>",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "query returns message and conversation IDs",
|
||||
command: "query-send-status",
|
||||
contains: []string{
|
||||
"openTaskId",
|
||||
"openMessageId",
|
||||
"openConversationId",
|
||||
"chat message edit",
|
||||
"chat message recall",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "edit includes post-send workflow",
|
||||
command: "edit",
|
||||
contains: []string{
|
||||
"send -> query-send-status -> edit",
|
||||
"query-send-status --open-task-id <上一步返回的openTaskId>",
|
||||
"edit --conversation-id <上一步返回的openConversationId> --msg-id <上一步返回的openMessageId>",
|
||||
},
|
||||
notContain: "chat message list",
|
||||
},
|
||||
{
|
||||
name: "recall includes post-send workflow",
|
||||
command: "recall",
|
||||
contains: []string{
|
||||
"send -> query-send-status -> recall",
|
||||
"query-send-status --open-task-id <上一步返回的openTaskId>",
|
||||
"recall --conversation-id <上一步返回的openConversationId> --msg-id <上一步返回的openMessageId>",
|
||||
},
|
||||
notContain: "chat message list",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
cmd := newChatCommand()
|
||||
var output bytes.Buffer
|
||||
cmd.SetOut(&output)
|
||||
cmd.SetErr(&output)
|
||||
cmd.SetArgs([]string{"message", test.command, "--help"})
|
||||
if err := cmd.Execute(); err != nil {
|
||||
t.Fatalf("chat message %s --help: %v\n%s", test.command, err, output.String())
|
||||
}
|
||||
|
||||
help := output.String()
|
||||
for _, want := range test.contains {
|
||||
if !strings.Contains(help, want) {
|
||||
t.Errorf("chat message %s help missing %q:\n%s", test.command, want, help)
|
||||
}
|
||||
}
|
||||
if test.notContain != "" && strings.Contains(help, test.notContain) {
|
||||
t.Errorf("chat message %s help still contains %q:\n%s", test.command, test.notContain, help)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -170,7 +170,6 @@ func TestCrossPlatformCoverageChartMailAndSheetPureHelpersCoverage(t *testing.T)
|
||||
_ = isEmptyDataValidation(value)
|
||||
_ = isEmptyHyperlink(value)
|
||||
}
|
||||
_ = fillIntMatrix(2, 3, 4)
|
||||
_ = maxColLenStr([][]string{{"a"}, {"b", "c"}})
|
||||
_ = maxColLen2D([][]int{{1}, {2, 3}})
|
||||
_ = checkMatrixShape(1, 2, 1, 2, "x")
|
||||
@@ -213,7 +212,7 @@ func TestCrossPlatformCoverageChartMailAndSheetPureHelpersCoverage(t *testing.T)
|
||||
{styleSpec{}, 1, 1},
|
||||
}
|
||||
for _, style := range styles {
|
||||
_ = applyStyleSpec(&style.spec, style.rows, style.cols, map[string]any{})
|
||||
_, _ = buildStyleCells(&style.spec, style.rows, style.cols)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
scalar, raw string
|
||||
@@ -227,7 +226,9 @@ func TestCrossPlatformCoverageChartMailAndSheetPureHelpersCoverage(t *testing.T)
|
||||
{"", `[[""]]`, hAlignEnum},
|
||||
{"", `[["left"]]`, hAlignEnum},
|
||||
} {
|
||||
_ = apply2DString(tc.scalar, tc.raw, 1, 1, "align", "alignments", tc.enum, map[string]any{})
|
||||
if get, err := strGrid(tc.scalar, tc.raw, "align", tc.enum, 1, 1); err == nil && get != nil {
|
||||
_, _ = get(0, 0)
|
||||
}
|
||||
}
|
||||
views := []map[string]any{{"id": "one"}, {"filterViewId": "two"}}
|
||||
_, _ = findFilterViewByID(views, "one")
|
||||
|
||||
@@ -44,6 +44,7 @@ func newSheetCommand() *cobra.Command {
|
||||
|
||||
命令结构:
|
||||
dws sheet create 创建钉钉表格文档
|
||||
dws sheet create-with-data 创建表格文档并写入初始数据(可选样式)
|
||||
dws sheet list 获取全部工作表列表
|
||||
dws sheet info 获取指定工作表详情
|
||||
dws sheet new 新建工作表
|
||||
@@ -110,6 +111,7 @@ func newSheetCommand() *cobra.Command {
|
||||
dws sheet chart update 更新浮动图表
|
||||
dws sheet chart delete 删除浮动图表
|
||||
dws sheet export 导出表格为 xlsx(异步任务一站式:提交→轮询→可选下载)
|
||||
dws sheet export-csv 导出单个工作表为纯 CSV(同步,可落盘)
|
||||
dws sheet import 导入 xlsx/xls 为在线电子表格
|
||||
dws sheet template list 获取表格模板列表
|
||||
dws sheet template search 搜索表格模板
|
||||
@@ -159,6 +161,10 @@ func newSheetCommand() *cobra.Command {
|
||||
},
|
||||
},
|
||||
})
|
||||
// 建表带初始数据、csv 同步导出都是与既有叶子不同的接口种类(一条 composite
|
||||
// 编排、一条 get_range_as_csv 直连),各自独立成叶子,不挂到 create / export 上。
|
||||
createWithDataCmd := newSheetCreateWithDataCmd()
|
||||
exportCsvCmd := newSheetExportCsvCmd()
|
||||
importCmd := newSheetImportCmd()
|
||||
templateCmd := newSheetTemplateCmd()
|
||||
tableCmds := newTableCmds()
|
||||
@@ -238,7 +244,7 @@ func newSheetCommand() *cobra.Command {
|
||||
standaloneCmds = append(standaloneCmds, mediaCmds...)
|
||||
standaloneCmds = append(standaloneCmds, floatImageCmds...)
|
||||
standaloneCmds = append(standaloneCmds, tableCmds...)
|
||||
standaloneCmds = append(standaloneCmds, exportCmd, importCmd, batchUpdateCmd)
|
||||
standaloneCmds = append(standaloneCmds, exportCmd, exportCsvCmd, importCmd, batchUpdateCmd, createWithDataCmd)
|
||||
|
||||
// Register cross-product aliases
|
||||
for _, cmd := range standaloneCmds {
|
||||
|
||||
@@ -517,12 +517,12 @@ func newRangeBatchClearCmd() *cobra.Command {
|
||||
}
|
||||
operations := make([]any, 0, len(ranges))
|
||||
for i, rng := range ranges {
|
||||
idx := strings.Index(rng, "!")
|
||||
if idx <= 0 || idx == len(rng)-1 {
|
||||
return fmt.Errorf("--ranges[%d] (%q) 必须包含工作表前缀,格式为 \"SheetName!A1:B3\"", i, rng)
|
||||
// 与 batch-set-style 共用同一个拆分器:此前这里自己拆,且只按原始串里
|
||||
// ! 的位置判断," !A1:B2" 会拆出空工作表名并带着 sheetId:"" 下发。
|
||||
sheetName, rangeAddr, err := splitSheetPrefixedRange(rng, i)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sheetName := strings.TrimSpace(rng[:idx])
|
||||
rangeAddr := strings.TrimSpace(rng[idx+1:])
|
||||
operations = append(operations, map[string]any{
|
||||
"toolName": "clear_range",
|
||||
"input": map[string]any{
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -129,6 +129,7 @@ sheetId 支持传入工作表 ID 或工作表名称,可通过 sheet list 获
|
||||
--match-case 区分大小写(默认 false)
|
||||
--match-entire-cell 完整单元格匹配(默认 false)
|
||||
--use-regexp 使用正则表达式匹配(默认 false)
|
||||
--match-formula 在公式文本中查找替换(默认 false,替换公式源码而非显示值)
|
||||
--include-hidden 包含隐藏行/列(默认 false)
|
||||
--range 限定替换范围,A1 表示法(不传时在整个工作表中替换)
|
||||
|
||||
@@ -166,6 +167,8 @@ sheetId 支持传入工作表 ID 或工作表名称,可通过 sheet list 获
|
||||
toolArgs["matchEntireCell"] = matchEntireCell
|
||||
useRegExp, _ := cmd.Flags().GetBool("use-regexp")
|
||||
toolArgs["useRegExp"] = useRegExp
|
||||
matchFormula, _ := cmd.Flags().GetBool("match-formula")
|
||||
toolArgs["matchFormulaText"] = matchFormula
|
||||
includeHidden, _ := cmd.Flags().GetBool("include-hidden")
|
||||
toolArgs["includeHidden"] = includeHidden
|
||||
return callMCPTool("replace_all", toolArgs)
|
||||
@@ -198,6 +201,7 @@ sheetId 支持传入工作表 ID 或工作表名称,可通过 sheet list 获
|
||||
},
|
||||
Parameters: []contract.ParamDecl{
|
||||
{Name: "find", Property: "text"},
|
||||
{Name: "match-formula", Property: "matchFormulaText"},
|
||||
{Name: "node", Property: "nodeId"},
|
||||
{Name: "replacement", Property: "replaceText"},
|
||||
{Name: "use-regexp", Property: "useRegExp"},
|
||||
@@ -212,6 +216,7 @@ sheetId 支持传入工作表 ID 或工作表名称,可通过 sheet list 获
|
||||
replaceCmd.Flags().Bool("match-case", false, "区分大小写 (默认 false)")
|
||||
replaceCmd.Flags().Bool("match-entire-cell", false, "完整单元格匹配")
|
||||
replaceCmd.Flags().Bool("use-regexp", false, "启用正则表达式匹配")
|
||||
replaceCmd.Flags().Bool("match-formula", false, "在公式文本中查找替换(默认 false)")
|
||||
replaceCmd.Flags().Bool("include-hidden", false, "包含隐藏行/列")
|
||||
|
||||
appendCmd := &cobra.Command{
|
||||
|
||||
@@ -3,12 +3,21 @@ package helpers
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/corecmd/contract"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// sizeTypeEnumHint 返回该维度支持的尺寸模式列表(行高含 auto,列宽不含,与飞书一致)。
|
||||
func sizeTypeEnumHint(dimension string) string {
|
||||
if dimension == "ROWS" {
|
||||
return "pixel / standard / auto"
|
||||
}
|
||||
return "pixel / standard"
|
||||
}
|
||||
|
||||
// newDimensionCmds creates dimension-related commands: insert/delete/update/move/add-dimension,
|
||||
// merge-cells, unmerge-cells, and dropdown commands (set/get/delete-dropdown).
|
||||
func newDimensionCmds() []*cobra.Command {
|
||||
@@ -43,8 +52,11 @@ func newDimensionCmds() []*cobra.Command {
|
||||
return fmt.Errorf("--dimension 必须为 ROWS 或 COLUMNS,当前值: %s", dimension)
|
||||
}
|
||||
lengthStr := mustGetFlag(cmd, "length")
|
||||
var length int
|
||||
if _, err := fmt.Sscanf(lengthStr, "%d", &length); err != nil || length < 1 {
|
||||
// strconv.Atoi 要求整个字符串都是合法整数。fmt.Sscanf("%d") 只消费前缀
|
||||
// 数字,会把 "3x" / "3foo" 静默当成 3,从而对错误的行列数执行插入/删除/
|
||||
// 调整——删除方向不可回滚。
|
||||
length, lengthErr := strconv.Atoi(lengthStr)
|
||||
if lengthErr != nil || length < 1 {
|
||||
return fmt.Errorf("--length 必须为正整数(>= 1),当前值: %s", lengthStr)
|
||||
}
|
||||
if length > 5000 {
|
||||
@@ -428,8 +440,11 @@ sheetId 支持传入工作表 ID 或工作表名称,可通过 sheet list 获
|
||||
return fmt.Errorf("--dimension 必须为 ROWS 或 COLUMNS,当前值: %s", dimension)
|
||||
}
|
||||
lengthStr := mustGetFlag(cmd, "length")
|
||||
var length int
|
||||
if _, err := fmt.Sscanf(lengthStr, "%d", &length); err != nil || length < 1 {
|
||||
// strconv.Atoi 要求整个字符串都是合法整数。fmt.Sscanf("%d") 只消费前缀
|
||||
// 数字,会把 "3x" / "3foo" 静默当成 3,从而对错误的行列数执行插入/删除/
|
||||
// 调整——删除方向不可回滚。
|
||||
length, lengthErr := strconv.Atoi(lengthStr)
|
||||
if lengthErr != nil || length < 1 {
|
||||
return fmt.Errorf("--length 必须为正整数(>= 1),当前值: %s", lengthStr)
|
||||
}
|
||||
if length > 5000 {
|
||||
@@ -490,9 +505,15 @@ sheetId 支持传入工作表 ID 或工作表名称,可通过 sheet list 获
|
||||
--dimension COLUMNS 时,--start-index 为列字母,如 "A" 表示从 A 列开始、"AB" 表示从 AB 列开始
|
||||
|
||||
支持在 --start-index 中携带工作表前缀(如 "Sheet1!3" / "Sheet1!A"),此时将忽略 --sheet-id。
|
||||
--hidden 与 --pixel-size 至少必须提供一个。当同时提供时,将先应用尺寸再应用显隐,任一失败整体失败。
|
||||
--hidden 与 --pixel-size 至少必须提供一个(或用 --size-type standard/auto 让服务端决定尺寸)。
|
||||
当同时提供时,将先应用尺寸再应用显隐,任一失败整体失败。
|
||||
--pixel-size 单位为像素,dimension=ROWS 时表示行高、dimension=COLUMNS 时表示列宽。
|
||||
|
||||
尺寸模式(--size-type,对齐飞书):
|
||||
pixel 默认,按 --pixel-size 指定的像素值设置
|
||||
standard 恢复默认行高/列宽,无需 --pixel-size
|
||||
auto 按内容自适应行高,仅 ROWS 支持(列宽不提供自适应),无需 --pixel-size
|
||||
|
||||
常见场景:隐藏/显示指定连续行或列、批量调整行高/列宽、在同一次调用中同时修改尺寸与显隐。`,
|
||||
Example: ` # 隐藏第 3~4 行
|
||||
dws sheet update-dimension --node NODE_ID --sheet-id SHEET_ID --dimension ROWS --start-index "3" --length 2 --hidden
|
||||
@@ -517,8 +538,11 @@ sheetId 支持传入工作表 ID 或工作表名称,可通过 sheet list 获
|
||||
return fmt.Errorf("--dimension 必须为 ROWS 或 COLUMNS,当前值: %s", dimension)
|
||||
}
|
||||
lengthStr := mustGetFlag(cmd, "length")
|
||||
var length int
|
||||
if _, err := fmt.Sscanf(lengthStr, "%d", &length); err != nil || length < 1 {
|
||||
// strconv.Atoi 要求整个字符串都是合法整数。fmt.Sscanf("%d") 只消费前缀
|
||||
// 数字,会把 "3x" / "3foo" 静默当成 3,从而对错误的行列数执行插入/删除/
|
||||
// 调整——删除方向不可回滚。
|
||||
length, lengthErr := strconv.Atoi(lengthStr)
|
||||
if lengthErr != nil || length < 1 {
|
||||
return fmt.Errorf("--length 必须为正整数(>= 1),当前值: %s", lengthStr)
|
||||
}
|
||||
if length > 5000 {
|
||||
@@ -526,8 +550,30 @@ sheetId 支持传入工作表 ID 或工作表名称,可通过 sheet list 获
|
||||
}
|
||||
hiddenChanged := cmd.Flags().Changed("hidden")
|
||||
pixelSizeChanged := cmd.Flags().Changed("pixel-size")
|
||||
if !hiddenChanged && !pixelSizeChanged {
|
||||
return fmt.Errorf("--hidden 与 --pixel-size 至少必须提供一个")
|
||||
sizeType, _ := cmd.Flags().GetString("size-type")
|
||||
sizeType = strings.ToLower(strings.TrimSpace(sizeType))
|
||||
// 尺寸模式枚举按维度区分(与飞书一致):行高有 auto,列宽只有 pixel / standard
|
||||
switch {
|
||||
case sizeType == "" || sizeType == "pixel" || sizeType == "standard":
|
||||
case sizeType == "auto" && dimension == "ROWS":
|
||||
case sizeType == "auto":
|
||||
return fmt.Errorf("--size-type 对 COLUMNS 仅支持 pixel / standard(列宽不提供自适应)")
|
||||
default:
|
||||
return fmt.Errorf("--size-type 必须为 %s,当前值: %s", sizeTypeEnumHint(dimension), sizeType)
|
||||
}
|
||||
// standard/auto 由服务端决定尺寸,无需 --pixel-size
|
||||
sizeTypeDrivesSize := sizeType == "standard" || sizeType == "auto"
|
||||
if !hiddenChanged && !pixelSizeChanged && !sizeTypeDrivesSize {
|
||||
return fmt.Errorf("--hidden 与 --pixel-size 至少必须提供一个(或用 --size-type standard/auto 让服务端决定尺寸)")
|
||||
}
|
||||
// standard/auto 说"尺寸交给服务端",--pixel-size 又指定固定像素,
|
||||
// 两者语义直接冲突;同时下发会得到依赖服务端实现的结果,故先拒。
|
||||
if sizeTypeDrivesSize && pixelSizeChanged {
|
||||
return fmt.Errorf("--size-type %s 表示尺寸由服务端决定,不能同时指定 --pixel-size;要指定固定像素请用 --size-type pixel(或省略 --size-type)", sizeType)
|
||||
}
|
||||
// 反向:显式声明 pixel 模式却不给像素值,同样是不完整的请求。
|
||||
if sizeType == "pixel" && !pixelSizeChanged {
|
||||
return fmt.Errorf("--size-type pixel 必须配合 --pixel-size 指定像素值;若本次只改显隐,请省略 --size-type")
|
||||
}
|
||||
toolArgs := map[string]any{
|
||||
"nodeId": mustGetFlag(cmd, "node"),
|
||||
@@ -547,6 +593,9 @@ sheetId 支持传入工作表 ID 或工作表名称,可通过 sheet list 获
|
||||
}
|
||||
toolArgs["pixelSize"] = pixelSize
|
||||
}
|
||||
if sizeType != "" {
|
||||
toolArgs["sizeType"] = sizeType
|
||||
}
|
||||
return callMCPTool("update_dimension", toolArgs)
|
||||
},
|
||||
}
|
||||
@@ -587,6 +636,7 @@ sheetId 支持传入工作表 ID 或工作表名称,可通过 sheet list 获
|
||||
updateDimensionCmd.Flags().String("length", "", "更新数量,正整数 (必填),最大 5000")
|
||||
updateDimensionCmd.Flags().Bool("hidden", false, "是否隐藏 (true=隐藏, false=显示)")
|
||||
updateDimensionCmd.Flags().Int("pixel-size", 0, "行高或列宽(像素),ROWS 时为行高,COLUMNS 时为列宽")
|
||||
updateDimensionCmd.Flags().String("size-type", "", "尺寸模式(对齐飞书): pixel(默认,用 --pixel-size) / standard(恢复默认行高列宽) / auto(按内容自适应行高,仅 ROWS;列宽无此选项)")
|
||||
|
||||
groupDimensionCmd := &cobra.Command{
|
||||
Use: "group-dimension",
|
||||
|
||||
@@ -2,6 +2,7 @@ package helpers
|
||||
|
||||
import (
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
@@ -74,6 +75,84 @@ func TestCrossPlatformCoverageDimensionValidationRemainingCoverage(t *testing.T)
|
||||
}
|
||||
}
|
||||
|
||||
// --length 必须整个值都是合法正整数。改用 strconv.Atoi 之前走的是
|
||||
// fmt.Sscanf("%d"),只消费前缀数字,"2x" 被静默当成 2 并对错误的行列数执行操作
|
||||
// ——delete 方向不可回滚。这是对既有命令的用户可见行为变更(已记入 CHANGELOG),
|
||||
// 用测试钉住,避免哪天改回宽松解析没人发现。
|
||||
func TestDimensionLengthRejectsTrailingCharacters(t *testing.T) {
|
||||
installScriptedCaller(t, &scriptedToolCaller{dry: true})
|
||||
common := []string{"--node", "node", "--sheet-id", "sheet", "--dimension", "ROWS"}
|
||||
|
||||
for _, cmdName := range []string{"insert-dimension", "delete-dimension", "update-dimension"} {
|
||||
locator := []string{"--position", "1"}
|
||||
if cmdName == "update-dimension" {
|
||||
locator = []string{"--start-index", "1", "--hidden"}
|
||||
}
|
||||
for _, bad := range []string{"2x", "3foo", "1 2", "0x10", "abc", ""} {
|
||||
args := append(append(append([]string{}, common...), locator...), "--length", bad)
|
||||
err := executeDimensionCoverage(t, cmdName, args...)
|
||||
if err == nil {
|
||||
t.Errorf("%s --length %q 未报错,畸形长度被静默接受", cmdName, bad)
|
||||
continue
|
||||
}
|
||||
if !strings.Contains(err.Error(), "--length") {
|
||||
t.Errorf("%s --length %q: err = %v, want 指明 --length", cmdName, bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// --size-type 的枚举按维度区分:行高有 auto,列宽只有 pixel / standard(对齐飞书)。
|
||||
func TestUpdateDimensionSizeTypeEnumIsDimensionScoped(t *testing.T) {
|
||||
installScriptedCaller(t, &scriptedToolCaller{dry: true})
|
||||
common := []string{"--node", "node", "--sheet-id", "sheet", "--start-index", "1", "--length", "2"}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
dimension string
|
||||
sizeType string
|
||||
wantErr string
|
||||
}{
|
||||
// standard / auto 由服务端决定尺寸,不再要求 --hidden 或 --pixel-size
|
||||
{"rows-standard", "ROWS", "standard", ""},
|
||||
{"rows-auto", "ROWS", "auto", ""},
|
||||
{"columns-standard", "COLUMNS", "standard", ""},
|
||||
{"columns-auto-rejected", "COLUMNS", "auto", "仅支持 pixel / standard"},
|
||||
// 非法枚举的提示文案必须按维度给出不同的合法值列表
|
||||
{"rows-bogus-hint", "ROWS", "bogus", "必须为 pixel / standard / auto"},
|
||||
{"columns-bogus-hint", "COLUMNS", "bogus", "必须为 pixel / standard"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
args := append(append([]string{}, common...), "--dimension", tc.dimension, "--size-type", tc.sizeType)
|
||||
err := executeDimensionCoverage(t, "update-dimension", args...)
|
||||
if tc.wantErr == "" {
|
||||
if err != nil {
|
||||
t.Fatalf("err = %v, want nil", err)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err == nil || !strings.Contains(err.Error(), tc.wantErr) {
|
||||
t.Fatalf("err = %v, want contains %q", err, tc.wantErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// pixel 仍需 --hidden 或 --pixel-size 之一
|
||||
args := append(append([]string{}, common...), "--dimension", "ROWS", "--size-type", "pixel")
|
||||
if err := executeDimensionCoverage(t, "update-dimension", args...); err == nil {
|
||||
t.Fatal("size-type=pixel 且未给 --pixel-size/--hidden 时应报错")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSizeTypeEnumHint(t *testing.T) {
|
||||
if got := sizeTypeEnumHint("ROWS"); got != "pixel / standard / auto" {
|
||||
t.Fatalf("ROWS hint = %q", got)
|
||||
}
|
||||
if got := sizeTypeEnumHint("COLUMNS"); got != "pixel / standard" {
|
||||
t.Fatalf("COLUMNS hint = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageDropdownValidationRemainingCoverage(t *testing.T) {
|
||||
installScriptedCaller(t, &scriptedToolCaller{dry: true})
|
||||
base := []string{"--node", "node", "--sheet-id", "sheet", "--range", "A1"}
|
||||
@@ -86,3 +165,80 @@ func TestCrossPlatformCoverageDropdownValidationRemainingCoverage(t *testing.T)
|
||||
t.Fatalf("multi-select dropdown: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// --size-type standard/auto 与 --pixel-size 语义冲突(一个说交给服务端、一个
|
||||
// 指定固定像素),必须在发请求前拒;反向 pixel 模式也必须带像素值。
|
||||
func TestUpdateDimensionRejectsSizeTypeAndPixelSizeConflict(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
flags [][2]string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
"standard-with-pixel-size",
|
||||
[][2]string{{"dimension", "ROWS"}, {"size-type", "standard"}, {"pixel-size", "40"}},
|
||||
"不能同时指定 --pixel-size",
|
||||
},
|
||||
{
|
||||
"auto-with-pixel-size",
|
||||
[][2]string{{"dimension", "ROWS"}, {"size-type", "auto"}, {"pixel-size", "40"}},
|
||||
"不能同时指定 --pixel-size",
|
||||
},
|
||||
{
|
||||
"explicit-pixel-without-size",
|
||||
[][2]string{{"dimension", "ROWS"}, {"size-type", "pixel"}, {"hidden", "true"}},
|
||||
"--size-type pixel 必须配合 --pixel-size",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
caller := &scriptedToolCaller{}
|
||||
flags := append([][2]string{{"node", "N"}, {"sheet-id", "S"}, {"start-index", "1"}, {"length", "2"}}, tc.flags...)
|
||||
err := runUpdateDimensionForTest(t, caller, flags)
|
||||
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("err = %v, want contains %q", err, tc.want)
|
||||
}
|
||||
if caller.calls != 0 {
|
||||
t.Fatalf("calls = %d, want 0(冲突必须在发请求前拒)", caller.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 合法组合仍然放行
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
flags [][2]string
|
||||
}{
|
||||
{"standard-alone", [][2]string{{"dimension", "ROWS"}, {"size-type", "standard"}}},
|
||||
{"auto-alone", [][2]string{{"dimension", "ROWS"}, {"size-type", "auto"}}},
|
||||
{"pixel-with-size", [][2]string{{"dimension", "ROWS"}, {"size-type", "pixel"}, {"pixel-size", "40"}}},
|
||||
{"pixel-size-without-size-type", [][2]string{{"dimension", "COLUMNS"}, {"pixel-size", "120"}}},
|
||||
{"hidden-only", [][2]string{{"dimension", "ROWS"}, {"hidden", "true"}}},
|
||||
} {
|
||||
t.Run("ok/"+tc.name, func(t *testing.T) {
|
||||
caller := &scriptedToolCaller{steps: []scriptedToolStep{{text: `{"success":true}`}}}
|
||||
flags := append([][2]string{{"node", "N"}, {"sheet-id", "S"}, {"start-index", "1"}, {"length", "2"}}, tc.flags...)
|
||||
if err := runUpdateDimensionForTest(t, caller, flags); err != nil {
|
||||
t.Fatalf("合法组合被拒: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func runUpdateDimensionForTest(t *testing.T, caller *scriptedToolCaller, flags [][2]string) error {
|
||||
t.Helper()
|
||||
installScriptedCaller(t, caller)
|
||||
installSheetProductArgs(t)
|
||||
for _, c := range newDimensionCmds() {
|
||||
if c.Name() != "update-dimension" {
|
||||
continue
|
||||
}
|
||||
for _, kv := range flags {
|
||||
if err := c.Flags().Set(kv[0], kv[1]); err != nil {
|
||||
t.Fatalf("set --%s: %v", kv[0], err)
|
||||
}
|
||||
}
|
||||
return c.RunE(c, nil)
|
||||
}
|
||||
t.Fatal("update-dimension not found")
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/corecmd/contract"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
// ============================================================================
|
||||
// sheet export-csv:把单个工作表同步导出为纯 RFC4180 CSV
|
||||
//
|
||||
// 独立成一条命令而不是给 sheet export 加 --export-format csv:sheet export 的叶子
|
||||
// 契约是 interface_mode=mcp + interface_ref=submit_export_job(xlsx 异步任务)。
|
||||
// csv 是互斥分支,走的是 get_range_as_csv,submit_export_job 根本不执行;挂在同一
|
||||
// 条叶子上会让 Agent 的接口审计、参数映射和后端能力判断在 csv 场景下全都拿到错误
|
||||
// 信息。本叶子如实声明 interface_ref=get_range_as_csv,sheet export 则保持原样。
|
||||
//
|
||||
// 与 sheet csv-get 的分工:csv-get 面向 Agent 阅读,输出带 [row=N] 行号前缀并按
|
||||
// -f 渲染,只回 stdout;本命令面向落盘,输出纯 CSV、可写文件,且截断时 fail-closed。
|
||||
// ============================================================================
|
||||
|
||||
func newSheetExportCsvCmd() *cobra.Command {
|
||||
cmd := &cobra.Command{
|
||||
Use: "export-csv",
|
||||
Short: "导出单个工作表为纯 CSV(同步)",
|
||||
Long: `将钉钉在线电子表格的单个工作表同步导出为纯 RFC4180 CSV。
|
||||
|
||||
整篇表格导出为 xlsx 请用 dws sheet export(异步任务:提交→轮询→可选下载)。
|
||||
|
||||
参数说明:
|
||||
--node 表格文档 ID 或链接 URL,系统自动识别(必填)
|
||||
--sheet-id 要导出的工作表 ID 或名称(不传则第一个工作表)
|
||||
--range 导出范围,A1 表示法(不传则整表;大表可用此分块导出)
|
||||
--value-render-option 取值模式: formatted_value(默认) / raw_value / formula
|
||||
--output 本地保存路径(可选)。可为文件路径或目录(目录时存为
|
||||
sheet-export.csv);不传则把 CSV 打到 stdout
|
||||
--allow-truncated 允许数据被截断时仍然导出
|
||||
|
||||
截断行为:
|
||||
表格超出单次读取上限时默认直接报错并且不写文件,避免不完整数据被当成完整导出、
|
||||
或覆盖掉已有的完整文件。要接受不完整结果须显式加 --allow-truncated。
|
||||
|
||||
落盘保证:
|
||||
写文件走同目录临时文件 + rename 原子替换,写入中途失败(磁盘满、配额、I/O 错误)
|
||||
不会破坏已存在的目标文件。父目录不存在时报错,不会替你创建。
|
||||
|
||||
权限要求:
|
||||
当前用户对目标表格具备可查看权限。`,
|
||||
Example: ` # 导出第一个工作表到 stdout(可管道处理)
|
||||
dws sheet export-csv --node NODE_ID
|
||||
|
||||
# 导出指定工作表为本地 CSV 文件
|
||||
dws sheet export-csv --node NODE_ID --sheet-id SHEET_ID --output ./data.csv
|
||||
|
||||
# 只导出某个范围,取原始值
|
||||
dws sheet export-csv --node NODE_ID --range A1:Z1000 --value-render-option raw_value`,
|
||||
RunE: runSheetExportCsv,
|
||||
}
|
||||
DeclareLeafMetadata(cmd, LeafSpec{
|
||||
Safety: contract.SafetySpec{
|
||||
Effect: "read", Risk: "low",
|
||||
Confirmation: "not_required", Idempotency: "idempotent",
|
||||
},
|
||||
Contract: LeafContract{
|
||||
Identity: contract.ToolIdentitySpec{
|
||||
ProductID: "sheet",
|
||||
Name: "export_csv",
|
||||
CanonicalPath: "sheet.export_csv",
|
||||
CLIPath: "sheet export-csv",
|
||||
PrimaryCLIPath: "sheet export-csv",
|
||||
},
|
||||
Description: "同步导出单个工作表为纯 RFC4180 CSV(可落盘,截断即报错)。",
|
||||
DryRun: &contract.DryRunSpec{PreviewKind: "plan", RemoteReads: false},
|
||||
Interface: &contract.InterfaceSpec{
|
||||
Mode: "mcp",
|
||||
Availability: "available",
|
||||
Ref: &contract.InterfaceRefSpec{ProductID: "sheet", RPCName: "get_range_as_csv"},
|
||||
},
|
||||
Selection: contract.SelectionSpec{
|
||||
AgentSummary: "同步导出单个工作表为纯 RFC4180 CSV(可落盘,截断即报错)。",
|
||||
UseWhen: []string{"需要单个工作表的纯 CSV(写本地文件或管道处理)时"},
|
||||
AvoidWhen: []string{"要整篇表格的 xlsx 用 sheet export;只是让 Agent 读内容用 sheet csv-get(带 [row=N] 行号)"},
|
||||
Examples: []string{
|
||||
"dws sheet export-csv --node <NODE_ID> --sheet-id <SHEET_ID> --output ./data.csv",
|
||||
"dws sheet export-csv --node <NODE_ID> --range A1:Z1000",
|
||||
},
|
||||
},
|
||||
Parameters: []contract.ParamDecl{
|
||||
{Name: "node", Property: "nodeId"},
|
||||
{Name: "range", Property: "range"},
|
||||
{Name: "sheet-id", Property: "sheetId"},
|
||||
{Name: "value-render-option", Property: "valueRenderOption"},
|
||||
},
|
||||
},
|
||||
})
|
||||
cmd.Flags().String("node", "", "表格文档 ID 或 URL (必填)")
|
||||
cmd.Flags().String("sheet-id", "", "工作表 ID 或名称(不传则第一个工作表)")
|
||||
cmd.Flags().String("range", "", "导出范围,A1 表示法(不传则整表;大表可用此分块导出)")
|
||||
cmd.Flags().String("value-render-option", "", "取值模式: formatted_value(默认) / raw_value / formula")
|
||||
cmd.Flags().String("output", "", "本地保存路径(可选,支持文件路径或目录);不传则输出到 stdout")
|
||||
cmd.Flags().Bool("allow-truncated", false, "允许数据被截断时仍然导出。默认截断即报错并不写文件,避免不完整数据被当成完整导出")
|
||||
return cmd
|
||||
}
|
||||
|
||||
// valueRenderOptionEnum 是 --value-render-option 的合法取值。
|
||||
var valueRenderOptionEnum = map[string]bool{
|
||||
"formatted_value": true, "raw_value": true, "formula": true,
|
||||
}
|
||||
|
||||
// runSheetExportCsv 导出单个工作表为纯 CSV(同步,复用 get_range_as_csv,annotateRowNumbers=false)。
|
||||
func runSheetExportCsv(cmd *cobra.Command, _ []string) error {
|
||||
nodeID := mustGetFlag(cmd, "node")
|
||||
if nodeID == "" {
|
||||
return fmt.Errorf("flag --node is required")
|
||||
}
|
||||
sheetID, _ := cmd.Flags().GetString("sheet-id")
|
||||
rangeAddr, _ := cmd.Flags().GetString("range")
|
||||
valueRenderOption, _ := cmd.Flags().GetString("value-render-option")
|
||||
valueRenderOption = strings.ToLower(strings.TrimSpace(valueRenderOption))
|
||||
if valueRenderOption != "" && !valueRenderOptionEnum[valueRenderOption] {
|
||||
return fmt.Errorf("--value-render-option 必须为 formatted_value / raw_value / formula,当前值: %s", valueRenderOption)
|
||||
}
|
||||
outputPath, _ := cmd.Flags().GetString("output")
|
||||
allowTruncated, _ := cmd.Flags().GetBool("allow-truncated")
|
||||
|
||||
if deps.Caller.DryRun() {
|
||||
deps.Out.PrintKeyValue("操作", "导出工作表为 CSV")
|
||||
deps.Out.PrintKeyValue("节点", nodeID)
|
||||
if sheetID != "" {
|
||||
deps.Out.PrintKeyValue("工作表", sheetID)
|
||||
}
|
||||
if outputPath != "" {
|
||||
deps.Out.PrintKeyValue("输出", outputPath)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
toolArgs := map[string]any{
|
||||
"nodeId": nodeID,
|
||||
"annotateRowNumbers": false,
|
||||
}
|
||||
if sheetID != "" {
|
||||
toolArgs["sheetId"] = sheetID
|
||||
}
|
||||
if rangeAddr != "" {
|
||||
toolArgs["range"] = rangeAddr
|
||||
}
|
||||
if valueRenderOption != "" {
|
||||
toolArgs["valueRenderOption"] = valueRenderOption
|
||||
}
|
||||
|
||||
// CSV 正文走 stdout,进度/警告一律不能污染它。
|
||||
text, err := callMCPToolReturnText(ctx, "get_range_as_csv", toolArgs)
|
||||
if err != nil {
|
||||
return fmt.Errorf("读取 CSV 失败: %w", err)
|
||||
}
|
||||
|
||||
csvContent, hasMore, err := parseGetRangeAsCsvResult(text)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// 截断必须 fail-closed:只打 stderr 警告然后照常落盘 + 报"导出完成" + 退出码 0,
|
||||
// 会让自动化调用方(和没留意 stderr 的人)把不完整文件当成完整导出,且若目标
|
||||
// 文件已存在还会被截断数据覆盖。默认在写文件/输出之前就失败,要接受不完整结果
|
||||
// 必须显式加 --allow-truncated。
|
||||
if hasMore && !allowTruncated {
|
||||
return fmt.Errorf("表格数据超出单次读取上限,CSV 会被截断,已中止导出(未写入 %s);"+
|
||||
"请用 --range 分块导出(如 --range A1:Z1000、A1001:Z2000 ...)、改用 dws sheet export 导出完整表格的 xlsx,"+
|
||||
"或确认可接受不完整数据后加 --allow-truncated",
|
||||
firstNonEmpty(outputPath, "stdout"))
|
||||
}
|
||||
if hasMore {
|
||||
deps.Out.PrintWarning("表格数据超出单次读取上限,CSV 已被截断(--allow-truncated 已显式放行)。" +
|
||||
"请用 --range 分块导出(如 --range A1:Z1000、A1001:Z2000 ...),或改用 dws sheet export 导出完整表格的 xlsx。")
|
||||
}
|
||||
|
||||
if outputPath == "" {
|
||||
deps.Out.PrintRaw(csvContent)
|
||||
return nil
|
||||
}
|
||||
if fi, statErr := os.Stat(outputPath); statErr == nil && fi.IsDir() {
|
||||
outputPath = filepath.Join(outputPath, "sheet-export.csv")
|
||||
}
|
||||
// 必须原子替换:os.WriteFile 会先把已存在的 CSV 截断,写入中途失败(磁盘满、
|
||||
// 配额、I/O 错误)就把用户的原文件毁掉了。AtomicWrite 写同目录临时文件再 rename,
|
||||
// 失败时原文件保持不变。
|
||||
// AtomicWrite 会 MkdirAll 父目录,先探一次,保持与 sheet export 一致的「父目录
|
||||
// 不存在即报错」语义,避免把拼错的路径悄悄建成目录。
|
||||
if _, statErr := os.Stat(filepath.Dir(outputPath)); statErr != nil {
|
||||
return fmt.Errorf("写入 CSV 文件失败: %w", statErr)
|
||||
}
|
||||
if err := AtomicWrite(outputPath, []byte(csvContent), 0o644); err != nil {
|
||||
return fmt.Errorf("写入 CSV 文件失败: %w", err)
|
||||
}
|
||||
if hasMore {
|
||||
deps.Out.PrintInfo(fmt.Sprintf("导出完成(数据已截断,不是完整表格): %s", outputPath))
|
||||
return nil
|
||||
}
|
||||
deps.Out.PrintInfo(fmt.Sprintf("导出完成: %s", outputPath))
|
||||
return nil
|
||||
}
|
||||
|
||||
// parseGetRangeAsCsvResult 从 get_range_as_csv 的 MCP 响应中提取 csv 文本与 hasMore 标志。
|
||||
//
|
||||
// csv 字段缺失或类型不对,必须报错而不是当成空表:调用方会把空内容写进
|
||||
// --output,用 0 字节覆盖已有文件并打印"导出完成",等于静默数据丢失。
|
||||
// 「字段存在且为空串」是合法的(真的空区域),与「字段缺失」区分开。
|
||||
func parseGetRangeAsCsvResult(text string) (csv string, hasMore bool, err error) {
|
||||
var data map[string]any
|
||||
if e := json.Unmarshal([]byte(text), &data); e != nil {
|
||||
return "", false, fmt.Errorf("解析 get_range_as_csv 响应失败: %w", e)
|
||||
}
|
||||
if raw, wrapped := data["result"]; wrapped {
|
||||
result, ok := raw.(map[string]any)
|
||||
if !ok {
|
||||
return "", false, fmt.Errorf("解析 get_range_as_csv 响应失败: result 不是对象,响应: %s", text)
|
||||
}
|
||||
data = result
|
||||
}
|
||||
raw, exists := data["csv"]
|
||||
if !exists {
|
||||
return "", false, fmt.Errorf("解析 get_range_as_csv 响应失败: 缺少 csv 字段,响应: %s", text)
|
||||
}
|
||||
csvVal, ok := raw.(string)
|
||||
if !ok {
|
||||
return "", false, fmt.Errorf("解析 get_range_as_csv 响应失败: csv 字段不是字符串(%T),响应: %s", raw, text)
|
||||
}
|
||||
csv = csvVal
|
||||
if hm, ok := data["hasMore"].(bool); ok {
|
||||
hasMore = hm
|
||||
}
|
||||
return csv, hasMore, nil
|
||||
}
|
||||
@@ -0,0 +1,353 @@
|
||||
// Copyright 2026 Alibaba Group
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
func executeSheetExportCsv(t *testing.T, caller *scriptedToolCaller, args ...string) error {
|
||||
t.Helper()
|
||||
installScriptedCaller(t, caller)
|
||||
oldArgs := os.Args
|
||||
os.Args = []string{"dws", "sheet"}
|
||||
t.Cleanup(func() { os.Args = oldArgs })
|
||||
cmd := newSheetExportCsvCmd()
|
||||
for index := 0; index < len(args); index += 2 {
|
||||
if err := cmd.Flags().Set(args[index], args[index+1]); err != nil {
|
||||
t.Fatalf("set %s: %v", args[index], err)
|
||||
}
|
||||
}
|
||||
return runSheetExportCsv(cmd, nil)
|
||||
}
|
||||
|
||||
// export-csv 是独立叶子,不能和 xlsx 的 sheet export 共用一套 flag:混在一条命令里
|
||||
// 时,自动化漏写 --export-format csv 会让 --range 被静默丢掉、导出整篇工作簿而仍报
|
||||
// 成功。这里钉住两条命令的 flag 面互不渗透。
|
||||
func TestSheetExportAndExportCsvFlagsDoNotLeak(t *testing.T) {
|
||||
xlsxOnly := []string{}
|
||||
newExportCmd().Flags().VisitAll(func(f *pflag.Flag) { xlsxOnly = append(xlsxOnly, f.Name) })
|
||||
sort.Strings(xlsxOnly)
|
||||
if want := []string{"node", "output"}; !reflect.DeepEqual(xlsxOnly, want) {
|
||||
t.Errorf("sheet export flags = %v, want %v(csv 专属 flag 不能回到 xlsx 命令上)", xlsxOnly, want)
|
||||
}
|
||||
|
||||
csvFlags := map[string]bool{}
|
||||
newSheetExportCsvCmd().Flags().VisitAll(func(f *pflag.Flag) { csvFlags[f.Name] = true })
|
||||
for _, name := range []string{"node", "output", "sheet-id", "range", "value-render-option", "allow-truncated"} {
|
||||
if !csvFlags[name] {
|
||||
t.Errorf("sheet export-csv 缺少 flag --%s", name)
|
||||
}
|
||||
}
|
||||
// 不能出现格式路由 flag:格式由命令名决定,避免又回到单命令多分支的老问题。
|
||||
if csvFlags["export-format"] {
|
||||
t.Error("sheet export-csv 不应有 --export-format(格式已由命令名区分)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestSheetExportCsvRequiresNode(t *testing.T) {
|
||||
caller := &scriptedToolCaller{}
|
||||
err := executeSheetExportCsv(t, caller)
|
||||
if err == nil || !strings.Contains(err.Error(), "--node is required") {
|
||||
t.Fatalf("err = %v, want required node", err)
|
||||
}
|
||||
if caller.calls != 0 {
|
||||
t.Fatalf("calls = %d, want 0", caller.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// --value-render-option 的枚举必须在发请求之前校验,否则非法取值会被静默透传。
|
||||
func TestSheetExportCsvValidatesValueRenderOption(t *testing.T) {
|
||||
caller := &scriptedToolCaller{}
|
||||
err := executeSheetExportCsv(t, caller, "node", "NODE", "value-render-option", "pretty")
|
||||
if err == nil ||
|
||||
!strings.Contains(err.Error(), "--value-render-option 必须为 formatted_value / raw_value / formula") {
|
||||
t.Fatalf("err = %v, want enum rejection", err)
|
||||
}
|
||||
if caller.calls != 0 {
|
||||
t.Fatalf("calls = %d, want 0(校验必须在发请求之前)", caller.calls)
|
||||
}
|
||||
|
||||
for _, option := range []string{"formatted_value", "raw_value", "formula", "FORMULA", " raw_value "} {
|
||||
ok := &scriptedToolCaller{steps: []scriptedToolStep{{text: `{"csv":"a,b\n"}`}}}
|
||||
if err := executeSheetExportCsv(t, ok, "node", "NODE", "value-render-option", option); err != nil {
|
||||
t.Fatalf("value-render-option=%q 应被接受: %v", option, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSheetExportCsvDryRunPreviewsSelectors(t *testing.T) {
|
||||
caller := &scriptedToolCaller{dry: true}
|
||||
if err := executeSheetExportCsv(t, caller,
|
||||
"node", "NODE", "sheet-id", "SHEET_1", "output", "out.csv"); err != nil {
|
||||
t.Fatalf("csv dry run: %v", err)
|
||||
}
|
||||
if caller.calls != 0 {
|
||||
t.Fatalf("dry run 不应发请求, calls = %d", caller.calls)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSheetExportCsvForwardsSelectorsAndWarnsOnTruncation(t *testing.T) {
|
||||
caller := &scriptedToolCaller{steps: []scriptedToolStep{
|
||||
{text: `{"csv":"a,b\n","hasMore":true}`},
|
||||
}}
|
||||
// 截断默认失败,所以要显式放行才能走到落盘/输出。
|
||||
if err := executeSheetExportCsv(t, caller,
|
||||
"node", "NODE", "range", "A1:Z1000", "sheet-id", "SHEET_1",
|
||||
"value-render-option", "raw_value", "allow-truncated", "true"); err != nil {
|
||||
t.Fatalf("csv export: %v", err)
|
||||
}
|
||||
for _, kv := range [][2]string{
|
||||
{"range", "A1:Z1000"},
|
||||
{"sheetId", "SHEET_1"},
|
||||
{"valueRenderOption", "raw_value"},
|
||||
} {
|
||||
if got := caller.args[kv[0]]; got != kv[1] {
|
||||
t.Errorf("%s 未透传: %#v", kv[0], got)
|
||||
}
|
||||
}
|
||||
// csv 正文不带行号前缀,annotateRowNumbers 必须显式关掉。
|
||||
if caller.args["annotateRowNumbers"] != false {
|
||||
t.Fatalf("annotateRowNumbers = %#v, want false", caller.args["annotateRowNumbers"])
|
||||
}
|
||||
}
|
||||
|
||||
// 截断必须 fail-closed:默认报错、不写文件、不报“导出完成”。否则自动化调用方会把
|
||||
// 不完整文件当成完整导出,且已存在的目标文件会被截断数据覆盖。
|
||||
func TestSheetExportCsvFailsOnTruncationWithoutOptIn(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
out := filepath.Join(dir, "out.csv")
|
||||
if err := os.WriteFile(out, []byte("PREEXISTING\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
caller := &scriptedToolCaller{steps: []scriptedToolStep{
|
||||
{text: `{"csv":"a,b\n","hasMore":true}`},
|
||||
}}
|
||||
err := executeSheetExportCsv(t, caller, "node", "NODE", "output", out)
|
||||
if err == nil {
|
||||
t.Fatal("截断时未放行应报错,而非静默成功")
|
||||
}
|
||||
for _, want := range []string{"截断", "已中止导出", "--allow-truncated"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Errorf("错误信息缺少 %q: %v", want, err)
|
||||
}
|
||||
}
|
||||
// 关键:既有文件必须保持原样,不能被截断数据覆盖。
|
||||
body, readErr := os.ReadFile(out)
|
||||
if readErr != nil {
|
||||
t.Fatalf("read output: %v", readErr)
|
||||
}
|
||||
if string(body) != "PREEXISTING\n" {
|
||||
t.Fatalf("目标文件被截断数据覆盖了: %q", string(body))
|
||||
}
|
||||
}
|
||||
|
||||
// 显式放行后允许落盘,但成功信息必须点明数据不完整。
|
||||
func TestSheetExportCsvAllowTruncatedWritesAndFlagsIncompleteness(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
out := filepath.Join(dir, "out.csv")
|
||||
caller := &scriptedToolCaller{steps: []scriptedToolStep{
|
||||
{text: `{"csv":"a,b\n","hasMore":true}`},
|
||||
}}
|
||||
if err := executeSheetExportCsv(t, caller,
|
||||
"node", "NODE", "output", out, "allow-truncated", "true"); err != nil {
|
||||
t.Fatalf("allow-truncated 应允许导出: %v", err)
|
||||
}
|
||||
body, err := os.ReadFile(out)
|
||||
if err != nil {
|
||||
t.Fatalf("read output: %v", err)
|
||||
}
|
||||
if string(body) != "a,b\n" {
|
||||
t.Fatalf("csv 内容 = %q", string(body))
|
||||
}
|
||||
}
|
||||
|
||||
// 未截断时不受影响:不需要 --allow-truncated,成功信息也不提不完整。
|
||||
func TestSheetExportCsvCompleteReadNeedsNoOptIn(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
out := filepath.Join(dir, "out.csv")
|
||||
caller := &scriptedToolCaller{steps: []scriptedToolStep{{text: `{"csv":"a,b\n","hasMore":false}`}}}
|
||||
if err := executeSheetExportCsv(t, caller, "node", "NODE", "output", out); err != nil {
|
||||
t.Fatalf("完整读取不应要求放行: %v", err)
|
||||
}
|
||||
body, err := os.ReadFile(out)
|
||||
if err != nil || string(body) != "a,b\n" {
|
||||
t.Fatalf("csv 内容 = %q, err = %v", string(body), err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSheetExportCsvWritesIntoDirectory(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
caller := &scriptedToolCaller{steps: []scriptedToolStep{{text: `{"csv":"a,b\n"}`}}}
|
||||
if err := executeSheetExportCsv(t, caller, "node", "NODE", "output", dir); err != nil {
|
||||
t.Fatalf("csv export: %v", err)
|
||||
}
|
||||
body, err := os.ReadFile(filepath.Join(dir, "sheet-export.csv"))
|
||||
if err != nil {
|
||||
t.Fatalf("read exported csv: %v", err)
|
||||
}
|
||||
if string(body) != "a,b\n" {
|
||||
t.Fatalf("csv 内容 = %q", string(body))
|
||||
}
|
||||
}
|
||||
|
||||
// 落盘失败必须保住已有文件:os.WriteFile 会先截断目标,写到一半失败(磁盘满、
|
||||
// 配额、I/O 错误)用户的原文件就没了。走 AtomicWrite 后失败只丢临时文件。
|
||||
func TestSheetExportCsvWriteFailureKeepsExistingFile(t *testing.T) {
|
||||
out := filepath.Join(t.TempDir(), "existing.csv")
|
||||
const original = "原有重要数据\n1,2,3\n"
|
||||
if err := os.WriteFile(out, []byte(original), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// 模拟"临时文件写完、替换目标时失败",这是 os.WriteFile 会毁掉原文件的时刻。
|
||||
previousRename := atomicRename
|
||||
t.Cleanup(func() { atomicRename = previousRename })
|
||||
atomicRename = func(string, string) error { return errors.New("no space left on device") }
|
||||
|
||||
caller := &scriptedToolCaller{steps: []scriptedToolStep{{text: `{"csv":"a,b\n"}`}}}
|
||||
err := executeSheetExportCsv(t, caller, "node", "NODE", "output", out)
|
||||
if err == nil || !strings.Contains(err.Error(), "写入 CSV 文件失败") {
|
||||
t.Fatalf("err = %v, want write failure", err)
|
||||
}
|
||||
|
||||
body, readErr := os.ReadFile(out)
|
||||
if readErr != nil {
|
||||
t.Fatalf("read output: %v", readErr)
|
||||
}
|
||||
if string(body) != original {
|
||||
t.Fatalf("写入失败后原文件被破坏为 %q,应保持不变", string(body))
|
||||
}
|
||||
|
||||
// 临时文件不能留在目录里冒充导出产物。
|
||||
entries, readDirErr := os.ReadDir(filepath.Dir(out))
|
||||
if readDirErr != nil {
|
||||
t.Fatalf("read dir: %v", readDirErr)
|
||||
}
|
||||
if len(entries) != 1 || entries[0].Name() != filepath.Base(out) {
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, entry := range entries {
|
||||
names = append(names, entry.Name())
|
||||
}
|
||||
t.Fatalf("目录残留临时文件: %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSheetExportCsvReportsWriteFailure(t *testing.T) {
|
||||
caller := &scriptedToolCaller{steps: []scriptedToolStep{{text: `{"csv":"a,b\n"}`}}}
|
||||
missing := filepath.Join(t.TempDir(), "no-such-dir", "out.csv")
|
||||
err := executeSheetExportCsv(t, caller, "node", "NODE", "output", missing)
|
||||
if err == nil || !strings.Contains(err.Error(), "写入 CSV 文件失败") {
|
||||
t.Fatalf("err = %v, want write failure", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSheetExportCsvReportsReadFailure(t *testing.T) {
|
||||
caller := &scriptedToolCaller{steps: []scriptedToolStep{{text: `{"errorCode":"NoPermission"}`}}}
|
||||
err := executeSheetExportCsv(t, caller, "node", "NODE")
|
||||
if err == nil || !strings.Contains(err.Error(), "读取 CSV 失败") {
|
||||
t.Fatalf("err = %v, want read failure", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseGetRangeAsCsvResult(t *testing.T) {
|
||||
// 兼容裸响应与 result 包装两种形状
|
||||
for _, body := range []string{
|
||||
`{"csv":"a,b\n","hasMore":true}`,
|
||||
`{"result":{"csv":"a,b\n","hasMore":true}}`,
|
||||
} {
|
||||
csv, hasMore, err := parseGetRangeAsCsvResult(body)
|
||||
if err != nil || csv != "a,b\n" || !hasMore {
|
||||
t.Fatalf("parseGetRangeAsCsvResult(%s) = (%q,%v,%v)", body, csv, hasMore, err)
|
||||
}
|
||||
}
|
||||
// 字段存在但为空串是合法的(真的空区域)
|
||||
csv, hasMore, err := parseGetRangeAsCsvResult(`{"csv":""}`)
|
||||
if err != nil || csv != "" || hasMore {
|
||||
t.Fatalf(`csv:"" = (%q,%v,%v), want ("",false,nil)`, csv, hasMore, err)
|
||||
}
|
||||
}
|
||||
|
||||
// csv 字段缺失或类型不对必须报错。此前会被当成空表,配合 --output 会用
|
||||
// 0 字节覆盖已有文件并打印"导出完成",属于静默数据丢失。
|
||||
func TestParseGetRangeAsCsvResultRejectsMissingOrBadCsvField(t *testing.T) {
|
||||
for _, tc := range []struct{ body, want string }{
|
||||
{"not json", "解析 get_range_as_csv 响应失败"},
|
||||
{`{"message":"something odd"}`, "缺少 csv 字段"},
|
||||
{`{"csv":123}`, "csv 字段不是字符串"},
|
||||
{`{"csv":null}`, "csv 字段不是字符串"},
|
||||
{`{"result":"not-an-object"}`, "result 不是对象"},
|
||||
{`{"result":{"message":"odd"}}`, "缺少 csv 字段"},
|
||||
} {
|
||||
if _, _, err := parseGetRangeAsCsvResult(tc.body); err == nil ||
|
||||
!strings.Contains(err.Error(), tc.want) {
|
||||
t.Errorf("parseGetRangeAsCsvResult(%s) err = %v, want contains %q", tc.body, err, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 端到端:响应缺 csv 字段时,绝不能覆盖 --output 指向的已有文件。
|
||||
func TestSheetExportCsvNeverTruncatesOutputOnBadResponse(t *testing.T) {
|
||||
out := filepath.Join(t.TempDir(), "existing.csv")
|
||||
const original = "原有重要数据\n1,2,3\n"
|
||||
if err := os.WriteFile(out, []byte(original), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
caller := &scriptedToolCaller{steps: []scriptedToolStep{{text: `{"message":"something odd"}`}}}
|
||||
err := executeSheetExportCsv(t, caller, "node", "NODE", "output", out)
|
||||
if err == nil || !strings.Contains(err.Error(), "缺少 csv 字段") {
|
||||
t.Fatalf("err = %v, want missing csv field", err)
|
||||
}
|
||||
body, readErr := os.ReadFile(out)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if string(body) != original {
|
||||
t.Fatalf("已有文件被改写为 %q,原内容应保持不变", string(body))
|
||||
}
|
||||
}
|
||||
|
||||
// CSV 正文走 stdout,截断警告必须只走 stderr:否则管道/重定向拿到的文件里会
|
||||
// 混入 [WARN] 文本,不再是合法 RFC4180 CSV。而大表恰恰最容易触发这个分支。
|
||||
func TestSheetExportCsvKeepsStdoutPureAndWarnsOnStderr(t *testing.T) {
|
||||
previousDeps := deps
|
||||
t.Cleanup(func() { deps = previousDeps })
|
||||
|
||||
caller := &scriptedToolCaller{steps: []scriptedToolStep{{text: `{"csv":"a,b\nc,d\n","hasMore":true}`}}}
|
||||
installScriptedCaller(t, caller)
|
||||
installSheetProductArgs(t)
|
||||
var stdout, stderr bytes.Buffer
|
||||
deps.Out.w, deps.Out.errW = &stdout, &stderr
|
||||
|
||||
cmd := newSheetExportCsvCmd()
|
||||
// 截断默认 fail-closed;本用例验证的是放行后 stdout 仍然纯净、警告只走 stderr。
|
||||
for _, kv := range [][2]string{{"node", "NODE"}, {"allow-truncated", "true"}} {
|
||||
if err := cmd.Flags().Set(kv[0], kv[1]); err != nil {
|
||||
t.Fatalf("set --%s: %v", kv[0], err)
|
||||
}
|
||||
}
|
||||
if err := runSheetExportCsv(cmd, nil); err != nil {
|
||||
t.Fatalf("csv export: %v", err)
|
||||
}
|
||||
|
||||
if got := stdout.String(); got != "a,b\nc,d\n" {
|
||||
t.Fatalf("stdout = %q, want 纯 CSV 正文", got)
|
||||
}
|
||||
if strings.Contains(stdout.String(), "WARN") || strings.Contains(stdout.String(), "截断") {
|
||||
t.Fatalf("stdout 混入了警告文本: %q", stdout.String())
|
||||
}
|
||||
if !strings.Contains(stderr.String(), "CSV 已被截断") {
|
||||
t.Fatalf("stderr = %q, want 截断提示", stderr.String())
|
||||
}
|
||||
}
|
||||
+599
-373
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,376 @@
|
||||
// Copyright 2026 Alibaba Group
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
|
||||
package helpers
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"github.com/spf13/pflag"
|
||||
)
|
||||
|
||||
// 跨 range 累计单元格预算(对齐飞书 checkBatchStampBudget)。
|
||||
//
|
||||
// 每个 "S!A1:Z1000" 是 26×1000=26000 格:单独看都在 buildStyleCells 的
|
||||
// 单区域上限(rows≤1000、rows×cols≤30000)之内,所以只有累计预算能拦住它们。
|
||||
// 7 个 = 182000 通过,8 个 = 208000 越过 200000 上限。
|
||||
const budgetTestRange = "A1:Z1000"
|
||||
|
||||
func budgetTestRanges(n int) []string {
|
||||
out := make([]string, 0, n)
|
||||
for i := 0; i < n; i++ {
|
||||
out = append(out, fmt.Sprintf("Sheet%d!%s", i+1, budgetTestRange))
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func newBatchStyleCmdWithStyle(t *testing.T) *cobra.Command {
|
||||
t.Helper()
|
||||
cmd := newRangeBatchSetStyleCmd()
|
||||
if err := cmd.Flags().Set("bg-color", "#FFF2CC"); err != nil {
|
||||
t.Fatalf("set --bg-color: %v", err)
|
||||
}
|
||||
return cmd
|
||||
}
|
||||
|
||||
func TestBatchStyleRangesRespectAggregateCellBudget(t *testing.T) {
|
||||
// 7 个区域刚好在预算内:必须成功,且每个区域各产出一个 op。
|
||||
within, err := json.Marshal(budgetTestRanges(7))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ops, err := buildBatchStyleOpsFromRanges(newBatchStyleCmdWithStyle(t), string(within))
|
||||
if err != nil {
|
||||
t.Fatalf("7 个区域(累计 182000 格)应在预算内: %v", err)
|
||||
}
|
||||
if len(ops) != 7 {
|
||||
t.Fatalf("operations = %d, want 7", len(ops))
|
||||
}
|
||||
|
||||
// 第 8 个把累计推到 208000,越过 200000 上限。
|
||||
over, err := json.Marshal(budgetTestRanges(8))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
_, err = buildBatchStyleOpsFromRanges(newBatchStyleCmdWithStyle(t), string(over))
|
||||
if err == nil {
|
||||
t.Fatal("8 个区域(累计 208000 格)必须被累计预算拒绝")
|
||||
}
|
||||
for _, want := range []string{"--ranges[7]", "208000", "200000"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("error = %v, want contains %q", err, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchStyleFileRespectsAggregateCellBudgetAndItemCap(t *testing.T) {
|
||||
writeBatch := func(t *testing.T, items []map[string]any) string {
|
||||
t.Helper()
|
||||
data, err := json.Marshal(items)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
path := filepath.Join(t.TempDir(), "styles.json")
|
||||
if err := os.WriteFile(path, data, 0o600); err != nil {
|
||||
t.Fatalf("write batch fixture: %v", err)
|
||||
}
|
||||
return path
|
||||
}
|
||||
item := func(i int) map[string]any {
|
||||
return map[string]any{
|
||||
"sheetId": fmt.Sprintf("Sheet%d", i+1),
|
||||
"range": budgetTestRange,
|
||||
"fontWeight": "bold",
|
||||
}
|
||||
}
|
||||
|
||||
// 累计预算:8 条 × 26000 = 208000 > 200000。
|
||||
overBudget := make([]map[string]any, 0, 8)
|
||||
for i := 0; i < 8; i++ {
|
||||
overBudget = append(overBudget, item(i))
|
||||
}
|
||||
_, err := buildBatchStyleOpsFromFile(writeBatch(t, overBudget))
|
||||
if err == nil {
|
||||
t.Fatal("--batch 累计 208000 格必须被拒绝")
|
||||
}
|
||||
for _, want := range []string{"第 8/8 条", "208000", "200000"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("error = %v, want contains %q", err, want)
|
||||
}
|
||||
}
|
||||
|
||||
// 条数上限与 --ranges 对齐:101 条应在展开任何矩阵之前就被拒。
|
||||
tooMany := make([]map[string]any, 0, maxBatchStyleRanges+1)
|
||||
for i := 0; i < maxBatchStyleRanges+1; i++ {
|
||||
tooMany = append(tooMany, map[string]any{
|
||||
"sheetId": "Sheet1", "range": "A1", "fontWeight": "bold",
|
||||
})
|
||||
}
|
||||
_, err = buildBatchStyleOpsFromFile(writeBatch(t, tooMany))
|
||||
if err == nil || !strings.Contains(err.Error(), "--batch 最多 100 条") {
|
||||
t.Fatalf("error = %v, want --batch item cap", err)
|
||||
}
|
||||
|
||||
// 预算内的正常配置仍然照常展开。
|
||||
ops, err := buildBatchStyleOpsFromFile(writeBatch(t, []map[string]any{item(0), item(1)}))
|
||||
if err != nil {
|
||||
t.Fatalf("2 条应在预算内: %v", err)
|
||||
}
|
||||
if len(ops) != 2 {
|
||||
t.Fatalf("operations = %d, want 2", len(ops))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAddBatchStyleCellsAccumulatesAcrossCalls(t *testing.T) {
|
||||
var total int64
|
||||
if err := addBatchStyleCells(&total, 1000, 26); err != nil {
|
||||
t.Fatalf("first range: %v", err)
|
||||
}
|
||||
if total != 26000 {
|
||||
t.Fatalf("total = %d, want 26000", total)
|
||||
}
|
||||
// 单次就越界也必须拦住(累计器同时覆盖单区域巨量输入)。
|
||||
var single int64
|
||||
if err := addBatchStyleCells(&single, 1000, 1000); err == nil {
|
||||
t.Fatal("1000x1000=1000000 必须超出累计预算")
|
||||
}
|
||||
}
|
||||
|
||||
// styleFlagNames 是手工维护的,必须与 bindStyleFlags 实际绑定的 flag 严格一致:
|
||||
// 漏登记会让 --batch 的互斥检查放过一个静默失效的 flag。
|
||||
func TestStyleFlagNamesMatchBoundFlags(t *testing.T) {
|
||||
probe := &cobra.Command{Use: "probe"}
|
||||
bindStyleFlags(probe)
|
||||
|
||||
bound := map[string]bool{}
|
||||
probe.Flags().VisitAll(func(f *pflag.Flag) { bound[f.Name] = true })
|
||||
|
||||
listed := map[string]bool{}
|
||||
for _, name := range styleFlagNames {
|
||||
if listed[name] {
|
||||
t.Fatalf("styleFlagNames 重复登记 %q", name)
|
||||
}
|
||||
listed[name] = true
|
||||
if !bound[name] {
|
||||
t.Errorf("styleFlagNames 登记了 %q,但 bindStyleFlags 没有绑定它", name)
|
||||
}
|
||||
}
|
||||
for name := range bound {
|
||||
if !listed[name] {
|
||||
t.Errorf("bindStyleFlags 绑定了 %q,但 styleFlagNames 漏登记(--batch 互斥检查会放过它)", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchSetStyleRejectsStyleFlagsInBatchMode(t *testing.T) {
|
||||
previousDeps := deps
|
||||
t.Cleanup(func() { deps = previousDeps })
|
||||
|
||||
batchPath := filepath.Join(t.TempDir(), "styles.json")
|
||||
if err := os.WriteFile(batchPath, []byte(`[{"sheetId":"Sheet1","range":"A1:B2","fontWeight":"bold"}]`), 0o600); err != nil {
|
||||
t.Fatalf("write batch fixture: %v", err)
|
||||
}
|
||||
|
||||
caller := &sheetStyleDryRunCaller{format: "json"}
|
||||
InitDeps(caller)
|
||||
|
||||
cmd := newRangeBatchSetStyleCmd()
|
||||
cmd.SetOut(io.Discard)
|
||||
cmd.SetErr(io.Discard)
|
||||
cmd.SilenceErrors = true
|
||||
cmd.SilenceUsage = true
|
||||
cmd.SetArgs([]string{"--node", "NODE_ID", "--batch", batchPath, "--bg-color", "#FFF2CC", "--font-family", "Arial"})
|
||||
err := cmd.Execute()
|
||||
if err == nil {
|
||||
t.Fatal("--batch 搭配命令行样式 flag 必须报错,而不是静默忽略")
|
||||
}
|
||||
for _, want := range []string{"--batch 模式下样式来自配置文件", "--bg-color", "--font-family"} {
|
||||
if !strings.Contains(err.Error(), want) {
|
||||
t.Fatalf("error = %v, want contains %q", err, want)
|
||||
}
|
||||
}
|
||||
if caller.calls != 0 {
|
||||
t.Fatalf("remote CallTool count = %d, want 0", caller.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// buildBatchStyleOpsFromRanges 的每条前置校验都必须在组装 operations 之前拦住。
|
||||
func TestBatchStyleRangesRejectsInvalidInput(t *testing.T) {
|
||||
tooMany := make([]string, 0, maxBatchStyleRanges+1)
|
||||
for i := 0; i <= maxBatchStyleRanges; i++ {
|
||||
tooMany = append(tooMany, `"Sheet1!A1"`)
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
ranges string
|
||||
style bool
|
||||
want string
|
||||
}{
|
||||
{name: "bad-json", ranges: `[`, style: true, want: "--ranges JSON 解析失败"},
|
||||
{name: "empty-array", ranges: `[]`, style: true, want: "--ranges 不能为空数组"},
|
||||
{
|
||||
name: "over-range-cap",
|
||||
ranges: "[" + strings.Join(tooMany, ",") + "]",
|
||||
style: true,
|
||||
want: "--ranges 最多 100 项",
|
||||
},
|
||||
{
|
||||
name: "missing-sheet-prefix",
|
||||
ranges: `["A1:B2"]`,
|
||||
style: true,
|
||||
want: "必须包含工作表前缀",
|
||||
},
|
||||
{
|
||||
name: "blank-sheet-prefix",
|
||||
ranges: `[" !A1:B2"]`,
|
||||
style: true,
|
||||
want: "必须包含工作表前缀",
|
||||
},
|
||||
{
|
||||
name: "blank-range-after-prefix",
|
||||
ranges: `["Sheet1! "]`,
|
||||
style: true,
|
||||
want: "必须包含工作表前缀",
|
||||
},
|
||||
{
|
||||
name: "bad-range-address",
|
||||
ranges: `["Sheet1!zz"]`,
|
||||
style: true,
|
||||
want: "解析失败",
|
||||
},
|
||||
{
|
||||
name: "no-style-flag",
|
||||
ranges: `["Sheet1!A1:B2"]`,
|
||||
style: false,
|
||||
want: "至少需要指定一个样式参数",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
cmd := newRangeBatchSetStyleCmd()
|
||||
if tc.style {
|
||||
if err := cmd.Flags().Set("bg-color", "#FFF2CC"); err != nil {
|
||||
t.Fatalf("set --bg-color: %v", err)
|
||||
}
|
||||
}
|
||||
_, err := buildBatchStyleOpsFromRanges(cmd, tc.ranges)
|
||||
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("err = %v, want contains %q", err, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 空白工作表标识必须在下发之前被拒绝 —— 三条入口共用同一条不变量。
|
||||
//
|
||||
// 只按原始串里 ! 的位置判断," !A1:B2" 会拆出空工作表名,操作却照样带着
|
||||
// sheetId:"" 提交:服务端要么让整批 batch_update 失败,要么落到默认工作表而不是
|
||||
// 用户指定的那张表(后者更糟,因为命令报成功)。--batch 的纯空白 sheetId 同理,
|
||||
// 它此前只挡 == ""。三条路径都必须在发请求之前失败。
|
||||
func TestBlankSheetIdentifierIsRejectedBeforeAnyRemoteCall(t *testing.T) {
|
||||
previousDeps := deps
|
||||
t.Cleanup(func() { deps = previousDeps })
|
||||
|
||||
batchDir := t.TempDir()
|
||||
writeBatch := func(t *testing.T, name, body string) string {
|
||||
t.Helper()
|
||||
p := filepath.Join(batchDir, name)
|
||||
if err := os.WriteFile(p, []byte(body), 0o600); err != nil {
|
||||
t.Fatalf("write batch fixture: %v", err)
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cmd func() *cobra.Command
|
||||
args func(t *testing.T) []string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "set-style-ranges-blank-sheet",
|
||||
cmd: newRangeBatchSetStyleCmd,
|
||||
args: func(*testing.T) []string {
|
||||
return []string{"--node", "NODE_ID", "--ranges", `[" !A1:B2"]`, "--bg-color", "#FFF2CC"}
|
||||
},
|
||||
want: "必须包含工作表前缀",
|
||||
},
|
||||
{
|
||||
name: "set-style-batch-blank-sheet-id",
|
||||
cmd: newRangeBatchSetStyleCmd,
|
||||
args: func(t *testing.T) []string {
|
||||
p := writeBatch(t, "blank-sheet.json", `[{"sheetId":" ","range":"A1:B2","fontWeight":"bold"}]`)
|
||||
return []string{"--node", "NODE_ID", "--batch", p}
|
||||
},
|
||||
want: "缺少 sheetId 或 range",
|
||||
},
|
||||
{
|
||||
name: "set-style-batch-blank-range",
|
||||
cmd: newRangeBatchSetStyleCmd,
|
||||
args: func(t *testing.T) []string {
|
||||
p := writeBatch(t, "blank-range.json", `[{"sheetId":"Sheet1","range":" ","fontWeight":"bold"}]`)
|
||||
return []string{"--node", "NODE_ID", "--batch", p}
|
||||
},
|
||||
want: "缺少 sheetId 或 range",
|
||||
},
|
||||
{
|
||||
name: "batch-clear-ranges-blank-sheet",
|
||||
cmd: rangeBatchClearCoverageCommand,
|
||||
args: func(*testing.T) []string {
|
||||
return []string{"--node", "NODE_ID", "--ranges", `[" !A1:B2"]`}
|
||||
},
|
||||
want: "必须包含工作表前缀",
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
caller := &sheetStyleDryRunCaller{format: "json"}
|
||||
InitDeps(caller)
|
||||
deps.Out.w = io.Discard
|
||||
deps.Out.errW = io.Discard
|
||||
|
||||
cmd := tc.cmd()
|
||||
cmd.SetArgs(tc.args(t))
|
||||
cmd.SilenceUsage, cmd.SilenceErrors = true, true
|
||||
err := cmd.Execute()
|
||||
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("err = %v, want contains %q", err, tc.want)
|
||||
}
|
||||
if caller.calls != 0 {
|
||||
t.Fatalf("remote CallTool count = %d, want 0", caller.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 判空看修剪后的值,但下发仍用原值:sheetId 可以是工作表**名**,名字允许带首尾
|
||||
// 空格,替用户修剪会指向另一张表。--batch 是需要精确名字时的入口,必须原样透传。
|
||||
func TestBatchStyleSheetIDIsSentVerbatimNotTrimmed(t *testing.T) {
|
||||
p := filepath.Join(t.TempDir(), "padded.json")
|
||||
if err := os.WriteFile(p, []byte(`[{"sheetId":" Sheet1 ","range":" A1:B2 ","fontWeight":"bold"}]`), 0o600); err != nil {
|
||||
t.Fatalf("write batch fixture: %v", err)
|
||||
}
|
||||
|
||||
ops, err := buildBatchStyleOpsFromFile(p)
|
||||
if err != nil {
|
||||
t.Fatalf("buildBatchStyleOpsFromFile = %v, want accepted", err)
|
||||
}
|
||||
if len(ops) != 1 {
|
||||
t.Fatalf("operations = %d, want 1", len(ops))
|
||||
}
|
||||
op, _ := ops[0].(map[string]any)
|
||||
input, _ := op["input"].(map[string]any)
|
||||
if input["sheetId"] != " Sheet1 " {
|
||||
t.Fatalf("sheetId = %#v, want %q (verbatim)", input["sheetId"], " Sheet1 ")
|
||||
}
|
||||
if input["rangeAddress"] != " A1:B2 " {
|
||||
t.Fatalf("rangeAddress = %#v, want %q (verbatim)", input["rangeAddress"], " A1:B2 ")
|
||||
}
|
||||
}
|
||||
@@ -12,17 +12,16 @@ func TestCrossPlatformCoverageSheetStyleRangeAndFontCoverage(t *testing.T) {
|
||||
for _, raw := range []string{"", "Sheet1!A1:B2", "B2:A1", "A1", "A", "1", "A0", "A-1", "A1:bad"} {
|
||||
_, _, _ = parseA1Range(raw)
|
||||
}
|
||||
_ = fillStringMatrix(2, 2, "x")
|
||||
_ = fillIntMatrix(2, 2, 1)
|
||||
for _, spec := range []*styleSpec{
|
||||
{FontSize: 1, FontSizesJSON: `[[1]]`},
|
||||
{FontSize: -1},
|
||||
{FontSize: 12},
|
||||
{FontSizesJSON: `{`},
|
||||
{FontSizesJSON: `[[1,2]]`},
|
||||
{FontSizesJSON: `[[1]]`},
|
||||
for _, tc := range []struct {
|
||||
scalar int
|
||||
jsonStr string
|
||||
}{
|
||||
{1, `[[1]]`}, {-1, ""}, {12, ""}, {0, `{`}, {0, `[[1,2]]`}, {0, `[[1]]`}, {0, ""},
|
||||
} {
|
||||
_ = applyFontSize(spec, 1, 1, map[string]any{})
|
||||
if get, err := intGrid(tc.scalar, tc.jsonStr, "font-size", 1, 1); err == nil && get != nil {
|
||||
_, _ = get(0, 0)
|
||||
_, _ = get(9, 9)
|
||||
}
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
scalar, raw string
|
||||
@@ -32,7 +31,17 @@ func TestCrossPlatformCoverageSheetStyleRangeAndFontCoverage(t *testing.T) {
|
||||
{"", "", nil}, {"", `{`, nil}, {"", `[["x","y"]]`, nil},
|
||||
{"", `[[""]]`, hAlignEnum}, {"", `[["bad"]]`, hAlignEnum}, {"", `[["left"]]`, hAlignEnum},
|
||||
} {
|
||||
_ = apply2DString(tc.scalar, tc.raw, 1, 1, "align", "alignments", tc.enum, map[string]any{})
|
||||
if get, err := strGrid(tc.scalar, tc.raw, "align", tc.enum, 1, 1); err == nil && get != nil {
|
||||
_, _ = get(0, 0)
|
||||
_, _ = get(9, 9)
|
||||
}
|
||||
}
|
||||
for _, raw := range []string{"", `{`, `{}`, `{"nope":{"style":"solid"}}`, `{"top":{}}`,
|
||||
`{"top":{"style":"bogus"}}`, `{"top":{"style":"solid"}}`, `{"top":{"style":"solid","color":"#000"}}`} {
|
||||
_, _ = parseBorderStyles(raw)
|
||||
}
|
||||
for _, raw := range []string{"Sheet1!A1:B2", "A1:B2", "Sheet1!", "!A1"} {
|
||||
_, _, _ = splitSheetPrefixedRange(raw, 0)
|
||||
}
|
||||
_ = maxColLenStr([][]string{{}, {"a", "b"}})
|
||||
_ = maxColLen2D([][]int{{}, {1, 2}})
|
||||
@@ -46,8 +55,16 @@ func TestCrossPlatformCoverageSheetStyleRangeAndFontCoverage(t *testing.T) {
|
||||
{styleSpec{}, 0, 1}, {styleSpec{}, 1001, 1}, {styleSpec{}, 1000, 31},
|
||||
{styleSpec{WordWrap: "invalid"}, 1, 1}, {styleSpec{WordWrap: "clip"}, 1, 1},
|
||||
{styleSpec{NumberFormat: "General"}, 1, 1}, {styleSpec{}, 1, 1},
|
||||
{styleSpec{FontStyle: "bogus"}, 1, 1}, {styleSpec{FontStyle: "italic"}, 1, 1},
|
||||
{styleSpec{FontLine: "bogus"}, 1, 1}, {styleSpec{FontLine: "underline"}, 1, 1},
|
||||
{styleSpec{FontLine: "line-through"}, 1, 1}, {styleSpec{FontLine: "none"}, 1, 1},
|
||||
{styleSpec{FontFamily: "Arial"}, 1, 1},
|
||||
{styleSpec{BorderStylesJSON: `{"top":{"style":"solid"}}`}, 1, 1},
|
||||
{styleSpec{BorderStylesJSON: `{`}, 1, 1},
|
||||
{styleSpec{BgColor: "#FFF", FontSize: 12, HAlign: "center", VAlign: "top",
|
||||
FontColor: "#000", FontWeight: "bold"}, 2, 2},
|
||||
} {
|
||||
_ = applyStyleSpec(&tc.spec, tc.rows, tc.cols, map[string]any{})
|
||||
_, _ = buildStyleCells(&tc.spec, tc.rows, tc.cols)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -62,16 +62,22 @@ func TestCrossPlatformCoverageRangeBatchSetStyleDryRunNeverCallsRemote(t *testin
|
||||
if err := json.Unmarshal(output.Bytes(), &payload); err != nil {
|
||||
t.Fatalf("JSON dry-run stdout must be one document: %v\n%s", err, preview)
|
||||
}
|
||||
results, _ := payload["results"].([]any)
|
||||
if len(results) != 1 {
|
||||
t.Fatalf("JSON dry-run results = %#v", payload["results"])
|
||||
// batch-set-style 现在组装为一次 batch_update 原子提交,
|
||||
// dry-run 因此是单条标准记录,而不是本地循环产生的 results 数组。
|
||||
if payload["tool"] != "batch_update" {
|
||||
t.Fatalf("JSON dry-run tool = %#v, want batch_update", payload["tool"])
|
||||
}
|
||||
entry, _ := results[0].(map[string]any)
|
||||
if entry["dryRun"] != true || entry["tool"] != "update_range" {
|
||||
t.Fatalf("JSON dry-run result = %#v", entry)
|
||||
args, _ := payload["arguments"].(map[string]any)
|
||||
ops, _ := args["operations"].([]any)
|
||||
if len(ops) != 1 {
|
||||
t.Fatalf("JSON dry-run operations = %#v, want 1 item", args["operations"])
|
||||
}
|
||||
op, _ := ops[0].(map[string]any)
|
||||
if op["toolName"] != "set_cell_range" {
|
||||
t.Fatalf("JSON dry-run operation toolName = %#v", op["toolName"])
|
||||
}
|
||||
} else {
|
||||
for _, want := range []string{"Tool:", "update_range", "Arguments:"} {
|
||||
for _, want := range []string{"Tool:", "batch_update", "set_cell_range", "Arguments:"} {
|
||||
if !strings.Contains(preview, want) {
|
||||
t.Fatalf("dry-run preview missing %q:\n%s", want, preview)
|
||||
}
|
||||
@@ -104,3 +110,104 @@ func TestRangeBatchSetStylePropagatesJSONWriteFailure(t *testing.T) {
|
||||
t.Fatalf("remote CallTool count = %d, want 0", caller.calls)
|
||||
}
|
||||
}
|
||||
|
||||
// 边框每条边只认 style / color。写错的键(colour)或类型不对的 color 此前被静默
|
||||
// 忽略:命令报成功,却画出一条没有颜色的边框。这与 --sheets / --styles 拒绝未知键
|
||||
// 是同一条不变量,三条使用路径(单区域 flag、batch、create-with-data --styles)共用
|
||||
// parseBorderStyles,所以核心在这里一次验完,再逐路径确认拒绝发生在发请求之前。
|
||||
func TestParseBorderStylesRejectsUnknownAndMistypedEdgeFields(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
json string
|
||||
want string
|
||||
}{
|
||||
{"near-miss-color-key", `{"top":{"style":"solid","colour":"#f00"}}`, `未知字段 "colour"`},
|
||||
{"unknown-key", `{"top":{"style":"solid","width":2}}`, `未知字段 "width"`},
|
||||
{"camel-case-alias-hinted", `{"top":{"style":"solid","Color":"#f00"}}`, `应为 "color"`},
|
||||
{"color-not-string", `{"top":{"style":"solid","color":123}}`, "color 必须是字符串,实际是 float64"},
|
||||
{"color-empty-string", `{"top":{"style":"solid","color":""}}`, "color 不能为空字符串"},
|
||||
{"style-not-string", `{"top":{"style":123}}`, "style 必须是字符串,实际是 float64"},
|
||||
{"style-empty-string", `{"top":{"style":""}}`, "缺少 style"},
|
||||
{"style-missing", `{"top":{"color":"#f00"}}`, "缺少 style"},
|
||||
{"style-null", `{"top":{"style":null}}`, "缺少 style"},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, err := parseBorderStyles(tc.json)
|
||||
if err == nil || !strings.Contains(err.Error(), tc.want) {
|
||||
t.Fatalf("err = %v, want contains %q", err, tc.want)
|
||||
}
|
||||
if err != nil && !strings.Contains(err.Error(), "--border-styles-json.top") {
|
||||
t.Fatalf("err = %v, want the edge name in the message", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// 合法形态不能被误拒:只给 style、给 style+color、显式 null color(等同省略)
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
json string
|
||||
wantColor any
|
||||
}{
|
||||
{"style-only", `{"top":{"style":"solid"}}`, nil},
|
||||
{"style-and-color", `{"top":{"style":"solid","color":"#FF0000"}}`, "#FF0000"},
|
||||
{"explicit-null-color", `{"top":{"style":"solid","color":null}}`, nil},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
out, err := parseBorderStyles(tc.json)
|
||||
if err != nil {
|
||||
t.Fatalf("parseBorderStyles(%s) = %v, want accepted", tc.json, err)
|
||||
}
|
||||
edge, _ := out["top"].(map[string]any)
|
||||
if edge["style"] != "solid" {
|
||||
t.Fatalf("style = %#v, want solid", edge["style"])
|
||||
}
|
||||
if edge["color"] != tc.wantColor {
|
||||
t.Fatalf("color = %#v, want %#v", edge["color"], tc.wantColor)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 单区域与 batch 两条路径:非法边框配置必须在组装/下发之前失败。
|
||||
func TestBorderStyleRejectionHappensBeforeAnyRemoteCall(t *testing.T) {
|
||||
const badBorder = `{"top":{"style":"solid","colour":"#f00"}}`
|
||||
previousDeps := deps
|
||||
t.Cleanup(func() { deps = previousDeps })
|
||||
|
||||
batchPath := filepath.Join(t.TempDir(), "styles.json")
|
||||
fixture := `[{"sheetId":"Sheet1","range":"A1:B2","borderStylesJson":"{\"top\":{\"style\":\"solid\",\"colour\":\"#f00\"}}"}]`
|
||||
if err := os.WriteFile(batchPath, []byte(fixture), 0o600); err != nil {
|
||||
t.Fatalf("write batch fixture: %v", err)
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
args []string
|
||||
}{
|
||||
{"single-range", []string{"--node", "NODE_ID", "--sheet-id", "S", "--range", "A1:B2", "--border-styles-json", badBorder}},
|
||||
{"batch-ranges", []string{"--node", "NODE_ID", "--ranges", `["Sheet1!A1:B2"]`, "--border-styles-json", badBorder}},
|
||||
{"batch-file", []string{"--node", "NODE_ID", "--batch", batchPath}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
caller := &sheetStyleDryRunCaller{format: "json"}
|
||||
InitDeps(caller)
|
||||
var output bytes.Buffer
|
||||
deps.Out.w = &output
|
||||
deps.Out.errW = &output
|
||||
|
||||
cmd := newRangeSetStyleCmd()
|
||||
if tc.name != "single-range" {
|
||||
cmd = newRangeBatchSetStyleCmd()
|
||||
}
|
||||
cmd.SetArgs(tc.args)
|
||||
cmd.SilenceUsage, cmd.SilenceErrors = true, true
|
||||
err := cmd.Execute()
|
||||
if err == nil || !strings.Contains(err.Error(), `未知字段 "colour"`) {
|
||||
t.Fatalf("err = %v, want the unknown border field rejected", err)
|
||||
}
|
||||
if caller.calls != 0 {
|
||||
t.Fatalf("remote CallTool count = %d, want 0", caller.calls)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ import (
|
||||
)
|
||||
|
||||
func TestCrossPlatformCoverageSheetAndMinutesSmallRemainingBranches(t *testing.T) {
|
||||
if err := applyStyleSpec(&styleSpec{FontColorsJSON: "{"}, 1, 1, map[string]any{}); err == nil {
|
||||
if _, err := buildStyleCells(&styleSpec{FontColorsJSON: "{"}, 1, 1); err == nil {
|
||||
t.Fatal("invalid font colors JSON returned nil")
|
||||
}
|
||||
|
||||
|
||||
@@ -73,6 +73,10 @@ func CompareAll(current Snapshot, references map[string]Snapshot) Report {
|
||||
// become required; an existing path may not gain a new required flag,
|
||||
// - new commands and flags are allowed.
|
||||
//
|
||||
// The single exception to the type rule is an individually reviewed migration
|
||||
// listed in reviewedFlagTypeChanges, and only when nothing else about the flag
|
||||
// changed. See reviewed.go.
|
||||
//
|
||||
// Comparing the effective local + inherited set is intentional. It catches a
|
||||
// persistent flag whose scope is accidentally narrowed to its declaring
|
||||
// command, while allowing a local flag to move to an ancestor without breaking
|
||||
@@ -183,13 +187,20 @@ func compareEffectiveFlags(result *Comparison, acceptedPath string, oldCommand,
|
||||
continue
|
||||
}
|
||||
if oldFlag.Type != newFlag.Type {
|
||||
result.Blocking = append(result.Blocking, Change{
|
||||
Kind: "flag_type_changed",
|
||||
Path: acceptedPath,
|
||||
Flag: name,
|
||||
Before: oldFlag.Type,
|
||||
After: newFlag.Type,
|
||||
})
|
||||
// Resolve the exemption against the canonical path, not acceptedPath.
|
||||
// An aliased command reaches this function once per accepted spelling,
|
||||
// so keying on acceptedPath would let every alias spelling re-report a
|
||||
// reviewed migration.
|
||||
if !reviewedFlagTypeChange(newCommand.Path, name, oldFlag.Type, newFlag.Type) ||
|
||||
flagContractOtherwiseChanged(oldFlag, newFlag) {
|
||||
result.Blocking = append(result.Blocking, Change{
|
||||
Kind: "flag_type_changed",
|
||||
Path: acceptedPath,
|
||||
Flag: name,
|
||||
Before: oldFlag.Type,
|
||||
After: newFlag.Type,
|
||||
})
|
||||
}
|
||||
}
|
||||
if !oldFlag.Required && newFlag.Required {
|
||||
result.Blocking = append(result.Blocking, Change{
|
||||
|
||||
@@ -13,7 +13,11 @@
|
||||
|
||||
package interfacesnapshot
|
||||
|
||||
import "testing"
|
||||
import (
|
||||
"os"
|
||||
"regexp"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestCrossPlatformCoverageCompareAdmissionPolicy(t *testing.T) {
|
||||
base := testSnapshot(
|
||||
@@ -310,6 +314,225 @@ func TestCrossPlatformCoverageCompareAllRequiresBothReferencesToPass(t *testing.
|
||||
}
|
||||
}
|
||||
|
||||
// registerReviewedFixture puts a fixture command in the reviewed table for the
|
||||
// duration of one test, so the behaviour tests exercise the real lookup instead
|
||||
// of depending on whichever production entries happen to exist.
|
||||
func registerReviewedFixture(t *testing.T, change flagTypeChange) {
|
||||
t.Helper()
|
||||
if _, exists := reviewedFlagTypeChanges[change]; exists {
|
||||
t.Fatalf("fixture %+v collides with a production entry", change)
|
||||
}
|
||||
reviewedFlagTypeChanges[change] = struct{}{}
|
||||
t.Cleanup(func() { delete(reviewedFlagTypeChanges, change) })
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageCompareAcceptsReviewedFlagTypeChange(t *testing.T) {
|
||||
base := testSnapshot(
|
||||
testCommand("dws"),
|
||||
testCommand("dws search", testFlag("query", "string", false)),
|
||||
)
|
||||
current := testSnapshot(
|
||||
testCommand("dws"),
|
||||
testCommand("dws search", testFlag("query", "int", false)),
|
||||
)
|
||||
|
||||
// Without an entry the migration is still a blocking change.
|
||||
if comparison := Compare(current, base, "base"); !hasChangeKind(comparison.Blocking, "flag_type_changed") {
|
||||
t.Fatalf("an unreviewed type change should block: %#v", comparison.Blocking)
|
||||
}
|
||||
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws search", Flag: "query", From: "string", To: "int"})
|
||||
if comparison := Compare(current, base, "base"); !comparison.Compatible {
|
||||
t.Fatalf("a reviewed string->int migration should pass: %#v", comparison.Blocking)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageCompareReviewedFlagTypeChangeIsDirectionSensitive(t *testing.T) {
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws search", Flag: "query", From: "string", To: "int"})
|
||||
|
||||
// The reverse migration shares command and flag but not direction, so the
|
||||
// string->int entry must not admit it.
|
||||
base := testSnapshot(
|
||||
testCommand("dws"),
|
||||
testCommand("dws search", testFlag("query", "int", false)),
|
||||
)
|
||||
current := testSnapshot(
|
||||
testCommand("dws"),
|
||||
testCommand("dws search", testFlag("query", "string", false)),
|
||||
)
|
||||
if comparison := Compare(current, base, "base"); comparison.Compatible {
|
||||
t.Fatal("int->string must not be admitted by a string->int entry")
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageCompareReviewedFlagTypeChangeRejectsOtherCommandsAndFlags(t *testing.T) {
|
||||
base := testSnapshot(
|
||||
testCommand("dws"),
|
||||
testCommand("dws search", testFlag("query", "string", false)),
|
||||
)
|
||||
current := testSnapshot(
|
||||
testCommand("dws"),
|
||||
testCommand("dws search", testFlag("query", "int", false)),
|
||||
)
|
||||
|
||||
// Same flag and direction, different command.
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws status", Flag: "query", From: "string", To: "int"})
|
||||
if comparison := Compare(current, base, "base"); comparison.Compatible {
|
||||
t.Fatal("an entry for another command must not admit this migration")
|
||||
}
|
||||
|
||||
// Same command and direction, different flag.
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws search", Flag: "elsewhere", From: "string", To: "int"})
|
||||
if comparison := Compare(current, base, "base"); comparison.Compatible {
|
||||
t.Fatal("an entry for another flag must not admit this migration")
|
||||
}
|
||||
}
|
||||
|
||||
// A reviewed migration is only accepted when the rest of the flag's contract
|
||||
// held still. Each case bundles one unrelated regression with the reviewed type
|
||||
// change and requires the type failure to reappear, which also anchors
|
||||
// flagContractOtherwiseChanged against the checks it mirrors: a condition that
|
||||
// drifts out of sync fails here instead of silently widening the exemption.
|
||||
func TestCrossPlatformCoverageCompareReviewedFlagTypeChangeRejectsBundledRegression(t *testing.T) {
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws search", Flag: "query", From: "string", To: "int"})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
base Flag
|
||||
next Flag
|
||||
kind string
|
||||
}{
|
||||
{
|
||||
name: "became required",
|
||||
base: Flag{Name: "query", Type: "string"},
|
||||
next: Flag{Name: "query", Type: "int", Required: true},
|
||||
kind: "flag_became_required",
|
||||
},
|
||||
{
|
||||
name: "lost shorthand",
|
||||
base: Flag{Name: "query", Type: "string", Shorthand: "q"},
|
||||
next: Flag{Name: "query", Type: "int"},
|
||||
kind: "flag_shorthand_changed",
|
||||
},
|
||||
{
|
||||
name: "changed no-opt",
|
||||
base: Flag{Name: "query", Type: "string", NoOpt: "all"},
|
||||
next: Flag{Name: "query", Type: "int", NoOpt: "1"},
|
||||
kind: "flag_no_opt_changed",
|
||||
},
|
||||
{
|
||||
name: "became hidden",
|
||||
base: Flag{Name: "query", Type: "string"},
|
||||
next: Flag{Name: "query", Type: "int", Hidden: true},
|
||||
kind: "flag_became_hidden",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
base := testSnapshot(testCommand("dws"), testCommand("dws search", test.base))
|
||||
current := testSnapshot(testCommand("dws"), testCommand("dws search", test.next))
|
||||
comparison := Compare(current, base, "base")
|
||||
if !hasChangeKind(comparison.Blocking, test.kind) {
|
||||
t.Fatalf("blocking=%#v, want kind %q", comparison.Blocking, test.kind)
|
||||
}
|
||||
if !hasChangeKind(comparison.Blocking, "flag_type_changed") {
|
||||
t.Fatalf("a bundled regression must re-report the type change: %#v", comparison.Blocking)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The exemption is resolved against the canonical Command.Path, never the
|
||||
// alias-expanded accepted path. An aliased command enters compareEffectiveFlags
|
||||
// once per accepted spelling, so keying on the accepted path would let every
|
||||
// alias spelling re-report a reviewed migration.
|
||||
func TestCrossPlatformCoverageCompareResolvesReviewedFlagTypeChangeByCanonicalPath(t *testing.T) {
|
||||
base := testSnapshot(
|
||||
testCommand("dws"),
|
||||
testCommandWithAliases("dws search", []string{"find"}, testFlag("query", "string", false)),
|
||||
)
|
||||
current := testSnapshot(
|
||||
testCommand("dws"),
|
||||
testCommandWithAliases("dws search", []string{"find"}, testFlag("query", "int", false)),
|
||||
)
|
||||
|
||||
// The canonical path admits the migration for every accepted spelling.
|
||||
canonical := flagTypeChange{CommandPath: "dws search", Flag: "query", From: "string", To: "int"}
|
||||
registerReviewedFixture(t, canonical)
|
||||
if comparison := Compare(current, base, "base"); !comparison.Compatible {
|
||||
t.Fatalf("canonical path should admit the migration on every alias: %#v", comparison.Blocking)
|
||||
}
|
||||
delete(reviewedFlagTypeChanges, canonical)
|
||||
|
||||
// An entry spelled with the alias path matches nothing, because the lookup
|
||||
// never sees the accepted spelling.
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws find", Flag: "query", From: "string", To: "int"})
|
||||
if comparison := Compare(current, base, "base"); comparison.Compatible {
|
||||
t.Fatal("an alias-spelled entry must not admit the migration")
|
||||
}
|
||||
}
|
||||
|
||||
// A string -> int migration always changes the recorded default ("" to "0").
|
||||
// Defaults are not part of what this gate enforces, and folding them into
|
||||
// flagContractOtherwiseChanged would make every table entry dead on arrival.
|
||||
func TestCrossPlatformCoverageCompareReviewedFlagTypeChangeToleratesDefaultDrift(t *testing.T) {
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws search", Flag: "query", From: "string", To: "int"})
|
||||
|
||||
base := testSnapshot(
|
||||
testCommand("dws"),
|
||||
testCommand("dws search", Flag{Name: "query", Type: "string", Default: ""}),
|
||||
)
|
||||
current := testSnapshot(
|
||||
testCommand("dws"),
|
||||
testCommand("dws search", Flag{Name: "query", Type: "int", Default: "0"}),
|
||||
)
|
||||
if comparison := Compare(current, base, "base"); !comparison.Compatible {
|
||||
t.Fatalf("default drift must not defeat a reviewed migration: %#v", comparison.Blocking)
|
||||
}
|
||||
}
|
||||
|
||||
// reviewedEntryPattern matches one table entry as gofmt writes it on a single
|
||||
// line. It is used to read the sibling copy of the table out of the policy
|
||||
// helper, which cannot be imported: that directory is copied into a worktree at
|
||||
// a historical revision and built there, so it must not depend on this package.
|
||||
var reviewedEntryPattern = regexp.MustCompile(
|
||||
`\{CommandPath:\s*"([^"]*)",\s*Flag:\s*"([^"]*)",\s*From:\s*"([^"]*)",\s*To:\s*"([^"]*)"\}`)
|
||||
|
||||
const interfaceBaselineReviewedPath = "../../scripts/policy/interface-baseline/reviewed.go"
|
||||
|
||||
// The two copies of the table must stay identical, otherwise a migration passes
|
||||
// one gate and is blocked by the other in the same CI job.
|
||||
func TestCrossPlatformCoverageReviewedFlagTypeTableMatchesInterfaceBaseline(t *testing.T) {
|
||||
source, err := os.ReadFile(interfaceBaselineReviewedPath)
|
||||
if err != nil {
|
||||
t.Fatalf("读取 %s 失败: %v", interfaceBaselineReviewedPath, err)
|
||||
}
|
||||
|
||||
sibling := make(map[flagTypeChange]struct{})
|
||||
for _, match := range reviewedEntryPattern.FindAllStringSubmatch(string(source), -1) {
|
||||
sibling[flagTypeChange{CommandPath: match[1], Flag: match[2], From: match[3], To: match[4]}] = struct{}{}
|
||||
}
|
||||
|
||||
// Without this the whole guard degrades into comparing two empty sets the
|
||||
// moment the pattern stops matching, which is exactly how a duplicated
|
||||
// allowlist goes stale unnoticed.
|
||||
if len(sibling) == 0 {
|
||||
t.Fatalf("未能从 %s 提取到任何条目:正则或表的书写形态已漂移,这条守卫已失效", interfaceBaselineReviewedPath)
|
||||
}
|
||||
|
||||
for change := range reviewedFlagTypeChanges {
|
||||
if _, ok := sibling[change]; !ok {
|
||||
t.Errorf("%+v 只存在于 interfacesnapshot,缺在 %s", change, interfaceBaselineReviewedPath)
|
||||
}
|
||||
}
|
||||
for change := range sibling {
|
||||
if _, ok := reviewedFlagTypeChanges[change]; !ok {
|
||||
t.Errorf("%+v 只存在于 %s,缺在 interfacesnapshot", change, interfaceBaselineReviewedPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func testSnapshot(commands ...Command) Snapshot {
|
||||
return Snapshot{
|
||||
SchemaVersion: SchemaVersion,
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
// Copyright 2026 Alibaba Group
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package interfacesnapshot
|
||||
|
||||
// flagTypeChange identifies one flag type migration exactly: which command,
|
||||
// which flag, and in which direction. Nothing is matched by wildcard — an entry
|
||||
// that differs in any of the four fields does not apply.
|
||||
//
|
||||
// CommandPath is the canonical Command.Path form, which always includes the root
|
||||
// command name ("dws minutes permission apply"). It is deliberately *not* the
|
||||
// alias-expanded accepted path: a command reachable through an alias enters
|
||||
// compareEffectiveFlags once per accepted spelling, and keying on the accepted
|
||||
// path would let every alias spelling bypass the exemption and re-report the
|
||||
// change.
|
||||
//
|
||||
// This table is duplicated in scripts/policy/interface-baseline/reviewed.go and
|
||||
// the two must stay identical; TestCrossPlatformCoverageReviewedFlagTypeTableMatchesInterfaceBaseline
|
||||
// fails if they drift. The duplication is forced rather than chosen:
|
||||
// check-authoritative-interface-baselines.sh copies the whole
|
||||
// scripts/policy/interface-baseline directory into a worktree checked out at a
|
||||
// historical revision and builds it there, so that copy cannot import a package
|
||||
// this branch adds.
|
||||
type flagTypeChange struct {
|
||||
CommandPath string
|
||||
Flag string
|
||||
From string
|
||||
To string
|
||||
}
|
||||
|
||||
// reviewedFlagTypeChanges enumerates the individually reviewed flag type
|
||||
// migrations this gate accepts. A flag type is part of the published CLI
|
||||
// contract, and a type swap cannot be proven safe from the type names alone —
|
||||
// whether old invocations still parse depends on the concrete value domain the
|
||||
// command enforces. So a migration is accepted only when this exact command,
|
||||
// flag, and old→new pair appear here. Adding an entry is a contract decision
|
||||
// and belongs in review, not in a feature change.
|
||||
//
|
||||
// Entries are direction-sensitive by construction: "string" → "int" is a
|
||||
// separate key from "int" → "string" and only the reviewed direction is
|
||||
// accepted. The reverse is not a candidate for this table — widening an int
|
||||
// flag back to string lets values the parser used to reject reach RunE, which
|
||||
// is a genuine loosening of validation rather than a type migration.
|
||||
//
|
||||
// The table alone does not admit a change: reviewedFlagTypeChange is consulted
|
||||
// only when nothing else about the flag moved. See compareEffectiveFlags.
|
||||
var reviewedFlagTypeChanges = map[flagTypeChange]struct{}{
|
||||
// "dws minutes permission apply --policy" moved from a String flag parsed
|
||||
// with strconv.ParseInt(v, 10, 64) in RunE to a native Int flag, keeping the
|
||||
// same [2,4] domain check in RunE.
|
||||
//
|
||||
// This is admissible because the historical set of *successful* invocations
|
||||
// is a subset of the new one, not merely similar to it:
|
||||
//
|
||||
// - Old: the value had to parse as base-10 and land in [2,4]. That is
|
||||
// exactly "2", "3", "4" plus sign/leading-zero spellings of them
|
||||
// ("+3", "03", "003", ...).
|
||||
// - New: pflag's intValue.Set parses with strconv.ParseInt(s, 0, 64) —
|
||||
// base 0 — and RunE still enforces [2,4]. Every base-10 spelling above
|
||||
// resolves to the same number under base 0, so no historical success
|
||||
// becomes a failure.
|
||||
// - Base 0 additionally accepts "0x3" and friends, which the old parser
|
||||
// rejected. That widens the accepted set; it cannot break a caller who
|
||||
// was already succeeding.
|
||||
// - Values outside [2,4] and non-numeric values still fail. Only the
|
||||
// failure *message and timing* move, from RunE to flag parsing.
|
||||
//
|
||||
// The flag's default value changes from "" to "0" as an unavoidable
|
||||
// consequence of the type. Neither gate compares defaults, and a default is
|
||||
// not reachable by a caller here because RunE requires the flag to be
|
||||
// explicitly set, so this is not a contract change.
|
||||
{CommandPath: "dws minutes permission apply", Flag: "policy", From: "string", To: "int"}: {},
|
||||
}
|
||||
|
||||
// reviewedFlagTypeChange reports whether this exact command, flag and direction
|
||||
// is a reviewed migration. Callers must additionally establish that the rest of
|
||||
// the flag's contract is unchanged before skipping the failure.
|
||||
func reviewedFlagTypeChange(commandPath, flag, from, to string) bool {
|
||||
_, reviewed := reviewedFlagTypeChanges[flagTypeChange{
|
||||
CommandPath: commandPath,
|
||||
Flag: flag,
|
||||
From: from,
|
||||
To: to,
|
||||
}]
|
||||
return reviewed
|
||||
}
|
||||
|
||||
// flagContractOtherwiseChanged reports whether anything this gate checks about a
|
||||
// flag, other than its type, differs between the two revisions. A reviewed type
|
||||
// migration is only accepted when this returns false, so the exemption cannot
|
||||
// carry an unrelated regression in behind it.
|
||||
//
|
||||
// Only the fields compareEffectiveFlags actually enforces are compared. Default
|
||||
// is deliberately excluded: a string → int migration always changes it ("" to
|
||||
// "0"), so including it would make every entry in the table dead. Deprecated is
|
||||
// excluded for the same reason it is not a blocking change on its own.
|
||||
func flagContractOtherwiseChanged(oldFlag, newFlag Flag) bool {
|
||||
if !oldFlag.Required && newFlag.Required {
|
||||
return true
|
||||
}
|
||||
if oldFlag.Shorthand != "" && newFlag.Shorthand != oldFlag.Shorthand {
|
||||
return true
|
||||
}
|
||||
if oldFlag.NoOpt != "" && newFlag.NoOpt != oldFlag.NoOpt {
|
||||
return true
|
||||
}
|
||||
if !oldFlag.Hidden && newFlag.Hidden {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -30,17 +30,20 @@ import (
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/corecmd"
|
||||
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/corecmd/contract"
|
||||
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/shortcut"
|
||||
)
|
||||
|
||||
const productDevApp = "devapp"
|
||||
|
||||
// applyCursor forwards --cursor/--page-size into params, matching the helper's
|
||||
// pass-through pagination (pageSize defaults to 20, cursor omitted on page 1).
|
||||
func applyCursor(rt *shortcut.RuntimeContext, params map[string]any) {
|
||||
// applyCursor forwards --cursor/--page-size into params and returns the opaque
|
||||
// request cursor for response-contract validation. pageSize defaults to 20 and
|
||||
// cursor is omitted on page 1.
|
||||
func applyCursor(rt *shortcut.RuntimeContext, params map[string]any) string {
|
||||
requestCursor := listAppRequestCursor(rt)
|
||||
if rt.Changed("cursor") {
|
||||
if cur := rt.Str("cursor"); cur != "" {
|
||||
params["cursor"] = cur
|
||||
if requestCursor != "" {
|
||||
params["cursor"] = requestCursor
|
||||
}
|
||||
}
|
||||
size := rt.Int("page-size")
|
||||
@@ -48,6 +51,15 @@ func applyCursor(rt *shortcut.RuntimeContext, params map[string]any) {
|
||||
size = 20
|
||||
}
|
||||
params["pageSize"] = size
|
||||
return requestCursor
|
||||
}
|
||||
|
||||
func listAppRequestCursor(rt *shortcut.RuntimeContext) string {
|
||||
if rt == nil || rt.Command() == nil {
|
||||
return ""
|
||||
}
|
||||
value, _ := rt.Command().Flags().GetString("cursor")
|
||||
return value
|
||||
}
|
||||
|
||||
var cursorFlags = []shortcut.Flag{
|
||||
@@ -105,7 +117,7 @@ var ListApp = shortcut.Shortcut{
|
||||
}, cursorFlags...),
|
||||
Execute: func(rt *shortcut.RuntimeContext) error {
|
||||
params := map[string]any{}
|
||||
applyCursor(rt, params)
|
||||
requestCursor := applyCursor(rt, params)
|
||||
if rt.Changed("name") {
|
||||
params["name"] = rt.Str("name")
|
||||
}
|
||||
@@ -137,23 +149,229 @@ var ListApp = shortcut.Shortcut{
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
apps := listAppProject(data)
|
||||
return rt.Output(map[string]any{"count": len(apps), "apps": apps})
|
||||
page, err := listAppParsePage(data, requestCursor)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
apps, err := listAppProject(page.apps)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return rt.Output(map[string]any{
|
||||
"count": len(apps),
|
||||
"apps": apps,
|
||||
"hasMore": page.hasMore,
|
||||
"nextCursor": page.nextCursor,
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
var listAppCollectionKeys = []string{
|
||||
"list", "items", "apps", "appList", "permissions", "events", "versions", "result", "data",
|
||||
}
|
||||
|
||||
type listAppPage struct {
|
||||
apps []any
|
||||
hasMore bool
|
||||
nextCursor string
|
||||
}
|
||||
|
||||
type listAppPageCandidate struct {
|
||||
envelope map[string]any
|
||||
apps []any
|
||||
}
|
||||
|
||||
// listAppParsePage accepts one page at the response top level or under exactly
|
||||
// one existing one-level list envelope. The app list and both pagination facts
|
||||
// must come from that same map; otherwise callers cannot safely distinguish a
|
||||
// terminal page from a truncated or conflicting response.
|
||||
func listAppParsePage(data map[string]any, requestCursor string) (listAppPage, error) {
|
||||
return devAppListParsePage(data, requestCursor, "list_dev_app")
|
||||
}
|
||||
|
||||
func devAppListParsePage(data map[string]any, requestCursor, tool string) (listAppPage, error) {
|
||||
candidates, invalid := listAppPageCandidates(data)
|
||||
if invalid || len(candidates) != 1 {
|
||||
return listAppPage{}, devAppPaginationContractError(tool)
|
||||
}
|
||||
|
||||
candidate := candidates[0]
|
||||
hasMoreValue, ok := candidate.envelope["hasMore"]
|
||||
if !ok {
|
||||
return listAppPage{}, devAppPaginationContractError(tool)
|
||||
}
|
||||
hasMore, ok := hasMoreValue.(bool)
|
||||
if !ok {
|
||||
return listAppPage{}, devAppPaginationContractError(tool)
|
||||
}
|
||||
nextCursorValue, ok := candidate.envelope["nextCursor"]
|
||||
|
||||
if hasMore {
|
||||
if !ok {
|
||||
return listAppPage{}, devAppPaginationContractError(tool)
|
||||
}
|
||||
nextCursor, ok := nextCursorValue.(string)
|
||||
if !ok {
|
||||
return listAppPage{}, devAppPaginationContractError(tool)
|
||||
}
|
||||
if nextCursor == "" || nextCursor == requestCursor {
|
||||
return listAppPage{}, devAppPaginationContractError(tool)
|
||||
}
|
||||
return listAppPage{
|
||||
apps: candidate.apps,
|
||||
hasMore: true,
|
||||
nextCursor: nextCursor,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// Deployed devapp providers use hasMore as the terminal authority and may
|
||||
// omit nextCursor or return null, an empty string, or the last observed
|
||||
// cursor on a terminal page. Normalize all provider-compatible forms to an
|
||||
// empty public cursor.
|
||||
if ok && nextCursorValue != nil {
|
||||
if _, ok := nextCursorValue.(string); !ok {
|
||||
return listAppPage{}, devAppPaginationContractError(tool)
|
||||
}
|
||||
}
|
||||
|
||||
return listAppPage{
|
||||
apps: candidate.apps,
|
||||
hasMore: false,
|
||||
nextCursor: "",
|
||||
}, nil
|
||||
}
|
||||
|
||||
// listAppPageCandidates enumerates only the response map and supported maps
|
||||
// directly beneath it. Candidate collection keys that have a wrong type,
|
||||
// multiple list-bearing maps, multiple lists in one map, pagination metadata
|
||||
// without its sibling list, or a second nested envelope all fail closed.
|
||||
func listAppPageCandidates(data map[string]any) ([]listAppPageCandidate, bool) {
|
||||
if data == nil {
|
||||
return nil, true
|
||||
}
|
||||
|
||||
type envelope struct {
|
||||
value map[string]any
|
||||
depth int
|
||||
}
|
||||
envelopes := []envelope{{value: data}}
|
||||
for key, value := range data {
|
||||
inner, ok := value.(map[string]any)
|
||||
if ok && listAppIsCollectionKey(key) {
|
||||
envelopes = append(envelopes, envelope{value: inner, depth: 1})
|
||||
}
|
||||
}
|
||||
|
||||
candidates := make([]listAppPageCandidate, 0, 1)
|
||||
for _, current := range envelopes {
|
||||
for key, value := range current.value {
|
||||
if listAppIsCollectionKey(key) {
|
||||
continue
|
||||
}
|
||||
inner, ok := value.(map[string]any)
|
||||
if ok && listAppHasPageEvidence(inner) {
|
||||
return nil, true
|
||||
}
|
||||
}
|
||||
|
||||
lists := make([][]any, 0, 1)
|
||||
invalidCollection := false
|
||||
for _, key := range listAppCollectionKeys {
|
||||
value, exists := current.value[key]
|
||||
if !exists {
|
||||
continue
|
||||
}
|
||||
switch typed := value.(type) {
|
||||
case []any:
|
||||
lists = append(lists, typed)
|
||||
case map[string]any:
|
||||
if current.depth > 0 {
|
||||
invalidCollection = true
|
||||
}
|
||||
default:
|
||||
invalidCollection = true
|
||||
}
|
||||
}
|
||||
|
||||
_, hasHasMore := current.value["hasMore"]
|
||||
_, hasNextCursor := current.value["nextCursor"]
|
||||
hasPageEvidence := len(lists) > 0 || hasHasMore || hasNextCursor || invalidCollection
|
||||
if !hasPageEvidence {
|
||||
continue
|
||||
}
|
||||
if invalidCollection || len(lists) != 1 {
|
||||
return nil, true
|
||||
}
|
||||
candidates = append(candidates, listAppPageCandidate{
|
||||
envelope: current.value,
|
||||
apps: lists[0],
|
||||
})
|
||||
}
|
||||
|
||||
return candidates, false
|
||||
}
|
||||
|
||||
func listAppIsCollectionKey(candidate string) bool {
|
||||
for _, key := range listAppCollectionKeys {
|
||||
if candidate == key {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func listAppHasPageEvidence(envelope map[string]any) bool {
|
||||
if _, ok := envelope["hasMore"]; ok {
|
||||
return true
|
||||
}
|
||||
if _, ok := envelope["nextCursor"]; ok {
|
||||
return true
|
||||
}
|
||||
for _, key := range listAppCollectionKeys {
|
||||
value, ok := envelope[key]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
switch typed := value.(type) {
|
||||
case []any:
|
||||
return true
|
||||
case map[string]any:
|
||||
if key == "apps" || key == "appList" || listAppHasPageEvidence(typed) {
|
||||
return true
|
||||
}
|
||||
default:
|
||||
if key == "apps" || key == "appList" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// DEC-DWS-917-R1B treats an unprojectable app item as a page-integrity failure:
|
||||
// silently dropping it could turn a real app into a false terminal "not found".
|
||||
// Keep the issue's frozen page-contract reason for both envelope and item failures.
|
||||
func listAppPaginationContractError() error {
|
||||
return devAppPaginationContractError("list_dev_app")
|
||||
}
|
||||
|
||||
func devAppPaginationContractError(tool string) error {
|
||||
return apperrors.NewAPI(
|
||||
tool+" returned an invalid pagination contract",
|
||||
apperrors.WithReason("devapp_pagination_contract_invalid"),
|
||||
)
|
||||
}
|
||||
|
||||
// listAppProject reshapes list_dev_app into a clean app list
|
||||
// ({unifiedAppId, name, appKey, agentId, status, gmtModified}) — output-projection
|
||||
// clean output projection. The list container and per-item field names are probed
|
||||
// defensively across candidate keys, so an unknown/empty shape yields an empty
|
||||
// list rather than a crash or fabricated data.
|
||||
func listAppProject(data map[string]any) []map[string]any {
|
||||
raw := listAppFindList(data)
|
||||
// clean output projection. The page container has already passed the strict
|
||||
// same-envelope pagination contract; per-item field aliases remain compatible.
|
||||
func listAppProject(raw []any) ([]map[string]any, error) {
|
||||
out := make([]map[string]any, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
m, ok := item.(map[string]any)
|
||||
if !ok {
|
||||
continue
|
||||
return nil, listAppPaginationContractError()
|
||||
}
|
||||
row := map[string]any{}
|
||||
if v, ok := listAppFirst(m, "unifiedAppId", "unified_app_id"); ok {
|
||||
@@ -174,36 +392,12 @@ func listAppProject(data map[string]any) []map[string]any {
|
||||
if v, ok := listAppFirst(m, "gmtModified", "gmt_modified", "modifyTime", "modified_time"); ok {
|
||||
row["gmtModified"] = v
|
||||
}
|
||||
if len(row) > 0 {
|
||||
out = append(out, row)
|
||||
if len(row) == 0 {
|
||||
return nil, listAppPaginationContractError()
|
||||
}
|
||||
out = append(out, row)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// listAppFindList locates the app list payload, tolerating a bare top-level
|
||||
// array or nesting one level under a common envelope key.
|
||||
func listAppFindList(data map[string]any) []any {
|
||||
if data == nil {
|
||||
return []any{}
|
||||
}
|
||||
for _, k := range []string{"list", "items", "apps", "appList", "result", "data"} {
|
||||
v, ok := data[k]
|
||||
if !ok {
|
||||
continue
|
||||
}
|
||||
if arr, ok := v.([]any); ok {
|
||||
return arr
|
||||
}
|
||||
if inner, ok := v.(map[string]any); ok {
|
||||
for _, ik := range []string{"list", "items", "apps", "appList", "result", "data"} {
|
||||
if arr, ok := inner[ik].([]any); ok {
|
||||
return arr
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return []any{}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// listAppFirst returns the first present candidate key's value.
|
||||
@@ -665,13 +859,22 @@ var PermissionList = shortcut.Shortcut{
|
||||
if rt.Changed("api-status") {
|
||||
params["apiStatus"] = rt.Str("api-status")
|
||||
}
|
||||
applyCursor(rt, params)
|
||||
requestCursor := applyCursor(rt, params)
|
||||
data, err := rt.CallMCPData(productDevApp, "list_dev_app_permissions", params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
permissions := permissionListProject(data)
|
||||
return rt.Output(map[string]any{"count": len(permissions), "permissions": permissions})
|
||||
page, err := devAppListParsePage(data, requestCursor, "list_dev_app_permissions")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
permissions := permissionListProject(map[string]any{"items": page.apps})
|
||||
return rt.Output(map[string]any{
|
||||
"count": len(permissions),
|
||||
"permissions": permissions,
|
||||
"hasMore": page.hasMore,
|
||||
"nextCursor": page.nextCursor,
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1143,13 +1346,22 @@ var EventList = shortcut.Shortcut{
|
||||
if rt.Changed("keyword") {
|
||||
params["keyword"] = rt.Str("keyword")
|
||||
}
|
||||
applyCursor(rt, params)
|
||||
requestCursor := applyCursor(rt, params)
|
||||
data, err := rt.CallMCPData(productDevApp, "list_dev_app_events", params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
events := eventListProject(data)
|
||||
return rt.Output(map[string]any{"count": len(events), "events": events})
|
||||
page, err := devAppListParsePage(data, requestCursor, "list_dev_app_events")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
events := eventListProject(map[string]any{"events": page.apps})
|
||||
return rt.Output(map[string]any{
|
||||
"count": len(events),
|
||||
"events": events,
|
||||
"hasMore": page.hasMore,
|
||||
"nextCursor": page.nextCursor,
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1330,13 +1542,22 @@ var VersionList = shortcut.Shortcut{
|
||||
}, cursorFlags...),
|
||||
Execute: func(rt *shortcut.RuntimeContext) error {
|
||||
params := map[string]any{"unifiedAppId": rt.Str("unified-app-id")}
|
||||
applyCursor(rt, params)
|
||||
requestCursor := applyCursor(rt, params)
|
||||
data, err := rt.CallMCPData(productDevApp, "list_dev_app_versions", params)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
versions := versionListProject(data)
|
||||
return rt.Output(map[string]any{"count": len(versions), "versions": versions})
|
||||
page, err := devAppListParsePage(data, requestCursor, "list_dev_app_versions")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
versions := versionListProject(map[string]any{"items": page.apps})
|
||||
return rt.Output(map[string]any{
|
||||
"count": len(versions),
|
||||
"versions": versions,
|
||||
"hasMore": page.hasMore,
|
||||
"nextCursor": page.nextCursor,
|
||||
})
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,665 @@
|
||||
// Copyright 2026 Alibaba Group
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
package devapp
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/corecmd"
|
||||
apperrors "github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/errors"
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/helpers"
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/shortcut"
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/pkg/edition"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
type listPaginationCall struct {
|
||||
product string
|
||||
tool string
|
||||
params map[string]any
|
||||
}
|
||||
|
||||
type listPaginationCaller struct {
|
||||
response string
|
||||
calls []listPaginationCall
|
||||
}
|
||||
|
||||
func (c *listPaginationCaller) CallTool(
|
||||
_ context.Context,
|
||||
product string,
|
||||
tool string,
|
||||
params map[string]any,
|
||||
) (*edition.ToolResult, error) {
|
||||
cloned := make(map[string]any, len(params))
|
||||
for key, value := range params {
|
||||
cloned[key] = value
|
||||
}
|
||||
c.calls = append(c.calls, listPaginationCall{product: product, tool: tool, params: cloned})
|
||||
return &edition.ToolResult{Content: []edition.ContentBlock{{Type: "text", Text: c.response}}}, nil
|
||||
}
|
||||
|
||||
func (*listPaginationCaller) Format() string { return "json" }
|
||||
func (*listPaginationCaller) DryRun() bool { return false }
|
||||
func (*listPaginationCaller) Fields() string { return "" }
|
||||
func (*listPaginationCaller) JQ() string { return "" }
|
||||
|
||||
func executeListPagination(
|
||||
t *testing.T,
|
||||
response string,
|
||||
args ...string,
|
||||
) (string, error, *listPaginationCaller) {
|
||||
t.Helper()
|
||||
|
||||
caller := &listPaginationCaller{response: response}
|
||||
helpers.InitDepsForTest(t, caller)
|
||||
|
||||
root := &cobra.Command{Use: "dws", SilenceErrors: true, SilenceUsage: true}
|
||||
root.PersistentFlags().Bool("yes", false, "")
|
||||
root.PersistentFlags().Bool("dry-run", false, "")
|
||||
root.PersistentFlags().StringP("format", "f", "json", "")
|
||||
root.PersistentFlags().String("fields", "", "")
|
||||
root.PersistentFlags().String("jq", "", "")
|
||||
service := &cobra.Command{Use: "devapp"}
|
||||
service.AddCommand(corecmd.New(shortcut.FromShortcut(ListApp)))
|
||||
root.AddCommand(service)
|
||||
|
||||
var output bytes.Buffer
|
||||
root.SetOut(&output)
|
||||
root.SetErr(&output)
|
||||
root.SetArgs(append([]string{"devapp", "+list"}, args...))
|
||||
err := root.Execute()
|
||||
return output.String(), err, caller
|
||||
}
|
||||
|
||||
func executeDevAppListShortcut(
|
||||
t *testing.T,
|
||||
command string,
|
||||
definition shortcut.Shortcut,
|
||||
response string,
|
||||
args ...string,
|
||||
) (string, error, *listPaginationCaller) {
|
||||
t.Helper()
|
||||
|
||||
caller := &listPaginationCaller{response: response}
|
||||
helpers.InitDepsForTest(t, caller)
|
||||
|
||||
root := &cobra.Command{Use: "dws", SilenceErrors: true, SilenceUsage: true}
|
||||
root.PersistentFlags().Bool("yes", false, "")
|
||||
root.PersistentFlags().Bool("dry-run", false, "")
|
||||
root.PersistentFlags().StringP("format", "f", "json", "")
|
||||
root.PersistentFlags().String("fields", "", "")
|
||||
root.PersistentFlags().String("jq", "", "")
|
||||
service := &cobra.Command{Use: "devapp"}
|
||||
service.AddCommand(corecmd.New(shortcut.FromShortcut(definition)))
|
||||
root.AddCommand(service)
|
||||
|
||||
var output bytes.Buffer
|
||||
root.SetOut(&output)
|
||||
root.SetErr(&output)
|
||||
root.SetArgs(append([]string{"devapp", command}, args...))
|
||||
err := root.Execute()
|
||||
return output.String(), err, caller
|
||||
}
|
||||
|
||||
func decodeListPaginationEnvelope(t *testing.T, output string) map[string]any {
|
||||
t.Helper()
|
||||
var payload map[string]any
|
||||
if err := json.Unmarshal([]byte(output), &payload); err != nil {
|
||||
t.Fatalf("decode output: %v\noutput=%q", err, output)
|
||||
}
|
||||
return payload
|
||||
}
|
||||
|
||||
func decodePrettyListPagination(t *testing.T, output string) map[string]string {
|
||||
t.Helper()
|
||||
values := map[string]string{}
|
||||
lines := strings.Split(strings.TrimSuffix(output, "\n"), "\n")
|
||||
if len(lines) != 4 {
|
||||
t.Fatalf("pretty output lines = %d, want four fields: %q", len(lines), output)
|
||||
}
|
||||
for _, line := range lines {
|
||||
parts := strings.SplitN(line, ":", 2)
|
||||
if len(parts) != 2 {
|
||||
t.Fatalf("pretty output line is not key/value: %q", line)
|
||||
}
|
||||
values[strings.TrimSpace(parts[0])] = strings.TrimSpace(parts[1])
|
||||
}
|
||||
return values
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageListPaginationNilRuntimeCursor(t *testing.T) {
|
||||
if got := listAppRequestCursor(nil); got != "" {
|
||||
t.Fatalf("nil runtime cursor = %q, want empty", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageAllDevAppPaginatedListsPreservePagination(t *testing.T) {
|
||||
const requestCursor = "opaque-current"
|
||||
const nextCursor = "opaque-next"
|
||||
tests := []struct {
|
||||
name string
|
||||
command string
|
||||
definition shortcut.Shortcut
|
||||
tool string
|
||||
listKey string
|
||||
response string
|
||||
args []string
|
||||
}{
|
||||
{
|
||||
name: "permissions",
|
||||
command: "+permission-list",
|
||||
definition: PermissionList,
|
||||
tool: "list_dev_app_permissions",
|
||||
listKey: "permissions",
|
||||
response: `{"result":{"items":[{"scopeValue":"Contact.User.Read"}],"hasMore":true,"nextCursor":"opaque-next"}}`,
|
||||
args: []string{"--unified-app-id", "app-1"},
|
||||
},
|
||||
{
|
||||
name: "events",
|
||||
command: "+event-list",
|
||||
definition: EventList,
|
||||
tool: "list_dev_app_events",
|
||||
listKey: "events",
|
||||
response: `{"result":{"events":[{"eventCode":"chat_update"}],"hasMore":true,"nextCursor":"opaque-next"}}`,
|
||||
args: []string{"--unified-app-id", "app-1"},
|
||||
},
|
||||
{
|
||||
name: "versions",
|
||||
command: "+version-list",
|
||||
definition: VersionList,
|
||||
tool: "list_dev_app_versions",
|
||||
listKey: "versions",
|
||||
response: `{"result":{"items":[{"versionId":"version-1"}],"hasMore":true,"nextCursor":"opaque-next"}}`,
|
||||
args: []string{"--unified-app-id", "app-1"},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
args := append([]string{}, test.args...)
|
||||
args = append(args, "--cursor", requestCursor, "--page-size", "1", "--format", "json")
|
||||
output, err, caller := executeDevAppListShortcut(
|
||||
t, test.command, test.definition, test.response, args...,
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("execute %s: %v", test.command, err)
|
||||
}
|
||||
if len(caller.calls) != 1 {
|
||||
t.Fatalf("calls = %#v", caller.calls)
|
||||
}
|
||||
call := caller.calls[0]
|
||||
if call.product != productDevApp || call.tool != test.tool ||
|
||||
call.params["cursor"] != requestCursor || call.params["pageSize"] != 1 {
|
||||
t.Fatalf("call = %#v", call)
|
||||
}
|
||||
|
||||
payload := decodeListPaginationEnvelope(t, output)
|
||||
items, ok := payload[test.listKey].([]any)
|
||||
if len(payload) != 4 || !ok || len(items) != 1 || payload["count"] != float64(1) ||
|
||||
payload["hasMore"] != true || payload["nextCursor"] != nextCursor {
|
||||
t.Fatalf("pagination payload = %#v", payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageListPaginationTerminalFormats(t *testing.T) {
|
||||
response := `{
|
||||
"apps":[{
|
||||
"unified_app_id":"app-1",
|
||||
"appName":"Alpha",
|
||||
"clientId":"client-1",
|
||||
"agent_id":42,
|
||||
"appStatus":"ENABLED",
|
||||
"modifyTime":"2026-08-09T00:00:00Z",
|
||||
"ignored":"drop-me"
|
||||
}],
|
||||
"hasMore":false,
|
||||
"nextCursor":""
|
||||
}`
|
||||
|
||||
for _, format := range []string{"json", "raw", "ndjson", "pretty"} {
|
||||
t.Run(format, func(t *testing.T) {
|
||||
if format == "pretty" {
|
||||
t.Setenv("NO_COLOR", "1")
|
||||
}
|
||||
output, err, caller := executeListPagination(t, response, "--format", format)
|
||||
if err != nil {
|
||||
t.Fatalf("execute terminal page: %v", err)
|
||||
}
|
||||
if len(caller.calls) != 1 {
|
||||
t.Fatalf("calls = %#v, want one page", caller.calls)
|
||||
}
|
||||
|
||||
if format == "pretty" {
|
||||
values := decodePrettyListPagination(t, output)
|
||||
if len(values) != 4 || values["count"] != "1" || values["hasMore"] != "false" ||
|
||||
values["nextCursor"] != "" || !strings.Contains(values["apps"], `"name":"Alpha"`) {
|
||||
t.Fatalf("pretty pagination values = %#v, output=%q", values, output)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if format == "ndjson" && len(strings.Split(strings.TrimSuffix(output, "\n"), "\n")) != 1 {
|
||||
t.Fatalf("ndjson expanded the page envelope: %q", output)
|
||||
}
|
||||
payload := decodeListPaginationEnvelope(t, output)
|
||||
if len(payload) != 4 || payload["count"] != float64(1) || payload["hasMore"] != false || payload["nextCursor"] != "" {
|
||||
t.Fatalf("terminal pagination payload = %#v", payload)
|
||||
}
|
||||
apps, ok := payload["apps"].([]any)
|
||||
if !ok || len(apps) != 1 {
|
||||
t.Fatalf("apps = %#v", payload["apps"])
|
||||
}
|
||||
app := apps[0].(map[string]any)
|
||||
want := map[string]any{
|
||||
"unifiedAppId": "app-1",
|
||||
"name": "Alpha",
|
||||
"appKey": "client-1",
|
||||
"agentId": float64(42),
|
||||
"status": "ENABLED",
|
||||
"gmtModified": "2026-08-09T00:00:00Z",
|
||||
}
|
||||
if !reflect.DeepEqual(app, want) {
|
||||
t.Fatalf("app projection = %#v, want %#v", app, want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageListPaginationValidItemProjectionIsOneToOne(t *testing.T) {
|
||||
response := `{
|
||||
"apps":[
|
||||
{"app_name":"Single","unknown":"drop-me"},
|
||||
{"unifiedAppId":"primary-id","unified_app_id":"secondary-id"},
|
||||
{"agent_id":null}
|
||||
],
|
||||
"hasMore":false,
|
||||
"nextCursor":""
|
||||
}`
|
||||
output, err, caller := executeListPagination(t, response, "--format", "json")
|
||||
if err != nil {
|
||||
t.Fatalf("valid item projection rejected: %v", err)
|
||||
}
|
||||
if len(caller.calls) != 1 {
|
||||
t.Fatalf("calls = %#v", caller.calls)
|
||||
}
|
||||
payload := decodeListPaginationEnvelope(t, output)
|
||||
apps, ok := payload["apps"].([]any)
|
||||
if len(payload) != 4 || !ok || len(apps) != 3 || payload["count"] != float64(3) {
|
||||
t.Fatalf("one-to-one payload = %#v", payload)
|
||||
}
|
||||
want := []any{
|
||||
map[string]any{"name": "Single"},
|
||||
map[string]any{"unifiedAppId": "primary-id"},
|
||||
map[string]any{"agentId": nil},
|
||||
}
|
||||
if !reflect.DeepEqual(apps, want) {
|
||||
t.Fatalf("projection = %#v, want %#v", apps, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageListPaginationSupportedOneLevelEnvelopes(t *testing.T) {
|
||||
for _, outerKey := range listAppCollectionKeys {
|
||||
for _, innerKey := range listAppCollectionKeys {
|
||||
name := outerKey + "/" + innerKey
|
||||
t.Run(name, func(t *testing.T) {
|
||||
response, err := json.Marshal(map[string]any{
|
||||
outerKey: map[string]any{
|
||||
innerKey: []any{map[string]any{"unifiedAppId": "app-envelope"}},
|
||||
"hasMore": false,
|
||||
"nextCursor": "",
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output, executeErr, caller := executeListPagination(t, string(response), "--format", "json")
|
||||
if executeErr != nil {
|
||||
t.Fatalf("supported envelope rejected: %v, response=%s", executeErr, response)
|
||||
}
|
||||
if len(caller.calls) != 1 {
|
||||
t.Fatalf("calls = %#v", caller.calls)
|
||||
}
|
||||
payload := decodeListPaginationEnvelope(t, output)
|
||||
if len(payload) != 4 || payload["count"] != float64(1) ||
|
||||
payload["hasMore"] != false || payload["nextCursor"] != "" {
|
||||
t.Fatalf("envelope payload = %#v", payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageListPaginationRejectsHiddenPageInSupportedEnvelopes(t *testing.T) {
|
||||
for _, outerKey := range listAppCollectionKeys {
|
||||
t.Run(outerKey, func(t *testing.T) {
|
||||
response, err := json.Marshal(map[string]any{
|
||||
outerKey: map[string]any{
|
||||
"apps": []any{},
|
||||
"hasMore": false,
|
||||
"nextCursor": "",
|
||||
"payload": map[string]any{
|
||||
"apps": []any{},
|
||||
"hasMore": false,
|
||||
"nextCursor": "",
|
||||
},
|
||||
},
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output, executeErr, caller := executeListPagination(t, string(response), "--format", "json")
|
||||
if executeErr == nil {
|
||||
t.Fatalf("hidden page unexpectedly accepted: %s", response)
|
||||
}
|
||||
if output != "" || len(caller.calls) != 1 {
|
||||
t.Fatalf("hidden page output=%q calls=%#v", output, caller.calls)
|
||||
}
|
||||
var typed *apperrors.Error
|
||||
if !errors.As(executeErr, &typed) || typed.Reason != "devapp_pagination_contract_invalid" {
|
||||
t.Fatalf("hidden page error = %T %#v", executeErr, executeErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageListPaginationAllowsNonPageMetadataSiblings(t *testing.T) {
|
||||
nonPageMetadata := map[string]any{
|
||||
"data": "trace-data",
|
||||
"result": "trace-result",
|
||||
"list": "trace-list",
|
||||
"items": "trace-items",
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
response map[string]any
|
||||
}{
|
||||
{
|
||||
name: "top-level page",
|
||||
response: map[string]any{
|
||||
"apps": []any{},
|
||||
"hasMore": false,
|
||||
"nextCursor": "",
|
||||
"metadata": nonPageMetadata,
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "supported wrapper",
|
||||
response: map[string]any{
|
||||
"result": map[string]any{
|
||||
"apps": []any{},
|
||||
"hasMore": false,
|
||||
"nextCursor": "",
|
||||
"metadata": nonPageMetadata,
|
||||
},
|
||||
},
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
response, err := json.Marshal(test.response)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
output, executeErr, caller := executeListPagination(t, string(response), "--format", "json")
|
||||
if executeErr != nil {
|
||||
t.Fatalf("non-page metadata rejected: %v, response=%s", executeErr, response)
|
||||
}
|
||||
if len(caller.calls) != 1 {
|
||||
t.Fatalf("calls = %#v", caller.calls)
|
||||
}
|
||||
payload := decodeListPaginationEnvelope(t, output)
|
||||
if len(payload) != 4 || payload["count"] != float64(0) ||
|
||||
payload["hasMore"] != false || payload["nextCursor"] != "" {
|
||||
t.Fatalf("non-page metadata payload = %#v", payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageListPaginationOneLevelAndOpaqueCursor(t *testing.T) {
|
||||
requestCursor := " opaque/request/+==:? "
|
||||
nextCursor := "opaque/next/+==:?"
|
||||
response := fmt.Sprintf(`{
|
||||
"result":{
|
||||
"items":[{"unifiedAppId":"app-2","name":"Beta"}],
|
||||
"hasMore":true,
|
||||
"nextCursor":%q
|
||||
}
|
||||
}`, nextCursor)
|
||||
|
||||
output, err, caller := executeListPagination(t, response,
|
||||
"--cursor", requestCursor,
|
||||
"--page-size", "7",
|
||||
"--name", "Beta",
|
||||
"--app-key", "client-2",
|
||||
"--format", "json",
|
||||
)
|
||||
if err != nil {
|
||||
t.Fatalf("execute non-terminal page: %v", err)
|
||||
}
|
||||
if len(caller.calls) != 1 {
|
||||
t.Fatalf("calls = %#v, want one page without auto-pagination", caller.calls)
|
||||
}
|
||||
call := caller.calls[0]
|
||||
if call.product != "devapp" || call.tool != "list_dev_app" {
|
||||
t.Fatalf("call target = %s/%s", call.product, call.tool)
|
||||
}
|
||||
wantParams := map[string]any{
|
||||
"cursor": requestCursor,
|
||||
"pageSize": 7,
|
||||
"name": "Beta",
|
||||
"appKey": "client-2",
|
||||
}
|
||||
if !reflect.DeepEqual(call.params, wantParams) {
|
||||
t.Fatalf("params = %#v, want %#v", call.params, wantParams)
|
||||
}
|
||||
payload := decodeListPaginationEnvelope(t, output)
|
||||
if len(payload) != 4 || payload["hasMore"] != true || payload["nextCursor"] != nextCursor || payload["count"] != float64(1) {
|
||||
t.Fatalf("non-terminal payload = %#v", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageListPaginationNormalizesDeployedTerminalEnvelope(t *testing.T) {
|
||||
response := `{
|
||||
"arguments":[],
|
||||
"errorCode":null,
|
||||
"errorMsg":null,
|
||||
"result":{
|
||||
"items":[{"unifiedAppId":"app-live","name":"Live App"}],
|
||||
"hasMore":false,
|
||||
"nextCursor":"4010069592"
|
||||
},
|
||||
"success":true
|
||||
}`
|
||||
|
||||
output, err, caller := executeListPagination(t, response, "--format", "json")
|
||||
if err != nil {
|
||||
t.Fatalf("deployed terminal envelope rejected: %v", err)
|
||||
}
|
||||
if len(caller.calls) != 1 || !reflect.DeepEqual(caller.calls[0].params, map[string]any{"pageSize": 20}) {
|
||||
t.Fatalf("calls = %#v", caller.calls)
|
||||
}
|
||||
payload := decodeListPaginationEnvelope(t, output)
|
||||
apps, ok := payload["apps"].([]any)
|
||||
if len(payload) != 4 || !ok || len(apps) != 1 || payload["count"] != float64(1) ||
|
||||
payload["hasMore"] != false || payload["nextCursor"] != "" {
|
||||
t.Fatalf("normalized deployed terminal payload = %#v", payload)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageListPaginationValidEmptyPages(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
response string
|
||||
args []string
|
||||
wantHasMore bool
|
||||
wantNext string
|
||||
wantRequest map[string]any
|
||||
}{
|
||||
{
|
||||
name: "terminal",
|
||||
response: `{"apps":[],"hasMore":false,"nextCursor":""}`,
|
||||
wantHasMore: false,
|
||||
wantNext: "",
|
||||
wantRequest: map[string]any{"pageSize": 20},
|
||||
},
|
||||
{
|
||||
name: "terminal omitted provider cursor",
|
||||
response: `{"apps":[],"hasMore":false}`,
|
||||
wantHasMore: false,
|
||||
wantNext: "",
|
||||
wantRequest: map[string]any{"pageSize": 20},
|
||||
},
|
||||
{
|
||||
name: "terminal null provider cursor",
|
||||
response: `{"apps":[],"hasMore":false,"nextCursor":null}`,
|
||||
wantHasMore: false,
|
||||
wantNext: "",
|
||||
wantRequest: map[string]any{"pageSize": 20},
|
||||
},
|
||||
{
|
||||
name: "terminal last provider cursor",
|
||||
response: `{"apps":[],"hasMore":false,"nextCursor":"4010069592"}`,
|
||||
wantHasMore: false,
|
||||
wantNext: "",
|
||||
wantRequest: map[string]any{"pageSize": 20},
|
||||
},
|
||||
{
|
||||
name: "non-terminal",
|
||||
response: `{"apps":[],"hasMore":true,"nextCursor":"after-empty"}`,
|
||||
args: []string{"--cursor", "before-empty"},
|
||||
wantHasMore: true,
|
||||
wantNext: "after-empty",
|
||||
wantRequest: map[string]any{"cursor": "before-empty", "pageSize": 20},
|
||||
},
|
||||
{
|
||||
name: "explicit empty request cursor",
|
||||
response: `{"apps":[],"hasMore":false,"nextCursor":""}`,
|
||||
args: []string{"--cursor", ""},
|
||||
wantHasMore: false,
|
||||
wantNext: "",
|
||||
wantRequest: map[string]any{"pageSize": 20},
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
args := append(append([]string(nil), test.args...), "--format", "json")
|
||||
output, err, caller := executeListPagination(t, test.response, args...)
|
||||
if err != nil {
|
||||
t.Fatalf("valid empty page rejected: %v", err)
|
||||
}
|
||||
if len(caller.calls) != 1 || !reflect.DeepEqual(caller.calls[0].params, test.wantRequest) {
|
||||
t.Fatalf("calls = %#v, want params %#v", caller.calls, test.wantRequest)
|
||||
}
|
||||
payload := decodeListPaginationEnvelope(t, output)
|
||||
apps, ok := payload["apps"].([]any)
|
||||
if len(payload) != 4 || !ok || len(apps) != 0 || payload["count"] != float64(0) ||
|
||||
payload["hasMore"] != test.wantHasMore || payload["nextCursor"] != test.wantNext {
|
||||
t.Fatalf("empty page payload = %#v", payload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageListPaginationRejectsInvalidContracts(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
response string
|
||||
args []string
|
||||
}{
|
||||
{name: "missing hasMore", response: `{"apps":[],"nextCursor":""}`},
|
||||
{name: "wrong hasMore type", response: `{"apps":[],"hasMore":"false","nextCursor":""}`},
|
||||
{name: "non-terminal missing continuation", response: `{"apps":[],"hasMore":true}`},
|
||||
{name: "empty continuation", response: `{"apps":[],"hasMore":true,"nextCursor":""}`},
|
||||
{name: "wrong continuation type", response: `{"apps":[],"hasMore":true,"nextCursor":7}`},
|
||||
{name: "terminal continuation wrong type", response: `{"apps":[],"hasMore":false,"nextCursor":7}`},
|
||||
{name: "stalled cursor", response: `{"apps":[],"hasMore":true,"nextCursor":"same"}`, args: []string{"--cursor", "same"}},
|
||||
{name: "null page", response: `null`},
|
||||
{name: "apps missing", response: `{"hasMore":false,"nextCursor":""}`},
|
||||
{name: "apps wrong type", response: `{"apps":"not-a-list","hasMore":false,"nextCursor":""}`},
|
||||
{name: "null app item", response: `{"apps":[null],"hasMore":false,"nextCursor":""}`},
|
||||
{name: "string app item", response: `{"apps":["bad"],"hasMore":false,"nextCursor":""}`},
|
||||
{name: "number app item", response: `{"apps":[7],"hasMore":false,"nextCursor":""}`},
|
||||
{name: "boolean app item", response: `{"apps":[true],"hasMore":false,"nextCursor":""}`},
|
||||
{name: "nested array app item", response: `{"apps":[[]],"hasMore":false,"nextCursor":""}`},
|
||||
{name: "empty app object", response: `{"apps":[{}],"hasMore":false,"nextCursor":""}`},
|
||||
{name: "unknown-only app object", response: `{"apps":[{"unknown":"value"}],"hasMore":false,"nextCursor":""}`},
|
||||
{name: "mixed valid and invalid app items", response: `{
|
||||
"apps":[{"unifiedAppId":"would-be-partial"},"bad"],
|
||||
"hasMore":false,"nextCursor":""
|
||||
}`},
|
||||
{name: "ambiguous list fields", response: `{"apps":[],"items":[],"hasMore":false,"nextCursor":""}`},
|
||||
{name: "ambiguous page envelopes", response: `{
|
||||
"apps":[],"hasMore":false,"nextCursor":"",
|
||||
"result":{"apps":[],"hasMore":false,"nextCursor":""}
|
||||
}`},
|
||||
{name: "metadata split across envelopes", response: `{
|
||||
"hasMore":false,"nextCursor":"",
|
||||
"result":{"apps":[]}
|
||||
}`},
|
||||
{name: "unknown payload wrapper conflicts with top page", response: `{
|
||||
"apps":[],"hasMore":false,"nextCursor":"",
|
||||
"payload":{"apps":[],"hasMore":false,"nextCursor":""}
|
||||
}`},
|
||||
{name: "unknown response wrapper conflicts with top page", response: `{
|
||||
"apps":[],"hasMore":false,"nextCursor":"",
|
||||
"response":{"items":[],"hasMore":false,"nextCursor":""}
|
||||
}`},
|
||||
{name: "unknown wrapper nextCursor evidence conflicts with top page", response: `{
|
||||
"apps":[],"hasMore":false,"nextCursor":"",
|
||||
"metadata":{"nextCursor":"hidden"}
|
||||
}`},
|
||||
{name: "unknown wrapper recursively nested list conflicts with top page", response: `{
|
||||
"apps":[],"hasMore":false,"nextCursor":"",
|
||||
"metadata":{"data":{"items":[]}}
|
||||
}`},
|
||||
{name: "unknown wrapper invalid apps evidence conflicts with top page", response: `{
|
||||
"apps":[],"hasMore":false,"nextCursor":"",
|
||||
"metadata":{"apps":"invalid"}
|
||||
}`},
|
||||
{name: "unsupported second-level envelope", response: `{
|
||||
"result":{"data":{"apps":[],"hasMore":false,"nextCursor":""}}
|
||||
}`},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
args := append(append([]string(nil), test.args...), "--format", "json")
|
||||
output, err, caller := executeListPagination(t, test.response, args...)
|
||||
if err == nil {
|
||||
t.Fatalf("invalid response unexpectedly succeeded: %s", test.response)
|
||||
}
|
||||
if output != "" {
|
||||
t.Fatalf("invalid response wrote success output: %q", output)
|
||||
}
|
||||
if len(caller.calls) != 1 {
|
||||
t.Fatalf("calls = %#v, want one bounded read", caller.calls)
|
||||
}
|
||||
var typed *apperrors.Error
|
||||
if !errors.As(err, &typed) {
|
||||
t.Fatalf("error = %T %v, want structured API error", err, err)
|
||||
}
|
||||
if typed.Category != apperrors.CategoryAPI || typed.ExitCode() != 1 || typed.Reason != "devapp_pagination_contract_invalid" {
|
||||
t.Fatalf("error contract = %#v", typed)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
#!/bin/sh
|
||||
# Mono↔multi skill content QA (G1–G4). See docs/skill-mono-multi-qa.md
|
||||
# Mono↔multi skill content QA (G1–G5). See docs/skill-mono-multi-qa.md
|
||||
set -eu
|
||||
|
||||
ROOT="$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)"
|
||||
|
||||
@@ -312,10 +312,13 @@ func checkCompatibility(root *cobra.Command, baseline interfaceContract) []strin
|
||||
continue
|
||||
}
|
||||
if actual.Value.Type() != expectedFlag.Type {
|
||||
failures = append(failures, fmt.Sprintf(
|
||||
"%q flag --%s changed type from %s to %s",
|
||||
displayPath(path), expectedFlag.Name, expectedFlag.Type, actual.Value.Type(),
|
||||
))
|
||||
if !reviewedFlagTypeChange(displayPath(path), expectedFlag.Name, expectedFlag.Type, actual.Value.Type()) ||
|
||||
flagContractOtherwiseChanged(expectedFlag, actual, actualScope) {
|
||||
failures = append(failures, fmt.Sprintf(
|
||||
"%q flag --%s changed type from %s to %s",
|
||||
displayPath(path), expectedFlag.Name, expectedFlag.Type, actual.Value.Type(),
|
||||
))
|
||||
}
|
||||
}
|
||||
if expectedFlag.Shorthand != "" && actual.Shorthand != expectedFlag.Shorthand {
|
||||
failures = append(failures, fmt.Sprintf(
|
||||
@@ -443,11 +446,20 @@ func mergeContracts(historical, current interfaceContract) (interfaceContract, [
|
||||
continue
|
||||
}
|
||||
if oldFlag.Type != newFlag.Type {
|
||||
failures = append(failures, fmt.Sprintf(
|
||||
"%q flag --%s changed type from %s to %s",
|
||||
displayPath(path), name, oldFlag.Type, newFlag.Type,
|
||||
))
|
||||
continue
|
||||
if !reviewedFlagTypeChange(displayPath(path), name, oldFlag.Type, newFlag.Type) ||
|
||||
mergedFlagContractOtherwiseChanged(oldFlag, newFlag) {
|
||||
failures = append(failures, fmt.Sprintf(
|
||||
"%q flag --%s changed type from %s to %s",
|
||||
displayPath(path), name, oldFlag.Type, newFlag.Type,
|
||||
))
|
||||
continue
|
||||
}
|
||||
// A reviewed migration keeps merging, and the merged entry keeps
|
||||
// the historical type below, exactly as this function keeps the
|
||||
// historical shorthand, required and hidden values. The baseline
|
||||
// records what was promised, so a later --check still resolves
|
||||
// this flag through the reviewed table rather than silently
|
||||
// adopting the new type as history.
|
||||
}
|
||||
if oldFlag.Shorthand != "" && oldFlag.Shorthand != newFlag.Shorthand {
|
||||
failures = append(failures, fmt.Sprintf(
|
||||
|
||||
@@ -10,6 +10,7 @@ import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/DingTalk-Real-AI/dingtalk-workspace-cli/internal/app"
|
||||
"github.com/spf13/cobra"
|
||||
)
|
||||
|
||||
@@ -239,6 +240,286 @@ func assertFailureContains(t *testing.T, failures []string, want string) {
|
||||
t.Fatalf("failures %v do not contain %q", failures, want)
|
||||
}
|
||||
|
||||
// policyRoot builds "dws old" with a single --policy flag declared by declare,
|
||||
// so a baseline and a candidate can differ only in how that flag is typed.
|
||||
func policyRoot(declare func(*cobra.Command)) *cobra.Command {
|
||||
root := &cobra.Command{Use: "dws"}
|
||||
old := &cobra.Command{Use: "old", Run: func(*cobra.Command, []string) {}}
|
||||
declare(old)
|
||||
root.AddCommand(old)
|
||||
root.InitDefaultHelpCmd()
|
||||
return root
|
||||
}
|
||||
|
||||
// registerReviewedFixture puts a fixture command in the reviewed table for the
|
||||
// duration of one test, so the behaviour tests exercise the real lookup instead
|
||||
// of depending on whichever production entries happen to exist.
|
||||
func registerReviewedFixture(t *testing.T, change flagTypeChange) {
|
||||
t.Helper()
|
||||
if _, exists := reviewedFlagTypeChanges[change]; exists {
|
||||
t.Fatalf("fixture %+v collides with a production entry", change)
|
||||
}
|
||||
reviewedFlagTypeChanges[change] = struct{}{}
|
||||
t.Cleanup(func() { delete(reviewedFlagTypeChanges, change) })
|
||||
}
|
||||
|
||||
const typeChangedFailure = "changed type from string to int"
|
||||
|
||||
func TestReviewedFlagTypeChangeAcceptsRegisteredMigration(t *testing.T) {
|
||||
baseline := snapshot(policyRoot(func(command *cobra.Command) {
|
||||
command.Flags().String("policy", "", "policy")
|
||||
}))
|
||||
current := policyRoot(func(command *cobra.Command) {
|
||||
command.Flags().Int("policy", 0, "policy")
|
||||
})
|
||||
|
||||
// Without an entry the migration is still a blocking change.
|
||||
assertFailureContains(t, checkCompatibility(current, baseline), typeChangedFailure)
|
||||
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws old", Flag: "policy", From: "string", To: "int"})
|
||||
if failures := checkCompatibility(current, baseline); len(failures) != 0 {
|
||||
t.Fatalf("a reviewed string->int migration should pass: %v", failures)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReviewedFlagTypeChangeIsDirectionSensitive(t *testing.T) {
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws old", Flag: "policy", From: "string", To: "int"})
|
||||
|
||||
// The reverse migration shares command and flag but not direction, so the
|
||||
// string->int entry must not admit it.
|
||||
baseline := snapshot(policyRoot(func(command *cobra.Command) {
|
||||
command.Flags().Int("policy", 0, "policy")
|
||||
}))
|
||||
current := policyRoot(func(command *cobra.Command) {
|
||||
command.Flags().String("policy", "", "policy")
|
||||
})
|
||||
assertFailureContains(t, checkCompatibility(current, baseline), "changed type from int to string")
|
||||
}
|
||||
|
||||
func TestReviewedFlagTypeChangeRejectsOtherCommandsAndFlags(t *testing.T) {
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws other", Flag: "policy", From: "string", To: "int"})
|
||||
baseline := snapshot(policyRoot(func(command *cobra.Command) {
|
||||
command.Flags().String("policy", "", "policy")
|
||||
}))
|
||||
current := policyRoot(func(command *cobra.Command) {
|
||||
command.Flags().Int("policy", 0, "policy")
|
||||
})
|
||||
// Same flag and direction, different command.
|
||||
assertFailureContains(t, checkCompatibility(current, baseline), typeChangedFailure)
|
||||
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws old", Flag: "elsewhere", From: "string", To: "int"})
|
||||
// Same command and direction, different flag.
|
||||
assertFailureContains(t, checkCompatibility(current, baseline), typeChangedFailure)
|
||||
}
|
||||
|
||||
// A reviewed migration is only accepted when the rest of the flag's contract
|
||||
// held still. Each case bundles one unrelated regression with the reviewed type
|
||||
// change and requires the type failure to reappear, which also anchors
|
||||
// flagContractOtherwiseChanged against the checks it mirrors: a condition that
|
||||
// drifts out of sync fails here instead of silently widening the exemption.
|
||||
func TestReviewedFlagTypeChangeRejectsBundledRegression(t *testing.T) {
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws old", Flag: "policy", From: "string", To: "int"})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
baseline func(*cobra.Command)
|
||||
current func(*cobra.Command)
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "became required",
|
||||
baseline: func(command *cobra.Command) { command.Flags().String("policy", "", "policy") },
|
||||
current: func(command *cobra.Command) {
|
||||
command.Flags().Int("policy", 0, "policy")
|
||||
_ = command.MarkFlagRequired("policy")
|
||||
},
|
||||
want: "became required",
|
||||
},
|
||||
{
|
||||
name: "became hidden",
|
||||
baseline: func(command *cobra.Command) { command.Flags().String("policy", "", "policy") },
|
||||
current: func(command *cobra.Command) {
|
||||
command.Flags().Int("policy", 0, "policy")
|
||||
_ = command.Flags().MarkHidden("policy")
|
||||
},
|
||||
want: "became hidden",
|
||||
},
|
||||
{
|
||||
name: "lost shorthand",
|
||||
baseline: func(command *cobra.Command) { command.Flags().StringP("policy", "p", "", "policy") },
|
||||
current: func(command *cobra.Command) { command.Flags().Int("policy", 0, "policy") },
|
||||
want: "lost shorthand",
|
||||
},
|
||||
{
|
||||
name: "changed no-opt value",
|
||||
baseline: func(command *cobra.Command) { command.Flags().String("policy", "", "policy") },
|
||||
current: func(command *cobra.Command) {
|
||||
command.Flags().Int("policy", 0, "policy")
|
||||
command.Flags().Lookup("policy").NoOptDefVal = "4"
|
||||
},
|
||||
want: "changed no-opt value",
|
||||
},
|
||||
{
|
||||
name: "narrowed persistent scope",
|
||||
baseline: func(command *cobra.Command) { command.PersistentFlags().String("policy", "", "policy") },
|
||||
current: func(command *cobra.Command) { command.Flags().Int("policy", 0, "policy") },
|
||||
want: "narrowed persistent scope",
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
failures := checkCompatibility(policyRoot(test.current), snapshot(policyRoot(test.baseline)))
|
||||
assertFailureContains(t, failures, test.want)
|
||||
assertFailureContains(t, failures, typeChangedFailure)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// mergeContracts runs the same admission decision on --merge. A reviewed
|
||||
// migration keeps merging and the merged entry keeps the historical type, so a
|
||||
// later --check still resolves the flag through the reviewed table.
|
||||
func TestMergeAcceptsReviewedFlagTypeChangeAndKeepsHistoricalType(t *testing.T) {
|
||||
historical := snapshot(policyRoot(func(command *cobra.Command) {
|
||||
command.Flags().String("policy", "", "policy")
|
||||
}))
|
||||
current := snapshot(policyRoot(func(command *cobra.Command) {
|
||||
command.Flags().Int("policy", 0, "policy")
|
||||
}))
|
||||
|
||||
if _, failures := mergeContracts(historical, current); len(failures) == 0 {
|
||||
t.Fatal("an unreviewed merge should report the type change")
|
||||
}
|
||||
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws old", Flag: "policy", From: "string", To: "int"})
|
||||
merged, failures := mergeContracts(historical, current)
|
||||
if len(failures) != 0 {
|
||||
t.Fatalf("a reviewed merge should pass: %v", failures)
|
||||
}
|
||||
if got := merged.Commands["old"].Flags["policy"].Type; got != "string" {
|
||||
t.Fatalf("merged type = %q, want the historical %q", got, "string")
|
||||
}
|
||||
}
|
||||
|
||||
// mergeContracts applies the same "nothing else moved" condition as
|
||||
// checkCompatibility, but against two recorded contracts rather than a live
|
||||
// pflag definition. Each case bundles one unrelated regression with the reviewed
|
||||
// type change and requires the type failure to reappear, anchoring
|
||||
// mergedFlagContractOtherwiseChanged against the checks it mirrors.
|
||||
func TestMergeRejectsReviewedFlagTypeChangeWithBundledRegression(t *testing.T) {
|
||||
registerReviewedFixture(t, flagTypeChange{CommandPath: "dws old", Flag: "policy", From: "string", To: "int"})
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
historical func(*cobra.Command)
|
||||
current func(*cobra.Command)
|
||||
}{
|
||||
{
|
||||
name: "lost shorthand",
|
||||
historical: func(command *cobra.Command) { command.Flags().StringP("policy", "p", "", "policy") },
|
||||
current: func(command *cobra.Command) { command.Flags().Int("policy", 0, "policy") },
|
||||
},
|
||||
{
|
||||
name: "became required",
|
||||
historical: func(command *cobra.Command) { command.Flags().String("policy", "", "policy") },
|
||||
current: func(command *cobra.Command) {
|
||||
command.Flags().Int("policy", 0, "policy")
|
||||
_ = command.MarkFlagRequired("policy")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "became hidden",
|
||||
historical: func(command *cobra.Command) { command.Flags().String("policy", "", "policy") },
|
||||
current: func(command *cobra.Command) {
|
||||
command.Flags().Int("policy", 0, "policy")
|
||||
_ = command.Flags().MarkHidden("policy")
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "changed no-opt value",
|
||||
historical: func(command *cobra.Command) { command.Flags().String("policy", "", "policy") },
|
||||
current: func(command *cobra.Command) {
|
||||
command.Flags().Int("policy", 0, "policy")
|
||||
command.Flags().Lookup("policy").NoOptDefVal = "4"
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "narrowed persistent scope",
|
||||
historical: func(command *cobra.Command) { command.PersistentFlags().String("policy", "", "policy") },
|
||||
current: func(command *cobra.Command) { command.Flags().Int("policy", 0, "policy") },
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
_, failures := mergeContracts(
|
||||
snapshot(policyRoot(test.historical)),
|
||||
snapshot(policyRoot(test.current)),
|
||||
)
|
||||
assertFailureContains(t, failures, typeChangedFailure)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The behaviour tests above register their own fixtures, so they cannot catch a
|
||||
// production entry whose key is spelled in the wrong form — that mistake
|
||||
// disables the exemption silently and only a real gate run reports it. Recompute
|
||||
// every key through displayPath instead of trusting the spelling in the table.
|
||||
func TestReviewedFlagTypeChangeKeysUseDisplayPaths(t *testing.T) {
|
||||
if len(reviewedFlagTypeChanges) == 0 {
|
||||
t.Fatal("豁免表为空:若确已清空,请连这条守卫一起删除")
|
||||
}
|
||||
for change := range reviewedFlagTypeChanges {
|
||||
if got := displayPath(internalCommandPath(change.CommandPath)); got != change.CommandPath {
|
||||
t.Errorf("命令路径不是 displayPath 的规范形态\n 登记: %s\n 规范: %s", change.CommandPath, got)
|
||||
}
|
||||
if change.Flag == "" || strings.HasPrefix(change.Flag, "-") {
|
||||
t.Errorf("%s: flag 名应是裸名(lookupFlag 用裸名查找),登记为 %q", change.CommandPath, change.Flag)
|
||||
}
|
||||
if change.From == "" || change.To == "" || change.From == change.To {
|
||||
t.Errorf("%s --%s: %q -> %q 不构成类型迁移", change.CommandPath, change.Flag, change.From, change.To)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Anchor every production entry to the real command tree. A misspelled command
|
||||
// or flag name would leave the exemption permanently inert, and the behaviour
|
||||
// tests cannot see that because they register their own paths.
|
||||
func TestReviewedFlagTypeChangeEntriesResolveInTheRealCommandTree(t *testing.T) {
|
||||
if len(reviewedFlagTypeChanges) == 0 {
|
||||
t.Fatal("豁免表为空:若确已清空,请连这条守卫一起删除")
|
||||
}
|
||||
root := app.NewRootCommand()
|
||||
for change := range reviewedFlagTypeChanges {
|
||||
command, resolved := resolveCommand(root, internalCommandPath(change.CommandPath))
|
||||
if !resolved {
|
||||
t.Errorf("%q 在真实命令树中不存在", change.CommandPath)
|
||||
continue
|
||||
}
|
||||
flag, _ := lookupFlag(command, change.Flag)
|
||||
if flag == nil {
|
||||
t.Errorf("%q 上不存在 --%s", change.CommandPath, change.Flag)
|
||||
continue
|
||||
}
|
||||
// Exactly one side holds depending on whether the migration has landed:
|
||||
// From before it does, To afterwards. Asserting membership catches a
|
||||
// misspelled type name without failing while the migration is pending.
|
||||
if actual := flag.Value.Type(); actual != change.From && actual != change.To {
|
||||
t.Errorf("%q --%s 当前类型 %q 既不是 %q 也不是 %q",
|
||||
change.CommandPath, change.Flag, actual, change.From, change.To)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// internalCommandPath inverts displayPath so a table key can be fed back into
|
||||
// resolveCommand and displayPath.
|
||||
func internalCommandPath(displayed string) string {
|
||||
if displayed == "dws" {
|
||||
return "root"
|
||||
}
|
||||
return strings.ReplaceAll(strings.TrimPrefix(displayed, "dws "), " ", ".")
|
||||
}
|
||||
|
||||
func testRoot() *cobra.Command {
|
||||
root := &cobra.Command{Use: "dws"}
|
||||
old := &cobra.Command{Use: "old"}
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// Copyright 2026 Alibaba Group
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
|
||||
package main
|
||||
|
||||
import "github.com/spf13/pflag"
|
||||
|
||||
// flagTypeChange identifies one flag type migration exactly: which command,
|
||||
// which flag, and in which direction. Nothing is matched by wildcard — an entry
|
||||
// that differs in any of the four fields does not apply.
|
||||
//
|
||||
// CommandPath is the display form produced by displayPath ("dws minutes
|
||||
// permission apply"), not the dot-separated internal path. Writing the internal
|
||||
// form here would silently disable the exemption instead of failing loudly, so
|
||||
// TestReviewedFlagTypeChangeKeysUseDisplayPaths recomputes every key through
|
||||
// displayPath rather than trusting the spelling below.
|
||||
//
|
||||
// This table is duplicated in internal/interfacesnapshot/reviewed.go and the two
|
||||
// must stay identical; the interfacesnapshot package has a test that fails if
|
||||
// they drift. The duplication is forced rather than chosen:
|
||||
// check-authoritative-interface-baselines.sh copies this whole directory into a
|
||||
// worktree checked out at a historical revision and builds it there, so nothing
|
||||
// here may import a package this branch adds — that build would fail with an
|
||||
// unresolved import instead of reporting a compatibility result.
|
||||
type flagTypeChange struct {
|
||||
CommandPath string
|
||||
Flag string
|
||||
From string
|
||||
To string
|
||||
}
|
||||
|
||||
// reviewedFlagTypeChanges enumerates the individually reviewed flag type
|
||||
// migrations this gate accepts. A flag type is part of the published CLI
|
||||
// contract, and a type swap cannot be proven safe from the type names alone —
|
||||
// whether old invocations still parse depends on the concrete value domain the
|
||||
// command enforces. So a migration is accepted only when this exact command,
|
||||
// flag, and old→new pair appear here. Adding an entry is a contract decision
|
||||
// and belongs in review, not in a feature change.
|
||||
//
|
||||
// Entries are direction-sensitive by construction: "string" → "int" is a
|
||||
// separate key from "int" → "string" and only the reviewed direction is
|
||||
// accepted. The reverse is not a candidate for this table — widening an int
|
||||
// flag back to string lets values the parser used to reject reach RunE, which
|
||||
// is a genuine loosening of validation rather than a type migration.
|
||||
//
|
||||
// The table alone does not admit a change: reviewedFlagTypeChange is consulted
|
||||
// only when nothing else about the flag moved. See the callers in
|
||||
// checkCompatibility and mergeContracts.
|
||||
var reviewedFlagTypeChanges = map[flagTypeChange]struct{}{
|
||||
// "dws minutes permission apply --policy" moved from a String flag parsed
|
||||
// with strconv.ParseInt(v, 10, 64) in RunE to a native Int flag, keeping the
|
||||
// same [2,4] domain check in RunE.
|
||||
//
|
||||
// This is admissible because the historical set of *successful* invocations
|
||||
// is a subset of the new one, not merely similar to it:
|
||||
//
|
||||
// - Old: the value had to parse as base-10 and land in [2,4]. That is
|
||||
// exactly "2", "3", "4" plus sign/leading-zero spellings of them
|
||||
// ("+3", "03", "003", ...).
|
||||
// - New: pflag's intValue.Set parses with strconv.ParseInt(s, 0, 64) —
|
||||
// base 0 — and RunE still enforces [2,4]. Every base-10 spelling above
|
||||
// resolves to the same number under base 0, so no historical success
|
||||
// becomes a failure.
|
||||
// - Base 0 additionally accepts "0x3" and friends, which the old parser
|
||||
// rejected. That widens the accepted set; it cannot break a caller who
|
||||
// was already succeeding.
|
||||
// - Values outside [2,4] and non-numeric values still fail. Only the
|
||||
// failure *message and timing* move, from RunE to flag parsing.
|
||||
//
|
||||
// The flag's default value changes from "" to "0" as an unavoidable
|
||||
// consequence of the type. Neither gate compares defaults, and a default is
|
||||
// not reachable by a caller here because RunE requires the flag to be
|
||||
// explicitly set, so this is not a contract change.
|
||||
{CommandPath: "dws minutes permission apply", Flag: "policy", From: "string", To: "int"}: {},
|
||||
}
|
||||
|
||||
// reviewedFlagTypeChange reports whether this exact command, flag and direction
|
||||
// is a reviewed migration. Callers must additionally establish that the rest of
|
||||
// the flag's contract is unchanged before skipping the failure.
|
||||
func reviewedFlagTypeChange(commandPath, flag, from, to string) bool {
|
||||
_, reviewed := reviewedFlagTypeChanges[flagTypeChange{
|
||||
CommandPath: commandPath,
|
||||
Flag: flag,
|
||||
From: from,
|
||||
To: to,
|
||||
}]
|
||||
return reviewed
|
||||
}
|
||||
|
||||
// flagContractOtherwiseChanged reports whether anything checkCompatibility
|
||||
// enforces about a flag, other than its type, regressed against the baseline. A
|
||||
// reviewed type migration is only accepted when this returns false, so the
|
||||
// exemption cannot carry an unrelated regression in behind it.
|
||||
//
|
||||
// Every condition here mirrors one of the checks that follow the type check in
|
||||
// checkCompatibility and must stay in step with them. The pairing is anchored by
|
||||
// tests that bundle each regression with the reviewed type change and require
|
||||
// the type failure to reappear, so a condition that drifts out of sync fails
|
||||
// loudly instead of silently widening the exemption.
|
||||
func flagContractOtherwiseChanged(expected flagContract, actual *pflag.Flag, actualScope string) bool {
|
||||
if expected.Shorthand != "" && actual.Shorthand != expected.Shorthand {
|
||||
return true
|
||||
}
|
||||
if expected.RequiredSet && !expected.Required && isRequiredFlag(actual) {
|
||||
return true
|
||||
}
|
||||
if expected.HiddenSet && !expected.Hidden && actual.Hidden {
|
||||
return true
|
||||
}
|
||||
if expected.NoOptSet && actual.NoOptDefVal != expected.NoOpt {
|
||||
return true
|
||||
}
|
||||
if expected.ScopeSet && expected.Scope == "persistent" && actualScope == "local" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// mergedFlagContractOtherwiseChanged is the mergeContracts counterpart of
|
||||
// flagContractOtherwiseChanged, comparing two recorded contracts rather than a
|
||||
// contract against a live pflag definition. It mirrors the checks that follow
|
||||
// the type check in mergeContracts.
|
||||
func mergedFlagContractOtherwiseChanged(oldFlag, newFlag flagContract) bool {
|
||||
if oldFlag.Shorthand != "" && oldFlag.Shorthand != newFlag.Shorthand {
|
||||
return true
|
||||
}
|
||||
if oldFlag.RequiredSet && !oldFlag.Required && newFlag.Required {
|
||||
return true
|
||||
}
|
||||
if oldFlag.HiddenSet && !oldFlag.Hidden && newFlag.Hidden {
|
||||
return true
|
||||
}
|
||||
if oldFlag.NoOptSet && newFlag.NoOptSet && oldFlag.NoOpt != newFlag.NoOpt {
|
||||
return true
|
||||
}
|
||||
if oldFlag.ScopeSet && oldFlag.Scope == "persistent" && newFlag.Scope == "local" {
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -18,6 +18,18 @@ import (
|
||||
|
||||
const schemaContractVersion = 3
|
||||
|
||||
// propertySourceReviewedMappingExclusion is the provenance source a parameter
|
||||
// reports when its property is deliberately omitted through the reviewed
|
||||
// mapping exclusion table (internal/cli/schema_parameter_mapping_ledger.go).
|
||||
// Only this source qualifies for the property-clearing carve-out in
|
||||
// checkParameterCompatibility.
|
||||
const propertySourceReviewedMappingExclusion = "reviewed_mapping_exclusion"
|
||||
|
||||
// interfaceModeMCP is the interface_mode of a tool backed by exactly one RPC.
|
||||
// Only a tool that is mcp on both sides can qualify for the interface_ref
|
||||
// redirect carve-out in compatibleInterfaceRefRedirect.
|
||||
const interfaceModeMCP = "mcp"
|
||||
|
||||
type schemaContract struct {
|
||||
Version int `json:"version"`
|
||||
Products map[string]productSchema `json:"products"`
|
||||
@@ -53,6 +65,7 @@ type positionalSchema struct {
|
||||
type parameterSchema struct {
|
||||
Type string `json:"type"`
|
||||
Property string `json:"property,omitempty"`
|
||||
PropertySource string `json:"property_source,omitempty"`
|
||||
InterfaceType string `json:"interface_type,omitempty"`
|
||||
Required bool `json:"required,omitempty"`
|
||||
CLIRequired bool `json:"cli_required,omitempty"`
|
||||
@@ -361,6 +374,11 @@ func normalizeParameter(raw json.RawMessage) (parameterSchema, error) {
|
||||
InterfaceDefault json.RawMessage `json:"interface_default"`
|
||||
Format string `json:"format"`
|
||||
Enum []string `json:"enum"`
|
||||
FieldProvenance struct {
|
||||
Property struct {
|
||||
Source string `json:"source"`
|
||||
} `json:"property"`
|
||||
} `json:"field_provenance"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, ¶meter); err != nil {
|
||||
return parameterSchema{}, err
|
||||
@@ -388,6 +406,7 @@ func normalizeParameter(raw json.RawMessage) (parameterSchema, error) {
|
||||
return parameterSchema{
|
||||
Type: parameterType,
|
||||
Property: strings.TrimSpace(parameter.Property),
|
||||
PropertySource: strings.TrimSpace(parameter.FieldProvenance.Property.Source),
|
||||
InterfaceType: strings.TrimSpace(parameter.InterfaceType),
|
||||
Required: parameter.Required,
|
||||
CLIRequired: parameter.CLIRequired,
|
||||
@@ -479,7 +498,6 @@ func checkToolCompatibility(toolPath string, oldTool, newTool toolSchema) []stri
|
||||
}{
|
||||
{name: "primary_cli_path", old: oldTool.PrimaryCLIPath, new: newTool.PrimaryCLIPath},
|
||||
{name: "interface_mode", old: oldTool.InterfaceMode, new: newTool.InterfaceMode},
|
||||
{name: "interface_ref", old: oldTool.InterfaceRef, new: newTool.InterfaceRef},
|
||||
{name: "availability", old: oldTool.Availability, new: newTool.Availability},
|
||||
{name: "effect", old: oldTool.Effect, new: newTool.Effect},
|
||||
{name: "risk", old: oldTool.Risk, new: newTool.Risk},
|
||||
@@ -510,10 +528,84 @@ func checkToolCompatibility(toolPath string, oldTool, newTool toolSchema) []stri
|
||||
}
|
||||
failures = append(failures, checkParameterCompatibility(toolPath, parameter, oldParameter, newParameter)...)
|
||||
}
|
||||
|
||||
// interface_ref is evaluated last, because the redirect carve-out below is
|
||||
// conditional on every other check for this tool having passed.
|
||||
if oldTool.InterfaceRef != newTool.InterfaceRef &&
|
||||
!compatibleInterfaceRefRedirect(toolPath, oldTool, newTool, failures) {
|
||||
failures = append(failures, fmt.Sprintf("schema tool %q changed interface_ref", toolPath))
|
||||
}
|
||||
sort.Strings(failures)
|
||||
return failures
|
||||
}
|
||||
|
||||
// reviewedInterfaceRefRedirect enumerates the exact, individually reviewed
|
||||
// backend RPC migrations this gate accepts. Schema shape alone cannot prove two
|
||||
// RPCs share business semantics, permissions, error behaviour, or side effects,
|
||||
// so a redirect is only accepted when the specific tool and the specific
|
||||
// old→new pair appear here. Any other ref change is still reported.
|
||||
//
|
||||
// Keyed by tool path ("<product>/<tool id>"), then by the previous
|
||||
// interface_ref, with the value being the single accepted new ref. Both refs are
|
||||
// the canonicalized interface_ref JSON exactly as parseTool produces it (see
|
||||
// canonicalRawJSON) — not a bare RPC name. Adding an entry is a contract
|
||||
// decision and belongs in review, not in a feature change.
|
||||
var reviewedInterfaceRefRedirect = map[string]map[string]string{
|
||||
// The style surface moved from update_range (which writes values) to
|
||||
// set_cell_range's cellStyles payload (style-only, preserving values). This
|
||||
// is the only channel that can express italic / underline / strike-through /
|
||||
// font family / borders. Same product, same target range semantics, same
|
||||
// permission scope; the flat style properties it loses are accepted
|
||||
// separately as reviewed mapping exclusions.
|
||||
"sheet/sheet.range_set_style": {
|
||||
`{"product_id":"sheet","rpc_name":"update_range"}`: `{"product_id":"sheet","rpc_name":"set_cell_range"}`,
|
||||
},
|
||||
}
|
||||
|
||||
// compatibleInterfaceRefRedirect accepts repointing a tool at a different
|
||||
// backing RPC when the migration is an explicitly reviewed entry in
|
||||
// reviewedInterfaceRefRedirect **and** the CLI-facing contract is provably
|
||||
// unchanged.
|
||||
//
|
||||
// interface_ref is audit and traceability metadata: it records which RPC backs a
|
||||
// leaf. Nothing reads it at runtime — the tool a leaf invokes is decided in the
|
||||
// CLI source, so a stale ref does not misroute a call, it only misinforms a
|
||||
// reader. When the backing RPC genuinely moves, the honest options are to update
|
||||
// the ref or to keep publishing a name that no longer matches the request being
|
||||
// sent.
|
||||
//
|
||||
// Being audit-only is why a reviewed redirect can be accepted at all; it is not
|
||||
// a reason to accept redirects in general. Two RPCs with compatible Schema
|
||||
// parameters may still differ in permissions, quota, error taxonomy, or side
|
||||
// effects, none of which this gate can see. Hence the allowlist below, plus:
|
||||
//
|
||||
// - interface_mode is unchanged and stays "mcp". A move to or from
|
||||
// "composite" is a change in kind, not a redirect, and is still reported.
|
||||
// - both refs are non-empty. Removing a ref is not a redirect.
|
||||
// - no other compatibility failure was recorded for this tool. This is the
|
||||
// operative meaning of "the CLI contract is unchanged": no parameter was
|
||||
// lost, none became required, no type / default / format / enum moved, no
|
||||
// constraint tightened, no positional or dry_run change. Any one of those
|
||||
// re-reports the redirect, so the exemption cannot smuggle a surface change
|
||||
// in behind a backend move.
|
||||
//
|
||||
// A cleared property that resolved through a reviewed mapping exclusion is
|
||||
// already accepted by checkParameterCompatibility and so does not block this;
|
||||
// that pairing is expected, since a leaf moving to a nested payload loses its
|
||||
// flat property names in the same change.
|
||||
func compatibleInterfaceRefRedirect(toolPath string, oldTool, newTool toolSchema, otherFailures []string) bool {
|
||||
if oldTool.InterfaceMode != newTool.InterfaceMode || newTool.InterfaceMode != interfaceModeMCP {
|
||||
return false
|
||||
}
|
||||
if oldTool.InterfaceRef == "" || newTool.InterfaceRef == "" {
|
||||
return false
|
||||
}
|
||||
if reviewedInterfaceRefRedirect[toolPath][oldTool.InterfaceRef] != newTool.InterfaceRef {
|
||||
return false
|
||||
}
|
||||
return len(otherFailures) == 0
|
||||
}
|
||||
|
||||
// compatibleAdditiveConstraintEvolution accepts constraint evolution that
|
||||
// cannot invalidate an invocation expressible by the historical public
|
||||
// parameter contract. Existing groups may only gain members; additions to a
|
||||
@@ -730,7 +822,6 @@ func checkParameterCompatibility(toolPath, name string, oldParameter, newParamet
|
||||
new string
|
||||
}{
|
||||
{name: "type", old: oldParameter.Type, new: newParameter.Type},
|
||||
{name: "property", old: oldParameter.Property, new: newParameter.Property},
|
||||
{name: "default", old: oldParameter.Default, new: newParameter.Default},
|
||||
{name: "interface_default", old: oldParameter.InterfaceDefault, new: newParameter.InterfaceDefault},
|
||||
{name: "format", old: oldParameter.Format, new: newParameter.Format},
|
||||
@@ -739,6 +830,36 @@ func checkParameterCompatibility(toolPath, name string, oldParameter, newParamet
|
||||
failures = append(failures, fmt.Sprintf("schema tool %q parameter %q changed %s", toolPath, name, field.name))
|
||||
}
|
||||
}
|
||||
// Clearing property is accepted as compatible only when the new value is
|
||||
// omitted through a reviewed mapping exclusion. This is the same shape as
|
||||
// the interface_type carve-out below: a declaration that the flag has no
|
||||
// single top-level RPC property, replacing a value that is no longer true.
|
||||
//
|
||||
// It exists because a leaf whose backing RPC gains a nested payload has no
|
||||
// honest flat property to publish. The alternative outcomes are both worse:
|
||||
// keep naming a field the request no longer contains, or let assembly fall
|
||||
// back to flag_name_inference and publish a name that appears in no request
|
||||
// at all.
|
||||
//
|
||||
// The predicate is deliberately narrow:
|
||||
// - old non-empty AND new empty (a redirect to a different non-empty
|
||||
// value stays a contract break)
|
||||
// - the new value resolved through reviewed_mapping_exclusion, so an
|
||||
// accidental or silent drop is still reported
|
||||
//
|
||||
// The exclusion table cannot be abused to wave through arbitrary clearing:
|
||||
// internal/cli/schema_parameter_bindings.go verifies that every parameter
|
||||
// claiming an exclusion really does deliver an empty property, and every
|
||||
// entry carries a non-empty reviewed reason.
|
||||
//
|
||||
// Consumers must treat a missing property as "no direct mapping" and read
|
||||
// the provenance reason for where the value actually lands. Re-populating a
|
||||
// property requires an explicit ParamDecl declaration.
|
||||
if oldParameter.Property != newParameter.Property &&
|
||||
!(oldParameter.Property != "" && newParameter.Property == "" &&
|
||||
newParameter.PropertySource == propertySourceReviewedMappingExclusion) {
|
||||
failures = append(failures, fmt.Sprintf("schema tool %q parameter %q changed property", toolPath, name))
|
||||
}
|
||||
// Clearing interface_type is accepted as compatible: a deliberate,
|
||||
// wire-visible policy decision taken with the pinned MCP metadata
|
||||
// retirement. Production no longer projects MCP-sourced types unless
|
||||
|
||||
@@ -5,6 +5,7 @@ package main
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -340,6 +341,18 @@ func TestSchemaCompatibilityRejectsContractDrift(t *testing.T) {
|
||||
{name: "changed property", want: "changed property", mutate: func(contract *schemaContract) {
|
||||
mutateParameter(contract, func(parameter *parameterSchema) { parameter.Property = "subject" })
|
||||
}},
|
||||
{name: "cleared property without a reviewed exclusion", want: "changed property", mutate: func(contract *schemaContract) {
|
||||
mutateParameter(contract, func(parameter *parameterSchema) {
|
||||
parameter.Property = ""
|
||||
parameter.PropertySource = "flag_name_inference"
|
||||
})
|
||||
}},
|
||||
{name: "redirected property despite a reviewed exclusion", want: "changed property", mutate: func(contract *schemaContract) {
|
||||
mutateParameter(contract, func(parameter *parameterSchema) {
|
||||
parameter.Property = "subject"
|
||||
parameter.PropertySource = propertySourceReviewedMappingExclusion
|
||||
})
|
||||
}},
|
||||
{name: "changed interface type", want: "changed interface_type", mutate: func(contract *schemaContract) {
|
||||
mutateParameter(contract, func(parameter *parameterSchema) { parameter.InterfaceType = "integer" })
|
||||
}},
|
||||
@@ -679,3 +692,242 @@ func TestCrossPlatformCoverageSchemaCompatAdditiveConstraintEvolution(t *testing
|
||||
t.Fatal("each historical group must match a distinct expanded group")
|
||||
}
|
||||
}
|
||||
|
||||
// Clearing a property through the reviewed mapping exclusion table is the one
|
||||
// accepted shape, mirroring the interface_type retirement allowance. A leaf
|
||||
// whose backing RPC moved to a nested payload has no honest flat property to
|
||||
// publish; the alternatives are naming a field the request no longer contains,
|
||||
// or letting flag_name_inference publish a name that appears in no request.
|
||||
func TestCrossPlatformCoverageSchemaCompatPropertyClearingExclusion(t *testing.T) {
|
||||
baseline := baselineContract()
|
||||
|
||||
// Accepted: non-empty -> empty, resolved through a reviewed exclusion.
|
||||
current := cloneContract(baseline)
|
||||
mutateParameter(¤t, func(parameter *parameterSchema) {
|
||||
parameter.Property = ""
|
||||
parameter.PropertySource = propertySourceReviewedMappingExclusion
|
||||
})
|
||||
if failures := checkCompatibility(baseline, current); len(failures) != 0 {
|
||||
t.Fatalf("clearing property through a reviewed exclusion should pass: %v", failures)
|
||||
}
|
||||
|
||||
// Every neighbouring shape must stay incompatible, so the carve-out cannot
|
||||
// be widened by accident.
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
property string
|
||||
source string
|
||||
}{
|
||||
{"cleared by inference", "", "flag_name_inference"},
|
||||
{"cleared by a native annotation", "", "native_annotation"},
|
||||
{"cleared with no recorded source", "", ""},
|
||||
{"redirected to another non-empty value", "cellStyles", propertySourceReviewedMappingExclusion},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
drifted := cloneContract(baseline)
|
||||
mutateParameter(&drifted, func(parameter *parameterSchema) {
|
||||
parameter.Property = tc.property
|
||||
parameter.PropertySource = tc.source
|
||||
})
|
||||
failures := checkCompatibility(baseline, drifted)
|
||||
if len(failures) == 0 {
|
||||
t.Fatal("must remain incompatible")
|
||||
}
|
||||
var sawProperty bool
|
||||
for _, failure := range failures {
|
||||
if strings.Contains(failure, "changed property") {
|
||||
sawProperty = true
|
||||
}
|
||||
}
|
||||
if !sawProperty {
|
||||
t.Fatalf("expected a changed property failure, got %v", failures)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// A parameter that never published a property must not gain one silently
|
||||
// just because it carries an exclusion source.
|
||||
populated := cloneContract(baseline)
|
||||
mutateParameter(&populated, func(parameter *parameterSchema) { parameter.Property = "" })
|
||||
gained := cloneContract(populated)
|
||||
mutateParameter(&gained, func(parameter *parameterSchema) {
|
||||
parameter.Property = "backgroundColors"
|
||||
parameter.PropertySource = propertySourceReviewedMappingExclusion
|
||||
})
|
||||
if failures := checkCompatibility(populated, gained); len(failures) == 0 {
|
||||
t.Fatal("populating a previously empty property must stay incompatible")
|
||||
}
|
||||
}
|
||||
|
||||
// Repointing a leaf at a different backing RPC is accepted only when the
|
||||
// CLI-facing contract is provably unchanged. interface_ref is audit metadata;
|
||||
// nothing reads it at runtime, so a stale value misinforms a reader rather than
|
||||
// misrouting a call. The gate is that no other compatibility check for the tool
|
||||
// failed — that is the operative meaning of "the contract is unchanged".
|
||||
// reviewedInterfaceRefRedirect 的键值必须是 parseTool 经 canonicalRawJSON 实际产出
|
||||
// 的紧凑 JSON。这条守卫是必要的:该表先前误登记为裸 RPC 名("update_range"),后又
|
||||
// 误登记为带空格的美化 JSON,两次都让豁免完全失效——而上面的用例是用测试自己注册
|
||||
// 的值断言的,所以两次都通过了,只有真实门禁才报错。这里用 canonicalRawJSON 复算
|
||||
// 期望值,把格式锚定到生产代码而不是作者的书写习惯。
|
||||
func TestCrossPlatformCoverageReviewedRedirectKeysAreCanonicalJSON(t *testing.T) {
|
||||
canon := func(raw string) string {
|
||||
got, err := canonicalRawJSON(json.RawMessage(raw))
|
||||
if err != nil {
|
||||
t.Fatalf("canonicalRawJSON(%s): %v", raw, err)
|
||||
}
|
||||
return got
|
||||
}
|
||||
if len(reviewedInterfaceRefRedirect) == 0 {
|
||||
t.Fatal("redirect allowlist 为空:若确已清空,请同时删除这条守卫")
|
||||
}
|
||||
for toolPath, pairs := range reviewedInterfaceRefRedirect {
|
||||
if len(pairs) == 0 {
|
||||
t.Errorf("%s: 空的 redirect 表项没有意义", toolPath)
|
||||
}
|
||||
for oldRef, newRef := range pairs {
|
||||
if got := canon(oldRef); got != oldRef {
|
||||
t.Errorf("%s: old ref 不是规范形态\n 登记: %s\n 规范: %s", toolPath, oldRef, got)
|
||||
}
|
||||
if got := canon(newRef); got != newRef {
|
||||
t.Errorf("%s: new ref 不是规范形态\n 登记: %s\n 规范: %s", toolPath, newRef, got)
|
||||
}
|
||||
if oldRef == newRef {
|
||||
t.Errorf("%s: old 与 new 相同,不构成 redirect", toolPath)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestCrossPlatformCoverageSchemaCompatInterfaceRefRedirect(t *testing.T) {
|
||||
// The redirect carve-out only accepts an explicitly reviewed tool + old→new
|
||||
// ref pair. Register the fixture's path for the duration of this test so the
|
||||
// accepted shapes below exercise the allowlist rather than a blanket rule.
|
||||
const fixturePath = "doc/doc.create"
|
||||
oldRef := `{"product_id":"sheet","rpc_name":"update_range"}`
|
||||
newRef := `{"product_id":"sheet","rpc_name":"set_cell_range"}`
|
||||
reviewedInterfaceRefRedirect[fixturePath] = map[string]string{oldRef: newRef}
|
||||
t.Cleanup(func() { delete(reviewedInterfaceRefRedirect, fixturePath) })
|
||||
|
||||
// The baseline fixture is interface_mode=local; the carve-out only applies to
|
||||
// mcp-backed leaves, so establish an mcp baseline first.
|
||||
baseline := cloneContract(baselineContract())
|
||||
mutateTool(&baseline, func(tool *toolSchema) {
|
||||
tool.InterfaceMode = interfaceModeMCP
|
||||
tool.InterfaceRef = oldRef
|
||||
})
|
||||
|
||||
// Accepted: mcp -> mcp, both refs non-empty, the pair is reviewed, nothing
|
||||
// else changed.
|
||||
redirected := cloneContract(baseline)
|
||||
mutateTool(&redirected, func(tool *toolSchema) { tool.InterfaceRef = newRef })
|
||||
if failures := checkCompatibility(baseline, redirected); len(failures) != 0 {
|
||||
t.Fatalf("a reviewed interface_ref redirect should pass: %v", failures)
|
||||
}
|
||||
|
||||
// Paired with a reviewed property clearing, which is the realistic shape:
|
||||
// a leaf moving to a nested payload loses its flat property names.
|
||||
withCleared := cloneContract(redirected)
|
||||
mutateParameter(&withCleared, func(parameter *parameterSchema) {
|
||||
parameter.Property = ""
|
||||
parameter.PropertySource = propertySourceReviewedMappingExclusion
|
||||
})
|
||||
if failures := checkCompatibility(baseline, withCleared); len(failures) != 0 {
|
||||
t.Fatalf("redirect plus reviewed property clearing should pass: %v", failures)
|
||||
}
|
||||
|
||||
// Rejected shapes. Each must still report the redirect, so a surface change
|
||||
// cannot ride along behind a backend move.
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
mutate func(*schemaContract)
|
||||
}{
|
||||
{"ref removed rather than redirected", func(contract *schemaContract) {
|
||||
mutateTool(contract, func(tool *toolSchema) { tool.InterfaceRef = "" })
|
||||
}},
|
||||
{"mode moved to composite", func(contract *schemaContract) {
|
||||
mutateTool(contract, func(tool *toolSchema) {
|
||||
tool.InterfaceMode = "composite"
|
||||
tool.InterfaceRef = ""
|
||||
})
|
||||
}},
|
||||
{"mode moved away from mcp while the ref is redirected", func(contract *schemaContract) {
|
||||
mutateTool(contract, func(tool *toolSchema) {
|
||||
tool.InterfaceMode = "local"
|
||||
tool.InterfaceRef = `{"product_id":"sheet","rpc_name":"set_cell_range"}`
|
||||
})
|
||||
}},
|
||||
{"a parameter became required", func(contract *schemaContract) {
|
||||
mutateTool(contract, func(tool *toolSchema) { tool.InterfaceRef = `{"product_id":"sheet","rpc_name":"set_cell_range"}` })
|
||||
mutateParameter(contract, func(parameter *parameterSchema) { parameter.Required = true })
|
||||
}},
|
||||
{"a parameter type moved", func(contract *schemaContract) {
|
||||
mutateTool(contract, func(tool *toolSchema) { tool.InterfaceRef = `{"product_id":"sheet","rpc_name":"set_cell_range"}` })
|
||||
mutateParameter(contract, func(parameter *parameterSchema) { parameter.Type = "integer" })
|
||||
}},
|
||||
{"a property was cleared without a reviewed exclusion", func(contract *schemaContract) {
|
||||
mutateTool(contract, func(tool *toolSchema) { tool.InterfaceRef = `{"product_id":"sheet","rpc_name":"set_cell_range"}` })
|
||||
mutateParameter(contract, func(parameter *parameterSchema) {
|
||||
parameter.Property = ""
|
||||
parameter.PropertySource = "flag_name_inference"
|
||||
})
|
||||
}},
|
||||
{"a confirmation gate moved", func(contract *schemaContract) {
|
||||
mutateTool(contract, func(tool *toolSchema) {
|
||||
tool.InterfaceRef = `{"product_id":"sheet","rpc_name":"set_cell_range"}`
|
||||
tool.Confirmation = "user_required"
|
||||
})
|
||||
}},
|
||||
{"a parameter was dropped", func(contract *schemaContract) {
|
||||
mutateTool(contract, func(tool *toolSchema) {
|
||||
tool.InterfaceRef = newRef
|
||||
delete(tool.Parameters, "title")
|
||||
})
|
||||
}},
|
||||
// The allowlist itself must be load-bearing: a redirect that is not an
|
||||
// exact reviewed tool + old→new pair stays incompatible even when the rest
|
||||
// of the contract is untouched. Schema shape cannot prove two RPCs share
|
||||
// permissions, error taxonomy, or side effects.
|
||||
{"redirect to a ref that is not the reviewed target", func(contract *schemaContract) {
|
||||
mutateTool(contract, func(tool *toolSchema) {
|
||||
tool.InterfaceRef = `{"product_id":"sheet","rpc_name":"some_other_rpc"}`
|
||||
})
|
||||
}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
drifted := cloneContract(baseline)
|
||||
tc.mutate(&drifted)
|
||||
failures := checkCompatibility(baseline, drifted)
|
||||
var sawRef bool
|
||||
for _, failure := range failures {
|
||||
if strings.Contains(failure, "changed interface_ref") {
|
||||
sawRef = true
|
||||
}
|
||||
}
|
||||
if !sawRef {
|
||||
t.Fatalf("expected the redirect to stay reported, got %v", failures)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// The allowlist must be load-bearing: the exact same old→new pair on a tool
|
||||
// with no reviewed entry stays incompatible. Asserted outside the table
|
||||
// because the registration has to survive until checkCompatibility runs.
|
||||
t.Run("redirect on a tool absent from the reviewed allowlist", func(t *testing.T) {
|
||||
saved := reviewedInterfaceRefRedirect[fixturePath]
|
||||
delete(reviewedInterfaceRefRedirect, fixturePath)
|
||||
defer func() { reviewedInterfaceRefRedirect[fixturePath] = saved }()
|
||||
|
||||
unlisted := cloneContract(baseline)
|
||||
mutateTool(&unlisted, func(tool *toolSchema) { tool.InterfaceRef = newRef })
|
||||
failures := checkCompatibility(baseline, unlisted)
|
||||
var sawRef bool
|
||||
for _, failure := range failures {
|
||||
if strings.Contains(failure, "changed interface_ref") {
|
||||
sawRef = true
|
||||
}
|
||||
}
|
||||
if !sawRef {
|
||||
t.Fatalf("an unlisted tool must not get the redirect carve-out, got %v", failures)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -142,12 +142,27 @@ omit_global:
|
||||
disposition: covered_by
|
||||
reason: "AI 表格字段规则已下沉到 dingtalk-aitable;G3/coverage 不强制全局同名"
|
||||
|
||||
# Byte-identical pairs (content surfaces that must stay in sync).
|
||||
# Reviewed file pairs. Most are byte-identical; layout-only link differences
|
||||
# must be declared as data-driven substitutions.
|
||||
paired_files:
|
||||
- mono: references/products/sheet.md
|
||||
multi: dingtalk-misc/references/sheet.md
|
||||
mode: link-normalized
|
||||
link_substitutions:
|
||||
- mono: "../url-patterns.md"
|
||||
multi: "../../dingtalk-shared/references/url-patterns.md"
|
||||
- mono: "../intent-guide.md"
|
||||
multi: "sheet-intent-guide.md"
|
||||
- mono: references/products/whiteboard/recipes.md
|
||||
multi: dingtalk-misc/references/whiteboard/recipes.md
|
||||
mode: identical
|
||||
|
||||
# Directory pairs whose relative file sets and contents must stay byte-identical.
|
||||
paired_trees:
|
||||
- mono: references/products/sheet
|
||||
multi: dingtalk-misc/references/sheet
|
||||
mode: identical
|
||||
|
||||
# Scripts under skills/multi/*/scripts not referenced by any .md in that skill tree.
|
||||
# yida/finance/aiapp are referenced via dingtalk-misc/references/unsupported-scripts.md
|
||||
orphan_scripts_allowlist:
|
||||
|
||||
@@ -46,6 +46,7 @@
|
||||
| "查看这条话题的所有回复" | 话题回复 | `chat +thread-replies` | `chat message list-topic-replies` | 已知 threadId/topicId 时自动投影回复人、正文和时间 |
|
||||
| "把这些消息里的附件下载下来" | 消息资源下载 | 查询 Shortcut 的 `--download-resources` | `resourceRefs.shortcut` 返回的下载命令 | 先用查询结果的 resourceRefs;单资源再执行返回的可运行参数 |
|
||||
| "消息发没发成功/查询消息发送状态" | 查询消息发送状态 | `chat message query-send-status` | — | 需要 send 返回的 openTaskId |
|
||||
| "编辑/撤回我刚发的消息" | 发后编辑/撤回 | `send` → `query-send-status` → `edit` / `recall` | 按消息内容反查 | 使用 send 返回的 openTaskId 直接获取两个后续 ID |
|
||||
| "撤回我发的消息/撤回消息" | 撤回个人消息 | `chat message recall` | `chat message recall-by-bot` | recall 撤回个人消息,recall-by-bot 撤回机器人消息 |
|
||||
| "未读消息会话/未读会话列表/我的未读会话" | 未读会话列表 | `chat message list-unread-conversations` | `chat message read-status` | list-unread-conversations 查哪些会话有未读;read-status 查具体消息的已读状态 |
|
||||
| "谁看了这条消息/消息已读未读/查读状态" | 查询消息已读状态 | `chat message read-status` | `chat message list-unread-conversations` | read-status 查具体消息的已读人员;list-unread-conversations 查未读会话列表 |
|
||||
@@ -312,6 +313,7 @@ dws chat +messages-send --as user --open-dingtalk-id <openDingTalkId> --msg-type
|
||||
|
||||
用 `chat message query-send-status` 的场景:
|
||||
- "消息发没发成功/查询消息发送状态" — 查询个人发送消息的状态,需要 send 返回的 openTaskId
|
||||
- 发送成功时返回 openMessageId 和 openConversationId,可直接用于 edit/recall
|
||||
|
||||
用 `chat +search-msg` 的场景(推荐首选):
|
||||
- "按发送者搜索消息/指定多个群搜索/@我的消息多维度搜" — 支持关键词、发送者、@我、@指定人、多个会话等维度组合搜索
|
||||
@@ -325,7 +327,7 @@ dws chat +messages-send --as user --open-dingtalk-id <openDingTalkId> --msg-type
|
||||
上述五个查询 Shortcut 与 `+messages-resource-download` 都沿用安全本地下载的 `read/not_required` 契约,不应添加 `--yes` 或触发交互确认。输出只允许工作目录内相对路径、默认不覆盖并原子落盘;需要覆盖时必须由用户显式传 `--overwrite`。
|
||||
|
||||
**不支持的场景**:
|
||||
- "撤回我刚发的消息"(但不知道消息 ID) — 需先通过消息拉取或搜索接口(如 `chat message list`、`chat message search-advanced` 等)获取 openMessageId,再调用 `chat message recall`
|
||||
- "撤回历史消息"(且已丢失发送返回的 openTaskId) — 通过消息拉取或搜索接口获取 openMessageId,再调用 `chat message recall`
|
||||
|
||||
判断关键:普通发送统一走 `+messages-send` 并显式选择 `--as`;个人撤回→ `recall`;机器人撤回→ `recall-by-bot`;查发送状态→ `query-send-status`;消息搜索类意图优先路由到 `+search-msg`,仅在不适用时降级到原子命令。
|
||||
|
||||
|
||||
@@ -653,6 +653,8 @@ dws chat message send --open-dingtalk-id <openDingTalkId> --msg-type file --file
|
||||
#### 查询消息发送状态 — 查询以当前用户身份发送的消息的发送状态
|
||||
|
||||
查询以当前用户身份发送的消息的发送状态。需要传入发送消息时返回的 openTaskId。
|
||||
|
||||
发送成功时返回 openMessageId 和 openConversationId,可直接用于后续编辑或撤回。
|
||||
```
|
||||
Usage:
|
||||
dws chat message query-send-status [flags]
|
||||
@@ -666,6 +668,23 @@ Flags:
|
||||
- openTaskId 由 `dws chat message send` 发送消息成功后返回
|
||||
- 用于确认消息是否已成功发送或获取发送失败的原因
|
||||
- 返回结果中含发送成功消息的 openMessageId,可用于后续 recall(撤回)、read-status(查已读)等命令
|
||||
- 返回结果同时含 openConversationId;与 openMessageId 组合后可直接用于 edit(编辑)或 recall(撤回)
|
||||
```
|
||||
|
||||
发送后编辑/撤回时,优先使用下列 ID 链,无需按消息内容反查:
|
||||
|
||||
```bash
|
||||
# 1. 发送后保留 openTaskId
|
||||
dws chat message send --group <openConversationId> --text "原始内容"
|
||||
# 2. 查询得到 openMessageId 和 openConversationId
|
||||
dws chat message query-send-status --open-task-id <openTaskId>
|
||||
# 3. 编辑消息
|
||||
dws chat message edit --conversation-id <openConversationId> --msg-id <openMessageId> --text "更新后的内容"
|
||||
|
||||
# 发送后撤回使用同一 ID 链
|
||||
dws chat message send --group <openConversationId> --text "待撤回的内容"
|
||||
dws chat message query-send-status --open-task-id <openTaskId>
|
||||
dws chat message recall --conversation-id <openConversationId> --msg-id <openMessageId>
|
||||
```
|
||||
|
||||
#### 撤回消息 — 撤回当前用户自己发出的消息
|
||||
@@ -676,15 +695,13 @@ Usage:
|
||||
dws chat message recall [flags]
|
||||
Example:
|
||||
dws chat message recall --conversation-id <openConversationId> --msg-id <openMessageId>
|
||||
# 查询会话 ID: dws chat search --query "群名"
|
||||
# 消息 ID 可通过 dws chat message list 获取
|
||||
Flags:
|
||||
--conversation-id string 会话 openConversationId (必填,支持单聊/群聊,别名: --group / --id / --chat)
|
||||
--msg-id string 消息 openMessageId (必填)
|
||||
|
||||
注意:
|
||||
- --conversation-id 的别名: --group, --id, --chat (均可替代 --conversation-id)
|
||||
- 消息 ID 可通过 `dws chat message list` 命令获取
|
||||
- 刚由 `chat message send` 发出的消息,使用 `query-send-status` 返回的 openConversationId 和 openMessageId;只有历史消息或已丢失 openTaskId 时才通过消息拉取/搜索获取 ID
|
||||
- 仅支持撤回当前用户以个人身份发出的消息,不能撤回他人发送的消息,也不能撤回机器人发出的消息
|
||||
- 与 `recall-by-bot` 的区别:本命令通过 IM 接口撤回用户自己发出的消息(需要 openConversationId + openMessageId),`recall-by-bot` 通过机器人接口撤回机器人发出的消息(需要 robot-code + processQueryKey)
|
||||
```
|
||||
@@ -2373,7 +2390,8 @@ Flags:
|
||||
| `chat bot find` | `botOpenDingTalkId` | 给机器人发单聊消息(send --open-dingtalk-id;字段名是 botOpenDingTalkId,非 openDingTalkId) |
|
||||
| `chat message send-by-bot` | `processQueryKey` | recall-by-bot 的 --keys |
|
||||
| `chat message send` | `openTaskId` | query-send-status 的 --open-task-id |
|
||||
| `chat message list` | `openMessageId` | recall 的 --msg-id |
|
||||
| `chat message query-send-status` | `openMessageId` + `openConversationId` | 刚发送消息的 edit / recall |
|
||||
| `chat message list` | `openMessageId` | 历史消息或已丢失 openTaskId 时的 recall |
|
||||
| `chat message search` | `nextCursor` | 下次 message search 的 --cursor |
|
||||
| `chat message search-advanced` | `nextCursor` | 下次 message search-advanced 的 --cursor |
|
||||
| `chat search-common` | `openConversationId` | message send/list 等的 --group |
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,9 +5,8 @@
|
||||
`batch-update` 把多次写入打包成单次请求,但每个子操作仍受编辑类任务硬性默认规则约束:
|
||||
|
||||
1. **目标 range 必须落在用户授权范围内**:除用户明示要修改的区域外,子操作禁止扩张到无关单元格 / 列 / 工作表。规划 range 时先确认每个子操作的边界。
|
||||
2. **批次完成后必须回读校验**:整个 `batch-update` 执行成功后,用 `range read` 或 `csv-get` 抽样回读受影响区域,至少校验 3-5 个代表性单元格(首 / 中 / 末),与本地预先计算的预期值对照。
|
||||
2. **批次完成后必须回读校验**:整个 `batch-update` 执行成功后,单元格值用 `range read` 或 `csv-get` 抽样回读受影响区域;合并用裸 `sheet info`,行列分组用 `sheet info --include groups` 回读校验。
|
||||
3. **预期条数前置断言**:涉及"批量填充 N 行"或"对 M 个区域分别写入"时,先把 N、M 硬编码进代码,回读后断言实际等于预期;不一致就再发一轮 `batch-update` 补齐,禁止交付半成品。
|
||||
4. **统一确认语义**:`range batch-clear` 和 `batch-update` 都可删除内容或结构;先用 `--dry-run` 预览,真实执行必须获得用户确认后追加 `--yes`。
|
||||
|
||||
## 使用场景
|
||||
|
||||
@@ -23,17 +22,28 @@
|
||||
- 原子事务:任一操作失败则整批回滚
|
||||
- 传 `--continue-on-error` 可切换为宽松模式(失败继续)
|
||||
|
||||
用户说"批量写入多个结构化 table/跨 sheet 写入 dataframe/table":
|
||||
- 不使用 `batch-update`;直接调用 `dws sheet table-put --node <NODE_ID> --sheets '{"sheets":[...]}'`
|
||||
- `table-put` 自身支持一次写入多个 sheet spec,写入后用 `table-get` 回读 dtype / format / 数据行数
|
||||
|
||||
用户说"批量创建行列分组/批量取消行列分组/同时调整尺寸并分组":
|
||||
- 连续行/列分组 → `group-dimension`
|
||||
- 取消连续行/列分组 → `ungroup-dimension`
|
||||
- 分组回读用 `sheet info --include groups`
|
||||
- `group-dimension` 在 batch 中只适合默认展开分组;需要创建后立即折叠时,用独立 `dws sheet group-dimension --group-state fold`
|
||||
|
||||
**何时推荐使用 `batch-update`**:
|
||||
- 需要对**多个**不同区域执行 `merge-cells` / `unmerge-cells` 时(如按分组合并多列相同内容)
|
||||
- 需要对**多个**不同区域执行 `update-dimension` 时(如统一调整多列列宽或多行行高,含 hidden + pixelSize)
|
||||
- 需要对**多个**连续行/列范围执行 `group-dimension` / `ungroup-dimension` 时(默认展开分组)
|
||||
- 需要先插入行列再写入数据时(`add-dimension` + `range update` / `csv-put`)
|
||||
- 需要批量创建或取消行列分组时(`group-dimension` / `ungroup-dimension`)
|
||||
- 需要对多个区域执行不同写入操作时(多次 `range update` + `range clear` 等组合)
|
||||
|
||||
当同一工具需要对多个区域重复调用时,**推荐**改用 `batch-update` 合并为单次请求——`batch-update` 是原子提交(要么全成功要么整批回滚);逐个调用非原子,中途失败会留下半成品。
|
||||
|
||||
**不可放进 `--operations` 的操作**(强行写入会被校验拒或行为未定义):
|
||||
- `range read` / `csv-get`(只读操作,不属于写入)
|
||||
- `range read` / `csv-get` / `table-get`(读取操作,不在 batch dispatch 表中;结构化 table 回读需在 batch 外单独调用)
|
||||
- `table-put`(当前 `batch-update` 不支持结构化 table 写入;请直接调用独立 `dws sheet table-put`)
|
||||
- `range sort` / `range move-to`(尚未支持,后续版本补充)
|
||||
- `write-image` / `media-upload` / `create-float-image` / `update-float-image`(需本地上传或依赖前置上传句柄)
|
||||
- `set-style` / `range batch-set-style`(自身已是批量入口,不可再嵌套)
|
||||
@@ -50,9 +60,9 @@
|
||||
Usage:
|
||||
dws sheet range batch-clear [flags]
|
||||
Example:
|
||||
dws sheet range batch-clear --node <NODE_ID> --ranges '["Sheet1!A1:B3","Sheet2!C1:D5"]' --yes
|
||||
dws sheet range batch-clear --node <NODE_ID> --ranges '["Sheet1!A1:Z1000"]' --type all --yes
|
||||
dws sheet range batch-clear --node <NODE_ID> --ranges '["Sheet1!A2:A100","Sheet1!C2:C100"]' --type format --yes
|
||||
dws sheet range batch-clear --node <NODE_ID> --ranges '["Sheet1!A1:B3","Sheet2!C1:D5"]'
|
||||
dws sheet range batch-clear --node <NODE_ID> --ranges '["Sheet1!A1:Z1000"]' --type all
|
||||
dws sheet range batch-clear --node <NODE_ID> --ranges '["Sheet1!A2:A100","Sheet1!C2:C100"]' --type format
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--ranges string 目标区域 JSON 数组,每项带 sheet 前缀 (必填)
|
||||
@@ -72,9 +82,10 @@ Example:
|
||||
{"toolName":"range clear","input":{"sheet-id":"Sheet1","range":"A1:B3","type":"content"}},
|
||||
{"toolName":"range update","input":{"sheet-id":"Sheet1","range":"A1","values":[[{"type":"text","text":"hello"}]]}},
|
||||
{"toolName":"merge-cells","input":{"sheet-id":"Sheet1","range":"A1:B1","merge-type":"mergeAll"}},
|
||||
{"toolName":"update-dimension","input":{"sheet-id":"Sheet1","dimension":"ROWS","start-index":"1","length":1,"pixel-size":40}}
|
||||
]' --yes
|
||||
dws sheet batch-update --node <NODE_ID> --continue-on-error --operations '[...]' --yes
|
||||
{"toolName":"update-dimension","input":{"sheet-id":"Sheet1","dimension":"ROWS","start-index":"1","length":1,"pixel-size":40}},
|
||||
{"toolName":"group-dimension","input":{"sheet-id":"Sheet1","range":"3:7","group-state":"expand"}}
|
||||
]'
|
||||
dws sheet batch-update --node <NODE_ID> --continue-on-error --operations '[...]'
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--operations string 操作数组 JSON (必填,每项 {toolName, input})
|
||||
@@ -91,7 +102,8 @@ Notes:
|
||||
- 当需要对多个区域执行相同清除时,优先使用 `range batch-clear`(更简洁)
|
||||
- `csv-put` 子操作与独立命令语义一致:CSV 字段值以 `=` 开头时按公式解析;前加单引号时写入以 `=` 开头的字面文本
|
||||
- 典型场景:先插入行列再写入数据、先清除再写入、批量合并+调整行高列宽
|
||||
- 真实执行必须获得用户确认后加 --yes;--dry-run 不需要 --yes
|
||||
- `group-dimension` 在 batch 中只适合默认展开分组;需要 `--group-state fold` 时请使用独立 `dws sheet group-dimension`
|
||||
- `table-put` 不支持放进 batch-update;结构化 table 请用独立 `dws sheet table-put`
|
||||
```
|
||||
|
||||
### 子操作定位规则
|
||||
@@ -107,6 +119,8 @@ Notes:
|
||||
]
|
||||
```
|
||||
|
||||
`table-put` / `table-get` 不支持放进 `batch-update`。结构化 table 写入请直接调用 `dws sheet table-put`,写入完成后在 batch 外单独调用 `table-get` 回读校验。
|
||||
|
||||
## 校验与预览
|
||||
|
||||
### Validate 阶段
|
||||
@@ -121,27 +135,10 @@ CLI 在发送请求前执行以下本地校验(不消耗网络请求):
|
||||
| 每项必须是 object | `operations[N] 不是 object` | `--operations '["string"]'` |
|
||||
| `toolName` 必须是支持的 CLI 命令名 | `unsupported toolName "xxx"` | 传 `"batch-update"`(禁止嵌套)或拼写错误 |
|
||||
| 禁止嵌套 `batch-update` | 同上(`batch-update` 不在 dispatch 表中,自动拦截) | `toolName: "batch-update"` |
|
||||
| 禁止 `table-put` / `table-get` | `unsupported toolName "table-put"` | 结构化 table 应使用独立 `table-put` |
|
||||
|
||||
> `input` 内的字段(如 `sheet-id`、`range`、`values` 等)由服务端校验,CLI 不提前拦截——传入空值或缺失必填字段时,请求会到达服务端再返回错误。
|
||||
|
||||
### DryRun 阶段
|
||||
|
||||
加 `--dry-run` 预览翻译后的完整 MCP 请求,不实际执行任何操作:
|
||||
|
||||
```bash
|
||||
dws sheet batch-update --node NODE_ID --dry-run --operations '[...]'
|
||||
```
|
||||
|
||||
DryRun 输出内容:
|
||||
- `Tool: batch_update`(最终调用的 MCP 工具名)
|
||||
- `Arguments:` 完整 JSON(含翻译后的 `operations` 数组,展示每个子操作的 MCP toolName + 参数名 + 参数值)
|
||||
- 若传了 `--continue-on-error`,输出 JSON 中会包含 `"continueOnError": true`
|
||||
|
||||
DryRun 适用场景:
|
||||
- 确认 CLI 命令名 → MCP toolName 的翻译是否正确
|
||||
- 确认参数名转换(如 `--range` → `rangeAddress`)是否符合预期
|
||||
- 检查 `csv-put` 的 `@filepath` 是否被正确解析为文件内容,并确认 `=...` / `'=...` 字段原样进入子操作
|
||||
|
||||
### --continue-on-error 行为
|
||||
|
||||
| 模式 | flag | 子操作失败时 | 返回格式 |
|
||||
@@ -149,7 +146,7 @@ DryRun 适用场景:
|
||||
| 严格事务(默认) | 不传 | 整批回滚到初始状态,后续子操作不执行 | 顶层 `error` 对象 |
|
||||
| 宽松模式 | `--continue-on-error` | 已执行的子操作不回滚,继续执行后续子操作 | `results` 数组 |
|
||||
|
||||
**严格事务失败的错误信息**由服务端(flex-table-app)生成,包含以下内容:
|
||||
**严格事务失败的错误信息**由服务端生成,包含以下内容:
|
||||
- 失败操作索引:`operations[N]`(0-based,即 `--operations` JSON 数组中的下标)
|
||||
- 回滚告知:"All previously executed operations have been rolled back."
|
||||
- 失败原因:原始错误码和错误消息
|
||||
@@ -177,13 +174,13 @@ Cause: The requested resource was not found by the identifier 'NonExistentSheet'
|
||||
| `merge-cells` | [sheet-style-format](./sheet-style-format.md) |
|
||||
| `unmerge-cells` | [sheet-style-format](./sheet-style-format.md) |
|
||||
| `update-dimension` | [sheet-dimension-operations](./sheet-dimension-operations.md) |
|
||||
| `group-dimension` | [sheet-dimension-operations](./sheet-dimension-operations.md) |
|
||||
| `ungroup-dimension` | [sheet-dimension-operations](./sheet-dimension-operations.md) |
|
||||
| `range fill` | [sheet-range-operations](./sheet-range-operations.md) |
|
||||
| `range copy-to` | [sheet-range-operations](./sheet-range-operations.md) |
|
||||
| `add-dimension` | [sheet-dimension-operations](./sheet-dimension-operations.md) |
|
||||
| `delete-dimension` | [sheet-dimension-operations](./sheet-dimension-operations.md) |
|
||||
| `move-dimension` | [sheet-dimension-operations](./sheet-dimension-operations.md) |
|
||||
| `group-dimension` | [sheet-dimension-operations](./sheet-dimension-operations.md) |
|
||||
| `ungroup-dimension` | [sheet-dimension-operations](./sheet-dimension-operations.md) |
|
||||
| `set-dropdown` | [sheet-dropdown](./sheet-dropdown.md) |
|
||||
| `delete-dropdown` | [sheet-dropdown](./sheet-dropdown.md) |
|
||||
| `csv-put` | [sheet-write-data](./sheet-write-data.md) |
|
||||
@@ -237,32 +234,44 @@ Cause: The requested resource was not found by the identifier 'NonExistentSheet'
|
||||
]
|
||||
```
|
||||
|
||||
### 批量创建行列分组
|
||||
### 批量创建/取消行列分组
|
||||
|
||||
分组属于工作表结构元数据,批次完成后用 `sheet info --include groups` 回读 `rowGroups` / `columnGroups`,不要用裸 `sheet info` 或 `range read` 校验。回读项中的 `level` 是 1-based,`collapsed` 表示当前折叠状态。
|
||||
|
||||
```jsonc
|
||||
[
|
||||
{"toolName":"group-dimension",
|
||||
"input":{"sheet-id":"...","range":"3:7","group-state":"expand"}},
|
||||
{"toolName":"group-dimension",
|
||||
"input":{"sheet-id":"...","range":"C:F"}},
|
||||
{"toolName":"ungroup-dimension",
|
||||
"input":{"sheet-id":"...","range":"10:12"}}
|
||||
"input":{"sheet-id":"...","range":"C:F","group-state":"expand"}}
|
||||
]
|
||||
```
|
||||
|
||||
```jsonc
|
||||
[
|
||||
{"toolName":"ungroup-dimension",
|
||||
"input":{"sheet-id":"...","range":"3:7"}},
|
||||
{"toolName":"ungroup-dimension",
|
||||
"input":{"sheet-id":"...","range":"C:F"}}
|
||||
]
|
||||
```
|
||||
|
||||
注意:batch 中不要用 `group-state:"fold"` 来创建折叠分组;需要折叠初始状态时,用独立 `dws sheet group-dimension --group-state fold`。
|
||||
|
||||
## 上下文传递
|
||||
|
||||
| 操作 | 从返回中提取 | 用于 |
|
||||
|------|-------------|------|
|
||||
| `list` | 工作表的 `sheetId` | batch-clear 的 --ranges sheet 前缀 / batch-update 子操作 input 的 sheet-id |
|
||||
| `batch-update` | 各子操作的执行结果 | 回读校验(range read / csv-get) |
|
||||
| `batch-update` | 各子操作的执行结果 | 回读校验(值用 range read / csv-get;合并用 sheet info;分组用 sheet info --include groups) |
|
||||
|
||||
## 注意事项
|
||||
|
||||
- ★ **`--sheet-id` 获取规范(强制)**:`sheetId` 未知时必须先通过 `dws sheet list --node <NODE_ID> --format json` 查询真实的 `sheetId` / 工作表名称后再调用,禁止凭空编造(如臆测为 `Sheet1`、`sheet1`、`0`、`default` 等)
|
||||
- ★ **需要对多个区域执行相同清除操作时,用 `range batch-clear`**:一次原子请求清除多个区域(可跨工作表),失败时整批回滚
|
||||
- ★ **需要组合多个不同写操作(清除+写入等)时,用 `batch-update`**:原子事务,任一操作失败则整批回滚,避免留下半成品
|
||||
- ★ **批次完成后必须回读校验**:用 `range read` 或 `csv-get` 抽样回读受影响区域,至少校验 3-5 个代表性单元格(首 / 中 / 末),与预期值对照
|
||||
- ★ **table 写入不进 batch-update**:当前 `batch-update` 不支持结构化 table 写入;结构化 table 请直接调用 `dws sheet table-put`
|
||||
- ★ **批次完成后必须回读校验**:值写入用 `range read` 或 `csv-get` 抽样回读受影响区域;结构变更用 `sheet info` 回读
|
||||
- ★ **`batch-update` 不支持嵌套**:`--operations` 中的 `toolName` 必须是原子操作,不可再嵌套 `batch-update`
|
||||
- `batch-update` 支持 `group-dimension` / `ungroup-dimension`;`input.range` 只接受整行或整列范围,如 `3:7`、`C:F`
|
||||
- 需要创建后立即折叠分组时,优先使用独立 `dws sheet group-dimension --group-state fold`
|
||||
- `batch-update` 支持 `group-dimension` / `ungroup-dimension`;分组结果用 `sheet info --include groups` 回读
|
||||
- `batch-update` 中 `group-dimension` 只适合默认展开分组;需要 `fold` 初始状态时使用独立 `group-dimension`
|
||||
|
||||
@@ -34,6 +34,7 @@
|
||||
| "百分比面积" | 百分比堆积面积图(areaPercentStacked) | 占比式面积 |
|
||||
| "散点图"、"相关性" | 散点图(scatter) | 两变量相关性 |
|
||||
| "雷达图"、"多维度" | 雷达图(radar) | 多维度对比 |
|
||||
| "柱+线"、"组合图"、"双轴" | 组合图(combo) | 多种图表叠加,支持副轴 |
|
||||
|
||||
**多图表需求**:当用户同时提到多种分析(如"统计占比 + 对比数量"),必须创建多个图表,每个对应一种类型,不要只做一个。
|
||||
|
||||
@@ -55,8 +56,6 @@ Flags:
|
||||
--chart-id string 浮动图表 ID (可选,不传则返回全部)
|
||||
```
|
||||
|
||||
- **判空看 `totalCount` / `message`,不要看数组长度**:无图表时 `floatCharts` 数组里仍会带 1 个全 null 的幽灵元素(`chart.category`/`chart.series` 全 null,无 id),但 `totalCount` 为 0、`message` 为「Successfully retrieved 0 float chart(s).」。判断有没有图表以 `totalCount` 为准,或过滤掉没有 `id` 的元素。
|
||||
|
||||
### 创建浮动图表
|
||||
```
|
||||
Usage:
|
||||
@@ -130,7 +129,7 @@ Flags:
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `row` | number | 是 | 锚点行索引(0-based),如 0 表示第一行 |
|
||||
| `col` | string | 是 | 锚点列。使用字母表示法(`"A"`=第1列, `"B"`=第2列, `"Z"`=第26列, `"AA"`=第27列),不支持数字形式 |
|
||||
| `col` | string/number | 是 | 锚点列。支持字母表示法(`"A"`=第1列, `"B"`=第2列, `"Z"`=第26列, `"AA"`=第27列)或 0-based 数字(`0`=第1列) |
|
||||
|
||||
**offset 字段**(可选,不传时默认 0):
|
||||
|
||||
@@ -150,9 +149,10 @@ Flags:
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `type` | string | 是 | 图表类型,枚举值:`column` / `bar` / `columnStacked` / `barStacked` / `line` / `lineStacked` / `area` / `areaStacked` / `areaPercentStacked` / `pie` / `doughnut` / `scatter` / `radar` |
|
||||
| `series` | object[] | 是 | 数据系列数组,至少一项,详见下方 series 字段表 |
|
||||
| `category` | string[] | 否 | 分类轴(X轴)数据区域,A1 表示法字符串数组(如 `["A2:A10"]`) |
|
||||
| `type` | string | 是 | 图表类型,枚举值:`column` / `bar` / `columnStacked` / `barStacked` / `line` / `lineStacked` / `area` / `areaStacked` / `areaPercentStacked` / `pie` / `doughnut` / `scatter` / `radar` / `combo` |
|
||||
| `series` | object[] | 非 combo 必填 | 数据系列数组,至少一项,详见下方 series 字段表。combo 类型不使用此字段 |
|
||||
| `subCharts` | object[] | combo 必填 | 组合图子图数组,至少一项,详见下方 subCharts 字段表。仅 combo 类型使用 |
|
||||
| `category` | string[] | 否 | 分类轴(X轴)数据区域,A1 表示法字符串数组(如 `["A2:A10"]`)。combo 类型在 subCharts 内声明 |
|
||||
| `title` | object | 否 | 图表标题配置,详见下方 title 字段表 |
|
||||
| `legend` | object | 否 | 图例配置,详见下方 legend 字段表 |
|
||||
| `catAx` | object | 否 | 分类轴(X轴)样式配置,详见下方轴配置表 |
|
||||
@@ -165,6 +165,15 @@ Flags:
|
||||
| `name` | string | 否 | 系列名称的单元格引用,A1 表示法(如 `"B1"`)。不传时图例显示为"系列1"等默认名 |
|
||||
| `value` | string[] | 是 | 系列数据区域,A1 表示法字符串数组(如 `["B2:B10"]`)。每个元素为一段连续区域 |
|
||||
|
||||
**subCharts 数组项**(仅 combo 类型):
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `type` | string | 是 | 子图类型,仅允许笛卡尔坐标系类型:`column` / `bar` / `columnStacked` / `barStacked` / `line` / `lineStacked` / `area` / `areaStacked` / `areaPercentStacked`。不允许 pie/doughnut/scatter/radar/combo |
|
||||
| `series` | object[] | 是 | 子图数据系列,格式同上方 series 数组项 |
|
||||
| `category` | string[] | 是 | 子图分类轴数据区域(笛卡尔坐标系必须提供) |
|
||||
| `useSecondaryAxis` | boolean | 否 | 是否使用副轴(右侧 Y 轴),默认 false |
|
||||
|
||||
**title 字段**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
@@ -199,7 +208,7 @@ Flags:
|
||||
- 格式:`"A2:B10"`(默认使用 `--sheet-id` 对应的工作表)
|
||||
- 跨 sheet 引用:`"SHEET_ID!A2:B10"`(前缀为工作表 ID)
|
||||
- 单元格引用:`"B1"`(等同于 `"B1:B1"`)
|
||||
- MCP 内部自动将 A1 引用转换为 ISheetRange 结构,CLI 直接透传即可
|
||||
- 直接传 A1 表示法字符串即可,命令会处理成图表所需的区域引用
|
||||
|
||||
## 图表位置选择(创建前必做)
|
||||
|
||||
@@ -277,32 +286,19 @@ dws sheet chart create --node <NODE_ID> --sheet-id <SHEET_ID> --properties '{
|
||||
}
|
||||
}'
|
||||
|
||||
# ── 工作流 4: 多图表组合分析 ──
|
||||
# 当用户需要"柱+线"等多种图表组合分析时,分别创建对应类型的图表:
|
||||
# ── 工作流 4: 创建组合图(combo)──
|
||||
# 当用户需要"柱+线"叠加、双轴对比时,使用 combo 类型:
|
||||
|
||||
# 创建柱形图
|
||||
dws sheet chart create --node <NODE_ID> --sheet-id <SHEET_ID> --properties '{
|
||||
"position": {"row": 40, "col": "A"},
|
||||
"dimensions": {"width": 700, "height": 450},
|
||||
"dimensions": {"width": 800, "height": 500},
|
||||
"chart": {
|
||||
"type": "column",
|
||||
"series": [{"name": "B1", "value": ["B2:B10"]}],
|
||||
"category": ["A2:A10"],
|
||||
"title": {"show": true, "text": "销售额"},
|
||||
"legend": {"show": true, "pos": "t"}
|
||||
}
|
||||
}'
|
||||
|
||||
# 创建折线图
|
||||
dws sheet chart create --node <NODE_ID> --sheet-id <SHEET_ID> --properties '{
|
||||
"position": {"row": 40, "col": "J"},
|
||||
"dimensions": {"width": 700, "height": 450},
|
||||
"chart": {
|
||||
"type": "line",
|
||||
"series": [{"name": "C1", "value": ["C2:C10"]}],
|
||||
"category": ["A2:A10"],
|
||||
"title": {"show": true, "text": "增长率"},
|
||||
"legend": {"show": true, "pos": "t"}
|
||||
"type": "combo",
|
||||
"subCharts": [
|
||||
{"type": "column", "series": [{"name": "B1", "value": ["B2:B10"]}], "category": ["A2:A10"]},
|
||||
{"type": "line", "series": [{"name": "C1", "value": ["C2:C10"]}], "category": ["A2:A10"], "useSecondaryAxis": true}
|
||||
],
|
||||
"title": {"show": true, "text": "销售额与增长率"}
|
||||
}
|
||||
}'
|
||||
```
|
||||
@@ -344,10 +340,10 @@ dws sheet chart update --node <NODE_ID> --sheet-id <SHEET_ID> --chart-id <CHART_
|
||||
|
||||
- [强制] **`--sheet-id` 获取规范**:`sheetId` 未知时必须先通过 `dws sheet list --node <NODE_ID> --format json` 查询,禁止凭空编造(如臆测为 `Sheet1`、`sheet1`、`0`、`default` 等)
|
||||
- [强制] **创建后必须验证**:图表创建后必须调用 `chart list` 验证配置是否正确
|
||||
- ⚠️ **`chart list` 判空看 `totalCount` 不看数组长度**:无图表时 `floatCharts` 仍含 1 个全 null 幽灵元素(无 id),`totalCount` 为 0、`message` 说明为空。判断有没有图表以 `totalCount` 为准或过滤无 `id` 的元素
|
||||
- [强制] **chart-id 禁止臆测**:必须通过 `chart list` 获取真实的图表 ID,不可编造
|
||||
- **图表类型映射**:用户说"柱形图"用 `column`,"条形图"(横向)用 `bar`,"散点图"用 `scatter`,"雷达图"用 `radar`,"环形图"用 `doughnut`
|
||||
- **图表类型映射**:用户说"柱形图"用 `column`,"条形图"(横向)用 `bar`,"散点图"用 `scatter`,"雷达图"用 `radar`,"环形图"用 `doughnut`,"柱+线/组合/双轴"用 `combo`
|
||||
- **堆积类型后缀**:堆叠版本的图表在基本类型后加 `Stacked`(如 `columnStacked`、`lineStacked`、`areaStacked`)
|
||||
- **combo 组合图**:不用顶层 `series`/`category`,改用 `chart.subCharts` 数组,每个子图独立声明 `type`/`series`/`category`,可选 `useSecondaryAxis: true` 指定副轴。子图 type 仅允许笛卡尔坐标系类型(column/bar/line/area 及其 Stacked 变体),不允许 pie/doughnut/scatter/radar/combo
|
||||
- **位置不得压在数据区上**:图表浮层会遮挡原始数据,必须放在空白区域
|
||||
- **多图表需求**:多次调用 `chart create`,不要试图用一个图表包含所有分析
|
||||
- **跨 sheet 引用数据**:在 A1 区域前加 `SHEET_ID!` 前缀,如 `"sheetXXX!A2:B10"`
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
# sheet comment(表格单元格评论:list / create / reply / update / delete)
|
||||
|
||||
> **前置条件(MUST READ):** 执行本命令前,必须先用 Read 工具读取以下文件:
|
||||
> 1. [`../sheet.md`](../sheet.md) — 命令路由 + 场景索引 + 意图判断 + 全局约束
|
||||
>
|
||||
> **同任务常配合**:`dws aisearch person`(查 `--mention` 用 userId)/ [`sheet-workbook.md`](sheet-workbook.md)(未知工作表名称时先 `list` 确认真实名称)
|
||||
|
||||
---
|
||||
|
||||
## 适用范围
|
||||
|
||||
- 仅支持钉钉在线电子表格(`extension=axls`)。`xlsx` / `xls` / `csv` 等本地表格不支持评论。
|
||||
- 评论锚定在**单元格位置**:`create` / `list` 通过 `--sheet-id`(工作表 ID 或名称)+ `--range`(单元格坐标)定位;`reply` / `update` / `delete` 通过 `--comment-key` 操作,不依赖单元格位置。
|
||||
- `create` / `list` 通过单元格位置定位;`reply` / `update` / `delete` 通过前一步返回的 `commentKey` 定位评论线程,不需要重新传单元格位置。
|
||||
- 评论正文与单元格位置由服务端关联。Agent 只使用命令返回的 `commentKey` 继续回复、更新或删除,不解析或拼接内部关联字段。
|
||||
|
||||
---
|
||||
|
||||
## sheet comment list(查询表格评论列表)
|
||||
|
||||
```
|
||||
Usage:
|
||||
dws sheet comment list [flags]
|
||||
Example:
|
||||
dws sheet comment list --node <SHEET_ID>
|
||||
dws sheet comment list --node <SHEET_ID> --sheet-id Sheet1 --range A2
|
||||
dws sheet comment list --node <SHEET_ID> --resolve-status unresolved
|
||||
dws sheet comment list --node <SHEET_ID> --cursor <TOKEN>
|
||||
Flags:
|
||||
--node string 目标表格的标识,支持传入 URL 或 ID (必填)
|
||||
--limit int 每页返回的评论数量,默认 50,最大 50
|
||||
--cursor string 分页游标,从上一次请求的返回结果中获取 (首次请求不传)
|
||||
--resolve-status string 按解决状态过滤: resolved (已解决) / unresolved (未解决)
|
||||
--sheet-id string 工作表 ID 或名称,如 Sheet1(与 --range 一起指定时按单元格过滤)
|
||||
--range string 单元格位置,A1 表示法,如 A2、B5:C10(与 --sheet-id 一起指定时按单元格过滤)
|
||||
```
|
||||
|
||||
- 同时传入 `--sheet-id` 和 `--range` 时,仅返回该单元格的评论(服务端按单元格精确过滤);不传则返回表格全部单元格评论。
|
||||
|
||||
---
|
||||
|
||||
## sheet comment create(创建单元格评论)
|
||||
|
||||
```
|
||||
Usage:
|
||||
dws sheet comment create [flags]
|
||||
Example:
|
||||
dws sheet comment create --node <SHEET_ID> --sheet-id Sheet1 --range A2 --content "这个数字有问题"
|
||||
dws sheet comment create --node <SHEET_ID> --sheet-id Sheet1 --range A2 --content "请核实" --mention uid1,uid2
|
||||
Flags:
|
||||
--node string 目标表格的标识,支持传入 URL 或 ID (必填)
|
||||
--sheet-id string 工作表 ID 或名称,如 Sheet1 (必填)
|
||||
--range string 单元格位置,A1 表示法,仅支持单个单元格,如 A2 (必填)
|
||||
--content string 评论的文字内容,纯文本 (必填)
|
||||
--mention string 被 @ 的用户 uid 列表,逗号分隔
|
||||
```
|
||||
|
||||
- 未知工作表名称时,先 `dws sheet list --node <SHEET_ID> --format json` 确认真实名称,禁止臆测 `Sheet1` / `0` / `default`。
|
||||
|
||||
---
|
||||
|
||||
## sheet comment reply(回复评论)
|
||||
|
||||
```
|
||||
Usage:
|
||||
dws sheet comment reply [flags]
|
||||
Example:
|
||||
dws sheet comment reply --node <SHEET_ID> --comment-key <COMMENT_KEY> --content "已核实"
|
||||
dws sheet comment reply --node <SHEET_ID> --comment-key <COMMENT_KEY> --content "比心" --emoji
|
||||
dws sheet comment reply --node <SHEET_ID> --comment-key <COMMENT_KEY> --content "请确认" --mention uid1,uid2
|
||||
Flags:
|
||||
--node string 目标表格的标识,支持传入 URL 或 ID (必填)
|
||||
--content string 回复的文字内容,表情回复时填写表情名称 (必填)
|
||||
--comment-key string 被回复评论的 commentKey,格式: {13位毫秒时间戳}{32位UUID},可从 list/create 结果获取 (必填)
|
||||
--emoji 设为 true 时作为表情贴图回复 (默认 false)
|
||||
--mention string 被 @ 的用户 uid 列表,逗号分隔
|
||||
```
|
||||
|
||||
- 回复自动归属到被回复评论所在的单元格线程,无需再传 `--sheet-id` / `--range`。
|
||||
|
||||
---
|
||||
|
||||
## sheet comment update(更新评论)
|
||||
|
||||
```
|
||||
Usage:
|
||||
dws sheet comment update [flags]
|
||||
Example:
|
||||
dws sheet comment update --node <SHEET_ID> --comment-key <COMMENT_KEY> --content "已按最新数据修正"
|
||||
Flags:
|
||||
--node string 目标表格的标识,支持传入 URL 或 ID (必填)
|
||||
--comment-key string 待更新评论的 commentKey,格式: {13位毫秒时间戳}{32位UUID},可从 list/create 结果获取 (必填)
|
||||
--content string 更新后的评论文字内容,纯文本 (必填)
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## sheet comment delete(删除评论)
|
||||
|
||||
> [强制] 危险操作:删除不可恢复。必须先向用户展示操作摘要并获得明确同意,用户同意后才加 `--yes` 执行。
|
||||
|
||||
```
|
||||
Usage:
|
||||
dws sheet comment delete [flags]
|
||||
Example:
|
||||
dws sheet comment delete --node <SHEET_ID> --comment-key <COMMENT_KEY> --yes
|
||||
Flags:
|
||||
--node string 目标表格的标识,支持传入 URL 或 ID (必填)
|
||||
--comment-key string 待删除评论的 commentKey,格式: {13位毫秒时间戳}{32位UUID},可从 list/create 结果获取 (必填)
|
||||
```
|
||||
|
||||
## 关键说明
|
||||
|
||||
- `--mention` 接受 `userId` 列表(逗号分隔),需要先用 `dws aisearch person --keyword "<姓名>" --dimension name` 拿到 userId。
|
||||
- `--comment-key` 是 13 位毫秒时间戳 + 32 位 UUID 的拼接字符串,从 `list` / `create` 返回中提取,用于 `reply` / `update` / `delete`。
|
||||
- `create` / `list`(按单元格过滤)的 `--sheet-id` 是工作表 ID 或名称;未知时先 `dws sheet list` 确认,禁止臆测。
|
||||
- `reply` 加 `--emoji` 时 `--content` 填表情名称(如 `比心`、`赞`),不是文字内容。
|
||||
- `delete` 是不可逆操作;AI Agent 必须先向用户展示操作摘要并获得明确同意,同意后才追加 `--yes`。
|
||||
|
||||
## 上下文传递
|
||||
|
||||
| 从返回中提取 | 用于 |
|
||||
|-------------|------|
|
||||
| `commentList[].commentKey` | `comment reply/update/delete` 的 `--comment-key` |
|
||||
| `comment create` 的 `commentKey` | `comment reply/update/delete` 的 `--comment-key` |
|
||||
| [`sheet-workbook.md`](sheet-workbook.md) `sheet list` 的工作表名称 | `comment create/list` 的 `--sheet-id` |
|
||||
| `dws aisearch person` 的 `userId` | `comment create/reply` 的 `--mention` |
|
||||
|
||||
## 常用模板
|
||||
|
||||
```bash
|
||||
# 查看表格全部单元格评论
|
||||
dws sheet comment list --node <SHEET_ID> --format json
|
||||
|
||||
# 仅看某个单元格的评论
|
||||
dws sheet comment list --node <SHEET_ID> --sheet-id Sheet1 --range A2 --format json
|
||||
|
||||
# 仅看未解决的评论
|
||||
dws sheet comment list --node <SHEET_ID> --resolve-status unresolved --format json
|
||||
|
||||
# 在单元格上创建评论(未知工作表名先 sheet list 确认)
|
||||
dws sheet list --node <SHEET_ID> --format json
|
||||
dws sheet comment create --node <SHEET_ID> --sheet-id Sheet1 --range A2 --content "这个数字有问题" --format json
|
||||
|
||||
# 创建评论 + @人(先 aisearch person 拿 userId)
|
||||
dws aisearch person --keyword "张三" --dimension name --format json
|
||||
dws sheet comment create --node <SHEET_ID> --sheet-id Sheet1 --range A2 --content "请确认" --mention <uid1>,<uid2> --format json
|
||||
|
||||
# 文字回复
|
||||
dws sheet comment reply --node <SHEET_ID> --comment-key <COMMENT_KEY> --content "已核实" --format json
|
||||
|
||||
# 表情回复(--content 填表情名称)
|
||||
dws sheet comment reply --node <SHEET_ID> --comment-key <COMMENT_KEY> --content "比心" --emoji --format json
|
||||
|
||||
# 更新评论
|
||||
dws sheet comment update --node <SHEET_ID> --comment-key <COMMENT_KEY> --content "已按最新数据修正" --format json
|
||||
|
||||
# 删除评论(不可逆;必须用户确认后再加 --yes)
|
||||
dws sheet comment delete --node <SHEET_ID> --comment-key <COMMENT_KEY> --yes --format json
|
||||
```
|
||||
|
||||
## 参考
|
||||
|
||||
- [`../sheet.md`](../sheet.md)(如何路由到本命令族)
|
||||
- [`./sheet-workbook.md`](sheet-workbook.md)(取工作表名称)
|
||||
- `dws aisearch person`(取 mention 用的 userId,跨产品命令)
|
||||
@@ -64,14 +64,13 @@
|
||||
|
||||
**正确做法(两步走)**:
|
||||
```bash
|
||||
# Step 1: 用 range update 在新列写判断公式(形成"是/否"辅助列)
|
||||
# 每个单元格必须是 object,公式写在 text(以 = 开头);不支持裸字符串
|
||||
dws sheet range update --node NODE_ID --sheet-id SHEET_ID --range "H2:H100" \
|
||||
--values '[[{"type":"text","text":"=IF(A2>B2,\"是\",\"否\")"}],...]'
|
||||
# Step 1: 用 range update 在新列写判断公式(形成"是/否"辅助列,以 H2:H4 为例)
|
||||
dws sheet range update --node NODE_ID --sheet-id SHEET_ID --range "H2:H4" \
|
||||
--values '[[{"type":"text","text":"=IF(A2>B2,\"是\",\"否\")"}],[{"type":"text","text":"=IF(A3>B3,\"是\",\"否\")"}],[{"type":"text","text":"=IF(A4>B4,\"是\",\"否\")"}]]'
|
||||
|
||||
# Step 2: 基于辅助列值做条件格式(用 formulaCondition 引用辅助列)
|
||||
dws sheet cond-format create --node NODE_ID --sheet-id SHEET_ID \
|
||||
--ranges '["A2:H100"]' \
|
||||
--ranges '["A2:H4"]' \
|
||||
--condition '{"formulaCondition":{"formula":"=$H2=\"是\""}}' \
|
||||
--cell-style '{"backgroundColor":"#FFECEC"}'
|
||||
```
|
||||
@@ -143,8 +142,7 @@ Flags:
|
||||
|
||||
- **用途**:查看指定工作表中已有的条件格式规则,或获取单个规则的详情。
|
||||
- **场景**:创建/更新/删除条件格式前后验证规则状态;获取 ruleId 供后续 update/delete 使用。
|
||||
- **返回**:`rules` 数组,每条规则包含 id、type、ranges、条件参数、cellStyle/dataBarStyle 等。
|
||||
- **判空要看 `message`,不要看数组长度**:无规则时 `rules` 数组里仍会带 1 个全 null 的幽灵元素(`colorScaleCondition`/`dataBarStyle`/`iconSetCondition` 全 null,无 id),`message` 会是「No conditional formatting rules found.」。该命令**没有 `totalCount` 字段**,判空以 message 为准,或过滤掉没有 `id` 的元素。
|
||||
- **返回**:rules 数组,每条规则包含 id、type、ranges、条件参数、cellStyle/dataBarStyle 等。
|
||||
|
||||
### 创建条件格式规则
|
||||
```
|
||||
@@ -271,4 +269,3 @@ Flags:
|
||||
- **辅助列+条件格式两步走**:用户明确要求"辅助列"时,必须按两步走(先建辅助列 → 再基于辅助列做条件格式),禁止直接用 `formulaCondition` 一步绕过
|
||||
- **大数据量优势**:当数据量 > 1000 行时,条件格式是首选——它由服务端自身渲染,不需要逐行调用 `range set-style`,性能远优于静态样式写入
|
||||
- **判断标准**:交付后 `cond-format list` 必须能返回该规则;否则视为违规
|
||||
- ⚠️ **`cond-format list` 判空看 `message` 不看数组长度**:无规则时 `rules` 仍含 1 个全 null 幽灵元素(无 id),`message` 为「No conditional formatting rules found.」。该命令无 `totalCount`,判空以 message 为准或过滤无 `id` 的元素
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
用户说"隐藏行/隐藏列/显示行/显示列/设置行高/设置列宽/调整行高/调整列宽/行列属性":
|
||||
- 隐藏/显示行或列 → `update-dimension --hidden` / `--hidden=false`
|
||||
- 设置行高/列宽 → `update-dimension --pixel-size`
|
||||
- 设置行高/列宽 → `update-dimension --pixel-size`;恢复默认尺寸 → `--size-type standard`;行高按内容自适应 → `--size-type auto`(列宽不提供 auto)
|
||||
- 同时修改尺寸与显隐 → `update-dimension --pixel-size --hidden`
|
||||
|
||||
用户说"移动行/移动列/调整行顺序/调整列顺序/行列拖拽/把第N行移到第M行":
|
||||
@@ -26,11 +26,12 @@
|
||||
- 注意与 `append`(追加数据行)区分:`add-dimension` 追加的是空行/空列,`append` 追加的是带数据的行
|
||||
- 请勿用 `range update` 写空数据来模拟追加,`add-dimension` 直接扩展表格维度
|
||||
|
||||
用户说"创建行分组/创建列分组/折叠几行/折叠几列/展开行列分组/取消行列分组":
|
||||
- 创建分组 → `group-dimension --range <整行或整列范围>`
|
||||
- 创建并折叠 → `group-dimension --group-state fold`
|
||||
- 取消分组 → `ungroup-dimension --range <整行或整列范围>`
|
||||
- `--range` 只能传整行或整列范围,如 `3:7`、`C:F`、`Sheet1!3:7`
|
||||
用户说"创建行分组/创建列分组/新建分组并折叠/新建分组并展开/取消分组":
|
||||
- 创建连续行/列分组 → `group-dimension`
|
||||
- 取消连续行/列分组 → `ungroup-dimension`
|
||||
- 分组创建后用 `sheet info --include groups` 回读 `rowGroups` / `columnGroups`
|
||||
- 仅创建分组时可用 `--group-state expand|fold` 指定初始展开/折叠;当前没有单独调整已有分组折叠状态的命令
|
||||
- 用户要求"折叠/展开已有分组"时,当前不支持直接修改已有分组的 `collapsed` 状态,不能承诺可用 `group-dimension` 完成
|
||||
|
||||
**结构预检**:插入、删除、移动行列前,必须先执行 `dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID> --format json` 查看 `mergedRanges`。合并区域跨过操作位置时,行列变更可能导致表头/分组标题断裂、空白或错位;需要先向用户说明影响,必要时取消合并后操作,再按原模式重新 `merge-cells`。
|
||||
|
||||
@@ -116,6 +117,12 @@ Example:
|
||||
|
||||
# 使用工作表前缀(忽略 --sheet-id)
|
||||
dws sheet update-dimension --node <NODE_ID> --sheet-id <SHEET_ID> --dimension ROWS --start-index "Sheet1!3" --length 2 --hidden
|
||||
|
||||
# 恢复第 2~3 行为默认行高(无需 --pixel-size)
|
||||
dws sheet update-dimension --node <NODE_ID> --sheet-id <SHEET_ID> --dimension ROWS --start-index "2" --length 2 --size-type standard
|
||||
|
||||
# 第 2~3 行按内容自适应行高
|
||||
dws sheet update-dimension --node <NODE_ID> --sheet-id <SHEET_ID> --dimension ROWS --start-index "2" --length 2 --size-type auto
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
@@ -124,14 +131,25 @@ Flags:
|
||||
--length string 更新数量,正整数 (必填),最大 5000
|
||||
--hidden 是否隐藏 (true=隐藏, false=显示),与 --pixel-size 至少填其一
|
||||
--pixel-size int 行高或列宽(像素),ROWS 时为行高,COLUMNS 时为列宽,与 --hidden 至少填其一
|
||||
--size-type string 尺寸模式: pixel(默认,用 --pixel-size) / standard(恢复默认行高列宽) / auto(按内容自适应行高,仅 ROWS;列宽无此选项)
|
||||
```
|
||||
|
||||
批量更新钉钉表格指定工作表中连续多行/多列的属性,支持设置显隐状态(hidden)与行高/列宽(pixelSize)。
|
||||
`--dimension ROWS` 时,`--start-index` 为 1-based 行号字符串;`--dimension COLUMNS` 时,`--start-index` 为列字母。
|
||||
支持在 `--start-index` 中携带工作表前缀(如 `Sheet1!3`),此时忽略 `--sheet-id`。
|
||||
`--hidden` 与 `--pixel-size` 至少必须提供一个。当同时提供时,将先应用尺寸再应用显隐,任一失败整体失败。
|
||||
`--hidden` 与 `--pixel-size` 至少必须提供一个(或用 `--size-type standard/auto` 让服务端决定尺寸)。当同时提供时,将先应用尺寸再应用显隐,任一失败整体失败。
|
||||
`--pixel-size` 单位为像素,`dimension=ROWS` 时表示行高、`dimension=COLUMNS` 时表示列宽。
|
||||
|
||||
`--size-type` 尺寸模式(对齐飞书 row_sizes/col_sizes 的 type):
|
||||
|
||||
| 值 | 行为 | ROWS | COLUMNS | 是否需要 --pixel-size |
|
||||
|----|------|------|---------|----------------------|
|
||||
| `pixel`(默认) | 使用 `--pixel-size` 指定的像素值 | 支持 | 支持 | 需要 |
|
||||
| `standard` | 恢复为工作表默认行高/列宽 | 支持 | 支持 | 不需要 |
|
||||
| `auto` | 按内容自适应行高 | 支持 | 不提供 | 不需要 |
|
||||
|
||||
列宽不提供 `auto`(与飞书 `col_sizes` 的 type 枚举一致,只有 `pixel` / `standard`)。需要控制列宽时用 `--pixel-size` 指定,或用 `--size-type standard` 恢复默认列宽。
|
||||
|
||||
### 移动行或列
|
||||
```
|
||||
Usage:
|
||||
@@ -183,32 +201,51 @@ Flags:
|
||||
Usage:
|
||||
dws sheet group-dimension [flags]
|
||||
Example:
|
||||
# 创建第 3~7 行分组,默认展开
|
||||
dws sheet group-dimension --node <NODE_ID> --sheet-id <SHEET_ID> --range "3:7"
|
||||
|
||||
# 创建 C~F 列分组,并在创建后折叠
|
||||
dws sheet group-dimension --node <NODE_ID> --sheet-id <SHEET_ID> --range "C:F" --group-state fold
|
||||
|
||||
# 使用工作表前缀(忽略 --sheet-id)
|
||||
dws sheet group-dimension --node <NODE_ID> --sheet-id <SHEET_ID> --range "Sheet1!3:7"
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
--range string 整行/整列范围,如 "3:7" 或 "C:F" (必填)
|
||||
--group-state string 创建后的分组状态: expand 或 fold,默认 expand
|
||||
--range string 整行或整列范围,A1 表示法 (必填)。行如 "3:7",列如 "C:F"
|
||||
--group-state string 创建后的分组状态: expand 或 fold (默认 expand)
|
||||
```
|
||||
|
||||
为连续行或连续列创建分组。`--range` 必须是整行或整列范围,不支持 `A1:C5` 这类普通单元格矩形范围。
|
||||
创建连续整行或整列分组。`--range` 只能是整行范围或整列范围,不支持普通单元格矩形(如 `A1:C5`)。支持单行/单列(如 `"3:3"` / `"C:C"`)以及带工作表前缀(如 `Sheet1!3:7`),带前缀时忽略 `--sheet-id`。
|
||||
|
||||
返回中使用 `level` 表示分组展示层级,`level` 为 1-based;不要查找或依赖 `depth`。`--group-state fold` 只用于创建后的初始折叠状态,当前不提供"仅修改已有分组 collapsed 状态"的独立命令。
|
||||
|
||||
创建后用以下命令回读:
|
||||
```bash
|
||||
dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID> --include groups --format json
|
||||
```
|
||||
|
||||
回读字段为 `rowGroups` / `columnGroups`,单项包含 `range`、起止行列、`count`、`level`、`collapsed`。`collapsed=true` 表示当前分组折叠。
|
||||
|
||||
### 取消行或列分组
|
||||
```
|
||||
Usage:
|
||||
dws sheet ungroup-dimension [flags]
|
||||
Example:
|
||||
# 取消第 3~7 行分组
|
||||
dws sheet ungroup-dimension --node <NODE_ID> --sheet-id <SHEET_ID> --range "3:7"
|
||||
|
||||
# 取消 C~F 列分组
|
||||
dws sheet ungroup-dimension --node <NODE_ID> --sheet-id <SHEET_ID> --range "C:F"
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
--range string 整行/整列范围,如 "3:7" 或 "C:F" (必填)
|
||||
--range string 整行或整列范围,A1 表示法 (必填)。行如 "3:7",列如 "C:F"
|
||||
```
|
||||
|
||||
取消指定连续行或连续列的分组。
|
||||
取消指定连续整行或整列范围上的分组。取消后同样用 `sheet info --include groups` 回读确认目标 `range` 已从 `rowGroups` / `columnGroups` 中移除。
|
||||
|
||||
`group-dimension` / `ungroup-dimension` 可以放进 `batch-update` 做原子组合;但 batch 中的 `group-dimension` 只适合默认展开分组。需要创建后立即折叠时,请使用独立 `dws sheet group-dimension --group-state fold`。
|
||||
|
||||
## 核心工作流
|
||||
|
||||
@@ -282,15 +319,15 @@ dws sheet update-dimension --node <NODE_ID> --sheet-id <SHEET_ID> \
|
||||
| `update-dimension` | `a1Notation` 被更新区域范围、`hidden` 生效的显隐状态、`pixelSize` 生效的尺寸 | 确认更新结果 |
|
||||
| `move-dimension` | `sheetId` 工作表 ID | 确认操作完成 |
|
||||
| `add-dimension` | `sheetId` 工作表 ID | 确认操作完成 |
|
||||
| `group-dimension` | `range` / `level` / `groupState` | 确认行列分组层级和展开状态 |
|
||||
| `ungroup-dimension` | `range` / `level` | 确认行列分组已取消 |
|
||||
| `group-dimension` | `range` / `level` / `groupState` | 确认创建的分组范围、层级和初始状态 |
|
||||
| `ungroup-dimension` | `range` / `level` | 确认取消分组的范围和层级 |
|
||||
| `list` | 工作表的 `sheetId` | info / range read / range update / find 的 --sheet-id |
|
||||
|
||||
## 注意事项
|
||||
|
||||
- ★ **`--sheet-id` 获取规范(强制)**:`sheetId` 未知时必须先通过 `dws sheet list --node <NODE_ID> --format json` 查询,禁止凭空编造(如臆测为 `Sheet1`、`sheet1`、`0`、`default` 等)
|
||||
- `sheet info` 的 `mergedRanges` 是行列结构操作的重要预检信息。插入列时尤其要检查多行表头合并区,原有合并区域通常不会自动扩展到新列,必要时需重新设置合并区域
|
||||
- `insert-dimension` 在指定位置之前插入空行或空列,不写入数据;如需在末尾追加行/列,使用 `append`
|
||||
- `insert-dimension` 在指定位置之前插入空行或空列,不写入数据;如需在末尾追加行/列,使用 `append`;如需"先插入行列再写入数据"的组合操作,使用 [batch-update](./sheet-batch-operations.md) 打包为原子事务
|
||||
- `insert-dimension` 的 `--dimension` 只接受 `ROWS` 或 `COLUMNS`
|
||||
- `insert-dimension` 的 `--position` 支持工作表前缀(如 `Sheet1!3`),此时忽略 `--sheet-id`
|
||||
- `insert-dimension` 的 `--length` 最大为 5000
|
||||
@@ -313,7 +350,8 @@ dws sheet update-dimension --node <NODE_ID> --sheet-id <SHEET_ID> \
|
||||
- `add-dimension` vs `range update`:需要在末尾追加空行/空列时,必须使用 `add-dimension` 命令,禁止用 `range update` 写空数据来模拟追加效果
|
||||
- `add-dimension` 追加的是空行/空列,与 `append`(追加带数据的行)不同
|
||||
- `add-dimension` 的 `--length` 必须为正整数(>= 1),行列均不超过 5000
|
||||
- `group-dimension` / `ungroup-dimension` 的 `--range` 只接受整行或整列范围,如 `3:7`、`C:F`、`Sheet1!3:7`,不支持 `A1:C5`
|
||||
- `group-dimension` 的 `--group-state` 只接受 `expand` 或 `fold`,默认 `expand`
|
||||
- 分组操作返回 `level` 表示当前分组层级;不要把它误认为固定深度参数
|
||||
- `batch-update` 支持 `group-dimension` / `ungroup-dimension`;需要创建后立即折叠时,优先使用独立 `group-dimension --group-state fold`
|
||||
- `group-dimension` / `ungroup-dimension` 的 `--range` 只接受整行或整列范围,不接受普通单元格矩形
|
||||
- `group-dimension` 输出和 `sheet info --include groups` 回读均使用 `level`,且为 1-based;不要使用旧的 `depth` 字段
|
||||
- `sheet info --include groups` 是分组回读入口;裸 `sheet info` 不承诺返回行列分组,`range read` / `csv-get` 不返回行列分组
|
||||
- 当前不能直接调整已有分组的 `collapsed` 状态;`--group-state fold` 只在创建分组时生效
|
||||
- `batch-update` 支持 `group-dimension` / `ungroup-dimension`,但不适合创建后立即折叠;需要 `fold` 时使用独立 `group-dimension`
|
||||
|
||||
@@ -55,11 +55,10 @@ Flags:
|
||||
--range string 查询范围,A1 表示法,如 A1:A100 (必填)
|
||||
```
|
||||
|
||||
查询指定范围内的下拉列表配置信息,包括选项值和颜色。
|
||||
查询指定范围内的下拉列表配置信息,包括选项值、颜色和是否多选。
|
||||
- **用途**:查看单元格已设置的下拉列表选项和配置。
|
||||
- **场景**:在修改下拉列表前先查询现有配置;确认下拉列表是否设置成功。
|
||||
- **返回**:`dataValidations` 数组,相同选项的单元格聚合为一组,每组包含 `conditionValues`(选项值)、`ranges`(覆盖范围)、`options`(含 `multipleValues` 和 `colorValueMap`)。**判空以 `hasDropdown` 为准**:范围内无下拉列表时 `hasDropdown` 为 false,但 `dataValidations` 里仍会带 1 个全 null 的幽灵条目,不要用数组长度判空。
|
||||
- ⚠️ **已知限制**:`options.multipleValues` 服务端恒返回 `null`(即使该下拉是用 `--multi-select` 建的),也不返回 `enableMultiSelect` 字段——**`get-dropdown` 读回无法判断该下拉是否多选**。要判断是否多选,改用 `range read`:它返回的 `cells[].dataValidation.enableMultiSelect` 字段是准确的(实测有效)。
|
||||
- **返回**:`dataValidations` 数组,相同选项的单元格聚合为一组,每组包含 `conditionValues`(选项值)、`ranges`(覆盖范围)、`options`(含 `enableMultiSelect` 和 `colorValueMap`)。范围内无下拉列表时 `hasDropdown` 为 false。
|
||||
|
||||
### 删除下拉列表
|
||||
```
|
||||
@@ -91,6 +90,5 @@ Flags:
|
||||
|
||||
- ★ **`--sheet-id` 获取规范(强制)**:`sheetId` 未知时必须先通过 `dws sheet list --node <NODE_ID> --format json` 查询,禁止凭空编造(如臆测为 `Sheet1`、`sheet1`、`0`、`default` 等)
|
||||
- `set-dropdown` 在指定范围内设置下拉列表,`--options` 为 JSON 数组,每个元素包含 `value`(必填)和 `color`(可选,`#RRGGBB` 格式)。选项值不能包含英文逗号。`--multi-select` 启用多选模式。如果目标范围已存在下拉列表,会被新配置覆盖
|
||||
- `get-dropdown` 查询指定范围内的下拉列表配置,返回 `dataValidations` 数组,相同选项的单元格聚合为一组。判空以 `hasDropdown` 为准(无下拉时为 false,但 `dataValidations` 仍含 1 个全 null 幽灵条目)
|
||||
- ⚠️ `get-dropdown` 的 `options.multipleValues` 恒为 `null`、无 `enableMultiSelect` 字段,读回无法判断是否多选;要判断是否多选改用 `range read`(其 `dataValidation.enableMultiSelect` 准确)
|
||||
- `get-dropdown` 查询指定范围内的下拉列表配置,返回 `dataValidations` 数组,相同选项的单元格聚合为一组。无下拉列表时 `hasDropdown` 为 false
|
||||
- `delete-dropdown` 删除指定范围内的下拉列表配置,单元格恢复为普通文本格式。已填写的值不会被清除。目标范围不存在下拉列表时操作仍返回成功
|
||||
|
||||
@@ -11,6 +11,11 @@
|
||||
- 禁止用 `range read` 全量读取后自行拼接 xlsx 来模拟导出,必须使用 `export` 命令(服务端原子导出,保留格式/合并/公式等属性)
|
||||
- 禁止在 AI Agent 侧实现轮询或重试,CLI 内部已按渐进式退避策略完成(最多 30 次约 5 分钟)
|
||||
|
||||
用户说"导出 CSV/存成 csv/导出这个工作表为 csv":
|
||||
- 导出单个工作表为纯 CSV → `export-csv`(**同步**,不走异步任务;与 `export` 是两条独立命令)
|
||||
- 用 `--sheet-id` 指定工作表(不传取第一个)、`--range` 限定范围、`--value-render-option` 选取值模式
|
||||
- 不传 `--output` 时 CSV 正文打印到 stdout,可直接管道处理
|
||||
|
||||
## 命令详细参考
|
||||
|
||||
### 导出表格为 xlsx(异步任务一站式)
|
||||
@@ -47,17 +52,60 @@ Flags:
|
||||
- 第 21~30 次:每次间隔 15 秒
|
||||
- **硬上限:最多轮询 30 次(约 5 分钟)**,超时后命令返回错误
|
||||
|
||||
**命令返回**(`--format json`,默认):输出规整 JSON `{success, jobId, downloadUrl[, outputPath]}`。轮询进度以 `[INFO] [N/30] 状态: ...` 打到 stderr,不污染 stdout 的 JSON(可直接 `python3 -m json.tool` 解析 stdout)。
|
||||
- `--output` 未指定:JSON 含 `jobId` + `downloadUrl`(链接有时效性,请尽快下载)
|
||||
- `--output` 指定为文件路径:下载到该路径,JSON 额外含 `outputPath`
|
||||
- `--output` 指定为已存在目录:自动从 `downloadUrl` 推断文件名保存,JSON 含 `outputPath`
|
||||
**命令返回**:
|
||||
- `--output` 未指定:进度日志 + 末尾输出 `jobId` 和 `downloadUrl`(链接有时效性,请尽快下载)
|
||||
- `--output` 指定为文件路径:下载到该路径并输出 `导出完成: <path>`
|
||||
- `--output` 指定为已存在目录:自动从 `downloadUrl` 推断文件名并保存到该目录下
|
||||
|
||||
**失败处理(命令内部已处理,Agent 仅需转述)**:
|
||||
- MCP 返回 `FAILED`:命令立即返回错误并附带失败原因,**禁止自动重试 `dws sheet export`**,告知用户稍后再试
|
||||
- 导出任务返回 `FAILED`:命令立即返回错误并附带失败原因,**禁止自动重试 `dws sheet export`**,告知用户稍后再试
|
||||
- 轮询 30 次仍 `PROCESSING`:命令返回超时错误,告知用户稍后再试
|
||||
|
||||
**限制**:仅支持钉钉在线电子表格(axls)→ xlsx。导出钉钉文字文档请使用 `doc` 产品对应的导出工具。
|
||||
|
||||
### 导出单个工作表为纯 CSV(同步)
|
||||
```
|
||||
Usage:
|
||||
dws sheet export-csv [flags]
|
||||
Example:
|
||||
dws sheet export-csv --node <NODE_ID>
|
||||
dws sheet export-csv --node <NODE_ID> --sheet-id <SHEET_ID> --output ./data.csv
|
||||
dws sheet export-csv --node <NODE_ID> --range A1:Z1000 --value-render-option raw_value
|
||||
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称(不传则第一个工作表)
|
||||
--range string 导出范围,A1 表示法(不传则整表;大表可用此分块导出)
|
||||
--value-render-option string 取值模式: formatted_value(默认) / raw_value / formula
|
||||
--output string 本地保存路径(可选,支持文件路径或目录);不传则输出到 stdout
|
||||
--allow-truncated 允许数据被截断时仍然导出。默认截断即报错且不写文件
|
||||
```
|
||||
|
||||
同步读取**单个**工作表并输出 RFC4180 CSV,不走异步导出任务。与 `export` 是两条独立命令:`export` 导整篇工作簿的 xlsx(异步提交+轮询),`export-csv` 只导一个工作表的纯值(一次请求即返回)。不传 `--output` 时 CSV 正文打印到 stdout,可直接管道处理。
|
||||
|
||||
**`--output` 落盘是原子替换**:CSV 先写同目录临时文件、成功后再替换目标,写入失败时已有文件保持原样(父目录不存在仍按错误处理,不会自动创建)。`--output` 指向已存在目录时保存为该目录下的 `sheet-export.csv`。
|
||||
|
||||
**超大表默认 fail-closed**:数据超出单次读取上限(服务端返回 `hasMore`)时,命令**直接报错并以非 0 退出,既不打印 CSV 也不写文件**(已存在的目标文件不会被截断数据覆盖)。处理方式:
|
||||
- 用 `--range` 分块导出(如 `--range A1:Z1000`、`A1001:Z2000` …)
|
||||
- 改用 `dws sheet export` 导出完整表格的 xlsx
|
||||
- 确认可以接受不完整数据时,显式加 `--allow-truncated`;此时才会照常输出/落盘,并在 stderr 给出「已被截断」警告,成功提示也会写明"数据已截断,不是完整表格"
|
||||
|
||||
```bash
|
||||
# 落盘到本地
|
||||
dws sheet export-csv --node <NODE_ID> --sheet-id <SHEET_ID> --output ./data.csv
|
||||
|
||||
# 输出到 stdout 便于管道处理
|
||||
dws sheet export-csv --node <NODE_ID> --sheet-id <SHEET_ID>
|
||||
|
||||
# 大表分块导出(避免截断;不分块时默认会因截断而报错)
|
||||
dws sheet export-csv --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:Z1000" --output ./part1.csv
|
||||
|
||||
# 明确接受不完整数据(否则截断即失败)
|
||||
dws sheet export-csv --node <NODE_ID> --sheet-id <SHEET_ID> --allow-truncated --output ./partial.csv
|
||||
```
|
||||
|
||||
注意:CSV 只写纯值,不保留样式/合并/公式;需要完整属性请用 `dws sheet export` 导 xlsx。只是让 Agent 读取内容(带 `[row=N]` 行号前缀)请用 `dws sheet csv-get`。
|
||||
|
||||
## 核心工作流
|
||||
|
||||
```bash
|
||||
@@ -83,6 +131,8 @@ dws sheet export --node <NODE_ID> --output ./
|
||||
| 操作 | 从返回中提取 | 用于 |
|
||||
|------|-------------|------|
|
||||
| `export` | `downloadUrl`(未指定 --output)/ `outputPath`(指定 --output) | 直接下发给用户或告知文件已保存到本地。命令内部已完成轮询,不要再调用其他 export 相关命令 |
|
||||
| `export` 超时中断 | 错误信息 | 直接报告失败或超时;当前没有独立续查命令,不自动重新提交导出 |
|
||||
| `export-csv` | CSV 正文(未指定 --output,走 stdout)/ `导出完成: <path>`(指定 --output) | 直接把 CSV 交给下游处理,或告知文件已保存到本地。命令是同步的,无任务/轮询概念 |
|
||||
|
||||
## 注意事项
|
||||
|
||||
@@ -93,3 +143,5 @@ dws sheet export --node <NODE_ID> --output ./
|
||||
- `export` 未指定 `--output` 时,返回的 `downloadUrl` 具有时效性,获取后请尽快下载;若用户需要本地文件,优先直接传 `--output` 让 CLI 代为下载
|
||||
- `export` 的 `--output` 可为文件路径或已存在目录;为目录时自动从 `downloadUrl` 推断文件名,为文件路径时直接按该路径保存
|
||||
- 用户要求"导出表格/下载 xlsx"时,必须使用 `export` 单命令,禁止用 `range read` 读全量数据后自行拼 xlsx 模拟导出(服务端导出会保留格式/合并/公式等完整属性)
|
||||
- `export-csv` 与 `export` 是两条独立命令:`export-csv` 同步导出**单个**工作表的纯值 CSV,不保留样式/合并/公式;要整篇工作簿或完整属性一律用 `export`
|
||||
- ★ `export-csv` 遇到数据超出单次读取上限时默认报错、既不输出也不写文件;优先用 `--range` 分块导出,只有用户明确接受不完整数据时才加 `--allow-truncated`
|
||||
|
||||
@@ -219,7 +219,6 @@ Flags:
|
||||
- **用途**:查看某个筛选视图的当前配置,包括已设置的所有筛选条件详情。
|
||||
- **场景**:在修改或删除筛选视图前,先确认其当前状态;或在 `update-criteria` 后验证条件是否生效。
|
||||
- **区分**:`info` 返回单个视图的完整信息(含 criteria);`list` 返回所有视图的列表概要。`info` 需要指定 `--filter-view-id`,ID 可通过 `list` 获取。
|
||||
- **实现**:内部调用 `get_filter_views` 获取全部列表后按 ID 过滤。
|
||||
|
||||
### 列出筛选视图所有列条件
|
||||
```
|
||||
@@ -238,7 +237,6 @@ Flags:
|
||||
- **用途**:查看某个筛选视图当前设置了哪些列的筛选条件,包括每列的条件类型和具体规则。
|
||||
- **场景**:在管理筛选条件(修改/删除特定列条件)前,先了解当前视图有哪些条件;或排查筛选结果不符合预期时检查条件配置。
|
||||
- **区分**:`list-criteria` 返回所有列的条件(按列偏移量为 key 的对象);`get-criteria` 只返回指定列的条件。如果没有设置任何条件,返回空对象 `{}`。
|
||||
- **实现**:内部调用 `get_filter_views` 获取视图详情后提取 `criteria` 字段。
|
||||
|
||||
### 获取单列筛选条件
|
||||
```
|
||||
@@ -261,7 +259,6 @@ Flags:
|
||||
- **用途**:查看某个筛选视图中指定列当前设置的筛选条件,包括条件类型、运算符和比较值。
|
||||
- **场景**:在修改某列条件前,先查看其当前配置;或验证 `update-criteria` 后该列条件是否正确。
|
||||
- **区分**:`get-criteria` 只返回指定列的条件;`list-criteria` 返回所有列的条件。`--column` 为列偏移量(从 0 开始),相对于筛选视图范围首列。
|
||||
- **实现**:内部调用 `get_filter_views` 获取视图详情后按列偏移量过滤 `criteria` 中的对应条件。
|
||||
|
||||
## 核心工作流
|
||||
|
||||
@@ -328,7 +325,7 @@ dws sheet filter-view create --node <NODE_ID> --sheet-id <SHEET_ID> \
|
||||
- ★ **`--sheet-id` 获取规范(强制)**:`sheetId` 未知时必须先通过 `dws sheet list --node <NODE_ID> --format json` 查询,禁止凭空编造(如臆测为 `Sheet1`、`sheet1`、`0`、`default` 等)
|
||||
- ★ **全局筛选(filter)与筛选视图(filter-view)的区别**:全局筛选影响所有协作者看到的数据展示,每个工作表最多一个;筛选视图是个人化的,互不影响。用户只说"筛选"时默认走 `filter` 系列
|
||||
- `filter-view list` 获取指定工作表的所有筛选视图列表,返回的 `id` 可用于后续 info / update / delete / update-criteria / delete-criteria / list-criteria / get-criteria 的 `--filter-view-id`
|
||||
- `filter-view info` 获取单个筛选视图的完整信息(含 criteria),内部复用 `get_filter_views` MCP 按 ID 过滤
|
||||
- `filter-view info` 获取单个筛选视图的完整信息(含 criteria),按 `--filter-view-id` 返回对应视图
|
||||
- `filter-view list-criteria` 列出指定筛选视图已设置的所有列条件,返回按列偏移量为 key 的对象;无条件时返回空对象 `{}`
|
||||
- `filter-view get-criteria` 获取指定列的条件详情,`--column` 为列偏移量(从 0 开始);该列无条件时返回错误提示
|
||||
- `filter-view create` 创建筛选视图时 `--range` 应包含表头行。`--criteria` 可选,不传则创建后无筛选条件,后续可通过 `filter-view update-criteria` 设置
|
||||
|
||||
@@ -32,7 +32,7 @@ Flags:
|
||||
- **用途**:查看当前工作表上是否存在全局筛选及其配置。
|
||||
- **场景**:在修改或删除筛选前,先读取当前筛选配置;创建筛选前先确认是否已存在(每个工作表只能有一个筛选)。
|
||||
- **区分**:全局筛选(filter)影响所有协作者看到的数据展示;筛选视图(filter-view)是个人化的。
|
||||
- **返回**:`range`(筛选范围,A1 表示法)、`id`(筛选 ID)和 `criteria`(各列条件对象,key 为列偏移量;无条件时为 `{}`)。如果未设置筛选,返回筛选信息为空。
|
||||
- **返回**:`range`(筛选范围,A1 表示法)和 `columnFilterCriteria`(各列条件,key 为列偏移量)。如果未设置筛选,返回筛选信息为空。
|
||||
|
||||
### 创建筛选
|
||||
```
|
||||
@@ -152,7 +152,7 @@ Flags:
|
||||
|
||||
| 操作 | 从返回中提取 | 用于 |
|
||||
|------|-------------|------|
|
||||
| `filter get` | `range`(筛选范围)、`id`、`criteria`(各列条件对象,无条件为 `{}`) | 查看当前筛选配置,确认筛选是否存在 |
|
||||
| `filter get` | `range`(筛选范围)、`columnFilterCriteria`(各列条件) | 查看当前筛选配置,确认筛选是否存在 |
|
||||
| `filter create` | 筛选创建成功的确认 | 确认筛选已建立,后续可通过 `filter update` 设置条件 |
|
||||
| `filter delete` | 删除成功的确认 | 确认筛选已删除 |
|
||||
| `filter update` | 更新成功的确认 | 确认条件已设置 |
|
||||
@@ -164,7 +164,7 @@ Flags:
|
||||
|
||||
- ★ **`--sheet-id` 获取规范(强制)**:`sheetId` 未知时必须先通过 `dws sheet list --node <NODE_ID> --format json` 查询,禁止凭空编造(如臆测为 `Sheet1`、`sheet1`、`0`、`default` 等)
|
||||
- ★ **全局筛选(filter)与筛选视图(filter-view)的区别**:全局筛选影响所有协作者看到的数据展示,每个工作表最多一个;筛选视图是个人化的,互不影响。用户只说"筛选"时默认走 `filter` 系列
|
||||
- `filter get` 获取工作表的全局筛选信息,返回 `range`(筛选范围)、`id` 和 `criteria`(各列条件对象,无条件时为 `{}`)。无筛选时返回空
|
||||
- `filter get` 获取工作表的全局筛选信息,返回 `range`(筛选范围)和 `columnFilterCriteria`(各列条件)。无筛选时返回空
|
||||
- `filter create` 创建全局筛选时 `--range` 必须包含表头行(如 `A1:E100`),不能只包含数据行。每个工作表只能有一个筛选,已存在时报错
|
||||
- `filter create` 的 `--criteria` 可选,不传则仅创建空筛选框架,后续通过 `filter update` 设置条件
|
||||
- `filter delete` 删除后所有筛选条件丢失且所有被隐藏行重新显示,不可恢复
|
||||
|
||||
@@ -0,0 +1,192 @@
|
||||
# 公式写入、回读与错误校验
|
||||
|
||||
## 使用场景
|
||||
|
||||
用户说"写公式/计算列/辅助列/总计/占比/增长率/查找计算/自动计算/校验公式/检查公式错误"时使用本页。
|
||||
|
||||
- 能由表内其他单元格推导的派生值,优先写公式,不要写一次性的静态结果。
|
||||
- 写公式前先读表头和 3-5 行样本,确认列含义、数据类型、真实行号和目标范围。
|
||||
- 用户明确要求"辅助列"时,需要真实写入辅助列公式;不要只用条件格式或本地计算绕过。
|
||||
|
||||
## 当前能力边界
|
||||
|
||||
- 写少量或需要单元格对象的公式:使用 `dws sheet range update`。
|
||||
- 从 CSV/表格文本批量写公式:使用 `dws sheet csv-put`,字段值以 `=` 开头时默认按公式解析;如需写入以 `=` 开头的字面文本,在字段值前加单引号。
|
||||
- 公式载体:公式写在 cell object 的 `text` 字段中,例如 `{"type":"text","text":"=SUM(B2:B10)"}`。
|
||||
- 读取公式文本:使用 `dws sheet range read --value-render-option formula`。
|
||||
- 读取计算结果:使用 `dws sheet range read --value-render-option raw_value` 或默认 `formatted_value`。
|
||||
- 聚合错误校验:使用 `dws sheet formula-verify`,支持整本表格、单个目标和多个目标。
|
||||
- `formula-verify` 扫描已经落表的公式计算结果,按 `#ERROR!` / `#NAME?` / `#DIV/0!` 等错误类型汇总;它不判断一个正常数值是否符合业务预期。
|
||||
- `append` / `table-put` 不作为公式写入协议;需要公式时用 `range update` 或 `csv-put`。
|
||||
|
||||
## 命令选择
|
||||
|
||||
| 目的 | 命令 | 说明 |
|
||||
|------|------|------|
|
||||
| 写入少量或中等范围公式 | `range update` | `--values` 必须是二维 cell object,维度与 `--range` 完全一致 |
|
||||
| 从 CSV/表格文本批量写公式 | `csv-put` | `=` 开头按公式;前导单引号写入以 `=` 开头的字面文本;不支持富格式对象 |
|
||||
| 查看已写入的公式文本 | `range read --value-render-option formula` | 确认公式本身是否落表、范围和引用是否正确 |
|
||||
| 查看公式计算结果 | `range read --value-render-option raw_value` | 用于数值对账、错误值检查 |
|
||||
| 查看格式化展示结果 | `range read` 或 `csv-get` 默认模式 | 用于用户肉眼看到的展示值检查 |
|
||||
| 扫描整本表格公式错误 | `formula-verify --node <NODE_ID>` | 不传目标时扫描全部工作表的非空范围 |
|
||||
| 扫描单个工作表或范围 | `formula-verify --sheet-id ... [--range ...]` | `--range` 只传 A1 范围,不带工作表前缀 |
|
||||
| 扫描多个目标 | `formula-verify --targets ...` | 必须是非空数组;每项为 `{"sheetId":"...","range":"..."}`,`range` 可省略 |
|
||||
|
||||
## 推荐流程
|
||||
|
||||
1. 用 `dws sheet list --node <NODE_ID> --format json` 获取真实 `sheetId`。
|
||||
2. 用 `range read` 或 `csv-get` 读取表头和样本数据,确认目标列与行号。
|
||||
3. 明确相对引用和绝对引用:向下填充时检查固定汇率、税率、查找表、标题行是否需要 `$` 锁定。
|
||||
4. 按数据形态写入公式:精确 cell object 用 `range update`,CSV/表格文本用 `csv-put`。`range update` 的矩阵行列数必须与 `--range` 完全一致。
|
||||
5. 用 `range read --value-render-option formula` 回读公式文本,确认实际公式、范围和引用。
|
||||
6. 对本次写入目标运行 `formula-verify`;若返回 `partial` / `hasMore=true`,缩小目标或提高 `--max-cells` 后继续扫描,直到结果完整。
|
||||
7. 用 `range read --value-render-option raw_value` 抽样对账业务数值;正常数值不会被 `formula-verify` 判定为业务计算错误。
|
||||
8. 若发现错误,先定位依赖单元格、空值、除数为 0、引用范围越界或函数名错误,再重写公式并重新执行文本回读、错误扫描和数值抽样。
|
||||
|
||||
## 聚合式公式校验
|
||||
|
||||
### 整本表格
|
||||
|
||||
不指定 `--sheet-id`、`--range` 或 `--targets` 时,扫描整本表格的全部工作表:
|
||||
|
||||
```bash
|
||||
dws sheet formula-verify --node <NODE_ID> --format json
|
||||
```
|
||||
|
||||
### 单个工作表或范围
|
||||
|
||||
`--sheet-id` 支持工作表 ID 或名称;省略 `--range` 时扫描该工作表的非空范围:
|
||||
|
||||
```bash
|
||||
dws sheet formula-verify --node <NODE_ID> --sheet-id <SHEET_ID> --format json
|
||||
|
||||
dws sheet formula-verify --node <NODE_ID> --sheet-id <SHEET_ID> \
|
||||
--range "D2:D100" --format json
|
||||
```
|
||||
|
||||
`--range` 必须和 `--sheet-id` 一起使用,且只传 `D2:D100` 这类 A1 范围,不能传 `Sheet1!D2:D100`。
|
||||
|
||||
### 多个目标
|
||||
|
||||
```bash
|
||||
dws sheet formula-verify --node <NODE_ID> \
|
||||
--targets '[{"sheetId":"Sheet1","range":"D2:D100"},{"sheetId":"Summary"}]' \
|
||||
--format json
|
||||
```
|
||||
|
||||
`--targets` 也支持 `@targets.json` 和 `-`(stdin)。数组必须至少包含一个目标,不能传 `[]`;每项只允许非空 `sheetId` 和可选的字符串 `range`,`range` 只写 A1 范围且不能带工作表前缀。使用 `--targets` 时不能再传 `--sheet-id` 或 `--range`。
|
||||
|
||||
### 扫描限制与自动化
|
||||
|
||||
```bash
|
||||
dws sheet formula-verify --node <NODE_ID> \
|
||||
--max-locations-per-error 20 --max-cells 30000 --format json
|
||||
|
||||
dws sheet formula-verify --node <NODE_ID> --exit-on-error --format json
|
||||
```
|
||||
|
||||
- `--max-locations-per-error` 只限制每类错误返回的 `locations` 和 `samples` 数量,`count` 与 `totalErrors` 仍保留实际扫描到的总数。
|
||||
- `--max-cells` 是本次调用跨全部 targets 共享的扫描预算;预算不足时返回 `status=partial`、`hasMore=true`。
|
||||
- `--exit-on-error` 适合 CI/自动化:发现公式错误时打印 JSON 结果并返回非 0;`partial` 结果中已经发现错误时同样返回非 0。
|
||||
|
||||
### 结果判定
|
||||
|
||||
| 字段 | 含义 |
|
||||
|------|------|
|
||||
| `status` | `success` / `errors_found` / `partial` |
|
||||
| `totalErrors` | 实际扫描到的错误公式单元格总数 |
|
||||
| `totalFormulas` | 实际扫描到的公式单元格总数 |
|
||||
| `scannedCells` | 实际扫描的单元格数 |
|
||||
| `hasMore` | `true` 表示结果不完整,不能据此声称目标范围零错误 |
|
||||
| `errorSummary` | 按错误类型聚合的 `count`、`locations` 和 `samples` |
|
||||
| `warningMessage` | `partial` 等情况下的扫描限制提示 |
|
||||
|
||||
判定规则:
|
||||
|
||||
- `status=success`、`hasMore=false`、`totalErrors=0`:本次目标范围未发现公式错误。
|
||||
- `status=errors_found`:按 `errorSummary` 修复后重新校验。
|
||||
- `status=partial` 或 `hasMore=true`:当前结果不完整;缩小 targets/range 或提高 `--max-cells` 后继续校验。
|
||||
|
||||
## 写入示例
|
||||
|
||||
### 单格公式
|
||||
|
||||
```bash
|
||||
dws sheet range update --node <NODE_ID> --sheet-id <SHEET_ID> --range "D2" \
|
||||
--values '[[{"type":"text","text":"=B2*C2"}]]' --format json
|
||||
```
|
||||
|
||||
### 整列公式
|
||||
|
||||
```bash
|
||||
dws sheet range update --node <NODE_ID> --sheet-id <SHEET_ID> --range "D2:D5" \
|
||||
--values '[
|
||||
[{"type":"text","text":"=B2*C2"}],
|
||||
[{"type":"text","text":"=B3*C3"}],
|
||||
[{"type":"text","text":"=B4*C4"}],
|
||||
[{"type":"text","text":"=B5*C5"}]
|
||||
]' --format json
|
||||
```
|
||||
|
||||
### 含绝对引用
|
||||
|
||||
税率在 `G1` 时,向下填充应锁定税率单元格:
|
||||
|
||||
```bash
|
||||
dws sheet range update --node <NODE_ID> --sheet-id <SHEET_ID> --range "E2:E5" \
|
||||
--values '[
|
||||
[{"type":"text","text":"=D2*$G$1"}],
|
||||
[{"type":"text","text":"=D3*$G$1"}],
|
||||
[{"type":"text","text":"=D4*$G$1"}],
|
||||
[{"type":"text","text":"=D5*$G$1"}]
|
||||
]' --format json
|
||||
```
|
||||
|
||||
## 公式文本与结果回读
|
||||
|
||||
### 1. 回读公式文本
|
||||
|
||||
```bash
|
||||
dws sheet range read --node <NODE_ID> --sheet-id <SHEET_ID> --range "D2:D5" \
|
||||
--value-render-option formula --format json
|
||||
```
|
||||
|
||||
检查点:
|
||||
- `value` 应返回以 `=` 开头的公式文本。
|
||||
- 行号、列号、相对引用、绝对引用应与写入计划一致。
|
||||
- 无公式的单元格在 `formula` 模式下可能回退为原始值,不能把这种回退误判为公式已写入。
|
||||
|
||||
### 2. 回读计算结果
|
||||
|
||||
```bash
|
||||
dws sheet range read --node <NODE_ID> --sheet-id <SHEET_ID> --range "D2:D5" \
|
||||
--value-render-option raw_value --format json
|
||||
```
|
||||
|
||||
检查点:
|
||||
- 数值结果应与样本手算或本地复算一致。
|
||||
- 检查结果中是否出现 `#REF!` / `#DIV/0!` / `#VALUE!` / `#NAME?` / `#NULL!` / `#NUM!` / `#N/A`。
|
||||
- 对大范围公式,至少抽样检查首行、末行、边界行和异常数据行;用户要求全量处理时,应分批回读并断言处理数量。
|
||||
|
||||
### 3. 数值正确性边界
|
||||
|
||||
`formula-verify` 负责聚合已经落表的公式错误值;`range read` 负责确认实际公式文本和具体计算结果。即使 `formula-verify` 返回 `success`,也仍需对金额、比例、汇率、边界行等关键业务结果做 `raw_value` 抽样对账,因为一个公式可能计算出合法数值但业务逻辑仍然写错。
|
||||
|
||||
## 常见错误
|
||||
|
||||
- 想用 `csv-put` 写入 `=SUM(...)` 文本却忘记加前导单引号,导致内容被解析为公式。
|
||||
- 用原始二维数组 `--values '[["=B2*C2"]]'`,而不是 cell object。
|
||||
- 写整列公式时只写第一行,忘记把 `--range` 和 `--values` 扩成同样行数。
|
||||
- 复制公式时没有锁定固定引用,例如税率、汇率、查找表范围。
|
||||
- 没有回读 `formula` 模式,只看写入返回 `success`。
|
||||
- 只回读展示值,不运行 `formula-verify` 聚合扫描错误。
|
||||
- 把 `max-locations-per-error` 误解为错误计数上限;它只截断位置和样本。
|
||||
- 看到 `status=partial` 或 `hasMore=true` 仍声称整本表公式零错误。
|
||||
- 在 `--range` 中传 `Sheet1!A1:D10`,或把 `--targets` 与 `--sheet-id` 混用。
|
||||
- 显式传空的 `--targets '[]'`;这不是“无目标”,应改为至少一个目标,整本扫描则完全省略 `--targets`。
|
||||
|
||||
## 关联文档
|
||||
|
||||
- [sheet-write-data](./sheet-write-data.md):`range update` 的 `--values` cell object 结构、维度校验、富格式能力。
|
||||
- [sheet-read-data](./sheet-read-data.md):`value-render-option` 的 `formatted_value` / `raw_value` / `formula` 读取模式。
|
||||
- [sheet-conditional-format](./sheet-conditional-format.md):条件格式中的 `formulaCondition` 与辅助列公式的职责边界。
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
- 支持本地 `xlsx` / `xls`,文件上限 20MB
|
||||
- `--folder-token` 与 `--workspace` 至少提供一个
|
||||
- CLI 内部完成创建会话、OSS 上传、确认转换和轮询,Agent 不要自行拆分或重试
|
||||
- CLI 内部完成创建会话、上传文件、确认转换和轮询,Agent 不要自行拆分或重试
|
||||
- `drive upload` 只上传二进制文件,不会转换为可编辑的在线表格,不能替代本命令
|
||||
|
||||
## 命令
|
||||
@@ -71,6 +71,6 @@ dws sheet import get --task-id <TASK_ID> --format json
|
||||
## 边界
|
||||
|
||||
- 本命令接受的是本地文件路径;它把 xlsx/xls 转换成新的 axls 在线表格
|
||||
- 已经存在于钉盘或文档中的 xlsx 节点不能直接传给工作表/单元格命令;先用 `doc download` 下载,需要在线编辑时再执行 `sheet import create`
|
||||
- 已经存在于钉盘或文档中的 xlsx 节点不能直接传给工作表/单元格命令;先用 `drive download` 下载,需要在线编辑时再执行 `sheet import create`
|
||||
- 向已有在线表格写数据应使用 `range update`、`append`、`csv-put` 或 `table-put`
|
||||
- md/doc/docx 等文字文档导入使用 `dws doc import`
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
|
||||
用户说"写入图片/插入图片/加图片/放图片到单元格/嵌入图片到表格":
|
||||
- 写入图片 → `write-image`(需表格 ID + 工作表 ID + 单元格范围 + 本地图片路径)
|
||||
- 禁止使用 `range update` 写入图片,因为 `update_range` 的 MCP 工具不支持图片类型参数,调用必定失败。必须使用 `write-image` 命令
|
||||
- 禁止使用 `range update` 写入图片;图片对象必须使用 `write-image` 命令
|
||||
- 用户指定了图片尺寸 → `write-image --width N --height M`
|
||||
|
||||
### 浮动图片
|
||||
@@ -48,8 +48,6 @@ Flags:
|
||||
--mime-type string 文件 MIME 类型 (默认根据扩展名推断)
|
||||
```
|
||||
|
||||
`--format json` 输出规整 JSON:`{success, resourceId, resourceUrl, fileName, fileSize}`。`resourceUrl` 可用于 `create-float-image` 的 `--src`。
|
||||
|
||||
### 上传图片并写入表格单元格
|
||||
```
|
||||
Usage:
|
||||
@@ -205,10 +203,13 @@ dws sheet write-image --node <NODE_ID> --sheet-id <SHEET_ID> --range C3:C3 --fil
|
||||
|
||||
# 4. 完整流程: 创建表格 → 写表头 → 写入图片
|
||||
dws sheet create --name "产品目录" -f json
|
||||
# 提取 nodeId 后:
|
||||
dws sheet range update --node <NODE_ID> --sheet-id Sheet1 --range "A1:B1" --values '[[{"type":"text","text":"产品名称"},{"type":"text","text":"产品图片"}]]' -f json
|
||||
dws sheet range update --node <NODE_ID> --sheet-id Sheet1 --range "A2:A2" --values '[[{"type":"text","text":"MacBook Pro"}]]' -f json
|
||||
dws sheet write-image --node <NODE_ID> --sheet-id Sheet1 --range B2:B2 --file ./macbook.png --width 150 --height 100 -f json
|
||||
# 提取 nodeId 后,先用 list 获取真实 sheetId:
|
||||
dws sheet list --node <NODE_ID> -f json
|
||||
dws sheet range update --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:B1" \
|
||||
--values '[[{"type":"text","text":"产品名称"},{"type":"text","text":"产品图片"}]]' -f json
|
||||
dws sheet range update --node <NODE_ID> --sheet-id <SHEET_ID> --range "A2:A2" \
|
||||
--values '[[{"type":"text","text":"MacBook Pro"}]]' -f json
|
||||
dws sheet write-image --node <NODE_ID> --sheet-id <SHEET_ID> --range B2:B2 --file ./macbook.png --width 150 --height 100 -f json
|
||||
```
|
||||
|
||||
## 上下文传递
|
||||
@@ -229,7 +230,7 @@ dws sheet write-image --node <NODE_ID> --sheet-id Sheet1 --range B2:B2 --file ./
|
||||
- ★ **`--sheet-id` 获取规范(强制)**:`sheetId` 未知时必须先通过 `dws sheet list --node <NODE_ID> --format json` 查询,禁止凭空编造(如臆测为 `Sheet1`、`sheet1`、`0`、`default` 等)
|
||||
- `media-upload` 是两步自动完成的流程 (获取附件上传凭证 → OSS 上传),无需手动分步操作
|
||||
- `write-image` 是三步自动完成的流程 (获取附件上传凭证 → OSS 上传 → 写入图片到单元格),无需手动分步操作
|
||||
- ★ 向表格单元格中写入图片必须使用 `write-image`,禁止使用 `range update`。`range update` 底层调用的 `update_range` MCP 工具不支持图片类型参数,调用会失败
|
||||
- ★ 向表格单元格中写入图片必须使用 `write-image`,禁止使用 `range update`。`range update` 不支持图片对象
|
||||
- `write-image` 与 `media-upload` 的区别:`media-upload` 仅上传附件到表格获取 resourceId;`write-image` 在上传后还会将图片写入指定单元格
|
||||
- `create-float-image` 创建浮动图片前必须先通过 `media-upload` 上传图片获取 `resourceUrl`,再将其作为 `--src` 传入。`--src` 的格式为 `/core/api/resources/img/...`,不能直接传外部 URL
|
||||
- `create-float-image` 的 `--range` 使用 A1 表示法指定锚点单元格(如 `A1`、`B3`),支持带工作表前缀(如 `Sheet1!A1`)
|
||||
|
||||
@@ -1,67 +1,292 @@
|
||||
# 透视表管理
|
||||
# 透视表 (pivot-table)
|
||||
|
||||
## 真对象硬约束
|
||||
|
||||
当用户要求"透视表 / 分组汇总 / 交叉分析 / 按 X 统计 Y"时,**必须**通过 `pivot-table create` 创建真实的透视表对象。**禁止**用 `SUMIFS` / `COUNTIFS` 等普通公式 + `csv-put` 在原表中拼一张"看起来像透视表的汇总表"来代替——静态公式无法随源数据动态更新,且失去交互能力。判断标准:交付后 `pivot-table list` 必须能返回该对象。
|
||||
|
||||
## 使用场景
|
||||
|
||||
- 用户要按部门、月份等维度汇总数据 → `pivot-table create`
|
||||
- 用户要查看现有透视表或取得 `pivotTableId` → `pivot-table list`
|
||||
- 用户要调整行列、聚合方式或显示选项 → `pivot-table update`
|
||||
- 用户明确要求删除透视表 → `pivot-table delete`(不可逆,必须先确认)
|
||||
读写透视表对象。本 reference 覆盖 4 个命令:
|
||||
|
||||
透视表是原生对象,会随源数据更新;不要用一组普通汇总公式冒充透视表。
|
||||
| 操作需求 | 使用命令 | 说明 |
|
||||
|---------|---------|------|
|
||||
| 查看已有透视表 | `pivot-table list` | 获取透视表的结构、数据源和配置 |
|
||||
| 创建透视表 | `pivot-table create` | 创建透视表对象 |
|
||||
| 更新透视表 | `pivot-table update` | 更新透视表配置(行/列/值/筛选字段) |
|
||||
| 删除透视表 | `pivot-table delete` | 删除透视表 |
|
||||
|
||||
## 列出与查看
|
||||
典型工作流:先读取现有透视表了解配置 -> 执行创建/更新/删除 -> 再次读取验证结果。
|
||||
|
||||
```bash
|
||||
dws sheet pivot-table list --node <NODE_ID> --sheet-id <SHEET_ID>
|
||||
dws sheet pivot-table list --node <NODE_ID> --sheet-id <SHEET_ID> --pivot-table-id <PIVOT_TABLE_ID>
|
||||
## 行/值字段映射(创建前必做)
|
||||
|
||||
创建透视表前先识别用户需求中的分组维度和聚合指标,**不要搞反**:
|
||||
|
||||
- **rows(行字段)** = 分组维度,即"按什么分组"。例:部门、地区、医生、产品类别
|
||||
- **values(值字段)** = 聚合指标,即"统计什么数值"。例:销售额(`summarize_by: "sum"`)、订单数(`summarize_by: "count"`)
|
||||
- **columns(列字段)** = 交叉维度(可选),即"再按什么横向展开"。例:月份、性别
|
||||
|
||||
| 用户说 | rows | values | columns |
|
||||
|--------|------|--------|---------|
|
||||
| "按部门统计人数" | 部门 | 姓名(`"count"`) | -- |
|
||||
| "按医生统计费用和结余" | 主管医生 | 费用(`"sum"`)、结余(`"sum"`) | -- |
|
||||
| "各部门男女人数" | 部门 | 姓名(`"count"`) | 性别 |
|
||||
|
||||
**常见配置错误(必须注意)**:
|
||||
- **数据源范围必须精确**:透视表的数据源范围必须包含表头行,且精确覆盖全部数据行列。范围过大(包含空行/空列)或过小(遗漏数据列)都会导致透视表结果错误
|
||||
- **行列字段选择要匹配用户意图**:用户说"按商品统计金额" -> 行字段=商品,值字段=金额(`summarize_by: "sum"`)。不要把行列字段搞反
|
||||
- **聚合类型要匹配**:用户说"统计数量" -> `"count"`;"统计总额" -> `"sum"`;"统计平均" -> `"average"`
|
||||
- **创建后必须验证**:调用 `pivot-table list` 确认透视表结构正确
|
||||
|
||||
## 命令详细参考
|
||||
|
||||
### 获取透视表
|
||||
```
|
||||
Usage:
|
||||
dws sheet pivot-table list [flags]
|
||||
Example:
|
||||
# 列出所有透视表
|
||||
dws sheet pivot-table list --node NODE_ID --sheet-id SHEET_ID
|
||||
|
||||
# 获取单个透视表详情
|
||||
dws sheet pivot-table list --node NODE_ID --sheet-id SHEET_ID --pivot-table-id PT_ID
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
--pivot-table-id string 透视表 ID (可选,不传则返回全部)
|
||||
```
|
||||
|
||||
不传 `--pivot-table-id` 时列出工作表中的全部透视表;传入时返回单个透视表详情。
|
||||
### 创建透视表
|
||||
```
|
||||
Usage:
|
||||
dws sheet pivot-table create [flags]
|
||||
Example:
|
||||
# 按部门统计销售额(默认自动新建工作表存放)
|
||||
dws sheet pivot-table create --node NODE_ID \
|
||||
--source "'Sheet1'!A1:D100" \
|
||||
--properties '{
|
||||
"rows": [{"field": "部门"}],
|
||||
"values": [{"field": "销售额", "summarize_by": "sum"}],
|
||||
"show_row_grand_total": true
|
||||
}'
|
||||
|
||||
## 创建
|
||||
# 指定放置到已有工作表的特定位置
|
||||
dws sheet pivot-table create --node NODE_ID \
|
||||
--source "'Sheet1'!A1:E200" \
|
||||
--target-sheet-id TARGET_SHEET_ID --target-position "A1" \
|
||||
--properties '{
|
||||
"rows": [{"field": "部门"}],
|
||||
"values": [{"field": "销售额", "summarize_by": "sum"}]
|
||||
}'
|
||||
|
||||
# 通过文件传入配置
|
||||
dws sheet pivot-table create --node NODE_ID \
|
||||
--source "'Sheet1'!A1:D50" --properties @pivot.json
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--source string 数据源区域,A1 表示法含 sheet 前缀 (必填,如 "'Sheet1'!A1:D100")
|
||||
--properties string 透视表配置 JSON (必填,含 rows/columns/values/filters)
|
||||
--target-sheet-id string 目标工作表 ID 或名称 (可选,不传则自动新建工作表)
|
||||
--target-position string 透视表放置位置 (可选,A1 格式单个 cell,如 "B5",不传默认 A1)
|
||||
```
|
||||
|
||||
### 更新透视表
|
||||
```
|
||||
Usage:
|
||||
dws sheet pivot-table update [flags]
|
||||
Example:
|
||||
# 先获取现有配置
|
||||
dws sheet pivot-table list --node NODE_ID --sheet-id SHEET_ID --pivot-table-id PT_ID
|
||||
|
||||
# 修改后回写
|
||||
dws sheet pivot-table update --node NODE_ID --sheet-id SHEET_ID --pivot-table-id PT_ID \
|
||||
--properties '{
|
||||
"rows": [{"field": "部门"}],
|
||||
"values": [
|
||||
{"field": "销售额", "summarize_by": "sum"},
|
||||
{"field": "订单号", "summarize_by": "count", "display_name": "订单数"}
|
||||
],
|
||||
"show_row_grand_total": true
|
||||
}'
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
--pivot-table-id string 透视表 ID (必填,可通过 pivot-table list 获取)
|
||||
--properties string 透视表配置 JSON (必填)
|
||||
```
|
||||
|
||||
### 删除透视表
|
||||
```
|
||||
Usage:
|
||||
dws sheet pivot-table delete [flags]
|
||||
Example:
|
||||
dws sheet pivot-table delete --node NODE_ID --sheet-id SHEET_ID --pivot-table-id PT_ID
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
--pivot-table-id string 透视表 ID (必填,可通过 pivot-table list 获取)
|
||||
```
|
||||
|
||||
> [强制] 危险操作:删除不可恢复。必须先向用户展示操作摘要并获得明确同意,用户同意后才加 `--yes` 执行。
|
||||
|
||||
## `--properties` JSON Schema 速查
|
||||
|
||||
**顶层字段**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `rows` | object[] | 否 | 行字段数组(分组维度),详见下方「rows/columns 字段项」表 |
|
||||
| `columns` | object[] | 否 | 列字段数组(交叉维度),结构同 rows |
|
||||
| `values` | object[] | 是 | 值字段数组(聚合指标,至少一项),详见下方「values 字段项」表 |
|
||||
| `filters` | object[] | 否 | 筛选字段数组,详见下方「filters 字段项」表 |
|
||||
| `show_row_grand_total` | boolean | 否 | 是否显示行总计,默认 true |
|
||||
| `show_col_grand_total` | boolean | 否 | 是否显示列总计,默认 true |
|
||||
| `show_subtotals` | boolean | 否 | 是否显示分类小计,默认 true |
|
||||
| `repeat_row_labels` | boolean | 否 | 是否显示重复项标签,默认 false |
|
||||
| `collapse` | object | 否 | 行字段折叠状态:字段名 -> 要折叠的项目列表,如 `{"部门": ["A组", "B组"]}` |
|
||||
|
||||
**rows/columns 字段项**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `field` | string | 是 | 列名(表头文本),必须与数据源首行的列名完全匹配 |
|
||||
| `display_name` | string | 否 | 显示名称(不传时使用 field 值) |
|
||||
|
||||
**filters 字段项**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `field` | string | 是 | 列名(表头文本),必须与数据源首行的列名完全匹配 |
|
||||
| `display_name` | string | 否 | 显示名称(不传时使用 field 值) |
|
||||
|
||||
**values 字段项**:
|
||||
|
||||
| 字段 | 类型 | 必填 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `field` | string | 是 | 列名(表头文本),必须与数据源首行的列名完全匹配 |
|
||||
| `summarize_by` | string | 否 | 聚合方式,默认 sum,详见下方枚举表 |
|
||||
| `display_name` | string | 否 | 显示名称(不传时自动生成,如"求和 - 销售额") |
|
||||
| `show_data_as` | string | 否 | 值显示方式:`normal`/`percent_of_row_total`/`percent_of_col_total`/`percent_of_grand_total` |
|
||||
|
||||
**summarize_by 枚举值**:
|
||||
|
||||
| 值 | 说明 |
|
||||
|----|------|
|
||||
| `sum` | 求和(默认) |
|
||||
| `count` | 计数 |
|
||||
| `average` | 平均值 |
|
||||
| `max` | 最大值 |
|
||||
| `min` | 最小值 |
|
||||
| `product` | 乘积 |
|
||||
| `count_numbers` | 数值计数 |
|
||||
| `std_dev` | 标准偏差 |
|
||||
| `std_dev_p` | 总体标准偏差 |
|
||||
| `var` | 方差 |
|
||||
| `var_p` | 总体方差 |
|
||||
| `distinct` | 去重计数 |
|
||||
| `median` | 中位数 |
|
||||
|
||||
## `--source` 数据源格式
|
||||
|
||||
- 格式:`'SheetName'!StartCell:EndCell`
|
||||
- 示例:`'Sheet1'!A1:D100`、`'销售数据'!A1:F500`
|
||||
- 必须包含表头行(通常从第 1 行开始)
|
||||
- sheet 名称用单引号包裹(含空格或特殊字符时必须)
|
||||
- `source` 直接使用上述 A1 表示法;不要自行改写成内部对象结构
|
||||
|
||||
## 高级功能示例
|
||||
|
||||
```bash
|
||||
# 含折叠 + show_data_as
|
||||
dws sheet pivot-table create --node <NODE_ID> \
|
||||
--source "'Data'!A1:D100" \
|
||||
--source "'Sheet1'!A1:E200" \
|
||||
--properties '{
|
||||
"rows":[{"field":"部门"}],
|
||||
"columns":[{"field":"月份"}],
|
||||
"values":[{"field":"销售额","summarize_by":"sum"}],
|
||||
"show_row_grand_total":true
|
||||
"rows": [{"field": "部门"}],
|
||||
"values": [
|
||||
{"field": "销售额", "summarize_by": "sum"},
|
||||
{"field": "订单数", "summarize_by": "count", "show_data_as": "percent_of_col_total"}
|
||||
],
|
||||
"collapse": {"部门": ["A组"]},
|
||||
"show_row_grand_total": true
|
||||
}'
|
||||
```
|
||||
|
||||
可选参数:
|
||||
> collapse/show_data_as 为可选透传字段,CLI 和 MCP 层不做额外校验,直接传递给底层引擎处理。
|
||||
|
||||
- `--target-sheet-id`:将透视表放到指定工作表;不传时由服务端创建目标工作表。
|
||||
- `--target-position`:目标起始单元格,例如 `B2`。
|
||||
- `--properties @pivot.json`:从文件读取配置。
|
||||
|
||||
`--source` 必须包含工作表前缀并覆盖表头和数据,例如 `"'Data'!A1:D100"`。创建时 `properties.values` 必须是非空数组。
|
||||
|
||||
## properties 结构
|
||||
|
||||
- `rows` / `columns` / `filters`:字段数组,每项至少包含非空 `field`。
|
||||
- `values`:聚合字段数组,每项至少包含 `field`;创建时至少一项。
|
||||
- `summarize_by`:`sum`、`count`、`average`、`max`、`min`、`product`、`count_numbers`、`std_dev`、`std_dev_p`、`var`、`var_p`、`distinct`、`median`。
|
||||
- `collapse`:字段折叠配置,可为对象或数组。
|
||||
- 显示选项:`show_row_grand_total`、`show_col_grand_total`、`show_subtotals`、`repeat_row_labels`。
|
||||
|
||||
## 更新
|
||||
## 核心工作流
|
||||
|
||||
```bash
|
||||
dws sheet pivot-table update --node <NODE_ID> --sheet-id <SHEET_ID> \
|
||||
--pivot-table-id <PIVOT_TABLE_ID> \
|
||||
--properties '{"show_subtotals":false}'
|
||||
# -- 工作流 1: 创建简单分组汇总 --
|
||||
|
||||
# 1. 先查 sheetId
|
||||
dws sheet list --node <NODE_ID> -f json
|
||||
|
||||
# 2. 查看数据范围确认列名和边界
|
||||
dws sheet csv-get --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:F5"
|
||||
|
||||
# 3. 创建透视表(按部门统计销售额)
|
||||
dws sheet pivot-table create --node <NODE_ID> \
|
||||
--source "'Sheet1'!A1:D100" \
|
||||
--properties '{
|
||||
"rows": [{"field": "部门"}],
|
||||
"values": [{"field": "销售额", "summarize_by": "sum"}],
|
||||
"show_row_grand_total": true
|
||||
}'
|
||||
|
||||
# 4. 验证创建结果(用 create 返回的 targetSheetId 查询)
|
||||
dws sheet pivot-table list --node <NODE_ID> --sheet-id <TARGET_SHEET_ID>
|
||||
|
||||
# -- 工作流 2: 多维度交叉分析 --
|
||||
|
||||
dws sheet pivot-table create --node <NODE_ID> \
|
||||
--source "'Sheet1'!A1:E200" \
|
||||
--properties '{
|
||||
"rows": [{"field": "部门"}, {"field": "产品"}],
|
||||
"columns": [{"field": "季度"}],
|
||||
"values": [
|
||||
{"field": "销售额", "summarize_by": "sum"},
|
||||
{"field": "订单号", "summarize_by": "count", "display_name": "订单数"}
|
||||
],
|
||||
"show_row_grand_total": true,
|
||||
"show_col_grand_total": true,
|
||||
"show_subtotals": true
|
||||
}'
|
||||
|
||||
# -- 工作流 3: 更新透视表配置 --
|
||||
|
||||
# 先获取现有配置
|
||||
dws sheet pivot-table list --node <NODE_ID> --sheet-id <SHEET_ID> --pivot-table-id <PT_ID>
|
||||
|
||||
# 修改后回写(增加一个值字段)
|
||||
dws sheet pivot-table update --node <NODE_ID> --sheet-id <SHEET_ID> --pivot-table-id <PT_ID> \
|
||||
--properties '{
|
||||
"rows": [{"field": "部门"}],
|
||||
"values": [
|
||||
{"field": "销售额", "summarize_by": "sum"},
|
||||
{"field": "利润", "summarize_by": "average", "display_name": "平均利润"}
|
||||
],
|
||||
"show_row_grand_total": true
|
||||
}'
|
||||
```
|
||||
|
||||
Open 接口支持部分更新,因此更新显示选项时不需要重复传入 `values`。更新行列或聚合字段时,应先用 `list --pivot-table-id` 读取当前配置,再传入需要变更的字段。
|
||||
## 上下文传递
|
||||
|
||||
## 删除
|
||||
| 操作 | 从返回中提取 | 用于 |
|
||||
|------|-------------|------|
|
||||
| `pivot-table list` | `pivotTables[].id` | 后续 update / delete 的 `--pivot-table-id` |
|
||||
| `pivot-table list --pivot-table-id` | 完整配置(rows/columns/values/filters/collapse/options) | update 时作为基础配置修改后回写 |
|
||||
| `pivot-table create` | `pivotTable.id` | 后续 update / delete 的 `--pivot-table-id` |
|
||||
| `pivot-table create` | `pivotTable.targetSheetId` | 后续 list / update / delete 的 `--sheet-id`(透视表所在工作表) |
|
||||
| `pivot-table delete` | `message` | 确认删除完成 |
|
||||
| `sheet list` | 工作表的 `sheetId` | 所有 pivot-table 命令的 `--sheet-id` |
|
||||
|
||||
```bash
|
||||
dws sheet pivot-table delete --node <NODE_ID> --sheet-id <SHEET_ID> \
|
||||
--pivot-table-id <PIVOT_TABLE_ID> --yes
|
||||
```
|
||||
## 注意事项
|
||||
|
||||
删除不可恢复。Agent 必须先展示目标文档、工作表和 `pivotTableId`,获得用户明确同意后才能附加 `--yes`。
|
||||
- [强制] **`--sheet-id` 获取规范**:`sheetId` 未知时必须先通过 `dws sheet list --node <NODE_ID> --format json` 查询,禁止凭空编造(如臆测为 `Sheet1`、`sheet1`、`0`、`default` 等)
|
||||
- [强制] **创建后必须验证**:透视表创建后必须调用 `pivot-table list` 验证配置是否正确
|
||||
- [强制] **pivot-table-id 禁止臆测**:必须通过 `pivot-table list` 获取真实的透视表 ID,不可编造
|
||||
- [强制] **source 必须精确**:数据源范围必须从表头行开始,精确覆盖数据区域,先用 `csv-get` 确认数据边界
|
||||
- **field 名称必须准确**:rows/columns/values/filters 中的 field 值必须与源数据表头完全一致(区分大小写)
|
||||
- **透视表自动新建子表**:创建的透视表默认放置在自动新建的子表中,不会覆盖源数据。可通过 `--target-sheet-id` 和 `--target-position` 指定放置到已有工作表
|
||||
- **不支持修改数据源**:update 仅可修改字段配置和显示选项,不可修改 source
|
||||
- **折叠状态**:collapse 字段用于控制行字段的展开/折叠,格式为 {字段名: [要折叠的项]}
|
||||
- **大 JSON 用 @file**:`--properties` 支持 `@文件路径` 读取本地 JSON 文件
|
||||
|
||||
@@ -22,6 +22,11 @@
|
||||
- 自动填充 → `range fill`
|
||||
- 请勿用 `range read` 读取源数据后手动计算规律再 `range update` 写入,`range fill` 支持服务端智能填充
|
||||
|
||||
用户说"批量清除/批量操作/一次执行多个写操作/原子批量/先清除再写入":
|
||||
- 批量清除多个区域 → `range batch-clear`
|
||||
- 组合多个不同写操作 → `batch-update`
|
||||
- 详见 [sheet-batch-operations](./sheet-batch-operations.md)
|
||||
|
||||
用户说"复制区域/把这块数据复制到/复制到另一个工作表":
|
||||
- 复制区域 → `range copy-to`
|
||||
- 跨工作表 → `range copy-to --target-sheet-id Sheet2` 或 `--target-range "Sheet2!A1"`
|
||||
@@ -82,11 +87,9 @@ Flags:
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
--source-range string 源数据范围,A1 表示法 (必填)
|
||||
--target-range string 目标填充范围,A1 表示法 (必填)
|
||||
--fill-type string 填充类型: 不传则自动检测 / copy(复制) / onlystyle(仅格式) / withoutstyle(仅值)
|
||||
--fill-type string 填充类型: series(序列,默认) / copy(复制) / onlystyle(仅格式) / withoutstyle(仅值)
|
||||
```
|
||||
|
||||
`--fill-type` **不传时自动检测**(根据源数据智能判断:数值序列递增、日期递增、文本复制等),这是填序列的默认行为,无需显式传值。`--help` 枚举的可选值只有 `copy` / `onlystyle` / `withoutstyle`;服务端另外也接受 `series`(强制按序列填充),但它不在 `--help` 列表里,一般用不到——要序列递增直接不传 `--fill-type` 即可。
|
||||
|
||||
目标范围须与源范围在行或列维度对齐(不支持对角填充)。
|
||||
|
||||
### 复制区域
|
||||
@@ -144,6 +147,8 @@ Flags:
|
||||
|------|-------------|------|
|
||||
| `list` | 工作表的 `sheetId` | range clear / range sort / range fill / range copy-to / range move-to 的 --sheet-id |
|
||||
|
||||
> **批量操作**(`range batch-clear` / `batch-update`)已拆分至 [sheet-batch-operations](./sheet-batch-operations.md),含写入边界 + 回读校验规范、典型组合场景示例等。
|
||||
|
||||
## 注意事项
|
||||
|
||||
- ★ **`--sheet-id` 获取规范(强制)**:`sheetId` 未知时必须先通过 `dws sheet list --node <NODE_ID> --format json` 查询真实的 `sheetId` / 工作表名称后再调用,禁止凭空编造(如臆测为 `Sheet1`、`sheet1`、`0`、`default` 等);用户仅给出工作表名称时,也应通过 `list` 校验该名称是否存在,避免名称大小写或拼写不一致导致失败
|
||||
@@ -153,3 +158,4 @@ Flags:
|
||||
- ★ **排序用 `range sort` 不用 `range read` + 客户端排序 + `range update`**:服务端原子操作,支持多级排序
|
||||
- ★ **排序前必须 `range read` 前几行判断表头**:读取排序范围前 3-5 行,对比首行与后续行的数据模式(类型、语义)来判断是否有表头。禁止不读就排,表头被排入数据不可撤销
|
||||
- ★ **填充用 `range fill` 不用 `range read` + 手动计算 + `range update`**:服务端智能填充,支持序列递增、公式扩展等
|
||||
- ★ **批量操作详见 [sheet-batch-operations](./sheet-batch-operations.md)**:`range batch-clear` 多区域清除、`batch-update` 组合写操作,均原子事务
|
||||
|
||||
@@ -3,43 +3,34 @@
|
||||
## 使用场景
|
||||
|
||||
用户说"读数据/看表格内容":
|
||||
- 需要列名、二维数据、dtype 和 number format,或准备与 `table-put` 配套处理 → `table-get`
|
||||
- 快速查看纯值数据、批量处理、大表分批读 → `csv-get`(token 消耗低,防爆保护)
|
||||
- 需要 dataframe/table 结构(列名、二维 data、pandas-style dtypes、number formats)→ `table-get`
|
||||
- 需要结构化信息(值+样式+数据验证+富文本+单元格级超链接)、查看公式或原始值 → `range read`
|
||||
- 需要校验公式写入结果 → 先 `range read --value-render-option formula` 回读公式文本,再用 `formula-verify` 聚合扫描错误;需要确认业务数值时用 `raw_value` 抽样对账。完整流程见 [sheet-formula](./sheet-formula.md)
|
||||
- 需要查看合并单元格 / 表头合并结构 → `sheet info`,读取返回的 `mergedRanges`;不要在 `csv-get` 或 `range read` 里找合并信息
|
||||
|
||||
## 命令选择
|
||||
|
||||
| 读取目的 | 推荐命令 | 说明 |
|
||||
|---------|---------|------|
|
||||
| DataFrame 风格结构化读取 | `table-get` | 返回 columns / data / dtypes / formats,可与 table-put 配套 |
|
||||
| 快速查看纯值、数据分析、大表分批读取 | `csv-get` | CSV 格式,token 消耗约为 JSON 的 1/3,内置 maxChars 防爆 |
|
||||
| 按 table/dataframe 协议读取 | `table-get` | 返回 `columns` / `data` / `dtypes` / `formats`;默认首行为表头 |
|
||||
| 查看数据验证配置(下拉/复选框) | `range read` | 返回 per-cell 结构,含 dataValidation |
|
||||
| 查看单元格样式(背景色/字体/对齐等) | `range read` | 返回 per-cell 结构,含 cellStyles(仅显式设置的样式) |
|
||||
| 查看单元格级超链接 | `range read` | 返回 per-cell 结构,含 hyperlink;富文本片段链接仍在 richText 内 |
|
||||
| 查看公式文本 | `range read --value-render-option formula` | value 返回公式 |
|
||||
| 公式写后结果校验 | `range read --value-render-option formula` + `formula-verify` + `raw_value` | 先确认公式文本,再聚合扫描错误,最后按需抽样对账业务数值 |
|
||||
| 获取原始值(数字/布尔而非格式化字符串) | `range read --value-render-option raw_value` | value 返回原始类型 |
|
||||
| 查看合并单元格范围 | `sheet info` | 返回 `mergedRanges`,这是工作表结构信息,不属于单元格值读取 |
|
||||
|
||||
## 与现有读取能力的区别
|
||||
|
||||
- `csv-get` 面向快速浏览和大表纯值读取:返回 CSV 文本、真实行号/列号映射和截断标记,token 低;不表达列类型、number format 或 per-cell 元数据
|
||||
- `table-get` 面向 dataframe/table 数据交换:返回 `columns` / `data` / `dtypes` / `formats`,适合后续结构化分析、类型保持和 `table-put` 回写;不返回合并单元格、dataValidation、hyperlink、richText、per-cell `cellStyles`
|
||||
- `range read` 面向精确单元格读取:返回二维 per-cell 对象,可看公式、原始值、dataValidation、hyperlink、richText、cellStyles;适合少量或中等范围的细节检查,但大范围读取 token 成本更高
|
||||
|
||||
## 命令详细参考
|
||||
|
||||
### 读取结构化 table 数据
|
||||
```
|
||||
Usage:
|
||||
dws sheet table-get [flags] # 别名: dws sheet table-read
|
||||
Example:
|
||||
dws sheet table-get --node <NODE_ID>
|
||||
dws sheet table-get --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:D20"
|
||||
dws sheet table-get --node <NODE_ID> --sheet-id <SHEET_ID> --no-header
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称
|
||||
--range string 读取范围,A1 表示法;可带 sheet 前缀
|
||||
--no-header 首行不作为表头,自动生成 col1/col2/...
|
||||
```
|
||||
|
||||
`table-get` 面向结构化数据处理,返回 `columns`、二维 `data`、`dtypes` 和可用时的 `formats`。未传 `--sheet-id` / `--range` 时由服务端读取目标文档中的 table 数据;大表仍应通过 `--range` 限定范围。需要单元格样式、公式、数据验证或富文本细节时,继续使用 `range read`。
|
||||
|
||||
### 以 CSV 格式读取工作表数据(推荐)
|
||||
```
|
||||
Usage:
|
||||
@@ -77,6 +68,46 @@ Flags:
|
||||
- 分批读取:`--range "A1:J500"`、`--range "A501:J1000"` ……
|
||||
- 单次建议 ≤5000 单元格
|
||||
|
||||
### 以 table/dataframe 协议读取结构化数据
|
||||
```
|
||||
Usage:
|
||||
dws sheet table-get [flags]
|
||||
Example:
|
||||
dws sheet table-get --node <NODE_ID>
|
||||
dws sheet table-get --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:D20"
|
||||
dws sheet table-get --node <NODE_ID> --sheet-id "Sheet1" --no-header
|
||||
dws sheet table-get --node <NODE_ID> --range "Sheet1!A1:D20"
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称;默认不指定
|
||||
--range string 读取范围,A1 表示法;可带 sheet 前缀,如 Sheet1!A1:D10;默认读取非空范围
|
||||
--no-header 首行不作为表头,自动生成 col1/col2/...;默认 false
|
||||
```
|
||||
|
||||
**默认行为**:
|
||||
- 不传 `--sheet-id` / `--range` 时,读取文档内所有工作表
|
||||
- `--range` 带 sheet 前缀时,以 `range` 中的 sheet 为读取目标
|
||||
- 不传 `--range` 时,每个目标工作表读取实际非空范围,并裁掉前导全空行/列;显式传 `--range` 时按用户范围原样读取
|
||||
- 默认首行作为表头;传 `--no-header` 时不消费表头行,并生成 `col1` / `col2` / ...
|
||||
- 大表或多 sheet 文档建议显式传 `--sheet-id` 和 `--range`,避免一次返回所有工作表造成超时或 token 过大
|
||||
|
||||
**返回字段说明**:
|
||||
- `sheets` — 工作表数组;每项表示一个 table 结果
|
||||
- `name` / `sheetId` — 工作表名称与 ID
|
||||
- `range` — 实际读取范围,A1 表示法
|
||||
- `columns` — 列名数组;默认来自第一行,传 `--no-header` 时生成 `col1` / `col2` / ...
|
||||
- `data` — 二维数组;默认不含表头行。空单元格 / 缺失值在 table 语义上是 `null`;部分返回链路中也可能表现为空对象 `{}`,此时 `{}` 只表示空位,不是 JSON object 单元格值
|
||||
- `dtypes` — 按列返回 pandas-style dtype,例如 `object` / `float64` / `bool` / `datetime64[ns]`。普通文本列返回 `object`,当前不返回 `string`
|
||||
- `formats` — 按列返回 number format code,例如 `@` / `#,##0.00` / `yyyy-mm-dd`
|
||||
|
||||
**适用边界**:
|
||||
- 不传 `--range` 时读取实际非空范围;如需控制数据量,请显式传 `--range` 分批读取
|
||||
- 首行作为表头时,表头必须非空且不重复;没有稳定表头时传 `--no-header`
|
||||
- `data[][]` 中的 `{}` 表示空位 / 空单元格,按 `null` 处理;不要把它理解成可写入的对象值
|
||||
- `table-get` 返回的是值级 table 结构,不返回合并单元格、dataValidation、hyperlink、richText 或 per-cell `cellStyles`。这些信息请使用 `sheet info` 或 `range read`
|
||||
- `dtypes` / `formats` 是列级推断结果;单列混合类型通常按 `object` 处理。即使 `table-put` 写入时声明 `string`,文本列回读也通常是 `object`
|
||||
- 大整数/长数字 ID 如果在 `table-get` 中回读为 `float64`,不要把它当作逐位精确值使用;超过 `9007199254740991` 的整数必须在写入时按文本保存,回读应表现为字符串 / `object`,必要时用 `range read --value-render-option raw_value` 复核
|
||||
|
||||
### 读取工作表数据(per-cell 结构化信息)
|
||||
```
|
||||
Usage:
|
||||
@@ -107,7 +138,7 @@ Flags:
|
||||
| `dataValidation` | object | 仅有数据验证时出现,无则省略 | 数据验证配置,见下表 |
|
||||
| `hyperlink` | object | 仅有单元格级超链接时出现,无则省略 | 整格超链接,结构为 `{type, link, text?}`,见下表 |
|
||||
| `richText` | object | 仅富文本单元格出现 | 富文本结构(含超链接、附件、图片、样式片段等),普通纯文本不含此字段 |
|
||||
| `cellStyles` | object | 仅有显式设置的样式时出现;MCP 序列化层也可能返回全 null 空壳 | cell-level 样式,见下表。读取时只看非 null 字段;全 null 等同不存在 |
|
||||
| `cellStyles` | object | 仅有显式设置的样式时出现;部分返回链路也可能返回全 null 空壳 | cell-level 样式,见下表。读取时只看非 null 字段;全 null 等同不存在 |
|
||||
|
||||
`range read` / `range get` 不返回合并单元格结构。要看合并单元格,请先或另行调用 `dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID> --format json`,使用其中的 `mergedRanges`。
|
||||
|
||||
@@ -174,7 +205,7 @@ Flags:
|
||||
}
|
||||
```
|
||||
|
||||
说明:第一行表头有 `cellStyles`(加粗 + 背景色),第二行第二格有单元格级 `hyperlink`。注意:MCP 平台序列化会将未设置的字段填充为 null(如 `"fontStyle": null`),读取时应忽略值为 null 的字段,仅关注非 null 的属性;如果 `cellStyles` 全字段都是 null,视同不存在。`richText` 字段同理——无富文本的普通单元格可能返回 `{"type": null, "texts": null}`,视同不存在。
|
||||
说明:第一行表头有 `cellStyles`(加粗 + 背景色),第二行第二格有单元格级 `hyperlink`。注意:部分返回链路会将未设置的字段填充为 null(如 `"fontStyle": null`),读取时应忽略值为 null 的字段,仅关注非 null 的属性;如果 `cellStyles` 全字段都是 null,视同不存在。`richText` 字段同理——无富文本的普通单元格可能返回 `{"type": null, "texts": null}`,视同不存在。
|
||||
|
||||
**取值模式说明**:
|
||||
| 模式 | value 返回内容 | 适用场景 |
|
||||
@@ -183,6 +214,8 @@ Flags:
|
||||
| `raw_value` | 原始值(如 1000、45808) | 数据处理、计算 |
|
||||
| `formula` | 公式文本(如 =SUM(A1:A10)),无公式时回退原始值 | 查看/复制公式 |
|
||||
|
||||
**公式校验建议**:写公式后不要只看写入返回结果。先用 `formula` 模式确认公式文本已落表,再运行 `formula-verify` 聚合扫描错误;关键业务数值继续用 `raw_value` 抽样对账。详见 [sheet-formula](./sheet-formula.md)。
|
||||
|
||||
**超时处理建议**:读取大范围数据时若出现超时或响应过慢,请主动缩小 `--range` 查询范围,**建议单次读取的单元格数量控制在 5000 个以内**(例如 50 行 × 100 列、100 行 × 50 列)。对于大表可采用分页读取策略:
|
||||
- 先通过 `info` 获取 `nonEmptyRange.range`,或用 `nonEmptyRange.lastRow` / `nonEmptyRange.lastColumn` 确定 A1 边界
|
||||
- 按行分批读取,如 `A1:J500`、`A501:J1000`、`A1001:J1500` ……
|
||||
@@ -219,5 +252,7 @@ dws sheet range read --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:D10" --f
|
||||
- `range read` 不传 `--range` 时默认读取整个工作表的全部非空数据
|
||||
- `range read` 的 `--range` 支持 `Sheet1!A1:D10` 格式直接指定工作表(此时忽略 `--sheet-id`)
|
||||
- ★ `csv-get` / `range read` / `range get` 不返回合并单元格结构;查看合并范围必须用 `sheet info` 的 `mergedRanges`
|
||||
- `range read` 遇到超时或响应过慢时,应缩小 `--range` 查询范围,**单次读取的单元格数量建议控制在 5000 个以内**;数据量较大时通过 `info` 获取边界后分批读取,避免不传 `--range` 直接读取整个大工作表
|
||||
- `table-get` 返回 table/dataframe 结构,适合需要 `columns` / `data` / `dtypes` / `formats` 的场景;它不返回 per-cell 元数据,也不替代 `range read`
|
||||
- ★ 大整数和长数字标识符回读校验:精确 ID 应是字符串 / `object`;若看到 `float64`,说明它已经按数值路径处理,超过 `9007199254740991` 时可能已丢精度
|
||||
- `range read` 遇到超时或响应过慢时,应缩小 `--range` 查询范围,**单次读取的单元格数量建议控制在 5000 个以内**;数据量较大时通过 `info` 的 `nonEmptyRange.range` 获取 A1 边界后分批读取,避免不传 `--range` 直接读取整个大工作表
|
||||
- ★ 当用户要求搜索/查找表格数据时,使用 `find` 命令,不要用 `range read` 读取全量数据后自行过滤——`find` 支持服务端搜索,效率更高、语义更准确
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
- 查找替换 → `replace`
|
||||
- 精确匹配后替换(只替换内容完全等于的单元格) → `replace --match-entire-cell`
|
||||
- 正则替换 → `replace --use-regexp`
|
||||
- 替换公式文本(改公式源码而非显示值) → `replace --match-formula`
|
||||
- 删除匹配内容 → `replace --replacement ""`
|
||||
- 请勿用 `find` + `range update`、`range read` + `range update` 等组合来模拟替换,`replace` 是服务端原子操作,效率更高且返回替换计数
|
||||
|
||||
@@ -68,6 +69,7 @@ Flags:
|
||||
--match-case 区分大小写 (默认 false)
|
||||
--match-entire-cell 完整单元格匹配
|
||||
--use-regexp 启用正则表达式匹配
|
||||
--match-formula 在公式文本中查找替换(默认 false,替换公式源码而非显示值)
|
||||
--include-hidden 包含隐藏行/列
|
||||
```
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
| 方式 | 命令 / 字段 | 适用场景 | 粒度 |
|
||||
|------|------------|---------|------|
|
||||
| **`set-style` / `batch-set-style`** | `dws sheet range set-style` | 批量刷整片区域的统一样式(表头加粗居中、数字格式等) | range 级别(2D 数组或全 range 统一值) |
|
||||
| **`set-style` / `batch-set-style`** | `dws sheet range set-style` / `batch-set-style` | 批量刷整片区域的统一样式(表头加粗居中、数字格式等);多区域批量走 `batch-set-style`(服务端原子事务) | range 级别(2D 数组或全 range 统一值) |
|
||||
| **`cellStyles`**(`range update` 内) | `--values` 中每个 cell 的 `cellStyles` 字段 | 写值同时附带样式,少量 cell 一步到位 | per-cell 级别 |
|
||||
| **`style`**(richText 片段样式) | `--values` 中 richText 子项(`text`/`link`)的 `style` | 同一单元格内不同文字有不同字体样式 | 文本片段级别 |
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
|
||||
用户说"设置样式/改颜色/设背景色/加粗/居中/换行/字体颜色/字号":
|
||||
- 仅设样式不改值 → `range set-style`
|
||||
- 批量设置不同 range 的样式 → `range batch-set-style --batch ./styles.json`(内部顺序循环调 `update_range`)
|
||||
- 多个区域刷同一组样式(可跨工作表)→ `range batch-set-style --ranges '["Sheet1!A1:B2","Sheet2!D1:D10"]' + 样式 flag`(一次原子提交)
|
||||
- 各区域样式不同 → `range batch-set-style --batch ./styles.json`(同样一次原子提交)
|
||||
- 写值同时附带样式 → `range update --values` 中使用 `cellStyles` 字段(参见 sheet-write-data.md)
|
||||
- 请勿用 `range update --values` 写空/重写来模拟纯样式变更
|
||||
|
||||
@@ -59,6 +60,14 @@ Example:
|
||||
|
||||
# 整片 range 启用自动换行
|
||||
dws sheet range set-style --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:E10" --word-wrap autoWrap
|
||||
|
||||
# 斜体 + 下划线 + 指定字体(整个 range 共用)
|
||||
dws sheet range set-style --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:A10" \
|
||||
--font-style italic --font-line underline --font-family "微软雅黑"
|
||||
|
||||
# 给 A1:D10 加四周实线边框(每格四边=网格线)
|
||||
dws sheet range set-style --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:D10" \
|
||||
--border-styles-json '{"top":{"style":"solid","color":"#000"},"bottom":{"style":"solid","color":"#000"},"left":{"style":"solid","color":"#000"},"right":{"style":"solid","color":"#000"}}'
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
@@ -77,26 +86,49 @@ Flags:
|
||||
--font-weights-json string 字体粗细二维 JSON 数组
|
||||
--word-wrap string 换行方式:overflow/clip/autoWrap(整个 range 共用)
|
||||
--number-format string 数字格式代码,如 General/@/#,##0/#,##0.00/0%/0.00%/yyyy/m/d/h:mm:ss
|
||||
--font-style string 字体样式:normal/italic(斜体,整个 range 共用)
|
||||
--font-line string 字体线条:none/underline/line-through(下划线/删除线,单选,整个 range 共用)
|
||||
--font-family string 字体族,如 Arial / 微软雅黑(整个 range 共用)
|
||||
--border-styles-json string 四边边框 JSON,如 '{"top":{"style":"solid","color":"#000"},"bottom":{"style":"medium"}}'
|
||||
```
|
||||
|
||||
**特性说明**:
|
||||
- 每个样式维度提供两种写法,二选一:`--xxx`(单值刷整个 range,CLI 本地展开为二维数组)vs `--xxx-json`(逐单元格指定,维度需与 `--range` 完全一致)
|
||||
- 至少需传入一个样式参数。单次调用建议:行数 ≤ 1000,单元格总数 ≤ 5000
|
||||
- 枚举值按驼峰书写:`autoWrap`、`bold`、`normal`、`center` 等
|
||||
- 每个可逐格样式维度(bg-color/font-size/h-align/v-align/font-color/font-weight)提供两种写法,二选一:`--xxx`(单值刷整个 range,CLI 本地展开为二维数组)vs `--xxx-json`(逐单元格指定,维度需与 `--range` 完全一致)
|
||||
- 整区共用的标量样式(无 `*-json` 形式):`--word-wrap` / `--number-format` / `--font-style` / `--font-line` / `--font-family` / `--border-styles-json`
|
||||
- `--border-styles-json`:四边 `{top/bottom/left/right}`,每边 `{style, color?}`;`style` 取 `solid/medium/thick/dashed/dotted/double/hair/none` 等(**粗细已含在 style 内**:`solid`=细、`medium`=中、`thick`=粗,无独立 weight 字段);只传的边生效、未传的边保留原状(按边合并)。每条边**只接受 `style` / `color` 两个键**,写错的键(如 `colour`)或非字符串的 `color` 直接报错而不是静默忽略(否则会画出一条没有颜色的边框却报成功);**逐格应用**:对整个 range 每个单元格都画指定的边 = 网格效果(非仅最外框)
|
||||
- `--font-line` 为单选:`underline` 置下划线、`line-through` 置删除线、`none` 清除两者
|
||||
- 至少需传入一个样式参数。单次调用建议:行数 ≤ 1000,单元格总数 ≤ 5000(服务端硬限 30000)
|
||||
- 枚举值按驼峰书写:`autoWrap`、`bold`、`normal`、`center`、`italic` 等
|
||||
- 底层走 `set_cell_range` 的 `cellStyles`(仅设样式、保留原值),因此**纯样式设置可直接作用于含合并单元格的区域**,无需先取消合并
|
||||
|
||||
### 批量设置单元格样式
|
||||
### 批量设置单元格样式(服务端原子事务)
|
||||
```
|
||||
Usage:
|
||||
dws sheet range batch-set-style [flags]
|
||||
Example:
|
||||
# 同一组样式刷多个区域(可跨工作表),一次原子提交
|
||||
dws sheet range batch-set-style --node <NODE_ID> \
|
||||
--ranges '["Sheet1!A1:B2","Sheet2!D1:D10"]' \
|
||||
--bg-color "#FFF2CC" --font-weight bold --font-family "微软雅黑"
|
||||
|
||||
# 每项不同样式:用配置文件
|
||||
dws sheet range batch-set-style --node <NODE_ID> --batch ./styles.json
|
||||
dws sheet range batch-set-style --node <NODE_ID> --batch ./styles.json --continue-on-error
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--batch string 批次配置 JSON 文件路径 (必填)
|
||||
--continue-on-error 遇到失败时继续执行后续条目(默认遇错即停)
|
||||
--ranges string 目标区域 JSON 数组,每项须带工作表前缀,最多 100 项(与 --batch 二选一,同一组样式应用到所有区域)
|
||||
--batch string 批次配置 JSON 文件路径(与 --ranges 二选一,每项可用不同样式)
|
||||
--continue-on-error 遇到失败时继续执行其余项(默认严格事务,整批回滚)
|
||||
(其余样式 flag 与 set-style 完全一致,配合 --ranges 使用)
|
||||
```
|
||||
|
||||
两种入口,二选一:
|
||||
|
||||
| 入口 | 适用 | 说明 |
|
||||
|------|------|------|
|
||||
| `--ranges` | 同一组样式刷多个区域 | 对齐飞书 `+cells-batch-set-style`;每项须带工作表前缀(`"Sheet1!A1:B2"`),**支持跨工作表**,最多 100 项;样式用与 `set-style` 相同的 flag |
|
||||
| `--batch <file>` | 各区域样式不同 | JSON 数组,每项含 `sheetId` + `range` + 该项自己的样式字段 |
|
||||
|
||||
配置文件格式(JSON 数组,每个元素一条批次项):
|
||||
```json
|
||||
[
|
||||
@@ -109,6 +141,10 @@ Flags:
|
||||
"vAlign": "middle",
|
||||
"fontColor": "#333333",
|
||||
"fontWeight": "bold",
|
||||
"fontStyle": "italic",
|
||||
"fontLine": "underline",
|
||||
"fontFamily": "Arial",
|
||||
"borderStylesJson": "{\"top\":{\"style\":\"solid\",\"color\":\"#000\"}}",
|
||||
"wordWrap": "autoWrap",
|
||||
"numberFormat": "General"
|
||||
},
|
||||
@@ -121,9 +157,11 @@ Flags:
|
||||
```
|
||||
|
||||
**特性说明**:
|
||||
- CLI 侧顺序循环逐条调用 `update_range`(非服务端批量),运行时输出 `[N/M]` 进度
|
||||
- 每条记录执行与 `set-style` 一致的校验:至少一项样式字段 + rows ≤ 1000 + rows×cols ≤ 30000 + 枚举合法
|
||||
- 默认遇错即停(返回非 0),`--continue-on-error` 时所有条目跑完再返回首个错误
|
||||
- CLI 把所有区域组装为**一次** `batch_update` 调用,由**服务端原子执行**:默认严格事务,任一项失败则**整批回滚**(不会出现部分区域已改、部分未改)
|
||||
- 所有项在下发前先做本地校验(每项与 `set-style` 一致:至少一项样式字段 + rows ≤ 1000 + rows×cols ≤ 30000 + 枚举合法),**任一项校验不过即整批不下发**
|
||||
- 批量上限:最多 **100 个区域**,且**所有区域累计不超过 200000 个单元格**(一次请求要把全部单元格矩阵建好,累计量才是真正的峰值约束)。超限同样是下发前本地报错、整批不执行;请拆成多次调用
|
||||
- `--continue-on-error` 透传给服务端:遇失败继续执行其余项(软批量)
|
||||
- 底层每项走 `set_cell_range` 的 `cellStyles`/`borderStyles`,因此纯样式批量同样可作用于含合并单元格的区域
|
||||
|
||||
### 合并单元格
|
||||
```
|
||||
@@ -219,7 +257,7 @@ Flags:
|
||||
```bash
|
||||
# ── 工作流 4: 写入数据并设置样式 ──
|
||||
|
||||
# 1. 写入数据(每个单元格必须是 object;数字也写成字符串)
|
||||
# 1. 写入数据
|
||||
dws sheet range update --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:C3" \
|
||||
--values '[[{"type":"text","text":"商品"},{"type":"text","text":"单价"},{"type":"text","text":"数量"}],[{"type":"text","text":"苹果"},{"type":"text","text":"5.5"},{"type":"text","text":"100"}],[{"type":"text","text":"香蕉"},{"type":"text","text":"3.2"},{"type":"text","text":"200"}]]' --format json
|
||||
|
||||
@@ -264,7 +302,9 @@ dws sheet merge-cells --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:C3" --m
|
||||
|
||||
- ★ **`--sheet-id` 获取规范(强制)**:`sheetId` 未知时必须先通过 `dws sheet list --node <NODE_ID> --format json` 查询,禁止凭空编造(如臆测为 `Sheet1`、`sheet1`、`0`、`default` 等)
|
||||
- ★ `range update` / `range set-style` / `range batch-set-style` 单次调用上限(强制):行数 ≤ 1000,单元格总数(行×列)建议≤ 5000(服务端硬限 30000);超限请拆分多次调用。CLI 会在调用前做本地预校验,服务端超 30000 会直接报错
|
||||
- `range set-style` / `range batch-set-style` 的样式枚举按驼峰书写:`wordWrap` 取 `overflow`/`clip`/`autoWrap`,`fontWeight` 取 `bold`/`normal`,`hAlign` 取 `left`/`center`/`right`/`general`,`vAlign` 取 `top`/`middle`/`bottom`;背景色/字体颜色统一使用 `#RRGGBB` 格式
|
||||
- `range set-style` / `range batch-set-style` 的样式枚举按驼峰书写:`wordWrap` 取 `overflow`/`clip`/`autoWrap`,`fontWeight` 取 `bold`/`normal`,`hAlign` 取 `left`/`center`/`right`/`general`,`vAlign` 取 `top`/`middle`/`bottom`,`fontStyle` 取 `normal`/`italic`;背景色/字体颜色统一使用 `#RRGGBB` 格式
|
||||
- `--font-line` 取 `none`/`underline`/`line-through`(单选,非驼峰):`underline` 置下划线、`line-through` 置删除线、`none` 同时清除;`--font-family` 传字体族名(如 `Arial`/`微软雅黑`);`--font-style`/`--font-line`/`--font-family` 均为整区共用标量,无 `*-json` 逐格形式
|
||||
- `range set-style` / `range batch-set-style` 底层走 `set_cell_range` 的 `cellStyles`(仅设样式、保留原值);纯样式设置可直接作用于**含合并单元格**的区域,无需先取消合并(写值到合并区仍会被拦截)
|
||||
- `range update` 支持通过 `cellStyles` 在写值时附带 per-cell 样式,适合少量单元格写值 + 样式一步到位的场景。批量设置整片区域的统一样式时,仍应使用 `set-style` / `batch-set-style`
|
||||
- `merge-cells` 合并时只保留左上角单元格的值,其他单元格的值会被丢弃
|
||||
- `merge-cells` 的 `--merge-type` 不传时默认为 `mergeAll`(合并所有单元格)
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
# 历史版本 (version)
|
||||
|
||||
## 使用场景
|
||||
|
||||
管理钉钉在线电子表格的历史版本快照。当用户说"保存版本/存个快照/看历史版本/版本列表/回滚到某个版本/恢复到之前的表格"时使用。
|
||||
|
||||
- 手动保存当前表格为一个版本快照 → `version save`
|
||||
- 查看表格的历史版本列表(含版本号、名称、创建人、创建时间) → `version list`(别名 `ls`)
|
||||
- 把表格回滚到指定历史版本 → `version revert`(危险操作,默认需二次确认)
|
||||
|
||||
三个命令统一用 `--node` 指定表格文档(ID 或 URL)。回滚用的**版本号 `--version` 从 `version list` 的返回中获取**,禁止臆测。
|
||||
|
||||
## 命令详细参考
|
||||
|
||||
### 保存表格版本快照
|
||||
```
|
||||
Usage:
|
||||
dws sheet version save [flags]
|
||||
Example:
|
||||
dws sheet version save --node SHEET_ID
|
||||
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
```
|
||||
手动为当前在线电子表格生成一个历史版本快照,便于后续查看或回滚。
|
||||
|
||||
### 查看表格历史版本列表
|
||||
```
|
||||
Usage:
|
||||
dws sheet version list [flags]
|
||||
dws sheet version ls [flags]
|
||||
Example:
|
||||
dws sheet version list --node SHEET_ID
|
||||
dws sheet version list --node SHEET_ID --limit 10
|
||||
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--limit int 返回版本数量上限 (可选)
|
||||
--cursor string 分页游标 (可选,游标分页)
|
||||
```
|
||||
返回表格的历史版本列表;回滚前先用它拿到目标 `version`(版本号)。
|
||||
|
||||
### 回滚表格到指定版本
|
||||
```
|
||||
Usage:
|
||||
dws sheet version revert [flags]
|
||||
Example:
|
||||
dws sheet version revert --node SHEET_ID --version 3 --yes
|
||||
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--version int 目标版本号 (必填,从 version list 获取)
|
||||
```
|
||||
把表格回滚到指定历史版本。**危险操作**:会覆盖当前内容,默认弹出二次确认;AI Agent 或脚本执行时可加全局 `--yes` 跳过确认。
|
||||
|
||||
## 上下文传递
|
||||
|
||||
| 操作 | 从返回中提取 | 用于 |
|
||||
|------|-------------|------|
|
||||
| `version list` | `version`(版本号) | 作为 `version revert --version` 的入参 |
|
||||
| `version save` | 版本快照结果 | 确认已生成快照 |
|
||||
| `version revert` | 回滚结果 | 确认回滚完成,回读表格内容验证 |
|
||||
|
||||
## 注意事项
|
||||
|
||||
- ★ 回滚 `version revert` 会**覆盖当前表格内容**,属危险操作,默认二次确认;确认无误再执行,脚本/Agent 场景加 `--yes`
|
||||
- ★ `--version` 必须来自 `version list` 的真实返回,禁止臆测版本号
|
||||
- 底层复用 doc 域的历史版本能力(`save_doc_version` / `list_doc_versions` / `revert_doc_version`),`--node` 传在线电子表格文档即可
|
||||
- 回滚后应用独立读命令(`csv-get` / `range read`)回读确认,避免"写返回不等于完成"
|
||||
@@ -3,7 +3,8 @@
|
||||
## 使用场景
|
||||
|
||||
用户说"创建表格/新建电子表格":
|
||||
- 创建表格文档 → `create`
|
||||
- 创建空表格文档 → `create`
|
||||
- 创建并写入初始数据(可选样式)→ `create-with-data`(`--values` / `--sheets` 必须给一个)
|
||||
|
||||
用户说"看工作表/有哪些工作表/表格结构":
|
||||
- 列出工作表 → `list`
|
||||
@@ -26,13 +27,15 @@
|
||||
- 复制并指定名称 → `copy --name "副本名称"`
|
||||
- 复制并指定位置 → `copy --index N`
|
||||
|
||||
用户说"显示网格线/显示网格/恢复网格线":
|
||||
- 显示网格线 → `show-gridline`(连续多次调用幂等,不报错)
|
||||
|
||||
用户说"隐藏网格线/去掉网格/关闭网格线/展示模式/看板模式":
|
||||
- 隐藏网格线 → `hide-gridline`(连续多次调用幂等,不报错)
|
||||
|
||||
用户说"删除工作表/移除工作表/删掉这个Sheet":
|
||||
- 删除工作表 → `delete-sheet`(不可逆操作,执行前必须向用户确认)
|
||||
|
||||
用户说"显示网格线/隐藏网格线/去掉单元格网格":
|
||||
- 显示网格线 → `show-gridline`
|
||||
- 隐藏网格线 → `hide-gridline`
|
||||
|
||||
## 命令详细参考
|
||||
|
||||
### 创建钉钉表格文档
|
||||
@@ -51,6 +54,76 @@ Flags:
|
||||
|
||||
> **ID 格式约束**:`--folder` 只接受 UUID 格式的 `fileId`(如 `ZgpG2NdyVXYOR2D5UGDok65MJMwvDqPk`)或 alidocs 文件夹 URL。`drive list` 返回中有 `dentryId`(纯数字,如 `218595998810`)和 `fileId`(UUID 格式)两个字段,**必须使用 `fileId`,禁止使用 `dentryId`**,传入纯数字会导致命令失败。
|
||||
|
||||
### 创建表格文档并写入初始数据
|
||||
```
|
||||
Usage:
|
||||
dws sheet create-with-data [flags]
|
||||
Example:
|
||||
dws sheet create-with-data --name "名单" --values '[["姓名","分数"],["张三","90"]]'
|
||||
dws sheet create-with-data --name "报表" --sheets '[{"name":"一月","columns":["项目","金额"],"data":[["房租",5000]]}]'
|
||||
Flags:
|
||||
--name string 表格名称 (必填)
|
||||
--folder string 目标文件夹 ID (dentryUuid 格式) 或 URL;禁止传入纯数字 dentryId
|
||||
--workspace string 目标知识库 ID
|
||||
--values string 初始数据,二维 JSON 数组,写入默认工作表 (与 --sheets 二选一)
|
||||
--sheets string 多工作表 typed table JSON (与 --values 二选一)
|
||||
--styles string 建表时一并应用的视觉处理 JSON(需与 --values 或 --sheets 搭配)
|
||||
```
|
||||
|
||||
建表并写入初始数据的多步编排:建文档 → 探活 → 定位默认工作表 → 写数据 → 回读校验 →(可选)应用样式。**只要一个空表格请用 `dws sheet create`**(单次调用);本命令必须给数据。
|
||||
|
||||
**写入初始数据**(`--values` 与 `--sheets` **二选一,必须给一个**):
|
||||
|
||||
- `--values`:二维 JSON 数组,裸值写入默认工作表 A1 起。适合单表快速建表,无表头/类型语义,内部复用 csv-put 通道,自动识别数字/布尔。单元格只能是字符串/数字/布尔/null;上限 30000 单元格、编码为 CSV 后 2000000 字符。
|
||||
- `--sheets`:typed table 数组,一次创建多个带数据的工作表,内部复用 table-put 通道。每项形如
|
||||
`{"name":"表名","columns":["列1","列2"],"data":[[...]],"dtypes":{...},"formats":{...},"cellStyles":[...]}`;
|
||||
`name`、`columns` **必填**。第一个条目写入默认工作表(自动重命名为其 `name`,避免残留空表),其余按 `name` 自动新建。
|
||||
- 字段名为 camelCase,只接受 `name` / `columns` / `data` / `dtypes` / `formats` / `cellStyles` / `startCell` / `mode`(`overwrite`|`append`) / `header` / `allowOverwrite`;**未知键与 snake_case 变体一律拒绝**(服务端会静默丢弃写错的键,`{"datas":[...]}` 会写出一张只有表头的表却报成功)
|
||||
- **不接受 `sheetId`**:文档此刻还不存在,工作表只能用 `name` 指定
|
||||
- `columns` 为非空字符串数组、列名不可为空/重复(按 trim 后比较);`data` 每行长度须等于 `columns`,单元格只能是字符串/数字/布尔/null
|
||||
- `dtypes` / `formats` 的键须是 `columns` 里的列名(服务端按列名查表,写错既不报错也不生效)
|
||||
- 单表写入上限 30000 单元格(写表头时含表头行)
|
||||
|
||||
**建表时一并应用样式**(`--styles`,顶层键对齐飞书 snake_case,列表项内字段兼容 camelCase;两级都拒绝未知键):
|
||||
|
||||
```json
|
||||
{"styles":[{"name":"表名",
|
||||
"cell_styles":[{"range":"A1:D1","font_weight":"bold","background_color":"#FFF2CC","number_format":"@"}],
|
||||
"row_sizes":[{"range":"1:1","type":"pixel","size":28}],
|
||||
"col_sizes":[{"range":"A:D","type":"pixel","size":120}],
|
||||
"cell_merges":[{"range":"A1:B1","merge_type":"all"}]}]}
|
||||
```
|
||||
|
||||
- 每项至少给 `cell_styles` / `row_sizes` / `col_sizes` / `cell_merges` 之一
|
||||
- 配 `--sheets` 时 styles 的**项数/顺序/name 必须与子表一一对应**;配 `--values` 时只给 1 项(`name` 被忽略)
|
||||
- 数据写入后按 `cell_styles` → `row_sizes` → `col_sizes` → `cell_merges` 顺序执行(**非原子**)
|
||||
- `row_sizes.type`:`pixel`(需 `size`)/ `standard`(恢复默认行高)/ `auto`(按内容自适应)
|
||||
- `col_sizes.type`:`pixel`(需 `size`)/ `standard`(恢复默认列宽)——与飞书一致,**列宽不提供 `auto`**
|
||||
- `size` 必须是正整数(小数会被拒绝而不是静默取整,避免得到与配置不符的行高列宽);`row_sizes.range` 形如 `"1:3"`、`col_sizes.range` 形如 `"A:C"`,带多余字符一律拒绝
|
||||
- `merge_type` 取 `all` / `rows` / `columns`
|
||||
|
||||
**行为要点**:
|
||||
- 所有 JSON 结构、字段类型与枚举都在**创建文档之前**校验(`--sheets` 按 table-put 的输入契约逐字段校验),非法配置直接失败,不会留下白建的空文档
|
||||
- 创建后 CLI 会先探活(新建文档服务端仍在初始化,此时写入可能返回成功但不落盘),再写数据
|
||||
- 写完会回读**首个预期非空单元格**校验确实落盘(不是死盯 A1:`--sheets` 会按 `startCell` / `header` / `mode` 推算实际写入位置);若未落盘会报错并提示用 `csv-put` / `range update` / `table-put` 补写
|
||||
- 报错信息里始终带上已创建的 `nodeId`,便于在部分成功时继续操作同一份文档
|
||||
|
||||
示例:
|
||||
|
||||
```bash
|
||||
# 创建并写入初始数据(默认工作表,裸二维值)
|
||||
dws sheet create-with-data --name "名单" --values '[["姓名","分数"],["张三","90"]]'
|
||||
|
||||
# 创建多个带数据的工作表
|
||||
dws sheet create-with-data --name "报表" --sheets '[{"name":"一月","columns":["项目","金额"],"data":[["房租",5000]]},{"name":"二月","columns":["项目","金额"],"data":[["房租",5000]]}]'
|
||||
|
||||
# 创建 + 写数据 + 一并应用样式(表头加粗黄底、行高、列宽)
|
||||
dws sheet create-with-data --name "带样式" --values '[["姓名","分数"],["张三","90"]]' \
|
||||
--styles '{"styles":[{"name":"Sheet1","cell_styles":[{"range":"A1:B1","font_weight":"bold","background_color":"#FFF2CC"}],"row_sizes":[{"range":"1:1","type":"pixel","size":28}],"col_sizes":[{"range":"A:B","type":"pixel","size":120}]}]}'
|
||||
```
|
||||
|
||||
> `--folder` / `--workspace` 的 ID 格式约束与 `dws sheet create` 完全一致(只接受 UUID 格式的 `fileId` 或 alidocs URL)。
|
||||
|
||||
### 获取全部工作表列表
|
||||
```
|
||||
Usage:
|
||||
@@ -70,13 +143,34 @@ Example:
|
||||
dws sheet info --node <NODE_ID>
|
||||
dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID>
|
||||
dws sheet info --node <NODE_ID> --sheet-id "Sheet1"
|
||||
dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID> --include groups
|
||||
dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID> --include row_heights,col_widths,hidden_rows,hidden_cols
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (不传则返回第一个工作表)
|
||||
--include strings 可选扩展信息,逗号分隔;支持 groups / row_heights / col_widths / hidden_rows / hidden_cols / frozen
|
||||
```
|
||||
|
||||
返回字段中 `mergedRanges` 是当前工作表的合并单元格范围列表(A1 表示法,如 `["C7:D11"]`)。它属于工作表结构/布局元数据:读写单元格内容前,如需判断表头、分组标题、续写位置或避开合并冲突,应先看 `sheet info`,不要在 `range read` / `csv-get` 的单元格值里寻找合并信息。
|
||||
|
||||
返回字段中 `frozenRowCount` / `frozenColumnCount` 是冻结行列数量:冻结总是从工作表顶部第 1 行、左侧第 A 列开始连续计算;`0` 表示未冻结。它们是工作表级元数据,默认随 `sheet info` 返回,不需要额外 `include`。
|
||||
|
||||
最后非空数据边界通过 `nonEmptyRange` 返回,字段均为 A1/UI 语义:`range` 是从 `A1` 到最后非空单元格的范围,`lastCell` 是最后非空单元格地址,`lastRow` 是 1-based 行号,`lastColumn` 是列字母。空表时 `nonEmptyRange` 为 `null`。不要使用旧的 0-based 字段 `lastNonEmptyRow` / `lastNonEmptyColumn`。
|
||||
|
||||
需要读取行列分组时,加 `--include groups`。返回字段:
|
||||
- `rowGroups`:行分组列表,单项包含 `range`、`startRow`、`endRow`、`count`、`level`、`collapsed`
|
||||
- `columnGroups`:列分组列表,单项包含 `range`、`startColumn`、`endColumn`、`count`、`level`、`collapsed`
|
||||
|
||||
其中 `range` 使用 A1 行/列范围(如 `"3:7"` / `"C:F"`),起止行号为 1-based,列使用字母;`level` 是 1-based 展示层级,不返回 `depth`;`collapsed` 表示当前折叠状态。`range read` / `csv-get` 不返回 `mergedRanges`、冻结或分组等结构元数据。
|
||||
|
||||
需要读取行高、列宽、隐藏行列时,按需加对应 `--include` 值(可组合,逗号分隔)。返回字段:
|
||||
- `--include row_heights` → `rowHeights`(逐条行高,单项 `{row, pixelSize}`,`row` 为 1-based)+ `defaultRowHeight`(默认行高像素)
|
||||
- `--include col_widths` → `colWidths`(逐条列宽,单项 `{column, pixelSize}`,`column` 为列字母)+ `defaultColumnWidth`(默认列宽像素)
|
||||
- `--include hidden_rows` → `hiddenRows`(隐藏行区间列表,单项 `{startRow, endRow}`,1-based,连续隐藏行合并为一个区间)
|
||||
- `--include hidden_cols` → `hiddenCols`(隐藏列区间列表,单项 `{startColumn, endColumn}`,列字母,连续隐藏列合并为一个区间)
|
||||
|
||||
注意:`rowHeights` / `colWidths` 只返回**显式设置过**尺寸的行列(未自定义的行列不出现,用 `defaultRowHeight` / `defaultColumnWidth` 兜底);隐藏行列即使未改尺寸也会出现在 `hiddenRows` / `hiddenCols`。`frozen` 也在 include 白名单中,但冻结字段本就默认返回,传 `frozen` 与否结果一致。
|
||||
|
||||
### 新建工作表
|
||||
```
|
||||
Usage:
|
||||
@@ -112,16 +206,14 @@ Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
--name string 新名称,最长 100 字符,不能包含 / \ ? * [ ] :
|
||||
--title string --name 的别名(兼容)
|
||||
--index int 新位置(从 0 开始)
|
||||
--hidden --hidden=true 隐藏,--hidden=false 取消隐藏
|
||||
--tab-color string 工作表标签颜色,Hex 如 #FF0000;传空字符串清除颜色
|
||||
--frozen-row-count int 冻结行数,0 表示取消冻结
|
||||
--frozen-column-count int 冻结列数,0 表示取消冻结
|
||||
```
|
||||
|
||||
更新工作表名称、位置、隐藏状态、标签颜色、冻结行列。
|
||||
`--name`(别名 `--title`)/ `--index` / `--hidden` / `--tab-color` / `--frozen-row-count` / `--frozen-column-count` 至少提供一个;多个属性可同时传入,将在同一次请求中更新。
|
||||
更新工作表名称、位置、隐藏状态、冻结行列。
|
||||
`--name` / `--index` / `--hidden` / `--frozen-row-count` / `--frozen-column-count` 至少提供一个;多个属性可同时传入,将在同一次请求中更新。
|
||||
|
||||
注意:
|
||||
- 至少需要保留一个可见的工作表,不能将所有工作表都隐藏
|
||||
@@ -169,17 +261,33 @@ Flags:
|
||||
- 不能删除隐藏的工作表(需先通过 `sheet update --hidden false` 取消隐藏再删除)
|
||||
- 不能删除最后一个可见工作表(至少保留一个可见工作表)
|
||||
|
||||
### 显示或隐藏网格线
|
||||
### 显示工作表网格线
|
||||
```
|
||||
Usage:
|
||||
dws sheet show-gridline [flags]
|
||||
Example:
|
||||
dws sheet show-gridline --node <NODE_ID> --sheet-id <SHEET_ID>
|
||||
dws sheet hide-gridline --node <NODE_ID> --sheet-id <SHEET_ID>
|
||||
dws sheet show-gridline --node <NODE_ID> --sheet-id "Sheet1"
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
```
|
||||
|
||||
这两个命令只修改指定工作表的网格线显示状态,不修改单元格内容或边框样式。执行后可用同一命令反向恢复。
|
||||
### 隐藏工作表网格线
|
||||
```
|
||||
Usage:
|
||||
dws sheet hide-gridline [flags]
|
||||
Example:
|
||||
dws sheet hide-gridline --node <NODE_ID> --sheet-id <SHEET_ID>
|
||||
dws sheet hide-gridline --node <NODE_ID> --sheet-id "Sheet1"
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
```
|
||||
|
||||
切换子表网格线显隐;二态语义在命令名里,无需额外参数(同 `update --hidden` / `update --hidden=false` 的隐藏/显示工作表模式)。
|
||||
网格线默认显示;隐藏后工作表背景为纯白色,适合截图、演示、仪表盘/看板场景(不影响打印和数据)。
|
||||
连续多次 show 或多次 hide 均为幂等操作,不会报错。
|
||||
|
||||
## 核心工作流
|
||||
|
||||
@@ -192,13 +300,16 @@ dws sheet create --name "销售数据" --format json
|
||||
# 2. 查看工作表列表 — 提取 sheetId
|
||||
dws sheet list --node <NODE_ID> --format json
|
||||
|
||||
# 3. 写入表头和数据(每个单元格必须是 object;数字也写成字符串)
|
||||
# 3. 写入表头和数据
|
||||
dws sheet range update --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:C1" \
|
||||
--values '[[{"type":"text","text":"姓名"},{"type":"text","text":"部门"},{"type":"text","text":"销售额"}]]' --format json
|
||||
|
||||
dws sheet range update --node <NODE_ID> --sheet-id <SHEET_ID> --range "A2:C4" \
|
||||
--values '[[{"type":"text","text":"张三"},{"type":"text","text":"销售部"},{"type":"text","text":"50000"}],[{"type":"text","text":"李四"},{"type":"text","text":"市场部"},{"type":"text","text":"38000"}],[{"type":"text","text":"王五"},{"type":"text","text":"销售部"},{"type":"text","text":"62000"}]]' --format json
|
||||
|
||||
# 4. 独立回读实际写入范围
|
||||
dws sheet range read --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:C4" --format json
|
||||
|
||||
# ── 工作流 2: 读取已有表格数据 ──
|
||||
|
||||
# 1. 获取工作表列表
|
||||
@@ -218,7 +329,7 @@ dws sheet range read --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:D10" --f
|
||||
# 1. 新建工作表
|
||||
dws sheet new --node <NODE_ID> --name "汇总" --format json
|
||||
|
||||
# 2. 在新工作表中写入汇总公式(公式写在 text,以 = 开头)
|
||||
# 2. 在新工作表中写入汇总公式
|
||||
dws sheet range update --node <NODE_ID> --sheet-id <NEW_SHEET_ID> --range "A1:B1" \
|
||||
--values '[[{"type":"text","text":"指标"},{"type":"text","text":"数值"}]]' --format json
|
||||
|
||||
@@ -233,7 +344,7 @@ dws sheet range update --node <NODE_ID> --sheet-id <NEW_SHEET_ID> --range "A2:B2
|
||||
| `create` | `nodeId` | list / info / new / range read / range update / find 的 --node |
|
||||
| `list` | 工作表的 `sheetId` | info / range read / range update / find 的 --sheet-id |
|
||||
| `new` | 新工作表的 `sheetId` | range read / range update / find 的 --sheet-id |
|
||||
| `info` | `rowCount` / `nonEmptyRange.range` / `nonEmptyRange.lastRow` / `nonEmptyRange.lastColumn` / `mergedRanges` | 确定数据范围、追加写入起始行、判断合并单元格结构 |
|
||||
| `info` | `rowCount` / `nonEmptyRange.range` / `nonEmptyRange.lastRow` / `nonEmptyRange.lastColumn` / `mergedRanges` / `frozenRowCount` / `frozenColumnCount` / `rowGroups` / `columnGroups` / `rowHeights` / `colWidths` / `hiddenRows` / `hiddenCols` | 确定数据范围、追加写入起始行、判断合并单元格结构、回读冻结与行列分组、回读行高列宽与隐藏行列 |
|
||||
|
||||
## 注意事项
|
||||
|
||||
@@ -257,4 +368,6 @@ dws sheet range update --node <NODE_ID> --sheet-id <NEW_SHEET_ID> --range "A2:B2
|
||||
- `delete-sheet` 为不可逆操作,执行前必须向用户确认
|
||||
- `delete-sheet` 不能删除隐藏的工作表,需先通过 `update --hidden=false` 取消隐藏再删除
|
||||
- `delete-sheet` 不能删除最后一个可见工作表,至少保留一个可见工作表
|
||||
- `show-gridline` / `hide-gridline` 为幂等写操作:连续调用同一命令不会报错,适合 Agent 不确定当前状态时直接调用
|
||||
- `show-gridline` / `hide-gridline` 仅控制网格线视觉显示,不影响数据、打印、冻结行列等任何其他属性
|
||||
- ★ 关键区分: sheet(电子表格/单元格读写) vs aitable(AI多维表/结构化记录/字段定义) vs doc(文档编辑/阅读)
|
||||
|
||||
@@ -3,12 +3,18 @@
|
||||
## 使用场景
|
||||
|
||||
用户说"写数据/填表/更新单元格/写入公式":
|
||||
- 从 DataFrame/结构化对象一次写入一个或多个工作表 → `table-put`
|
||||
- 更新数据 → `range update`
|
||||
- 写入公式前先读 [sheet-formula](./sheet-formula.md);写完必须回读公式文本并运行 `formula-verify`,关键业务数值还要抽样对账,不能只看写入返回成功
|
||||
- 【强制】`--sheet-id` 必填:即使是单工作表也不能省略,不要参照 `range read` 的默认行为;未知时先执行 `dws sheet list --node <NODE_ID> --format json` 获取 `sheetId`,禁止凭空臆测为 `Sheet1`、`sheet1`、`0`、`default` 等
|
||||
- 注意:如果用户的目的是替换文本、移动行列、追加空行空列、清空区域、排序、填充、复制区域或移动区域,请勿使用 `range update`,必须使用对应的专用命令(`replace`/`move-dimension`/`add-dimension`/`range clear`/`range sort`/`range fill`/`range copy-to`/`range move-to`)
|
||||
- **批量 CSV 值/公式写入优先用 `csv-put`**:当写入场景同时满足以下条件时,必须优先使用 `csv-put` 而非 `range update`:(1) 不需要超链接、dataValidation、cellStyles 或 richText;(2) 数据量较大(超过 5 行或超过 20 个单元格);(3) 数据来源为表格/CSV 文本/结构化文本。`csv-put` 无需手动构造二维 JSON 数组,字段值以 `=` 开头时按公式解析,并支持自动扩容
|
||||
|
||||
用户说"写入结构化 table/dataframe/带列类型和格式的数据/跨 sheet 写入表格":
|
||||
- 写入结构化 table → `table-put`
|
||||
- `table-put` 的 `--sheets` 是 table spec JSON,支持一次写入一个或多个工作表;适合有明确 `columns` / `data` / `dtypes` / `formats` 的数据
|
||||
- table spec 较长或来自文件时,优先用 `--sheets @table.json`,避免 shell 转义长 JSON 出错
|
||||
- 如果只是一段 CSV 文本且没有 dtype/format 需求,用 `csv-put` 更简单(可含 `=` 开头的公式);如果需要超链接、dataValidation、richText 或 cellStyles,用 `range update`
|
||||
|
||||
用户说"追加数据/添加行/在末尾加数据/新增记录":
|
||||
- 追加数据 → `append`
|
||||
|
||||
@@ -17,38 +23,34 @@
|
||||
- 与 `range update` 的区别:`csv-put` 接受 CSV 文本直接写入,无需手动构造二维 JSON 数组;适合大批量值或公式写入,但不支持富格式对象
|
||||
- 与 `append` 的区别:`csv-put` 写入指定位置(--start-cell),`append` 在末尾追加
|
||||
|
||||
**与现有写入能力的区别**:
|
||||
|
||||
- `range update` 面向精确单元格对象写入:适合少量公式、超链接、dataValidation、richText、少量 cellStyles 和 `{}` 跳过;必须自己提供 `--sheet-id`、`--range` 和维度完全匹配的二维 cell 对象
|
||||
- `append` 面向简单追加行:自动定位到末尾,只写原始值,不支持样式、公式、超链接或数据验证
|
||||
- `csv-put` 面向大批量 CSV 值/公式导入:输入 CSV 文本,写入指定起点;字段值以 `=` 开头时按公式解析,前加单引号时写入以 `=` 开头的字面文本;不保留 dtype/format 协议,也不支持富格式
|
||||
- `table-put` 面向 dataframe/table 数据交换:输入 `columns` / `data` / `dtypes` / `formats`,可一次写多个 sheet,适合和 `table-get` 往返;不支持 dataValidation、hyperlink、richText、附件或图片
|
||||
|
||||
**四种写入命令能力对比**:
|
||||
|
||||
| 能力 | `table-put` | `range update` | `append` | `csv-put` |
|
||||
|------|-------------|----------------|----------|-----------|
|
||||
| 多工作表结构化写入 | 支持 | 不支持 | 不支持 | 不支持 |
|
||||
| columns / dtypes / formats | 支持 | 不支持 | 不支持 | 不支持 |
|
||||
| 公式(`=` 开头) | 按 dtype/底层能力 | 支持 | 不支持 | 支持;前导单引号写入以 `=` 开头的字面文本 |
|
||||
| 单元格级超链接(`hyperlink`) | 不使用此命令 | 支持 | 不支持 | 不支持 |
|
||||
| 富文本(片段链接/附件/图片) | 不使用此命令 | 支持 | 不支持 | 不支持 |
|
||||
| 原始值(纯数字/字符串) | 支持 | 支持 | 支持 | 支持 |
|
||||
| 自动定位末尾 | mode=append | 不支持 | 支持 | 不支持 |
|
||||
| 自动扩容行列 | 支持 | 不支持 | 支持 | 支持 |
|
||||
| 能力 | `range update` | `append` | `csv-put` | `table-put` |
|
||||
|------|---------------|----------|-----------|-------------|
|
||||
| 公式(`=` 开头) | 支持 | 不支持 | 支持;前导单引号写入以 `=` 开头的字面文本 | 不作为公式协议;公式请用 `range update` 或 `csv-put` |
|
||||
| 单元格级超链接(`hyperlink`) | 支持 | 不支持 | 不支持 | 不支持 |
|
||||
| 富文本(片段链接/附件/图片) | 支持 | 不支持 | 不支持 | 不支持 |
|
||||
| richText 片段样式(bold/color) | 支持 | 不支持 | 不支持 | 不支持 |
|
||||
| `cellStyles`(背景色/字号/对齐等 cell-level 样式) | 支持 | 不支持 | 不支持 | 支持基础 cell-level 样式 |
|
||||
| `{}` 跳过(保留原值) | 支持 | 不适用 | 不适用 | 不支持,按 table 矩阵写入 |
|
||||
| `dataValidation`(下拉/复选框) | 支持 | 不支持 | 不支持 | 不支持 |
|
||||
| 原始值(纯数字/字符串/布尔/null) | 支持 | 支持 | 支持 | 支持 |
|
||||
| 列级 dtype / number format | 手工写 cellStyles | 不支持 | 自动识别为主 | 支持 `dtypes` / `formats` |
|
||||
| 自动定位末尾 | 不支持 | 支持 | 不支持 | `mode:"append"` 支持 |
|
||||
| 自动扩容行列 | 不支持 | 支持 | 支持 | 支持 |
|
||||
| 跨 sheet 一次写入 | 不支持 | 不支持 | 不支持 | 支持 `sheets[]` |
|
||||
|
||||
公式写入与校验的完整流程见 [sheet-formula](./sheet-formula.md)。写公式后先回读 `formula` 模式确认公式文本,再运行 `formula-verify` 聚合扫描错误;需要确认业务数值时继续回读 `raw_value` 抽样对账。
|
||||
|
||||
## 命令详细参考
|
||||
|
||||
### 写入结构化 table 数据
|
||||
```
|
||||
Usage:
|
||||
dws sheet table-put [flags] # 别名: dws sheet table-write
|
||||
Example:
|
||||
dws sheet table-put --node <NODE_ID> \
|
||||
--sheets '[{"name":"Data","columns":["name","score"],"data":[["Alice",95]],"dtypes":{"score":"float64"}}]'
|
||||
|
||||
dws sheet table-put --node <NODE_ID> --sheets @table.json
|
||||
cat table.json | dws sheet table-put --node <NODE_ID> --sheets -
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheets string sheet table JSON、@文件路径 或 - 表示 stdin (必填)
|
||||
```
|
||||
|
||||
`--sheets` 接受 JSON 数组、`{"sheets":[...]}` 包装对象或单个 sheet 对象,CLI 会统一转换为非空数组。每个 sheet 至少需要 `columns`,并提供 `sheetId` 或 `name`;`name` 必须非空且少于 31 个字符。写入后必须用 `table-get` 回读验证。`table-get/table-put` 不支持放入 `sheet batch-update`。
|
||||
|
||||
### 更新工作表指定区域内容
|
||||
```
|
||||
Usage:
|
||||
@@ -80,7 +82,7 @@ Flags:
|
||||
--values string 单元格内容,二维 JSON 数组 (必填);每个元素必须是 object:{type:text,text:...}、{type:richText,texts:[...]}、{dataValidation:...}、{cellStyles:...}、{hyperlink:...} 或 {}(详见下文 values 参数格式说明)
|
||||
```
|
||||
|
||||
**合并单元格注意(`range update`)**:这里说的是 `range update` 写入单元格对象这一路径,不是所有写入命令的统一行为。目标范围与已有合并区域冲突时,MCP 服务端会拦截并返回 `MERGED_CELLS_CONFLICT` 错误,错误消息中通常会列出具体冲突的合并区域地址。收到此错误时按以下流程处理:
|
||||
**合并单元格注意(`range update`)**:这里说的是 `range update` 写入单元格对象这一路径,不是所有写入命令的统一行为。目标范围与已有合并区域冲突时,服务端会拦截并返回 `MERGED_CELLS_CONFLICT` 错误,错误消息中通常会列出具体冲突的合并区域地址。收到此错误时按以下流程处理:
|
||||
1. 从错误消息中获取冲突的合并区域地址(如 `A1:B2, C3:D4`),或通过 `dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID> --format json` 查询完整的合并区域列表(`mergedRanges` 数组)
|
||||
2. 用 `dws sheet unmerge-cells --range <冲突区域>` 取消这些合并
|
||||
3. 执行 `range update` 写入数据
|
||||
@@ -94,6 +96,8 @@ Flags:
|
||||
|
||||
**范围职责**:`range update` 负责写入单元格内容(原始值/公式/富文本对象),并支持通过 `cellStyles` 附带 per-cell 样式。如需批量设置整片区域的样式(不写值),请使用 `dws sheet range set-style`。
|
||||
|
||||
**公式校验要求**:公式用 `{"type":"text","text":"=..."}` 写入。写完后先执行 `range read --value-render-option formula` 确认公式文本,再执行 `formula-verify` 聚合扫描错误;关键业务结果继续用 `range read --value-render-option raw_value` 抽样对账。详见 [sheet-formula](./sheet-formula.md)。
|
||||
|
||||
### 在工作表末尾追加数据
|
||||
```
|
||||
Usage:
|
||||
@@ -116,14 +120,12 @@ Flags:
|
||||
Usage:
|
||||
dws sheet csv-put [flags]
|
||||
Example:
|
||||
# 内联多行 CSV:必须用 $'...' 让 \n 变成真换行;普通单引号 '...\n...' 里的 \n 是字面量,会写成一行含字面 \n 的错误数据
|
||||
dws sheet csv-put --node <NODE_ID> --sheet-id <SHEET_ID> --start-cell A1 \
|
||||
--csv $'name,score\nAlice,95\nBob,87'
|
||||
--csv 'name,score\nAlice,95\nBob,87'
|
||||
|
||||
dws sheet csv-put --node <NODE_ID> --sheet-id <SHEET_ID> --start-cell A1 \
|
||||
--csv "=1+1,'=1+1"
|
||||
|
||||
# 多行数据推荐用 @文件,最稳妥
|
||||
dws sheet csv-put --node <NODE_ID> --sheet-id <SHEET_ID> --start-cell B2 \
|
||||
--csv @data.csv --allow-overwrite
|
||||
|
||||
@@ -143,7 +145,7 @@ Flags:
|
||||
将 RFC 4180 格式的 CSV 文本写入指定工作表的指定单元格位置。
|
||||
- **分隔符必须是英文逗号 `,`**(ASCII 0x2C),禁止使用中文逗号 `,`(U+FF0C)。中文逗号不会被识别为分隔符,会导致整行被写入同一个单元格。生成 CSV 内容时务必检查分隔符
|
||||
- 写入值和公式,不支持样式/批注。字段值以 `=` 开头时默认按公式解析;如需写入以 `=` 开头的字面文本,在字段值前加单引号(例如 `'=1+1`)
|
||||
- 数字/日期/百分数由表格引擎自动识别类型(如 `95` 存为数字,`2025-03-01` 存为日期)
|
||||
- 数字/日期/百分数由表格系统自动识别类型(如 `95` 存为数字,`2025-03-01` 存为日期)
|
||||
- 自动扩容行列:CSV 数据超出当前工作表维度时自动追加行/列
|
||||
- 与 `range update` 不同,目标区域如含合并单元格,`csv-put` 会打散合并并写入 CSV 数据
|
||||
- 若需要保留原有合并结构,写入前先用 `sheet info` 记录 `mergedRanges`,写入后用 `merge-cells` 恢复对应区域
|
||||
@@ -152,6 +154,121 @@ Flags:
|
||||
- CSV 文本上限 2M 字符,单元格总数上限 30000
|
||||
- 特殊字符处理:CLI 会自动过滤 `\r`(Windows 换行符)和 BOM(UTF-8 文件头标记),Excel/Windows 导出的 CSV 可直接使用;如 CSV 数据中含零宽字符(U+200B 等)或 Bidi 控制符,CLI 会拒绝并报错
|
||||
|
||||
### 写入结构化 table 数据
|
||||
```
|
||||
Usage:
|
||||
dws sheet table-put [flags]
|
||||
Example:
|
||||
dws sheet table-put --node <NODE_ID> \
|
||||
--sheets '[{"name":"Sheet1","columns":["name","score"],"data":[["Alice",95]],"dtypes":{"score":"float64"},"formats":{"score":"0"}}]'
|
||||
|
||||
dws sheet table-put --node <NODE_ID> --sheets @table.json
|
||||
cat table.json | dws sheet table-put --node <NODE_ID> --sheets -
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheets string sheet table JSON、@文件路径 或 - 表示 stdin (必填)
|
||||
```
|
||||
|
||||
`--sheets` 支持三种形态:
|
||||
```json
|
||||
[
|
||||
{"name":"Sheet1","columns":["name"],"data":[["Alice"]]}
|
||||
]
|
||||
```
|
||||
```json
|
||||
{
|
||||
"sheets": [
|
||||
{"name":"Sheet1","columns":["name"],"data":[["Alice"]]}
|
||||
]
|
||||
}
|
||||
```
|
||||
```json
|
||||
{"name":"Sheet1","columns":["name"],"data":[["Alice"]]}
|
||||
```
|
||||
|
||||
**单个 sheet spec 字段**:
|
||||
|
||||
| 字段 | 必填 | 说明 |
|
||||
|------|------|------|
|
||||
| `name` | 与 `sheetId` 二选一 | 工作表名称。名称已存在时写入已有 sheet;不存在时创建同名 sheet |
|
||||
| `sheetId` | 与 `name` 二选一 | 工作表 ID;传入时优先于 `name`,不会按 `name` 创建新 sheet |
|
||||
| `startCell` | 否 | overwrite 起始单元格,或 append 起始列;默认 `A1` |
|
||||
| `mode` | 否 | `overwrite`(默认)或 `append` |
|
||||
| `header` | 否 | 是否写入表头。overwrite 默认 true;append 默认 false;append 到空表且未显式指定时写表头 |
|
||||
| `allowOverwrite` | 否 | 是否允许覆盖已有值。默认 true;显式传 false 时,目标区域已有值会报错 |
|
||||
| `columns` | 是 | 有序列名数组;不可为空、不可重复、不可包含空列名 |
|
||||
| `data` | 否 | 行优先二维数组,默认 `[]`;每行宽度必须等于 `columns.length`;值支持 string / number / boolean / null。写入空位建议传 `null`;若复用 `table-get` 结果,`data[][]` 中的 `{}` 表示空位 / 空单元格,按 `null` 对待 |
|
||||
| `dtypes` | 否 | 按列名指定 pandas-style dtype;默认 `{}`,未指定列按 object/string 写入。普通文本建议声明 `object`;`string` 会按文本写入,但 `table-get` 回读通常仍是 `object` |
|
||||
| `formats` | 否 | 按列名指定 number format code;默认 `{}`,系统按 dtype 补日期/文本默认格式 |
|
||||
| `cellStyles` | 否 | 基础 cell-level 样式,默认不设置样式;支持二维样式矩阵,或按列名指定样式对象。字段范围与下文 `cellStyles 子结构` 一致 |
|
||||
|
||||
**完整示例**:
|
||||
```json
|
||||
{
|
||||
"sheets": [
|
||||
{
|
||||
"name": "销售",
|
||||
"startCell": "A1",
|
||||
"mode": "overwrite",
|
||||
"allowOverwrite": true,
|
||||
"columns": ["日期", "金额", "渠道"],
|
||||
"data": [
|
||||
["2026-07-06", 1500.5, "门店"],
|
||||
["2026-07-07", 2300.75, "线上"]
|
||||
],
|
||||
"dtypes": {
|
||||
"日期": "datetime64[ns]",
|
||||
"金额": "float64",
|
||||
"渠道": "object"
|
||||
},
|
||||
"formats": {
|
||||
"日期": "yyyy-mm-dd",
|
||||
"金额": "¥#,##0.00"
|
||||
},
|
||||
"cellStyles": {
|
||||
"金额": {"numberFormat": "¥#,##0.00"}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**dtype 与 format 规则**:
|
||||
- `datetime64[ns]` / `date` 按日期写入;日期值建议使用 ISO 字符串(如 `2026-07-06`),未传 format 时默认 `yyyy-mm-dd`
|
||||
- `bool` / `boolean` 按布尔写入
|
||||
- `int*` / `uint*` / `float*` / `complex*` 按数值写入;读回时数值列通常统一表现为 `float64`
|
||||
- `object` 是普通文本列的推荐 dtype;`string` 等其他 dtype 按字符串列处理,未传 format 时默认文本格式 `@`。读回时文本列通常表现为 `object`,不要期待返回 `string`
|
||||
- `formats` 使用表格 number format code,含义与 `range set-style --number-format` 一致
|
||||
- 大整数精度保护:超过 `9007199254740991` 的整数、长数字 ID、订单号、手机号、SKU 等需要逐位精确的值,必须按文本写入。`table-put` 中即使把值写成字符串,只要 dtype 声明为 `int64` / `uint64` / `float64`,链路仍会按 number 处理并可能丢精度;应使用字符串值 + `object` dtype + 文本格式 `@`
|
||||
|
||||
**大整数/长数字 ID 示例**:
|
||||
```json
|
||||
{
|
||||
"name": "订单",
|
||||
"columns": ["order_id", "amount"],
|
||||
"data": [["9007199254740993", 128.5]],
|
||||
"dtypes": {"order_id": "object", "amount": "float64"},
|
||||
"formats": {"order_id": "@", "amount": "#,##0.00"}
|
||||
}
|
||||
```
|
||||
|
||||
**返回字段说明**:
|
||||
- `sheets` — 写入结果数组,每项对应一个 sheet spec
|
||||
- `name` / `sheetId` — 实际写入的工作表名称与 ID
|
||||
- `range` — 实际写入范围
|
||||
- `dataRows` — 写入的数据行数,不含表头
|
||||
- `columns` — 写入列数
|
||||
- `writes` — 实际写入次数
|
||||
- `mode` — 实际写入模式,`overwrite` 或 `append`
|
||||
|
||||
**限制与边界**:
|
||||
- `table-put` 支持跨 sheet:一个 `sheets[]` 可包含多个 sheet spec
|
||||
- 单次 table 写入单元格数上限 30000,计算包含表头行;超过上限需拆分
|
||||
- 大整数和长数字标识符不应声明为 `int64` / `uint64`。例如 `9007199254740993` 按数值写入会回读为 `9007199254740992`;要保精度必须写成 `"9007199254740993"`,并把该列声明为 `object` 且设置 `formats: {"列名":"@"}`
|
||||
- `table-put` 不支持 dataValidation、hyperlink、richText、附件、单元格图片;这些能力用 `range update` / `write-image`
|
||||
- 样式能力以 `cellStyles` 基础 cell-level 样式为准;复杂结构样式、合并单元格、行高列宽请另用 `range set-style` / `merge-cells` / `update-dimension`
|
||||
- 写入后需要用 `table-get` 回读 `columns` / `data` / `dtypes` / `formats` 校验;`table-get` 不返回 `cellStyles`,需要校验 table 写入样式时用 `range read`;需要校验合并或结构元数据时用 `sheet info`
|
||||
|
||||
## values 参数格式说明
|
||||
|
||||
`range update` 只接受 `--values` 一个数据参数,为二维 JSON 数组,第一维为行,第二维为列。每个 cell 是以下之一:
|
||||
@@ -187,7 +304,7 @@ Flags:
|
||||
`hyperlink` 作用于整个单元格,适合“这个单元格整体可点击跳转”的场景。它和 richText 的片段级 `link` 不同。
|
||||
|
||||
> **hyperlink 三种语义**:
|
||||
> - **不传 `hyperlink` 字段** → 保留原超链接(引擎自动 readback 回写)
|
||||
> - **不传 `hyperlink` 字段** → 保留原超链接(系统自动保留)
|
||||
> - **`hyperlink: {"type":"none"}`** → 显式清除单元格超链接
|
||||
> - **`hyperlink: {"type":"path"/"sheet"/"range", link, text?}`** → 写新超链接(覆盖)
|
||||
>
|
||||
@@ -208,7 +325,7 @@ Flags:
|
||||
|
||||
注意:
|
||||
- 不传 `hyperlink` 字段同于 “保留原超链接”,无需先 read 再回传
|
||||
- Agent 调用统一使用 `hyperlink: {type:"none"}` 清除超链接;底层 REST 兼容 `hyperlink:null`,但 MCP schema / 网关可能过滤 null 字段,不要把 null 当默认写法
|
||||
- Agent 调用统一使用 `hyperlink: {type:"none"}` 清除超链接;不要把 `hyperlink:null` 当默认写法,避免空字段在调用链路中被过滤后语义不清
|
||||
- `hyperlink` 可以不带 `type/text` cell 单独出现,用于只设置或清理链接并保留原值
|
||||
- 不要把 `hyperlink` 和 `type:"richText"` 混用;整格链接用 `hyperlink`,片段链接用 richText 子项 `type:"link"`
|
||||
|
||||
@@ -341,7 +458,7 @@ dws sheet range update --node NODE_ID --sheet-id SHEET_ID --range "A1:C1" \
|
||||
|
||||
### 重要约束
|
||||
|
||||
- 不再支持 `{type:"number"}` / `{type:"boolean"}` / `{type:"null"}` —— MCP `complexValues` 仅接受 `text` / `richText` 两种 type,或 `{}` 跳过。数字 / 布尔走 `{type:"text","text":"<字符串形式>"}`
|
||||
- 不再支持 `{type:"number"}` / `{type:"boolean"}` / `{type:"null"}` —— 当前单元格对象协议仅接受 `text` / `richText` 两种 type,或 `{}` 跳过。数字 / 布尔走 `{type:"text","text":"<字符串形式>"}`
|
||||
- 不支持直接传入原始值(字符串、数字、布尔、null、空字符串);`null` 不等同于 `{}`,`null` 会报错
|
||||
- 维度必须与 `--range` 范围完全一致,例如 `--range "A1:B3"` 需要 3 行 2 列的数组
|
||||
- 清理整格超链接使用 `{"hyperlink":{"type":"none"}}`;不要使用 `{"hyperlink":null}` 作为 agent 默认调用形态
|
||||
@@ -366,6 +483,9 @@ dws sheet range update --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:C1" \
|
||||
dws sheet range update --node <NODE_ID> --sheet-id <SHEET_ID> --range "A2:C4" \
|
||||
--values '[[{"type":"text","text":"张三"},{"type":"text","text":"销售部"},{"type":"text","text":"50000"}],[{"type":"text","text":"李四"},{"type":"text","text":"市场部"},{"type":"text","text":"38000"}],[{"type":"text","text":"王五"},{"type":"text","text":"销售部"},{"type":"text","text":"62000"}]]' --format json
|
||||
|
||||
# 4. 独立回读实际写入范围
|
||||
dws sheet range read --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:C4" --format json
|
||||
|
||||
# ── 工作流 4: 写入数据并设置样式 ──
|
||||
|
||||
# 1. 写入数据
|
||||
@@ -407,12 +527,13 @@ dws sheet append --node <NODE_ID> --sheet-id <SHEET_ID> \
|
||||
|
||||
| 操作 | 从返回中提取 | 用于 |
|
||||
|------|-------------|------|
|
||||
| `create` | `nodeId` | list / info / new / range update / append / csv-put 的 --node |
|
||||
| `list` | 工作表的 `sheetId` | range update / append / csv-put 的 --sheet-id |
|
||||
| `new` | 新工作表的 `sheetId` | range update / append / csv-put 的 --sheet-id |
|
||||
| `create` | `nodeId` | list / info / new / range update / append / csv-put / table-put 的 --node |
|
||||
| `list` | 工作表的 `sheetId` | range update / append / csv-put 的 --sheet-id;table-put 的 sheetId |
|
||||
| `new` | 新工作表的 `sheetId` | range update / append / csv-put 的 --sheet-id;table-put 的 sheetId |
|
||||
| `info` | `rowCount` / `nonEmptyRange.range` / `nonEmptyRange.lastRow` / `nonEmptyRange.lastColumn` / `mergedRanges` | 确定数据范围、追加写入起始行、识别合并单元格结构 |
|
||||
| `append` | `a1Notation` 追加数据所在范围 | 确认追加位置 |
|
||||
| `csv-put` | `a1Notation` 实际写入的单元格范围 | 确认写入位置和范围 |
|
||||
| `table-put` | `sheets[].sheetId` / `sheets[].range` / `sheets[].dataRows` | 确认实际写入的 sheet、范围和行数;再用 `table-get` 回读类型与格式 |
|
||||
|
||||
## 注意事项
|
||||
|
||||
@@ -423,14 +544,17 @@ dws sheet append --node <NODE_ID> --sheet-id <SHEET_ID> \
|
||||
- 维度不足请按行 / 列补齐为同等大小;不需要修改的位置用 `{}` 跳过(保留原值),需要清空的位置用 `{"type":"text","text":""}`;禁止出现各行列数不一致或与 `--range` 不匹配的情况,否则调用会直接报错
|
||||
- 如需写整格超链接,把 `{"type":"text","text":"...","hyperlink":{"type":"path","link":"..."}}` 放进 `--values` 二维数组对应的单元格里;富文本片段链接才使用 richText 子项 `type:"link"`
|
||||
- ★ **清空区域优先用 `range clear`(强制)**:需要清空整片区域时必须使用 `range clear`,禁止用 `range update` 模拟。仅在 `range update` 写入混合数据时个别 cell 需要清空,才在 `--values` 中用 `{"type":"text","text":""}`
|
||||
- ★ **不再支持 `{type:"number"}` / `{type:"boolean"}` / `{type:"null"}`(强制)**:MCP `complexValues` 仅接受 `type:"text"` 与 `type:"richText"` 两种,CLI 会在本地直接拦截非法 type 并报错。写数字 / 布尔请用 `{"type":"text","text":"<字符串形式>"}`(服务端按内容自动识别),不要再用旧的 `value` 字段
|
||||
- **dataValidation 三语义**:不传字段=保留;`{type:"none"}`=清除;`{type:"dropdown"/"checkbox",...}`=覆盖。无需先 read 再回传,引擎自动保留原 DV
|
||||
- ★ **不再支持 `{type:"number"}` / `{type:"boolean"}` / `{type:"null"}`(强制)**:当前单元格对象协议仅接受 `type:"text"` 与 `type:"richText"` 两种,CLI 会在本地直接拦截非法 type 并报错。写数字 / 布尔请用 `{"type":"text","text":"<字符串形式>"}`(服务端按内容自动识别),不要再用旧的 `value` 字段
|
||||
- **dataValidation 三语义**:不传字段=保留;`{type:"none"}`=清除;`{type:"dropdown"/"checkbox",...}`=覆盖。无需先 read 再回传,系统会保留原 DV
|
||||
- **hyperlink 三语义**:不传字段=保留;`{type:"none"}`=清除;`{type:"path"/"sheet"/"range",...}`=覆盖。Agent 调用不要使用 `hyperlink:null`
|
||||
- ★ **单次调用上限(强制)**:`range update` / `set-style` 行数 ≤ 1000,单元格总数建议 ≤ 5000(硬限 30000)
|
||||
- ★ **大批量 CSV 值/公式写入用 `csv-put` 不用 `range update`**:当数据可表达为 CSV(可含 `=` 开头的公式)、不需要超链接或富文本对象且数据量较大时(>5 行或 >20 单元格),必须使用 `csv-put`。它无需构造二维 JSON 数组并支持自动扩容。需要单元格级超链接、富文本对象、样式、数据验证、`{}` 跳过,或仅更新少量单元格时使用 `range update`
|
||||
- ★ **公式写完必须分层校验**:先用 `range read --value-render-option formula` 确认公式文本,再用 `formula-verify` 聚合扫描错误;若返回 `partial` / `hasMore=true` 必须继续校验,关键业务数值还要用 `raw_value` 抽样对账
|
||||
- ★ **结构化 table 写入用 `table-put`**:需要列名、dtype、number format、跨 sheet specs 或 `table-get` 回写形态时使用 `table-put`;单次写入单元格数硬限 30000,包含表头
|
||||
- ★ **大整数/长数字 ID 必须按文本写(强制)**:超过 `9007199254740991` 的整数、订单号、手机号、SKU 等需要逐位精确的值,不要用 JSON number,也不要声明 `int64` / `uint64`。用字符串值 + `object` dtype + 文本格式 `@`;写后用 `table-get` 或 `range read --value-render-option raw_value` 回读确认
|
||||
- `range update` 必填 `--values`;单元格级超链接通过 cell 的 `hyperlink` 字段表达,附件 / 图片 / 带样式片段通过 `--values` 内的 richText 富格式表达,CLI 不再有 `--hyperlinks` 参数
|
||||
- `range update` 职责边界:`range update` 写入单元格内容(文本 / 公式 / 富文本对象),支持通过 `cellStyles` 附带 per-cell 样式(背景色 / 字号 / 对齐等)。但批量刷整片区域的统一样式时,应使用 `dws sheet range set-style`(如 "给表头加粗居中")或 `dws sheet range batch-set-style --batch <config.json>`。两种方式各有适用场景:少量 cell 写值 + 样式一步到位用 `cellStyles`;大面积统一样式用 `set-style`
|
||||
- `append` 自动定位到最后一行有数据的位置下方插入,无需手动计算行号
|
||||
- `append` 的 `--values` 二维数组中每行的列数必须一致,否则会报错。如果用户提供的数据中各行长度不同,必须先将短行用空字符串 `""` 补齐到与最长行相同的列数后再调用。追加的数据列数也应与工作表已有数据列数保持一致
|
||||
- `append` vs `range update`:追加新行用 `append`,修改已有单元格用 `range update`
|
||||
- ★ **`append` / `csv-put` 不支持 `{}` skip、`dataValidation`、富文本或超链接**:这些能力仅限 `range update`。`append` 只接受原始值;`csv-put` 接受 CSV 值和公式,字段值以 `=` 开头时按公式解析,前加单引号时写入以 `=` 开头的字面文本。需要下拉列表、富格式或跳过部分单元格时,必须使用 `range update`
|
||||
- ★ **`append` / `csv-put` / `table-put` 不支持 `{}` skip、dataValidation、富文本、超链接**:这些能力仅限 `range update`。`append` 只接受原始值;`csv-put` 接受 CSV 值和公式;`table-put` 接受 table 矩阵、dtypes、formats 和基础 `cellStyles`。需要超链接、下拉列表、富文本或跳过部分单元格时,必须使用 `range update`
|
||||
|
||||
@@ -93,7 +93,7 @@ metadata:
|
||||
| 场景 | Reference |
|
||||
|---|---|
|
||||
| 复杂发送、跨会话转发、共同群或组合流程 | [01-messaging.md](references/01-messaging.md) |
|
||||
| 引用、转发、卡片、reaction、Pin/Top/Favorite | [chat-message.md](references/chat/chat-message.md) |
|
||||
| 编辑/撤回/引用/转发/卡片/reaction/Pin/Top/Favorite | [chat-message.md](references/chat/chat-message.md) |
|
||||
| 建群、成员、管理员、群公告、群设置 | [chat-group.md](references/chat/chat-group.md) |
|
||||
| Bot 搜索、入群、群发和撤回 | [chat-bot.md](references/chat/chat-bot.md) |
|
||||
| 会话置顶、分类、红点、免打扰和隐藏 | [chat-conversation.md](references/chat/chat-conversation.md) |
|
||||
|
||||
@@ -227,6 +227,22 @@ dws chat message search --query "codereview" --group <openConversationId> --star
|
||||
| `message edit` | 编辑已发送消息内容 | `--conversation-id` `--msg-id`,并在 `--text` / `--content` 中二选一;可选 `--title` `--at-all` `--at-open-dingtalk-ids` |
|
||||
| `message read-status` | 查消息已读/未读状态 | `--group` `--message-id`;可选目标用户 |
|
||||
|
||||
刚由 `message send` 发出的消息会返回 `openTaskId`。先用 `message query-send-status` 查询,成功结果中的 `openMessageId` 和 `openConversationId` 可直接传给 `message edit` 或 `message recall`,无需再按消息内容从列表反查 ID。
|
||||
|
||||
```bash
|
||||
# 1. 发送后保留 openTaskId
|
||||
dws chat message send --group <openConversationId> --text "原始内容"
|
||||
# 2. 查询得到 openMessageId 和 openConversationId
|
||||
dws chat message query-send-status --open-task-id <openTaskId>
|
||||
# 3. 编辑消息
|
||||
dws chat message edit --conversation-id <openConversationId> --msg-id <openMessageId> --text "更新后的内容"
|
||||
|
||||
# 发送后撤回使用同一 ID 链
|
||||
dws chat message send --group <openConversationId> --text "待撤回的内容"
|
||||
dws chat message query-send-status --open-task-id <openTaskId>
|
||||
dws chat message recall --conversation-id <openConversationId> --msg-id <openMessageId>
|
||||
```
|
||||
|
||||
`+messages-recall` 与 `recall-by-bot` 不同:前者使用 `openMessageId`,缺少会话 ID 时先只读查询消息详情;后者撤回机器人消息,需要 `robot-code + processQueryKey`。不要把 `processQueryKey` 当 `openMessageId`。
|
||||
|
||||
编辑消息使用 `message edit`。推荐传 `--text`,CLI 会生成 markdown content JSON:`{"title":"标题","text":"正文"}`;可选 `--title`,不传时会从正文自动生成标题。高级场景可直接传 `--content`,此时必须是完整 markdown content JSON,且不能同时传 `--text`。
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
|---------|---------|
|
||||
| 在线电子表格(`axls`) | 走 `sheet` 全部命令 |
|
||||
| `xlsx` / `xls` / `xlsm` / `csv` | `dws drive download --node <ID> --output <路径>` 下载到本地处理,禁止调用任何 `sheet` 子命令 |
|
||||
| 本地 xlsx/xls 导入为在线表格 | `dws sheet import --file <路径>`(单命令一站式:创建会话→上传→确认→轮询,产出在线电子表格) |
|
||||
| 本地 xlsx/xls 导入为在线表格 | `dws sheet import create --file <路径>`(单命令一站式:创建会话→上传→确认→轮询,产出在线电子表格;`sheet import` 保留兼容) |
|
||||
| 在线表格导出为 xlsx | `dws sheet export`(axls → xlsx 格式转换) |
|
||||
|
||||
用户贴原始 `alidocs` URL 时必须先 probe:`dws drive info --node <URL> --format json`,按 [链接规范](../../dingtalk-shared/references/url-patterns.md#alidocs-url-类型探测流程) 校验:
|
||||
@@ -29,7 +29,7 @@
|
||||
## Agent 编辑总则
|
||||
|
||||
1. **先定位再编辑**:未知 `sheet-id` 时必须先 `dws sheet list --node <ID> --format json`,禁止猜 `Sheet1` / `sheet1` / `0` / `default`。用户只给工作表名称时,也先用 `list` 确认真实名称或 ID。
|
||||
2. **先读结构再动结构**:合并、冻结、行列分组、行高列宽、隐藏行列、最后非空边界都属于工作表结构信息,先读 `dws sheet info --node <ID> --sheet-id <SHEET_ID> --format json`。
|
||||
2. **先读结构再动结构**:合并、冻结、行列分组、行高列宽、隐藏行列、最后非空边界都属于工作表结构信息,先读 `dws sheet info --node <ID> --sheet-id <SHEET_ID> --format json`;分组回读加 `--include groups`,行高、列宽和隐藏行列按需加 `--include row_heights,col_widths,hidden_rows,hidden_cols`。
|
||||
3. **按目的选择读取方式**:快速看值和大表分批用 `csv-get`;需要 `columns` / `data` / `dtypes` / `formats` 用 `table-get`;需要公式、样式、数据验证、超链接、富文本等 per-cell 元数据用 `range read`。
|
||||
4. **写返回不等于完成**:任何写操作完成后都要用独立读命令回读确认。值写入用 `csv-get` / `range read` / `table-get`,结构变更用 `sheet info`,对象类操作用对应 `list` / `get`。
|
||||
5. **大批量 CSV 值/公式不要拼大 JSON**:超过 5 行或 20 个单元格、且不需要富格式对象时优先 `csv-put`;字段值以 `=` 开头按公式解析,前加单引号写入以 `=` 开头的字面文本;需要 table/dataframe 语义时用 `table-put`。
|
||||
@@ -68,7 +68,7 @@
|
||||
|
||||
| Reference | 描述 |
|
||||
|-----------|------|
|
||||
| [sheet-workbook](sheet/sheet-workbook.md) | 管理表格文档与工作表。当用户说"创建表格"、"有哪些工作表"、"新建/重命名/隐藏/冻结/复制/删除工作表"、"显示/隐藏网格线"时使用;`info` 可回读冻结行列等工作表结构信息。命令:`create`/`list`/`info`/`new`/`update`/`copy`/`delete-sheet`/`show-gridline`/`hide-gridline` |
|
||||
| [sheet-workbook](sheet/sheet-workbook.md) | 管理表格文档与工作表。当用户说"创建表格"、"有哪些工作表"、"新建/重命名/隐藏/冻结/复制/删除工作表"、"显示/隐藏网格线"时使用;`info` 可回读冻结行列,`--include groups` 回读分组,其他行列结构按需使用对应 `--include`。命令:`create`/`list`/`info`/`new`/`update`/`copy`/`delete-sheet`/`show-gridline`/`hide-gridline` |
|
||||
| [sheet-read-data](sheet/sheet-read-data.md) | 读取工作表数据。当用户说"读数据"、"看表格内容"、"查看数据"时使用。推荐 `csv-get`(CSV 格式、token 低、防爆保护);需按 table/dataframe 结构读取列名、data、dtypes、formats 时用 `table-get`;需 value + dataValidation / hyperlink / richText / cellStyles 等 per-cell 元数据时用 `range read`。大范围数据建议分页读取(单次 ≤5000 单元格)。命令:`csv-get`/`table-get`/`range read` |
|
||||
| [sheet-write-data](sheet/sheet-write-data.md) | 写入数据到工作表。当用户说"写数据"、"填表"、"更新单元格"、"写公式"、"超链接"、"写值同时设样式/数据验证"、"追加数据"、"导入CSV"、"写入结构化 table"时使用。大批量 CSV 值/公式(>5行或>20单元格,且无需富格式)必须用 `csv-put` 而非 `range update`;结构化 table/dataframe 输入用 `table-put`。命令:`range update`/`append`/`csv-put`/`table-put` |
|
||||
| [sheet-formula](sheet/sheet-formula.md) | 公式写入、文本回读、错误聚合与结果抽样。当用户说"写公式"、"计算列"、"辅助列"、"总计/占比/增长率/查找计算"、"校验公式"、"检查公式错误"时使用。命令:`range update` / `csv-put` / `range read --value-render-option formula/raw_value` / `formula-verify` |
|
||||
@@ -82,8 +82,8 @@
|
||||
| [sheet-filter](sheet/sheet-filter.md) | 全局筛选。当用户说"筛选"、"过滤"、"只看某些行"(未说"筛选视图")时使用。禁止用"删除不符合条件的行"代替筛选。命令:`filter get`/`create`/`delete`/`update`/`clear-criteria`/`sort` |
|
||||
| [sheet-filter-view](sheet/sheet-filter-view.md) | 筛选视图(个人化,不影响协作者)。当用户明确说"筛选视图"时使用,与全局筛选相互独立。命令:`filter-view list`/`create`/`update`/`delete`/`info`/`update-criteria`/`delete-criteria`/`list-criteria`/`get-criteria` |
|
||||
| [sheet-conditional-format](sheet/sheet-conditional-format.md) | 条件格式规则。触发词:标红/标黄/高亮/突出/标记/数据条/色阶/颜色随数据变 → **强制**走条件格式,禁止 `range set-style` 静态样式替代。命令:`cond-format list`/`create`/`update`/`delete` |
|
||||
| [sheet-export](sheet/sheet-export.md) | 导出表格为 xlsx。当用户说“导出”、“下载xlsx”、“存为Excel”时使用。单命令一站式,CLI 内部自动轮询,禁止 Agent 侧重试。命令:`export` / `export get` |
|
||||
| [sheet-import](sheet/sheet-import.md) | 导入本地表格文件为在线电子表格。当用户说“导入表格”、“把xlsx传成在线表格”、“上传Excel变在线表格”时使用。单命令一站式,CLI 内部自动轮询,禁止 Agent 侧重试,禁止用 `drive upload` 代替。命令:`import`/`import get` |
|
||||
| [sheet-export](sheet/sheet-export.md) | 导出表格为 xlsx。当用户说“导出”、“下载xlsx”、“存为Excel”时使用。单命令一站式,CLI 内部自动轮询,禁止 Agent 侧重试。命令:`export` |
|
||||
| [sheet-import](sheet/sheet-import.md) | 导入本地表格文件为在线电子表格。当用户说“导入表格”、“把xlsx传成在线表格”、“上传Excel变在线表格”时使用。Agent 入口为 `import create`,`import` 保留兼容;超时后只用 `import get` 续查,禁止重新创建或用 `drive upload` 代替。命令:`import create`/`import get` |
|
||||
| [sheet-chart](sheet/sheet-chart.md) | 浮动图表管理。当用户说“画图/数据可视化/趋势图/对比图/占比图/柱形图/折线图/饼图”时使用。禁止用本地脚本生成静态图片替代。命令:`chart list`/`create`/`update`/`delete` |
|
||||
| [sheet-pivot-table](sheet/sheet-pivot-table.md) | 透视表管理。当用户说“透视表/分组汇总/交叉分析/按X统计Y”时使用。禁止用公式拼汇总表替代。命令:`pivot-table list`/`create`/`update`/`delete` |
|
||||
| [sheet-comment](sheet/sheet-comment.md) | 单元格评论管理。当用户说“给单元格加评论/批注”、“看某格的评论”、“回复/更新/删除评论”、“@某人讨论这个数据”时使用。评论锚定单元格(`--sheet-id`+`--range`),禁止把评论写进单元格值。命令:`comment list`/`create`/`reply`/`update`/`delete` |
|
||||
@@ -95,7 +95,7 @@
|
||||
1. **`--sheet-id` 禁止臆测**:未知时必须 `dws sheet list --node <ID> --format json` 查询,禁止编造 `Sheet1`/`sheet1`/`0`/`default`
|
||||
2. **合并单元格是结构信息**:`dws sheet info --node <ID> --sheet-id <SHEET_ID> --format json` 返回 `mergedRanges`(如 `["C7:D11"]`);不要在 `range read` / `csv-get` 里寻找合并信息
|
||||
3. **冻结行列是工作表元数据**:`sheet info` 顶层返回 `frozenRowCount` / `frozenColumnCount`,分别表示从顶部第 1 行、左侧第 A 列开始冻结的数量;`0` 表示未冻结。不要在 `range read` / `csv-get` 里寻找冻结信息
|
||||
4. **结构变更后回读**:创建/取消分组、调整行高列宽或隐藏行列后,用 `dws sheet info --node <ID> --sheet-id <SHEET_ID> --format json` 回读工作表结构确认。
|
||||
4. **结构变更后按需 include 回读**:创建/取消分组后,用 `dws sheet info --node <ID> --sheet-id <SHEET_ID> --include groups --format json` 回读 `rowGroups` / `columnGroups`;行高、列宽、隐藏行列分别使用 `--include row_heights` / `col_widths` / `hidden_rows` / `hidden_cols`。裸 `sheet info` 不承诺返回这些可选结构字段。
|
||||
5. **最后非空坐标只用 A1 语义**:`sheet info` 通过 `nonEmptyRange` 返回 A1/UI 边界;优先使用 `nonEmptyRange.range`,需要追加行/列时使用 `nonEmptyRange.lastRow` / `nonEmptyRange.lastColumn`。不要使用旧的 0-based 字段 `lastNonEmptyRow` / `lastNonEmptyColumn`
|
||||
6. **`range update` 维度校验**:`--values` 行列数必须与 `--range` 完全一致;只接 `--values` 一个数据参数,cell `type` 仅支持 `text` / `richText`;整格超链接通过 cell-level `hyperlink` 表达,富文本片段链接才使用 `richText.texts[].type="link"`
|
||||
7. **dataValidation 三语义**:不传 `dataValidation` 字段=保留原 DV;`dataValidation:{type:"none"}`=显式清除;`dataValidation:{type:"dropdown"/"checkbox",...}`=覆盖。`{}` 跳过亦保留原 DV
|
||||
@@ -104,7 +104,7 @@
|
||||
10. **用专用命令不用组合模拟**:搜索→`find`、替换→`replace`、清空→`range clear`、排序→`range sort`、填充→`range fill`、复制区域→`range copy-to`、移动区域→`range move-to`、移动行列→`move-dimension`
|
||||
11. **大批量 CSV 值/公式用 `csv-put`**(>5 行或 >20 单元格,且无需富格式),不用 `range update`;需要 dataframe/table 语义(列名、dtypes、formats、跨 sheet specs)时用 `table-get` / `table-put`
|
||||
12. **单元格图片用 `write-image`**(`range update` 不支持图片参数)
|
||||
13. **`export` / `import` 禁止自行轮询**(CLI 内部已完成渐进式退避,最多 30 次约 5 分钟);`export get` / `import get`为单次查询,非终态时可手动再次调用
|
||||
13. **`export` / `import create` 禁止自行轮询**(CLI 内部已完成渐进式退避,最多 30 次约 5 分钟);导入超时只按返回的 `next_command` 调用 `import get`,导出失败或超时直接转述,不自动重调
|
||||
14. **单次调用上限**:`range update` / `set-style` 行数 ≤ 1000,单元格总数建议 ≤ 5000(硬限 30000)
|
||||
15. **大整数精度保护**:超过 `9007199254740991` 的整数和长数字标识符必须按文本写入;`table-put` 中不要使用 JSON number 或 `int64` / `uint64` dtype,改用字符串值 + `object` dtype + `formats`/`cellStyles` 的 `@`
|
||||
16. **批量写操作推荐用 `batch-update`**:对多个区域重复调用同一写入工具时,推荐合并为单次原子请求(详见 [sheet-batch-operations](./sheet/sheet-batch-operations.md));逐个调用非原子,中途失败会留下半成品。结构化 table 例外,`table-put` 不进 `batch-update`
|
||||
@@ -116,7 +116,7 @@
|
||||
- **视觉规范**:当前不维护独立的表格视觉方案文档;样式、条件格式、图表分别按对应子文档执行。
|
||||
- **结构化 table**:`table-get` / `table-put` 是 table/dataframe 语义入口,不嵌入 `batch-update`;需要原子组合时只组合已支持的单元格/结构写操作。
|
||||
- **历史版本**:支持通过 `version save`/`list`/`revert` 手动保存快照、查看版本列表、回滚到指定版本(底层复用 doc 域版本能力);回滚为危险操作,需二次确认。
|
||||
- **单元格评论**:支持通过 `comment create`/`list`/`reply`/`update`/`delete` 管理单元格评论(锚定 `--sheet-id`+`--range`,内容复用 `doc-comment` 服务、与前端评论同桶,单元格位置由 flex-table-app 承载并以 `customCategory`(cmt-*) 关联),详见 [sheet-comment](sheet/sheet-comment.md)。
|
||||
- **单元格评论**:支持通过 `comment create`/`list`/`reply`/`update`/`delete` 管理锚定在 `--sheet-id` + `--range` 的评论;评论与单元格值相互独立,详见 [sheet-comment](sheet/sheet-comment.md)。
|
||||
- **未暴露或未确认能力**:迷你图、历史 changeset 等能力未在本入口承诺;只有出现稳定 DWS 命令和可回读语义后再补充。
|
||||
|
||||
## URL 粘贴场景
|
||||
@@ -132,16 +132,16 @@
|
||||
|
||||
## 导入本地表格
|
||||
|
||||
用户说"导入Excel/把xlsx转为在线表格/上传表格并在线编辑"时,用 `dws sheet import`(单命令一站式,详见 [sheet-import](./sheet/sheet-import.md)):
|
||||
用户说"导入Excel/把xlsx转为在线表格/上传表格并在线编辑"时,用 `dws sheet import create`(单命令一站式;`sheet import` 保留兼容,详见 [sheet-import](./sheet/sheet-import.md)):
|
||||
```bash
|
||||
# 导入本地表格文件为在线电子表格(默认表格名取文件名)
|
||||
dws sheet import --file ./data.xlsx
|
||||
dws sheet import create --file ./data.xlsx
|
||||
|
||||
# 指定目标文件夹与导入后表格名
|
||||
dws sheet import --file ./report.xls --folder-token <FOLDER_TOKEN> --name "月度报表"
|
||||
dws sheet import create --file ./report.xls --folder-token <FOLDER_TOKEN> --name "月度报表"
|
||||
|
||||
# 导入到指定知识库
|
||||
dws sheet import --file ./data.xls --workspace <WORKSPACE_ID>
|
||||
dws sheet import create --file ./data.xls --workspace <WORKSPACE_ID>
|
||||
```
|
||||
- 支持 `.xlsx` / `.xls`,固定产出**在线电子表格**;只新建、不覆盖已有表格
|
||||
- CLI 内部自动完成「创建会话→上传→确认→渐进式退避轮询」(最多 30 次约 5 分钟),**禁止 Agent 侧再实现轮询或重试**
|
||||
@@ -258,6 +258,7 @@ Flags:
|
||||
|
||||
- 多维表 / 字段类型 → 切到 `dingtalk-aitable`
|
||||
- 把表数据写进文档 → 切到 `dingtalk-doc`
|
||||
|
||||
## 局部意图与 Recipe
|
||||
|
||||
- [局部意图消歧](sheet-intent-guide.md)。
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
`batch-update` 把多次写入打包成单次请求,但每个子操作仍受编辑类任务硬性默认规则约束:
|
||||
|
||||
1. **目标 range 必须落在用户授权范围内**:除用户明示要修改的区域外,子操作禁止扩张到无关单元格 / 列 / 工作表。规划 range 时先确认每个子操作的边界。
|
||||
2. **批次完成后必须回读校验**:整个 `batch-update` 执行成功后,单元格值用 `range read` 或 `csv-get` 抽样回读受影响区域;合并、行列分组等结构元数据用 `sheet info` 回读校验。
|
||||
2. **批次完成后必须回读校验**:整个 `batch-update` 执行成功后,单元格值用 `range read` 或 `csv-get` 抽样回读受影响区域;合并用裸 `sheet info`,行列分组用 `sheet info --include groups` 回读校验。
|
||||
3. **预期条数前置断言**:涉及"批量填充 N 行"或"对 M 个区域分别写入"时,先把 N、M 硬编码进代码,回读后断言实际等于预期;不一致就再发一轮 `batch-update` 补齐,禁止交付半成品。
|
||||
|
||||
## 使用场景
|
||||
@@ -29,7 +29,7 @@
|
||||
用户说"批量创建行列分组/批量取消行列分组/同时调整尺寸并分组":
|
||||
- 连续行/列分组 → `group-dimension`
|
||||
- 取消连续行/列分组 → `ungroup-dimension`
|
||||
- 分组回读用 `sheet info`
|
||||
- 分组回读用 `sheet info --include groups`
|
||||
- `group-dimension` 在 batch 中只适合默认展开分组;需要创建后立即折叠时,用独立 `dws sheet group-dimension --group-state fold`
|
||||
|
||||
**何时推荐使用 `batch-update`**:
|
||||
@@ -236,7 +236,7 @@ Cause: The requested resource was not found by the identifier 'NonExistentSheet'
|
||||
|
||||
### 批量创建/取消行列分组
|
||||
|
||||
分组属于工作表结构元数据,批次完成后用 `sheet info` 回读 `rowGroups` / `columnGroups`,不要用 `range read` 校验。回读项中的 `level` 是 1-based,`collapsed` 表示当前折叠状态。
|
||||
分组属于工作表结构元数据,批次完成后用 `sheet info --include groups` 回读 `rowGroups` / `columnGroups`,不要用裸 `sheet info` 或 `range read` 校验。回读项中的 `level` 是 1-based,`collapsed` 表示当前折叠状态。
|
||||
|
||||
```jsonc
|
||||
[
|
||||
@@ -263,7 +263,7 @@ Cause: The requested resource was not found by the identifier 'NonExistentSheet'
|
||||
| 操作 | 从返回中提取 | 用于 |
|
||||
|------|-------------|------|
|
||||
| `list` | 工作表的 `sheetId` | batch-clear 的 --ranges sheet 前缀 / batch-update 子操作 input 的 sheet-id |
|
||||
| `batch-update` | 各子操作的执行结果 | 回读校验(值用 range read / csv-get;合并、分组等结构用 sheet info) |
|
||||
| `batch-update` | 各子操作的执行结果 | 回读校验(值用 range read / csv-get;合并用 sheet info;分组用 sheet info --include groups) |
|
||||
|
||||
## 注意事项
|
||||
|
||||
@@ -273,5 +273,5 @@ Cause: The requested resource was not found by the identifier 'NonExistentSheet'
|
||||
- ★ **table 写入不进 batch-update**:当前 `batch-update` 不支持结构化 table 写入;结构化 table 请直接调用 `dws sheet table-put`
|
||||
- ★ **批次完成后必须回读校验**:值写入用 `range read` 或 `csv-get` 抽样回读受影响区域;结构变更用 `sheet info` 回读
|
||||
- ★ **`batch-update` 不支持嵌套**:`--operations` 中的 `toolName` 必须是原子操作,不可再嵌套 `batch-update`
|
||||
- `batch-update` 支持 `group-dimension` / `ungroup-dimension`;分组结果用 `sheet info` 回读
|
||||
- `batch-update` 支持 `group-dimension` / `ungroup-dimension`;分组结果用 `sheet info --include groups` 回读
|
||||
- `batch-update` 中 `group-dimension` 只适合默认展开分组;需要 `fold` 初始状态时使用独立 `group-dimension`
|
||||
|
||||
@@ -11,8 +11,8 @@
|
||||
|
||||
- 仅支持钉钉在线电子表格(`extension=axls`)。`xlsx` / `xls` / `csv` 等本地表格不支持评论。
|
||||
- 评论锚定在**单元格位置**:`create` / `list` 通过 `--sheet-id`(工作表 ID 或名称)+ `--range`(单元格坐标)定位;`reply` / `update` / `delete` 通过 `--comment-key` 操作,不依赖单元格位置。
|
||||
- `create` / `list` 为表格专属工具(`doc-comment` server 的 `create_sheet_comment` / `list_sheet_comments`);`reply` / `update` / `delete` 位置无关,复用 `doc-comment` server 的通用评论工具(`reply_comment` / `update_comment` / `delete_comment`)。五个命令统一走 `doc-comment` server。
|
||||
- 底层评论内容与文档评论同源存储(bizCode=DOCS),单元格位置由表格引擎(flex-table-app CP)承载,二者以 `cmt-{uuid}` 关联。
|
||||
- `create` / `list` 通过单元格位置定位;`reply` / `update` / `delete` 通过前一步返回的 `commentKey` 定位评论线程,不需要重新传单元格位置。
|
||||
- 评论正文与单元格位置由服务端关联。Agent 只使用命令返回的 `commentKey` 继续回复、更新或删除,不解析或拼接内部关联字段。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
用户说"隐藏行/隐藏列/显示行/显示列/设置行高/设置列宽/调整行高/调整列宽/行列属性":
|
||||
- 隐藏/显示行或列 → `update-dimension --hidden` / `--hidden=false`
|
||||
- 设置行高/列宽 → `update-dimension --pixel-size`
|
||||
- 设置行高/列宽 → `update-dimension --pixel-size`;恢复默认尺寸 → `--size-type standard`;行高按内容自适应 → `--size-type auto`(列宽不提供 auto)
|
||||
- 同时修改尺寸与显隐 → `update-dimension --pixel-size --hidden`
|
||||
|
||||
用户说"移动行/移动列/调整行顺序/调整列顺序/行列拖拽/把第N行移到第M行":
|
||||
@@ -29,7 +29,7 @@
|
||||
用户说"创建行分组/创建列分组/新建分组并折叠/新建分组并展开/取消分组":
|
||||
- 创建连续行/列分组 → `group-dimension`
|
||||
- 取消连续行/列分组 → `ungroup-dimension`
|
||||
- 分组创建后用 `sheet info` 回读 `rowGroups` / `columnGroups`
|
||||
- 分组创建后用 `sheet info --include groups` 回读 `rowGroups` / `columnGroups`
|
||||
- 仅创建分组时可用 `--group-state expand|fold` 指定初始展开/折叠;当前没有单独调整已有分组折叠状态的命令
|
||||
- 用户要求"折叠/展开已有分组"时,当前不支持直接修改已有分组的 `collapsed` 状态,不能承诺可用 `group-dimension` 完成
|
||||
|
||||
@@ -117,6 +117,12 @@ Example:
|
||||
|
||||
# 使用工作表前缀(忽略 --sheet-id)
|
||||
dws sheet update-dimension --node <NODE_ID> --sheet-id <SHEET_ID> --dimension ROWS --start-index "Sheet1!3" --length 2 --hidden
|
||||
|
||||
# 恢复第 2~3 行为默认行高(无需 --pixel-size)
|
||||
dws sheet update-dimension --node <NODE_ID> --sheet-id <SHEET_ID> --dimension ROWS --start-index "2" --length 2 --size-type standard
|
||||
|
||||
# 第 2~3 行按内容自适应行高
|
||||
dws sheet update-dimension --node <NODE_ID> --sheet-id <SHEET_ID> --dimension ROWS --start-index "2" --length 2 --size-type auto
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
@@ -125,14 +131,25 @@ Flags:
|
||||
--length string 更新数量,正整数 (必填),最大 5000
|
||||
--hidden 是否隐藏 (true=隐藏, false=显示),与 --pixel-size 至少填其一
|
||||
--pixel-size int 行高或列宽(像素),ROWS 时为行高,COLUMNS 时为列宽,与 --hidden 至少填其一
|
||||
--size-type string 尺寸模式: pixel(默认,用 --pixel-size) / standard(恢复默认行高列宽) / auto(按内容自适应行高,仅 ROWS;列宽无此选项)
|
||||
```
|
||||
|
||||
批量更新钉钉表格指定工作表中连续多行/多列的属性,支持设置显隐状态(hidden)与行高/列宽(pixelSize)。
|
||||
`--dimension ROWS` 时,`--start-index` 为 1-based 行号字符串;`--dimension COLUMNS` 时,`--start-index` 为列字母。
|
||||
支持在 `--start-index` 中携带工作表前缀(如 `Sheet1!3`),此时忽略 `--sheet-id`。
|
||||
`--hidden` 与 `--pixel-size` 至少必须提供一个。当同时提供时,将先应用尺寸再应用显隐,任一失败整体失败。
|
||||
`--hidden` 与 `--pixel-size` 至少必须提供一个(或用 `--size-type standard/auto` 让服务端决定尺寸)。当同时提供时,将先应用尺寸再应用显隐,任一失败整体失败。
|
||||
`--pixel-size` 单位为像素,`dimension=ROWS` 时表示行高、`dimension=COLUMNS` 时表示列宽。
|
||||
|
||||
`--size-type` 尺寸模式(对齐飞书 row_sizes/col_sizes 的 type):
|
||||
|
||||
| 值 | 行为 | ROWS | COLUMNS | 是否需要 --pixel-size |
|
||||
|----|------|------|---------|----------------------|
|
||||
| `pixel`(默认) | 使用 `--pixel-size` 指定的像素值 | 支持 | 支持 | 需要 |
|
||||
| `standard` | 恢复为工作表默认行高/列宽 | 支持 | 支持 | 不需要 |
|
||||
| `auto` | 按内容自适应行高 | 支持 | 不提供 | 不需要 |
|
||||
|
||||
列宽不提供 `auto`(与飞书 `col_sizes` 的 type 枚举一致,只有 `pixel` / `standard`)。需要控制列宽时用 `--pixel-size` 指定,或用 `--size-type standard` 恢复默认列宽。
|
||||
|
||||
### 移动行或列
|
||||
```
|
||||
Usage:
|
||||
@@ -205,7 +222,7 @@ Flags:
|
||||
|
||||
创建后用以下命令回读:
|
||||
```bash
|
||||
dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID> --format json
|
||||
dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID> --include groups --format json
|
||||
```
|
||||
|
||||
回读字段为 `rowGroups` / `columnGroups`,单项包含 `range`、起止行列、`count`、`level`、`collapsed`。`collapsed=true` 表示当前分组折叠。
|
||||
@@ -226,7 +243,7 @@ Flags:
|
||||
--range string 整行或整列范围,A1 表示法 (必填)。行如 "3:7",列如 "C:F"
|
||||
```
|
||||
|
||||
取消指定连续整行或整列范围上的分组。取消后同样用 `sheet info` 回读确认目标 `range` 已从 `rowGroups` / `columnGroups` 中移除。
|
||||
取消指定连续整行或整列范围上的分组。取消后同样用 `sheet info --include groups` 回读确认目标 `range` 已从 `rowGroups` / `columnGroups` 中移除。
|
||||
|
||||
`group-dimension` / `ungroup-dimension` 可以放进 `batch-update` 做原子组合;但 batch 中的 `group-dimension` 只适合默认展开分组。需要创建后立即折叠时,请使用独立 `dws sheet group-dimension --group-state fold`。
|
||||
|
||||
@@ -334,7 +351,7 @@ dws sheet update-dimension --node <NODE_ID> --sheet-id <SHEET_ID> \
|
||||
- `add-dimension` 追加的是空行/空列,与 `append`(追加带数据的行)不同
|
||||
- `add-dimension` 的 `--length` 必须为正整数(>= 1),行列均不超过 5000
|
||||
- `group-dimension` / `ungroup-dimension` 的 `--range` 只接受整行或整列范围,不接受普通单元格矩形
|
||||
- `group-dimension` 输出使用 `level`,且为 1-based;不要使用旧的 `depth` 字段
|
||||
- `sheet info` 是分组回读入口;`range read` / `csv-get` 不返回行列分组
|
||||
- `group-dimension` 输出和 `sheet info --include groups` 回读均使用 `level`,且为 1-based;不要使用旧的 `depth` 字段
|
||||
- `sheet info --include groups` 是分组回读入口;裸 `sheet info` 不承诺返回行列分组,`range read` / `csv-get` 不返回行列分组
|
||||
- 当前不能直接调整已有分组的 `collapsed` 状态;`--group-state fold` 只在创建分组时生效
|
||||
- `batch-update` 支持 `group-dimension` / `ungroup-dimension`,但不适合创建后立即折叠;需要 `fold` 时使用独立 `group-dimension`
|
||||
|
||||
@@ -11,6 +11,11 @@
|
||||
- 禁止用 `range read` 全量读取后自行拼接 xlsx 来模拟导出,必须使用 `export` 命令(服务端原子导出,保留格式/合并/公式等属性)
|
||||
- 禁止在 AI Agent 侧实现轮询或重试,CLI 内部已按渐进式退避策略完成(最多 30 次约 5 分钟)
|
||||
|
||||
用户说"导出 CSV/存成 csv/导出这个工作表为 csv":
|
||||
- 导出单个工作表为纯 CSV → `export-csv`(**同步**,不走异步任务;与 `export` 是两条独立命令)
|
||||
- 用 `--sheet-id` 指定工作表(不传取第一个)、`--range` 限定范围、`--value-render-option` 选取值模式
|
||||
- 不传 `--output` 时 CSV 正文打印到 stdout,可直接管道处理
|
||||
|
||||
## 命令详细参考
|
||||
|
||||
### 导出表格为 xlsx(异步任务一站式)
|
||||
@@ -56,7 +61,50 @@ Flags:
|
||||
- 导出任务返回 `FAILED`:命令立即返回错误并附带失败原因,**禁止自动重试 `dws sheet export`**,告知用户稍后再试
|
||||
- 轮询 30 次仍 `PROCESSING`:命令返回超时错误,告知用户稍后再试
|
||||
|
||||
**限制**:仅支持钉钉在线电子表格(alxs)→ xlsx。导出钉钉文字文档请使用 `doc` 产品对应的导出工具。
|
||||
**限制**:仅支持钉钉在线电子表格(axls)→ xlsx。导出钉钉文字文档请使用 `doc` 产品对应的导出工具。
|
||||
|
||||
### 导出单个工作表为纯 CSV(同步)
|
||||
```
|
||||
Usage:
|
||||
dws sheet export-csv [flags]
|
||||
Example:
|
||||
dws sheet export-csv --node <NODE_ID>
|
||||
dws sheet export-csv --node <NODE_ID> --sheet-id <SHEET_ID> --output ./data.csv
|
||||
dws sheet export-csv --node <NODE_ID> --range A1:Z1000 --value-render-option raw_value
|
||||
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称(不传则第一个工作表)
|
||||
--range string 导出范围,A1 表示法(不传则整表;大表可用此分块导出)
|
||||
--value-render-option string 取值模式: formatted_value(默认) / raw_value / formula
|
||||
--output string 本地保存路径(可选,支持文件路径或目录);不传则输出到 stdout
|
||||
--allow-truncated 允许数据被截断时仍然导出。默认截断即报错且不写文件
|
||||
```
|
||||
|
||||
同步读取**单个**工作表并输出 RFC4180 CSV,不走异步导出任务。与 `export` 是两条独立命令:`export` 导整篇工作簿的 xlsx(异步提交+轮询),`export-csv` 只导一个工作表的纯值(一次请求即返回)。不传 `--output` 时 CSV 正文打印到 stdout,可直接管道处理。
|
||||
|
||||
**`--output` 落盘是原子替换**:CSV 先写同目录临时文件、成功后再替换目标,写入失败时已有文件保持原样(父目录不存在仍按错误处理,不会自动创建)。`--output` 指向已存在目录时保存为该目录下的 `sheet-export.csv`。
|
||||
|
||||
**超大表默认 fail-closed**:数据超出单次读取上限(服务端返回 `hasMore`)时,命令**直接报错并以非 0 退出,既不打印 CSV 也不写文件**(已存在的目标文件不会被截断数据覆盖)。处理方式:
|
||||
- 用 `--range` 分块导出(如 `--range A1:Z1000`、`A1001:Z2000` …)
|
||||
- 改用 `dws sheet export` 导出完整表格的 xlsx
|
||||
- 确认可以接受不完整数据时,显式加 `--allow-truncated`;此时才会照常输出/落盘,并在 stderr 给出「已被截断」警告,成功提示也会写明"数据已截断,不是完整表格"
|
||||
|
||||
```bash
|
||||
# 落盘到本地
|
||||
dws sheet export-csv --node <NODE_ID> --sheet-id <SHEET_ID> --output ./data.csv
|
||||
|
||||
# 输出到 stdout 便于管道处理
|
||||
dws sheet export-csv --node <NODE_ID> --sheet-id <SHEET_ID>
|
||||
|
||||
# 大表分块导出(避免截断;不分块时默认会因截断而报错)
|
||||
dws sheet export-csv --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:Z1000" --output ./part1.csv
|
||||
|
||||
# 明确接受不完整数据(否则截断即失败)
|
||||
dws sheet export-csv --node <NODE_ID> --sheet-id <SHEET_ID> --allow-truncated --output ./partial.csv
|
||||
```
|
||||
|
||||
注意:CSV 只写纯值,不保留样式/合并/公式;需要完整属性请用 `dws sheet export` 导 xlsx。只是让 Agent 读取内容(带 `[row=N]` 行号前缀)请用 `dws sheet csv-get`。
|
||||
|
||||
## 核心工作流
|
||||
|
||||
@@ -78,27 +126,22 @@ dws sheet export --node <NODE_ID> --output ./
|
||||
# 若命令返回失败或超时,直接告知用户稍后再试,不要自动重调 dws sheet export。
|
||||
```
|
||||
|
||||
```bash
|
||||
# ── 工作流 13: 导出超时后查询任务状态(手动兜底)──
|
||||
|
||||
# 1. 执行导出(一体化命令,内部自动轮询约 5 分钟)
|
||||
dws sheet export --node <NODE_ID> --format json
|
||||
# 若超时,命令返回错误;等待一段时间后重新执行导出即可
|
||||
```
|
||||
|
||||
## 上下文传递
|
||||
|
||||
| 操作 | 从返回中提取 | 用于 |
|
||||
|------|-------------|------|
|
||||
| `export` | `downloadUrl`(未指定 --output)/ `导出完成: <path>`(指定 --output) | 直接下发给用户或告知文件已保存到本地。命令内部已完成轮询,不要再调用其他 export 相关命令 |
|
||||
| `export` 超时中断 | 错误信息 | 告知用户稍后重试 |
|
||||
| `export` | `downloadUrl`(未指定 --output)/ `outputPath`(指定 --output) | 直接下发给用户或告知文件已保存到本地。命令内部已完成轮询,不要再调用其他 export 相关命令 |
|
||||
| `export` 超时中断 | 错误信息 | 直接报告失败或超时;当前没有独立续查命令,不自动重新提交导出 |
|
||||
| `export-csv` | CSV 正文(未指定 --output,走 stdout)/ `导出完成: <path>`(指定 --output) | 直接把 CSV 交给下游处理,或告知文件已保存到本地。命令是同步的,无任务/轮询概念 |
|
||||
|
||||
## 注意事项
|
||||
|
||||
- ★ `export` 仅支持钉钉在线电子表格(alxs)→ xlsx;传入钉钉文字文档会报 `invalidRequest.document.typeIllegal`
|
||||
- ★ `export` 仅支持钉钉在线电子表格(axls)→ xlsx;传入钉钉文字文档会报 `invalidRequest.document.typeIllegal`
|
||||
- ★ `export` 为单命令一站式,CLI 内部已自动完成「提交 → 渐进式退避轮询 → 可选下载」,**Agent 不得在外部实现轮询或重试**;命令返回成功后不再调用其他 export 相关命令
|
||||
- `export` 内置轮询策略:1~5 次间隔 2s、6~10 次间隔 5s、11~20 次间隔 10s、21~30 次间隔 15s,硬上限 30 次(约 5 分钟);超时后命令返回错误,告知用户稍后再试即可
|
||||
- ★ `export` 命令返回失败或超时时,**禁止自动重调 `dws sheet export`**;直接告知用户导出失败并建议稍后再试
|
||||
- `export` 未指定 `--output` 时,返回的 `downloadUrl` 具有时效性,获取后请尽快下载;若用户需要本地文件,优先直接传 `--output` 让 CLI 代为下载
|
||||
- `export` 的 `--output` 可为文件路径或已存在目录;为目录时自动从 `downloadUrl` 推断文件名,为文件路径时直接按该路径保存
|
||||
- 用户要求"导出表格/下载 xlsx"时,必须使用 `export` 单命令,禁止用 `range read` 读全量数据后自行拼 xlsx 模拟导出(服务端导出会保留格式/合并/公式等完整属性)
|
||||
- `export-csv` 与 `export` 是两条独立命令:`export-csv` 同步导出**单个**工作表的纯值 CSV,不保留样式/合并/公式;要整篇工作簿或完整属性一律用 `export`
|
||||
- ★ `export-csv` 遇到数据超出单次读取上限时默认报错、既不输出也不写文件;优先用 `--range` 分块导出,只有用户明确接受不完整数据时才加 `--allow-truncated`
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
| 查看格式化展示结果 | `range read` 或 `csv-get` 默认模式 | 用于用户肉眼看到的展示值检查 |
|
||||
| 扫描整本表格公式错误 | `formula-verify --node <NODE_ID>` | 不传目标时扫描全部工作表的非空范围 |
|
||||
| 扫描单个工作表或范围 | `formula-verify --sheet-id ... [--range ...]` | `--range` 只传 A1 范围,不带工作表前缀 |
|
||||
| 扫描多个目标 | `formula-verify --targets ...` | 每项为 `{"sheetId":"...","range":"..."}`,`range` 可省略 |
|
||||
| 扫描多个目标 | `formula-verify --targets ...` | 必须是非空数组;每项为 `{"sheetId":"...","range":"..."}`,`range` 可省略 |
|
||||
|
||||
## 推荐流程
|
||||
|
||||
@@ -74,7 +74,7 @@ dws sheet formula-verify --node <NODE_ID> \
|
||||
--format json
|
||||
```
|
||||
|
||||
`--targets` 也支持 `@targets.json` 和 `-`(stdin)。每项只允许 `sheetId` 和可选的 `range`;使用 `--targets` 时不能再传 `--sheet-id` 或 `--range`。
|
||||
`--targets` 也支持 `@targets.json` 和 `-`(stdin)。数组必须至少包含一个目标,不能传 `[]`;每项只允许非空 `sheetId` 和可选的字符串 `range`,`range` 只写 A1 范围且不能带工作表前缀。使用 `--targets` 时不能再传 `--sheet-id` 或 `--range`。
|
||||
|
||||
### 扫描限制与自动化
|
||||
|
||||
@@ -183,6 +183,7 @@ dws sheet range read --node <NODE_ID> --sheet-id <SHEET_ID> --range "D2:D5" \
|
||||
- 把 `max-locations-per-error` 误解为错误计数上限;它只截断位置和样本。
|
||||
- 看到 `status=partial` 或 `hasMore=true` 仍声称整本表公式零错误。
|
||||
- 在 `--range` 中传 `Sheet1!A1:D10`,或把 `--targets` 与 `--sheet-id` 混用。
|
||||
- 显式传空的 `--targets '[]'`;这不是“无目标”,应改为至少一个目标,整本扫描则完全省略 `--targets`。
|
||||
|
||||
## 关联文档
|
||||
|
||||
|
||||
@@ -1,115 +1,76 @@
|
||||
# 导入 (import)
|
||||
# 导入本地表格(import)
|
||||
|
||||
## 使用场景
|
||||
|
||||
### 导入
|
||||
用户说“导入 Excel”“把 xlsx 变成在线表格”“上传本地表格并在线编辑”时,使用 Agent 可发现入口 `dws sheet import create`。它只新建在线电子表格,不覆盖已有表格。旧入口 `dws sheet import` 继续兼容人工调用。
|
||||
|
||||
用户说"导入/上传本地表格/把 xlsx 变成在线表格/把 Excel 传成在线电子表格/供应商发来的报价单传成在线表格":
|
||||
- 导入本地表格文件 → `import`(单命令一站式,内部自动完成创建会话、上传、确认、轮询)
|
||||
- 需传 `--file` 与目标位置(`--folder-token` 或 `--workspace` 至少一个),`--name` 自定义表格名
|
||||
- 固定产出**在线电子表格**;只**新建**文档,不写入/覆盖已有表格
|
||||
- 支持格式:`xlsx` / `xls`(按扩展名识别);文件大小上限 20MB
|
||||
- 禁止用 `drive upload` 代替:`drive upload` 只上传文件,不转换为可编辑的在线电子表格,语义不同且不在表格任务闭环内
|
||||
- 禁止在 AI Agent 侧实现轮询或重试,CLI 内部已按渐进式退避策略完成(最多 30 次约 5 分钟)
|
||||
- 导入后如需 @同事,由 Agent 拿到 `documentUrl` 后再走 `chat`/`doc` 相关命令编排,本命令不负责通知
|
||||
- 支持本地 `xlsx` / `xls`,文件上限 20MB
|
||||
- `--folder-token` 与 `--workspace` 至少提供一个
|
||||
- CLI 内部完成创建会话、上传文件、确认转换和轮询,Agent 不要自行拆分或重试
|
||||
- `drive upload` 只上传二进制文件,不会转换为可编辑的在线表格,不能替代本命令
|
||||
|
||||
## 命令详细参考
|
||||
|
||||
### 导入本地表格文件为在线电子表格(异步任务一站式)
|
||||
```
|
||||
Usage:
|
||||
dws sheet import [flags] # 一站式:创建会话 → 上传 → 确认 → 轮询
|
||||
dws sheet import get [flags] # 兜底:按 taskId 手动查询导入结果
|
||||
Example:
|
||||
# 导入 xlsx 为在线电子表格(默认表格名取文件名)
|
||||
dws sheet import --file ./quote.xlsx
|
||||
|
||||
# 指定目标文件夹与导入后表格名称
|
||||
dws sheet import --file ./report.xls --folder-token <FOLDER_TOKEN> --name "月度报表"
|
||||
|
||||
# 导入到指定知识库
|
||||
dws sheet import --file ./data.xls --workspace <WORKSPACE_ID>
|
||||
|
||||
Flags:
|
||||
--file string 本地表格文件路径 (必填,支持 xlsx/xls)
|
||||
--folder-token string 目标文件夹 ID 或 URL (与 --workspace 至少传一个)
|
||||
--workspace string 目标知识库 ID 或 URL (与 --folder-token 至少传一个)
|
||||
-n, --name string 导入后表格名称 (可选,默认取文件名去扩展名)
|
||||
```
|
||||
|
||||
将本地表格文件(xlsx/xls)导入为一个新的钉钉在线电子表格,与 `dws sheet export`(导出)对称,构成表格"进出闭环"。**单命令一站式**:命令内部自动完成「创建导入会话 → 上传文件到 OSS → 确认导入 → 渐进式退避轮询」全流程,AI Agent 无需自行拆分步骤或实现轮询。
|
||||
|
||||
**内部流程**:
|
||||
1. 调 `create_import_session` 获取 `sessionId` 与 OSS `uploadUrl`(入参 `fileName`/`suffix`/`fileSize`,可选 `targetFolderId`/`workspaceId`)
|
||||
2. HTTP PUT 上传本地文件到 `uploadUrl`
|
||||
3. 调 `confirm_import` 触发格式转换,获取 `taskId`
|
||||
4. 按渐进式退避策略轮询 `query_import_task` 直至任务终态或超时
|
||||
|
||||
**内置轮询策略(CLI 内实现,无需关心)**:
|
||||
- 第 1~5 次:每次间隔 2 秒
|
||||
- 第 6~10 次:每次间隔 5 秒
|
||||
- 第 11~20 次:每次间隔 10 秒
|
||||
- 第 21~30 次:每次间隔 15 秒
|
||||
- **硬上限:最多轮询 30 次(约 5 分钟)**,超时后命令输出结构化 `timed_out:true` + `next_command` 并以成功退出(exit 0)
|
||||
|
||||
**命令返回**:
|
||||
- 成功:进度日志(`[1/4]`~`[4/4]`)+ 末尾 JSON,含 `success` / `taskId` / `documentUrl` / `documentName` / `documentType` / `nodeId`
|
||||
- 超时:输出结构化 JSON,含 `success:false` / `timed_out:true` / `taskId` / `status:"processing"` / `next_command`(可直接复制执行的续查命令 `dws sheet import get --task-id <taskId>`);命令以成功退出(exit 0),业务态由 `success:false` 表达,便于 Agent 编排续查
|
||||
|
||||
**失败处理(命令内部已处理,Agent 仅需转述)**:
|
||||
- 转换返回失败状态:命令立即返回错误并附带原因,**禁止自动重试**,告知用户检查文件内容后再试
|
||||
- 轮询 30 次仍处理中:命令输出 `timed_out:true` + `next_command` 结构化字段(exit 0),Agent 检测到后按 `next_command` 用 `import get --task-id` 续查
|
||||
|
||||
**限制**:仅支持 xlsx/xls → 在线电子表格。导入为钉钉在线文档(md/docx 等 → 文字文档)请使用 `doc` 产品的 `import` 命令。
|
||||
|
||||
### 查询导入任务结果(兜底)
|
||||
```
|
||||
Usage:
|
||||
dws sheet import get [flags]
|
||||
Example:
|
||||
dws sheet import get --task-id <TASK_ID>
|
||||
|
||||
Flags:
|
||||
--task-id string 导入任务 ID (必填)
|
||||
```
|
||||
|
||||
按 `taskId` 查询导入任务状态。通常不需要手动调用,`import` 会自动轮询到终态;仅在导入命令超时或中断后用于兜底查询。任务状态:`processing`(转换中)/ `completed`(成功,返回 documentUrl)/ `failed`(失败)。
|
||||
|
||||
## 核心工作流
|
||||
## 命令
|
||||
|
||||
```bash
|
||||
# ── 工作流 13: 导入本地表格文件为在线电子表格(单命令一站式)──
|
||||
# 导入到指定文件夹
|
||||
dws sheet import create \
|
||||
--file ./quote.xlsx \
|
||||
--folder-token <FOLDER_TOKEN> \
|
||||
--format json
|
||||
|
||||
# 场景 A:导入 xlsx,默认表格名取文件名(命令内部自动完成上传+转换+轮询)
|
||||
dws sheet import --file ./quote.xlsx --format json
|
||||
# 导入到指定知识库,并自定义名称
|
||||
dws sheet import create \
|
||||
--file ./report.xls \
|
||||
--workspace <WORKSPACE_ID> \
|
||||
--name "月度报表" \
|
||||
--format json
|
||||
|
||||
# 场景 B:导入 xls 到指定文件夹并自定义表格名
|
||||
dws sheet import --file ./report.xls --folder-token <FOLDER_TOKEN> --name "月度报表"
|
||||
|
||||
# 场景 C:导入到指定知识库
|
||||
dws sheet import --file ./data.xls --workspace <WORKSPACE_ID>
|
||||
|
||||
# 场景 D:导入超时后兜底查询(用命令输出的 taskId)
|
||||
dws sheet import get --task-id <TASK_ID>
|
||||
|
||||
# 禁止在 Agent 侧实现任何轮询或重试,CLI 内部已按 2s/5s/10s/15s 渐进式退避自动完成(最多 30 次)。
|
||||
# 若命令返回失败或超时,按提示用 import get 查询,不要自动重调 import。
|
||||
# 导入超时或中断后续查
|
||||
dws sheet import get --task-id <TASK_ID> --format json
|
||||
```
|
||||
|
||||
## 上下文传递
|
||||
公开参数:
|
||||
|
||||
| 操作 | 从返回中提取 | 用于 |
|
||||
|------|-------------|------|
|
||||
| `import` | `documentUrl` / `nodeId`(导入成功后返回) | 下发给用户,或作为后续 `sheet` 操作的 `--node`;如需 @同事再走 `chat` 命令编排 |
|
||||
| `import`(超时) | `timed_out` / `taskId` / `next_command`(结构化输出) | 检测到 `timed_out:true` 后执行 `next_command`(即 `import get --task-id`)续查 |
|
||||
| `import get` | `status` / `documentUrl` | 判断任务是否完成并取回文档链接 |
|
||||
| 命令 | 参数 | 说明 |
|
||||
|------|------|------|
|
||||
| `sheet import create` | `--file` | 本地 xlsx/xls 文件(必填) |
|
||||
| `sheet import create` | `--folder-token` | 目标文件夹 ID 或 URL,与 `--workspace` 至少传一个 |
|
||||
| `sheet import create` | `--workspace` | 目标知识库 ID 或 URL,与 `--folder-token` 至少传一个 |
|
||||
| `sheet import create` | `--name`, `-n` | 导入后的名称;默认取文件名并去掉扩展名 |
|
||||
| `sheet import get` | `--task-id` | 导入任务 ID |
|
||||
|
||||
## 注意事项
|
||||
## 返回与续查
|
||||
|
||||
- ★ `import` 仅支持 xlsx/xls → 在线电子表格;导入为文字文档(md/docx 等)请用 `doc import`
|
||||
- ★ `import` 只**新建**在线电子表格,不写入或覆盖已有表格;要往已有表格追加数据请用 `range update` / `range append` / `csv put`
|
||||
- ★ `import` 为单命令一站式,CLI 内部已自动完成「创建会话 → 上传 → 确认 → 渐进式退避轮询」,**Agent 不得在外部实现轮询或重试**
|
||||
- ★ 命令失败或超时时,**禁止自动重调 `import`**;超时会输出 `timed_out:true`,按 `next_command` 用 `import get --task-id` 续查,失败则告知用户检查文件后再试
|
||||
- 文件大小上限 20MB;空文件、目录、非白名单格式均会在上传前被 CLI 拦截报错
|
||||
- `--name` 未指定时默认取文件名去掉扩展名;`--folder-token` 与 `--workspace` 用于指定目标位置,至少提供一个,均不传会被 CLI 层拦截报错
|
||||
- 用户要求"导入表格/上传 xlsx 变在线表格"时,必须使用 `import`,禁止用 `drive upload`(只上传不转换,产出不可编辑,且不在表格闭环内)
|
||||
成功时返回:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"taskId": "<TASK_ID>",
|
||||
"documentUrl": "<DOCUMENT_URL>",
|
||||
"documentName": "月度报表",
|
||||
"documentType": "1",
|
||||
"nodeId": "<NODE_ID>"
|
||||
}
|
||||
```
|
||||
|
||||
轮询达到上限时命令以退出码 0 返回业务态,避免 Agent 重复创建文档:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": false,
|
||||
"timed_out": true,
|
||||
"taskId": "<TASK_ID>",
|
||||
"status": "processing",
|
||||
"next_command": "dws sheet import get --task-id <TASK_ID>"
|
||||
}
|
||||
```
|
||||
|
||||
检测到 `timed_out:true` 后,只执行 `next_command` 续查。不要重新执行 `sheet import create`。
|
||||
|
||||
## 边界
|
||||
|
||||
- 本命令接受的是本地文件路径;它把 xlsx/xls 转换成新的 axls 在线表格
|
||||
- 已经存在于钉盘或文档中的 xlsx 节点不能直接传给工作表/单元格命令;先用 `drive download` 下载,需要在线编辑时再执行 `sheet import create`
|
||||
- 向已有在线表格写数据应使用 `range update`、`append`、`csv-put` 或 `table-put`
|
||||
- md/doc/docx 等文字文档导入使用 `dws doc import`
|
||||
|
||||
@@ -191,7 +191,7 @@ Flags:
|
||||
- 示例:`'Sheet1'!A1:D100`、`'销售数据'!A1:F500`
|
||||
- 必须包含表头行(通常从第 1 行开始)
|
||||
- sheet 名称用单引号包裹(含空格或特殊字符时必须)
|
||||
- MCP 内部自动将 source 解析为内部 sheetId + ISheetRange,CLI 直接透传即可
|
||||
- `source` 直接使用上述 A1 表示法;不要自行改写成内部对象结构
|
||||
|
||||
## 高级功能示例
|
||||
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
- 查找替换 → `replace`
|
||||
- 精确匹配后替换(只替换内容完全等于的单元格) → `replace --match-entire-cell`
|
||||
- 正则替换 → `replace --use-regexp`
|
||||
- 替换公式文本(改公式源码而非显示值) → `replace --match-formula`
|
||||
- 删除匹配内容 → `replace --replacement ""`
|
||||
- 请勿用 `find` + `range update`、`range read` + `range update` 等组合来模拟替换,`replace` 是服务端原子操作,效率更高且返回替换计数
|
||||
|
||||
@@ -68,6 +69,7 @@ Flags:
|
||||
--match-case 区分大小写 (默认 false)
|
||||
--match-entire-cell 完整单元格匹配
|
||||
--use-regexp 启用正则表达式匹配
|
||||
--match-formula 在公式文本中查找替换(默认 false,替换公式源码而非显示值)
|
||||
--include-hidden 包含隐藏行/列
|
||||
```
|
||||
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
|
||||
| 方式 | 命令 / 字段 | 适用场景 | 粒度 |
|
||||
|------|------------|---------|------|
|
||||
| **`set-style` / `batch-set-style`** | `dws sheet range set-style` | 批量刷整片区域的统一样式(表头加粗居中、数字格式等) | range 级别(2D 数组或全 range 统一值) |
|
||||
| **`set-style` / `batch-set-style`** | `dws sheet range set-style` / `batch-set-style` | 批量刷整片区域的统一样式(表头加粗居中、数字格式等);多区域批量走 `batch-set-style`(服务端原子事务) | range 级别(2D 数组或全 range 统一值) |
|
||||
| **`cellStyles`**(`range update` 内) | `--values` 中每个 cell 的 `cellStyles` 字段 | 写值同时附带样式,少量 cell 一步到位 | per-cell 级别 |
|
||||
| **`style`**(richText 片段样式) | `--values` 中 richText 子项(`text`/`link`)的 `style` | 同一单元格内不同文字有不同字体样式 | 文本片段级别 |
|
||||
|
||||
@@ -26,7 +26,8 @@
|
||||
|
||||
用户说"设置样式/改颜色/设背景色/加粗/居中/换行/字体颜色/字号":
|
||||
- 仅设样式不改值 → `range set-style`
|
||||
- 批量设置不同 range 的样式 → `range batch-set-style --batch ./styles.json`(按配置顺序执行多条样式更新)
|
||||
- 多个区域刷同一组样式(可跨工作表)→ `range batch-set-style --ranges '["Sheet1!A1:B2","Sheet2!D1:D10"]' + 样式 flag`(一次原子提交)
|
||||
- 各区域样式不同 → `range batch-set-style --batch ./styles.json`(同样一次原子提交)
|
||||
- 写值同时附带样式 → `range update --values` 中使用 `cellStyles` 字段(参见 sheet-write-data.md)
|
||||
- 请勿用 `range update --values` 写空/重写来模拟纯样式变更
|
||||
|
||||
@@ -59,6 +60,14 @@ Example:
|
||||
|
||||
# 整片 range 启用自动换行
|
||||
dws sheet range set-style --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:E10" --word-wrap autoWrap
|
||||
|
||||
# 斜体 + 下划线 + 指定字体(整个 range 共用)
|
||||
dws sheet range set-style --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:A10" \
|
||||
--font-style italic --font-line underline --font-family "微软雅黑"
|
||||
|
||||
# 给 A1:D10 加四周实线边框(每格四边=网格线)
|
||||
dws sheet range set-style --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:D10" \
|
||||
--border-styles-json '{"top":{"style":"solid","color":"#000"},"bottom":{"style":"solid","color":"#000"},"left":{"style":"solid","color":"#000"},"right":{"style":"solid","color":"#000"}}'
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--sheet-id string 工作表 ID 或名称 (必填)
|
||||
@@ -77,26 +86,49 @@ Flags:
|
||||
--font-weights-json string 字体粗细二维 JSON 数组
|
||||
--word-wrap string 换行方式:overflow/clip/autoWrap(整个 range 共用)
|
||||
--number-format string 数字格式代码,如 General/@/#,##0/#,##0.00/0%/0.00%/yyyy/m/d/h:mm:ss
|
||||
--font-style string 字体样式:normal/italic(斜体,整个 range 共用)
|
||||
--font-line string 字体线条:none/underline/line-through(下划线/删除线,单选,整个 range 共用)
|
||||
--font-family string 字体族,如 Arial / 微软雅黑(整个 range 共用)
|
||||
--border-styles-json string 四边边框 JSON,如 '{"top":{"style":"solid","color":"#000"},"bottom":{"style":"medium"}}'
|
||||
```
|
||||
|
||||
**特性说明**:
|
||||
- 每个样式维度提供两种写法,二选一:`--xxx`(单值刷整个 range,CLI 本地展开为二维数组)vs `--xxx-json`(逐单元格指定,维度需与 `--range` 完全一致)
|
||||
- 至少需传入一个样式参数。单次调用建议:行数 ≤ 1000,单元格总数 ≤ 5000
|
||||
- 枚举值按驼峰书写:`autoWrap`、`bold`、`normal`、`center` 等
|
||||
- 每个可逐格样式维度(bg-color/font-size/h-align/v-align/font-color/font-weight)提供两种写法,二选一:`--xxx`(单值刷整个 range,CLI 本地展开为二维数组)vs `--xxx-json`(逐单元格指定,维度需与 `--range` 完全一致)
|
||||
- 整区共用的标量样式(无 `*-json` 形式):`--word-wrap` / `--number-format` / `--font-style` / `--font-line` / `--font-family` / `--border-styles-json`
|
||||
- `--border-styles-json`:四边 `{top/bottom/left/right}`,每边 `{style, color?}`;`style` 取 `solid/medium/thick/dashed/dotted/double/hair/none` 等(**粗细已含在 style 内**:`solid`=细、`medium`=中、`thick`=粗,无独立 weight 字段);只传的边生效、未传的边保留原状(按边合并)。每条边**只接受 `style` / `color` 两个键**,写错的键(如 `colour`)或非字符串的 `color` 直接报错而不是静默忽略(否则会画出一条没有颜色的边框却报成功);**逐格应用**:对整个 range 每个单元格都画指定的边 = 网格效果(非仅最外框)
|
||||
- `--font-line` 为单选:`underline` 置下划线、`line-through` 置删除线、`none` 清除两者
|
||||
- 至少需传入一个样式参数。单次调用建议:行数 ≤ 1000,单元格总数 ≤ 5000(服务端硬限 30000)
|
||||
- 枚举值按驼峰书写:`autoWrap`、`bold`、`normal`、`center`、`italic` 等
|
||||
- 底层走 `set_cell_range` 的 `cellStyles`(仅设样式、保留原值),因此**纯样式设置可直接作用于含合并单元格的区域**,无需先取消合并
|
||||
|
||||
### 批量设置单元格样式
|
||||
### 批量设置单元格样式(服务端原子事务)
|
||||
```
|
||||
Usage:
|
||||
dws sheet range batch-set-style [flags]
|
||||
Example:
|
||||
# 同一组样式刷多个区域(可跨工作表),一次原子提交
|
||||
dws sheet range batch-set-style --node <NODE_ID> \
|
||||
--ranges '["Sheet1!A1:B2","Sheet2!D1:D10"]' \
|
||||
--bg-color "#FFF2CC" --font-weight bold --font-family "微软雅黑"
|
||||
|
||||
# 每项不同样式:用配置文件
|
||||
dws sheet range batch-set-style --node <NODE_ID> --batch ./styles.json
|
||||
dws sheet range batch-set-style --node <NODE_ID> --batch ./styles.json --continue-on-error
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
--batch string 批次配置 JSON 文件路径 (必填)
|
||||
--continue-on-error 遇到失败时继续执行后续条目(默认遇错即停)
|
||||
--ranges string 目标区域 JSON 数组,每项须带工作表前缀,最多 100 项(与 --batch 二选一,同一组样式应用到所有区域)
|
||||
--batch string 批次配置 JSON 文件路径(与 --ranges 二选一,每项可用不同样式)
|
||||
--continue-on-error 遇到失败时继续执行其余项(默认严格事务,整批回滚)
|
||||
(其余样式 flag 与 set-style 完全一致,配合 --ranges 使用)
|
||||
```
|
||||
|
||||
两种入口,二选一:
|
||||
|
||||
| 入口 | 适用 | 说明 |
|
||||
|------|------|------|
|
||||
| `--ranges` | 同一组样式刷多个区域 | 对齐飞书 `+cells-batch-set-style`;每项须带工作表前缀(`"Sheet1!A1:B2"`),**支持跨工作表**,最多 100 项;样式用与 `set-style` 相同的 flag |
|
||||
| `--batch <file>` | 各区域样式不同 | JSON 数组,每项含 `sheetId` + `range` + 该项自己的样式字段 |
|
||||
|
||||
配置文件格式(JSON 数组,每个元素一条批次项):
|
||||
```json
|
||||
[
|
||||
@@ -109,6 +141,10 @@ Flags:
|
||||
"vAlign": "middle",
|
||||
"fontColor": "#333333",
|
||||
"fontWeight": "bold",
|
||||
"fontStyle": "italic",
|
||||
"fontLine": "underline",
|
||||
"fontFamily": "Arial",
|
||||
"borderStylesJson": "{\"top\":{\"style\":\"solid\",\"color\":\"#000\"}}",
|
||||
"wordWrap": "autoWrap",
|
||||
"numberFormat": "General"
|
||||
},
|
||||
@@ -121,9 +157,11 @@ Flags:
|
||||
```
|
||||
|
||||
**特性说明**:
|
||||
- CLI 按配置顺序逐条执行样式更新(非原子事务),运行时输出 `[N/M]` 进度
|
||||
- 每条记录执行与 `set-style` 一致的校验:至少一项样式字段 + rows ≤ 1000 + rows×cols ≤ 30000 + 枚举合法
|
||||
- 默认遇错即停(返回非 0),`--continue-on-error` 时所有条目跑完再返回首个错误
|
||||
- CLI 把所有区域组装为**一次** `batch_update` 调用,由**服务端原子执行**:默认严格事务,任一项失败则**整批回滚**(不会出现部分区域已改、部分未改)
|
||||
- 所有项在下发前先做本地校验(每项与 `set-style` 一致:至少一项样式字段 + rows ≤ 1000 + rows×cols ≤ 30000 + 枚举合法),**任一项校验不过即整批不下发**
|
||||
- 批量上限:最多 **100 个区域**,且**所有区域累计不超过 200000 个单元格**(一次请求要把全部单元格矩阵建好,累计量才是真正的峰值约束)。超限同样是下发前本地报错、整批不执行;请拆成多次调用
|
||||
- `--continue-on-error` 透传给服务端:遇失败继续执行其余项(软批量)
|
||||
- 底层每项走 `set_cell_range` 的 `cellStyles`/`borderStyles`,因此纯样式批量同样可作用于含合并单元格的区域
|
||||
|
||||
### 合并单元格
|
||||
```
|
||||
@@ -264,7 +302,9 @@ dws sheet merge-cells --node <NODE_ID> --sheet-id <SHEET_ID> --range "A1:C3" --m
|
||||
|
||||
- ★ **`--sheet-id` 获取规范(强制)**:`sheetId` 未知时必须先通过 `dws sheet list --node <NODE_ID> --format json` 查询,禁止凭空编造(如臆测为 `Sheet1`、`sheet1`、`0`、`default` 等)
|
||||
- ★ `range update` / `range set-style` / `range batch-set-style` 单次调用上限(强制):行数 ≤ 1000,单元格总数(行×列)建议≤ 5000(服务端硬限 30000);超限请拆分多次调用。CLI 会在调用前做本地预校验,服务端超 30000 会直接报错
|
||||
- `range set-style` / `range batch-set-style` 的样式枚举按驼峰书写:`wordWrap` 取 `overflow`/`clip`/`autoWrap`,`fontWeight` 取 `bold`/`normal`,`hAlign` 取 `left`/`center`/`right`/`general`,`vAlign` 取 `top`/`middle`/`bottom`;背景色/字体颜色统一使用 `#RRGGBB` 格式
|
||||
- `range set-style` / `range batch-set-style` 的样式枚举按驼峰书写:`wordWrap` 取 `overflow`/`clip`/`autoWrap`,`fontWeight` 取 `bold`/`normal`,`hAlign` 取 `left`/`center`/`right`/`general`,`vAlign` 取 `top`/`middle`/`bottom`,`fontStyle` 取 `normal`/`italic`;背景色/字体颜色统一使用 `#RRGGBB` 格式
|
||||
- `--font-line` 取 `none`/`underline`/`line-through`(单选,非驼峰):`underline` 置下划线、`line-through` 置删除线、`none` 同时清除;`--font-family` 传字体族名(如 `Arial`/`微软雅黑`);`--font-style`/`--font-line`/`--font-family` 均为整区共用标量,无 `*-json` 逐格形式
|
||||
- `range set-style` / `range batch-set-style` 底层走 `set_cell_range` 的 `cellStyles`(仅设样式、保留原值);纯样式设置可直接作用于**含合并单元格**的区域,无需先取消合并(写值到合并区仍会被拦截)
|
||||
- `range update` 支持通过 `cellStyles` 在写值时附带 per-cell 样式,适合少量单元格写值 + 样式一步到位的场景。批量设置整片区域的统一样式时,仍应使用 `set-style` / `batch-set-style`
|
||||
- `merge-cells` 合并时只保留左上角单元格的值,其他单元格的值会被丢弃
|
||||
- `merge-cells` 的 `--merge-type` 不传时默认为 `mergeAll`(合并所有单元格)
|
||||
|
||||
@@ -3,7 +3,8 @@
|
||||
## 使用场景
|
||||
|
||||
用户说"创建表格/新建电子表格":
|
||||
- 创建表格文档 → `create`
|
||||
- 创建空表格文档 → `create`
|
||||
- 创建并写入初始数据(可选样式)→ `create-with-data`(`--values` / `--sheets` 必须给一个)
|
||||
|
||||
用户说"看工作表/有哪些工作表/表格结构":
|
||||
- 列出工作表 → `list`
|
||||
@@ -53,6 +54,76 @@ Flags:
|
||||
|
||||
> **ID 格式约束**:`--folder` 只接受 UUID 格式的 `fileId`(如 `ZgpG2NdyVXYOR2D5UGDok65MJMwvDqPk`)或 alidocs 文件夹 URL。`drive list` 返回中有 `dentryId`(纯数字,如 `218595998810`)和 `fileId`(UUID 格式)两个字段,**必须使用 `fileId`,禁止使用 `dentryId`**,传入纯数字会导致命令失败。
|
||||
|
||||
### 创建表格文档并写入初始数据
|
||||
```
|
||||
Usage:
|
||||
dws sheet create-with-data [flags]
|
||||
Example:
|
||||
dws sheet create-with-data --name "名单" --values '[["姓名","分数"],["张三","90"]]'
|
||||
dws sheet create-with-data --name "报表" --sheets '[{"name":"一月","columns":["项目","金额"],"data":[["房租",5000]]}]'
|
||||
Flags:
|
||||
--name string 表格名称 (必填)
|
||||
--folder string 目标文件夹 ID (dentryUuid 格式) 或 URL;禁止传入纯数字 dentryId
|
||||
--workspace string 目标知识库 ID
|
||||
--values string 初始数据,二维 JSON 数组,写入默认工作表 (与 --sheets 二选一)
|
||||
--sheets string 多工作表 typed table JSON (与 --values 二选一)
|
||||
--styles string 建表时一并应用的视觉处理 JSON(需与 --values 或 --sheets 搭配)
|
||||
```
|
||||
|
||||
建表并写入初始数据的多步编排:建文档 → 探活 → 定位默认工作表 → 写数据 → 回读校验 →(可选)应用样式。**只要一个空表格请用 `dws sheet create`**(单次调用);本命令必须给数据。
|
||||
|
||||
**写入初始数据**(`--values` 与 `--sheets` **二选一,必须给一个**):
|
||||
|
||||
- `--values`:二维 JSON 数组,裸值写入默认工作表 A1 起。适合单表快速建表,无表头/类型语义,内部复用 csv-put 通道,自动识别数字/布尔。单元格只能是字符串/数字/布尔/null;上限 30000 单元格、编码为 CSV 后 2000000 字符。
|
||||
- `--sheets`:typed table 数组,一次创建多个带数据的工作表,内部复用 table-put 通道。每项形如
|
||||
`{"name":"表名","columns":["列1","列2"],"data":[[...]],"dtypes":{...},"formats":{...},"cellStyles":[...]}`;
|
||||
`name`、`columns` **必填**。第一个条目写入默认工作表(自动重命名为其 `name`,避免残留空表),其余按 `name` 自动新建。
|
||||
- 字段名为 camelCase,只接受 `name` / `columns` / `data` / `dtypes` / `formats` / `cellStyles` / `startCell` / `mode`(`overwrite`|`append`) / `header` / `allowOverwrite`;**未知键与 snake_case 变体一律拒绝**(服务端会静默丢弃写错的键,`{"datas":[...]}` 会写出一张只有表头的表却报成功)
|
||||
- **不接受 `sheetId`**:文档此刻还不存在,工作表只能用 `name` 指定
|
||||
- `columns` 为非空字符串数组、列名不可为空/重复(按 trim 后比较);`data` 每行长度须等于 `columns`,单元格只能是字符串/数字/布尔/null
|
||||
- `dtypes` / `formats` 的键须是 `columns` 里的列名(服务端按列名查表,写错既不报错也不生效)
|
||||
- 单表写入上限 30000 单元格(写表头时含表头行)
|
||||
|
||||
**建表时一并应用样式**(`--styles`,顶层键对齐飞书 snake_case,列表项内字段兼容 camelCase;两级都拒绝未知键):
|
||||
|
||||
```json
|
||||
{"styles":[{"name":"表名",
|
||||
"cell_styles":[{"range":"A1:D1","font_weight":"bold","background_color":"#FFF2CC","number_format":"@"}],
|
||||
"row_sizes":[{"range":"1:1","type":"pixel","size":28}],
|
||||
"col_sizes":[{"range":"A:D","type":"pixel","size":120}],
|
||||
"cell_merges":[{"range":"A1:B1","merge_type":"all"}]}]}
|
||||
```
|
||||
|
||||
- 每项至少给 `cell_styles` / `row_sizes` / `col_sizes` / `cell_merges` 之一
|
||||
- 配 `--sheets` 时 styles 的**项数/顺序/name 必须与子表一一对应**;配 `--values` 时只给 1 项(`name` 被忽略)
|
||||
- 数据写入后按 `cell_styles` → `row_sizes` → `col_sizes` → `cell_merges` 顺序执行(**非原子**)
|
||||
- `row_sizes.type`:`pixel`(需 `size`)/ `standard`(恢复默认行高)/ `auto`(按内容自适应)
|
||||
- `col_sizes.type`:`pixel`(需 `size`)/ `standard`(恢复默认列宽)——与飞书一致,**列宽不提供 `auto`**
|
||||
- `size` 必须是正整数(小数会被拒绝而不是静默取整,避免得到与配置不符的行高列宽);`row_sizes.range` 形如 `"1:3"`、`col_sizes.range` 形如 `"A:C"`,带多余字符一律拒绝
|
||||
- `merge_type` 取 `all` / `rows` / `columns`
|
||||
|
||||
**行为要点**:
|
||||
- 所有 JSON 结构、字段类型与枚举都在**创建文档之前**校验(`--sheets` 按 table-put 的输入契约逐字段校验),非法配置直接失败,不会留下白建的空文档
|
||||
- 创建后 CLI 会先探活(新建文档服务端仍在初始化,此时写入可能返回成功但不落盘),再写数据
|
||||
- 写完会回读**首个预期非空单元格**校验确实落盘(不是死盯 A1:`--sheets` 会按 `startCell` / `header` / `mode` 推算实际写入位置);若未落盘会报错并提示用 `csv-put` / `range update` / `table-put` 补写
|
||||
- 报错信息里始终带上已创建的 `nodeId`,便于在部分成功时继续操作同一份文档
|
||||
|
||||
示例:
|
||||
|
||||
```bash
|
||||
# 创建并写入初始数据(默认工作表,裸二维值)
|
||||
dws sheet create-with-data --name "名单" --values '[["姓名","分数"],["张三","90"]]'
|
||||
|
||||
# 创建多个带数据的工作表
|
||||
dws sheet create-with-data --name "报表" --sheets '[{"name":"一月","columns":["项目","金额"],"data":[["房租",5000]]},{"name":"二月","columns":["项目","金额"],"data":[["房租",5000]]}]'
|
||||
|
||||
# 创建 + 写数据 + 一并应用样式(表头加粗黄底、行高、列宽)
|
||||
dws sheet create-with-data --name "带样式" --values '[["姓名","分数"],["张三","90"]]' \
|
||||
--styles '{"styles":[{"name":"Sheet1","cell_styles":[{"range":"A1:B1","font_weight":"bold","background_color":"#FFF2CC"}],"row_sizes":[{"range":"1:1","type":"pixel","size":28}],"col_sizes":[{"range":"A:B","type":"pixel","size":120}]}]}'
|
||||
```
|
||||
|
||||
> `--folder` / `--workspace` 的 ID 格式约束与 `dws sheet create` 完全一致(只接受 UUID 格式的 `fileId` 或 alidocs URL)。
|
||||
|
||||
### 获取全部工作表列表
|
||||
```
|
||||
Usage:
|
||||
@@ -72,6 +143,7 @@ Example:
|
||||
dws sheet info --node <NODE_ID>
|
||||
dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID>
|
||||
dws sheet info --node <NODE_ID> --sheet-id "Sheet1"
|
||||
dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID> --include groups
|
||||
dws sheet info --node <NODE_ID> --sheet-id <SHEET_ID> --include row_heights,col_widths,hidden_rows,hidden_cols
|
||||
Flags:
|
||||
--node string 表格文档 ID 或 URL (必填)
|
||||
@@ -85,7 +157,7 @@ Flags:
|
||||
|
||||
最后非空数据边界通过 `nonEmptyRange` 返回,字段均为 A1/UI 语义:`range` 是从 `A1` 到最后非空单元格的范围,`lastCell` 是最后非空单元格地址,`lastRow` 是 1-based 行号,`lastColumn` 是列字母。空表时 `nonEmptyRange` 为 `null`。不要使用旧的 0-based 字段 `lastNonEmptyRow` / `lastNonEmptyColumn`。
|
||||
|
||||
返回字段:
|
||||
需要读取行列分组时,加 `--include groups`。返回字段:
|
||||
- `rowGroups`:行分组列表,单项包含 `range`、`startRow`、`endRow`、`count`、`level`、`collapsed`
|
||||
- `columnGroups`:列分组列表,单项包含 `range`、`startColumn`、`endColumn`、`count`、`level`、`collapsed`
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Copyright 2026 Alibaba Group
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
//
|
||||
// Mono↔multi skill content QA (G1–G4). Spec: docs/skill-mono-multi-qa.md
|
||||
// Mono↔multi skill content QA (G1–G5). Spec: docs/skill-mono-multi-qa.md
|
||||
// Contract: skills/content-qa/mono-multi-coverage.yaml
|
||||
|
||||
package unit_test
|
||||
@@ -9,8 +9,11 @@ package unit_test
|
||||
import (
|
||||
"bytes"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
@@ -41,10 +44,16 @@ type monoMultiQAContract struct {
|
||||
ExpectedMulti string `yaml:"expected_multi"`
|
||||
} `yaml:"omit_global"`
|
||||
PairedFiles []struct {
|
||||
Mono string `yaml:"mono"`
|
||||
Multi string `yaml:"multi"`
|
||||
Mode string `yaml:"mode"`
|
||||
LinkSubstitutions []monoMultiLinkSubstitution `yaml:"link_substitutions"`
|
||||
} `yaml:"paired_files"`
|
||||
PairedTrees []struct {
|
||||
Mono string `yaml:"mono"`
|
||||
Multi string `yaml:"multi"`
|
||||
Mode string `yaml:"mode"`
|
||||
} `yaml:"paired_files"`
|
||||
} `yaml:"paired_trees"`
|
||||
OrphanScriptsAllowlist []struct {
|
||||
Path string `yaml:"path"`
|
||||
Disposition string `yaml:"disposition"`
|
||||
@@ -53,6 +62,24 @@ type monoMultiQAContract struct {
|
||||
SkillsWithoutReferencesAllowlist []string `yaml:"skills_without_references_allowlist"`
|
||||
}
|
||||
|
||||
type monoMultiLinkSubstitution struct {
|
||||
Mono string `yaml:"mono"`
|
||||
Multi string `yaml:"multi"`
|
||||
}
|
||||
|
||||
type markdownLink struct {
|
||||
Line int
|
||||
Target string
|
||||
}
|
||||
|
||||
type markdownLinkIssue struct {
|
||||
Link markdownLink
|
||||
Resolved string
|
||||
Err error
|
||||
}
|
||||
|
||||
var inlineMarkdownLinkPattern = regexp.MustCompile(`!?\[[^\]\n]*\]\(\s*(<[^>\n]+>|[^)\s\n]+)(?:\s+[^)\n]+)?\)`)
|
||||
|
||||
func loadMonoMultiQAContract(t *testing.T) (string, monoMultiQAContract) {
|
||||
t.Helper()
|
||||
root := repoRoot(t)
|
||||
@@ -255,13 +282,50 @@ func TestMonoMultiSkillContentG4Drift(t *testing.T) {
|
||||
if mode == "" {
|
||||
mode = "identical"
|
||||
}
|
||||
switch mode {
|
||||
case "identical":
|
||||
if err := comparePairedFileContent(monoData, multiData, mode, pair.LinkSubstitutions); err != nil {
|
||||
t.Errorf("G4: paired file mono %s vs multi %s: %v", pair.Mono, pair.Multi, err)
|
||||
}
|
||||
}
|
||||
|
||||
for _, pair := range c.PairedTrees {
|
||||
if pair.Mono == "" || pair.Multi == "" {
|
||||
t.Fatalf("G4: paired tree requires mono and multi paths: %+v", pair)
|
||||
}
|
||||
mode := pair.Mode
|
||||
if mode == "" {
|
||||
mode = "identical"
|
||||
}
|
||||
if mode != "identical" {
|
||||
t.Errorf("G4: unknown paired tree mode %q", mode)
|
||||
continue
|
||||
}
|
||||
|
||||
monoDir := filepath.Join(root, "skills", "mono", filepath.FromSlash(pair.Mono))
|
||||
multiDir := filepath.Join(multiRoot, filepath.FromSlash(pair.Multi))
|
||||
monoFiles, err := readRelativeFileTree(monoDir)
|
||||
if err != nil {
|
||||
t.Errorf("G4: paired mono tree %s: %v", pair.Mono, err)
|
||||
continue
|
||||
}
|
||||
multiFiles, err := readRelativeFileTree(multiDir)
|
||||
if err != nil {
|
||||
t.Errorf("G4: paired multi tree %s: %v", pair.Multi, err)
|
||||
continue
|
||||
}
|
||||
for rel, monoData := range monoFiles {
|
||||
multiData, ok := multiFiles[rel]
|
||||
if !ok {
|
||||
t.Errorf("G4: paired multi tree %s missing %s from mono %s", pair.Multi, rel, pair.Mono)
|
||||
continue
|
||||
}
|
||||
if !bytes.Equal(monoData, multiData) {
|
||||
t.Errorf("G4: paired files differ: mono %s vs multi %s", pair.Mono, pair.Multi)
|
||||
t.Errorf("G4: paired tree file differs: mono %s/%s vs multi %s/%s", pair.Mono, rel, pair.Multi, rel)
|
||||
}
|
||||
}
|
||||
for rel := range multiFiles {
|
||||
if _, ok := monoFiles[rel]; !ok {
|
||||
t.Errorf("G4: paired mono tree %s missing %s from multi %s", pair.Mono, rel, pair.Multi)
|
||||
}
|
||||
default:
|
||||
t.Errorf("G4: unknown paired mode %q", mode)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -318,6 +382,396 @@ func TestMonoMultiSkillContentG4Drift(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonoMultiSkillContentG5RelativeLinks(t *testing.T) {
|
||||
root, c := loadMonoMultiQAContract(t)
|
||||
multiRoot := filepath.Join(root, "skills", "multi")
|
||||
sources := map[string]bool{}
|
||||
|
||||
for _, pair := range c.PairedFiles {
|
||||
if pair.Mono == "" || pair.Multi == "" {
|
||||
t.Fatalf("G5: paired file requires mono and multi paths: %+v", pair)
|
||||
}
|
||||
sources[filepath.Join(root, "skills", "mono", filepath.FromSlash(pair.Mono))] = true
|
||||
sources[filepath.Join(multiRoot, filepath.FromSlash(pair.Multi))] = true
|
||||
}
|
||||
for _, pair := range c.PairedTrees {
|
||||
if pair.Mono == "" || pair.Multi == "" {
|
||||
t.Fatalf("G5: paired tree requires mono and multi paths: %+v", pair)
|
||||
}
|
||||
trees := []string{
|
||||
filepath.Join(root, "skills", "mono", filepath.FromSlash(pair.Mono)),
|
||||
filepath.Join(multiRoot, filepath.FromSlash(pair.Multi)),
|
||||
}
|
||||
for _, tree := range trees {
|
||||
files, err := readRelativeFileTree(tree)
|
||||
if err != nil {
|
||||
t.Errorf("G5: read paired Markdown tree %s: %v", tree, err)
|
||||
continue
|
||||
}
|
||||
for rel := range files {
|
||||
sources[filepath.Join(tree, filepath.FromSlash(rel))] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
paths := make([]string, 0, len(sources))
|
||||
for path := range sources {
|
||||
paths = append(paths, path)
|
||||
}
|
||||
sort.Strings(paths)
|
||||
for _, source := range paths {
|
||||
if !strings.EqualFold(filepath.Ext(source), ".md") {
|
||||
continue
|
||||
}
|
||||
data, err := os.ReadFile(source)
|
||||
if err != nil {
|
||||
t.Errorf("G5: read %s: %v", source, err)
|
||||
continue
|
||||
}
|
||||
rel, relErr := filepath.Rel(root, source)
|
||||
if relErr != nil {
|
||||
rel = source
|
||||
}
|
||||
for _, issue := range unresolvedRelativeMarkdownLinks(root, source, data) {
|
||||
resolved := issue.Resolved
|
||||
if resolved != "" {
|
||||
if resolvedRel, err := filepath.Rel(root, resolved); err == nil {
|
||||
resolved = filepath.ToSlash(resolvedRel)
|
||||
}
|
||||
}
|
||||
t.Errorf("G5: %s:%d relative link %q resolves to %q: %v", filepath.ToSlash(rel), issue.Link.Line, issue.Link.Target, resolved, issue.Err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonoMultiSkillContentLinkNormalization(t *testing.T) {
|
||||
rules := []monoMultiLinkSubstitution{
|
||||
{Mono: "../url-patterns.md", Multi: "../../dingtalk-shared/references/url-patterns.md"},
|
||||
{Mono: "../intent-guide.md", Multi: "sheet-intent-guide.md"},
|
||||
}
|
||||
mono := []byte("url=../url-patterns.md\nintent=../intent-guide.md\n")
|
||||
multi := []byte("url=../../dingtalk-shared/references/url-patterns.md\nintent=sheet-intent-guide.md\n")
|
||||
if err := comparePairedFileContent(mono, multi, "link-normalized", rules); err != nil {
|
||||
t.Fatalf("valid substitutions rejected: %v", err)
|
||||
}
|
||||
if err := comparePairedFileContent(mono, append(multi, []byte("drift\n")...), "link-normalized", rules); err == nil {
|
||||
t.Fatal("unknown content drift must not be normalized away")
|
||||
}
|
||||
if err := comparePairedFileContent(mono, multi, "identical", rules); err == nil {
|
||||
t.Fatal("identical mode must reject link substitutions")
|
||||
}
|
||||
if err := comparePairedFileContent(mono, multi, "unknown", nil); err == nil {
|
||||
t.Fatal("unknown paired-file mode must fail closed")
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonoMultiSkillContentLinkNormalizationRejectsInvalidRules(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
mono string
|
||||
multi string
|
||||
rules []monoMultiLinkSubstitution
|
||||
}{
|
||||
{name: "no rules", mono: "m1", multi: "x1"},
|
||||
{name: "empty mono", mono: "m1", multi: "x1", rules: []monoMultiLinkSubstitution{{Multi: "x1"}}},
|
||||
{name: "empty multi", mono: "m1", multi: "x1", rules: []monoMultiLinkSubstitution{{Mono: "m1"}}},
|
||||
{name: "same sides", mono: "m1", multi: "m1", rules: []monoMultiLinkSubstitution{{Mono: "m1", Multi: "m1"}}},
|
||||
{name: "duplicate mono", mono: "m1", multi: "x1 x2", rules: []monoMultiLinkSubstitution{{Mono: "m1", Multi: "x1"}, {Mono: "m1", Multi: "x2"}}},
|
||||
{name: "duplicate multi", mono: "m1 m2", multi: "x1", rules: []monoMultiLinkSubstitution{{Mono: "m1", Multi: "x1"}, {Mono: "m2", Multi: "x1"}}},
|
||||
{name: "overlapping mono", mono: "m1 m", multi: "x1 x2", rules: []monoMultiLinkSubstitution{{Mono: "m", Multi: "x1"}, {Mono: "m1", Multi: "x2"}}},
|
||||
{name: "missing occurrence", mono: "m1", multi: "x1", rules: []monoMultiLinkSubstitution{{Mono: "m2", Multi: "x1"}}},
|
||||
{name: "multiple occurrences", mono: "m1 m1", multi: "x1", rules: []monoMultiLinkSubstitution{{Mono: "m1", Multi: "x1"}}},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if _, _, err := normalizePairedFileLinks([]byte(tt.mono), []byte(tt.multi), tt.rules); err == nil {
|
||||
t.Fatal("invalid substitution rules must fail closed")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonoMultiSkillContentRelativeLinkScanner(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
docs := filepath.Join(root, "docs")
|
||||
if err := os.MkdirAll(filepath.Join(docs, "sheet"), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(docs, "topic.md"), []byte("# Topic\n"), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body := []byte("[topic](./topic.md#section)\n[directory](./sheet/)\n[external](https://example.com/a)\n[email](mailto:test@example.com)\n[anchor](#section)\n`[inline](missing-inline.md)`\n```text\n[fenced](missing-fenced.md)\n```\n[missing](missing.md)\n[escape](../../escape.md)\n")
|
||||
issues := unresolvedRelativeMarkdownLinks(root, filepath.Join(docs, "source.md"), body)
|
||||
if len(issues) != 2 {
|
||||
t.Fatalf("got %d unresolved links, want 2: %+v", len(issues), issues)
|
||||
}
|
||||
if issues[0].Link.Target != "missing.md" || issues[0].Link.Line != 10 {
|
||||
t.Fatalf("unexpected unresolved link: %+v", issues[0])
|
||||
}
|
||||
if issues[1].Link.Target != "../../escape.md" || issues[1].Link.Line != 11 || !strings.Contains(issues[1].Err.Error(), "escapes repository") {
|
||||
t.Fatalf("unexpected escaping link: %+v", issues[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestMonoMultiSkillContentReadRelativeFileTreeFiltersNonMarkdown(t *testing.T) {
|
||||
root := t.TempDir()
|
||||
for _, dir := range []string{"nested", ".hidden"} {
|
||||
if err := os.MkdirAll(filepath.Join(root, dir), 0o755); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
files := map[string]string{
|
||||
"guide.md": "visible",
|
||||
"nested/topic.md": "nested",
|
||||
"notes.txt": "ignored",
|
||||
".DS_Store": "ignored",
|
||||
".draft.md": "ignored",
|
||||
".hidden/topic.md": "ignored",
|
||||
"nested/README.MD": "accepted",
|
||||
"nested/.hidden.md": "ignored",
|
||||
}
|
||||
for rel, body := range files {
|
||||
if err := os.WriteFile(filepath.Join(root, filepath.FromSlash(rel)), []byte(body), 0o644); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got, err := readRelativeFileTree(root)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"guide.md", "nested/README.MD", "nested/topic.md"}
|
||||
gotNames := make([]string, 0, len(got))
|
||||
for rel := range got {
|
||||
gotNames = append(gotNames, rel)
|
||||
}
|
||||
sort.Strings(gotNames)
|
||||
if strings.Join(gotNames, "\n") != strings.Join(want, "\n") {
|
||||
t.Fatalf("visible Markdown tree = %v, want %v", gotNames, want)
|
||||
}
|
||||
}
|
||||
|
||||
func comparePairedFileContent(monoData, multiData []byte, mode string, substitutions []monoMultiLinkSubstitution) error {
|
||||
switch mode {
|
||||
case "identical":
|
||||
if len(substitutions) != 0 {
|
||||
return fmt.Errorf("identical mode does not allow link_substitutions")
|
||||
}
|
||||
if !bytes.Equal(monoData, multiData) {
|
||||
return fmt.Errorf("contents differ")
|
||||
}
|
||||
return nil
|
||||
case "link-normalized":
|
||||
monoNormalized, multiNormalized, err := normalizePairedFileLinks(monoData, multiData, substitutions)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !bytes.Equal(monoNormalized, multiNormalized) {
|
||||
return fmt.Errorf("contents differ after declared link substitutions")
|
||||
}
|
||||
return nil
|
||||
default:
|
||||
return fmt.Errorf("unknown paired mode %q", mode)
|
||||
}
|
||||
}
|
||||
|
||||
func normalizePairedFileLinks(monoData, multiData []byte, substitutions []monoMultiLinkSubstitution) ([]byte, []byte, error) {
|
||||
if len(substitutions) == 0 {
|
||||
return nil, nil, fmt.Errorf("link-normalized mode requires link_substitutions")
|
||||
}
|
||||
for i, substitution := range substitutions {
|
||||
if substitution.Mono == "" || substitution.Multi == "" {
|
||||
return nil, nil, fmt.Errorf("link_substitutions[%d] requires non-empty mono and multi values", i)
|
||||
}
|
||||
if substitution.Mono == substitution.Multi {
|
||||
return nil, nil, fmt.Errorf("link_substitutions[%d] must describe a layout difference", i)
|
||||
}
|
||||
for j := 0; j < i; j++ {
|
||||
previous := substitutions[j]
|
||||
if strings.Contains(substitution.Mono, previous.Mono) || strings.Contains(previous.Mono, substitution.Mono) {
|
||||
return nil, nil, fmt.Errorf("link_substitutions[%d].mono overlaps link_substitutions[%d].mono", i, j)
|
||||
}
|
||||
if strings.Contains(substitution.Multi, previous.Multi) || strings.Contains(previous.Multi, substitution.Multi) {
|
||||
return nil, nil, fmt.Errorf("link_substitutions[%d].multi overlaps link_substitutions[%d].multi", i, j)
|
||||
}
|
||||
}
|
||||
if count := bytes.Count(monoData, []byte(substitution.Mono)); count != 1 {
|
||||
return nil, nil, fmt.Errorf("link_substitutions[%d].mono occurs %d times, want exactly 1", i, count)
|
||||
}
|
||||
if count := bytes.Count(multiData, []byte(substitution.Multi)); count != 1 {
|
||||
return nil, nil, fmt.Errorf("link_substitutions[%d].multi occurs %d times, want exactly 1", i, count)
|
||||
}
|
||||
}
|
||||
|
||||
monoNormalized := bytes.Clone(monoData)
|
||||
multiNormalized := bytes.Clone(multiData)
|
||||
for i, substitution := range substitutions {
|
||||
marker := []byte(fmt.Sprintf("\x00DWS_LINK_SUBSTITUTION_%d\x00", i))
|
||||
if bytes.Contains(monoNormalized, marker) || bytes.Contains(multiNormalized, marker) {
|
||||
return nil, nil, fmt.Errorf("link_substitutions[%d] normalization marker already exists in content", i)
|
||||
}
|
||||
monoNormalized = bytes.Replace(monoNormalized, []byte(substitution.Mono), marker, 1)
|
||||
multiNormalized = bytes.Replace(multiNormalized, []byte(substitution.Multi), marker, 1)
|
||||
}
|
||||
return monoNormalized, multiNormalized, nil
|
||||
}
|
||||
|
||||
func unresolvedRelativeMarkdownLinks(repoRoot, source string, body []byte) []markdownLinkIssue {
|
||||
var issues []markdownLinkIssue
|
||||
for _, link := range extractMarkdownLinks(body) {
|
||||
targetPath, check, err := relativeMarkdownTargetPath(link.Target)
|
||||
if err != nil {
|
||||
issues = append(issues, markdownLinkIssue{Link: link, Err: err})
|
||||
continue
|
||||
}
|
||||
if !check {
|
||||
continue
|
||||
}
|
||||
resolved := filepath.Clean(filepath.Join(filepath.Dir(source), filepath.FromSlash(targetPath)))
|
||||
rel, err := filepath.Rel(repoRoot, resolved)
|
||||
if err != nil {
|
||||
issues = append(issues, markdownLinkIssue{Link: link, Resolved: resolved, Err: err})
|
||||
continue
|
||||
}
|
||||
if rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSeparator)) {
|
||||
issues = append(issues, markdownLinkIssue{Link: link, Resolved: resolved, Err: fmt.Errorf("target escapes repository")})
|
||||
continue
|
||||
}
|
||||
if _, err := os.Stat(resolved); err != nil {
|
||||
issues = append(issues, markdownLinkIssue{Link: link, Resolved: resolved, Err: err})
|
||||
continue
|
||||
}
|
||||
realRoot, err := filepath.EvalSymlinks(repoRoot)
|
||||
if err != nil {
|
||||
issues = append(issues, markdownLinkIssue{Link: link, Resolved: resolved, Err: fmt.Errorf("resolve repository path: %w", err)})
|
||||
continue
|
||||
}
|
||||
realTarget, err := filepath.EvalSymlinks(resolved)
|
||||
if err != nil {
|
||||
issues = append(issues, markdownLinkIssue{Link: link, Resolved: resolved, Err: fmt.Errorf("resolve target path: %w", err)})
|
||||
continue
|
||||
}
|
||||
realRel, err := filepath.Rel(realRoot, realTarget)
|
||||
if err != nil || realRel == ".." || strings.HasPrefix(realRel, ".."+string(os.PathSeparator)) {
|
||||
if err == nil {
|
||||
err = fmt.Errorf("target escapes repository through a symbolic link")
|
||||
}
|
||||
issues = append(issues, markdownLinkIssue{Link: link, Resolved: resolved, Err: err})
|
||||
}
|
||||
}
|
||||
return issues
|
||||
}
|
||||
|
||||
func extractMarkdownLinks(body []byte) []markdownLink {
|
||||
var links []markdownLink
|
||||
var fence byte
|
||||
for i, line := range strings.Split(string(body), "\n") {
|
||||
if marker := markdownFenceMarker(line); marker != 0 {
|
||||
if fence == 0 {
|
||||
fence = marker
|
||||
} else if fence == marker {
|
||||
fence = 0
|
||||
}
|
||||
continue
|
||||
}
|
||||
if fence != 0 {
|
||||
continue
|
||||
}
|
||||
masked := maskInlineMarkdownCode(line)
|
||||
for _, match := range inlineMarkdownLinkPattern.FindAllStringSubmatch(masked, -1) {
|
||||
target := match[1]
|
||||
if strings.HasPrefix(target, "<") && strings.HasSuffix(target, ">") {
|
||||
target = strings.TrimSuffix(strings.TrimPrefix(target, "<"), ">")
|
||||
}
|
||||
links = append(links, markdownLink{Line: i + 1, Target: target})
|
||||
}
|
||||
}
|
||||
return links
|
||||
}
|
||||
|
||||
func markdownFenceMarker(line string) byte {
|
||||
trimmed := strings.TrimLeft(line, " \t")
|
||||
if strings.HasPrefix(trimmed, "```") {
|
||||
return '`'
|
||||
}
|
||||
if strings.HasPrefix(trimmed, "~~~") {
|
||||
return '~'
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func maskInlineMarkdownCode(line string) string {
|
||||
masked := []byte(line)
|
||||
for i := 0; i < len(masked); {
|
||||
if masked[i] != '`' {
|
||||
i++
|
||||
continue
|
||||
}
|
||||
endOfOpener := i
|
||||
for endOfOpener < len(masked) && masked[endOfOpener] == '`' {
|
||||
endOfOpener++
|
||||
}
|
||||
marker := masked[i:endOfOpener]
|
||||
closingOffset := bytes.Index(masked[endOfOpener:], marker)
|
||||
if closingOffset < 0 {
|
||||
i = endOfOpener
|
||||
continue
|
||||
}
|
||||
end := endOfOpener + closingOffset + len(marker)
|
||||
for j := i; j < end; j++ {
|
||||
masked[j] = ' '
|
||||
}
|
||||
i = end
|
||||
}
|
||||
return string(masked)
|
||||
}
|
||||
|
||||
func relativeMarkdownTargetPath(target string) (string, bool, error) {
|
||||
parsed, err := url.Parse(target)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("parse target: %w", err)
|
||||
}
|
||||
if parsed.Scheme != "" || parsed.Host != "" || strings.HasPrefix(target, "//") || strings.HasPrefix(parsed.Path, "/") {
|
||||
return "", false, nil
|
||||
}
|
||||
if parsed.Path == "" {
|
||||
return "", false, nil
|
||||
}
|
||||
path, err := url.PathUnescape(parsed.Path)
|
||||
if err != nil {
|
||||
return "", false, fmt.Errorf("decode target path: %w", err)
|
||||
}
|
||||
return path, true, nil
|
||||
}
|
||||
|
||||
func readRelativeFileTree(root string) (map[string][]byte, error) {
|
||||
files := map[string][]byte{}
|
||||
err := filepath.WalkDir(root, func(path string, entry os.DirEntry, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if entry.IsDir() {
|
||||
if path != root && strings.HasPrefix(entry.Name(), ".") {
|
||||
return filepath.SkipDir
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if strings.HasPrefix(entry.Name(), ".") || !strings.EqualFold(filepath.Ext(entry.Name()), ".md") {
|
||||
return nil
|
||||
}
|
||||
rel, err := filepath.Rel(root, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
data, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
files[filepath.ToSlash(rel)] = data
|
||||
return nil
|
||||
})
|
||||
return files, err
|
||||
}
|
||||
|
||||
type skillFrontmatter struct {
|
||||
Name string `yaml:"name"`
|
||||
Description string `yaml:"description"`
|
||||
|
||||
Reference in New Issue
Block a user