-
Notifications
You must be signed in to change notification settings - Fork 0
/
project.go
130 lines (100 loc) · 2.31 KB
/
project.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
package data
import (
"encoding/json"
"os"
"path"
"strings"
)
const (
CurrentVersion = "0.0.1"
)
type Project struct {
Name string `json:"name"`
Version string `json:"version"`
RootDir string `json:"-"`
requests []*Request `json:"-"`
requestMap map[string]*Request `json:"-"`
}
func LoadProject(rootDir string) (*Project, error) {
var project Project
/* #nosec G304 */
data, err := os.ReadFile(path.Join(rootDir, "sonata.json"))
if err != nil {
return nil, err
}
err = json.Unmarshal(data, &project)
if err != nil {
return nil, err
}
project.RootDir = rootDir
if err := project.ReloadRequests(); err != nil {
return nil, err
}
return &project, nil
}
func (p *Project) ReloadRequests() error {
p.requestMap = make(map[string]*Request)
p.requests = make([]*Request, 0)
files, err := os.ReadDir(p.RootDir)
if err != nil {
return err
}
for _, file := range files {
if !strings.HasSuffix(file.Name(), ".request.json") {
continue
}
data, err := os.ReadFile(path.Join(p.RootDir, file.Name()))
if err != nil {
return err
}
var request Request
err = json.Unmarshal(data, &request)
if err != nil {
return err
}
p.requests = append(p.requests, &request)
request.path = path.Join(p.RootDir, file.Name())
request.p = p
request.Name = strings.TrimSuffix(file.Name(), ".request.json")
p.requestMap[request.Name] = &request
}
return nil
}
func NewProject(rootDir string, name string) (*Project, error) {
project := Project{
Name: name,
Version: CurrentVersion,
RootDir: rootDir,
}
return &project, nil
}
func (p *Project) Save() error {
data, err := json.Marshal(p)
if err != nil {
return err
}
/* #nosec G306 */
/* #nosec G302 */
return os.WriteFile(path.Join(p.RootDir, "sonata.json"), data, 0644)
}
func (p *Project) GetRequest(name string) (*Request, bool) {
r, found := p.requestMap[name]
return r, found
}
func (p *Project) ListRequests() []*Request {
return p.requests
}
func (p *Project) ListEnvironments() ([]string, error) {
entries, err := os.ReadDir(p.RootDir)
if err != nil {
return nil, err
}
environments := make([]string, 0, len(entries))
for _, entry := range entries {
if !strings.HasSuffix(entry.Name(), ".env") {
continue
}
environments = append(environments, entry.Name())
}
return environments, nil
}