feat(undent): add initial implementation of String, Stringf, and Bytes

This commit is contained in:
2020-11-26 02:48:17 +00:00
parent 7228fc7247
commit 6cdaf8a476
10 changed files with 812 additions and 0 deletions

73
undent.go Normal file
View File

@@ -0,0 +1,73 @@
// Package undent removes leading indentation/white-space from strings and byte
// slices.
package undent
import (
"fmt"
"regexp"
)
var matcher = regexp.MustCompile(`(?m)^([ \t]*)(?:\S)`)
// Bytes removes leading indentation/white-space from given byte slice.
func Bytes(b []byte) []byte {
matches := matcher.FindAll(b, -1)
if len(matches) == 0 {
return b
}
index := 0
length := len(matches[0])
for i, s := range matches[1:] {
l := len(s)
if l < length {
index = i + 1
length = l
}
}
if length <= 1 {
return b
}
indent := matches[index][0 : length-1]
return regexp.MustCompile(
`(?m)^`+regexp.QuoteMeta(string(indent)),
).ReplaceAllLiteral(b, []byte{})
}
// String removes leading indentation/white-space from given string.
func String(s string) string {
matches := matcher.FindAllString(s, -1)
if len(matches) == 0 {
return s
}
index := 0
length := len(matches[0])
for i, s := range matches[1:] {
l := len(s)
if l < length {
index = i + 1
length = l
}
}
if length <= 1 {
return s
}
indent := matches[index][0 : length-1]
return regexp.MustCompile(
`(?m)^`+regexp.QuoteMeta(indent),
).ReplaceAllLiteralString(s, "")
}
// Stringf removes leading indentation/white-space from given format string
// before passing format and all additional arguments to fmt.Sprintf, returning
// the result.
func Stringf(format string, a ...interface{}) string {
return fmt.Sprintf(String(format), a...)
}