Skip to content
Open
Show file tree
Hide file tree
Changes from 1 commit
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
}
91 changes: 91 additions & 0 deletions shortcuts/base/field_group_create_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// Copyright (c) 2026 Lark Technologies Pte. Ltd.
// SPDX-License-Identifier: MIT

package base

import (
"context"
"strings"
"testing"
)

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"},
{"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)
}
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"}]`)
}
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
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