Documentation
¶
Index ¶
- Constants
- Variables
- func AtLeastOneTyped(rt *RuntimeContext, flags ...string) error
- func AutoGrantCurrentUserDrivePermission(runtime *RuntimeContext, token, resourceType string) map[string]interface{}
- func BuildResourceURL(brand core.LarkBrand, kind, token string) string
- func CallMCPTool(runtime *RuntimeContext, toolName string, args map[string]interface{}) (map[string]interface{}, error)
- func CheckApiError(w io.Writer, result interface{}, action string) bool
- func ClassifyAPIResponseWith(resp *larkcore.ApiResp, cc errclass.ClassifyContext) (map[string]interface{}, error)
- func DefaultMinuteArtifactDir(minuteToken string) string
- func DoMCPCall(ctx context.Context, httpClient *http.Client, toolName string, ...) (interface{}, error)
- func EachMap(items []interface{}, fn func(m map[string]interface{}))
- func ExactlyOneTyped(rt *RuntimeContext, flags ...string) error
- func ExtractMCPResult(raw interface{}) interface{}
- func FetchDriveMetaTitle(runtime *RuntimeContext, token, docType string) (string, error)
- func FetchDriveMetaURL(runtime *RuntimeContext, token, docType string) (string, error)
- func FormatSize(bytes int64) string
- func FormatTime(ts interface{}) string
- func FormatTimeWithSeconds(ts interface{}) string
- func GetBool(m map[string]interface{}, keys ...string) bool
- func GetFloat(m map[string]interface{}, keys ...string) float64
- func GetInt(m map[string]interface{}, keys ...string) int
- func GetMap(m map[string]interface{}, keys ...string) map[string]interface{}
- func GetSlice(m map[string]interface{}, keys ...string) []interface{}
- func GetString(m map[string]interface{}, keys ...string) string
- func IsDangerousUnicode(r rune) bool
- func MCPEndpoint(brand core.LarkBrand) string
- func MaskToken(token string) string
- func MutuallyExclusiveTyped(rt *RuntimeContext, flags ...string) error
- func PaginationHint(data map[string]interface{}, count int) string
- func PaginationMeta(data map[string]interface{}) (hasMore bool, pageToken string)
- func ParseJSON(data []byte, v interface{}) error
- func ParseTime(input string, hint ...string) (string, error)
- func RejectDangerousCharsTyped(paramName, value string) error
- func ResolveDownloadFileName(header http.Header, fallback string) string
- func ResolveOpenIDsTyped(flagName string, ids []string, runtime *RuntimeContext) ([]string, error)
- func SplitCSV(input string) []string
- func TruncateStr(s string, n int) string
- func UnwrapMCPResult(v interface{}) interface{}
- func UploadDriveMediaAllTyped(runtime *RuntimeContext, cfg DriveMediaUploadAllConfig) (string, error)
- func UploadDriveMediaMultipartTyped(runtime *RuntimeContext, cfg DriveMediaMultipartUploadConfig) (string, error)
- func ValidateChatIDTyped(param, input string) (string, error)
- func ValidatePageSizeTyped(rt *RuntimeContext, flagName string, defaultVal, minVal, maxVal int) (int, error)
- func ValidateSafePathTyped(fio fileio.FileIO, path string) error
- func ValidateUserIDTyped(param, input string) (string, error)
- func ValidationErrorf(format string, args ...any) *errs.ValidationError
- func WrapInputStatErrorTyped(err error, readMsg ...string) error
- func WrapOpenError(err error, pathMsg, readMsg string) error
- func WrapSaveErrorTyped(err error) error
- type BotInfo
- type DownloadExtensionResolution
- type DriveMediaMultipartUploadConfig
- type DriveMediaMultipartUploadSession
- type DriveMediaUploadAllConfig
- type DriveMeta
- type DryRunAPI
- type DryRunAPICall
- type Flag
- type MultipartWriter
- type ResourceRef
- type RuntimeContext
- func TestNewRuntimeContext(cmd *cobra.Command, cfg *core.CliConfig) *RuntimeContext
- func TestNewRuntimeContextForAPI(ctx context.Context, cmd *cobra.Command, cfg *core.CliConfig, ...) *RuntimeContext
- func TestNewRuntimeContextWithBotInfo(cmd *cobra.Command, cfg *core.CliConfig, info *BotInfo) *RuntimeContext
- func TestNewRuntimeContextWithCtx(ctx context.Context, cmd *cobra.Command, cfg *core.CliConfig) *RuntimeContext
- func TestNewRuntimeContextWithIdentity(cmd *cobra.Command, cfg *core.CliConfig, as core.Identity) *RuntimeContext
- func (ctx *RuntimeContext) APIClassifyContext() errclass.ClassifyContext
- func (ctx *RuntimeContext) AccessToken() (string, error)
- func (ctx *RuntimeContext) As() core.Identity
- func (ctx *RuntimeContext) Bool(name string) bool
- func (ctx *RuntimeContext) BotInfo() (*BotInfo, error)
- func (ctx *RuntimeContext) CallAPITyped(method, url string, params map[string]interface{}, data interface{}) (map[string]interface{}, error)
- func (ctx *RuntimeContext) Changed(name string) bool
- func (ctx *RuntimeContext) ClassifyAPIResponse(resp *larkcore.ApiResp) (map[string]interface{}, error)
- func (ctx *RuntimeContext) Command() string
- func (ctx *RuntimeContext) Ctx() context.Context
- func (ctx *RuntimeContext) DoAPI(req *larkcore.ApiReq, opts ...larkcore.RequestOptionFunc) (*larkcore.ApiResp, error)
- func (ctx *RuntimeContext) DoAPIAsBot(req *larkcore.ApiReq, opts ...larkcore.RequestOptionFunc) (*larkcore.ApiResp, error)
- func (ctx *RuntimeContext) DoAPIJSONTyped(method, apiPath string, query larkcore.QueryParams, body any) (map[string]any, error)
- func (ctx *RuntimeContext) DoAPIStream(callCtx context.Context, req *larkcore.ApiReq, opts ...client.Option) (*http.Response, error)
- func (ctx *RuntimeContext) EnsureScopes(scopes []string) error
- func (ctx *RuntimeContext) FileIO() fileio.FileIO
- func (ctx *RuntimeContext) Float64(name string) float64
- func (ctx *RuntimeContext) IO() *cmdutil.IOStreams
- func (ctx *RuntimeContext) Int(name string) int
- func (ctx *RuntimeContext) IntArray(name string) []int
- func (ctx *RuntimeContext) IsBot() bool
- func (ctx *RuntimeContext) Lang() i18n.Lang
- func (ctx *RuntimeContext) LarkSDK() *lark.Client
- func (ctx *RuntimeContext) Out(data interface{}, meta *output.Meta)
- func (ctx *RuntimeContext) OutFormat(data interface{}, meta *output.Meta, prettyFn func(w io.Writer))
- func (ctx *RuntimeContext) OutFormatRaw(data interface{}, meta *output.Meta, prettyFn func(w io.Writer))
- func (ctx *RuntimeContext) OutPartialFailure(data interface{}, meta *output.Meta) error
- func (ctx *RuntimeContext) OutRaw(data interface{}, meta *output.Meta)
- func (ctx *RuntimeContext) PaginateAll(method, url string, params map[string]interface{}, data interface{}, ...) (interface{}, error)
- func (ctx *RuntimeContext) RawAPI(method, url string, params map[string]interface{}, data interface{}) (interface{}, error)
- func (ctx *RuntimeContext) ResolveSavePath(path string) (string, error)
- func (ctx *RuntimeContext) Str(name string) string
- func (ctx *RuntimeContext) StrArray(name string) []string
- func (ctx *RuntimeContext) StrSlice(name string) []string
- func (ctx *RuntimeContext) StreamPages(method, url string, params map[string]interface{}, data interface{}, ...) (interface{}, bool, error)
- func (ctx *RuntimeContext) UserOpenId() string
- func (ctx *RuntimeContext) ValidatePath(path string) error
- type Shortcut
- func (s *Shortcut) ConditionalScopesForIdentity(identity string) []string
- func (s *Shortcut) DeclaredScopesForIdentity(identity string) []string
- func (s Shortcut) Mount(parent *cobra.Command, f *cmdutil.Factory)
- func (s Shortcut) MountWithContext(ctx context.Context, parent *cobra.Command, f *cmdutil.Factory)
- func (s *Shortcut) ScopesForIdentity(identity string) []string
Constants ¶
const ( PermissionGrantGranted = "granted" PermissionGrantSkipped = "skipped" PermissionGrantFailed = "failed" )
const ( File = "file" // support @path to read value from a file Stdin = "stdin" // support - to read value from stdin )
Flag.Input source constants.
const ArtifactTypeRecording = "recording"
ArtifactTypeRecording is the artifact_type value emitted by `minutes +download` so that callers can index results by kind without parsing saved_path.
const DefaultMinuteArtifactSubdir = "minutes"
DefaultMinuteArtifactSubdir is the top-level directory for minute-scoped artifacts under the default layout.
const DefaultTranscriptFileName = "transcript.txt"
DefaultTranscriptFileName is the fixed transcript filename under the default layout. Recording files keep the server-provided name.
const MaxDriveMediaUploadSinglePartSize int64 = 20 * 1024 * 1024 // 20MB
Variables ¶
var NewDryRunAPI = cmdutil.NewDryRunAPI
Functions ¶
func AtLeastOneTyped ¶ added in v1.0.47
func AtLeastOneTyped(rt *RuntimeContext, flags ...string) error
AtLeastOneTyped checks that at least one of the given flags is set.
func AutoGrantCurrentUserDrivePermission ¶ added in v1.0.7
func AutoGrantCurrentUserDrivePermission(runtime *RuntimeContext, token, resourceType string) map[string]interface{}
AutoGrantCurrentUserDrivePermission grants full_access on a newly created Drive resource to the current CLI user when the shortcut runs as bot.
Callers should attach the returned result only when it is non-nil.
func BuildResourceURL ¶ added in v1.0.21
BuildResourceURL returns a brand-standard, user-facing URL for a freshly created Lark resource. It is intended as a fallback when the create API does not return a URL field (e.g. drive +upload, wiki +node-create) or when the returned URL is empty (e.g. degraded MCP responses for docs +create v1).
The returned URL points at the brand's standard host (www.feishu.cn / www.larksuite.com), which transparently redirects to the tenant-specific domain. It is NOT a guess at the tenant's vanity domain.
Returns "" when token is empty or kind is unrecognized — callers should only set the field when the result is non-empty so that "" never overrides a real URL the backend already returned.
func CallMCPTool ¶
func CallMCPTool(runtime *RuntimeContext, toolName string, args map[string]interface{}) (map[string]interface{}, error)
CallMCPTool calls an MCP tool via JSON-RPC 2.0 and returns the parsed result.
func CheckApiError ¶
CheckApiError checks if API result is an error and prints it to w.
func ClassifyAPIResponseWith ¶ added in v1.0.52
func ClassifyAPIResponseWith(resp *larkcore.ApiResp, cc errclass.ClassifyContext) (map[string]interface{}, error)
ClassifyAPIResponseWith is the RuntimeContext-free form of ClassifyAPIResponse for callers that drive the request outside a running shortcut (e.g. a cobra command holding only a factory) and supply their own classification context.
func DefaultMinuteArtifactDir ¶ added in v1.0.18
DefaultMinuteArtifactDir returns the default output directory for an artifact keyed by minuteToken. The same path is shared across commands so that related artifacts of one meeting land together.
func EachMap ¶
func EachMap(items []interface{}, fn func(m map[string]interface{}))
EachMap iterates over map elements in a slice, skipping non-map items.
func ExactlyOneTyped ¶ added in v1.0.47
func ExactlyOneTyped(rt *RuntimeContext, flags ...string) error
ExactlyOneTyped checks that exactly one of the given flags is set.
func ExtractMCPResult ¶
func ExtractMCPResult(raw interface{}) interface{}
func FetchDriveMetaTitle ¶ added in v1.0.34
func FetchDriveMetaTitle(runtime *RuntimeContext, token, docType string) (string, error)
FetchDriveMetaTitle looks up the document title via the drive metas batch_query API.
func FetchDriveMetaURL ¶ added in v1.0.36
func FetchDriveMetaURL(runtime *RuntimeContext, token, docType string) (string, error)
FetchDriveMetaURL looks up the document access URL via the drive metas batch_query API.
func FormatSize ¶
func FormatTime ¶
func FormatTime(ts interface{}) string
FormatTime converts Unix seconds/ms string to local time string.
func FormatTimeWithSeconds ¶
func FormatTimeWithSeconds(ts interface{}) string
FormatTimeWithSeconds converts Unix seconds/ms string to local time string with seconds precision.
func GetInt ¶ added in v1.0.33
GetInt safely extracts an int, accepting both in-memory ints and JSON-style float64 values.
func GetString ¶
GetString safely extracts a string from a nested map path. Usage: GetString(data, "user", "name") is equivalent to data["user"].(map[string]interface{})["name"].(string)
func IsDangerousUnicode ¶
IsDangerousUnicode reports whether r is a Unicode character that can cause terminal injection: BiDi overrides, zero-width characters, and Unicode line terminators.
func MCPEndpoint ¶
func MutuallyExclusiveTyped ¶ added in v1.0.47
func MutuallyExclusiveTyped(rt *RuntimeContext, flags ...string) error
MutuallyExclusiveTyped checks that at most one of the given flags is set.
func PaginationHint ¶
PaginationHint returns a human-readable pagination hint for pretty output.
func PaginationMeta ¶
PaginationMeta extracts pagination metadata from an API response data map.
func ParseTime ¶
ParseTime converts time expressions to Unix seconds string.
Optional hint: "end" makes day-granularity inputs snap to 23:59:59 instead of 00:00:00.
ParseTime("2026-01-01") → 2026-01-01 00:00:00
ParseTime("2026-01-01", "end") → 2026-01-01 23:59:59
Supported formats: ISO 8601 (with or without time/timezone), date-only, Unix timestamp.
func RejectDangerousCharsTyped ¶ added in v1.0.47
RejectDangerousCharsTyped returns an error if value contains ASCII control characters or dangerous Unicode code points.
func ResolveDownloadFileName ¶ added in v1.0.33
ResolveDownloadFileName returns a sanitized filename from Content-Disposition, falling back to the caller-provided name when the header is absent or invalid.
func ResolveOpenIDsTyped ¶ added in v1.0.47
func ResolveOpenIDsTyped(flagName string, ids []string, runtime *RuntimeContext) ([]string, error)
ResolveOpenIDsTyped expands the special identifier "me" to the current user's open_id, removes duplicates case-insensitively while preserving the first-occurrence form, and returns nil for an empty input. flagName names the flag being resolved (e.g. "--user-ids") and is recorded on the typed error.
func TruncateStr ¶
TruncateStr truncates s to at most n runes.
func UnwrapMCPResult ¶
func UnwrapMCPResult(v interface{}) interface{}
func UploadDriveMediaAllTyped ¶ added in v1.0.48
func UploadDriveMediaAllTyped(runtime *RuntimeContext, cfg DriveMediaUploadAllConfig) (string, error)
UploadDriveMediaAllTyped uploads a file in a single request: file-open failures surface as typed validation errors, transport failures as typed network errors, and API failures are classified via ClassifyAPIResponse so subtype / code / log_id survive on the error.
func UploadDriveMediaMultipartTyped ¶ added in v1.0.48
func UploadDriveMediaMultipartTyped(runtime *RuntimeContext, cfg DriveMediaMultipartUploadConfig) (string, error)
UploadDriveMediaMultipartTyped uploads a file in server-planned chunks: prepare/finish failures come back typed from CallAPITyped, malformed session plans surface as invalid-response internal errors, and per-part transport/API failures are classified the same way as UploadDriveMediaAllTyped.
func ValidateChatIDTyped ¶ added in v1.0.47
ValidateChatIDTyped checks if a chat ID has valid format (oc_ prefix). Also extracts token from URL if provided. param names the flag being validated (e.g. "--chat-ids") and is recorded on the typed error.
func ValidatePageSizeTyped ¶ added in v1.0.47
func ValidatePageSizeTyped(rt *RuntimeContext, flagName string, defaultVal, minVal, maxVal int) (int, error)
ValidatePageSizeTyped validates that the named flag (if set) is an integer within [minVal, maxVal]. It returns the parsed value (or defaultVal if the flag is empty) and any validation error.
func ValidateSafePathTyped ¶ added in v1.0.47
ValidateSafePathTyped ensures path is relative and resolves within the current working directory. It catches traversal, symlink escape, and control characters by delegating to FileIO.ResolvePath. Works for both file and directory paths.
func ValidateUserIDTyped ¶ added in v1.0.47
ValidateUserIDTyped checks if a user ID has valid format (ou_ prefix). param names the flag being validated (e.g. "--creator-ids") and is recorded on the typed error.
func ValidationErrorf ¶ added in v1.0.47
func ValidationErrorf(format string, args ...any) *errs.ValidationError
ValidationErrorf returns a typed validation error with invalid_argument subtype.
func WrapInputStatErrorTyped ¶ added in v1.0.47
WrapInputStatErrorTyped wraps a FileIO.Stat/Open error for input file validation, returning a typed validation error with the appropriate message:
- Path validation failures → "unsafe file path: ..."
- Other errors → readMsg prefix (default "cannot read file")
Pass an optional readMsg to override the non-path-validation message prefix.
func WrapOpenError ¶ added in v1.0.6
WrapOpenError matches a FileIO.Open/Stat error and wraps it with the caller-provided message prefix.
func WrapSaveErrorTyped ¶ added in v1.0.47
WrapSaveErrorTyped maps a FileIO.Save error to typed validation/internal errors. Non-path failures always emit the canonical "internal" wire type; call sites migrating from a custom category (e.g. "io", "api_error") change their envelope's type field.
Types ¶
type BotInfo ¶ added in v1.0.9
BotInfo holds bot identity metadata fetched lazily from /bot/v3/info.
type DownloadExtensionResolution ¶ added in v1.0.33
DownloadExtensionResolution describes how a file extension was inferred.
func AutoAppendDownloadExtension ¶ added in v1.0.33
func AutoAppendDownloadExtension(outputPath string, header http.Header, fallbackExt string) (string, *DownloadExtensionResolution)
AutoAppendDownloadExtension appends an inferred file extension when the target path has no explicit suffix. If no extension can be inferred, the original basename is preserved without adding a synthetic fallback suffix.
type DriveMediaMultipartUploadConfig ¶ added in v1.0.6
type DriveMediaMultipartUploadSession ¶ added in v1.0.6
type DriveMediaUploadAllConfig ¶ added in v1.0.6
type DriveMediaUploadAllConfig struct {
FilePath string
FileName string
FileSize int64
ParentType string
ParentNode *string
Extra string
// Reader, when non-nil, is used as the upload source instead of opening
// FilePath. Callers must set FileName and FileSize explicitly. The reader
// is NOT closed by UploadDriveMediaAllTyped; the caller owns its lifetime.
// Used by the clipboard path in docs +media-insert.
Reader io.Reader
}
type DriveMeta ¶ added in v1.0.36
DriveMeta is the subset of drive metas/batch_query fields used by shortcuts.
func FetchDriveMeta ¶ added in v1.0.36
func FetchDriveMeta(runtime *RuntimeContext, token, docType string, withURL bool) (DriveMeta, error)
FetchDriveMeta looks up document metadata via the drive metas batch_query API.
type DryRunAPI ¶
Type aliases so all existing shortcut code continues to use common.DryRunAPI without any changes. The real implementation lives in internal/cmdutil.
type DryRunAPICall ¶
type DryRunAPICall = cmdutil.DryRunAPICall
type Flag ¶
type Flag struct {
Name string // flag name (e.g. "calendar-id")
Type string // "string" (default) | "bool" | "int" | "float64" | "int_array" | "string_array" | "string_slice"
Default string // default value as string
Desc string // help text
Hidden bool // hidden from --help, still readable at runtime
Required bool
Enum []string // allowed values (e.g. ["asc", "desc"]); empty means no constraint
Input []string // extra input sources: File (@path), Stdin (-); empty = flag value only
}
Flag describes a CLI flag for a shortcut.
type MultipartWriter ¶
MultipartWriter wraps multipart.Writer for file uploads. CreateFormFile is promoted from the embedded *multipart.Writer, which escapes special characters in the field name and filename — a filename like `report "draft".pdf` therefore round-trips through the Content-Disposition header instead of being truncated at the first unescaped quote.
func NewMultipartWriter ¶
func NewMultipartWriter(w io.Writer) *MultipartWriter
NewMultipartWriter creates a new MultipartWriter.
type ResourceRef ¶ added in v1.0.34
type ResourceRef struct {
Type string // e.g. "docx", "bitable", "wiki", "sheet", etc.
Token string // the token extracted from the URL path
}
ResourceRef holds the parsed type and token from a Lark resource URL.
func ParseResourceURL ¶ added in v1.0.34
func ParseResourceURL(rawURL string) (ResourceRef, bool)
ParseResourceURL parses a Lark/Feishu URL and extracts the resource type and token from the URL path. It is the inverse of BuildResourceURL.
Supported path patterns:
/docx/TOKEN -> {Type: "docx", Token: TOKEN}
/doc/TOKEN -> {Type: "doc", Token: TOKEN}
/sheets/TOKEN -> {Type: "sheet", Token: TOKEN}
/base/TOKEN -> {Type: "bitable", Token: TOKEN}
/wiki/TOKEN -> {Type: "wiki", Token: TOKEN}
/file/TOKEN -> {Type: "file", Token: TOKEN}
/drive/folder/TOKEN -> {Type: "folder", Token: TOKEN}
/mindnote/TOKEN -> {Type: "mindnote", Token: TOKEN}
/slides/TOKEN -> {Type: "slides", Token: TOKEN}
Returns (ResourceRef{}, false) when the URL does not match any known pattern.
type RuntimeContext ¶
type RuntimeContext struct {
Config *core.CliConfig
Cmd *cobra.Command
Format string
JqExpr string // --jq expression; empty = no filter
Factory *cmdutil.Factory // injected by framework
// contains filtered or unexported fields
}
RuntimeContext provides helpers for shortcut execution.
func TestNewRuntimeContext ¶
func TestNewRuntimeContext(cmd *cobra.Command, cfg *core.CliConfig) *RuntimeContext
TestNewRuntimeContext creates a RuntimeContext for testing purposes. Only Cmd and Config are set; other fields (Factory, larkSDK, etc.) are nil.
func TestNewRuntimeContextForAPI ¶ added in v1.0.18
func TestNewRuntimeContextForAPI(ctx context.Context, cmd *cobra.Command, cfg *core.CliConfig, f *cmdutil.Factory, as core.Identity) *RuntimeContext
TestNewRuntimeContextForAPI creates a RuntimeContext ready for HTTP tests: sets Cmd, Config, Factory, context, and the requested identity so callers can invoke DoAPI / CallAPI directly without wiring through a cobra parent command.
Pass core.AsBot or core.AsUser explicitly — exposing the identity as a parameter keeps the helper reusable for tests that need to exercise the user-identity code path (token store, auth login, etc.) without forking into a second near-identical helper.
func TestNewRuntimeContextWithBotInfo ¶ added in v1.0.9
func TestNewRuntimeContextWithBotInfo(cmd *cobra.Command, cfg *core.CliConfig, info *BotInfo) *RuntimeContext
TestNewRuntimeContextWithBotInfo creates a RuntimeContext with a pre-set BotInfo for testing.
func TestNewRuntimeContextWithCtx ¶
func TestNewRuntimeContextWithCtx(ctx context.Context, cmd *cobra.Command, cfg *core.CliConfig) *RuntimeContext
TestNewRuntimeContextWithCtx creates a RuntimeContext with an explicit context for tests that invoke functions which call Ctx() (e.g. HTTP request helpers).
func TestNewRuntimeContextWithIdentity ¶ added in v1.0.4
func TestNewRuntimeContextWithIdentity(cmd *cobra.Command, cfg *core.CliConfig, as core.Identity) *RuntimeContext
TestNewRuntimeContextWithIdentity creates a RuntimeContext with a specific identity for testing.
func (*RuntimeContext) APIClassifyContext ¶ added in v1.0.47
func (ctx *RuntimeContext) APIClassifyContext() errclass.ClassifyContext
APIClassifyContext builds the errclass.ClassifyContext for the running command from the runtime config and resolved identity.
func (*RuntimeContext) AccessToken ¶
func (ctx *RuntimeContext) AccessToken() (string, error)
AccessToken returns a valid access token for the current identity. For user: returns user access token (with auto-refresh). For bot: returns tenant access token.
func (*RuntimeContext) As ¶
func (ctx *RuntimeContext) As() core.Identity
As returns the current identity. For bot-only shortcuts, always returns AsBot. For dual-auth shortcuts, uses the resolved identity (respects default-as config).
func (*RuntimeContext) Bool ¶
func (ctx *RuntimeContext) Bool(name string) bool
Bool returns a bool flag value.
func (*RuntimeContext) BotInfo ¶ added in v1.0.9
func (ctx *RuntimeContext) BotInfo() (*BotInfo, error)
BotInfo returns the bot's open_id and display name, fetched lazily from /bot/v3/info. Unlike UserOpenId() (which reads from config), this requires a network call and may fail. Thread-safe via sync.OnceValues; the API is called at most once per RuntimeContext.
func (*RuntimeContext) CallAPITyped ¶ added in v1.0.47
func (ctx *RuntimeContext) CallAPITyped(method, url string, params map[string]interface{}, data interface{}) (map[string]interface{}, error)
CallAPITyped calls the Lark API using the current identity (ctx.As()) via the SDK request path (buildRequest → APIClient.DoAPI → DoSDKRequest) and returns the "data" object, classifying failures into typed errs.* errors via errclass.BuildAPIError.
A transport / auth error from the client boundary is already typed and passes through unchanged; a non-zero API response code is classified into a typed error carrying subtype / code / log_id.
It lifts x-tt-logid from the response header (which the body-only parse drops) so log_id surfaces on the typed error even when the server returns it only in the header.
func (*RuntimeContext) Changed ¶ added in v1.0.19
func (ctx *RuntimeContext) Changed(name string) bool
Changed reports whether the user explicitly set the named flag on the command line, as opposed to the flag carrying its default value.
func (*RuntimeContext) ClassifyAPIResponse ¶ added in v1.0.47
func (ctx *RuntimeContext) ClassifyAPIResponse(resp *larkcore.ApiResp) (map[string]interface{}, error)
ClassifyAPIResponse turns a raw *larkcore.ApiResp into the "data" object or a typed errs.* error. It is the shared response classifier for typed API paths — used by CallAPITyped and by callers that drive the request themselves (e.g. file upload via DoAPI). It:
- parses the JSON body; an unparseable body on an HTTP error status (a gateway 5xx text/html page, an empty body, a missing Content-Type) is classified by status — 5xx → retryable network/server_error, 404 → not_found, other 4xx → api error — not a misleading invalid-response internal error;
- rejects a top-level non-object JSON ([], null, scalar) as an invalid-response internal error — never a silent success ack;
- lifts x-tt-logid from the response header onto the typed error so log_id surfaces even when the body omits it;
- classifies a non-zero API code via errclass.BuildAPIError, and treats any HTTP error status that parsed to code==0 as a status error.
The success "data" object is returned untouched. On a non-zero API code the data is returned alongside the typed error, since the response can still carry fields a caller needs on failure (e.g. the file_token an overwrite returned, for token-stability handling).
func (*RuntimeContext) Command ¶ added in v1.0.47
func (ctx *RuntimeContext) Command() string
Command returns the shortcut command name as cobra knows it (e.g. "+pivot-create"). Used by per-service helpers (e.g. sheets schema validation) that key off the shortcut identity.
func (*RuntimeContext) Ctx ¶
func (ctx *RuntimeContext) Ctx() context.Context
Ctx returns the context.Context propagated from cmd.Context().
func (*RuntimeContext) DoAPI ¶
func (ctx *RuntimeContext) DoAPI(req *larkcore.ApiReq, opts ...larkcore.RequestOptionFunc) (*larkcore.ApiResp, error)
DoAPI executes a raw Lark SDK request with automatic auth handling. Unlike CallAPI which parses JSON and extracts the "data" field, DoAPI returns the raw *larkcore.ApiResp — suitable for file downloads (WithFileDownload) and uploads (WithFileUpload).
Auth resolution is delegated to APIClient.DoSDKRequest to avoid duplicating the identity → token logic across the generic and shortcut API paths.
func (*RuntimeContext) DoAPIAsBot ¶ added in v1.0.3
func (ctx *RuntimeContext) DoAPIAsBot(req *larkcore.ApiReq, opts ...larkcore.RequestOptionFunc) (*larkcore.ApiResp, error)
DoAPIAsBot executes a raw Lark SDK request using bot identity (tenant access token), regardless of the current --as flag. Use this for APIs that must always be called with TAT even when the surrounding shortcut runs as user.
func (*RuntimeContext) DoAPIJSONTyped ¶ added in v1.0.49
func (ctx *RuntimeContext) DoAPIJSONTyped(method, apiPath string, query larkcore.QueryParams, body any) (map[string]any, error)
DoAPIJSONTyped issues a larkcore.ApiReq request, parses the JSON response, and classifies failures into typed errs.* errors via ClassifyAPIResponse, which lifts MissingScopes / ConsoleURL / Identity onto the typed error at the source and merges the response log id into the returned data. A transport / auth error from the client boundary is already typed and passes through unchanged; a non-zero API code is classified with subtype / code / log_id.
func (*RuntimeContext) DoAPIStream ¶
func (ctx *RuntimeContext) DoAPIStream(callCtx context.Context, req *larkcore.ApiReq, opts ...client.Option) (*http.Response, error)
DoAPIStream executes a streaming HTTP request via APIClient.DoStream. Unlike DoAPI (which buffers the full body via the SDK), DoAPIStream returns a live *http.Response whose Body is an io.Reader for streaming consumption. HTTP errors (status >= 400) are handled internally by DoStream.
func (*RuntimeContext) EnsureScopes ¶ added in v1.0.23
func (ctx *RuntimeContext) EnsureScopes(scopes []string) error
EnsureScopes runs the same pre-flight scope check used by the framework before Validate, but on a caller-supplied set of scopes. Use it from a shortcut's Validate to enforce conditional scope requirements that depend on flag values (e.g. --delete-remote needing space:document:delete) so a destructive operation never starts on a token that can't finish it.
Behavior matches checkShortcutScopes: when no token is available or the resolver doesn't expose scope metadata, this is a silent no-op — the downstream API call still surfaces missing_scope at runtime.
func (*RuntimeContext) FileIO ¶ added in v1.0.6
func (ctx *RuntimeContext) FileIO() fileio.FileIO
FileIO resolves the FileIO using the current execution context. Falls back to the globally registered provider when Factory or its FileIOProvider is nil (e.g. in lightweight test helpers).
func (*RuntimeContext) Float64 ¶ added in v1.0.47
func (ctx *RuntimeContext) Float64(name string) float64
Float64 returns a float64 flag value (non-integer numbers).
func (*RuntimeContext) IO ¶
func (ctx *RuntimeContext) IO() *cmdutil.IOStreams
IO returns the IOStreams from the Factory.
func (*RuntimeContext) Int ¶
func (ctx *RuntimeContext) Int(name string) int
Int returns an int flag value.
func (*RuntimeContext) IntArray ¶ added in v1.0.57
func (ctx *RuntimeContext) IntArray(name string) []int
IntArray returns an int-array flag value (repeated flag, also supports CSV splitting).
func (*RuntimeContext) IsBot ¶
func (ctx *RuntimeContext) IsBot() bool
IsBot returns true if current identity is bot.
func (*RuntimeContext) Lang ¶ added in v1.0.43
func (ctx *RuntimeContext) Lang() i18n.Lang
Lang returns the user's preference as a canonical locale, or "" if unset or unrecognized; callers choose their own fallback.
func (*RuntimeContext) LarkSDK ¶
func (ctx *RuntimeContext) LarkSDK() *lark.Client
LarkSDK returns the eagerly-initialized Lark SDK client.
func (*RuntimeContext) Out ¶
func (ctx *RuntimeContext) Out(data interface{}, meta *output.Meta)
Out prints a success JSON envelope to stdout.
func (*RuntimeContext) OutFormat ¶
func (ctx *RuntimeContext) OutFormat(data interface{}, meta *output.Meta, prettyFn func(w io.Writer))
OutFormat prints output based on --format flag. "json" (default) outputs JSON envelope; "pretty" calls prettyFn; others delegate to FormatValue. When JqExpr is set, routes through Out() regardless of format. For json/"" and jq paths, Out() handles content safety scanning. For pretty/table/csv/ndjson, scanning is done here and the alert is written to stderr.
func (*RuntimeContext) OutFormatRaw ¶ added in v1.0.19
func (ctx *RuntimeContext) OutFormatRaw(data interface{}, meta *output.Meta, prettyFn func(w io.Writer))
OutFormatRaw is like OutFormat but with HTML escaping disabled in JSON output. Use this when the data contains XML/HTML content that should be preserved as-is.
func (*RuntimeContext) OutPartialFailure ¶ added in v1.0.47
func (ctx *RuntimeContext) OutPartialFailure(data interface{}, meta *output.Meta) error
OutPartialFailure writes an ok:false multi-status result envelope to stdout and returns the partial-failure exit signal. Use it for batch operations where some items failed but the per-item outcomes are the primary output: the full result (summary + per-item statuses) stays machine-readable on stdout, the process exits non-zero, and nothing is written to stderr.
It is the typed alternative to `Out(...)` + `output.ErrBare(...)` — the envelope's ok field honestly reports failure instead of a misleading ok:true, and the exit signal is distinct from ErrBare (the stdout-carries-the-answer silent-exit signal).
func (*RuntimeContext) OutRaw ¶ added in v1.0.19
func (ctx *RuntimeContext) OutRaw(data interface{}, meta *output.Meta)
OutRaw prints a success JSON envelope to stdout with HTML escaping disabled. Use this instead of Out when the data contains XML/HTML content (e.g. document bodies) that should be preserved as-is in JSON output.
func (*RuntimeContext) PaginateAll ¶
func (ctx *RuntimeContext) PaginateAll(method, url string, params map[string]interface{}, data interface{}, opts client.PaginationOptions) (interface{}, error)
PaginateAll fetches all pages and returns a single merged result.
func (*RuntimeContext) RawAPI ¶
func (ctx *RuntimeContext) RawAPI(method, url string, params map[string]interface{}, data interface{}) (interface{}, error)
RawAPI uses an internal HTTP wrapper with limited control over request/response. Prefer DoAPI for new code — it calls the Lark SDK directly and supports file upload/download options.
RawAPI calls the Lark API using the current identity (ctx.As()) and returns raw result for manual error handling.
func (*RuntimeContext) ResolveSavePath ¶ added in v1.0.6
func (ctx *RuntimeContext) ResolveSavePath(path string) (string, error)
ResolveSavePath resolves a relative path to a validated absolute path via FileIO.ResolvePath. It returns an error if no FileIO provider is registered or if the path fails validation (e.g. traversal, symlink escape).
func (*RuntimeContext) Str ¶
func (ctx *RuntimeContext) Str(name string) string
Str returns a string flag value.
func (*RuntimeContext) StrArray ¶
func (ctx *RuntimeContext) StrArray(name string) []string
StrArray returns a string-array flag value (repeated flag, no CSV splitting).
func (*RuntimeContext) StrSlice ¶ added in v1.0.17
func (ctx *RuntimeContext) StrSlice(name string) []string
StrSlice returns a string-slice flag value (supports CSV splitting and repeated flags).
func (*RuntimeContext) StreamPages ¶
func (ctx *RuntimeContext) StreamPages(method, url string, params map[string]interface{}, data interface{}, onItems func([]interface{}), opts client.PaginationOptions) (interface{}, bool, error)
StreamPages fetches all pages and streams each page's items via onItems. Returns the last result (for error checking) and whether any list items were found.
func (*RuntimeContext) UserOpenId ¶
func (ctx *RuntimeContext) UserOpenId() string
UserOpenId returns the current user's open_id from config.
func (*RuntimeContext) ValidatePath ¶ added in v1.0.6
func (ctx *RuntimeContext) ValidatePath(path string) error
ValidatePath checks that path is a valid relative input path within the working directory by delegating to FileIO.Stat. Returns nil if the path is valid or does not exist yet; returns an error only for illegal paths (absolute, traversal, symlink escape, control chars).
NOTE: This validates input (read) paths via SafeInputPath semantics inside the FileIO implementation. For output (write) path validation, use ResolveSavePath instead.
type Shortcut ¶
type Shortcut struct {
Service string
Command string
Description string
Risk string // "read" | "write" | "high-risk-write" (empty defaults to "read")
Scopes []string // unconditional pre-flight scopes (fallback when UserScopes/BotScopes are empty)
UserScopes []string // optional: user-identity unconditional scopes (overrides Scopes when non-empty)
BotScopes []string // optional: bot-identity unconditional scopes (overrides Scopes when non-empty)
// ConditionalScopes are additional scopes that only some execution paths
// need (for example a default mode vs. a lighter --quick mode, or a
// destructive flag like --delete-remote). They are surfaced in metadata,
// auth hints, and scope-diagnosis output via DeclaredScopesForIdentity, but
// they are NOT enforced by the framework's unconditional pre-flight check.
ConditionalScopes []string // fallback when ConditionalUserScopes/BotScopes are empty
ConditionalUserScopes []string // optional: user-identity conditional scopes
ConditionalBotScopes []string // optional: bot-identity conditional scopes
// Declarative fields (new framework).
AuthTypes []string // supported identities: "user", "bot" (default: ["user"])
Flags []Flag // flag definitions; --dry-run is auto-injected
HasFormat bool // Deprecated: --format is now always injected; this field has no effect.
Tips []string // optional tips shown in --help output
Hidden bool // hide from --help / tab completion (still executable); use when deprecating a command in favor of a replacement
// Business logic hooks.
DryRun func(ctx context.Context, runtime *RuntimeContext) *DryRunAPI // optional: framework prints & returns when --dry-run is set
Validate func(ctx context.Context, runtime *RuntimeContext) error // optional pre-execution validation
Execute func(ctx context.Context, runtime *RuntimeContext) error // main logic
// OnInvoke, when non-nil, runs from the command's cobra PreRunE — before
// cobra validates required flags — so its side effect fires even when the
// call later fails on a missing required flag (which short-circuits before
// Validate/Execute). The backward-compat aliases use it to record a
// deprecation notice that must surface regardless of whether the call
// validates. Fire-and-forget: no args, no return (e.g. deprecation.SetPending).
OnInvoke func()
// PrintFlagSchema, when non-nil, opts this shortcut into the
// `--print-schema --flag-name <name>` runtime introspection contract.
// The framework auto-injects those two system flags and short-circuits
// Validate/Execute when --print-schema is set, dispatching to this hook.
//
// Contract:
// - flagName == "" → list the flags this shortcut can describe
// (output is impl-defined; agents read this to
// discover which flags are introspectable).
// - flagName == "...": → return the JSON Schema (or schema-like blob)
// for that flag.
// Return value is written to stdout verbatim; callers typically format
// it as JSON. Returning an error surfaces as a normal command error.
PrintFlagSchema func(flagName string) ([]byte, error)
// PostMount is an optional hook called after the cobra.Command is fully
// configured (flags registered, tips set) and after parent.AddCommand(cmd)
// has attached it to the parent. Use it to install custom help functions or
// tweak the command; cmd.Parent() is available at this point.
PostMount func(cmd *cobra.Command)
}
Shortcut represents a high-level CLI command.
func (*Shortcut) ConditionalScopesForIdentity ¶ added in v1.0.31
ConditionalScopesForIdentity returns additional flag/path-dependent scopes for the given identity. Identity-specific conditional scopes override the default ConditionalScopes when present.
func (*Shortcut) DeclaredScopesForIdentity ¶ added in v1.0.31
DeclaredScopesForIdentity returns the full scope set agents/help/diagnostics should know about for this shortcut: unconditional pre-flight scopes plus any conditional scopes that some execution paths may require.
func (Shortcut) MountWithContext ¶ added in v1.0.16
func (*Shortcut) ScopesForIdentity ¶
ScopesForIdentity returns the scopes applicable for the given identity. If identity-specific scopes (UserScopes/BotScopes) are set, they take precedence over the default Scopes.