~samwhited/cli

ref: 5252292b499e09ef67de02bdcc916fbbdf5dcebd cli/example_subcommands_test.go -rw-r--r-- 2.2 KiB
5252292bSam Whited cli: simplify example code 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
// Copyright 2017 The Mellium Contributors.
// Use of this source code is governed by the BSD 2-clause license that can be
// found in the LICENSE file.

package cli_test

import (
	"fmt"
	"os"

	"mellium.im/cli"
)

func Example_subcommands() {
	cmds := &cli.Command{
		Usage: "go <command>",
		Run: func(c *cli.Command, args ...string) error {
			fmt.Println("Ran go")
			return nil
		},
		Commands: []*cli.Command{{
			Usage: `mod <command> [arguments]`,
			Description: `Go mod provides access to operations on modules.

Note that support for modules is built into all the go commands…`,
			Run: func(c *cli.Command, args ...string) error {
				fmt.Println("Ran go mod")
				return nil
			},
			Commands: []*cli.Command{{
				Usage: `tidy [-v]`,
				Description: `Add missing and remove unused modules.

Tidy makes sure go.mod matches the source code in the module…`,
				Run: func(c *cli.Command, args ...string) error {
					fmt.Println("Ran go mod tidy")
					return nil
				},
			}},
		}},
	}
	cmds.Commands = append(cmds.Commands, cli.Help(cmds))
	fmt.Println("$ go help")
	cmds.Exec(os.Stdout, os.Stdout, "help")

	fmt.Print("$ go help mod\n\n")
	cmds.Exec(os.Stdout, os.Stdout, "help", "mod")

	fmt.Print("$ go help mod tidy\n\n")
	cmds.Exec(os.Stdout, os.Stdout, "help", "mod", "tidy")

	fmt.Print("$ go\n\n")
	cmds.Exec(os.Stdout, os.Stdout)

	fmt.Print("$ go mod\n\n")
	cmds.Exec(os.Stdout, os.Stdout, "mod")

	fmt.Print("$ go mod tidy\n\n")
	cmds.Exec(os.Stdout, os.Stdout, "mod", "tidy")

	// Output:
	// $ go help
	// Usage: go <command>
	//
	// Commands:
	//
	//	mod	Go mod provides access to operations on modules.
	//	help	Print articles and detailed information about subcommands.
	// $ go help mod
	//
	// Usage: mod <command> [arguments]
	//
	// Go mod provides access to operations on modules.
	//
	// Note that support for modules is built into all the go commands…
	// Commands:
	//
	//	tidy	Add missing and remove unused modules.
	// $ go help mod tidy
	//
	// Usage: tidy [-v]
	//
	// Add missing and remove unused modules.
	//
	// Tidy makes sure go.mod matches the source code in the module…
	// $ go
	//
	// Ran go
	// $ go mod
	//
	// Ran go mod
	// $ go mod tidy
	//
	// Ran go mod tidy
}