Skip to content

Commit

Permalink
schemahcl: add helper/debug print function (#1834)
Browse files Browse the repository at this point in the history
  • Loading branch information
a8m authored Jul 8, 2023
1 parent f195755 commit 769f527
Show file tree
Hide file tree
Showing 2 changed files with 58 additions and 0 deletions.
23 changes: 23 additions & 0 deletions schemahcl/stdlib.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package schemahcl

import (
"fmt"
"net/url"
"strconv"

Expand All @@ -14,6 +15,7 @@ import (
"github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty/function"
"github.com/zclconf/go-cty/cty/function/stdlib"
"github.com/zclconf/go-cty/cty/json"
)

func stdTypes(ctx *hcl.EvalContext) *hcl.EvalContext {
Expand Down Expand Up @@ -128,6 +130,7 @@ func stdFuncs() map[string]function.Function {
"min": stdlib.MinFunc,
"parseint": stdlib.ParseIntFunc,
"pow": stdlib.PowFunc,
"print": printFunc,
"range": stdlib.RangeFunc,
"regex": stdlib.RegexFunc,
"regexall": stdlib.RegexAllFunc,
Expand Down Expand Up @@ -306,3 +309,23 @@ var urlEscape = function.New(&function.Spec{
return cty.StringVal(u), nil
},
})

var printFunc = function.New(&function.Spec{
Params: []function.Parameter{
{
Name: "print",
Type: cty.DynamicPseudoType,
},
},
Type: func(args []cty.Value) (cty.Type, error) {
return args[0].Type(), nil
},
Impl: func(args []cty.Value, retType cty.Type) (cty.Value, error) {
if b, err := json.Marshal(args[0], args[0].Type()); err != nil {
fmt.Println(args[0].GoString())
} else {
fmt.Println(string(b))
}
return args[0], nil
},
})
35 changes: 35 additions & 0 deletions schemahcl/stdlib_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,3 +108,38 @@ func TestURLEscapeFunc(t *testing.T) {
})
}
}

func Example_PrintFunc() {
for _, f := range []string{
`v = print(1)`,
`v = print(true)`,
`v = print("hello, world")`,
`v = print({"hello": "world"})`,
`v = print(["hello", "world"])`,
} {
var d struct {
V cty.Value `spec:"v"`
}
if err := New().EvalBytes([]byte(f), &d, nil); err != nil {
fmt.Println("failed to evaluate:", err)
return
}
fmt.Printf("%#v\n\n", d.V)
}
// Output:
// 1
// cty.NumberIntVal(1)
//
// true
// cty.True
//
// "hello, world"
// cty.StringVal("hello, world")
//
// {"hello":"world"}
// cty.ObjectVal(map[string]cty.Value{"hello":cty.StringVal("world")})
//
// ["hello","world"]
// cty.ListVal([]cty.Value{cty.StringVal("hello"), cty.StringVal("world")})
//
}

0 comments on commit 769f527

Please sign in to comment.