chromedp/cmd/chromedp-gen/templates/util.go

78 lines
1.6 KiB
Go
Raw Normal View History

// Package templates contains the valyala/quicktemplate based code generation
// templates used by chromedp-gen.
2017-01-24 15:09:23 +00:00
package templates
import (
"strings"
2017-09-28 08:41:05 +00:00
"unicode"
2017-01-24 15:09:23 +00:00
2017-01-26 07:28:34 +00:00
"github.com/knq/chromedp/cmd/chromedp-gen/internal"
2017-09-28 08:41:05 +00:00
"github.com/knq/snaker"
2017-01-24 15:09:23 +00:00
)
const (
commentWidth = 80
commentPrefix = `// `
)
2017-09-28 08:41:05 +00:00
var toUpper = map[string]bool{
"DOM": true,
"X": true,
"Y": true,
}
var keep = map[string]bool{
"JavaScript": true,
}
2017-01-24 15:09:23 +00:00
// formatComment formats a comment.
2017-01-26 07:28:34 +00:00
func formatComment(s, chop, newstr string) string {
2017-01-24 15:09:23 +00:00
s = strings.TrimPrefix(s, chop)
s = strings.TrimSpace(internal.CleanDesc(s))
2017-01-24 15:09:23 +00:00
2017-01-26 07:28:34 +00:00
l := len(s)
if newstr != "" && l > 0 {
2017-09-28 08:41:05 +00:00
if i := strings.IndexFunc(s, unicode.IsSpace); i != -1 {
firstWord, remaining := s[:i], s[i:]
if snaker.IsInitialism(firstWord) || toUpper[firstWord] {
s = strings.ToUpper(firstWord)
} else if keep[firstWord] {
s = firstWord
} else {
s = strings.ToLower(firstWord[:1]) + firstWord[1:]
}
s += remaining
}
2017-01-24 15:09:23 +00:00
}
2017-01-26 07:28:34 +00:00
s = newstr + strings.TrimSuffix(s, ".")
if l < 1 {
s += "[no description]"
}
s += "."
2017-01-24 15:09:23 +00:00
return wrap(s, commentWidth-len(commentPrefix), commentPrefix)
}
// wrap wraps a line of text to the specified width, and adding the prefix to
// each wrapped line.
func wrap(s string, width int, prefix string) string {
words := strings.Fields(strings.TrimSpace(s))
if len(words) == 0 {
return s
}
wrapped := prefix + words[0]
spaceLeft := width - len(wrapped)
for _, word := range words[1:] {
if len(word)+1 > spaceLeft {
wrapped += "\n" + prefix + word
spaceLeft = width - len(word)
} else {
wrapped += " " + word
spaceLeft -= 1 + len(word)
}
}
return wrapped
}