Skip to content

Commit

Permalink
improved Description(..) and Examples(..)
Browse files Browse the repository at this point in the history
  • Loading branch information
hedzr committed Nov 4, 2024
1 parent 4c7e978 commit 4b55483
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 4 deletions.
37 changes: 34 additions & 3 deletions cli/baseopt.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package cli

import (
"bufio"
"fmt"
"regexp"
"strings"
Expand Down Expand Up @@ -33,12 +34,42 @@ func (c *BaseOpt) SetShorts(shorts ...string) {

func (c *BaseOpt) SetDescription(description string, longDescription ...string) {
c.description = description
var (
lines []string
lead = true
)
for _, str := range longDescription {
c.longDesc = str
if s := strings.Trim(str, "\r\n\t "); s != "" {
lines = append(lines, s)
} else if !lead {
lines = append(lines, s)
} else {
lead = false
lines = append(lines, s)
}
}
end := len(lines) - 1
for i := end; i >= 0; i-- {
if s := strings.Trim(lines[i], "\r\n\t "); s == "" {
end--
}
}
lines = lines[:end+1]
c.longDesc = strings.Join(lines, "\n")
if description == "" && len(c.longDesc) > 0 {
c.description = firstNonBlankLine(c.longDesc)
}
if description == "" && len(longDescription) > 0 {
c.description = longDescription[0]
}

func firstNonBlankLine(desc string) string {
scanner := bufio.NewScanner(strings.NewReader(desc))
for scanner.Scan() {
line := scanner.Text()
if s := strings.Trim(line, "\r\n\t "); s != "" {
return line
}
}
return ""
}

func (c *BaseOpt) SetExamples(examples ...string) {
Expand Down
10 changes: 9 additions & 1 deletion cli/commandbuilder.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,17 @@ type CommandBuilder interface {
// aliases will be used as is.
Titles(longTitle string, titles ...string) CommandBuilder
// Description specifies the one-line description and a multi-line
// description (optional)
// description (optional).
//
// For the longDescription, some tips are:
//
// 1. the extra leading and following blank lines will be stripped.
// 2. the given params will be joint together as a one big multi-line
// string.
Description(description string, longDescription ...string) CommandBuilder
// Examples can be a multi-line string.
//
// Tip: the extra leading and following blank lines will be stripped.
Examples(examples string) CommandBuilder
// Group specify a group name,
// A special prefix could sort it, has a form like `[0-9a-zA-Z]+\.`.
Expand Down

0 comments on commit 4b55483

Please sign in to comment.