-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsimplehelp.go
76 lines (61 loc) · 2.13 KB
/
simplehelp.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
package simplehelp
import (
"flag"
"fmt"
"github.com/fatih/color"
)
// SimpleHelp - object containing configuration options for the help function
type SimpleHelp struct {
ProgramTitle string // Title of your CLI program goes here
ProgramDescription string // Program description
Indentation int // How many characters to indent the flag descriptions
helpSections []helpSection
helpFormatString string
}
type helpSection struct {
name string
description string
}
// Help - Gets available flags, combines with the config options,
// and outputs a help page to stdout.
// Usage: flag.CommandLine.Usage = help.Help
// Can also be called directly: help.Help()
func (h *SimpleHelp) Help() {
h.helpFormatString = h.makeHelpFormatStr()
grebo := color.New(color.FgBlue, color.Bold)
printSection(h.ProgramTitle, h.ProgramDescription, grebo)
for _, section := range h.helpSections {
printSection(section.name, section.description, grebo)
}
grebo.Print("\nFlags:\n")
// print usage for all flags
flag.CommandLine.VisitAll(func(fl *flag.Flag) {
var defaultString string
if fl.DefValue != "" {
defaultString = fmt.Sprintf("(Default: %s)", fl.DefValue)
}
fmt.Printf(" --%s%s %s\n", h.flagIndentation(fl.Name), fl.Usage, defaultString)
})
fmt.Print("\n")
}
// AddSection - Adds a help section to the help output.
func (h *SimpleHelp) AddSection(name string, description string) {
h.helpSections = append(h.helpSections, helpSection{name: name, description: description})
}
// Prints a section (colored title, plain content)
func printSection(title string, content string, c *color.Color) {
c.Printf("\n%s\n", title)
fmt.Println(" " + content)
}
// creates a formatting string that can be used for space-padding via Sprintf
func (h *SimpleHelp) makeHelpFormatStr() string {
return fmt.Sprintf("%%-%ds", h.Indentation)
}
// uses the formatting string to apply space padding
func (h *SimpleHelp) flagIndentation(flagName string) string {
return fmt.Sprintf(h.helpFormatString, flagName)
}
// Hint - Prints a small hint about the --help parameter
func Hint() {
fmt.Println("Use --help for more information")
}