1
0
mirror of https://github.com/danog/gojekyll.git synced 2025-01-23 05:11:31 +01:00
gojekyll/utils/strings.go

60 lines
1.4 KiB
Go
Raw Normal View History

2017-07-09 16:17:20 -04:00
package utils
import (
2017-06-15 10:17:21 -04:00
"regexp"
2017-07-14 11:30:39 -04:00
"strings"
)
2017-06-15 07:19:49 -04:00
// LeftPad left-pads s with spaces to n wide. It's an alternative to http://left-pad.io.
2017-06-13 17:19:05 -04:00
func LeftPad(s string, n int) string {
2017-06-11 16:00:03 -04:00
if n <= len(s) {
return s
}
ws := make([]byte, n-len(s))
for i := range ws {
ws[i] = ' '
}
return string(ws) + s
}
2017-07-03 09:37:14 -04:00
type replaceStringFuncError error
// SafeReplaceAllStringFunc is like regexp.ReplaceAllStringFunc but passes an
// an error back from the replacement function.
func SafeReplaceAllStringFunc(re *regexp.Regexp, src string, repl func(m string) (string, error)) (out string, err error) {
// The ReplaceAllStringFunc callback signals errors via panic.
// Turn them into return values.
defer func() {
if r := recover(); r != nil {
if e, ok := r.(replaceStringFuncError); ok {
err = e.(error)
} else {
panic(r)
}
}
}()
return re.ReplaceAllStringFunc(src, func(m string) string {
out, err := repl(m)
if err != nil {
panic(replaceStringFuncError(err))
}
return out
}), nil
}
var nonAlphanumericSequenceMatcher = regexp.MustCompile(`[^[:alnum:]]+`)
// Slugify replaces each sequence of non-alphanumerics by a single hyphen
func Slugify(s string) string {
2017-07-14 11:30:39 -04:00
return strings.ToLower(nonAlphanumericSequenceMatcher.ReplaceAllString(s, "-"))
2017-07-03 09:37:14 -04:00
}
2017-06-16 19:17:22 -04:00
// StringArrayToMap creates a map for use as a set.
2017-07-14 11:30:39 -04:00
func StringArrayToMap(a []string) map[string]bool {
stringMap := map[string]bool{}
2017-07-14 11:30:39 -04:00
for _, s := range a {
stringMap[s] = true
}
return stringMap
}