Skip to content

Commit c9c4f7e

Browse files
authored
Merge pull request #8 from jeffwilliams/main
Tolerate leading zeros in numeric color parameters
2 parents 518023b + 8ce94ec commit c9c4f7e

File tree

2 files changed

+36
-4
lines changed

2 files changed

+36
-4
lines changed

ansi.go

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,10 @@ package ansi
22

33
import (
44
"fmt"
5-
"github.com/rivo/uniseg"
65
"strconv"
76
"strings"
7+
8+
"github.com/rivo/uniseg"
89
)
910

1011
// TextStyle is a type representing the
@@ -321,6 +322,7 @@ func Parse(input string, options ...ParseOption) ([]*StyledText, error) {
321322
skip--
322323
continue
323324
}
325+
param = stripLeadingZeros(param)
324326
switch param {
325327
case "0", "":
326328
colourMap = ColourMap["Regular"]
@@ -369,9 +371,10 @@ func Parse(input string, options ...ParseOption) ([]*StyledText, error) {
369371
return nil, invalid
370372
}
371373
// 256 colours
372-
if params[index+1] == "5" {
374+
param1 := stripLeadingZeros(params[index+1])
375+
if param1 == "5" {
373376
skip = 2
374-
colIndexText := params[index+2]
377+
colIndexText := stripLeadingZeros(params[index+2])
375378
colIndex, err := strconv.Atoi(colIndexText)
376379
if err != nil {
377380
return nil, invalid256ColSequence
@@ -391,7 +394,7 @@ func Parse(input string, options ...ParseOption) ([]*StyledText, error) {
391394
if len(params)-index < 5 {
392395
return nil, invalidTrueColorSequence
393396
}
394-
if params[index+1] != "2" {
397+
if param1 != "2" {
395398
return nil, invalidTrueColorSequence
396399
}
397400
var r, g, b uint8
@@ -465,6 +468,13 @@ func Parse(input string, options ...ParseOption) ([]*StyledText, error) {
465468
}
466469
}
467470

471+
func stripLeadingZeros(s string) string {
472+
if len(s) < 2 {
473+
return s
474+
}
475+
return strings.TrimLeft(s, "0")
476+
}
477+
468478
// HasEscapeCodes tests that input has escape codes.
469479
func HasEscapeCodes(input string) bool {
470480
return strings.IndexAny(input, "\033[") != -1

ansi_test.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -687,3 +687,25 @@ func TestLength(t *testing.T) {
687687
})
688688
}
689689
}
690+
691+
func TestStripLeadingZeros(t *testing.T) {
692+
is2 := is.New(t)
693+
tests := []struct {
694+
name string
695+
input string
696+
want string
697+
}{
698+
{"Blank", "", ""},
699+
{"One rune not 0", "4", "4"},
700+
{"Only 0", "0", "0"},
701+
{"Multi-digit non-0", "35", "35"},
702+
{"Two-digit leading 0", "05", "5"},
703+
{"Three-digit leading 0", "045", "45"},
704+
}
705+
for _, tt := range tests {
706+
t.Run(tt.name, func(t *testing.T) {
707+
got := stripLeadingZeros(tt.input)
708+
is2.Equal(got, tt.want)
709+
})
710+
}
711+
}

0 commit comments

Comments
 (0)