Skip to content

Commit

Permalink
utils/cobrautil/templates: new value type search algorithm
Browse files Browse the repository at this point in the history
This patch replaces regexp with manual searching for matching bracket.
The regexp implementation is not aware of the brackets semantics and matches the last closing bracket preventing the use of <> and [] later in usage.
The current implementation finds the value type definition until the first upper case letter.
  • Loading branch information
mmatczuk committed Aug 1, 2023
1 parent 7024b2c commit 4764ca0
Showing 1 changed file with 54 additions and 6 deletions.
60 changes: 54 additions & 6 deletions utils/cobrautil/templates/help_flags_printer.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ import (
"bytes"
"fmt"
"io"
"regexp"
"strings"
"unicode"

"github.com/mitchellh/go-wordwrap"
flag "github.com/spf13/pflag"
Expand Down Expand Up @@ -95,13 +95,12 @@ func writeFlag(out io.Writer, f *flag.Flag, envPrefix string) {
fmt.Fprintf(out, getFlagFormat(f), f.Shorthand, f.Name, name, def, env, usage, deprecated)
}

var valueTypeRegex = regexp.MustCompile(`^[<|\[].+[>|\]]`)

func flagNameAndUsage(f *flag.Flag) (string, string) {
name, usage := flag.UnquoteUsage(f)
if vt := valueTypeRegex.FindString(usage); vt != "" {
name = vt
usage = strings.TrimSpace(usage[len(vt):])

if vt := findValueType(usage); vt > 0 {
name = usage[:vt]
usage = strings.TrimSpace(usage[vt:])
} else {
if name == "" || name == "string" {
name = "value"
Expand All @@ -115,6 +114,55 @@ func flagNameAndUsage(f *flag.Flag) (string, string) {
return name, usage
}

func findValueType(usage string) int {
runes := []rune(usage)
if len(runes) == 0 {
return 0
}

var (
a, b rune
stack int
)
update := func(r rune) {
switch r {
case '<':
a, b = '<', '>'
stack = 1
case '[':
a, b = '[', ']'
stack = 1
}
}
update(runes[0])

if stack == 0 {
return 0
}

for i := 1; i < len(runes); i++ {
if stack == 0 {
if unicode.IsUpper(runes[i]) {
return i
}
update(runes[i])
} else {
switch runes[i] {
case a:
stack++
case b:
stack--
}
}
}

if stack > 0 {
panic("unbalanced brackets in usage string")
}

return len(runes)
}

var envReplacer = strings.NewReplacer(".", "_", "-", "_")

func envName(envPrefix, flagName string) string {
Expand Down

0 comments on commit 4764ca0

Please sign in to comment.