• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..23-Jun-2021-

LICENSEH A D23-Jun-20211.1 KiB2217

README.mdH A D23-Jun-20218.3 KiB317255

app.goH A D23-Jun-20216.7 KiB311231

cli.goH A D23-Jun-2021927 4117

command.goH A D23-Jun-20216.2 KiB257183

context.goH A D23-Jun-20219.3 KiB397306

flag.goH A D23-Jun-202111.6 KiB502379

help.goH A D23-Jun-20216.1 KiB271204

README.md

1[![Build Status](https://travis-ci.org/codegangsta/cli.png?branch=master)](https://travis-ci.org/codegangsta/cli)
2
3# cli.go
4`cli.go` is simple, fast, and fun package for building command line apps in Go. The goal is to enable developers to write fast and distributable command line applications in an expressive way.
5
6You can view the API docs here:
7http://godoc.org/github.com/codegangsta/cli
8
9## Overview
10Command line apps are usually so tiny that there is absolutely no reason why your code should *not* be self-documenting. Things like generating help text and parsing command flags/options should not hinder productivity when writing a command line app.
11
12**This is where `cli.go` comes into play.** `cli.go` makes command line programming fun, organized, and expressive!
13
14## Installation
15Make sure you have a working Go environment (go 1.1+ is *required*). [See the install instructions](http://golang.org/doc/install.html).
16
17To install `cli.go`, simply run:
18```
19$ go get github.com/codegangsta/cli
20```
21
22Make sure your `PATH` includes to the `$GOPATH/bin` directory so your commands can be easily used:
23```
24export PATH=$PATH:$GOPATH/bin
25```
26
27## Getting Started
28One of the philosophies behind `cli.go` is that an API should be playful and full of discovery. So a `cli.go` app can be as little as one line of code in `main()`.
29
30``` go
31package main
32
33import (
34  "os"
35  "github.com/codegangsta/cli"
36)
37
38func main() {
39  cli.NewApp().Run(os.Args)
40}
41```
42
43This app will run and show help text, but is not very useful. Let's give an action to execute and some help documentation:
44
45``` go
46package main
47
48import (
49  "os"
50  "github.com/codegangsta/cli"
51)
52
53func main() {
54  app := cli.NewApp()
55  app.Name = "boom"
56  app.Usage = "make an explosive entrance"
57  app.Action = func(c *cli.Context) {
58    println("boom! I say!")
59  }
60
61  app.Run(os.Args)
62}
63```
64
65Running this already gives you a ton of functionality, plus support for things like subcommands and flags, which are covered below.
66
67## Example
68
69Being a programmer can be a lonely job. Thankfully by the power of automation that is not the case! Let's create a greeter app to fend off our demons of loneliness!
70
71Start by creating a directory named `greet`, and within it, add a file, `greet.go` with the following code in it:
72
73``` go
74package main
75
76import (
77  "os"
78  "github.com/codegangsta/cli"
79)
80
81func main() {
82  app := cli.NewApp()
83  app.Name = "greet"
84  app.Usage = "fight the loneliness!"
85  app.Action = func(c *cli.Context) {
86    println("Hello friend!")
87  }
88
89  app.Run(os.Args)
90}
91```
92
93Install our command to the `$GOPATH/bin` directory:
94
95```
96$ go install
97```
98
99Finally run our new command:
100
101```
102$ greet
103Hello friend!
104```
105
106`cli.go` also generates some bitchass help text:
107
108```
109$ greet help
110NAME:
111    greet - fight the loneliness!
112
113USAGE:
114    greet [global options] command [command options] [arguments...]
115
116VERSION:
117    0.0.0
118
119COMMANDS:
120    help, h  Shows a list of commands or help for one command
121
122GLOBAL OPTIONS
123    --version	Shows version information
124```
125
126### Arguments
127You can lookup arguments by calling the `Args` function on `cli.Context`.
128
129``` go
130...
131app.Action = func(c *cli.Context) {
132  println("Hello", c.Args()[0])
133}
134...
135```
136
137### Flags
138Setting and querying flags is simple.
139``` go
140...
141app.Flags = []cli.Flag {
142  cli.StringFlag{
143    Name: "lang",
144    Value: "english",
145    Usage: "language for the greeting",
146  },
147}
148app.Action = func(c *cli.Context) {
149  name := "someone"
150  if len(c.Args()) > 0 {
151    name = c.Args()[0]
152  }
153  if c.String("lang") == "spanish" {
154    println("Hola", name)
155  } else {
156    println("Hello", name)
157  }
158}
159...
160```
161
162See full list of flags at http://godoc.org/github.com/codegangsta/cli
163
164#### Alternate Names
165
166You can set alternate (or short) names for flags by providing a comma-delimited list for the `Name`. e.g.
167
168``` go
169app.Flags = []cli.Flag {
170  cli.StringFlag{
171    Name: "lang, l",
172    Value: "english",
173    Usage: "language for the greeting",
174  },
175}
176```
177
178That flag can then be set with `--lang spanish` or `-l spanish`. Note that giving two different forms of the same flag in the same command invocation is an error.
179
180#### Values from the Environment
181
182You can also have the default value set from the environment via `EnvVar`.  e.g.
183
184``` go
185app.Flags = []cli.Flag {
186  cli.StringFlag{
187    Name: "lang, l",
188    Value: "english",
189    Usage: "language for the greeting",
190    EnvVar: "APP_LANG",
191  },
192}
193```
194
195The `EnvVar` may also be given as a comma-delimited "cascade", where the first environment variable that resolves is used as the default.
196
197``` go
198app.Flags = []cli.Flag {
199  cli.StringFlag{
200    Name: "lang, l",
201    Value: "english",
202    Usage: "language for the greeting",
203    EnvVar: "LEGACY_COMPAT_LANG,APP_LANG,LANG",
204  },
205}
206```
207
208### Subcommands
209
210Subcommands can be defined for a more git-like command line app.
211```go
212...
213app.Commands = []cli.Command{
214  {
215    Name:      "add",
216    Aliases:     []string{"a"},
217    Usage:     "add a task to the list",
218    Action: func(c *cli.Context) {
219      println("added task: ", c.Args().First())
220    },
221  },
222  {
223    Name:      "complete",
224    Aliases:     []string{"c"},
225    Usage:     "complete a task on the list",
226    Action: func(c *cli.Context) {
227      println("completed task: ", c.Args().First())
228    },
229  },
230  {
231    Name:      "template",
232    Aliases:     []string{"r"},
233    Usage:     "options for task templates",
234    Subcommands: []cli.Command{
235      {
236        Name:  "add",
237        Usage: "add a new template",
238        Action: func(c *cli.Context) {
239            println("new task template: ", c.Args().First())
240        },
241      },
242      {
243        Name:  "remove",
244        Usage: "remove an existing template",
245        Action: func(c *cli.Context) {
246          println("removed task template: ", c.Args().First())
247        },
248      },
249    },
250  },
251}
252...
253```
254
255### Bash Completion
256
257You can enable completion commands by setting the `EnableBashCompletion`
258flag on the `App` object.  By default, this setting will only auto-complete to
259show an app's subcommands, but you can write your own completion methods for
260the App or its subcommands.
261```go
262...
263var tasks = []string{"cook", "clean", "laundry", "eat", "sleep", "code"}
264app := cli.NewApp()
265app.EnableBashCompletion = true
266app.Commands = []cli.Command{
267  {
268    Name:  "complete",
269    Aliases: []string{"c"},
270    Usage: "complete a task on the list",
271    Action: func(c *cli.Context) {
272       println("completed task: ", c.Args().First())
273    },
274    BashComplete: func(c *cli.Context) {
275      // This will complete if no args are passed
276      if len(c.Args()) > 0 {
277        return
278      }
279      for _, t := range tasks {
280        fmt.Println(t)
281      }
282    },
283  }
284}
285...
286```
287
288#### To Enable
289
290Source the `autocomplete/bash_autocomplete` file in your `.bashrc` file while
291setting the `PROG` variable to the name of your program:
292
293`PROG=myprogram source /.../cli/autocomplete/bash_autocomplete`
294
295#### To Distribute
296
297Copy `autocomplete/bash_autocomplete` into `/etc/bash_completion.d/` and rename
298it to the name of the program you wish to add autocomplete support for (or
299automatically install it there if you are distributing a package). Don't forget
300to source the file to make it active in the current shell.
301
302```
303   sudo cp src/bash_autocomplete /etc/bash_completion.d/<myprogram>
304   source /etc/bash_completion.d/<myprogram>
305```
306
307Alternatively, you can just document that users should source the generic
308`autocomplete/bash_autocomplete` in their bash configuration with `$PROG` set
309to the name of their program (as above).
310
311## Contribution Guidelines
312Feel free to put up a pull request to fix a bug or maybe add a feature. I will give it a code review and make sure that it does not break backwards compatibility. If I or any other collaborators agree that it is in line with the vision of the project, we will work with you to get the code into a mergeable state and merge it into the master branch.
313
314If you have contributed something significant to the project, I will most likely add you as a collaborator. As a collaborator you are given the ability to merge others pull requests. It is very important that new code does not break existing code, so be careful about what code you do choose to merge. If you have any questions feel free to link @codegangsta to the issue in question and we can review it together.
315
316If you feel like you have contributed to the project but have not yet been added as a collaborator, I probably forgot to add you. Hit @codegangsta up over email and we will get it figured out.
317