Repository navigation
feat(base): add +field-group-create shortcut #2656
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
oliver-mee
wants to merge
3
commits into
larksuite:main
Choose a base branch
from
oliver-mee:feat/base-field-group-create
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from 1 commit
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) { | ||
| 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) | ||
| } | ||
|
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"}]`) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.