-
Notifications
You must be signed in to change notification settings - Fork 1
/
calculator_example.go
92 lines (78 loc) · 2.13 KB
/
calculator_example.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
package main
import (
"fmt"
. "github.com/WindomZ/go-commander"
"strconv"
)
func main() {
// ----------- go-commander -----------
// calculator_example
Program.Version("0.0.1").
Description("Simple calculator example")
// calculator_example <value> ( ( + | - | * | / ) <value> )...
Program.Command("<value> ( ( + | - | * | / ) <value> )...", "", func() {
var result int
values := Program.MustStrings("<value>")
for index, value := range values {
if i, err := strconv.Atoi(value); err != nil {
} else if index == 0 {
result = i
} else {
switch Program.GetArg(index*2 - 1) {
case "+":
result += i
case "-":
result -= i
case "*":
result *= i
case "/":
result /= i
}
}
}
fmt.Println(Program.ArgsString(), "=", result)
})
// calculator_example <function> <value> [( , <value> )]...
Program.Command("<function> <value> [( , <value> )]...", "", func() {
var result int
switch Program.MustString("<function>") {
case "sum":
values := Program.MustStrings("<value>")
for _, value := range values {
if i, err := strconv.Atoi(value); err == nil {
result += i
}
}
}
fmt.Println(Program.ArgsString(), "=", result)
})
// Examples: ...
Program.Annotation("Examples",
[]string{
"calculator_example 1 + 2 + 3 + 4 + 5",
"calculator_example 1 + 2 '*' 3 / 4 - 5 # note quotes around '*'",
"calculator_example sum 10 , 20 , 30 , 40",
},
)
Program.Parse()
//fmt.Println(Program.HelpMessage()) // print help messages
fmt.Println("-------------")
// ----------- docopt-go -----------
usage := `Not a serious example.
Usage:
calculator_example <value> ( ( + | - | * | / ) <value> )...
calculator_example <function> <value> [( , <value> )]...
calculator_example (-h | --help)
Examples:
calculator_example 1 + 2 + 3 + 4 + 5
calculator_example 1 + 2 '*' 3 / 4 - 5 # note quotes around '*'
calculator_example sum 10 , 20 , 30 , 40
Options:
-h, --help
`
arguments, _ := Parse(usage, nil, true, "", false)
//fmt.Println(usage) // print help messages
fmt.Println(arguments)
fmt.Println("===============================")
fmt.Println()
}