-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathmodules.go
More file actions
107 lines (90 loc) · 2.39 KB
/
modules.go
File metadata and controls
107 lines (90 loc) · 2.39 KB
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
package pike
import (
"encoding/json"
"fmt"
"io"
"os"
"path/filepath"
"github.com/hashicorp/go-version"
"github.com/rs/zerolog/log"
)
const (
ManifestSnapshotFilename = "modules.json"
)
// Record represents some metadata about an installed module, as part
// of a module JSON.
type Record struct {
Key string `json:"Key"`
SourceAddr string `json:"Source"`
Version *version.Version `json:"-"`
VersionStr string `json:"Version,omitempty"`
Dir string `json:"Dir"`
}
type ModuleJson map[string]Record
type modulesJson struct {
Records []Record `json:"Modules"`
}
type invalidVersionError struct {
err error
key string
version string
}
func (m *invalidVersionError) Error() string {
return fmt.Sprintf("invalid version %q for %s: %s", m.version, m.key, m.err)
}
func ReadModuleJson(r io.Reader) (ModuleJson, error) {
src, err := io.ReadAll(r)
if err != nil {
return nil, err
}
if len(src) == 0 {
return make(ModuleJson), nil
}
var read modulesJson
err = json.Unmarshal(src, &read)
if err != nil {
return nil, &unmarshallJSONError{err, ""}
}
newModuleJson := make(ModuleJson)
for _, record := range read.Records {
if record.VersionStr != "" {
record.Version, err = version.NewVersion(record.VersionStr)
if err != nil {
return nil, &invalidVersionError{err, record.Key, record.VersionStr}
}
}
// Ensure Windows is using the proper modules path format after
// reading the module's manifest Dir records
record.Dir = filepath.FromSlash(record.Dir)
if _, exists := newModuleJson[record.Key]; exists {
return nil, fmt.Errorf("snapshot file contains two records for path %s", record.Key)
}
newModuleJson[record.Key] = record
}
return newModuleJson, nil
}
func ReadModuleJsonForDir(dir string) (ModuleJson, error) {
fn := filepath.Join(dir, ManifestSnapshotFilename)
r, err := os.Open(fn) // #nosec G304 -- Reading Terraform module manifest from known location
if err != nil {
if os.IsNotExist(err) {
return make(ModuleJson), nil
}
return nil, err
}
defer func(r *os.File) {
err := r.Close()
if err != nil {
log.Warn().Msgf("Faile dto close file %s", r.Name())
}
}(r)
return ReadModuleJson(r)
}
func ReturnLocalAddrFromSource(source string, listModules ModuleJson) string {
for _, module := range listModules {
if module.SourceAddr == source {
return module.Dir
}
}
return ""
}