Debian Codegraph @

docs/v1/examples/bash-completions.md

raw symbols SCIP
1 ---
2 tags:
3 - v1
4 ---
5
6 You can enable completion commands by setting the `EnableBashCompletion`
7 flag on the `App` object. By default, this setting will only auto-complete to
8 show an app's subcommands, but you can write your own completion methods for
9 the App or its subcommands.
10
11 <!-- {
12 "args": ["complete", "&#45;&#45;generate&#45;bash&#45;completion"],
13 "output": "laundry"
14 } -->
15 ``` go
16 package main
17
18 import (
19 "fmt"
20 "log"
21 "os"
22
23 "github.com/urfave/cli"
24 )
25
26 func main() {
27 tasks := []string{"cook", "clean", "laundry", "eat", "sleep", "code"}
28
29 app := cli.NewApp()
30 app.EnableBashCompletion = true
31 app.Commands = []cli.Command{
32 {
33 Name: "complete",
34 Aliases: []string{"c"},
35 Usage: "complete a task on the list",
36 Action: func(c *cli.Context) error {
37 fmt.Println("completed task: ", c.Args().First())
38 return nil
39 },
40 BashComplete: func(c *cli.Context) {
41 // This will complete if no args are passed
42 if c.NArg() > 0 {
43 return
44 }
45 for _, t := range tasks {
46 fmt.Println(t)
47 }
48 },
49 },
50 }
51
52 err := app.Run(os.Args)
53 if err != nil {
54 log.Fatal(err)
55 }
56 }
57 ```
58
59 #### Enabling
60
61 Source the `autocomplete/bash_autocomplete` file in your `.bashrc` file while
62 setting the `PROG` variable to the name of your program:
63
64 `PROG=myprogram source /.../cli/autocomplete/bash_autocomplete`
65
66 #### Distribution
67
68 Copy `autocomplete/bash_autocomplete` into `/etc/bash_completion.d/` and rename
69 it to the name of the program you wish to add autocomplete support for (or
70 automatically install it there if you are distributing a package). Don't forget
71 to source the file to make it active in the current shell.
72
73 ```
74 sudo cp src/bash_autocomplete /etc/bash_completion.d/<myprogram>
75 source /etc/bash_completion.d/<myprogram>
76 ```
77
78 Alternatively, you can just document that users should source the generic
79 `autocomplete/bash_autocomplete` in their bash configuration with `$PROG` set
80 to the name of their program (as above).
81
82 #### Customization
83
84 The default bash completion flag (`--generate-bash-completion`) is defined as
85 `cli.BashCompletionFlag`, and may be redefined if desired, e.g.:
86
87 <!-- {
88 "args": ["&#45;&#45;compgen"],
89 "output": "wat\nhelp\nh"
90 } -->
91 ``` go
92 package main
93
94 import (
95 "log"
96 "os"
97
98 "github.com/urfave/cli"
99 )
100
101 func main() {
102 cli.BashCompletionFlag = cli.BoolFlag{
103 Name: "compgen",
104 Hidden: true,
105 }
106
107 app := cli.NewApp()
108 app.EnableBashCompletion = true
109 app.Commands = []cli.Command{
110 {
111 Name: "wat",
112 },
113 }
114 err := app.Run(os.Args)
115 if err != nil {
116 log.Fatal(err)
117 }
118 }
119 ```