首页 > 其他分享 >Go每日一库之5:cobra

Go每日一库之5:cobra

时间:2023-09-12 09:13:12浏览次数:40  
标签:选项 cobra git 命令 cmd 一库 go Go

简介

cobra是一个命令行程序库,可以用来编写命令行程序。同时,它也提供了一个脚手架,

用于生成基于 cobra 的应用程序框架。非常多知名的开源项目使用了 cobra 库构建命令行,如KubernetesHugoetcd等等等等。

本文介绍 cobra 库的基本使用和一些有趣的特性。

关于作者spf13,这里多说两句。spf13 开源不少项目,而且他的开源项目质量都比较高。

相信使用过 vim 的都知道spf13-vim,号称 vim 终极配置。

可以一键配置,对于我这样的懒人来说绝对是福音。他的viper是一个完整的配置解决方案。

完美支持 JSON/TOML/YAML/HCL/envfile/Java properties 配置文件等格式,还有一些比较实用的特性,如配置热更新、多查找目录、配置保存等。

还有非常火的静态网站生成器hugo也是他的作品。

快速使用

第三方库都需要先安装,后使用。下面命令安装了cobra生成器程序和 cobra 库:

$ go get github.com/spf13/cobra/cobra

如果出现了golang.org/x/text库找不到之类的错误,需要手动从 GitHub 上下载该库,再执行上面的安装命令。我以前写过一篇博客搭建 Go 开发环境提到了这个方法。

我们实现一个简单的命令行程序 git,当然这不是真的 git,只是模拟其命令行。最终还是通过os/exec库调用外部程序执行真实的 git 命令,返回结果。

所以我们的系统上要安装 git,且 git 在可执行路径中。目前我们只添加一个子命令version。目录结构如下:

▾ get-started/
    ▾ cmd/
        helper.go
        root.go
        version.go
    main.go

root.go

package cmd

import (
  "errors"

  "github.com/spf13/cobra"
)

var rootCmd = &cobra.Command {
  Use: "git",
  Short: "Git is a distributed version control system.",
  Long: `Git is a free and open source distributed version control system
designed to handle everything from small to very large projects 
with speed and efficiency.`,
  Run: func(cmd *cobra.Command, args []string) {
    Error(cmd, args, errors.New("unrecognized command"))
  },
}

func Execute() {
  rootCmd.Execute()
}

version.go

package cmd

import (
  "fmt"
  "os"

  "github.com/spf13/cobra"
)

var versionCmd = &cobra.Command {
  Use: "version",
  Short: "version subcommand show git version info.",
  
  Run: func(cmd *cobra.Command, args []string) {
    output, err := ExecuteCommand("git", "version", args...)
    if err != nil {
      Error(cmd, args, err)
    }

    fmt.Fprint(os.Stdout, output)
  },
}

func init() {
  rootCmd.AddCommand(versionCmd)
}

main.go文件中只是调用命令入口:

package main

import (
  "github.com/go-quiz/go-daily-lib/cobra/get-started/cmd"
)

func main() {
  cmd.Execute()
}

为了编码方便,在helpers.go中封装了调用外部程序和错误处理函数:

package cmd

import (
  "fmt"
  "os"
  "os/exec"

  "github.com/spf13/cobra"
)

func ExecuteCommand(name string, subname string, args ...string) (string, error) {
  args = append([]string{subname}, args...)

  cmd := exec.Command(name, args...)
  bytes, err := cmd.CombinedOutput()

  return string(bytes), err
}

func Error(cmd *cobra.Command, args []string, err error) {
  fmt.Fprintf(os.Stderr, "execute %s args:%v error:%v\n", cmd.Name(), args, err)
  os.Exit(1)
}

每个 cobra 程序都有一个根命令,可以给它添加任意多个子命令。我们在version.goinit函数中将子命令添加到根命令中。

编译程序。注意,不能直接go run main.go,这已经不是单文件程序了。如果强行要用,请使用go run .

$ go build -o main.exe

cobra 自动生成的帮助信息,very cool:

$ ./main.exe -h
Git is a free and open source distributed version control system
designed to handle everything from small to very large projects
with speed and efficiency.

Usage:
  git [flags]
  git [command]

Available Commands:
  help        Help about any command
  version     version subcommand show git version info.

Flags:
  -h, --help   help for git

Use "git [command] --help" for more information about a command.

单个子命令的帮助信息:

$ ./main.exe version -h
version subcommand show git version info.

Usage:
  git version [flags]

Flags:
  -h, --help   help for version

调用子命令:

$ ./main.exe version
git version 2.19.1.windows.1

未识别的子命令:

$ ./main.exe clone
Error: unknown command "clone" for "git"
Run 'git --help' for usage.

编译时可以将main.exe改成git,用起来会更有感觉

标签:选项,cobra,git,命令,cmd,一库,go,Go
From: https://www.cnblogs.com/startisan/p/17695079.html

相关文章

  • Golang日志新选择:slog
    go1.21中,slog这一被Go语言团队精心设计的结构化日志包正式落地,本文将带领读者上手slog,体会其与传统log的差异。WHY在日志处理上,我们从前使用的log包缺乏结构化的输出,导致信息呈现出来的样子并非最适合人类阅读,而slog是一种结构化的日志,它可以用键值对的形式将我们需要的信息呈现......
  • Django-分页组件
    在/test_orm/文件夹下新建一个文件夹utils,在其下新建一个paginater.py:classPaginater():def__init__(self,url_address,cur_page_num,total_rows,one_page_lines=10,page_maxtag=9):"""url_address:页码标签href的地址,也就是分页功能的网页URL......
  • Django_debug page_XSS漏洞(CVE-2017-12794)漏洞复现
    目录1.1、漏洞描述1.2、漏洞等级1.3、影响版本1.4、漏洞复现1、基础环境2、漏洞分析3、漏洞验证说明内容漏洞编号CVE-2017-12794漏洞名称Django_debugpage_XSS漏洞漏洞评级影响范围1.11.5版本漏洞描述修复方案1.1、漏洞描述1.11.5版本,修复了......
  • Go每日一库之4:go-ini
    简介ini是Windows上常用的配置文件格式。MySQL的Windows版就是使用ini格式存储配置的。go-ini是Go语言中用于操作ini文件的第三方库。本文介绍go-ini库的使用。快速使用go-ini是第三方库,使用前需要安装:$gogetgopkg.in/ini.v1也可以使用GitHub上的仓库:$......
  • K8s - 安装部署MongoDB数据库教程1(单实例)
    来源:https://www.hangge.com/blog/cache/detail_3158.htmlMongoDB 是一个基于分布式文件存储的数据库。我之前文件中介绍如何使用官方提供的安装包进行 MongoDB 数据库的安装(点击查看),以及如何通过 Docker 来快速搭建 MongoDB 数据库环境(点击查看)。本文接着演示如何在 Ku......
  • Proj. CRR Paper Reading: Optimal Speedup of Las Vegas Algorithms, Adaptive resta
    TitleAdaptiverestartforstochasticsynthesisPLDI2021TaskDistributethepowerbetweenmultiplerunsinstochasticprogramsynthesistoaccelerateHere,astochasticprogramsynthesisprogramcanbesummarizedasfollows:Givenasetof<input,ou......
  • RunnerGo:让你的性能测试变得轻松简单
    在当今这个数字化时代,应用程序的性能至关重要。一款可靠的性能测试工具,能够为企业带来无数的好处。最近,一款名为RunnerGo的开源性能测试工具备受瞩目。本文将详细介绍RunnerGo的特点、优势以及如何解决性能测试中的痛点。RunnerGo产品介绍RunnerGo是一款由国内开发者自主研发的性能......
  • RunnerGo:让你的性能测试变得轻松简单
    在当今这个数字化时代,应用程序的性能至关重要。一款可靠的性能测试工具,能够为企业带来无数的好处。最近,一款名为RunnerGo的开源性能测试工具备受瞩目。本文将详细介绍RunnerGo的特点、优势以及如何解决性能测试中的痛点。 RunnerGo产品介绍RunnerGo是一款由国内开发者自主研......
  • fyne container.NewHSplit水平分割容器 Go golang
    环境:gofyne 要求:go项目中将窗口分成左右两个容器,实现窗口分割效果:实现代码:1packagemain23import(4"fyne.io/fyne/v2"5"fyne.io/fyne/v2/app"6"fyne.io/fyne/v2/container"7"fyne.io/fyne/v2/widget"8)91......
  • MongoDB监测工具
    mongostatinsert表示每秒插入数据库的对象数量,如果跟在一个*后面,表示这是复制操作query每秒查询操作数量update每秒更新操作数量delete每秒删除操作数量getmore每秒getmore操作的数量command每秒执行数据库命令操作的数量(比如插入、查找、更新、删除等等)flushes每秒......