forked from coretech/terrafile
-
Notifications
You must be signed in to change notification settings - Fork 2
/
parser.go
85 lines (70 loc) · 1.85 KB
/
parser.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
package main
import (
"path/filepath"
"strings"
"gopkg.in/yaml.v2"
)
type SourceDependenciesMap map[string][]*Dependency
type Dependency struct {
Alias *string
SourceRef
}
func (d *Dependency) GetTargetPath(basePath string) (string, error) {
var relativePath string
if d.Alias == nil {
// Use segment target path format
pathParts := strings.Split(d.Source, ":")
repositoryName := pathParts[1]
relativePath = filepath.Join(basePath, repositoryName, d.Version)
} else {
// Use community target path format
relativePath = filepath.Join(basePath, *d.Alias)
}
return filepath.Abs(relativePath)
}
type SourceRef struct {
Source string `yaml:"source"`
Version string `yaml:"version"`
}
func parseTerrafile(in []byte) (SourceDependenciesMap, error) {
// Try parse Segment internal format
result, err := parseSegmentTerrafile(in)
if _, ok := err.(*yaml.TypeError); ok {
// Try fallback to community format
result, err = parseCommunityTerrafile(in)
}
return result, err
}
func parseSegmentTerrafile(in []byte) (SourceDependenciesMap, error) {
var config map[string][]string
if err := yaml.Unmarshal(in, &config); err != nil {
return nil, err
}
result := make(SourceDependenciesMap)
for source, versions := range config {
for _, version := range versions {
result[source] = append(result[source], &Dependency{
SourceRef: SourceRef{
Source: source,
Version: version,
},
})
}
}
return result, nil
}
func parseCommunityTerrafile(in []byte) (SourceDependenciesMap, error) {
var config map[string]SourceRef
if err := yaml.Unmarshal(in, &config); err != nil {
return nil, err
}
result := make(SourceDependenciesMap)
for key, sourceRef := range config {
alias := key
result[sourceRef.Source] = append(result[sourceRef.Source], &Dependency{
Alias: &alias,
SourceRef: sourceRef,
})
}
return result, nil
}