Documentation
¶
Index ¶
- Constants
- Variables
- func AtLeastOne(rt *RuntimeContext, flags ...string) error
- 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 DoMCPCall(ctx context.Context, httpClient *http.Client, toolName string, ...) (interface{}, error)
- func EachMap(items []interface{}, fn func(m map[string]interface{}))
- func EnsureWritableFile(path string, overwrite bool) error
- func ExactlyOne(rt *RuntimeContext, flags ...string) error
- func ExtractMCPResult(raw interface{}) interface{}
- func FlagErrorf(format string, args ...any) 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 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 HandleApiResult(result interface{}, err error, action string) (map[string]interface{}, error)
- func IsDangerousUnicode(r rune) bool
- func MCPEndpoint(brand core.LarkBrand) string
- func MaskToken(token string) string
- func MutuallyExclusive(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 ParseIntBounded(rt *RuntimeContext, name string, min, max int) int
- func ParseJSON(data []byte, v interface{}) error
- func ParseTime(input string, hint ...string) (string, error)
- func RejectDangerousChars(paramName, value string) error
- func RequireConfirmation(risk string, yes bool, action string) error
- func SplitCSV(input string) []string
- func TruncateStr(s string, n int) string
- func UnwrapMCPResult(v interface{}) interface{}
- func ValidateChatID(input string) (string, error)
- func ValidatePageSize(rt *RuntimeContext, flagName string, defaultVal, minVal, maxVal int) (int, error)
- func ValidateSafeOutputDir(outputDir string) error
- func ValidateUserID(input string) (string, error)
- type DryRunAPI
- type DryRunAPICall
- type Flag
- type MultipartWriter
- type RuntimeContext
- func TestNewRuntimeContext(cmd *cobra.Command, cfg *core.CliConfig) *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) AccessToken() (string, error)
- func (ctx *RuntimeContext) As() core.Identity
- func (ctx *RuntimeContext) Bool(name string) bool
- func (ctx *RuntimeContext) CallAPI(method, url string, params map[string]interface{}, data interface{}) (map[string]interface{}, error)
- 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) DoAPIJSON(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) IO() *cmdutil.IOStreams
- func (ctx *RuntimeContext) Int(name string) int
- func (ctx *RuntimeContext) IsBot() bool
- 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) 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)deprecated
- func (ctx *RuntimeContext) Str(name string) string
- func (ctx *RuntimeContext) StrArray(name string) []string
- func (ctx *RuntimeContext) StreamPages(method, url string, params map[string]interface{}, data interface{}, ...) (interface{}, bool, error)
- func (ctx *RuntimeContext) UserOpenId() string
- type Shortcut
Constants ¶
const ( File = "file" // support @path to read value from a file Stdin = "stdin" // support - to read value from stdin )
Flag.Input source constants.
Variables ¶
var NewDryRunAPI = cmdutil.NewDryRunAPI
Functions ¶
func AtLeastOne ¶
func AtLeastOne(rt *RuntimeContext, flags ...string) error
AtLeastOne checks that at least one of the given flags is set.
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 EachMap ¶
func EachMap(items []interface{}, fn func(m map[string]interface{}))
EachMap iterates over map elements in a slice, skipping non-map items.
func EnsureWritableFile ¶
EnsureWritableFile refuses to overwrite an existing file unless overwrite is true.
func ExactlyOne ¶
func ExactlyOne(rt *RuntimeContext, flags ...string) error
ExactlyOne checks that exactly one of the given flags is set.
func ExtractMCPResult ¶
func ExtractMCPResult(raw interface{}) interface{}
func FlagErrorf ¶
FlagErrorf returns a validation error with flag context (exit code 2).
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 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 HandleApiResult ¶
HandleApiResult checks for network/API errors and returns the "data" field.
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 MutuallyExclusive ¶
func MutuallyExclusive(rt *RuntimeContext, flags ...string) error
MutuallyExclusive 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 ParseIntBounded ¶
func ParseIntBounded(rt *RuntimeContext, name string, min, max int) int
ParseIntBounded parses an int flag and clamps it to [min, max].
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 RejectDangerousChars ¶
RejectDangerousChars returns an error if value contains ASCII control characters or dangerous Unicode code points.
func RequireConfirmation ¶
RequireConfirmation blocks high-risk-write operations unless --yes is passed.
func TruncateStr ¶
TruncateStr truncates s to at most n runes.
func UnwrapMCPResult ¶
func UnwrapMCPResult(v interface{}) interface{}
func ValidateChatID ¶
ValidateChatID checks if a chat ID has valid format (oc_ prefix). Also extracts token from URL if provided.
func ValidatePageSize ¶
func ValidatePageSize(rt *RuntimeContext, flagName string, defaultVal, minVal, maxVal int) (int, error)
ValidatePageSize 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 ValidateSafeOutputDir ¶
ValidateSafeOutputDir ensures outputDir is a relative path that resolves within the current working directory, preventing path traversal attacks (including symlink-based escape).
func ValidateUserID ¶
ValidateUserID checks if a user ID has valid format (ou_ prefix).
Types ¶
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" | "string_array"
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.
func NewMultipartWriter ¶
func NewMultipartWriter(w io.Writer) *MultipartWriter
NewMultipartWriter creates a new MultipartWriter.
func (*MultipartWriter) CreateFormFile ¶
func (mw *MultipartWriter) CreateFormFile(fieldname, filename string) (io.Writer, error)
CreateFormFile creates a form file with the given field name and file name.
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 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) 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) CallAPI ¶
func (ctx *RuntimeContext) CallAPI(method, url string, params map[string]interface{}, data interface{}) (map[string]interface{}, error)
CallAPI 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.
CallAPI calls the Lark API using the current identity (ctx.As()) and auto-handles errors.
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 bot-only APIs (e.g. image/file upload) that must be called with TAT even when the surrounding shortcut runs as user.
func (*RuntimeContext) DoAPIJSON ¶
func (ctx *RuntimeContext) DoAPIJSON(method, apiPath string, query larkcore.QueryParams, body any) (map[string]any, error)
DoAPIJSON calls the Lark API via DoAPI, parses the JSON response envelope, and returns the "data" field. Suitable for standard JSON APIs (non-file).
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) 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) IsBot ¶
func (ctx *RuntimeContext) IsBot() bool
IsBot returns true if current identity is bot.
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.
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
deprecated
func (ctx *RuntimeContext) RawAPI(method, url string, params map[string]interface{}, data interface{}) (interface{}, error)
Deprecated: 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) 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) 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.
type Shortcut ¶
type Shortcut struct {
Service string
Command string
Description string
Risk string // "read" | "write" | "high-risk-write" (empty defaults to "read")
Scopes []string // default scopes (fallback when UserScopes/BotScopes are empty)
UserScopes []string // optional: user-identity scopes (overrides Scopes when non-empty)
BotScopes []string // optional: bot-identity scopes (overrides Scopes when non-empty)
// Declarative fields (new framework).
AuthTypes []string // supported identities: "user", "bot" (default: ["user"])
Flags []Flag // flag definitions; --dry-run is auto-injected
HasFormat bool // auto-inject --format flag (json|pretty|table|ndjson|csv)
Tips []string // optional tips shown in --help output
// 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
}
Shortcut represents a high-level CLI command.
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.