/
usage.go
78 lines (65 loc) · 1.8 KB
/
usage.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
package zli
import (
"os"
"path/filepath"
"regexp"
"strings"
)
// Formatting flags for Usage.
const (
// UsageTrim removes leading and trailing whitespace and appends a newline.
//
// This makes it easier to write usage strings without worrying too much
// about leading/trailing whitespace, and with the trailing newline it's
// easy to add a blank line between the usage and any error message
// (fmt.Println if you wnat a blank line, fmt.Print if you don't).
UsageTrim = 1
// UsageHeaders formats headers in the form of:
//
// Header:
//
// A header must be at the start of the line, preceded by a blank line, and
// end with a double colon (:).
UsageHeaders = 2
// UsageFlags formats flags in the form of:
//
// -f
// -flag
// -flag=foo
// -flag=[foo]
UsageFlags = 4
// UsageProgram replaces "%(prog)" with filepath.Base(os.Args[0]).
UsageProgram = 8
)
var (
reHeader = regexp.MustCompile(`^\w[\w -]+:$`)
reFlags = regexp.MustCompile(`\B-{1,2}[a-z0-9=-]+\b`)
)
var (
// FormatHeader is the formatting to apply for a header.
FormatHeader = Bold
// FormatFlag is the formatting to apply for a flag.
FormatFlag = Underline
)
// Usage applies some formatting to a usage message. See the Usage* constants.
func Usage(opts int, text string) string {
if opts&UsageTrim != 0 {
text = strings.TrimSpace(text) + "\n"
}
if opts&UsageProgram != 0 {
text = strings.ReplaceAll(text, "%(prog)", filepath.Base(os.Args[0]))
}
if opts&UsageHeaders != 0 {
split := strings.Split(text, "\n")
for i := range split {
if reHeader.MatchString(split[i]) && (i == 0 || split[i-1] == "") {
split[i] = Colorize(split[i], FormatHeader)
}
}
text = strings.Join(split, "\n")
}
if opts&UsageFlags != 0 {
text = reFlags.ReplaceAllString(text, Colorize(`$0`, FormatFlag))
}
return text
}