protofmt/aligned.go

52 lines
1.3 KiB
Go

package protofmt
import "strings"
import "bytes"
type aligned struct {
source string
left bool
padding bool
}
var (
alignedEquals = leftAligned(" = ")
alignedShortEquals = leftAligned("=")
alignedSpace = leftAligned(" ")
alignedComma = leftAligned(", ")
alignedEmpty = leftAligned("")
alignedSemicolon = notAligned(";")
alignedColon = notAligned(":")
)
func leftAligned(src string) aligned { return aligned{src, true, true} }
func rightAligned(src string) aligned { return aligned{src, false, true} }
func notAligned(src string) aligned { return aligned{src, false, false} }
func (a aligned) preferredWidth() int {
if !a.hasAlignment() {
return 0 // means do not force padding because of this source
}
return len(a.source)
}
func (a aligned) formatted(indentSeparator string, indentLevel, width int) string {
if !a.padding {
// if the source has newlines then make sure the correct indent level is applied
buf := new(bytes.Buffer)
for _, each := range a.source {
buf.WriteRune(each)
if '\n' == each {
buf.WriteString(strings.Repeat(indentSeparator, indentLevel))
}
}
return buf.String()
}
if a.left {
return a.source + strings.Repeat(" ", width-len(a.source))
}
return strings.Repeat(" ", width-len(a.source)) + a.source
}
func (a aligned) hasAlignment() bool { return a.left || a.padding }