This repository has been archived by the owner on Nov 29, 2022. It is now read-only.
generated from ministryofjustice/template-repository
-
Notifications
You must be signed in to change notification settings - Fork 0
/
patch.go
533 lines (470 loc) · 13 KB
/
patch.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
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
package main
import (
"bytes"
"context"
"flag"
"fmt"
"io"
"log"
"os"
"path/filepath"
git "github.com/go-git/go-git/v5"
"github.com/go-git/go-git/v5/plumbing"
"github.com/go-git/go-git/v5/plumbing/transport/http"
"github.com/google/go-github/v48/github"
"golang.org/x/oauth2"
"golang.org/x/sync/errgroup"
"gopkg.in/yaml.v3"
)
type repository struct {
Name string
LocalRepo *git.Repository
Reference *plumbing.Reference
Worktree *git.Worktree
Template *template
Head string
}
type template struct {
Ing ingress
Dep deployment
Svc service
}
type manifest struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
}
type deployment struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Metadata struct {
Name string `yaml:"name"`
} `yaml:"metadata"`
Spec struct {
Replicas int `yaml:"replicas"`
Selector struct {
MatchLabels struct {
App string `yaml:"app"`
} `yaml:"matchLabels"`
} `yaml:"selector"`
Template struct {
Metadata struct {
Labels struct {
App string `yaml:"app"`
} `yaml:"labels"`
} `yaml:"metadata"`
Spec struct {
Containers []struct {
Name string `yaml:"name"`
Image string `yaml:"image"`
Env []struct {
Name string `yaml:"name"`
ValueFrom struct {
SecretKeyRef struct {
Name string `yaml:"name"`
Key string `yaml:"key"`
} `yaml:"secretKeyRef"`
} `yaml:"valueFrom"`
} `yaml:"env"`
Ports []struct {
ContainerPort int `yaml:"containerPort"`
} `yaml:"ports"`
} `yaml:"containers"`
} `yaml:"spec"`
} `yaml:"template"`
} `yaml:"spec"`
}
type service struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Metadata struct {
Name string `yaml:"name"`
Labels struct {
App string `yaml:"app"`
} `yaml:"labels"`
} `yaml:"metadata"`
Spec struct {
Ports []struct {
Port int `yaml:"port"`
Name string `yaml:"name"`
TargetPort int `yaml:"targetPort"`
} `yaml:"ports"`
Selector struct {
App string `yaml:"app"`
} `yaml:"selector"`
} `yaml:"spec"`
}
type ingress struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
Metadata struct {
Name string `yaml:"name"`
Annotations struct {
ExternalDNSAlphaKubernetesIoSetIdentifier string `yaml:"external-dns.alpha.kubernetes.io/set-identifier"`
ExternalDNSAlphaKubernetesIoAwsWeight string `yaml:"external-dns.alpha.kubernetes.io/aws-weight"`
} `yaml:"annotations"`
} `yaml:"metadata"`
Spec struct {
IngressClassName string `yaml:"ingressClassName"`
TLS []struct {
Hosts []string `yaml:"hosts"`
} `yaml:"tls"`
Rules []struct {
Host string `yaml:"host"`
HTTP struct {
Paths []struct {
Path string `yaml:"path"`
PathType string `yaml:"pathType"`
Backend struct {
Service struct {
Name string `yaml:"name"`
Port struct {
Number int `yaml:"number"`
} `yaml:"port"`
} `yaml:"service"`
} `yaml:"backend"`
} `yaml:"paths"`
} `yaml:"http"`
} `yaml:"rules"`
} `yaml:"spec"`
}
func main() {
const (
base = "https://github.com/ministryofjustice/"
newApi = "networking.k8s.io/v1"
oldApi = "networking.k8s.io/v1beta1"
message = "Update ingress apiVersion to networking.k8s.io/v1 and format yaml"
branchName = "ingress-patch"
fileName = "kubernetes-deploy.tpl"
tempDir = "./tmp/"
)
var (
user = flag.String("u", "", "github username")
pass = flag.String("p", "", "github password")
)
flag.Parse()
// create the github client
client, err := createGitHubClient(*pass)
if err != nil {
log.Fatal(err)
}
// define a slice of repositories to patch
repos := []string{
// "apply-for-compensation-prototype",
// "apply-for-legal-aid-prototype",
// "book-a-prison-visit-prototype",
// "dex-ia-proto",
// "eligibility-estimate",
// "hmpps-assess-risks-and-needs-prototypes",
// "hmpps-incentives-tool",
// "hmpps-interventions-prototype",
// "hmpps-licenses-prototype",
// "hmpps-manage-supervisions-prototype",
// "hmpps-prepare-a-case-prototype",
// "hmpps-prisoner-education",
// "interventions-design-history",
"jason-design-demo",
// "laa-crime-apply-prototype",
// "laa-view-court-data-prototype",
// "makerecall-prototype",
// "manage-supervisions-design-history",
// "opg-lpa-fd-prototype",
// "opg-sirius-prototypes",
// "request-info-from-moj",
// "send-legal-mail-prototype",
}
if err := prepareTempDir(tempDir); err != nil {
log.Fatal(err)
}
defer func() {
err = cleanTempDir(tempDir)
if err != nil {
log.Println(err)
}
}()
repositories, err := createRepositories(base, *user, *pass, repos)
if err != nil {
log.Printf("error creating repositories: %v", err)
}
g := new(errgroup.Group)
for _, repo := range repositories {
repo := repo
g.Go(func() error {
fmt.Println("cloning " + repo.Name)
if err = repo.Checkout(branchName); err != nil {
return fmt.Errorf("error checking out branch on repo %s: %v", repo.Name, err)
}
kFile := filepath.Join(repo.Name, fileName)
b, err := os.ReadFile(kFile)
if err != nil {
return fmt.Errorf("unable to find file %v: %e", kFile, err)
}
if err := repo.PatchIngress(newApi, b); err != nil {
return fmt.Errorf("error patching ingress on repo %s: %v", repo.Name, err)
}
file, err := createKubernetesDeploy(kFile)
if err != nil {
return fmt.Errorf("error creating kubernetes deploy file on repo %s: %v", repo.Name, err)
}
defer file.Close()
if err := repo.writeYaml(file); err != nil {
return fmt.Errorf("error writing yaml: %v", err)
}
if err := repo.createPullRequest(*user, *pass, message, branchName, client); err != nil {
return fmt.Errorf("error creating pull request on repo %s: %v", repo.Name, err)
}
fmt.Printf("/n---/ncreated pull request on " + "https://github.com/ministryofjustice/" + repo.Name)
fmt.Println("url located at: https://" + repo.Name + "cloud-platform.service.justice.gov.uk")
return err
})
}
if err := g.Wait(); err != nil {
log.Println(err)
} else {
fmt.Println("finished")
}
}
func cleanTempDir(dir string) error {
err := os.Chdir("..")
if err != nil {
return err
}
return os.RemoveAll(dir)
}
func createRepositories(base, user, pass string, repos []string) ([]repository, error) {
var repositories []repository
for _, repo := range repos {
repository, err := NewRepository(base, repo, user, pass)
if err != nil {
return nil, fmt.Errorf("failed to clone %s: %v", repo, err)
}
repositories = append(repositories, *repository)
}
return repositories, nil
}
func createGitHubClient(pass string) (*github.Client, error) {
if pass == "" {
return nil, fmt.Errorf("no github token provided")
}
ctx := context.Background()
ts := oauth2.StaticTokenSource(
&oauth2.Token{AccessToken: pass},
)
tc := oauth2.NewClient(ctx, ts)
client := github.NewClient(tc)
return client, nil
}
func prepareTempDir(path string) error {
// loop through repositories and git clone
err := os.Mkdir(path, 0755)
if err != nil {
return err
}
err = os.Chdir(path)
if err != nil {
return err
}
return nil
}
func NewRepository(base, repo, user, pass string) (*repository, error) {
localRepo, err := git.PlainClone(repo, false, &git.CloneOptions{
URL: base + repo,
Auth: &http.BasicAuth{
Username: user,
Password: pass,
},
})
if err != nil {
return nil, fmt.Errorf("cloning error %s: %v", repo, err)
}
// Get HEAD ref from repository
ref, err := localRepo.Head()
if err != nil {
return nil, err
}
// Get the worktree for the local repository
tree, err := localRepo.Worktree()
if err != nil {
return nil, err
}
t := &template{}
return &repository{
Name: repo,
LocalRepo: localRepo,
Reference: ref,
Worktree: tree,
Template: t,
Head: ref.Name().Short(),
}, nil
}
func (r *repository) Checkout(branch string) error {
err := r.Worktree.Checkout(&git.CheckoutOptions{
Hash: r.Reference.Hash(),
Branch: plumbing.NewBranchReferenceName(branch),
Create: true,
})
if err != nil {
return err
}
return nil
}
func (r *repository) PatchIngress(newApi string, yamlFile []byte) error {
allByteSlices, err := splitYAML(yamlFile)
if err != nil {
return fmt.Errorf("failed to split yaml for %s: %v", r.Name, err)
}
for _, byteSlice := range allByteSlices {
var t manifest
err := yaml.Unmarshal(byteSlice, &t)
if err != nil {
return fmt.Errorf("failed to unmarshal yaml for %s: %v", r.Name, err)
}
// case switch to create a deployment, service and ingress
switch t.Kind {
case "Ingress":
err := yaml.Unmarshal(byteSlice, &r.Template.Ing)
if err != nil {
return fmt.Errorf("failed to unmarshal yaml for %s: %v", r.Name, err)
}
case "Deployment":
err := yaml.Unmarshal(byteSlice, &r.Template.Dep)
if err != nil {
return fmt.Errorf("failed to unmarshal yaml for %s: %v", r.Name, err)
}
case "Service":
err := yaml.Unmarshal(byteSlice, &r.Template.Svc)
if err != nil {
return fmt.Errorf("failed to unmarshal yaml for %s: %v", r.Name, err)
}
}
}
if r.Template.Ing.APIVersion == newApi {
return fmt.Errorf("api version already set to %s", newApi)
}
// Move ingress to the new controller
r.Template.Ing.Spec.IngressClassName = "default"
// Change the ingress API to the new version
r.Template.Ing.APIVersion = newApi
// Add specfic pathtype
r.Template.Ing.Spec.Rules[0].HTTP.Paths[0].PathType = "ImplementationSpecific"
// Add new service data
r.Template.Ing.Spec.Rules[0].HTTP.Paths[0].Backend.Service.Name = r.Template.Svc.Metadata.Name
r.Template.Ing.Spec.Rules[0].HTTP.Paths[0].Backend.Service.Port.Number = r.Template.Svc.Spec.Ports[0].Port
return nil
}
func createKubernetesDeploy(filePath string) (*os.File, error) {
err := os.Remove(filePath)
if err != nil {
return nil, fmt.Errorf("failed to remove file for %s: %v", filePath, err)
}
// write the new ingress to the file
f, err := os.Create(filePath)
if err != nil {
return nil, fmt.Errorf("failed to create file for %s: %v", filePath, err)
}
return f, nil
}
func (r *repository) writeYaml(f *os.File) error {
// write the new ingress to the file
templates := []any{
r.Template.Dep,
r.Template.Svc,
r.Template.Ing,
}
for _, template := range templates {
y, err := yaml.Marshal(template)
if err != nil {
return fmt.Errorf("failed to marshal yaml for %s: %v", r.Name, err)
}
// write any to a file
_, err = f.Write(y)
if err != nil {
return fmt.Errorf("failed to write to file for %s: %v", r.Name, err)
}
_, err = f.WriteString("\n---\n\n")
if err != nil {
return fmt.Errorf("failed to write to file for %s: %v", r.Name, err)
}
}
return nil
}
func stageChanges(repo string, worktree *git.Worktree) error {
status, err := worktree.Status()
if err != nil {
return fmt.Errorf("failed to get status for %s: %v", repo, err)
}
if status.IsClean() {
log.Printf("no changes for %s", repo)
}
for path := range status {
if status.IsUntracked(path) {
_, err := worktree.Add(path)
if err != nil {
log.Printf("failed to add file for %s: %v", repo, err)
}
}
}
return nil
}
func (r *repository) createPullRequest(user, password, message, branchName string, client *github.Client) error {
if err := stageChanges(r.Name, r.Worktree); err != nil {
return fmt.Errorf("failed to stage changes for %s: %v", r.Name, err)
}
if err := commitChanges(user, password, r.Name, r.LocalRepo, r.Worktree, message); err != nil {
return fmt.Errorf("failed to commit changes for %s: %v", r.Name, err)
}
if err := prChanges(r.Head, r.Name, message, branchName, *client); err != nil {
return fmt.Errorf("failed to push changes for %s: %v", r.Name, err)
}
return nil
}
func prChanges(head, repo, message, branchName string, client github.Client) error {
createPR := &github.NewPullRequest{
Title: github.String(message),
Head: github.String(string(branchName)),
Base: github.String(head),
}
_, _, err := client.PullRequests.Create(context.Background(), "ministryofjustice", repo, createPR)
if err != nil {
return fmt.Errorf("failed to create pull request for %s: %v", repo, err)
}
return nil
}
func commitChanges(user, password, repo string, localRepo *git.Repository, worktree *git.Worktree, message string) error {
_, err := worktree.Commit(message, &git.CommitOptions{
All: true,
})
if err != nil {
log.Printf("failed to commit for %s: %v", repo, err)
}
err = localRepo.Push(&git.PushOptions{
RemoteName: "origin",
Auth: &http.BasicAuth{
Username: user,
Password: password,
},
})
if err != nil {
return fmt.Errorf("failed to push for %s: %v", repo, err)
}
return nil
}
func splitYAML(resources []byte) ([][]byte, error) {
dec := yaml.NewDecoder(bytes.NewReader(resources))
var res [][]byte
for {
var value any
err := dec.Decode(&value)
if err == io.EOF {
break
}
if err != nil {
return nil, err
}
valueBytes, err := yaml.Marshal(value)
if err != nil {
return nil, err
}
res = append(res, valueBytes)
}
return res, nil
}