Skip to content

Commit

Permalink
feat(ansi): cut (#319)
Browse files Browse the repository at this point in the history
Signed-off-by: Carlos Alexandro Becker <caarlos0@users.noreply.github.com>
  • Loading branch information
caarlos0 authored Jan 7, 2025
1 parent e89a5e6 commit 356f65f
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
11 changes: 11 additions & 0 deletions ansi/truncate.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ import (
"github.com/rivo/uniseg"
)

// Cut the string, without adding any prefix or tail strings.
// This function is aware of ANSI escape codes and will not break them, and
// accounts for wide-characters (such as East Asians and emojis).
// Note that the [left] parameter is inclusive, while [right] isn't.
func Cut(s string, left, right int) string {
if left == 0 {
return Truncate(s, right, "")
}
return TruncateLeft(Truncate(s, right, ""), left, "")
}

// Truncate truncates a string to a given length, adding a tail to the
// end if the string is longer than the given length.
// This function is aware of ANSI escape codes and will not break them, and
Expand Down
26 changes: 26 additions & 0 deletions ansi/truncate_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -300,3 +300,29 @@ func TestTruncateLeft(t *testing.T) {
})
}
}

func TestCut(t *testing.T) {
t.Run("simple string", func(t *testing.T) {
got := Cut("This is a long string", 2, 6)
expect := "is i"
if got != expect {
t.Errorf("exptected %q, got %q", expect, got)
}
})

t.Run("with ansi", func(t *testing.T) {
got := Cut("I really \x1B[38;2;249;38;114mlove\x1B[0m Go!", 4, 25)
expect := "ally \x1b[38;2;249;38;114mlove\x1b[0m Go!"
if got != expect {
t.Errorf("exptected %q, got %q", expect, got)
}
})

t.Run("left is 0", func(t *testing.T) {
got := Cut("Foo \x1B[38;2;249;38;114mbar\x1B[0mbaz", 0, 5)
expect := "Foo \x1B[38;2;249;38;114mb\x1B[0m"
if got != expect {
t.Errorf("exptected %q, got %q", expect, got)
}
})
}

0 comments on commit 356f65f

Please sign in to comment.