-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathexample_test.go
111 lines (102 loc) · 2.41 KB
/
example_test.go
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// This example demonstrates a simple "Hello, World!" CLI program.
package xflags
import (
"fmt"
"os"
"strings"
)
var (
flagLanguage string
flagNoNewLines bool
flagMessage []string
)
var translations = map[string]string{
"en": "Hello, World!",
"es": "Hola, Mundo!",
"it": "Ciao, Mondo!",
"nl": "Hallo, Wereld!",
}
var App = NewCommand("helloworld", "Print \"Hello, World!\"").
Synopsis(
"The helloworld utility writes \"Hello, World!\" to the standard\n"+
" output multiple languages.",
).
Flags(
// Bool flag to turn off newline printing with -n. The flag value is
// stored in cmd.NoNewLines.
Bool(
&flagNoNewLines,
"n",
false,
"Do not print the trailing newline character",
),
// String flag to select a desired language. Can be specified with
// -l, --language or the HW_LANG environment variable.
String(
&flagLanguage,
"language",
"en",
"Language (en, es, it or nl)",
).
ShortName("l").
Env("HW_LANG"),
// StringSlice flag to optionally print multiple positional
// arguments. Positional arguments are not denoted with "-" or "--".
Strings(
&flagMessage,
"MESSAGE",
nil,
"Optional message to print",
).Positional(),
).
HandleFunc(helloWorld)
// helloWorld is the HandlerFunc for the main App command.
func helloWorld(args []string) (exitCode int) {
s, ok := translations[flagLanguage]
if !ok {
fmt.Fprintf(os.Stderr, "Unsupported language: %s", flagLanguage)
return 1
}
if len(flagMessage) > 0 {
s = strings.Join(flagMessage, " ")
}
fmt.Print(s)
if !flagNoNewLines {
fmt.Print("\n")
}
return
}
func Example() {
fmt.Println("+ helloworld --help")
RunWithArgs(App, "--help")
// Most programs will call the following from main:
//
// func main() {
// os.Exit(xflags.Run(App))
// }
//
fmt.Println()
fmt.Println("+ helloworld --language=es")
RunWithArgs(App, "--language=es")
// Output:
// + helloworld --help
// Usage: helloworld [OPTIONS] [MESSAGE...]
//
// Print "Hello, World!"
//
// Positional arguments:
// MESSAGE Optional message to print
//
// Options:
// -n Do not print the trailing newline character
// -l, --language Language (en, es, it or nl)
//
// Environment variables:
// HW_LANG Language (en, es, it or nl)
//
// The helloworld utility writes "Hello, World!" to the standard
// output multiple languages.
//
// + helloworld --language=es
// Hola, Mundo!
}