Skip to content

Commit

Permalink
command/hook_ui: Truncate the ID considering multibyte characters
Browse files Browse the repository at this point in the history
Fixes hashicorp#18822

The `tuncatedId` function had been introduced in hashicorp#12261 and increased the
`maxIdLen` to 80 in hashicorp#13317. Since the number of bytes itself seems to be
unimportant, the ID should be truncated to 80 characters, not 80 bytes.
  • Loading branch information
minamijoyo committed Sep 9, 2018
1 parent c886869 commit b0a26da
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 5 deletions.
13 changes: 8 additions & 5 deletions command/hook_ui.go
Original file line number Diff line number Diff line change
Expand Up @@ -385,7 +385,10 @@ func dropCR(data []byte) []byte {
}

func truncateId(id string, maxLen int) string {
totalLength := len(id)
// Note that the id may contain multibyte characters.
// We need to truncate it to maxLen characters, not maxLen bytes.
rid := []rune(id)
totalLength := len(rid)
if totalLength <= maxLen {
return id
}
Expand All @@ -395,11 +398,11 @@ func truncateId(id string, maxLen int) string {
maxLen = 5
}

dots := "..."
dots := []rune("...")
partLen := maxLen / 2

leftIdx := partLen - 1
leftPart := id[0:leftIdx]
leftPart := rid[0:leftIdx]

rightIdx := totalLength - partLen - 1

Expand All @@ -408,7 +411,7 @@ func truncateId(id string, maxLen int) string {
rightIdx -= overlap
}

rightPart := id[rightIdx:]
rightPart := rid[rightIdx:]

return leftPart + dots + rightPart
return string(leftPart) + string(dots) + string(rightPart)
}
45 changes: 45 additions & 0 deletions command/hook_ui_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -238,6 +238,51 @@ func TestTruncateId(t *testing.T) {
Expected: "Hello world",
MaxLen: 12,
},
{
Input: "あいうえおかきくけこさ",
Expected: "あ...さ",
MaxLen: 3,
},
{
Input: "あいうえおかきくけこさ",
Expected: "あ...さ",
MaxLen: 5,
},
{
Input: "あいうえおかきくけこさ",
Expected: "あい...さ",
MaxLen: 6,
},
{
Input: "あいうえおかきくけこさ",
Expected: "あい...こさ",
MaxLen: 7,
},
{
Input: "あいうえおかきくけこさ",
Expected: "あいう...こさ",
MaxLen: 8,
},
{
Input: "あいうえおかきくけこさ",
Expected: "あいう...けこさ",
MaxLen: 9,
},
{
Input: "あいうえおかきくけこさ",
Expected: "あいうえ...けこさ",
MaxLen: 10,
},
{
Input: "あいうえおかきくけこさ",
Expected: "あいうえおかきくけこさ",
MaxLen: 11,
},
{
Input: "あいうえおかきくけこさ",
Expected: "あいうえおかきくけこさ",
MaxLen: 12,
},
}
for i, tc := range testCases {
testName := fmt.Sprintf("%d", i)
Expand Down

0 comments on commit b0a26da

Please sign in to comment.