yq/pkg/yqlib/operator_to_number.go

53 lines
1.3 KiB
Go
Raw Normal View History

2023-10-05 04:13:46 +00:00
package yqlib
import (
"container/list"
"fmt"
"strconv"
)
func tryConvertToNumber(value string) (string, bool) {
2023-11-23 00:54:25 +00:00
// try an int first
2023-10-05 04:13:46 +00:00
_, _, err := parseInt64(value)
if err == nil {
return "!!int", true
}
// try float
_, floatErr := strconv.ParseFloat(value, 64)
if floatErr == nil {
return "!!float", true
}
return "", false
}
2024-01-11 02:17:34 +00:00
func toNumberOperator(_ *dataTreeNavigator, context Context, _ *ExpressionNode) (Context, error) {
2023-10-05 04:13:46 +00:00
log.Debugf("ToNumberOperator")
var results = list.New()
for el := context.MatchingNodes.Front(); el != nil; el = el.Next() {
candidate := el.Value.(*CandidateNode)
if candidate.Kind != ScalarNode {
return Context{}, fmt.Errorf("cannot convert node at path %v of tag %v to number", candidate.GetNicePath(), candidate.Tag)
2023-10-05 04:13:46 +00:00
}
if candidate.Tag == "!!int" || candidate.Tag == "!!float" {
2023-10-05 04:13:46 +00:00
// it already is a number!
results.PushBack(candidate)
} else {
tag, converted := tryConvertToNumber(candidate.Value)
2023-10-05 04:13:46 +00:00
if converted {
result := candidate.CreateReplacement(ScalarNode, tag, candidate.Value)
2023-10-05 04:13:46 +00:00
results.PushBack(result)
} else {
return Context{}, fmt.Errorf("cannot convert node value [%v] at path %v of tag %v to number", candidate.Value, candidate.GetNicePath(), candidate.Tag)
2023-10-05 04:13:46 +00:00
}
}
}
return context.ChildContext(results), nil
}