diff options
author | Michael Muré <batolettre@gmail.com> | 2018-12-01 15:15:57 +0100 |
---|---|---|
committer | Michael Muré <batolettre@gmail.com> | 2018-12-01 15:17:16 +0100 |
commit | 5e7448912618b6199310f0974118633aadbc3ccb (patch) | |
tree | 1c52c5a8418430be69d80f00d01205669871a0c0 /util/text/left_padded.go | |
parent | 5653ae98e0a7ac4396ac4e840f88ccf7ccdf7d7f (diff) | |
download | git-bug-5e7448912618b6199310f0974118633aadbc3ccb.tar.gz |
text: fix broken truncate with unicode and use the ellipsis character in LeftPadMaxLine
Diffstat (limited to 'util/text/left_padded.go')
-rw-r--r-- | util/text/left_padded.go | 25 |
1 files changed, 15 insertions, 10 deletions
diff --git a/util/text/left_padded.go b/util/text/left_padded.go index 78d772d5..729834db 100644 --- a/util/text/left_padded.go +++ b/util/text/left_padded.go @@ -2,22 +2,27 @@ package text import ( "bytes" + "fmt" "strings" - "unicode/utf8" ) // LeftPadMaxLine pads a string on the left by a specified amount and pads the string on the right to fill the maxLength -func LeftPadMaxLine(value string, maxValueLength, leftPad int) string { - valueLength := utf8.RuneCountInString(value) - if maxValueLength-leftPad >= valueLength { - return strings.Repeat(" ", leftPad) + value + strings.Repeat(" ", maxValueLength-valueLength-leftPad) - } else if maxValueLength-leftPad < valueLength { - tmp := strings.Trim(value[0:maxValueLength-leftPad-3], " ") + "..." - tmpLength := utf8.RuneCountInString(tmp) - return strings.Repeat(" ", leftPad) + tmp + strings.Repeat(" ", maxValueLength-tmpLength-leftPad) +func LeftPadMaxLine(text string, length, leftPad int) string { + runes := []rune(text) + + // truncate and ellipse if needed + if len(runes)+leftPad > length { + runes = append(runes[:(length-leftPad-1)], '…') + } + + if len(runes)+leftPad < length { + runes = append(runes, []rune(strings.Repeat(" ", length-len(runes)-leftPad))...) } - return value + return fmt.Sprintf("%s%s", + strings.Repeat(" ", leftPad), + string(runes), + ) } // LeftPad left pad each line of the given text |