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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion shortcuts/base/base_shortcuts_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -169,7 +169,7 @@ func TestShortcutsCatalog(t *testing.T) {
"+url-resolve", "+title-resolve",
"+base-block-list", "+base-block-create", "+base-block-move", "+base-block-rename", "+base-block-delete",
"+table-list", "+table-get", "+table-create", "+table-update", "+table-delete", "+table-copy", "+table-copy-status",
"+field-list", "+field-get", "+field-create", "+field-update", "+field-delete", "+field-search-options",
"+field-list", "+field-get", "+field-create", "+field-update", "+field-delete", "+field-group-create", "+field-search-options",
"+field-extension-get", "+field-extension-update", "+field-extension-update-cells",
"+view-list", "+view-get", "+view-create", "+view-delete", "+view-get-filter", "+view-set-filter", "+view-get-visible-fields", "+view-set-visible-fields", "+view-get-group", "+view-set-group", "+view-get-sort", "+view-set-sort", "+view-get-timebar", "+view-set-timebar", "+view-get-card", "+view-set-card", "+view-rename",
"+record-list", "+record-search", "+record-get", "+record-upsert", "+record-batch-create", "+record-batch-update", "+record-share-link-create", "+record-upload-attachment", "+record-download-attachment", "+record-remove-attachment", "+record-delete",
Expand Down
150 changes: 150 additions & 0 deletions shortcuts/base/field_group_create.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT

package base

import (
"context"
"fmt"
"net/http"
"strings"

larkcore "github.com/larksuite/oapi-sdk-go/v3/core"

"github.com/larksuite/cli/internal/validate"
"github.com/larksuite/cli/shortcuts/common"
)

var BaseFieldGroupCreate = common.Shortcut{
Service: "base",
Command: "+field-group-create",
Description: "Create field groups on a table",
Risk: "write",
Scopes: []string{"base:field_group:create"},
AuthTypes: authTypes(),
Flags: []common.Flag{
baseTokenFlag(true),
tableRefFlag(true),
{Name: "json", Desc: `field group JSON object with a "field_groups" array, or a bare array of groups; supports @file`, Required: true},
},
Tips: []string{
`Example: lark-cli base +field-group-create --base-token <base_token> --table-id <table_id> --json '{"field_groups":[{"name":"Customer Info","children":[{"type":"field","id":"fldXXXXXX"}]}]}'`,
"Field groups bundle fields in the table UI; they are distinct from +view-set-group, which groups records inside a view.",
"Each field can belong to only one field group; a conflict fails with 1254122 (Child belongs to multiple field groups).",
"The platform exposes create only: there is no list, update, or delete field group API, so a 1254122 retry cannot check-then-create. Pick unused field IDs before retrying.",
"Requires scope base:field_group:create; a full-domain auth login may omit it, request it explicitly with lark-cli auth login --scope base:field_group:create.",
},
Validate: func(ctx context.Context, runtime *common.RuntimeContext) error {
_, err := parseFieldGroupBodies(newParseCtx(runtime), runtime.Str("json"))
return err
},
DryRun: func(ctx context.Context, runtime *common.RuntimeContext) *common.DryRunAPI {
groups, err := parseFieldGroupBodies(newParseCtx(runtime), runtime.Str("json"))
if err != nil {
return common.NewDryRunAPI().Desc(fmt.Sprintf("dry-run validation failed: %v", err))
}
return common.NewDryRunAPI().
POST("/open-apis/bitable/v1/apps/:base_token/tables/:table_id/field_groups").
Body(map[string]interface{}{"field_groups": groups}).
Set("base_token", runtime.Str("base-token")).
Set("table_id", baseTableID(runtime))
},
Execute: func(ctx context.Context, runtime *common.RuntimeContext) error {
groups, err := parseFieldGroupBodies(newParseCtx(runtime), runtime.Str("json"))
if err != nil {
return err
}

apiResp, err := runtime.DoAPI(&larkcore.ApiReq{
HttpMethod: http.MethodPost,
ApiPath: fmt.Sprintf(
"/open-apis/bitable/v1/apps/%s/tables/%s/field_groups",
validate.EncodePathSegment(runtime.Str("base-token")),
validate.EncodePathSegment(baseTableID(runtime)),
),
Body: map[string]interface{}{"field_groups": groups},
})
if err != nil {
return err
}

return handleRoleAPIResponse(runtime, apiResp, "create field groups failed")
},
}

// parseFieldGroupBodies parses --json into the field_groups array, accepting
// either the API body shape {"field_groups":[...]} or a bare array of groups.
func parseFieldGroupBodies(pc *parseCtx, raw string) ([]interface{}, error) {
resolved, err := loadJSONInput(pc, raw, "json")
if err != nil {
return nil, err
}
resolved = strings.TrimSpace(resolved)

var groups []interface{}
switch {
case strings.HasPrefix(resolved, "["):
if err := common.ParseJSON([]byte(resolved), &groups); err != nil {
return nil, formatJSONError("json", "array", err)
}
case strings.HasPrefix(resolved, "{"):
var body map[string]interface{}
if err := common.ParseJSON([]byte(resolved), &body); err != nil {
return nil, formatJSONError("json", "object", err)
}
rawGroups, ok := body["field_groups"]
if !ok {
return nil, baseFlagErrorf(`--json object must contain a "field_groups" array`)
}
arr, ok := rawGroups.([]interface{})
if !ok {
return nil, baseFlagErrorf(`--json "field_groups" must be an array`)
}
groups = arr
default:
return nil, baseFlagErrorf("--json must be a JSON array of field groups or an object with a field_groups array")
}

return validateFieldGroupBodies(groups)
}

// validateFieldGroupBodies enforces the API's group contract plus the
// one-field-one-group rule client-side, because the create-only API gives no
// way to check membership before retrying a 1254122 conflict.
func validateFieldGroupBodies(groups []interface{}) ([]interface{}, error) {
if len(groups) == 0 {
return nil, baseFlagErrorf("--json must contain at least one field group")
}

seen := map[string]string{}
for i, g := range groups {
group, ok := g.(map[string]interface{})
if !ok {
return nil, baseFlagErrorf("field group %d must be an object", i+1)
}
name := strings.TrimSpace(common.GetString(group, "name"))
if name == "" {
return nil, baseFlagErrorf("field group %d needs a non-empty name", i+1)
}
rawChildren, ok := group["children"].([]interface{})
if !ok || len(rawChildren) == 0 {
return nil, baseFlagErrorf("field group %q needs at least one child", name)
}
for j, c := range rawChildren {
child, ok := c.(map[string]interface{})
if !ok {
return nil, baseFlagErrorf("field group %q child %d must be an object", name, j+1)
}
childType := strings.TrimSpace(common.GetString(child, "type"))
childID := strings.TrimSpace(common.GetString(child, "id"))
if childType == "" || childID == "" {
return nil, baseFlagErrorf("field group %q child %d needs type and id", name, j+1)
}
if prev, dup := seen[childID]; dup {
return nil, baseFlagErrorf("field %q is listed in both %q and %q; each field can belong to only one field group", childID, prev, name)
}
seen[childID] = name
}
}
return groups, nil
}
136 changes: 136 additions & 0 deletions shortcuts/base/field_group_create_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,136 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT

package base

import (
"context"
"os"
"path/filepath"
"strings"
"testing"

"github.com/larksuite/cli/errs"
)

func TestParseFieldGroupBodiesAcceptsWrappedAndBare(t *testing.T) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
rt := newBaseTestRuntime(nil, nil, nil)
pc := newParseCtx(rt)

wrapped := `{"field_groups":[{"name":"G1","children":[{"type":"field","id":"fldA"}]}]}`
groups, err := parseFieldGroupBodies(pc, wrapped)
if err != nil {
t.Fatalf("wrapped body: %v", err)
}
if len(groups) != 1 {
t.Fatalf("wrapped body groups = %d, want 1", len(groups))
}

bare := `[{"name":"G1","children":[{"type":"field","id":"fldA"}]}]`
groups, err = parseFieldGroupBodies(pc, bare)
if err != nil {
t.Fatalf("bare array: %v", err)
}
if len(groups) != 1 {
t.Fatalf("bare array groups = %d, want 1", len(groups))
}
}

func TestParseFieldGroupBodiesRejectsBadShapes(t *testing.T) {
rt := newBaseTestRuntime(nil, nil, nil)
pc := newParseCtx(rt)

cases := []struct {
name string
raw string
want string
}{
{"not json", `nope`, "--json"},
{"malformed json", `[{"name":]`, "--json"},
{"empty array", `[]`, "at least one field group"},
{"object without field_groups", `{"groups":[]}`, "field_groups"},
{"group without name", `[{"children":[{"type":"field","id":"fldA"}]}]`, "non-empty name"},
{"group without children", `[{"name":"G1"}]`, "at least one child"},
{"child without id", `[{"name":"G1","children":[{"type":"field"}]}]`, "type and id"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
_, err := parseFieldGroupBodies(pc, tc.raw)
if err == nil {
t.Fatalf("expected error for %s", tc.name)
}
p, ok := errs.ProblemOf(err)
if !ok {
t.Fatalf("expected typed error, got %T %v", err, err)
}
if p.Category != errs.CategoryValidation || p.Subtype != errs.SubtypeInvalidArgument {
t.Fatalf("category/subtype=%s/%s, want validation/invalid_argument", p.Category, p.Subtype)
}
if !strings.Contains(err.Error(), tc.want) {
t.Fatalf("error %q missing %q", err.Error(), tc.want)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
})
}
}

func TestParseFieldGroupBodiesRejectsDuplicateFieldAcrossGroups(t *testing.T) {
rt := newBaseTestRuntime(nil, nil, nil)
pc := newParseCtx(rt)

raw := `[{"name":"G1","children":[{"type":"field","id":"fldA"}]},{"name":"G2","children":[{"type":"field","id":"fldA"}]}]`
_, err := parseFieldGroupBodies(pc, raw)
if err == nil {
t.Fatal("expected duplicate field error")
}
if !strings.Contains(err.Error(), "only one field group") {
t.Fatalf("unexpected error: %v", err)
}
}

func TestDryRunFieldGroupCreate(t *testing.T) {
ctx := context.Background()
rt := newBaseTestRuntime(map[string]string{
"base-token": "app_x",
"table-id": "tbl_1",
"json": `{"field_groups":[{"name":"Customer Info","children":[{"type":"field","id":"fldA"}]}]}`,
}, nil, nil)

sc := BaseFieldGroupCreate
assertDryRunContains(t, sc.DryRun(ctx, rt),
"POST /open-apis/bitable/v1/apps/app_x/tables/tbl_1/field_groups",
`"name":"Customer Info"`,
`"children":[{"id":"fldA","type":"field"}]`)
}

func TestDryRunFieldGroupCreateFromFile(t *testing.T) {
tmpDir := t.TempDir()
specPath := filepath.Join(tmpDir, "groups.json")
spec := `[{"name":"From File","children":[{"type":"field","id":"fldF"}]}]`
if err := os.WriteFile(specPath, []byte(spec), 0o600); err != nil {
t.Fatalf("write spec: %v", err)
}
withBaseWorkingDir(t, tmpDir)

factory, stdout, _ := newExecuteFactory(t)
err := runShortcut(t, BaseFieldGroupCreate, []string{
"+field-group-create",
"--base-token", "app_x",
"--table-id", "tbl_1",
"--json", "@./groups.json",
"--dry-run",
}, factory, stdout)
if err != nil {
t.Fatalf("err=%v", err)
}
out := stdout.String()
for _, want := range []string{
`"method": "POST"`,
`"url": "/open-apis/bitable/v1/apps/app_x/tables/tbl_1/field_groups"`,
`"name": "From File"`,
`"id": "fldF"`,
} {
if !strings.Contains(out, want) {
t.Fatalf("dry-run output missing %q\noutput:\n%s", want, out)
}
}
}
1 change: 1 addition & 0 deletions shortcuts/base/shortcuts.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ func Shortcuts() []common.Shortcut {
BaseFieldCreate,
BaseFieldUpdate,
BaseFieldDelete,
BaseFieldGroupCreate,
BaseFieldSearchOptions,
BaseFieldExtensionGet,
BaseFieldExtensionUpdate,
Expand Down
2 changes: 2 additions & 0 deletions skills/lark-base/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,8 @@ Field 定义列 schema。`field_id` 是稳定列标识,`name` 是可修改的

**读取 Field:** `+field-list` / `+field-get` / `+field-search-options`。**写入 Field:** 已有 Table 中创建多个字段时,优先向一次 `+field-create --json` 传字段对象数组;单字段更新和删除用 `+field-update` / `+field-delete`。创建和更新分别读取 [field-create](references/lark-base-field-create.md) / [field-update](references/lark-base-field-update.md),由命令文档继续路由 Field JSON、Formula 和 Lookup 协议。`字段插件` 用于扩展基础字段能力:按同一行其他字段内容触发 LLM 生成,并写回已有目标字段;当前已确认目标字段支持文本、单选、数字,配置或触发前先读 [field-extension](references/lark-base-field-extension.md)。

**字段编组(Field Group):** 用 `+field-group-create` 把字段打包成 UI 编组,与 `+view-set-group`(视图内记录分组)不是一回事。每个字段只能属于一个编组,冲突报 `1254122`;平台只开放创建,没有 list/update/delete 接口,重试前先在 Table 里确认字段未被占用。

### Record

Record 是 Table 中的一行数据,包含该记录在各个 Field 下的 CellValue。系统 `record_id` 是表内稳定、非空且唯一的主键,Table 的主字段只是展示字段。
Expand Down
40 changes: 40 additions & 0 deletions tests/cli_e2e/base/base_field_group_dryrun_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT

package base

import (
"context"
"testing"
"time"

clie2e "github.com/larksuite/cli/tests/cli_e2e"
"github.com/stretchr/testify/require"
)

func TestBaseFieldGroupCreateDryRun(t *testing.T) {
setBaseDryRunConfigEnv(t)

ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
t.Cleanup(cancel)

result, err := clie2e.RunCmd(ctx, clie2e.Request{
Args: []string{
"base", "+field-group-create",
"--base-token", "app_x",
"--table-id", "tbl_x",
"--json", `{"field_groups":[{"name":"Customer Info","children":[{"type":"field","id":"fldA"}]}]}`,
"--dry-run",
},
DefaultAs: "bot",
})
require.NoError(t, err)
result.AssertExitCode(t, 0)

out := result.Stdout
require.Equal(t, "/open-apis/bitable/v1/apps/app_x/tables/tbl_x/field_groups", clie2e.DryRunGet(out, "api.0.url").String(), out)
require.Equal(t, "POST", clie2e.DryRunGet(out, "api.0.method").String(), out)
require.Equal(t, "Customer Info", clie2e.DryRunGet(out, "api.0.body.field_groups.0.name").String(), out)
require.Equal(t, "field", clie2e.DryRunGet(out, "api.0.body.field_groups.0.children.0.type").String(), out)
require.Equal(t, "fldA", clie2e.DryRunGet(out, "api.0.body.field_groups.0.children.0.id").String(), out)
}
Loading
Loading