golang构建命令行界面的简单完整API插件库teris-io/cli的使用

Golang构建命令行界面的简单完整API插件库teris-io/cli的使用

概述

teris-io/cli是一个用于在Go中构建命令行应用程序的简单、快速且完整的API库。与其他库相比,它强调位置参数的定义和验证,以及从所有级别处理选项的能力,同时保持最小的依赖集。

基本用法

定义命令

package main

import (
	"os"
	"github.com/teris-io/cli"
)

func main() {
	// 创建checkout命令
	co := cli.NewCommand("checkout", "checkout a branch or revision").
		WithShortcut("co").
		WithArg(cli.NewArg("revision", "branch or revision to checkout")).
		WithOption(cli.NewOption("branch", "Create branch if missing").WithChar('b').WithType(cli.TypeBool)).
		WithOption(cli.NewOption("upstream", "Set upstream for the branch").WithChar('u').WithType(cli.TypeBool)).
		WithAction(func(args []string, options map[string]string) int {
			// 执行checkout操作
			return 0
		})

	// 创建add命令
	add := cli.NewCommand("add", "add a remote").
		WithArg(cli.NewArg("remote", "remote to add"))

	// 创建remote命令并添加子命令
	rmt := cli.NewCommand("remote", "Work with git remotes").
		WithCommand(add)

	// 创建主应用
	app := cli.New("git tool").
		WithOption(cli.NewOption("verbose", "Verbose execution").WithChar('v').WithType(cli.TypeBool)).
		WithCommand(co).
		WithCommand(rmt)
		// 没有附加action,执行时只打印用法

	os.Exit(app.Run(os.Args, os.Stdout))
}

执行结果

  1. 不带参数运行程序会显示帮助信息:
gitc [--verbose]

Description:
    git tool

Options:
    -v, --verbose   Verbose execution

Sub-commands:
    git checkout    checkout a branch or revision
    git remote      Work with git remotes
  1. 使用checkout命令:
gitc co -vbu dev
# 或
gitc checkout -v --branch -u dev
  1. 如果提供未知选项会显示错误:
gitc co -f dev

输出:

fatal: unknown flag -f
usage: gitc checkout [--verbose] [--branch] [--upstream] <revision>

功能特点

  1. 支持位置参数定义和验证
  2. 支持选项定义(包括短选项和长选项)
  3. 支持子命令嵌套
  4. 简洁的API设计
  5. 最小依赖

许可证

Copyright (c) 2017. Oleg Sklyar and teris.io. MIT license applies. All rights reserved.

这个库非常适合需要构建复杂命令行界面的Go应用程序,特别是那些需要多级子命令和丰富选项的应用。


更多关于golang构建命令行界面的简单完整API插件库teris-io/cli的使用的实战教程也可以访问 https://www.itying.com/category-94-b0.html

1 回复

更多关于golang构建命令行界面的简单完整API插件库teris-io/cli的使用的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


teris-io/cli: 一个简单易用的Golang命令行界面构建库

teris-io/cli 是一个轻量级的Golang库,用于快速构建命令行界面(CLI)应用程序。它提供了简洁的API来定义命令、子命令、参数和标志,同时自动生成帮助信息。

安装

go get github.com/teris-io/cli

基本用法

1. 创建简单命令

package main

import (
	"fmt"
	"os"
	
	"github.com/teris-io/cli"
)

func main() {
	app := cli.New("My CLI App").
		WithCommand(cli.NewCommand("greet", "Print a greeting").
			WithArg(cli.NewArg("name", "Name to greet")).
			WithAction(func(args []string, options map[string]string) int {
				fmt.Printf("Hello, %s!\n", args[0])
				return 0
			}))
	
	os.Exit(app.Run(os.Args, os.Stdout))
}

2. 使用标志(flags)

app := cli.New("Calculator").
	WithCommand(cli.NewCommand("add", "Add two numbers").
		WithOption(cli.NewOption("round", "Round the result").WithChar('r').WithType(cli.TypeBool)).
		WithArg(cli.NewArg("num1", "First number").WithType(cli.TypeInt)).
		WithArg(cli.NewArg("num2", "Second number").WithType(cli.TypeInt)).
		WithAction(func(args []string, options map[string]string) int {
			num1 := args[0].(int)
			num2 := args[1].(int)
			result := num1 + num2
			
			if options["round"] == "true" {
				fmt.Printf("Result: %.0f\n", float64(result))
			} else {
				fmt.Printf("Result: %d\n", result)
			}
			return 0
		}))

3. 子命令结构

app := cli.New("File Manager").
	WithCommand(cli.NewCommand("file", "File operations").
		WithCommand(cli.NewCommand("create", "Create a file").
			WithArg(cli.NewArg("filename", "Name of the file to create")).
			WithAction(func(args []string, options map[string]string) int {
				// 创建文件逻辑
				return 0
			}).
		WithCommand(cli.NewCommand("delete", "Delete a file").
			WithArg(cli.NewArg("filename", "Name of the file to delete")).
			WithAction(func(args []string, options map[string]string) int {
				// 删除文件逻辑
				return 0
			}))

4. 类型验证

teris-io/cli 支持多种参数类型验证:

cli.NewArg("count", "Number of items").WithType(cli.TypeInt)
cli.NewOption("verbose", "Verbose output").WithType(cli.TypeBool)

支持的类型包括:TypeBool, TypeInt, TypeFloat, TypeString(默认)

5. 自定义帮助信息

app := cli.New("My App").
	WithDescription("A comprehensive CLI tool for various tasks").
	WithCommand(cli.NewCommand("version", "Show version information").
		WithAction(func(args []string, options map[string]string) int {
			fmt.Println("v1.0.0")
			return 0
		}))

高级特性

1. 短选项和长选项

cli.NewOption("output", "Output file").
	WithChar('o').  // 短选项 -o
	WithType(cli.TypeString)

2. 必需参数和可选参数

cli.NewArg("required", "Required argument").WithType(cli.TypeInt)
cli.NewArg("optional", "Optional argument").WithOptional(true)

3. 默认值

cli.NewOption("port", "Port number").
	WithType(cli.TypeInt).
	WithDefault("8080")

4. 多值参数

cli.NewArg("files", "List of files").WithOptional(true).WithVariadic(true)

完整示例

package main

import (
	"fmt"
	"os"
	"strings"
	
	"github.com/teris-io/cli"
)

func main() {
	searchCmd := cli.NewCommand("search", "Search for items").
		WithOption(cli.NewOption("case-sensitive", "Case sensitive search").WithChar('c').WithType(cli.TypeBool)).
		WithArg(cli.NewArg("query", "Search query")).
		WithAction(func(args []string, options map[string]string) int {
			query := args[0]
			if options["case-sensitive"] != "true" {
				query = strings.ToLower(query)
			}
			fmt.Printf("Searching for: %s (case-sensitive: %v)\n", query, options["case-sensitive"] == "true")
			return 0
		})

	configCmd := cli.NewCommand("config", "Manage configuration").
		WithCommand(cli.NewCommand("set", "Set a config value").
			WithArg(cli.NewArg("key", "Config key")).
			WithArg(cli.NewArg("value", "Config value")).
			WithAction(func(args []string, options map[string]string) int {
				fmt.Printf("Setting %s to %s\n", args[0], args[1])
				return 0
			}).
		WithCommand(cli.NewCommand("get", "Get a config value").
			WithArg(cli.NewArg("key", "Config key")).
			WithAction(func(args []string, options map[string]string) int {
				fmt.Printf("Getting value for %s\n", args[0])
				return 0
			}))

	app := cli.New("My CLI Tool").
		WithDescription("A powerful command-line tool for various tasks").
		WithCommand(searchCmd).
		WithCommand(configCmd).
		WithCommand(cli.NewCommand("version", "Show version").
			WithAction(func(args []string, options map[string]string) int {
				fmt.Println("v1.0.0")
				return 0
			}))

	os.Exit(app.Run(os.Args, os.Stdout))
}

总结

teris-io/cli 提供了以下主要优势:

  1. 简洁直观的API设计
  2. 自动生成帮助信息
  3. 内置参数类型验证
  4. 支持命令、子命令、参数和标志
  5. 轻量级,无额外依赖

对于需要快速构建CLI工具而又不想引入复杂框架的Golang开发者来说,teris-io/cli是一个很好的选择。它平衡了功能和简洁性,适合大多数中小型CLI应用场景。

回到顶部