github.com/opentofu/opentofu@v1.7.1/internal/command/metadata_functions.go (about) 1 // Copyright (c) The OpenTofu Authors 2 // SPDX-License-Identifier: MPL-2.0 3 // Copyright (c) 2023 HashiCorp, Inc. 4 // SPDX-License-Identifier: MPL-2.0 5 6 package command 7 8 import ( 9 "fmt" 10 11 "github.com/zclconf/go-cty/cty/function" 12 13 "github.com/opentofu/opentofu/internal/command/jsonfunction" 14 "github.com/opentofu/opentofu/internal/lang" 15 ) 16 17 var ( 18 ignoredFunctions = []string{"map", "list"} 19 ) 20 21 // MetadataFunctionsCommand is a Command implementation that prints out information 22 // about the available functions in OpenTofu. 23 type MetadataFunctionsCommand struct { 24 Meta 25 } 26 27 func (c *MetadataFunctionsCommand) Help() string { 28 return metadataFunctionsCommandHelp 29 } 30 31 func (c *MetadataFunctionsCommand) Synopsis() string { 32 return "Show signatures and descriptions for the available functions" 33 } 34 35 func (c *MetadataFunctionsCommand) Run(args []string) int { 36 args = c.Meta.process(args) 37 cmdFlags := c.Meta.defaultFlagSet("metadata functions") 38 var jsonOutput bool 39 cmdFlags.BoolVar(&jsonOutput, "json", false, "produce JSON output") 40 41 cmdFlags.Usage = func() { c.Ui.Error(c.Help()) } 42 if err := cmdFlags.Parse(args); err != nil { 43 c.Ui.Error(fmt.Sprintf("Error parsing command-line flags: %s\n", err.Error())) 44 return 1 45 } 46 47 if !jsonOutput { 48 c.Ui.Error( 49 "The `tofu metadata functions` command requires the `-json` flag.\n") 50 cmdFlags.Usage() 51 return 1 52 } 53 54 scope := &lang.Scope{} 55 funcs := scope.Functions() 56 filteredFuncs := make(map[string]function.Function) 57 for k, v := range funcs { 58 if isIgnoredFunction(k) { 59 continue 60 } 61 filteredFuncs[k] = v 62 } 63 64 jsonFunctions, marshalDiags := jsonfunction.Marshal(filteredFuncs) 65 if marshalDiags.HasErrors() { 66 c.showDiagnostics(marshalDiags) 67 return 1 68 } 69 c.Ui.Output(string(jsonFunctions)) 70 71 return 0 72 } 73 74 const metadataFunctionsCommandHelp = ` 75 Usage: tofu [global options] metadata functions -json 76 77 Prints out a json representation of the available function signatures. 78 ` 79 80 func isIgnoredFunction(name string) bool { 81 for _, i := range ignoredFunctions { 82 if i == name || lang.CoreNamespace+i == name { 83 return true 84 } 85 } 86 return false 87 }