![cobra logo](https://cloud.githubusercontent.com/assets/173412/10886352/ad566232-814f-11e5-9cd0-aa101788c117.png)
Cobra is both a library for creating powerful modern CLI applications as well as a program to generate applications and command files.
Cobra is used in many Go projects such as [Kubernetes](http://kubernetes.io/),
[Hugo](https://gohugo.io), and [Github CLI](https://github.com/cli/cli) to
name a few. [This list](./projects_using_cobra.md) contains a more extensive list of projects using Cobra.
[![](https://img.shields.io/github/workflow/status/spf13/cobra/Test?longCache=tru&label=Test&logo=github%20actions&logoColor=fff)](https://github.com/spf13/cobra/actions?query=workflow%3ATest)
[![Build Status](https://travis-ci.org/spf13/cobra.svg "Travis CI status")](https://travis-ci.org/spf13/cobra)
[![GoDoc](https://godoc.org/github.com/spf13/cobra?status.svg)](https://godoc.org/github.com/spf13/cobra)
[![Go Report Card](https://goreportcard.com/badge/github.com/spf13/cobra)](https://goreportcard.com/report/github.com/spf13/cobra)
[![Slack](https://img.shields.io/badge/Slack-cobra-brightgreen)](https://gophers.slack.com/archives/CD3LP1199)
# Table of Contents
- [Overview](#overview)
- [Concepts](#concepts)
* [Commands](#commands)
* [Flags](#flags)
- [Installing](#installing)
- [Getting Started](#getting-started)
* [Using the Cobra Generator](#using-the-cobra-generator)
* [Using the Cobra Library](#using-the-cobra-library)
* [Working with Flags](#working-with-flags)
* [Positional and Custom Arguments](#positional-and-custom-arguments)
* [Example](#example)
* [Help Command](#help-command)
* [Usage Message](#usage-message)
* [PreRun and PostRun Hooks](#prerun-and-postrun-hooks)
* [Suggestions when "unknown command" happens](#suggestions-when-unknown-command-happens)
* [Generating documentation for your command](#generating-documentation-for-your-command)
* [Generating shell completions](#generating-shell-completions)
- [Contributing](CONTRIBUTING.md)
- [License](#license)
# Overview
Cobra is a library providing a simple interface to create powerful modern CLI
interfaces similar to git & go tools.
Cobra is also an application that will generate your application scaffolding to rapidly
develop a Cobra-based application.
Cobra provides:
* Easy subcommand-based CLIs: `app server`, `app fetch`, etc.
* Fully POSIX-compliant flags (including short & long versions)
* Nested subcommands
* Global, local and cascading flags
* Easy generation of applications & commands with `cobra init appname` & `cobra add cmdname`
* Intelligent suggestions (`app srver`... did you mean `app server`?)
* Automatic help generation for commands and flags
* Automatic help flag recognition of `-h`, `--help`, etc.
* Automatically generated shell autocomplete for your application (bash, zsh, fish, powershell)
* Automatically generated man pages for your application
* Command aliases so you can change things without breaking them
* The flexibility to define your own help, usage, etc.
* Optional tight integration with [viper](http://github.com/spf13/viper) for 12-factor apps
# Concepts
Cobra is built on a structure of commands, arguments & flags.
**Commands** represent actions, **Args** are things and **Flags** are modifiers for those actions.
The best applications read like sentences when used, and as a result, users
intuitively know how to interact with them.
The pattern to follow is
`APPNAME VERB NOUN --ADJECTIVE.`
or
`APPNAME COMMAND ARG --FLAG`
A few good real world examples may better illustrate this point.
In the following example, 'server' is a command, and 'port' is a flag:
hugo server --port=1313
In this command we are telling Git to clone the url bare.
git clone URL --bare
## Commands
Command is the central point of the application. Each interaction that
the application supports will be contained in a Command. A command can
have children commands and optionally run an action.
In the example above, 'server' is the command.
[More about cobra.Command](https://godoc.org/github.com/spf13/cobra#Command)
## Flags
A flag is a way to modify the behavior of a command. Cobra supports
fully POSIX-compliant flags as well as the Go [flag package](https://golang.org/pkg/flag/).
A Cobra command can define flags that persist through to children commands
and flags that are only available to that command.
In the example above, 'port' is the flag.
Flag functionality is provided by the [pflag
library](https://github.com/spf13/pflag), a fork of the flag standard library
which maintains the same interface while adding POSIX compliance.
# Installing
Using Cobra is easy. First, use `go get` to install the latest version
of the library. This command will install the `cobra` generator executable
along with the library and its dependencies:
go get -u github.com/spf13/cobra
Next, include Cobra in your application:
```go
import "github.com/spf13/cobra"
```
# Getting Started
While you are welcome to provide your own organization, typically a Cobra-based
application will follow the following organizational structure:
```
▾ appName/
▾ cmd/
add.go
your.go
commands.go
here.go
main.go
```
In a Cobra app, typically the main.go file is very bare. It serves one purpose: initializing Cobra.
```go
package main
import (
"{pathToYourApp}/cmd"
)
func main() {
cmd.Execute()
}
```
## Using the Cobra Generator
Cobra provides its own program that will create your application and add any
commands you want. It's the easiest way to incorporate Cobra into your application.
[Here](https://github.com/spf13/cobra/blob/master/cobra/README.md) you can find more information about it.
## Using the Cobra Library
To manually implement Cobra you need to create a bare main.go file and a rootCmd file.
You will optionally provide additional commands as you see fit.
### Create rootCmd
Cobra doesn't require any special constructors. Simply create your commands.
Ideally you place this in app/cmd/root.go:
```go
var rootCmd = &cobra.Command{
Use: "hugo",
Short: "Hugo is a very fast static site generator",
Long: `A Fast and Flexible Static Site Generator built with
love by spf13 and friends in Go.
Complete documentation is available at http://hugo.spf13.com`,
Run: func(cmd *cobra.Command, args []string) {
// Do Stuff Here
},
}
func Execute() {
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
```
You will additionally define flags and handle configuration in your init() function.
For example cmd/root.go:
```go
package cmd
import (
"fmt"
"os"
homedir "github.com/mitchellh/go-homedir"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
// Used for flags.
cfgFile string
userLicense string
rootCmd = &cobra.Command{
Use: "cobra",
Short: "A generator for Cobra based Applications",
Long: `Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
}
)
// Execute executes the root command.
func Execute() error {
return rootCmd.Execute()
}
func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cobra.yaml)")
rootCmd.PersistentFlags().StringP("author", "a", "YOUR NAME", "author name for copyright attribution")
rootCmd.PersistentFlags().StringVarP(&userLicense, "license", "l", "", "name of license for the project")
rootCmd.PersistentFlags().Bool("viper", true, "use Viper for configuration")
viper.BindPFlag("author", rootCmd.PersistentFlags().Lookup("author"))
viper.BindPFlag("useViper", rootCmd.PersistentFlags().Lookup("viper"))
viper.SetDefault("author", "NAME HERE <EMAIL ADDRESS>")
viper.SetDefault("license", "apache")
rootCmd.AddCommand(addCmd)
rootCmd.AddCommand(initCmd)
}
func initConfig() {
没有合适的资源?快使用搜索试试~ 我知道了~
温馨提示
goland 支持调试(支持go1.8.3) 1)编译dlv delve 地址:https://github.com/go-delve/delve delve-master: 支持1.8.3 进入delve-master/delve/cmd go build 得到dlv 2)然后将dlv文件复制到/usr/local/go/bin 3)配置调试器 在goland配置调试器 Help->Edit Custom Properties dlv.path=/usr/local/go/bin/dlv 完成这一步后,需要重启一下JetBrains GoLand,选择路径File->Invalidate Caches /Restart
资源详情
资源评论
资源推荐
收起资源包目录
goland 调试器 delve (1283个子文件)
AUTHORS 174B
AUTHORS 173B
AUTHORS 173B
mkerrors.bash 2KB
mkknownfolderids.bash 1KB
mktypes.bash 329B
bpfile 69B
mach_exc_user_darwin.c 20KB
exc_user_darwin.c 20KB
trace.bpf.c 8KB
proc_darwin.c 7KB
threads_darwin.c 5KB
exec_darwin.c 2KB
proc_freebsd.c 2KB
gccgo_c.c 1KB
test.c 805B
hello.c 431B
codereview.cfg 21B
.clang-format 491B
CONTRIBUTORS 171B
CONTRIBUTORS 170B
CONTRIBUTORS 170B
COPYING 1KB
debug_line_benchmark_data 452KB
debug_line_c_data 209B
ebpf-Dockerfile 450B
frame 70KB
.gitattributes 29B
.gitignore 484B
.gitignore 206B
.gitignore 111B
.gitignore 46B
.gitignore 27B
.gitignore 16B
.gitignore 14B
.gitignore 9B
.gitignore 7B
zerrors_windows.go 923KB
server_test.go 282KB
tables.go 266KB
tables.go 212KB
proc_test.go 182KB
zsyscall_windows.go 165KB
zerrors_linux.go 152KB
properties.go 148KB
ztypes_linux.go 141KB
server.go 139KB
zsysnum_zos_s390x.go 117KB
types_windows.go 97KB
integration2_test.go 87KB
zerrors_darwin_arm64.go 87KB
zerrors_darwin_amd64.go 87KB
schematypes.go 87KB
command.go 84KB
zerrors_openbsd_mips64.go 77KB
decode.go 77KB
zerrors_freebsd_arm64.go 76KB
zerrors_freebsd_386.go 76KB
zerrors_freebsd_amd64.go 76KB
scannerc.go 76KB
zerrors_openbsd_arm64.go 74KB
syscall_windows.go 73KB
zerrors_netbsd_386.go 73KB
zerrors_openbsd_amd64.go 73KB
zerrors_netbsd_arm64.go 72KB
zerrors_netbsd_amd64.go 72KB
bininfo.go 72KB
zerrors_freebsd_arm.go 72KB
zerrors_netbsd_arm.go 72KB
variables_test.go 72KB
zerrors_dragonfly_amd64.go 71KB
variables.go 70KB
syscall_linux.go 69KB
zerrors_openbsd_arm.go 68KB
zerrors_openbsd_386.go 68KB
eval.go 66KB
zsyscall_darwin_amd64.go 65KB
zsyscall_darwin_arm64.go 65KB
debugger.go 61KB
gdbserver.go 60KB
zerrors_solaris_amd64.go 59KB
library.go 58KB
zsyscall_solaris_amd64.go 57KB
starlark_mapping.go 53KB
zerrors_aix_ppc64.go 53KB
zerrors_aix_ppc.go 52KB
security_windows.go 52KB
syscall_zos_s390x.go 49KB
zsyscall_linux.go 49KB
zsyscall_freebsd_arm.go 48KB
zsyscall_freebsd_386.go 48KB
zsyscall_freebsd_arm64.go 48KB
zsyscall_freebsd_amd64.go 48KB
compile.go 47KB
command.go 46KB
decode.go 45KB
zsyscall_netbsd_arm.go 44KB
zsyscall_netbsd_386.go 44KB
emitterc.go 44KB
zsyscall_netbsd_arm64.go 44KB
共 1283 条
- 1
- 2
- 3
- 4
- 5
- 6
- 13
小鱼的狂想
- 粉丝: 7
- 资源: 14
上传资源 快速赚钱
- 我的内容管理 展开
- 我的资源 快来上传第一个资源
- 我的收益 登录查看自己的收益
- 我的积分 登录查看自己的积分
- 我的C币 登录后查看C币余额
- 我的收藏
- 我的下载
- 下载帮助
安全验证
文档复制为VIP权益,开通VIP直接复制
信息提交成功
评论0