cortana

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Jun 9, 2026 License: Apache-2.0 Imports: 10 Imported by: 0

README

Cortana

上游仓库 https://github.com/shafreeck/cortana

一个极其易用的 Go 命令行参数解析库。

通过结构体标签(struct tags)声明式地定义命令行参数,无需手动编写解析逻辑。

功能特性

  • 声明式参数定义:通过结构体标签定义长选项、短选项、默认值和描述
  • 多层次子命令:支持 say hello cortana 这样的多级命令路径
  • 多来源参数:支持从配置文件、环境变量、命令行参数三种来源加载值
  • 命令别名:为命令创建快捷别名
  • 组合命令:使用方括号 [] 将多个参数组合为命令路径
  • 自动生成帮助:根据结构体标签自动生成帮助文档
  • 丰富的类型支持:string、int、uint、float、bool、slice、time.Duration

安装

go get github.com/liwenson/cortana

快速开始

基础用法
package main

import (
    "fmt"
    "github.com/liwenson/cortana"
)

func main() {
    args := struct {
        Name string `cortana:"--name, -n, tom, 你要对谁说话"`
        Text string `cortana:"text, -, -, 要说的内容"`
    }{}

    cortana.Parse(&args)
    fmt.Printf("Say to %s: %s\n", args.Name, args.Text)
}

运行:

$ go run main.go -n alice hello
Say to alice: hello

$ go run main.go --name bob "good morning"
Say to bob: good morning
使用子命令
package main

import (
    "fmt"
    "github.com/liwenson/cortana"
)

func say() {
    args := struct {
        Name string `cortana:"--name, -n, tom, 你要对谁说话"`
        Text string `cortana:"text, -, -, 要说的内容"`
    }{}
    cortana.Parse(&args)
    fmt.Printf("Say to %s: %s\n", args.Name, args.Text)
}

func main() {
    cortana.AddCommand("say", say, "说点什么")
    cortana.Launch()
}

运行:

$ go run main.go say -n alice hello
Say to alice: hello
多级子命令

同一个处理函数可以注册到不同的命令路径:

func main() {
    cortana.AddCommand("say greeting", say, "打招呼")
    cortana.AddCommand("greeting say", say, "打招呼(另一种方式)")
    cortana.Launch()
}

运行:

$ go run main.go say greeting -n alice hello
Say to alice: hello

$ go run main.go greeting say -n alice hello
Say to alice: hello

结构体标签格式

Cortana 使用 cortanalsdd(long-short-default-description 的缩写)标签来定义参数:

`cortana:"长选项, 短选项, 默认值, 描述"`
部分 说明 示例
长选项 -- 开头的选项名;不带 - 前缀则为位置参数 --nametext
短选项 - 开头的单字符选项名;无短选项用 - 占位 -n-
默认值 参数的默认值;- 表示必填项;''/"" 表示空值 tom18-
描述 参数的描述信息,支持逗号,会自动生成帮助文档 用户名
标签示例
type Args struct {
    // 选项参数:--name 或 -n,默认值 "tom"
    Name     string   `cortana:"--name, -n, tom, 用户名"`

    // 必填选项:必须通过 --age 或 -a 提供
    Age      int      `cortana:"--age, -a, -, 年龄"`

    // 位置参数:不带 "-" 前缀,按顺序匹配
    Text     string   `cortana:"text, -, -, 要说的内容"`

    // 布尔选项:出现即为 true
    Verbose  bool     `cortana:"--verbose, -v, false, 详细模式"`

    // 空字符串默认值
    Label    string   `cortana:"--label, -l, '', 标签名"`

    // 只有长选项,无短选项
    Output   string   `cortana:"--output, -, /tmp/out, 输出路径"`
}
支持的字段类型
Go 类型 示例默认值 说明
string tom 字符串
int/int16/... 18 整数
uint/uint16/... 8080 无符号整数
float32/float64 3.14 浮点数
bool false 布尔值,出现即为 true
[]string nil 可多次使用的切片参数
time.Duration 5s 时间间隔

命令行参数格式

Cortana 支持多种命令行参数书写格式:

# 长选项 + 空格分隔
--name alice

# 长选项 + 等号连接
--name=alice

# 短选项
-n alice

# 布尔选项(出现即为 true)
--verbose

# 位置参数(按顺序匹配)
hello world

配置文件支持

Cortana 支持从配置文件中加载参数值,配置文件的优先级低于命令行参数。

通过 AddConfig 添加默认配置文件
import (
    "encoding/json"
    "github.com/liwenson/cortana"
)

func main() {
    args := struct {
        Name string `json:"name" cortana:"--name, -n, tom, 用户名"`
        Age  int    `json:"age"  cortana:"--age, -a, 18, 年龄"`
    }{}

    // 自动加载 config.json(如果存在)
    cortana.AddConfig("config.json", cortana.UnmarshalFunc(json.Unmarshal))
    cortana.Parse(&args)

    fmt.Printf("Name: %s, Age: %d\n", args.Name, args.Age)
}
通过 ConfFlag 允许命令行指定配置文件路径
func main() {
    args := struct {
        Name string `json:"name" cortana:"--name, -n, tom, 用户名"`
    }{}

    cortana.AddConfig("config.json", cortana.UnmarshalFunc(json.Unmarshal))
    // 添加 --config/-c 选项来指定配置文件路径
    cortana.Use(cortana.ConfFlag("--config", "-c", cortana.UnmarshalFunc(json.Unmarshal)))
    cortana.Parse(&args)
}

运行:

$ go run main.go --config myconfig.json

环境变量支持

通过 AddEnvUnmarshaler 从环境变量加载参数值:

func main() {
    args := struct {
        Name string `cortana:"--name, -n, tom, 用户名"`
    }{}

    cortana.AddEnvUnmarshaler(cortana.EnvUnmarshalFunc(func(v interface{}) error {
        // 自定义从环境变量读取值的逻辑
        if name := os.Getenv("APP_NAME"); name != "" {
            if s, ok := v.(*struct {
                Name string `cortana:"--name, -n, tom, 用户名"`
            }); ok {
                s.Name = name
            }
        }
        return nil
    }))

    cortana.Parse(&args)
}

命令别名

为常用命令创建简短的别名:

func main() {
    cortana.AddCommand("say hello cortana", sayHelloCortana, "向 cortana 问好")

    // "cortana" 等价于 "say hello cortana"
    cortana.Alias("cortana", "say hello cortana")

    cortana.Launch()
}

运行:

$ go run main.go cortana
hello cortana

参数优先级

当多种来源同时提供值时,优先级从高到低为:

  1. 命令行参数(最高优先级)
  2. 环境变量
  3. 配置文件
  4. 结构体标签中的默认值(最低优先级)

更多示例

example/ 目录下有更多完整的示例代码:

示例文件 说明
example/say.go 综合示例,展示所有功能

运行示例:

cd example
go run say.go say hello cortana

API 参考

创建实例
// 创建新的 Cortana 实例(推荐用于多实例场景)
c := cortana.New()

// 创建实例时自定义选项
c := cortana.New(
    cortana.HelpFlag("--usage", "-u"),           // 自定义帮助选项
    cortana.ConfFlag("--config", "-c", unmarshaler), // 配置文件选项
)

// 禁用默认帮助选项
c := cortana.New(cortana.DisableHelpFlag())
全局便捷函数

Cortana 提供了一组全局函数,内部代理到默认实例,适合简单场景:

函数 说明
cortana.Parse(v, opts...) 解析命令行参数到结构体
cortana.AddCommand(path, cmd, brief) 注册命令
cortana.AddRootCommand(cmd) 注册根命令
cortana.Launch() 查找并执行匹配的命令
cortana.Alias(name, definition) 创建命令别名
cortana.AddConfig(path, unmarshaler) 添加配置文件
cortana.Title(text) 设置命令标题
cortana.Description(text) 设置命令描述
cortana.Args() 获取当前命令的参数列表
cortana.Commands() 获取所有已注册的命令
cortana.Use(opts...) 应用配置选项
Parse 选项
// 忽略未知参数(不报错退出)
cortana.Parse(&args, cortana.IgnoreUnknownArgs())

// 指定自定义参数列表(替代 os.Args,用于测试)
cortana.Parse(&args, cortana.WithArgs([]string{"--name", "alice"}))

许可证

Apache License 2.0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddCommand

func AddCommand(path string, cmd func(), brief string)

AddCommand 注册一个命令(使用全局默认实例)

func AddConfig

func AddConfig(path string, unmarshaler Unmarshaler)

AddConfig 添加一个配置文件(使用全局默认实例)

func AddRootCommand

func AddRootCommand(cmd func())

AddRootCommand 注册一个根命令(使用全局默认实例)

func Alias

func Alias(name, definition string)

Alias 给命令创建别名(使用全局默认实例)

func Args

func Args() []string

Args 返回当前命令的参数列表(使用全局默认实例)

func Description

func Description(text string)

Description 设置命令描述(使用全局默认实例)

func Launch

func Launch()

Launch 查找并执行匹配的命令(使用全局默认实例)

func Parse

func Parse(v interface{}, opts ...ParseOption)

Parse 将命令行参数解析到结构体中(使用全局默认实例)

func Title

func Title(text string)

Title 设置命令标题(使用全局默认实例)

func Usage

func Usage()

Usage 打印帮助信息并退出(使用全局默认实例)

func Use

func Use(opts ...Option)

Use 应用配置选项(使用全局默认实例)

Types

type Command

type Command struct {
	Path  string // 命令路径,如 "say hello"
	Proc  func() // 命令被匹配时执行的处理函数
	Brief string // 命令的简要描述
	Alias bool   // 是否是别名命令
	// contains filtered or unexported fields
}

Command 表示一个命令的执行单元 每个命令有路径(名称)、处理函数和简要描述

func Commands

func Commands() []*Command

Commands 返回所有已注册的命令(使用全局默认实例)

type Cortana

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

Cortana 是命令行解析器的核心结构体 管理命令注册、参数解析、配置加载等功能

func New

func New(opts ...Option) *Cortana

New 创建一个新的 Cortana 实例 默认设置帮助选项为 --help/-h,命令行参数从 os.Args 获取

func (*Cortana) AddCommand

func (c *Cortana) AddCommand(path string, cmd func(), brief string)

AddCommand 注册一个命令 参数:

  • path: 命令路径,多级命令用空格分隔,如 "say hello cortana"
  • cmd: 命令被匹配时执行的处理函数
  • brief: 命令的简要描述,用于帮助信息展示

func (*Cortana) AddConfig

func (c *Cortana) AddConfig(path string, unmarshaler Unmarshaler)

AddConfig 添加一个配置文件 参数:

  • path: 配置文件路径
  • unmarshaler: 配置文件的反序列化器

func (*Cortana) AddEnvUnmarshaler

func (c *Cortana) AddEnvUnmarshaler(unmarshaler EnvUnmarshaler)

AddEnvUnmarshaler 添加一个环境变量反序列化器

func (*Cortana) AddRootCommand

func (c *Cortana) AddRootCommand(cmd func())

AddRootCommand 注册一个根命令(无子路径) 当没有匹配到任何子命令时执行

func (*Cortana) Alias

func (c *Cortana) Alias(name, definition string)

Alias 给命令创建一个别名 参数:

  • name: 别名,如 "cortana"
  • definition: 原始命令路径,如 "say hello cortana"

func (*Cortana) Args

func (c *Cortana) Args() []string

Args 返回当前上下文中的参数列表

func (*Cortana) Commands

func (c *Cortana) Commands() []*Command

Commands 返回所有已注册的命令

func (*Cortana) Description

func (c *Cortana) Description(text string)

Description 设置当前命令的详细描述 描述信息会在帮助文档中展示,用于说明命令的用途和用法

func (*Cortana) Launch

func (c *Cortana) Launch()

Launch 查找并执行匹配的命令 它会解析命令行参数,查找对应的命令,如果找到则执行 如果未找到匹配命令,则显示帮助信息

func (*Cortana) Parse

func (c *Cortana) Parse(v interface{}, opts ...ParseOption)

Parse 将命令行参数解析到结构体中 通过结构体标签声明参数定义,支持配置文件、环境变量和命令行参数三种来源 参数:

  • v: 指向结构体的指针,结构体字段需使用 cortana 标签声明
  • opts: 可选的解析选项

func (*Cortana) Title

func (c *Cortana) Title(text string)

Title 设置当前命令的标题

func (*Cortana) Usage

func (c *Cortana) Usage()

Usage 打印帮助信息并退出 包含命令标题、描述、可用命令列表和选项说明

func (*Cortana) Use

func (c *Cortana) Use(opts ...Option)

Use 应用配置选项到当前 Cortana 实例

type EnvUnmarshalFunc

type EnvUnmarshalFunc func(v interface{}) error

EnvUnmarshalFunc 是一个函数类型,实现了 EnvUnmarshaler 接口 方便将普通函数转换为 EnvUnmarshaler

func (EnvUnmarshalFunc) Unmarshal

func (f EnvUnmarshalFunc) Unmarshal(v interface{}) error

Unmarshal 实现 EnvUnmarshaler 接口,直接调用函数本身

type EnvUnmarshaler

type EnvUnmarshaler interface {
	Unmarshal(v interface{}) error
}

EnvUnmarshaler 定义环境变量反序列化接口 实现此接口可以从环境变量中读取值并填充到目标结构体中

type Option

type Option func(flags *predefined)

Option 是 Cortana 的配置选项函数类型(函数式选项模式)

func ConfFlag

func ConfFlag(long, short string, unmarshaler Unmarshaler) Option

ConfFlag 添加配置文件路径选项 允许用户通过命令行参数指定配置文件路径 参数:

  • long: 长选项名,如 "--config"
  • short: 短选项名,如 "-c"
  • unmarshaler: 配置文件反序列化器

func DisableHelpFlag

func DisableHelpFlag() Option

DisableHelpFlag 禁用自动帮助选项

func HelpFlag

func HelpFlag(long, short string) Option

HelpFlag 自定义帮助选项的长选项名和短选项名

type ParseOption

type ParseOption func(opt *parseOption)

ParseOption 是 Parse 方法的选项函数类型

func IgnoreUnknownArgs

func IgnoreUnknownArgs() ParseOption

IgnoreUnknownArgs 设置解析时忽略未知的参数,不报错退出

func WithArgs

func WithArgs(args []string) ParseOption

WithArgs 指定自定义的参数列表进行解析(替代 os.Args) 主要用于测试场景

type UnmarshalFunc

type UnmarshalFunc func(data []byte, v interface{}) error

UnmarshalFunc 是一个函数类型,实现了 Unmarshaler 接口 方便将普通函数转换为 Unmarshaler,例如:

cortana.UnmarshalFunc(json.Unmarshal)

func (UnmarshalFunc) Unmarshal

func (f UnmarshalFunc) Unmarshal(data []byte, v interface{}) error

Unmarshal 实现 Unmarshaler 接口,直接调用函数本身

type Unmarshaler

type Unmarshaler interface {
	Unmarshal(data []byte, v interface{}) error
}

Unmarshaler 定义配置文件反序列化接口 实现此接口可以将配置文件的原始字节数据解析到目标结构体中

Directories

Path Synopsis
say.go 是一个综合示例,展示 Cortana 的主要功能: - 多层次子命令注册 - 结构体标签定义参数(cortana 和 lsdd 两种标签) - 命令标题和描述(用于帮助文档) - 命令别名 - 配置文件支持(JSON 格式) - 通过 --config/-c 选项动态指定配置文件路径
say.go 是一个综合示例,展示 Cortana 的主要功能: - 多层次子命令注册 - 结构体标签定义参数(cortana 和 lsdd 两种标签) - 命令标题和描述(用于帮助文档) - 命令别名 - 配置文件支持(JSON 格式) - 通过 --config/-c 选项动态指定配置文件路径

Jump to

Keyboard shortcuts

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