-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
257 lines (211 loc) · 5.18 KB
/
main.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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
package main
import (
"bytes"
"fmt"
"github.com/go-git/go-billy/v5/memfs"
"github.com/go-git/go-billy/v5/util"
"github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/storage/memory"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclparse"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/spf13/cobra"
"github.com/zclconf/go-cty/cty"
)
type Resource struct {
Name string
Attributes map[string]cty.Value
Blocks map[string]Block
}
type Block struct {
Attributes map[string]cty.Value
Blocks map[string]Block
}
func main() {
rootCmd := &cobra.Command{
Run: func(c *cobra.Command, args []string) {
baseBranch, err := c.PersistentFlags().GetString("base")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
err = diff(baseBranch)
if err != nil {
fmt.Println(err)
os.Exit(1)
}
},
}
rootCmd.PersistentFlags().StringP("base", "b", "", "base branch")
if err := rootCmd.Execute(); err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func diff(baseBranch string) error {
if baseBranch == "" {
_, err := exec.Command("sh", "-c", "git branch | grep -q main").Output()
if err == nil {
baseBranch = "main"
}
_, err = exec.Command("sh", "-c", "git branch | grep -q master").Output()
if err == nil {
baseBranch = "master"
}
if baseBranch == "" {
return fmt.Errorf("can't specify base branch")
}
}
p, err := exec.Command("sh", "-c", "git rev-parse --show-prefix").Output()
if err != nil {
return err
}
path := strings.TrimSpace(string(p))
// Get resources on the base branch
content, err := getContent(baseBranch, path)
if err != nil {
return err
}
baseResources, err := parse(content)
if err != nil {
return err
}
// Get resources on the target branch
content, err = getContent("", path)
if err != nil {
return err
}
targetResources, err := parse(content)
if err != nil {
return err
}
var differentResources []string
for name, _ := range baseResources {
if _, ok := targetResources[name]; !ok {
differentResources = append(differentResources, name)
continue
}
if !reflect.DeepEqual(baseResources[name], targetResources[name]) {
differentResources = append(differentResources, name)
}
}
for name, _ := range targetResources {
if _, ok := baseResources[name]; !ok {
differentResources = append(differentResources, name)
}
}
if len(differentResources) > 0 {
for _, r := range differentResources {
fmt.Printf("-target %s ", r)
}
} else {
fmt.Print("-refresh=false")
}
return nil
}
func getContent(baseBranch, path string) ([]byte, error) {
var buf bytes.Buffer
if baseBranch == "" {
files, err := filepath.Glob("*.tf")
if err != nil {
return nil, err
}
for _, f := range files {
c, err := ioutil.ReadFile(f)
if err != nil {
return nil, err
}
buf.Write(c)
}
} else {
r, err := exec.Command("sh", "-c", "git rev-parse --show-toplevel").Output()
if err != nil {
return nil, err
}
root := strings.TrimSpace(string(r))
storer := memory.NewStorage()
fs := memfs.New()
repo, err := git.Clone(storer, fs, &git.CloneOptions{
URL: root,
})
if err != nil {
return nil, err
}
w, err := repo.Worktree()
if err != nil {
return nil, err
}
err = w.Checkout(&git.CheckoutOptions{Branch: plumbing.NewBranchReferenceName(baseBranch)})
files, err := util.Glob(fs, fmt.Sprintf("%s*.tf", path))
if err != nil {
return nil, err
}
for _, f := range files {
c, err := util.ReadFile(fs, f)
if err != nil {
return nil, err
}
buf.Write(c)
}
}
return buf.Bytes(), nil
}
func parse(content []byte) (map[string]*Resource, error) {
resources := make(map[string]*Resource)
parser := hclparse.NewParser()
file, parseDiags := parser.ParseHCL(content, "")
if parseDiags.HasErrors() {
return nil, fmt.Errorf(parseDiags.Error())
}
for _, block := range reflect.ValueOf(file.Body).Elem().Interface().(hclsyntax.Body).Blocks {
if block.Type == "resource" || block.Type == "module" {
resource := decodeResource(block)
resources[resource.Name] = resource
}
}
return resources, nil
}
func decodeResource(block *hclsyntax.Block) *Resource {
r := &Resource{}
if block.Type == "resource" {
r.Name = fmt.Sprintf("%s.%s", block.Labels[0], block.Labels[1])
} else if block.Type == "module" {
r.Name = fmt.Sprintf("module.%s", block.Labels[0])
}
if len(block.Body.Attributes) > 0 {
r.Attributes = decodeAttributes(block.Body.Attributes)
}
if len(block.Body.Blocks) > 0 {
r.Blocks = decodeBlocks(block.Body.Blocks)
}
return r
}
func decodeAttributes(attributes hclsyntax.Attributes) map[string]cty.Value {
a := make(map[string]cty.Value)
for _, attr := range attributes {
v, _ := attr.Expr.Value(&hcl.EvalContext{})
a[attr.Name] = v
}
return a
}
func decodeBlocks(blocks hclsyntax.Blocks) map[string]Block {
block := make(map[string]Block)
for _, b := range blocks {
n := Block{}
if len(b.Body.Attributes) > 0 {
n.Attributes = decodeAttributes(b.Body.Attributes)
}
if len(b.Body.Blocks) > 0 {
n.Blocks = decodeBlocks(b.Body.Blocks)
}
block[b.Type] = n
}
return block
}