-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdoc_example_test.go
More file actions
59 lines (45 loc) · 1.46 KB
/
doc_example_test.go
File metadata and controls
59 lines (45 loc) · 1.46 KB
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
// SPDX-FileCopyrightText: 2025 The Cipher Host Team <team@cipher.host>
//
// SPDX-License-Identifier: MIT
package cmdkit_test
import (
"errors"
"fmt"
"go.cipher.host/cmdkit"
)
func Example() {
var (
// Create a new application with explicit metadata. You can also leave
// the name and version empty to have the application infer them from
// os.Args[0] and Go module information.
app = cmdkit.New("myapp", "A simple example application", "1.0.0")
// Add a simple command to the application.
greet = cmdkit.NewCommand("greet", "Greet someone by name", "[--formal] <name>")
)
var formal bool
// Register your flags using flag.TypeVar-kind of methods, e.g.
// flag.BoolVar. If you want to add a Unix-style short form, register both
// the long and short forms and then use App.AddShorthand.
greet.Flags.BoolVar(&formal, "formal", false, "use formal greeting")
// Set the command's run function.
greet.RunE = func(args []string) error {
if len(args) < 1 {
return errors.New("name is required")
}
if formal {
fmt.Fprintf(greet.OutWriter(), "Good day, %s!\n", args[0])
} else {
fmt.Fprintf(greet.OutWriter(), "Hi, %s!\n", args[0])
}
return nil
}
// Add the command to the application.
app.AddCommand(greet)
// Run the application with example arguments. You'd normally use
// os.Args[1:] instead.
if err := app.Run([]string{"greet", "Alice"}); err != nil {
app.Errorf("error: %v", err)
cmdkit.Exit(err)
}
// Output: Hi, Alice!
}