Generating Command Completion and Documentation

Powerful Command-Line Applications in Go — by Ricardo Gerardi (81 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Using Viper for Configuration Manag ement | TOC | Exercises 👉

Two features that improve your user experience are command completion and documentation. Command completion guides the user by providing contextual suggestions when they press the TAB key. Documentation instructs users by providing additional information, context, and examples about using the application.

Let’s add two new subcommands to your tool allowing the users to generate command completion and documentation for it. Start with the command completion subcommand completion. Use the Cobra generator again to add this subcommand to your application:

​ ​$ ​​cobra​​ ​​add​​ ​​completion​
​ Using config file: /home/ricardo/.cobra.yaml
​ completion created at /home/ricardo/pragprog.com/rggo/cobra/pScan

Then edit the generated file cmd/completion.go. Update the import section by removing the fmt package as this command doesn’t use it. Also, add the io package to use the io.Writer interface and the os package to use the file os.Stdout to print the command completion to STDOUT.

cobra/pScan.v7/cmd/completion.go

​ ​import​ (
» ​"io"​
» ​"os"​
»

​ ​"github.com/spf13/cobra"​
​ )

Next, update the completionCmd definition by updating the Short description, including an…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.