Skip to content

Commit 5a6fce1

Browse files
authored
fix: truncate table output by rune
1 parent 4102a04 commit 5a6fce1

2 files changed

Lines changed: 18 additions & 3 deletions

File tree

cmd/wacli/helpers.go

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,13 +38,17 @@ func sanitize(s string) string {
3838

3939
func truncate(s string, max int) string {
4040
s = sanitize(s)
41-
if max <= 0 || len(s) <= max {
41+
if max <= 0 {
42+
return s
43+
}
44+
runes := []rune(s)
45+
if len(runes) <= max {
4246
return s
4347
}
4448
if max <= 1 {
45-
return s[:max]
49+
return string(runes[:max])
4650
}
47-
return s[:max-1] + "…"
51+
return string(runes[:max-1]) + "…"
4852
}
4953

5054
func fullTableOutput(forceFull bool) bool {

cmd/wacli/messages_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import (
99
"strings"
1010
"testing"
1111
"time"
12+
"unicode/utf8"
1213

1314
"github.com/spf13/cobra"
1415
"github.com/steipete/wacli/internal/store"
@@ -35,6 +36,16 @@ func TestTruncate(t *testing.T) {
3536
}
3637
}
3738

39+
func TestTruncatePreservesUTF8(t *testing.T) {
40+
got := truncate("🙂🙂🙂", 2)
41+
if got != "🙂…" {
42+
t.Fatalf("truncate emoji = %q, want first rune plus ellipsis", got)
43+
}
44+
if !utf8.ValidString(got) {
45+
t.Fatalf("truncate produced invalid UTF-8: %q", got)
46+
}
47+
}
48+
3849
func TestTruncateForDisplay(t *testing.T) {
3950
const longID = "3EB0B0E8A1B2C3D4E5F6A7B8C9D0"
4051
if got := tableCell(longID, 14, true); got != longID {

0 commit comments

Comments
 (0)