/
param_def.go
84 lines (74 loc) · 2.41 KB
/
param_def.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
package modconfig
import (
"encoding/json"
"fmt"
"github.com/hashicorp/hcl/v2"
typehelpers "github.com/turbot/go-kit/types"
"github.com/turbot/pipe-fittings/hclhelpers"
"github.com/turbot/pipe-fittings/printers"
)
type ParamDef struct {
ShortName string `cty:"name" json:"name"`
UnqualifiedName string `cty:"full_name" json:"-"`
Description *string `cty:"description" json:"description"`
Default *string `cty:"default" json:"default"`
// tactical - is the raw value a string
IsString bool `cty:"is_string" json:"-"`
// list of all blocks referenced by the resource
References []*ResourceReference `json:"-"`
DeclRange hcl.Range `json:"-"`
}
func NewParamDef(block *hcl.Block) *ParamDef {
return &ParamDef{
ShortName: block.Labels[0],
UnqualifiedName: fmt.Sprintf("param.%s", block.Labels[0]),
DeclRange: hclhelpers.BlockRange(block),
}
}
func (p *ParamDef) String() string {
return fmt.Sprintf("Name: %s, Description: %s, Default: %s", p.UnqualifiedName, typehelpers.SafeString(p.Description), typehelpers.SafeString(p.Default))
}
func (p *ParamDef) Equals(other *ParamDef) bool {
return p.ShortName == other.ShortName &&
typehelpers.SafeString(p.Description) == typehelpers.SafeString(other.Description) &&
typehelpers.SafeString(p.Default) == typehelpers.SafeString(other.Default)
}
// SetDefault sets the default as a atring points, marshalling to json is the underlying value is NOT a string
func (p *ParamDef) SetDefault(value interface{}) error {
strVal, ok := value.(string)
if ok {
p.IsString = true
// no need to convert to string
p.Default = &strVal
return nil
}
// format the arg value as a JSON string
jsonBytes, err := json.Marshal(value)
if err != nil {
return err
}
def := string(jsonBytes)
p.Default = &def
return nil
}
// GetDefault returns the default as an interface{}, unmarshalling json is the underlying value was NOT a string
func (p *ParamDef) GetDefault() (any, error) {
if p.Default == nil {
return nil, nil
}
if p.IsString {
return *p.Default, nil
}
var val any
err := json.Unmarshal([]byte(*p.Default), &val)
return val, err
}
// GetShowData implements printers.Showable
func (p *ParamDef) GetShowData() *printers.RowData {
res := printers.NewRowData(
printers.NewFieldValue("Name", p.UnqualifiedName),
printers.NewFieldValue("Description", p.Description),
printers.NewFieldValue("Default", p.Default),
)
return res
}