/
utils.go
78 lines (60 loc) · 1.58 KB
/
utils.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
package generators
import (
"bufio"
"io/ioutil"
"os"
"regexp"
"strings"
"github.com/ghodss/yaml"
"github.com/golang/glog"
)
// Pattern used to detect if a line contains a YAML key
var yamlKeyPattern = regexp.MustCompile("^[^ :]*:")
// writeYamlFile write a given interface into yaml
func writeYamlFile(filePath string, data interface{}) error {
output, err := yaml.Marshal(data)
if err != nil {
return err
}
return writeFile(filePath, output, 0644)
}
// writeAndFormatKustomizationConfig adds line break and comments
func writeAndFormatKustomizationConfig(filePath string, comments bool) error {
glog.V(4).Infof("Formatting %s", filePath)
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
var output []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
// add line break before comment except for if this is the first line
if yamlKeyPattern.MatchString(line) && len(output) > 0 {
output = append(output, "")
}
// add comments
if comments {
for key, value := range commentsMapping {
if strings.HasPrefix(line, key+":") {
output = append(output, value)
}
}
}
output = append(output, line)
}
if err := scanner.Err(); err != nil {
return err
}
return writeFile(filePath, []byte(strings.Join(output, "\n")), 0644)
}
// writeFile writes data to a file named by filename.
func writeFile(filePath string, data []byte, perm os.FileMode) error {
glog.V(4).Infof("Writing %s", filePath)
err := ioutil.WriteFile(filePath, data, perm)
if err != nil {
return err
}
return nil
}