1
1
mirror of https://github.com/wader/fq.git synced 2024-11-30 18:08:16 +03:00

Merge pull request #285 from wader/toyaml-toml

interp: Improve type normalization and use it for toyaml and totoml
This commit is contained in:
Mattias Wadman 2022-05-28 20:58:20 +02:00 committed by GitHub
commit fd02df7efc
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 23 additions and 2 deletions

View File

@ -137,14 +137,33 @@ func ToGoJQValue(v any) (any, bool) {
case int: case int:
return vv, true return vv, true
case int64: case int64:
if vv >= math.MinInt && vv <= math.MaxInt {
return int(vv), true
}
return big.NewInt(vv), true return big.NewInt(vv), true
case uint64: case uint64:
if vv <= math.MaxInt {
return int(vv), true
}
return new(big.Int).SetUint64(vv), true return new(big.Int).SetUint64(vv), true
case float32: case float32:
return float64(vv), true return float64(vv), true
case float64: case float64:
return vv, true return vv, true
case *big.Int: case *big.Int:
if vv.IsInt64() {
vv := vv.Int64()
if vv >= math.MinInt && vv <= math.MaxInt {
return int(vv), true
}
return vv, true
} else if vv.IsUint64() {
vv := vv.Uint64()
if vv <= math.MaxInt {
return int(vv), true
}
return vv, true
}
return vv, true return vv, true
case string: case string:
return vv, true return vv, true

View File

@ -717,7 +717,7 @@ func init() {
}) })
addFunc("_toyaml", func(c any) any { addFunc("_toyaml", func(c any) any {
b, err := yaml.Marshal(c) b, err := yaml.Marshal(norm(c))
if err != nil { if err != nil {
return err return err
} }
@ -734,7 +734,7 @@ func init() {
addFunc("_totoml", func(c map[string]any) any { addFunc("_totoml", func(c map[string]any) any {
b := &bytes.Buffer{} b := &bytes.Buffer{}
if err := toml.NewEncoder(b).Encode(c); err != nil { if err := toml.NewEncoder(b).Encode(norm(c)); err != nil {
return err return err
} }
return b.String() return b.String()

View File

@ -1,4 +1,5 @@
# toml does not support null in arrays # toml does not support null in arrays
# TODO: add uint64 norm test
$ fq -rRs 'fromjson[] | (walk(if type == "array" then map(select(. != null)) end) | try (totoml | ., fromtoml) catch .), "----"' variants.json $ fq -rRs 'fromjson[] | (walk(if type == "array" then map(select(. != null)) end) | try (totoml | ., fromtoml) catch .), "----"' variants.json
{} {}

View File

@ -1,3 +1,4 @@
# TODO: add uint64 norm test
$ fq -rRs 'fromjson[] | (try (toyaml | ., fromyaml) catch .), "----"' variants.json $ fq -rRs 'fromjson[] | (try (toyaml | ., fromyaml) catch .), "----"' variants.json
null null