mirror of
https://github.com/jimeh/undent.git
synced 2026-02-19 03:56:38 +00:00
feat(undent): add initial implementation of String, Stringf, and Bytes
This commit is contained in:
73
undent.go
Normal file
73
undent.go
Normal 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...)
|
||||
}
|
||||
Reference in New Issue
Block a user