environment

package
v1.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 21, 2026 License: MIT Imports: 26 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package environment 提供 CLI 各 command owner 共用的执行环境:输入输出流、stdin 输入契约、 flag 绑定、usage 错误标记与命令生命周期声明。

本包只供 internal/cli 使用;不含 Pixiv 或 FANBOX 的业务语义。

包的组成:Env 承载输入输出与 flag 绑定,State 保存一条命令解析后的 stdin 输入, Execution 声明启动、更新和 MCP 等执行要求。

Index

Constants

View Source
const AnnotationKey = "pixiv-cli.input-spec"

AnnotationKey 让架构检查确认命令声明了输入 codec,不需要解析 Use 字符串或 从帮助文本推断参数个数。

View Source
const LifecycleAnnotationKey = "pixiv-cli.lifecycle"

LifecycleAnnotationKey 存放 command owner 与 composition root 之间的生命周期契约。 声明存放在 Cobra command 本身,避免进程级 command-pointer registry 泄漏状态。

View Source
const OutputNDJSONAnnotationKey = "pixiv-cli.output-ndjson"

OutputNDJSONAnnotationKey 记录命令本次执行是否把 NDJSON 写到 stdout;root 据此 把下游关闭管道造成的 EPIPE 视为正常结束。

Variables

This section is empty.

Functions

func ActionInputArgs

func ActionInputArgs(in io.Reader, usage string, usageError func(error) error) cobra.PositionalArgs

ActionInputArgs 校验最多一个显式 ID;没有位置参数时仅允许真实管道输入。 usageError 由根控制器注入,以保留 CLI 的 usage exit code 语义。

func ActionOrTargetsArgs

func ActionOrTargetsArgs(in io.Reader, usage string, usageError func(error) error) cobra.PositionalArgs

ActionOrTargetsArgs 允许显式资源,也允许从 stdin 读取 NDJSON 记录。

func Bind

func Bind(command *cobra.Command, execution Execution)

Bind 把生命周期声明写进 command 的 annotation,子命令继承时逐级向上查找。

func BindFanboxListFlags

func BindFanboxListFlags(cmd *cobra.Command, jsonOut, ndjson *bool, limit, page *int)

BindFanboxListFlags 给 FANBOX 列表命令注册输出格式和逻辑分页 flag。 FANBOX 的 --limit/--page 没有短选项,帮助文本与既有输出保持一致。

func BindFanboxSingleFlags

func BindFanboxSingleFlags(cmd *cobra.Command, jsonOut, ndjson *bool)

BindFanboxSingleFlags 只给单实体命令注册 --json/--ndjson,避免接受会被静默忽略的 --limit/--page。

func BindListFlags

func BindListFlags(cmd *cobra.Command, limit, page *int)

BindListFlags 给列表命令注册逻辑分页 flag;未给 --limit 时只读一批。

func BindNDJSONFlag

func BindNDJSONFlag(cmd *cobra.Command, value *bool)

BindNDJSONFlag 注册列表命令自己的记录流开关。

func ConsumeActionRecords

func ConsumeActionRecords(ctx context.Context, in io.Reader, errOut io.Writer, operation, onError string, allowedTypes map[string]struct{}, invoke func(context.Context, int64) error, usageError func(error) error) error

ConsumeActionRecords 在一条 operation snapshot 上顺序执行记录动作;它不缓存 整个输入,因此大管道只保留当前 Record。

func ErrorText

func ErrorText(err error, language i18n.Locale) (text string)

ErrorText 在 CLI 边界解释常见 SDK 错误,保留原始错误值供结构化调用方使用。

func FirstNonWhitespace

func FirstNonWhitespace(body []byte) (byte, bool)

FirstNonWhitespace 返回第一个非 JSON 空白的字节。记录 codec 只需要 JSON 定义的前导 空白集合;按字节判断可以避免解码或改写不透明的输入内容。

func IsOffline

func IsOffline(cmd *cobra.Command) bool

IsOffline 报告本次执行是否调用过 SetOffline。

func IsTTY

func IsTTY(reader io.Reader) bool

IsTTY 只把真正的终端文件当作 TTY;内存和管道 reader 按非 TTY 处理, 让嵌入式调用方得到管道语义。

func LocalizeCommands added in v1.4.0

func LocalizeCommands(cmd *cobra.Command, locale i18n.Locale)

LocalizeCommands 在命令树组装完毕后解析帮助消息键,Cobra 的内建项也使用同一语言。

func NewUsageError

func NewUsageError(err error) error

NewUsageError 给参数错误打上 usage 标记;已经带标记的错误原样返回。

func NormalizeFlagError

func NormalizeFlagError(err error) error

NormalizeFlagError 把 pflag 的未知选项错误翻译成 usage 错误;其他错误原样返回。

func OutputNDJSON

func OutputNDJSON(cmd *cobra.Command) bool

OutputNDJSON 读取 SetOutputNDJSON 记录的结果;未记录时返回 false。

func ParsePlan

func ParsePlan(cmd *cobra.Command, limit, page int) (pagination.PagePlan, error)

ParsePlan 校验 --limit/--page 并生成逻辑分页计划;未显式给 --limit 时只读一批。

func PositiveInt64

func PositiveInt64(value, name string) (int64, error)

PositiveInt64 把十进制文本解析为正整数;失败时在错误中带上 name 说明字段。

func ProxyOverride

func ProxyOverride(cmd *cobra.Command, opts ProxyOptions) (*string, error)

ProxyOverride 解析共用的代理 flag;两者都未出现时返回 nil,表示沿用配置。

func ReadValue

func ReadValue(reader io.Reader) (string, error)

ReadValue 读完整个流并只去掉一个行尾 LF 或 CRLF;不去空白、不拆词、不设大小上限。

func SetOffline

func SetOffline(cmd *cobra.Command)

SetOffline 让本次执行跳过自动更新检查,供会消费凭据或产生副作用的命令使用。

func SetOutputNDJSON

func SetOutputNDJSON(cmd *cobra.Command, enabled bool)

SetOutputNDJSON 记录本次执行是否向 stdout 写标准 NDJSON;root 据此把下游关闭管道 导致的 EPIPE 判为正常结束。

func WritesNDJSON

func WritesNDJSON(cmd *cobra.Command) bool

WritesNDJSON 只认命令自己 --ndjson flag 的显式取值;自动 NDJSON 由 command owner 通过 SetOutputNDJSON 记录。

Types

type BrokenPipe

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

BrokenPipe 临时安装平台的 broken-pipe 信号策略,使 stdout 写失败能以 EPIPE 返回 Go 调用链。NDJSON 与 MCP 各持有一个状态,只有前者可把 EPIPE 归为成功。

func (*BrokenPipe) Enable

func (b *BrokenPipe) Enable()

Enable 忽略 SIGPIPE 并记住恢复函数;重复调用不产生额外副作用。

func (*BrokenPipe) Installed

func (b *BrokenPipe) Installed() bool

Installed 报告当前是否安装了 broken-pipe 策略。

func (*BrokenPipe) Restore

func (b *BrokenPipe) Restore()

Restore 在本次执行结束时恢复平台默认处理;重复调用是安全的。

type Codec

type Codec string

Codec 指明命令显式声明的 stdin 输入协议。

const (
	// NoInput 保留 stdin 给 MCP 等命令自有协议。
	NoInput Codec = "none"
	// TextValue 把整个 stdin 流映射成一个位置参数值。
	TextValue Codec = "text-value"
	// TextOrRecord 区分单个原始值与标准 NDJSON 记录流。
	TextOrRecord Codec = "text-or-record"
)

type Env

type Env struct {
	Language i18n.Locale
	In       io.Reader
	Out      io.Writer
	Err      io.Writer
	// WrapUsage 给参数或输入契约错误打上 CLI usage 退出码的标记。
	WrapUsage func(error) error
	// ResolveJSON 返回本次执行生效的 JSON 设置;override 为 nil 时读取运行时配置。
	ResolveJSON func(*bool) (bool, error)
	// EnablePipelineSignal 在第一次 NDJSON 写出前安装执行边界的 broken-pipe 策略,
	// 重复调用不产生额外副作用。
	EnablePipelineSignal func()
}

Env 汇集所有 command owner 共用的输入输出流和 flag 绑定;root 构造一份, 各命令包通过构造函数参数取得。

func New

func New(in io.Reader, out, errOut io.Writer, wrapUsage func(error) error, enablePipelineSignal func(), resolveJSON func(*bool) (bool, error)) Env

New 构造所有 command owner 共用的执行环境;WrapUsage 给参数错误打上 usage 标记, ResolveJSON 在 override 为 nil 时读取运行时配置。

func (Env) ActionInputArgs

func (e Env) ActionInputArgs(usage string) cobra.PositionalArgs

ActionInputArgs 给出 TextOrRecord 动作命令共用的位置参数校验。

func (Env) AutoNDJSON

func (e Env) AutoNDJSON(cmd *cobra.Command, ndjson, jsonOut bool) bool

AutoNDJSON 决定列表命令是否输出记录流:显式 --ndjson 直接选择记录流; 否则显式 --json 或配置的 JSON 模式优先,两者都没有时只要 stdout 不是终端就输出记录流。 结果记录在命令上,执行边界据此把提前关闭的管道判为正常结束。

func (Env) BindCommonFlags

func (e Env) BindCommonFlags(cmd *cobra.Command, opts *Options)

BindCommonFlags 注册 --json(短选项 -j)和代理覆盖 flag。

func (Env) BindNoInput

func (e Env) BindNoInput(cmd *cobra.Command) *State

BindNoInput 声明命令不读取 stdin,保留 stdin 给 MCP 等协议使用。

func (Env) BindProxyFlags

func (e Env) BindProxyFlags(cmd *cobra.Command, opts *ProxyOptions)

BindProxyFlags 只注册代理覆盖 flag,供没有 --json 的命令使用。

func (Env) BindTextOrRecord

func (e Env) BindTextOrRecord(cmd *cobra.Command, minArgs, maxArgs, fillPosition int) *State

BindTextOrRecord 让 stdin 在单个文本值和 NDJSON 记录流之间自动判别。

func (Env) BindTextValue

func (e Env) BindTextValue(cmd *cobra.Command, minArgs, maxArgs, fillPosition int) *State

BindTextValue 把 stdin 声明为单个文本值,并返回本次命令的输入状态。

func (Env) BindTextValueWhen

func (e Env) BindTextValueWhen(cmd *cobra.Command, minArgs, maxArgs, fillPosition int, enabled func(*cobra.Command, []string) bool) *State

BindTextValueWhen 与 BindTextValue 相同,但 enabled 返回 false 时不读取 stdin。

func (Env) CanPrompt

func (e Env) CanPrompt() bool

CanPrompt 报告输入和输出是否都是终端,决定能否发起交互式提问。

func (Env) ConsumeActionRecords

func (e Env) ConsumeActionRecords(cmd *cobra.Command, state *State, operation, onError string, allowedTypes map[string]struct{}, invoke func(context.Context, int64) error) error

ConsumeActionRecords 把标准记录解析和逐行诊断交给 input 包;允许的实体类型、 已解析的输入状态和实际动作由调用方负责。

func (Env) ExactArgs

func (e Env) ExactArgs(count int, usage string) cobra.PositionalArgs

ExactArgs 校验位置参数个数恰好为 count。个数不符按普通命令失败处理; usage 退出码只留给未知选项和显式输入契约违规。

func (Env) JSONOverride

func (e Env) JSONOverride(cmd *cobra.Command, opts Options) *bool

JSONOverride 返回显式 --json 的取值;flag 未出现时返回 nil,让调用方沿用配置。

func (Env) ListJSONOut

func (e Env) ListJSONOut(cmd *cobra.Command, jsonOut, ndjson bool) (bool, error)

ListJSONOut 解析文档输出模式;同时给 --ndjson 和 --json 时按 usage 错误拒绝。

func (Env) MaxArgs

func (e Env) MaxArgs(count int, usage string) cobra.PositionalArgs

MaxArgs 校验位置参数至多 count 个。

func (Env) MinArgs

func (e Env) MinArgs(count int, usage string) cobra.PositionalArgs

MinArgs 校验位置参数至少 count 个。

func (Env) OutputIsTTY

func (e Env) OutputIsTTY() bool

OutputIsTTY 报告 stdout 是否连接到终端。

func (Env) PrintJSON

func (e Env) PrintJSON(value any) error

PrintJSON 向 stdout 写一个两空格缩进的 JSON 文档并追加换行。

func (Env) PromptConfirm

func (e Env) PromptConfirm(message string, defaultValue bool) (bool, error)

PromptConfirm 接受 y/yes、n/no;直接回车使用 defaultValue。

func (Env) PromptInput

func (e Env) PromptInput(message, defaultValue string) (string, error)

PromptInput 读取一个非空回答;直接回车时使用 defaultValue,空答案会重新提问。

func (Env) PromptSecret

func (e Env) PromptSecret(message string) (string, error)

PromptSecret 读取密码并在输入过程中关闭回显;空答案会重新提问。

func (Env) PromptSelect

func (e Env) PromptSelect(message string, options []string) (string, error)

PromptSelect 打印编号选项并返回用户选择的那一项。

func (Env) Request

func (e Env) Request(cmd *cobra.Command, opts ProxyOptions) (PixivRequest, error)

Request 从共用代理 flag 构造一次 Pixiv 执行请求。

func (Env) Text added in v1.4.0

func (e Env) Text(key string) string

Text 返回本次执行语言的界面消息。

type Execution

type Execution struct {
	// StartupHooks 启用启动阶段的系统副作用:清理待安装更新和 pixiv:// handler。
	StartupHooks bool
	// EnsureConfig 确保默认配置文件存在,并在配置允许时启动日志。
	EnsureConfig bool
	// AutomaticUpdate 在命令成功后检查更新。
	AutomaticUpdate bool
	// MCP 启用 MCP transport 专用的 broken-pipe 策略。
	MCP bool
}

Execution 描述 root 在命令执行前后负责的通用生命周期行为;业务资源由各 command owner 的窄依赖端口按需创建,不经过这里定位。

func AuthBundleImport

func AuthBundleImport() Execution

AuthBundleImport 不检查自动更新,避免导入凭据后立即发起无关网络请求。

func FanboxAuth

func FanboxAuth() Execution

FanboxAuth 仍运行 root 启动钩子,但不确保默认配置文件;FANBOX 登录只需要清理待安装更新、 维护 pixiv:// handler 和检查自动更新,不需要 Pixiv 配置的启动副作用。

func For

func For(command *cobra.Command) Execution

For 返回最近的 owner 声明;未声明命令保留 startup 默认行为。

func Normal

func Normal() Execution

Normal 返回普通 CLI 叶子命令的生命周期:启动钩子、确保配置并检查自动更新。

func PixivMCP

func PixivMCP() Execution

PixivMCP 启用启动钩子并确保配置,同时标记 MCP transport 以安装对应的管道策略。

func UpdateCommand

func UpdateCommand() Execution

UpdateCommand 不运行自动更新检查,避免 update 命令递归触发自己。

type InputSpec

type InputSpec struct {
	Codec        Codec
	MinArgs      int
	MaxArgs      int
	FillPosition int
	Reader       io.Reader
	UsageError   func(error) error
	Enabled      func(*cobra.Command, []string) bool
	IsTTY        func(io.Reader) bool
}

InputSpec 描述一条 Cobra 命令的显式输入契约。

FillPosition 指定 stdin 填入的位置参数下标(从 0 开始)。只有一个必填或可选值的命令 通常填 0;"config set KEY [VALUE]" 这类命令填 1,保留显式的 KEY 作为第一个参数,只读取 省略的 VALUE。MaxArgs 为 -1 表示参数数量可变。

type Mode

type Mode string

Mode 记录 TextOrRecord 解析后得到文本还是记录。

const (
	// TextMode 表示 stdin 被解析成一个文本值。
	TextMode Mode = "text"
	// RecordMode 表示 stdin 被解析成 NDJSON 记录流。
	RecordMode Mode = "record"
)

type Options

type Options struct {
	ProxyOptions
	JSON bool
}

Options 保存数据命令共用的 --json 与代理 flag 取值。

type PixivExecutor added in v1.4.0

type PixivExecutor func(context.Context, PixivRequest, func(context.Context, int64, *pixiv.Client) (bool, error)) error

PixivExecutor 交出本次选择的账号与 client;回调提交后停止账号池重放。

type PixivRequest added in v1.4.0

type PixivRequest struct {
	UserID             int64
	HTTPSProxyOverride *string
}

PixivRequest 携带命令或 MCP 请求的可选账号与代理覆盖;组合根解析配置。

type ProxyOptions

type ProxyOptions struct {
	Proxy   string
	NoProxy bool
}

ProxyOptions 保存一条命令的 --proxy/--no-proxy 取值。

type StartupError

type StartupError struct{ Err error }

StartupError 标记命令启动阶段的副作用失败。它不使用 usage 退出码,也不打印 "error:" 前缀,调用方据此区分启动失败与参数错误。

func (*StartupError) Error

func (e *StartupError) Error() string

Error 返回启动副作用的原始错误文本。

func (*StartupError) Unwrap

func (e *StartupError) Unwrap() error

Unwrap 暴露启动失败的原始错误。

type State

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

State 保存一条命令实例解析后的输入。命令构造函数持有它;不按 *cobra.Command 建索引, 也不在多次执行之间共享。

func BindInput

func BindInput(cmd *cobra.Command, spec InputSpec) *State

BindInput 把 InputSpec 挂到 cmd 上并返回本次命令实例的输入状态。它包装原有的位置参数校验和 RunE,使业务代码看到解析后的参数切片,记录消费者则从 State.Reader 取得可重放 reader。

func (*State) Args

func (s *State) Args(fallback []string) []string

Args 返回 stdin 解析后的位置参数;解析尚未发生时返回调用方的切片, 例如测试直接调用 RunE 的场景。

func (*State) Mode

func (s *State) Mode() Mode

Mode 报告 TextOrRecord 流被判定为文本还是记录。

func (*State) Reader

func (s *State) Reader(fallback io.Reader) io.Reader

Reader 返回 codec 选定的可重放 reader;不读取 stdin 的命令保留配置的 reader。

type UsageError

type UsageError struct{ Err error }

UsageError 标记由 CLI 参数、flag 或显式输入契约验证导致的错误;上游 SDK、 网络和本地 I/O 错误不得包裹为此类型,以保持 shell 可区分的退出码语义。

func (*UsageError) Error

func (e *UsageError) Error() string

Error 返回参数校验的原始错误文本。

func (*UsageError) Unwrap

func (e *UsageError) Unwrap() error

Unwrap 暴露参数校验的原始错误。

Jump to

Keyboard shortcuts

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