From e1d727de9f970263fd0b37ddad758be7fe173a2e Mon Sep 17 00:00:00 2001 From: palytoxin Date: Tue, 11 May 2021 15:36:42 +0800 Subject: [PATCH] fix utf8 string truncate. --- modules/base/tool.go | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/modules/base/tool.go b/modules/base/tool.go index 157bd9bc3..ebbff8671 100644 --- a/modules/base/tool.go +++ b/modules/base/tool.go @@ -21,6 +21,7 @@ import ( "strings" "time" "unicode" + "unicode/utf8" "code.gitea.io/gitea/modules/git" "code.gitea.io/gitea/modules/log" @@ -284,22 +285,22 @@ func Subtract(left interface{}, right interface{}) interface{} { // EllipsisString returns a truncated short string, // it appends '...' in the end of the length of string is too large. func EllipsisString(str string, length int) string { - if length <= 3 { + if utf8.RuneCountInString(str) <= 3 { return "..." } - if len(str) <= length { + if utf8.RuneCountInString(str) <= length { return str } - return str[:length-3] + "..." + return string([]rune(str)[:length-3]) + "..." } // TruncateString returns a truncated string with given limit, // it returns input string if length is not reached limit. func TruncateString(str string, limit int) string { - if len(str) < limit { + if utf8.RuneCountInString(str) < limit { return str } - return str[:limit] + return string([]rune(str)[:limit]) } // StringsToInt64s converts a slice of string to a slice of int64.