fix: truncate table output by rune

This commit is contained in:
Dinakar Sarbada 2026-05-07 18:11:39 -07:00 committed by GitHub
parent 4102a04e38
commit 5a6fce1e41
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 18 additions and 3 deletions

View File

@ -38,13 +38,17 @@ func sanitize(s string) string {
func truncate(s string, max int) string {
s = sanitize(s)
if max <= 0 || len(s) <= max {
if max <= 0 {
return s
}
runes := []rune(s)
if len(runes) <= max {
return s
}
if max <= 1 {
return s[:max]
return string(runes[:max])
}
return s[:max-1] + "…"
return string(runes[:max-1]) + "…"
}
func fullTableOutput(forceFull bool) bool {

View File

@ -9,6 +9,7 @@ import (
"strings"
"testing"
"time"
"unicode/utf8"
"github.com/spf13/cobra"
"github.com/steipete/wacli/internal/store"
@ -35,6 +36,16 @@ func TestTruncate(t *testing.T) {
}
}
func TestTruncatePreservesUTF8(t *testing.T) {
got := truncate("🙂🙂🙂", 2)
if got != "🙂…" {
t.Fatalf("truncate emoji = %q, want first rune plus ellipsis", got)
}
if !utf8.ValidString(got) {
t.Fatalf("truncate produced invalid UTF-8: %q", got)
}
}
func TestTruncateForDisplay(t *testing.T) {
const longID = "3EB0B0E8A1B2C3D4E5F6A7B8C9D0"
if got := tableCell(longID, 14, true); got != longID {