/
terraform.go
106 lines (89 loc) · 2.55 KB
/
terraform.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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package types
import (
"fmt"
"github.com/hashicorp/terraform/version"
"github.com/mcuadros/ascode/terraform"
"go.starlark.net/starlark"
)
// Terraform is a representation of Terraform as a starlark.Value
//
// outline: types
// types:
// Terraform
// Terraform holds all the configuration defined by a script. A global
// variable called `tf` contains a unique instance of Terraform.
//
// examples:
// tf_overview.star
//
// fields:
// version string
// Terraform version.
// backend Backend
// Backend used to store the state, if None a `local` backend it's
// used.
// provider ProviderCollection
// Dict with all the providers defined by provider type.
//
type Terraform struct {
b *Backend
p *ProviderCollection
}
// NewTerraform returns a new instance of Terraform
func NewTerraform(pm *terraform.PluginManager) *Terraform {
return &Terraform{
p: NewProviderCollection(pm),
}
}
var _ starlark.Value = &Terraform{}
var _ starlark.HasAttrs = &Terraform{}
var _ starlark.HasSetField = &Terraform{}
// Attr honors the starlark.HasAttrs interface.
func (t *Terraform) Attr(name string) (starlark.Value, error) {
switch name {
case "version":
return starlark.String(version.String()), nil
case "provider":
return t.p, nil
case "backend":
if t.b == nil {
return starlark.None, nil
}
return t.b, nil
}
return starlark.None, nil
}
// SetField honors the starlark.HasSetField interface.
func (t *Terraform) SetField(name string, val starlark.Value) error {
if name != "backend" {
errmsg := fmt.Sprintf("terraform has no .%s field or method", name)
return starlark.NoSuchAttrError(errmsg)
}
if b, ok := val.(*Backend); ok {
t.b = b
return nil
}
return fmt.Errorf("unexpected value %s at %s", val.Type(), name)
}
// AttrNames honors the starlark.HasAttrs interface.
func (t *Terraform) AttrNames() []string {
return []string{"provider", "backend", "version"}
}
// Freeze honors the starlark.Value interface.
func (t *Terraform) Freeze() {} // immutable
// Hash honors the starlark.Value interface.
func (t *Terraform) Hash() (uint32, error) {
return 0, fmt.Errorf("unhashable type: %s", t.Type())
}
// String honors the starlark.Value interface.
func (t *Terraform) String() string {
return "terraform"
}
// Truth honors the starlark.Value interface.
func (t *Terraform) Truth() starlark.Bool {
return t.p.Len() != 0
}
// Type honors the starlark.Value interface.
func (t *Terraform) Type() string {
return "Terraform"
}