Skip to content

Commit

Permalink
Handle numbers with underscores #2039
Browse files Browse the repository at this point in the history
  • Loading branch information
mikefarah committed Jun 16, 2024
1 parent d58870b commit 68aafb6
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
6 changes: 5 additions & 1 deletion pkg/yqlib/lib.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
16 changes: 15 additions & 1 deletion pkg/yqlib/lib_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,17 +106,28 @@ func TestParseSnippet(t *testing.T) {
type parseInt64Scenario struct {
numberString string
expectedParsedNumber int64
expectedFormatString string
}

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,
Expand All @@ -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))
}
}

0 comments on commit 68aafb6

Please sign in to comment.