-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathusage.go
More file actions
36 lines (32 loc) · 719 Bytes
/
usage.go
File metadata and controls
36 lines (32 loc) · 719 Bytes
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
package flagx
import (
"flag"
"fmt"
"os"
"strings"
)
// Usage prints s and optional description for all the flags if -h or -help flag is passed to the app.
func Usage(s string) {
f := flag.CommandLine.Output()
fmt.Fprintf(f, "%s\n", s)
if hasHelpFlag(os.Args[1:]) {
flag.PrintDefaults()
} else {
fmt.Fprintf(f, `Run "%s -help" in order to see the description for all the available flags`+"\n", os.Args[0])
}
}
func hasHelpFlag(args []string) bool {
for _, arg := range args {
if isHelpArg(arg) {
return true
}
}
return false
}
func isHelpArg(arg string) bool {
if !strings.HasPrefix(arg, "-") {
return false
}
arg = strings.TrimPrefix(arg[1:], "-")
return arg == "h" || arg == "help"
}