Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

replaced interface with any, fixed staticcheck problems #32

Merged
merged 1 commit into from
Mar 6, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions convert/convert.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"github.com/zclconf/go-cty/cty/gocty"
)

func GoToCtyValue(val interface{}) (cty.Value, error) {
func GoToCtyValue(val any) (cty.Value, error) {
typ, err := gocty.ImpliedType(val)
if err != nil {
return cty.False, err
Expand Down Expand Up @@ -55,6 +55,6 @@ func GoToCtyValue(val interface{}) (cty.Value, error) {
return ctyVal, nil
}

func CtyToGo(val cty.Value, target interface{}) error {
func CtyToGo(val cty.Value, target any) error {
return gocty.FromCtyValue(val, target)
}
4 changes: 2 additions & 2 deletions errors/parser_error.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package errors

import (
"fmt"
"io/ioutil"
"os"
"strings"

"github.com/mitchellh/go-wordwrap"
Expand Down Expand Up @@ -35,7 +35,7 @@ func (p *ParserError) Error() string {

err.WriteString(" " + fmt.Sprintf("%s:%d,%d\n", p.Filename, p.Line, p.Column))
// process the file
file, _ := ioutil.ReadFile(wordwrap.WrapString(p.Filename, 80))
file, _ := os.ReadFile(wordwrap.WrapString(p.Filename, 80))

lines := strings.Split(string(file), "\n")

Expand Down
4 changes: 2 additions & 2 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"github.com/zclconf/go-cty/cty/function/stdlib"
)

func createCtyFunctionFromGoFunc(f interface{}) (function.Function, error) {
func createCtyFunctionFromGoFunc(f any) (function.Function, error) {
// get the parameters
inParams := []function.Parameter{}
var outParam function.TypeFunc
Expand Down Expand Up @@ -287,7 +287,7 @@ func getDefaultFunctions(filePath string) map[string]function.Function {
return cty.StringVal(""), fmt.Errorf("error parsing template: %s", err)
}

tmpl.RegisterHelpers(map[string]interface{}{
tmpl.RegisterHelpers(map[string]any{
"quote": func(in string) string {
return fmt.Sprintf(`"%s"`, in)
},
Expand Down
2 changes: 1 addition & 1 deletion functions_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ func TestCreateFunctionCallsFunction(t *testing.T) {
func TestCreateFunctionHandlesInputParams(t *testing.T) {
type testCase struct {
name string
f interface{}
f any
}

cases := []testCase{
Expand Down
20 changes: 10 additions & 10 deletions lookup/lookup.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,20 @@ const (
)

var (
ErrMalformedIndex = errors.New("Malformed index key")
ErrInvalidIndexUsage = errors.New("Invalid index key usage")
ErrKeyNotFound = errors.New("Unable to find the key")
ErrMalformedIndex = errors.New("malformed index key")
ErrInvalidIndexUsage = errors.New("invalid index key usage")
ErrKeyNotFound = errors.New("unable to find the key")
)

// LookupString performs a lookup into a value, using a string. Same as `Lookup`
// but using a string with the keys separated by `.`
func LookupString(i interface{}, path string, tags []string) (reflect.Value, error) {
func LookupString(i any, path string, tags []string) (reflect.Value, error) {
return Lookup(i, strings.Split(path, SplitToken), tags)
}

// LookupStringI is the same as LookupString, but the path is not case
// sensitive.
func LookupStringI(i interface{}, path string, tags []string) (reflect.Value, error) {
func LookupStringI(i any, path string, tags []string) (reflect.Value, error) {
return LookupI(i, strings.Split(path, SplitToken), tags)
}

Expand All @@ -44,16 +44,16 @@ func LookupStringI(i interface{}, path string, tags []string) (reflect.Value, er
// If one key owns to a slice and an index is not
// specified the rest of the path will be applied to eval value of the
// slice, and the value will be merged into a slice.
func Lookup(i interface{}, path []string, tags []string) (reflect.Value, error) {
func Lookup(i any, path []string, tags []string) (reflect.Value, error) {
return lookup(i, false, path, tags)
}

// LookupI is the same as Lookup, but the path keys are not case sensitive.
func LookupI(i interface{}, path []string, tags []string) (reflect.Value, error) {
func LookupI(i any, path []string, tags []string) (reflect.Value, error) {
return lookup(i, true, path, tags)
}

func SetValueStringI[V int64 | int | string | bool | reflect.Value](i interface{}, v V, path string, tags []string) error {
func SetValueStringI[V int64 | int | string | bool | reflect.Value](i any, v V, path string, tags []string) error {
// First find the variable
dest, err := Lookup(i, strings.Split(path, SplitToken), tags)
if err != nil {
Expand Down Expand Up @@ -86,7 +86,7 @@ func SetValueStringI[V int64 | int | string | bool | reflect.Value](i interface{
return nil
}

func lookup(i interface{}, caseInsensitive bool, path []string, tags []string) (reflect.Value, error) {
func lookup(i any, caseInsensitive bool, path []string, tags []string) (reflect.Value, error) {
value := reflect.ValueOf(i)
var parent reflect.Value
var err error
Expand Down Expand Up @@ -275,7 +275,7 @@ func isMergeable(v reflect.Value) bool {
}

func hasIndex(s string) bool {
return strings.Index(s, IndexOpenChar) != -1
return strings.Contains(s, IndexOpenChar)
}

func parseIndex(s string) (string, int, error) {
Expand Down
8 changes: 4 additions & 4 deletions lookup/lookup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -465,7 +465,7 @@ type MyStruct struct {
Map map[string]int `json:"jsontagmap" hcl:"hcltagmap"`
Nested *MyStruct
StructSlice []*MyStruct
Interface interface{}
Interface any
Slice []string
}

Expand All @@ -485,11 +485,11 @@ var structFixture = MyStruct{

var emptyFixture = structs.Container{}

var mapComplexFixture = map[string]interface{}{
"map": map[string]interface{}{
var mapComplexFixture = map[string]any{
"map": map[string]any{
"bar": 1,
},
"list": []map[string]interface{}{
"list": []map[string]any{
{"baz": 1},
{"baz": 2},
{"baz": 3},
Expand Down
16 changes: 8 additions & 8 deletions parse_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,9 @@ func TestParseResolvesArrayReferences(t *testing.T) {
require.NotNil(t, r)

out = r.(*resources.Output)
require.Equal(t, "10.6.0.200", out.Value.([]interface{})[0].(string))
require.Equal(t, "10.7.0.201", out.Value.([]interface{})[1].(string))
require.Equal(t, float64(12), out.Value.([]interface{})[2].(float64))
require.Equal(t, "10.6.0.200", out.Value.([]any)[0].(string))
require.Equal(t, "10.7.0.201", out.Value.([]any)[1].(string))
require.Equal(t, float64(12), out.Value.([]any)[2].(float64))
}

func TestLoadsVariableFilesInOptionsOverridingVariableDefaults(t *testing.T) {
Expand Down Expand Up @@ -279,14 +279,14 @@ func TestResourceReferencesInExpressionsAreEvaluated(t *testing.T) {
r, err = c.FindResource("output.splat")
require.NoError(t, err)
cont := r.(*resources.Output)
require.Equal(t, "/cache", cont.Value.([]interface{})[0])
require.Equal(t, "/cache2", cont.Value.([]interface{})[1])
require.Equal(t, "/cache", cont.Value.([]any)[0])
require.Equal(t, "/cache2", cont.Value.([]any)[1])

r, err = c.FindResource("output.splat_with_null")
require.NoError(t, err)
cont = r.(*resources.Output)
require.Equal(t, "test1", cont.Value.([]interface{})[0])
require.Equal(t, "test2", cont.Value.([]interface{})[1])
require.Equal(t, "test1", cont.Value.([]any)[0])
require.Equal(t, "test2", cont.Value.([]any)[1])

r, err = c.FindResource("output.function")
require.NoError(t, err)
Expand Down Expand Up @@ -467,7 +467,7 @@ func TestParseModuleCreatesOutputs(t *testing.T) {

// check element can be obtained from a map of values
// returned in the output
meta := cont.(*resources.Output).Value.(map[string]interface{})["meta"].(map[string]interface{})
meta := cont.(*resources.Output).Value.(map[string]any)["meta"].(map[string]any)
require.Equal(t, "base", meta["name"])
}

Expand Down
15 changes: 7 additions & 8 deletions parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ package hclconfig
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
Expand Down Expand Up @@ -116,7 +115,7 @@ func (p *Parser) RegisterType(name string, resource types.Resource) {
// RegisterFunction type registers a custom interpolation function
// with the given name
// the parser uses this list to convert hcl defined resources into concrete types
func (p *Parser) RegisterFunction(name string, f interface{}) error {
func (p *Parser) RegisterFunction(name string, f any) error {
ctyFunc, err := createCtyFunctionFromGoFunc(f)
if err != nil {
return nil
Expand Down Expand Up @@ -243,13 +242,13 @@ func (p *Parser) UnmarshalJSON(d []byte) (*Config, error) {
}

for _, m := range rawMessagesForResources {
mm := map[string]interface{}{}
mm := map[string]any{}
err := json.Unmarshal(*m, &mm)
if err != nil {
return nil, err
}

meta := mm["meta"].(map[string]interface{})
meta := mm["meta"].(map[string]any)

r, err := p.registeredTypes.CreateResource(meta["type"].(string), meta["name"].(string))
if err != nil {
Expand Down Expand Up @@ -278,7 +277,7 @@ func (p *Parser) parseDirectory(ctx *hcl.EvalContext, dir string, c *Config) []e
return []error{fmt.Errorf("%s is not a directory", dir)}
}

files, err := ioutil.ReadDir(dir)
files, err := os.ReadDir(dir)
if err != nil {
return []error{fmt.Errorf("unable to list files in directory %s, error: %s", dir, err)}
}
Expand Down Expand Up @@ -891,7 +890,7 @@ func (p *Parser) parseResource(ctx *hcl.EvalContext, c *Config, file string, b *
Meta: types.Meta{
Name: name,
Type: b.Labels[0],
Properties: map[string]interface{}{},
Properties: map[string]any{},
},
}

Expand Down Expand Up @@ -1266,7 +1265,7 @@ func buildContext(filePath string, customFunctions map[string]function.Function)
return ctx
}

func decodeBody(ctx *hcl.EvalContext, config *Config, path string, b *hclsyntax.Block, p interface{}, ignoreErrors bool) error {
func decodeBody(ctx *hcl.EvalContext, config *Config, path string, b *hclsyntax.Block, p any, ignoreErrors bool) error {
dr, err := getDependentResources(b, ctx, config, p, "")
if err != nil {
return err
Expand Down Expand Up @@ -1319,7 +1318,7 @@ func decodeBody(ctx *hcl.EvalContext, config *Config, path string, b *hclsyntax.
// i.e. resource.container.foo.network[0].name
// when a link is found it is replaced with an empty value of the correct type and the
// dependent resources are returned to be processed later
func getDependentResources(b *hclsyntax.Block, ctx *hcl.EvalContext, c *Config, resource interface{}, path string) ([]string, error) {
func getDependentResources(b *hclsyntax.Block, ctx *hcl.EvalContext, c *Config, resource any, path string) ([]string, error) {
references := []string{}

for _, a := range b.Body.Attributes {
Expand Down
9 changes: 5 additions & 4 deletions resources/fqrn.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package resources

import (
"errors"
"fmt"
"regexp"
"strings"
Expand Down Expand Up @@ -64,14 +65,14 @@ func ParseFQRN(fqrn string) (*FQRN, error) {
}

if len(results) < 2 {
return nil, fmt.Errorf(formatErrorString(fqrn))
return nil, errors.New(formatErrorString(fqrn))
}

switch results["resource"] {
case "resource":
resourceParts := strings.Split(results["attributes"], ".")
if len(resourceParts) < 2 {
return nil, fmt.Errorf(formatErrorString(fqrn))
return nil, errors.New(formatErrorString(fqrn))
}

typeName = resourceParts[0]
Expand Down Expand Up @@ -107,7 +108,7 @@ func ParseFQRN(fqrn string) (*FQRN, error) {
case "variable":
varParts := strings.Split(results["attributes"], ".")
if len(varParts) != 1 {
return nil, fmt.Errorf(formatErrorString(fqrn))
return nil, errors.New(formatErrorString(fqrn))
}

typeName = TypeVariable
Expand All @@ -116,7 +117,7 @@ func ParseFQRN(fqrn string) (*FQRN, error) {

default:
if results["onlymodules"] == "" || !strings.HasPrefix(results["onlymodules"], "module.") {
return nil, fmt.Errorf(formatErrorString(fqrn))
return nil, errors.New(formatErrorString(fqrn))
}

//module1.module2
Expand Down
4 changes: 2 additions & 2 deletions resources/locals.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,6 @@ const TypeLocal = "local"
type Local struct {
types.ResourceBase `hcl:",remain"`

CtyValue cty.Value `hcl:"value,optional"` // value of the output
Value interface{} `json:"value"`
CtyValue cty.Value `hcl:"value,optional"` // value of the output
Value any `json:"value"`
}
2 changes: 1 addition & 1 deletion resources/module.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type Module struct {
Source string `hcl:"source" json:"source"`
Version string `hcl:"version,optional" json:"version,omitempty"`

Variables interface{} `hcl:"variables,optional" json:"variables,omitempty"`
Variables any `hcl:"variables,optional" json:"variables,omitempty"`

// SubContext is used to store the variables as a context that can be
// passed to child resources
Expand Down
6 changes: 3 additions & 3 deletions resources/output.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const TypeOutput = "output"
type Output struct {
types.ResourceBase `hcl:",remain"`

CtyValue cty.Value `hcl:"value,optional"` // value of the output
Value interface{} `json:"value"`
Description string `hcl:"description,optional" json:"description,omitempty"` // description for the output
CtyValue cty.Value `hcl:"value,optional"` // value of the output
Value any `json:"value"`
Description string `hcl:"description,optional" json:"description,omitempty"` // description for the output
}
4 changes: 2 additions & 2 deletions resources/variable.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ const TypeVariable = "variable"
// Output defines an output variable which can be set by a module
type Variable struct {
types.ResourceBase `hcl:",remain"`
Default interface{} `hcl:"default" json:"default"` // default value for a variable
Description string `hcl:"description,optional" json:"description,omitempty"` // description of the variable
Default any `hcl:"default" json:"default"` // default value for a variable
Description string `hcl:"description,optional" json:"description,omitempty"` // description of the variable
}
9 changes: 5 additions & 4 deletions schematest/example.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,13 @@ import (
"encoding/json"
"fmt"
"reflect"
"strings"

"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/gohcl"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/hashicorp/hcl/v2/hclsyntax"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)

type Schema struct {
Expand Down Expand Up @@ -95,7 +96,7 @@ func createDynamicType(s *Schema) reflect.Type {
t := getType(f.Type)
if t != nil {
field := reflect.StructField{
Name: strings.Title(f.Name),
Name: cases.Title(language.English).String(f.Name),
Type: getType(f.Type),
Tag: reflect.StructTag(fmt.Sprintf(`hcl:"%s,optional"`, f.Name)),
}
Expand Down
10 changes: 5 additions & 5 deletions test_fixtures/structs/template.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ type Template struct {

Depends []string `hcl:"depends_on,optional" json:"depends,omitempty"`

Source string `hcl:"source" json:"source"` // Source template to be processed as string
Destination string `hcl:"destination" json:"destination"` // Destination filename to write
Vars cty.Value `hcl:"vars,optional" json:"vars,omitempty"` // Variables to be processed in the template
InternalVars map[string]interface{} // stores a converted go type version of the hcl.Value types
AppendFile bool `hcl:"append_file,optional" json:"append_file,omitempty"`
Source string `hcl:"source" json:"source"` // Source template to be processed as string
Destination string `hcl:"destination" json:"destination"` // Destination filename to write
Vars cty.Value `hcl:"vars,optional" json:"vars,omitempty"` // Variables to be processed in the template
InternalVars map[string]any // stores a converted go type version of the hcl.Value types
AppendFile bool `hcl:"append_file,optional" json:"append_file,omitempty"`
}

func (t *Template) Process() error {
Expand Down
Loading