-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
71 lines (63 loc) · 1.87 KB
/
config.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
package tfsyntax
import (
"log"
"os"
hcl "github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/hclwrite"
)
// Config type implement all terraform blocks
type Config struct {
Variables []*Variable
Modules []*ModuleConfig
Providers []*ProviderConfig
}
// Method to read HCL file
func (c *Config) HclFile(filePath string) *hcl.File {
content, err := os.ReadFile(filePath)
if err != nil {
log.Fatal("read error ", filePath)
}
file, diags := hclsyntax.ParseConfig(content, filePath, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
log.Fatal("parse config error", diags)
}
return file
}
// Method to get HCL block of given type
func (c *Config) BlocksOfType(filePath, typeName string, BodySchema *hcl.BodySchema) hcl.Blocks {
file := c.HclFile(filePath)
bc, _, diags := file.Body.PartialContent(BodySchema)
if diags.HasErrors() {
log.Fatal("file content error ", diags)
}
return bc.Blocks.OfType(typeName)
}
// Method to get blocks within a block
func (c *Config) BlocksWithinBlock(block *hcl.Block, typeName string, BodySchema *hcl.BodySchema) hcl.Blocks {
bc, _, _ := block.Body.PartialContent(BodySchema)
return bc.Blocks.OfType(typeName)
}
// HCL write implementation
func (c *Config) HclWriteFile(filePath string) *hclwrite.File {
content, err := os.ReadFile(filePath)
if err != nil {
log.Fatal("read error ", filePath)
}
file, diags := hclwrite.ParseConfig(content, filePath, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
log.Fatal("parse config error", diags)
}
return file
}
// HCL write implementation
func (c *Config) HclWriteBlockOfType(filePath, typeName string) []*hclwrite.Block {
var BlocksByType []*hclwrite.Block
file := c.HclWriteFile(filePath)
for _, block := range file.Body().Blocks() {
if block.Type() == typeName {
BlocksByType = append(BlocksByType, block)
}
}
return BlocksByType
}