forked from sapcc/helm-charts
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathautofix-beta-apiversions.go
executable file
·94 lines (83 loc) · 2.27 KB
/
autofix-beta-apiversions.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
///usr/bin/go run "$0" "$@"; exit $?
//
// This program can be used to replace deprecated API versions in your Helm templates automatically. Run as:
//
// find $CHART_DIRECTORY/templates -type f -exec go run autofix-beta-apiversions.go {} \;
//
// Then review and commit any changes.
package main
import (
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
)
var (
kindRx = regexp.MustCompile(`^\s*kind:\s*(\S+)\s*$`)
apiVersionRx = regexp.MustCompile(`^\s*apiVersion:\s*(\S+)\s*$`)
isDeprecatedAPIVersion = map[string]bool{
"extensions/v1beta1": true,
"apps/v1beta1": true,
"apps/v1beta2": true,
}
correctAPIVersions = map[string]string{
"NetworkPolicy": "networking.k8s.io/v1",
"PodSecurityPolicy": "policy/v1beta1",
"DaemonSet": "apps/v1",
"Deployment": "apps/v1",
"StatefulSet": "apps/v1",
"Ingress": "networking.k8s.io/v1beta1",
}
)
func main() {
if len(os.Args) < 2 {
fmt.Fprintf(os.Stderr, "usage: %s <yaml-template>...\n", os.Args[0])
os.Exit(1)
}
for _, path := range os.Args[1:] {
contents, err := ioutil.ReadFile(path)
must(err)
lines := strings.SplitAfter(string(contents), "\n")
for idx, line := range lines {
apiVersionMatch := apiVersionRx.FindStringSubmatch(line)
if apiVersionMatch == nil {
continue
}
apiVersion := apiVersionMatch[1]
if !isDeprecatedAPIVersion[apiVersion] {
continue
}
kind := findNearbyKind(lines, idx)
if kind == "" {
fmt.Fprintf(os.Stderr, "%s:%d: cannot find Kind nearby\n", path, idx+1)
os.Exit(1)
}
newAPIVersion := correctAPIVersions[kind]
if newAPIVersion == "" {
fmt.Fprintf(os.Stderr, "%s:%d: do not know how to fix %s/%s\n", path, idx+1, apiVersion, kind)
os.Exit(1)
}
fmt.Printf("%s: autofixing %s/%s -> %s/%s\n", path, apiVersion, kind, newAPIVersion, kind)
lines[idx] = strings.Replace(line, apiVersion, newAPIVersion, 1)
}
must(ioutil.WriteFile(path, []byte(strings.Join(lines, "")), 0666))
}
}
func must(err error) {
if err != nil {
panic(err.Error())
}
}
func findNearbyKind(lines []string, idx int) string {
for i := idx - 3; i <= idx+3; i++ {
if i < 0 || i >= len(lines) {
continue
}
match := kindRx.FindStringSubmatch(lines[i])
if match != nil {
return match[1]
}
}
return ""
}