Skip to content

Commit

Permalink
Merge pull request #8 from jeffwilliams/main
Browse files Browse the repository at this point in the history
Tolerate leading zeros in numeric color parameters
  • Loading branch information
leaanthony authored Jun 9, 2023
2 parents 518023b + 8ce94ec commit c9c4f7e
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 4 deletions.
18 changes: 14 additions & 4 deletions ansi.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package ansi

import (
"fmt"
"github.com/rivo/uniseg"
"strconv"
"strings"

"github.com/rivo/uniseg"
)

// TextStyle is a type representing the
Expand Down Expand Up @@ -321,6 +322,7 @@ func Parse(input string, options ...ParseOption) ([]*StyledText, error) {
skip--
continue
}
param = stripLeadingZeros(param)
switch param {
case "0", "":
colourMap = ColourMap["Regular"]
Expand Down Expand Up @@ -369,9 +371,10 @@ func Parse(input string, options ...ParseOption) ([]*StyledText, error) {
return nil, invalid
}
// 256 colours
if params[index+1] == "5" {
param1 := stripLeadingZeros(params[index+1])
if param1 == "5" {
skip = 2
colIndexText := params[index+2]
colIndexText := stripLeadingZeros(params[index+2])
colIndex, err := strconv.Atoi(colIndexText)
if err != nil {
return nil, invalid256ColSequence
Expand All @@ -391,7 +394,7 @@ func Parse(input string, options ...ParseOption) ([]*StyledText, error) {
if len(params)-index < 5 {
return nil, invalidTrueColorSequence
}
if params[index+1] != "2" {
if param1 != "2" {
return nil, invalidTrueColorSequence
}
var r, g, b uint8
Expand Down Expand Up @@ -465,6 +468,13 @@ func Parse(input string, options ...ParseOption) ([]*StyledText, error) {
}
}

func stripLeadingZeros(s string) string {
if len(s) < 2 {
return s
}
return strings.TrimLeft(s, "0")
}

// HasEscapeCodes tests that input has escape codes.
func HasEscapeCodes(input string) bool {
return strings.IndexAny(input, "\033[") != -1
Expand Down
22 changes: 22 additions & 0 deletions ansi_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -687,3 +687,25 @@ func TestLength(t *testing.T) {
})
}
}

func TestStripLeadingZeros(t *testing.T) {
is2 := is.New(t)
tests := []struct {
name string
input string
want string
}{
{"Blank", "", ""},
{"One rune not 0", "4", "4"},
{"Only 0", "0", "0"},
{"Multi-digit non-0", "35", "35"},
{"Two-digit leading 0", "05", "5"},
{"Three-digit leading 0", "045", "45"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := stripLeadingZeros(tt.input)
is2.Equal(got, tt.want)
})
}
}

0 comments on commit c9c4f7e

Please # to comment.