-
Notifications
You must be signed in to change notification settings - Fork 380
Expand file tree
/
Copy pathdeps.go
More file actions
342 lines (285 loc) · 7.84 KB
/
deps.go
File metadata and controls
342 lines (285 loc) · 7.84 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
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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
package buildscript
import (
"encoding/json"
"fmt"
"io/fs"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"sort"
"strings"
"syscall"
"github.com/craiggwilson/goke/pkg/sh"
"github.com/craiggwilson/goke/task"
mapset "github.com/deckarep/golang-set/v2"
"github.com/pkg/errors"
"golang.org/x/mod/modfile"
)
func WriteSBOMLite(ctx *task.Context) error {
if err := requirePodman(ctx); err != nil {
return err
}
if err := startPodmanMachine(ctx); err != nil {
return err
}
//nolint:errcheck
defer stopPodmanMachine(ctx)
return sh.Run(ctx, "scripts/regenerate-sbom-lite.sh")
}
// WriteAugmentedSBOM creates the SBOM Lite file for this project. This requires the following env
// vars to be set:
//
// - KONDUKTO_TOKEN
// - EVG_TRIGGERED_BY_TAG
func WriteAugmentedSBOM(ctx *task.Context) error {
if err := requirePodman(ctx); err != nil {
return err
}
return sh.Run(ctx, "scripts/regenerate-augmented-sbom.sh")
}
func requirePodman(ctx *task.Context) error {
err := sh.Run(ctx, "which", "podman")
if err == nil {
return nil
}
fmt.Println(`This command requires the "podman" CLI tool, which you will need to install.`)
fmt.Println("See https://podman.io/ for more information and installation instructions.")
return err
}
func startPodmanMachine(ctx *task.Context) error {
if runtime.GOOS == "linux" {
// Linux doesn't need a podman machine to be up.
return nil
}
out, err := sh.RunOutput(ctx, "podman", "machine", "info", "--format", "json")
if err != nil {
return err
}
fmt.Printf("podman machine info: %s\n", out)
info := struct {
Host struct {
CurrentMachine string `json:"CurrentMachine"`
MachineState string `json:"MachineState"`
} `json:"Host"`
}{}
err = json.Unmarshal([]byte(out), &info)
if err != nil {
return err
}
// Run podman machine init if there's no current machine.
if info.Host.CurrentMachine == "" {
err = sh.RunCmd(ctx, exec.CommandContext(ctx, "podman", "machine", "init"))
if err != nil {
return err
}
}
if info.Host.MachineState == "Running" {
return nil
}
return sh.Run(ctx, "podman", "machine", "start")
}
func stopPodmanMachine(ctx *task.Context) error {
if runtime.GOOS == "linux" {
// Linux doesn't need a podman machine.
return nil
}
return sh.Run(ctx, "podman", "machine", "stop")
}
//nolint:misspell // "licence" is intentional here
var (
// This matches a file that starts with "license" or "licence", in any
// case, with an optional extension.
licenseRegexp1 = regexp.MustCompile(`(?i)^licen[cs]e(?:\..+)?$`)
// This matches a file that has an extension of "license" or "licence", in
// any case.
licenseRegexp2 = regexp.MustCompile(`(?i)\.licen[cs]e$`)
trailingSpaceRegexp = regexp.MustCompile(`(?m)[^\\n\\S]+$`)
horizontalLine = strings.Repeat("-", 70)
)
// WriteThirdPartyNotices writes the `THIRD-PARTY-NOTICES` file for this project, which contains all
// the licenses for our vendored code.
func WriteThirdPartyNotices(ctx *task.Context) error {
root, err := repoRoot()
if err != nil {
return err
}
licenseFiles, err := getLicenseFiles(root)
if err != nil {
return err
}
var notices string
for _, lf := range licenseFiles {
notices += "\n"
notices += horizontalLine
notices += "\n"
notices += fmt.Sprintf(
"License notice for %s (%s)\n",
lf.packageName,
filepath.Base(lf.path),
)
notices += horizontalLine
notices += "\n"
notices += "\n"
content, err := os.ReadFile(lf.path)
if err != nil {
return err
}
contentStr := string(content)
// Trim trailing space from each line.
contentStr = trailingSpaceRegexp.ReplaceAllString(contentStr, "")
notices += contentStr
}
return os.WriteFile(filepath.Join(root, "THIRD-PARTY-NOTICES"), []byte(notices), 0644)
}
const vendorDir string = "vendor"
type licenseFile struct {
packageName string
path string
}
func getLicenseFiles(root string) ([]licenseFile, error) {
var (
walkIn = filepath.Join(root, vendorDir)
pathPrefix = walkIn + "/"
licenseFiles []licenseFile
)
err := filepath.WalkDir(
walkIn,
func(path string, d fs.DirEntry, err error) error {
if err != nil {
return err
}
if !d.Type().IsRegular() {
return nil
}
filename := d.Name()
if licenseRegexp1.MatchString(filename) || licenseRegexp2.MatchString(filename) {
packageName := strings.TrimPrefix(filepath.Dir(path), pathPrefix)
licenseFiles = append(licenseFiles, licenseFile{packageName, path})
}
return nil
},
)
if err != nil {
return nil, err
}
sort.Slice(
licenseFiles,
func(i, j int) bool {
return licenseFiles[i].path < licenseFiles[j].path
},
)
return licenseFiles, nil
}
// AddDep adds a new dependency. Pass a package name with an optional `@$version` at the end.
func AddDep(ctx *task.Context) error {
return addOrUpdateGoDep(ctx, ctx.Get("pkg"), false)
}
// UpdateDep updates an existing dependency. Pass a package name with an optional `@$version` at the
// end.
func UpdateDep(ctx *task.Context) error {
return addOrUpdateGoDep(ctx, ctx.Get("pkg"), true)
}
// UpdateAll updates all existing dependencies to their latest versions. To exclude one or more
// packages, set the `-exclude` argument to a list of packages separated by a space.
//
// This does not upgrade packages included as the replacement in a `replace` block. Those must be
// upgraded by editing the `go.mod` file directly.
func UpdateAllDeps(ctx *task.Context) error {
pkgs, err := allGoDependencies()
if err != nil {
return err
}
excludeSet := mapset.NewSet(strings.Fields(ctx.Get("exclude"))...)
for _, pkg := range pkgs {
if excludeSet.Contains(pkg) {
fmt.Printf("Excluding %s from the package updates\n", pkg)
continue
}
if err := goGet(ctx, pkg, true); err != nil {
return err
}
}
return updateGoPackageMetadata(ctx)
}
func allGoDependencies() ([]string, error) {
root, err := repoRoot()
if err != nil {
return nil, err
}
goModPath := filepath.Join(root, "go.mod")
raw, err := os.ReadFile(goModPath)
if err != nil {
return nil, errors.Wrapf(err, "could not read go.mod file at %s", goModPath)
}
file, err := modfile.Parse(goModPath, raw, nil)
if err != nil {
return nil, err
}
modules := mapset.NewSet[string]()
for _, req := range file.Require {
modules.Add(req.Mod.Path)
}
return mapset.Sorted(modules), nil
}
func addOrUpdateGoDep(ctx *task.Context, pkg string, isUpdate bool) error {
if err := goGet(ctx, pkg, isUpdate); err != nil {
return err
}
return updateGoPackageMetadata(ctx)
}
func goGet(ctx *task.Context, pkg string, isUpdate bool) error {
v, err := goVersion(ctx)
if err != nil {
return err
}
args := []string{"get"}
if isUpdate {
args = append(args, "-u")
}
args = append(args, pkg)
cmd := exec.Command("go", args...)
// Setting GOTOOLCHAIN to the current version prevents Go from trying to update itself because a
// dependency we add or update requires a newer Go version.
//
// If we set _anything_ in `cmd.Env` then we don't get any of our current env vars, so we pass
// the current env through and then overwrite GOTOOLCHAIN.
cmd.Env = append(
syscall.Environ(),
"GOTOOLCHAIN="+v,
)
return sh.RunCmd(ctx, cmd)
}
var versionRE = regexp.MustCompile(`go version (go\d+\.\d+\.\d+) `)
var v string
func goVersion(ctx *task.Context) (string, error) {
if v != "" {
return v, nil
}
out, err := sh.RunOutput(ctx, "go", "version")
if err != nil {
return "", err
}
matches := versionRE.FindStringSubmatch(out)
if len(matches) < 1 {
return "", fmt.Errorf(
"could not parse go version from `go version` output: %s",
strings.TrimSpace(out),
)
}
v = matches[1]
return v, nil
}
func updateGoPackageMetadata(ctx *task.Context) error {
if err := sh.Run(ctx, "go", "mod", "tidy"); err != nil {
return err
}
if err := sh.Run(ctx, "go", "mod", "vendor"); err != nil {
return err
}
if err := WriteSBOMLite(ctx); err != nil {
return err
}
return WriteThirdPartyNotices(ctx)
}