Skip to content

Commit

Permalink
fix(ansi): update truncateLeft description, fix edge case (#328)
Browse files Browse the repository at this point in the history
  • Loading branch information
pranavkrishnan02 authored Jan 15, 2025
1 parent 94a44a5 commit 5a7fd32
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
18 changes: 9 additions & 9 deletions ansi/truncate.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,13 +122,13 @@ func Truncate(s string, length int, tail string) string {
return buf.String()
}

// TruncateLeft truncates a string from the left side to a given length, adding
// a prefix to the beginning if the string is longer than the given length.
// TruncateLeft truncates a string from the left side by removing n characters,
// adding a prefix to the beginning if the string is longer than n.
// This function is aware of ANSI escape codes and will not break them, and
// accounts for wide-characters (such as East-Asian characters and emojis).
func TruncateLeft(s string, length int, prefix string) string {
if length == 0 {
return ""
func TruncateLeft(s string, n int, prefix string) string {
if n <= 0 {
return s
}

var cluster []byte
Expand All @@ -153,7 +153,7 @@ func TruncateLeft(s string, length int, prefix string) string {
i += len(cluster)
curWidth += width

if curWidth > length && ignoring {
if curWidth > n && ignoring {
ignoring = false
buf.WriteString(prefix)
}
Expand All @@ -162,7 +162,7 @@ func TruncateLeft(s string, length int, prefix string) string {
continue
}

if curWidth > length {
if curWidth > n {
buf.Write(cluster)
}

Expand All @@ -174,7 +174,7 @@ func TruncateLeft(s string, length int, prefix string) string {
case parser.PrintAction:
curWidth++

if curWidth > length && ignoring {
if curWidth > n && ignoring {
ignoring = false
buf.WriteString(prefix)
}
Expand All @@ -191,7 +191,7 @@ func TruncateLeft(s string, length int, prefix string) string {
}

pstate = state
if curWidth > length && ignoring {
if curWidth > n && ignoring {
ignoring = false
buf.WriteString(prefix)
}
Expand Down
8 changes: 8 additions & 0 deletions ansi/truncate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,14 @@ var tcases = []struct {
"",
"",
},
{
"truncate_length_0",
"foo",
"",
0,
"",
"foo",
},
{
"equalascii",
"one",
Expand Down

0 comments on commit 5a7fd32

Please sign in to comment.