Skip to content

Commit

Permalink
add SuperFlagHelp tool to generate flag help text (#251)
Browse files Browse the repository at this point in the history
  • Loading branch information
karlmcguire authored Feb 18, 2021
1 parent 9c8fa18 commit 024fba8
Showing 1 changed file with 62 additions and 0 deletions.
62 changes: 62 additions & 0 deletions z/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,75 @@ package z
import (
"fmt"
"log"
"sort"
"strconv"
"strings"
"time"

"github.com/pkg/errors"
)

// SuperFlagHelp makes it really easy to generate command line `--help` output for a SuperFlag. For
// example:
//
// const flagDefaults = `enabled=true; path=some/path;`
//
// var help string = z.NewSuperFlagHelp(flagDefaults).
// Flag("enabled", "Turns on <something>.").
// Flag("path", "The path to <something>.").
// Flag("another", "Not present in defaults, but still included.").
// String()
//
// The `help` string would then contain:
//
// enabled=true; Turns on <something>.
// path=some/path; The path to <something>.
// another=; Not present in defaults, but still included.
//
// All flags are sorted alphabetically for consistent `--help` output. Flags with default values are
// placed at the top, and everything else goes under.
type SuperFlagHelp struct {
head string
defaults *SuperFlag
flags map[string]string
}

func NewSuperFlagHelp(defaults string) *SuperFlagHelp {
return &SuperFlagHelp{
defaults: NewSuperFlag(defaults),
flags: make(map[string]string, 0),
}
}

func (h *SuperFlagHelp) Head(head string) *SuperFlagHelp {
h.head = head
return h
}

func (h *SuperFlagHelp) Flag(name, description string) *SuperFlagHelp {
h.flags[name] = description
return h
}

func (h *SuperFlagHelp) String() string {
defaultLines := make([]string, 0)
otherLines := make([]string, 0)
for name, help := range h.flags {
val, found := h.defaults.m[name]
line := fmt.Sprintf(" %s=%s; %s\n", name, val, help)
if found {
defaultLines = append(defaultLines, line)
} else {
otherLines = append(otherLines, line)
}
}
sort.Strings(defaultLines)
sort.Strings(otherLines)
dls := strings.Join(defaultLines, "")
ols := strings.Join(otherLines, "")
return h.head + "\n" + dls + ols[:len(ols)-1] // remove last newline
}

func parseFlag(flag string) map[string]string {
kvm := make(map[string]string)
for _, kv := range strings.Split(flag, ";") {
Expand Down

0 comments on commit 024fba8

Please sign in to comment.