Skip to content

Commit ce8e781

Browse files
author
Pam Selle
authored
Merge pull request #18823 from minamijoyo/fix-multibyte-trucate
command/hook_ui: Truncate the ID considering multibyte characters
2 parents e9f8f92 + 33e1839 commit ce8e781

2 files changed

Lines changed: 53 additions & 5 deletions

File tree

command/hook_ui.go

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -373,7 +373,10 @@ func dropCR(data []byte) []byte {
373373
}
374374

375375
func truncateId(id string, maxLen int) string {
376-
totalLength := len(id)
376+
// Note that the id may contain multibyte characters.
377+
// We need to truncate it to maxLen characters, not maxLen bytes.
378+
rid := []rune(id)
379+
totalLength := len(rid)
377380
if totalLength <= maxLen {
378381
return id
379382
}
@@ -383,11 +386,11 @@ func truncateId(id string, maxLen int) string {
383386
maxLen = 5
384387
}
385388

386-
dots := "..."
389+
dots := []rune("...")
387390
partLen := maxLen / 2
388391

389392
leftIdx := partLen - 1
390-
leftPart := id[0:leftIdx]
393+
leftPart := rid[0:leftIdx]
391394

392395
rightIdx := totalLength - partLen - 1
393396

@@ -396,7 +399,7 @@ func truncateId(id string, maxLen int) string {
396399
rightIdx -= overlap
397400
}
398401

399-
rightPart := id[rightIdx:]
402+
rightPart := rid[rightIdx:]
400403

401-
return leftPart + dots + rightPart
404+
return string(leftPart) + string(dots) + string(rightPart)
402405
}

command/hook_ui_test.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,6 +252,51 @@ func TestTruncateId(t *testing.T) {
252252
Expected: "Hello world",
253253
MaxLen: 12,
254254
},
255+
{
256+
Input: "あいうえおかきくけこさ",
257+
Expected: "あ...さ",
258+
MaxLen: 3,
259+
},
260+
{
261+
Input: "あいうえおかきくけこさ",
262+
Expected: "あ...さ",
263+
MaxLen: 5,
264+
},
265+
{
266+
Input: "あいうえおかきくけこさ",
267+
Expected: "あい...さ",
268+
MaxLen: 6,
269+
},
270+
{
271+
Input: "あいうえおかきくけこさ",
272+
Expected: "あい...こさ",
273+
MaxLen: 7,
274+
},
275+
{
276+
Input: "あいうえおかきくけこさ",
277+
Expected: "あいう...こさ",
278+
MaxLen: 8,
279+
},
280+
{
281+
Input: "あいうえおかきくけこさ",
282+
Expected: "あいう...けこさ",
283+
MaxLen: 9,
284+
},
285+
{
286+
Input: "あいうえおかきくけこさ",
287+
Expected: "あいうえ...けこさ",
288+
MaxLen: 10,
289+
},
290+
{
291+
Input: "あいうえおかきくけこさ",
292+
Expected: "あいうえおかきくけこさ",
293+
MaxLen: 11,
294+
},
295+
{
296+
Input: "あいうえおかきくけこさ",
297+
Expected: "あいうえおかきくけこさ",
298+
MaxLen: 12,
299+
},
255300
}
256301
for i, tc := range testCases {
257302
testName := fmt.Sprintf("%d", i)

0 commit comments

Comments
 (0)