-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
382 lines (325 loc) · 10.3 KB
/
main.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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package main
import (
"errors"
"fmt"
"log"
"os"
"os/exec"
"slices"
"strings"
)
var removeSoftwareList = []string{
"aliyun-cli",
"android-sdk",
"apache",
"aws-tools",
"bazel",
"gfortran",
"heroku",
"julia",
"kotlin",
"leiningen",
"oc-cli",
"php",
"postgresql",
"pulumi",
"rlang",
"rust",
"sbt",
"selenium",
"swift",
"vcpkg",
}
var addSoftwareList = []string{
"cosign",
"github-runner",
"golangci-lint",
"google-cloud-cli",
"playwright-dependencies",
"trivy",
"kubelogin",
}
func checkDiff(filesPath string, localGitDir string, gitDir string) {
err := os.Chdir(gitDir)
if err != nil {
log.Fatal(err)
}
filesByte, err := exec.Command("git", "ls-files", filesPath).CombinedOutput()
if err != nil {
fmt.Println(string(filesByte))
log.Fatal(err)
}
files := string(filesByte)
if files == "" {
fmt.Println(" No files found.")
return
}
for _, byteFile := range strings.Split(files, "\n") {
file := string(byteFile)
if file == "" {
return
}
localGitDirFile := localGitDir + "/" + file
if _, err := os.Stat(localGitDirFile); errors.Is(err, os.ErrNotExist) {
// Special case for install scripts
installScriptShouldBeRemoved := slices.ContainsFunc(removeSoftwareList, func(s string) bool {
return strings.HasSuffix(file, "scripts/build/install-"+s+".sh")
})
if !installScriptShouldBeRemoved {
fmt.Printf("File '%s' is not in the list of software to be removed; do you want to add it? [y/N]\n", file)
acceptAll := os.Getenv("ACCEPT_ALL") == "true"
var REPLY string
if !acceptAll {
_, err := fmt.Scanln(&REPLY)
if err != nil {
log.Fatal(err)
}
}
if acceptAll || REPLY == "Y" || REPLY == "y" {
cp, err := exec.Command("cp", gitDir+"/"+file, localGitDirFile).CombinedOutput()
if err != nil {
fmt.Println(string(cp))
log.Fatal(err)
}
}
} else {
fmt.Printf(" File '%s' does not exist in local git directory.\n", file)
}
continue
}
gitDirFile := gitDir + "/" + file
if _, err := os.Stat(gitDirFile); errors.Is(err, os.ErrNotExist) {
fmt.Printf(" File '%s' does not exist in git temp directory.\n", file)
continue
}
// Ignore error, diff will return non-zero exit code if files are different.
fileDiffByte, _ := exec.Command("diff", "-u", "--color", localGitDirFile, gitDirFile).CombinedOutput()
fileDiff := string(fileDiffByte)
if fileDiff != "" {
fmt.Printf("\nChanges in '%s':\n\n", file)
fmt.Println(fileDiff)
fmt.Printf("\n\n")
fmt.Println("Do you want to apply these changes to " + file + "? [y/N]\n")
acceptAll := os.Getenv("ACCEPT_ALL") == "true"
var REPLY string
if !acceptAll {
_, err := fmt.Scanln(&REPLY)
if err != nil {
log.Fatal(err)
}
}
if acceptAll || REPLY == "Y" || REPLY == "y" {
cp, err := exec.Command("cp", gitDirFile, localGitDirFile).CombinedOutput()
if err != nil {
fmt.Println(string(cp))
log.Fatal(err)
}
}
} else {
fmt.Printf(" No changes in '%s'.\n", file)
}
}
}
func removeSoftware(templateFilRelative string, gitDir string) {
templateFile := gitDir + "/" + templateFilRelative
toolsetFile := gitDir + "/images/ubuntu/toolsets/toolset-2204.json"
fmt.Println("Disabling software report generation...")
softwareGenBlock := ` provisioner "shell" {
environment_vars = ["IMAGE_VERSION=${var.image_version}", "INSTALLER_SCRIPT_FOLDER=${var.installer_script_folder}"]
inline = ["pwsh -File ${var.image_folder}/SoftwareReport/Generate-SoftwareReport.ps1 -OutputDirectory ${var.image_folder}", "pwsh -File ${var.image_folder}/tests/RunAll-Tests.ps1 -OutputDirectory ${var.image_folder}"]
}
provisioner "file" {
destination = "${path.root}/../Ubuntu2204-Readme.md"
direction = "download"
source = "${var.image_folder}/software-report.md"
}
provisioner "file" {
destination = "${path.root}/../software-report.json"
direction = "download"
source = "${var.image_folder}/software-report.json"
}`
templateFileContentsBytes, err := os.ReadFile(templateFile)
if err != nil {
log.Fatal(err)
}
templateFileContents := string(templateFileContentsBytes)
templateFileNewContents := strings.Replace(templateFileContents, softwareGenBlock, "", 1)
err_ := os.WriteFile(templateFile, []byte(templateFileNewContents), 0644)
if err_ != nil {
log.Fatal(err_)
}
fmt.Printf("Done.\n\n")
fmt.Println("Removing software...")
for _, software := range removeSoftwareList {
fmt.Printf(" Removing install script for '%s'...\n", software)
rmRfScript, err := exec.Command("rm", "-f", gitDir+"/images/ubuntu/scripts/build/install-"+software+".sh").CombinedOutput()
if err != nil {
fmt.Println(string(rmRfScript))
log.Fatal(err)
}
fmt.Printf(" Removing line from Packer configuration for '%s'...\n", software)
replaceScript, err := exec.Command("sed", "-i", "/install-"+software+".sh/d", templateFile).CombinedOutput()
if err != nil {
fmt.Println(string(replaceScript))
log.Fatal(err)
}
// Special case for 'android-sdk' since toolset file uses 'android' instead
if software == "android-sdk" {
software = "android"
}
toolsetFileContentsBytes, err := os.ReadFile(toolsetFile)
if err != nil {
log.Fatal(err)
}
toolsetFileContents := string(toolsetFileContentsBytes)
if strings.Contains(toolsetFileContents, software) {
fmt.Printf(" Removing configuration from '%s' for '%s'...\n\n", toolsetFile, software)
sed, err := exec.Command("sed", "-i", "/ \""+software+"\":/,/ },/d", toolsetFile).CombinedOutput()
if err != nil {
fmt.Println(string(sed))
log.Fatal(err)
}
}
}
fmt.Printf("Done.\n\n")
}
func addSoftware(templateFileRelative string, localDir string, gitDir string) {
templateFile := gitDir + "/" + templateFileRelative
fmt.Println("Adding software...")
for _, software := range addSoftwareList {
err := copyScript(localDir, gitDir, "install-"+software+".sh")
if err != nil {
log.Fatal(err)
}
templateFileContentsBytes, err := os.ReadFile(templateFile)
if err != nil {
log.Fatal(err)
}
templateFileContents := string(templateFileContentsBytes)
if strings.Contains(templateFileContents, "install-"+software+".sh") {
fmt.Printf(" Line for '%s' already exists in Packer configuration.", software)
} else {
fmt.Printf(" Adding line to Packer configuration for '%s'...", software)
templateFileLines := strings.Split(templateFileContents, "\n")
foundLine := false
for i, line := range templateFileLines {
zstdLine := " \"${path.root}/../scripts/build/install-zstd.sh\""
newLine := "\n \"${path.root}/../scripts/build/install-" + software + ".sh\","
// Account for zstd line not having a comma at the end
if line == zstdLine {
templateFileLines[i] = line + "," + newLine
foundLine = true
} else if line == zstdLine+"," {
templateFileLines[i] = line + newLine
foundLine = true
}
}
if !foundLine {
log.Fatal("Could not find line to insert new software.")
}
templateFileOutput := strings.Join(templateFileLines, "\n")
err_ := os.WriteFile(templateFile, []byte(templateFileOutput), 0644)
if err_ != nil {
log.Fatal(err_)
}
}
}
fmt.Printf("\nDone.\n\n")
}
func copyScript(localDir string, gitDir string, scriptName string) error {
script := gitDir + "/images/ubuntu/scripts/build/" + scriptName
localScript := localDir + "/scripts/" + scriptName
if _, err := os.Stat(script); err == nil {
fmt.Printf(" Install script '%s' already exists.\n", scriptName)
if _, err := exec.Command("cmp", "-s", localScript, script).Output(); err == nil {
fmt.Printf(" Install script '%s' is up-to-date.\n", scriptName)
} else {
fmt.Printf(" Install script '%s' is outdated, will update it.\n", scriptName)
cpScript, err := exec.Command("cp", localScript, script).CombinedOutput()
if err != nil {
return fmt.Errorf(
"Error copying install script '%s' to '%s': %s",
localScript,
script,
cpScript,
)
}
}
} else {
fmt.Printf(" Adding install script '%s'...\n", script)
cpScript, err := exec.Command("cp", localScript, script).CombinedOutput()
if err != nil {
return fmt.Errorf(
"Error copying install script '%s' to '%s': %s",
localScript,
script,
cpScript,
)
}
}
return nil
}
func validatePacker(templateFile string) {
fmt.Println("Validating Packer configuration for '" + templateFile + "'...")
packerInit, err := exec.Command("packer", "init", templateFile).CombinedOutput()
if err != nil {
fmt.Println(string(packerInit))
log.Fatal(err)
}
packerValidate, err := exec.Command("packer", "validate", "-var", "managed_image_resource_group_name=test", "-var", "location=westeurope", templateFile).CombinedOutput()
if err != nil {
fmt.Println(string(packerValidate))
log.Fatal(err)
}
fmt.Printf("Done.\n\n")
}
func applyCustomizations(templateFile string, localDir string, gitDir string) {
removeSoftware(templateFile, gitDir)
addSoftware(templateFile, localDir, gitDir)
}
func update(templateFile string, localDir string) {
tmpDir, err := os.MkdirTemp(os.TempDir(), "")
if err != nil {
log.Fatal(err)
}
gitDir := tmpDir + "/runner-images"
defer os.RemoveAll(tmpDir)
fmt.Println("Cloning runner-images repository...")
clone, err := exec.Command("git", "clone", "https://github.com/actions/runner-images.git", "-q", gitDir).CombinedOutput()
if err != nil {
fmt.Println(string(clone))
log.Fatal(err)
}
fmt.Printf("Done.\n\n")
applyCustomizations(templateFile, localDir, gitDir)
filesDirs := []string{
"images/ubuntu",
"helpers",
}
for _, fileDir := range filesDirs {
localGitDir := localDir + "/runner-images"
mkdir, err := exec.Command("mkdir", "-p", localGitDir+"/"+fileDir).CombinedOutput()
if err != nil {
fmt.Println(string(mkdir))
log.Fatal(err)
}
fmt.Printf("Checking differences in '%s'...\n", fileDir)
checkDiff(fileDir, localGitDir, gitDir)
fmt.Printf("Done.\n\n")
}
validatePacker(localDir + "/runner-images/" + templateFile)
}
func main() {
templateFile := "images/ubuntu/templates/ubuntu-22.04.pkr.hcl"
localDir, err := os.Getwd()
if err != nil {
fmt.Println("Error: ", err)
}
if len(os.Args) > 1 && os.Args[1] == "--apply" {
gitDir := localDir + "/runner-images"
applyCustomizations(templateFile, localDir, gitDir)
validatePacker(localDir + "/runner-images/" + templateFile)
} else {
update(templateFile, localDir)
}
}