-
Notifications
You must be signed in to change notification settings - Fork 23
/
buildinfo.go
105 lines (90 loc) · 2.42 KB
/
buildinfo.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
package buildinfo
import (
"encoding/json"
"errors"
"io/ioutil"
"github.com/vim-volt/volt/lockjson"
"github.com/vim-volt/volt/pathutil"
)
type BuildInfo struct {
Repos ReposList `json:"repos"`
Version int64 `json:"version"`
Strategy string `json:"strategy"`
}
type ReposList []Repos
type Repos struct {
Type lockjson.ReposType `json:"type"`
Path pathutil.ReposPath `json:"path"`
Version string `json:"version"`
Files FileMap `json:"files,omitempty"`
DirtyWorktree bool `json:"dirty_worktree,omitempty"`
}
// key: filepath, value: version
type FileMap map[string]string
func Read() (*BuildInfo, error) {
// Return initial build-info.json struct
// if the file does not exist
file := pathutil.BuildInfoJSON()
if !pathutil.Exists(file) {
return &BuildInfo{}, nil
}
// Read build-info.json
bytes, err := ioutil.ReadFile(file)
if err != nil {
return nil, err
}
var buildInfo BuildInfo
err = json.Unmarshal(bytes, &buildInfo)
if err != nil {
return nil, err
}
// Validate build-info.json
err = buildInfo.validate()
if err != nil {
return nil, errors.New("validation failed: build-info.json: " + err.Error())
}
return &buildInfo, nil
}
func (buildInfo *BuildInfo) Write() error {
// Validate build-info.json
err := buildInfo.validate()
if err != nil {
return errors.New("validation failed: build-info.json: " + err.Error())
}
// Write to build-info.json
bytes, err := json.MarshalIndent(buildInfo, "", " ")
if err != nil {
return err
}
return ioutil.WriteFile(pathutil.BuildInfoJSON(), bytes, 0644)
}
func (buildInfo *BuildInfo) validate() error {
// Validate if repos do not have duplicate repository
dupRepos := make(map[pathutil.ReposPath]bool, len(buildInfo.Repos))
for i := range buildInfo.Repos {
r := &buildInfo.Repos[i]
if _, exists := dupRepos[r.Path]; exists {
return errors.New("duplicate repos: " + r.Path.String())
}
dupRepos[r.Path] = true
}
return nil
}
func (reposList *ReposList) FindByReposPath(reposPath pathutil.ReposPath) *Repos {
for i := range *reposList {
repos := &(*reposList)[i]
if repos.Path == reposPath {
return repos
}
}
return nil
}
func (reposList *ReposList) RemoveByReposPath(reposPath pathutil.ReposPath) {
for i := range *reposList {
repos := &(*reposList)[i]
if repos.Path == reposPath {
*reposList = append((*reposList)[:i], (*reposList)[i+1:]...)
break
}
}
}