opentofu/internal/command/metadata_functions.go
Daniel Banck 4fa77727b5
Introduce metadata functions command (#32487)
* Add metadata functions command skeleton

* Export functions as JSON via cli command

* Add metadata command

* Add tests to jsonfunction package

* WIP: Add metadata functions test

* Change return_type & type in JSON to json.RawMessage

This enables easier deserialisation of types when parsing the JSON.

* Skip is_nullable when false

* Update cli docs with metadata command

* Use tfdiags to report function marshal errors

* Ignore map, list and type functions

* Test Marshal function with diags

* Test metadata functions command output

* Simplify type marshaling by using cty.Type

* Add static function signatures for can and try

* Update internal/command/jsonfunction/function_test.go

Co-authored-by: kmoe <5575356+kmoe@users.noreply.github.com>

---------

Co-authored-by: kmoe <5575356+kmoe@users.noreply.github.com>
2023-02-14 14:08:47 +00:00

82 lines
1.9 KiB
Go

package command
import (
"fmt"
"github.com/hashicorp/terraform/internal/command/jsonfunction"
"github.com/hashicorp/terraform/internal/lang"
"github.com/zclconf/go-cty/cty/function"
)
var (
ignoredFunctions = []string{"map", "list"}
)
// MetadataFunctionsCommand is a Command implementation that prints out information
// about the available functions in Terraform.
type MetadataFunctionsCommand struct {
Meta
}
func (c *MetadataFunctionsCommand) Help() string {
return metadataFunctionsCommandHelp
}
func (c *MetadataFunctionsCommand) Synopsis() string {
return "Show signatures and descriptions for the available functions"
}
func (c *MetadataFunctionsCommand) Run(args []string) int {
args = c.Meta.process(args)
cmdFlags := c.Meta.defaultFlagSet("metadata functions")
var jsonOutput bool
cmdFlags.BoolVar(&jsonOutput, "json", false, "produce JSON output")
cmdFlags.Usage = func() { c.Ui.Error(c.Help()) }
if err := cmdFlags.Parse(args); err != nil {
c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error()))
return 1
}
if !jsonOutput {
c.Ui.Error(
"The `terraform metadata functions` command requires the `-json` flag.\n")
cmdFlags.Usage()
return 1
}
scope := &lang.Scope{}
funcs := scope.Functions()
filteredFuncs := make(map[string]function.Function)
for k, v := range funcs {
if isIgnoredFunction(k) {
continue
}
filteredFuncs[k] = v
}
jsonFunctions, marshalDiags := jsonfunction.Marshal(filteredFuncs)
if marshalDiags.HasErrors() {
c.showDiagnostics(marshalDiags)
return 1
}
c.Ui.Output(string(jsonFunctions))
return 0
}
const metadataFunctionsCommandHelp = `
Usage: terraform [global options] metadata functions -json
Prints out a json representation of the available function signatures.
`
func isIgnoredFunction(name string) bool {
for _, i := range ignoredFunctions {
if i == name {
return true
}
}
return false
}