/
manager.go
269 lines (230 loc) · 6.95 KB
/
manager.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
package dependency
import (
"crypto/sha256"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/g2a-com/klio/internal/context"
"github.com/g2a-com/klio/internal/dependency/registry"
"github.com/g2a-com/klio/internal/lock"
"github.com/g2a-com/klio/internal/log"
"github.com/g2a-com/klio/internal/schema"
"github.com/g2a-com/klio/internal/tarball"
"github.com/schollz/progressbar/v3"
"golang.org/x/term"
)
type ScopeType string
const (
GlobalScope ScopeType = "global"
ProjectScope ScopeType = "project"
)
type Updates struct {
NonBreaking string
Breaking string
}
type Manager struct {
DefaultRegistry string
registries map[string]*registry.Registry
context context.CLIContext
}
func NewManager(ctx context.CLIContext) *Manager {
return &Manager{
context: ctx,
}
}
func (mgr *Manager) GetUpdateFor(dep schema.Dependency) (Updates, error) {
// Initialize depRegistry
if _, ok := mgr.registries[dep.Registry]; !ok {
if mgr.registries == nil {
mgr.registries = map[string]*registry.Registry{}
}
mgr.registries[dep.Registry] = registry.New(dep.Registry)
if err := mgr.registries[dep.Registry].Update(); err != nil {
return Updates{}, err
}
}
// Find versions
depRegistry := mgr.registries[dep.Registry]
nonBreaking := depRegistry.FindCompatibleDependency(schema.Dependency{
Registry: dep.Registry,
Name: dep.Name,
Version: fmt.Sprintf("> %s, ^ %s", dep.Version, dep.Version),
})
breaking := depRegistry.FindCompatibleDependency(schema.Dependency{
Registry: dep.Registry,
Name: dep.Name,
Version: "> " + dep.Version,
})
// Prepare result
updates := Updates{}
if nonBreaking != nil {
updates.NonBreaking = nonBreaking.Version
}
if breaking != nil {
updates.Breaking = breaking.Version
}
return updates, nil
}
func (mgr *Manager) InstallDependency(dep schema.Dependency, scope ScopeType) (*schema.Dependency, error) {
installDir, err := mgr.getInstallDir(scope)
if err != nil {
return nil, err
}
indexPath := filepath.Join(installDir, "dependencies.json")
indexLockfilePath := filepath.Join(installDir, "dependencies.lock")
// Fill missing values
if dep.Alias == "" {
dep.Alias = dep.Name
}
if dep.Registry == "" {
dep.Registry = mgr.DefaultRegistry
}
// Make sure that install directory exists
if _, err := os.Stat(installDir); os.IsNotExist(err) {
if err := os.MkdirAll(installDir, 0o755); err != nil {
log.LogfAndExit(log.FatalLevel, "unable to create directory: %s due to %s", installDir, err)
}
}
// Acquire lock for updating dependencies.json
if err := lock.Acquire(indexLockfilePath); err != nil {
return nil, err
}
// Initialize registry
if _, ok := mgr.registries[dep.Registry]; !ok {
if mgr.registries == nil {
mgr.registries = map[string]*registry.Registry{}
}
mgr.registries[dep.Registry] = registry.New(dep.Registry)
if err := mgr.registries[dep.Registry].Update(); err != nil {
return nil, err
}
}
// Search for a suitable version
entry := mgr.registries[dep.Registry].FindCompatibleDependency(dep)
if entry == nil {
return nil, fmt.Errorf("cannot find %s@%s in %s", dep.Name, dep.Version, dep.Registry)
}
// Create temporary file for a tarball
file, err := ioutil.TempFile("", "klio-")
if err != nil {
return nil, err
}
defer func(name string) {
_ = os.Remove(name)
}(file.Name())
// Download tarball
checksum, err := downloadFile(entry.URL, file)
if err != nil {
return nil, err
}
// Verify checksum
if entry.Checksum != "" && entry.Checksum != checksum {
return nil, fmt.Errorf(`checksum of the archive (%s) is different from the one specified in the regsitry (%s)`, checksum, entry.Checksum)
}
// Make sure that output dir exists and is empty
outputRelPath := filepath.Join("dependencies", checksum)
outputAbsPath := filepath.Join(installDir, outputRelPath)
if _, err := os.Stat(outputAbsPath); err == nil {
_ = os.RemoveAll(outputAbsPath)
} else if !os.IsNotExist(err) {
log.LogfAndExit(log.FatalLevel, "unable to remove directory: %s due to %s", outputAbsPath, err)
}
if err := os.MkdirAll(outputAbsPath, 0o755); err != nil {
log.LogfAndExit(log.FatalLevel, "unable to create directory: %s due to %s", outputAbsPath, err)
}
// Extract tarball
_, _ = file.Seek(0, io.SeekStart)
if err := tarball.Extract(file, outputAbsPath); err != nil {
return nil, err
}
// Add dependency to dependencies.json
index, err := schema.LoadDependenciesIndex(indexPath)
if err != nil {
return nil, err
}
newEntries := make([]schema.DependenciesIndexEntry, 0, len(index.Entries))
for _, entry := range index.Entries {
if entry.Alias != dep.Alias {
newEntries = append(newEntries, entry)
}
}
newEntries = append(newEntries, schema.DependenciesIndexEntry{
Alias: dep.Alias,
Registry: dep.Registry,
Name: dep.Name,
Version: entry.Version,
OS: entry.OS,
Arch: entry.Arch,
Checksum: entry.Checksum,
Path: outputRelPath,
})
index.Entries = newEntries
if err := schema.SaveDependenciesIndex(index); err != nil {
return nil, err
}
// Release lock
_ = lock.Release(indexLockfilePath)
// Return info about installed dependency
result := dep
result.Version = entry.Version
return &result, nil
}
func (mgr *Manager) GetInstalledCommands(scope ScopeType) ([]schema.DependenciesIndexEntry, error) {
installDir, err := mgr.getInstallDir(scope)
if err != nil {
return []schema.DependenciesIndexEntry{}, err
}
indexPath := filepath.Join(installDir, "dependencies.json")
indexData, err := schema.LoadDependenciesIndex(indexPath)
if err != nil {
return []schema.DependenciesIndexEntry{}, err
}
// dependencies.json contains relative paths for commands, make them absolute
for idx := range indexData.Entries {
indexData.Entries[idx].Path = filepath.Join(installDir, indexData.Entries[idx].Path)
}
return indexData.Entries, nil
}
func (mgr *Manager) getInstallDir(scope ScopeType) (string, error) {
switch scope {
case GlobalScope:
if mgr.context.Paths.GlobalInstallDir == "" {
return "", errors.New("cannot find global directory")
}
return mgr.context.Paths.GlobalInstallDir, nil
case ProjectScope:
if mgr.context.Paths.ProjectInstallDir == "" {
return "", errors.New("cannot find project directory")
}
return mgr.context.Paths.ProjectInstallDir, nil
default:
return "", fmt.Errorf("unknown scope: %s", scope)
}
}
func downloadFile(url string, file io.Writer) (checksum string, err error) {
log.Verbosef("Downloading %s", url)
resp, err := http.Get(url)
if err != nil {
return "", err
}
defer func(Body io.ReadCloser) {
_ = Body.Close()
}(resp.Body)
hash := sha256.New()
writer := io.MultiWriter(file, hash)
if term.IsTerminal(int(os.Stdout.Fd())) {
progress := progressbar.DefaultBytes(
resp.ContentLength, // value -1 indicates that the length is unknown
"Downloading",
)
writer = io.MultiWriter(writer, progress)
}
if _, err = io.Copy(writer, resp.Body); err != nil {
return "", err
}
return fmt.Sprintf("sha256-%x", hash.Sum(nil)), nil
}