forked from jessevdk/go-flags
-
Notifications
You must be signed in to change notification settings - Fork 0
/
help.go
124 lines (95 loc) · 2.47 KB
/
help.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
112
113
114
115
116
117
118
119
120
121
122
123
124
// Copyright 2012 Jesse van den Kieboom. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package flags
import (
"bufio"
"fmt"
"io"
"strings"
"unicode/utf8"
)
func (p *Parser) maxLongLen() (int, bool) {
maxlonglen := 0
hasshort := false
for _, grp := range p.Groups {
for _, info := range grp.Options {
if info.ShortName != 0 {
hasshort = true
}
l := utf8.RuneCountInString(info.LongName)
if l > maxlonglen {
maxlonglen = l
}
}
}
return maxlonglen, hasshort
}
func (p *Parser) writeHelpOption(writer *bufio.Writer, option *Option, maxlen int, hasshort bool, termcol int) {
if option.ShortName != 0 {
writer.WriteString(" -")
writer.WriteRune(option.ShortName)
} else if hasshort {
writer.WriteString(" ")
}
written := 0
prelen := 4
if option.LongName != "" {
if option.ShortName != 0 {
writer.WriteString(", ")
} else {
writer.WriteString(" ")
}
fmt.Fprintf(writer, "--%s", option.LongName)
written = utf8.RuneCountInString(option.LongName)
prelen += written + 4
}
if option.Description != "" {
if written < maxlen {
dw := maxlen - written
writer.WriteString(strings.Repeat(" ", dw))
prelen += dw
}
def := convertToString(option.value, option.options)
var desc string
if def != "" {
desc = fmt.Sprintf("%s (%v)", option.Description, def)
} else {
desc = option.Description
}
writer.WriteString(wrapText(desc,
termcol-prelen,
strings.Repeat(" ", prelen)))
}
writer.WriteString("\n")
}
// WriteHelp writes a help message containing all the possible options and
// their descriptions to the provided writer. Note that the HelpFlag parser
// option provides a convenient way to add a -h/--help option group to the
// command line parser which will automatically show the help messages using
// this method.
func (p *Parser) WriteHelp(writer io.Writer) {
if writer == nil {
return
}
wr := bufio.NewWriter(writer)
if p.ApplicationName != "" {
wr.WriteString("Usage:\n")
fmt.Fprintf(wr, " %s", p.ApplicationName)
if p.Usage != "" {
fmt.Fprintf(wr, " %s", p.Usage)
}
wr.WriteString("\n")
}
maxlonglen, hasshort := p.maxLongLen()
maxlen := maxlonglen + 4
termcol := getTerminalColumns()
for _, grp := range p.Groups {
wr.WriteString("\n")
fmt.Fprintf(wr, "%s:\n", grp.Name)
for _, info := range grp.Options {
p.writeHelpOption(wr, info, maxlen, hasshort, termcol)
}
}
wr.Flush()
}