cmdutil

package
v1.0.5 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 7, 2026 License: MIT Imports: 31 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HeaderSource      = "X-Cli-Source"
	HeaderVersion     = "X-Cli-Version"
	HeaderShortcut    = "X-Cli-Shortcut"
	HeaderExecutionId = "X-Cli-Execution-Id"

	SourceValue = "lark-cli"

	HeaderUserAgent = "User-Agent"
)

Variables

This section is empty.

Functions

func AccessTokensToIdentities

func AccessTokensToIdentities(tokens []interface{}) []string

AccessTokensToIdentities converts from_meta accessTokens (e.g. ["tenant", "user"]) to CLI identity names (e.g. ["bot", "user"]).

func AddTips

func AddTips(cmd *cobra.Command, tips ...string)

AddTips appends tips to a command (merges with existing).

func BaseSecurityHeaders

func BaseSecurityHeaders() http.Header

BaseSecurityHeaders returns headers that every request must carry.

func ContextWithShortcut

func ContextWithShortcut(ctx context.Context, name, executionId string) context.Context

ContextWithShortcut injects shortcut name and execution ID into the context.

func DisableAuthCheck

func DisableAuthCheck(cmd *cobra.Command)

DisableAuthCheck marks a command (and all its children) as not requiring auth.

func ExecutionIdFromContext

func ExecutionIdFromContext(ctx context.Context) (string, bool)

ExecutionIdFromContext extracts the execution ID from the context.

func GetSupportedIdentities added in v1.0.5

func GetSupportedIdentities(cmd *cobra.Command) []string

GetSupportedIdentities returns the declared identities, or nil if not declared.

func GetTips

func GetTips(cmd *cobra.Command) []string

GetTips retrieves the tips from a command's annotations.

func IsAuthCheckDisabled

func IsAuthCheckDisabled(cmd *cobra.Command) bool

IsAuthCheckDisabled returns true if the command or any ancestor has auth check disabled.

func ParseJSONMap

func ParseJSONMap(input, label string) (map[string]any, error)

ParseJSONMap parses a JSON string into a map. Returns an empty map if input is empty.

func ParseOptionalBody

func ParseOptionalBody(httpMethod, data string) (interface{}, error)

ParseOptionalBody parses --data JSON for methods that accept a request body. Returns (nil, nil) if the method has no body or data is empty.

func PrintDryRun

func PrintDryRun(w io.Writer, request client.RawApiRequest, config *core.CliConfig, format string) error

PrintDryRun outputs a standardised dry-run summary using DryRunAPI. When format is "pretty", outputs human-readable text; otherwise JSON.

func PrintIdentity

func PrintIdentity(w io.Writer, as core.Identity, config *core.CliConfig, autoDetected bool)

PrintIdentity outputs the current identity to stderr so callers (including AI agents) can see which identity is being used for the API call.

func SetSupportedIdentities added in v1.0.5

func SetSupportedIdentities(cmd *cobra.Command, identities []string)

SetSupportedIdentities marks which identities a command supports.

func SetTips

func SetTips(cmd *cobra.Command, tips []string)

SetTips sets the tips for a command (stored as JSON in Annotations).

func ShortcutHeaderOpts

func ShortcutHeaderOpts(ctx context.Context) larkcore.RequestOptionFunc

ShortcutHeaderOpts extracts Shortcut info from the context and returns a RequestOptionFunc that injects the corresponding headers into SDK requests. Returns nil if the context has no Shortcut info.

func ShortcutHeaders added in v1.0.5

func ShortcutHeaders(ctx context.Context) http.Header

ShortcutHeaders extracts Shortcut info from the context and returns the corresponding HTTP headers. Returns nil if the context has no Shortcut info.

func ShortcutNameFromContext

func ShortcutNameFromContext(ctx context.Context) (string, bool)

ShortcutNameFromContext extracts the shortcut name from the context.

func ThemeFeishu

func ThemeFeishu() *huh.Theme

ThemeFeishu returns a huh theme with Feishu brand colors.

func UserAgentValue

func UserAgentValue() string

UserAgentValue returns the User-Agent value: "lark-cli/{version}".

Types

type DryRunAPI

type DryRunAPI struct {
	// contains filtered or unexported fields
}

DryRunAPI is the builder and result type for dry-run output. URL templates use :param placeholders; Set stores actual values; MarshalJSON and Format resolve them.

func NewDryRunAPI

func NewDryRunAPI() *DryRunAPI

func (*DryRunAPI) Body

func (d *DryRunAPI) Body(body interface{}) *DryRunAPI

Body sets the request body on the last added call.

func (*DryRunAPI) DELETE

func (d *DryRunAPI) DELETE(url string) *DryRunAPI

func (*DryRunAPI) Desc

func (d *DryRunAPI) Desc(desc string) *DryRunAPI

Desc sets a description on the last added call. If no calls exist yet, sets the top-level description.

func (*DryRunAPI) Format

func (d *DryRunAPI) Format() string

Format renders the dry-run output as plain text for AI/human consumption.

func (*DryRunAPI) GET

func (d *DryRunAPI) GET(url string) *DryRunAPI

func (*DryRunAPI) MarshalJSON

func (d *DryRunAPI) MarshalJSON() ([]byte, error)

MarshalJSON serializes as {"description": "...", "api": [...calls with resolved URLs], ...extra}.

func (*DryRunAPI) PATCH

func (d *DryRunAPI) PATCH(url string) *DryRunAPI

func (*DryRunAPI) POST

func (d *DryRunAPI) POST(url string) *DryRunAPI

func (*DryRunAPI) PUT

func (d *DryRunAPI) PUT(url string) *DryRunAPI

func (*DryRunAPI) Params

func (d *DryRunAPI) Params(params map[string]interface{}) *DryRunAPI

Params sets query parameters on the last added call.

func (*DryRunAPI) Set

func (d *DryRunAPI) Set(key string, value interface{}) *DryRunAPI

Set adds an extra context field. Values are also used to resolve :key placeholders in URLs.

type DryRunAPICall

type DryRunAPICall struct {
	Desc   string                 `json:"desc,omitempty"`
	Method string                 `json:"method"`
	URL    string                 `json:"url"`
	Params map[string]interface{} `json:"params,omitempty"`
	Body   interface{}            `json:"body,omitempty"`
}

DryRunAPICall describes a single API call in dry-run output.

type Factory

type Factory struct {
	Config     func() (*core.CliConfig, error) // lazily loads app config from Credential
	HttpClient func() (*http.Client, error)    // HTTP client for non-Lark API calls (with retry and security headers)
	LarkClient func() (*lark.Client, error)    // Lark SDK client for all Open API calls
	IOStreams  *IOStreams                      // stdin/stdout/stderr streams

	Invocation           InvocationContext       // Immutable call context; do not mutate after Factory construction.
	Keychain             keychain.KeychainAccess // secret storage (real keychain in prod, mock in tests)
	IdentityAutoDetected bool                    // set by ResolveAs when identity was auto-detected
	ResolvedIdentity     core.Identity           // identity resolved by the last ResolveAs call

	Credential *credential.CredentialProvider
}

func NewDefault

func NewDefault(inv InvocationContext) *Factory

NewDefault creates a production Factory with cached closures. Initialization follows a credential-first order:

Phase 1: HttpClient (no credential dependency)
Phase 2: Credential (sole data source for account info)
Phase 3: Config derived from Credential
Phase 4: LarkClient derived from Credential

func TestFactory

func TestFactory(t *testing.T, config *core.CliConfig) (*Factory, *bytes.Buffer, *bytes.Buffer, *httpmock.Registry)

TestFactory creates a Factory for testing. Returns (factory, stdout buffer, stderr buffer, http mock registry).

func (*Factory) CheckIdentity

func (f *Factory) CheckIdentity(as core.Identity, supported []string) error

CheckIdentity verifies the resolved identity is in the supported list. On success, sets f.ResolvedIdentity. On failure, returns an error tailored to whether the identity was explicit (--as) or auto-detected.

func (*Factory) CheckStrictMode added in v1.0.5

func (f *Factory) CheckStrictMode(ctx context.Context, as core.Identity) error

CheckStrictMode returns an error if strict mode is active and identity is not allowed.

func (*Factory) NewAPIClient

func (f *Factory) NewAPIClient() (*client.APIClient, error)

NewAPIClient creates an APIClient using the Factory's base Config (app credentials only). For user-mode calls where the correct user profile matters, use NewAPIClientWithConfig instead.

func (*Factory) NewAPIClientWithConfig

func (f *Factory) NewAPIClientWithConfig(cfg *core.CliConfig) (*client.APIClient, error)

NewAPIClientWithConfig creates an APIClient with an explicit config. Use this when the caller has already resolved the correct config.

func (*Factory) ResolveAs

func (f *Factory) ResolveAs(ctx context.Context, cmd *cobra.Command, flagAs core.Identity) core.Identity

ResolveAs returns the effective identity type. If the user explicitly passed --as, use that value; otherwise use the configured default. When the value is "auto" (or unset), auto-detect based on credential hints.

func (*Factory) ResolveStrictMode added in v1.0.5

func (f *Factory) ResolveStrictMode(ctx context.Context) core.StrictMode

ResolveStrictMode returns the effective strict mode by reading Account.SupportedIdentities from the credential provider chain.

type IOStreams

type IOStreams struct {
	In         io.Reader
	Out        io.Writer
	ErrOut     io.Writer
	IsTerminal bool
}

IOStreams provides the standard input/output/error streams. Commands should use these instead of os.Stdin/Stdout/Stderr to enable testing and output capture.

type InvocationContext added in v1.0.5

type InvocationContext struct {
	Profile string
}

Factory holds shared dependencies injected into every command. All function fields are lazily initialized and cached after first call. In tests, replace any field to stub out external dependencies.

type RetryTransport

type RetryTransport struct {
	Base       http.RoundTripper
	MaxRetries int
	Delay      time.Duration // base delay for exponential backoff; defaults to 500ms
}

RetryTransport is an http.RoundTripper that retries on 5xx responses and network errors. MaxRetries defaults to 0 (no retries).

func (*RetryTransport) RoundTrip

func (t *RetryTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type SecurityHeaderTransport

type SecurityHeaderTransport struct {
	Base http.RoundTripper
}

SecurityHeaderTransport is an http.RoundTripper that injects CLI security headers into every request. Shortcut headers are read from the request context.

func (*SecurityHeaderTransport) RoundTrip

func (t *SecurityHeaderTransport) RoundTrip(req *http.Request) (*http.Response, error)

RoundTrip implements http.RoundTripper.

type UserAgentTransport

type UserAgentTransport struct {
	Base http.RoundTripper
}

UserAgentTransport is an http.RoundTripper that sets the User-Agent header. Used in the SDK transport chain to override the SDK's default User-Agent.

func (*UserAgentTransport) RoundTrip

func (t *UserAgentTransport) RoundTrip(req *http.Request) (*http.Response, error)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL