From 68aafb6a53d8812bf8bebc19dd003088179bbb9d Mon Sep 17 00:00:00 2001 From: Mike Farah Date: Sun, 16 Jun 2024 11:05:27 +1000 Subject: [PATCH] Handle numbers with underscores #2039 --- pkg/yqlib/lib.go | 6 +++++- pkg/yqlib/lib_test.go | 16 +++++++++++++++- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/pkg/yqlib/lib.go b/pkg/yqlib/lib.go index ad4aa38f..d0c81cbc 100644 --- a/pkg/yqlib/lib.go +++ b/pkg/yqlib/lib.go @@ -135,8 +135,12 @@ func recursiveNodeEqual(lhs *CandidateNode, rhs *CandidateNode) bool { return false } -// yaml numbers can be hex and octal encoded... +// yaml numbers can have underscores, be hex and octal encoded... func parseInt64(numberString string) (string, int64, error) { + if strings.Contains(numberString, "_") { + numberString = strings.ReplaceAll(numberString, "_", "") + } + if strings.HasPrefix(numberString, "0x") || strings.HasPrefix(numberString, "0X") { num, err := strconv.ParseInt(numberString[2:], 16, 64) diff --git a/pkg/yqlib/lib_test.go b/pkg/yqlib/lib_test.go index ecd541a7..d87980e7 100644 --- a/pkg/yqlib/lib_test.go +++ b/pkg/yqlib/lib_test.go @@ -106,6 +106,7 @@ func TestParseSnippet(t *testing.T) { type parseInt64Scenario struct { numberString string expectedParsedNumber int64 + expectedFormatString string } var parseInt64Scenarios = []parseInt64Scenario{ @@ -113,10 +114,20 @@ var parseInt64Scenarios = []parseInt64Scenario{ numberString: "34", expectedParsedNumber: 34, }, + { + numberString: "10_000", + expectedParsedNumber: 10000, + expectedFormatString: "10000", + }, { numberString: "0x10", expectedParsedNumber: 16, }, + { + numberString: "0x10_000", + expectedParsedNumber: 65536, + expectedFormatString: "0x10000", + }, { numberString: "0o10", expectedParsedNumber: 8, @@ -132,7 +143,10 @@ func TestParseInt64(t *testing.T) { t.Error(err) } test.AssertResultComplexWithContext(t, tt.expectedParsedNumber, actualNumber, tt.numberString) + if tt.expectedFormatString == "" { + tt.expectedFormatString = tt.numberString + } - test.AssertResultComplexWithContext(t, tt.numberString, fmt.Sprintf(format, actualNumber), fmt.Sprintf("Formatting of: %v", tt.numberString)) + test.AssertResultComplexWithContext(t, tt.expectedFormatString, fmt.Sprintf(format, actualNumber), fmt.Sprintf("Formatting of: %v", tt.numberString)) } }