Skip to content

Commit

Permalink
Support multibyte for truncate string functions (argoproj#5055)
Browse files Browse the repository at this point in the history
Signed-off-by: kenchan0130 <[email protected]>
  • Loading branch information
kenchan0130 authored Dec 14, 2020
1 parent e1990fa commit fba23d9
Show file tree
Hide file tree
Showing 3 changed files with 10 additions and 5 deletions.
5 changes: 3 additions & 2 deletions cmd/argocd/commands/app.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import (
"strings"
"text/tabwriter"
"time"
"unicode/utf8"

"github.com/argoproj/gitops-engine/pkg/diff"
"github.com/argoproj/gitops-engine/pkg/health"
Expand Down Expand Up @@ -430,11 +431,11 @@ func appURL(acdClient argocdclient.Client, appName string) string {

func truncateString(str string, num int) string {
bnoden := str
if len(str) > num {
if utf8.RuneCountInString(str) > num {
if num > 3 {
num -= 3
}
bnoden = str[0:num] + "..."
bnoden = string([]rune(str)[0:num]) + "..."
}
return bnoden
}
Expand Down
9 changes: 6 additions & 3 deletions util/text/text.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
package text

import "strings"
import (
"strings"
"unicode/utf8"
)

// truncates messages to n characters
func Trunc(message string, n int) string {
if len(message) > n {
return message[0:n-3] + "..."
if utf8.RuneCountInString(message) > n {
return string([]rune(message)[0:n-3]) + "..."
}
return message
}
Expand Down
1 change: 1 addition & 0 deletions util/text/text_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ func TestTrunc(t *testing.T) {
{"Empty", args{}, ""},
{"5", args{message: "xxxxx", n: 5}, "xxxxx"},
{"4", args{message: "xxxxx", n: 4}, "x..."},
{"Multibyte", args{message: "こんにちは, world", n: 8}, "こんにちは..."},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
Expand Down

0 comments on commit fba23d9

Please sign in to comment.