From c8e653e2787ef602a0d536f7c4cec717e1cfe60a Mon Sep 17 00:00:00 2001 From: Andrey Nering Date: Thu, 5 Jun 2025 13:38:57 -0300 Subject: [PATCH] fix(diffview): fix left pad for ansi stuff --- internal/exp/diffview/util.go | 7 +++++-- internal/exp/diffview/util_test.go | 27 +++++++++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 internal/exp/diffview/util_test.go diff --git a/internal/exp/diffview/util.go b/internal/exp/diffview/util.go index 6cf260aa9c654a162fd1e41d64e832c2cacb3320..4834cc53377fd345aab8dfa2b7a7d59a674dbab6 100644 --- a/internal/exp/diffview/util.go +++ b/internal/exp/diffview/util.go @@ -3,12 +3,15 @@ package diffview import ( "fmt" "strings" + + "github.com/charmbracelet/x/ansi" ) func pad(v any, width int) string { s := fmt.Sprintf("%v", v) - if len(s) >= width { + w := ansi.StringWidth(s) + if w >= width { return s } - return strings.Repeat(" ", width-len(s)) + s + return strings.Repeat(" ", width-w) + s } diff --git a/internal/exp/diffview/util_test.go b/internal/exp/diffview/util_test.go new file mode 100644 index 0000000000000000000000000000000000000000..3bba5070773a98c99a010722d0019fa48f45db43 --- /dev/null +++ b/internal/exp/diffview/util_test.go @@ -0,0 +1,27 @@ +package diffview + +import ( + "testing" +) + +func TestPad(t *testing.T) { + tests := []struct { + input any + width int + expected string + }{ + {7, 2, " 7"}, + {7, 3, " 7"}, + {"a", 2, " a"}, + {"a", 3, " a"}, + {"…", 2, " …"}, + {"…", 3, " …"}, + } + + for _, tt := range tests { + result := pad(tt.input, tt.width) + if result != tt.expected { + t.Errorf("expected %q, got %q", tt.expected, result) + } + } +}