-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
util.go
244 lines (222 loc) · 5.79 KB
/
util.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
/*
Copyright 2019 The Kubernetes Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package util
import (
"bufio"
"bytes"
"crypto/rand"
"errors"
"fmt"
"io/ioutil"
"math/big"
"os"
"regexp"
"strings"
)
const (
// KubebuilderBinName define the name of the kubebuilder binary to be used in the tests
KubebuilderBinName = "kubebuilder"
)
// RandomSuffix returns a 4-letter string.
func RandomSuffix() (string, error) {
source := []rune("abcdefghijklmnopqrstuvwxyz")
res := make([]rune, 4)
for i := range res {
bi := new(big.Int)
r, err := rand.Int(rand.Reader, bi.SetInt64(int64(len(source))))
if err != nil {
return "", err
}
res[i] = source[r.Int64()]
}
return string(res), nil
}
// GetNonEmptyLines converts given command output string into individual objects
// according to line breakers, and ignores the empty elements in it.
func GetNonEmptyLines(output string) []string {
var res []string
elements := strings.Split(output, "\n")
for _, element := range elements {
if element != "" {
res = append(res, element)
}
}
return res
}
// InsertCode searches target content in the file and insert `toInsert` after the target.
func InsertCode(filename, target, code string) error {
// false positive
// nolint:gosec
contents, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
idx := strings.Index(string(contents), target)
if idx == -1 {
return fmt.Errorf("string %s not found in %s", target, string(contents))
}
out := string(contents[:idx+len(target)]) + code + string(contents[idx+len(target):])
// false positive
// nolint:gosec
return ioutil.WriteFile(filename, []byte(out), 0644)
}
// UncommentCode searches for target in the file and remove the comment prefix
// of the target content. The target content may span multiple lines.
func UncommentCode(filename, target, prefix string) error {
// false positive
// nolint:gosec
content, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
strContent := string(content)
idx := strings.Index(strContent, target)
if idx < 0 {
return fmt.Errorf("unable to find the code %s to be uncomment", target)
}
out := new(bytes.Buffer)
_, err = out.Write(content[:idx])
if err != nil {
return err
}
scanner := bufio.NewScanner(bytes.NewBufferString(target))
if !scanner.Scan() {
return nil
}
for {
_, err := out.WriteString(strings.TrimPrefix(scanner.Text(), prefix))
if err != nil {
return err
}
// Avoid writing a newline in case the previous line was the last in target.
if !scanner.Scan() {
break
}
if _, err := out.WriteString("\n"); err != nil {
return err
}
}
_, err = out.Write(content[idx+len(target):])
if err != nil {
return err
}
// false positive
// nolint:gosec
return ioutil.WriteFile(filename, out.Bytes(), 0644)
}
// ImplementWebhooks will mock an webhook data
func ImplementWebhooks(filename string) error {
// false positive
// nolint:gosec
bs, err := ioutil.ReadFile(filename)
if err != nil {
return err
}
str := string(bs)
str, err = EnsureExistAndReplace(
str,
"import (",
`import (
"errors"`)
if err != nil {
return err
}
// implement defaulting webhook logic
str, err = EnsureExistAndReplace(
str,
"// TODO(user): fill in your defaulting logic.",
`if r.Spec.Count == 0 {
r.Spec.Count = 5
}`)
if err != nil {
return err
}
// implement validation webhook logic
str, err = EnsureExistAndReplace(
str,
"// TODO(user): fill in your validation logic upon object creation.",
`if r.Spec.Count < 0 {
return errors.New(".spec.count must >= 0")
}`)
if err != nil {
return err
}
str, err = EnsureExistAndReplace(
str,
"// TODO(user): fill in your validation logic upon object update.",
`if r.Spec.Count < 0 {
return errors.New(".spec.count must >= 0")
}`)
if err != nil {
return err
}
// false positive
// nolint:gosec
return ioutil.WriteFile(filename, []byte(str), 0644)
}
// EnsureExistAndReplace check if the content exists and then do the replace
func EnsureExistAndReplace(input, match, replace string) (string, error) {
if !strings.Contains(input, match) {
return "", fmt.Errorf("can't find %q", match)
}
return strings.Replace(input, match, replace, -1), nil
}
// ReplaceInFile replaces all instances of old with new in the file at path.
func ReplaceInFile(path, old, new string) error {
info, err := os.Stat(path)
if err != nil {
return err
}
// false positive
// nolint:gosec
b, err := ioutil.ReadFile(path)
if err != nil {
return err
}
if !strings.Contains(string(b), old) {
return errors.New("unable to find the content to be replaced")
}
s := strings.Replace(string(b), old, new, -1)
err = ioutil.WriteFile(path, []byte(s), info.Mode())
if err != nil {
return err
}
return nil
}
// ReplaceRegexInFile finds all strings that match `match` and replaces them
// with `replace` in the file at path.
func ReplaceRegexInFile(path, match, replace string) error {
matcher, err := regexp.Compile(match)
if err != nil {
return err
}
info, err := os.Stat(path)
if err != nil {
return err
}
// false positive
// nolint:gosec
b, err := ioutil.ReadFile(path)
if err != nil {
return err
}
s := matcher.ReplaceAllString(string(b), replace)
if s == string(b) {
return errors.New("unable to find the content to be replaced")
}
err = ioutil.WriteFile(path, []byte(s), info.Mode())
if err != nil {
return err
}
return nil
}