/
kustomization.go
109 lines (88 loc) · 2.49 KB
/
kustomization.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
package flow
import (
"context"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
securejoin "github.com/cyphar/filepath-securejoin"
"github.com/lunarway/release-manager/internal/log"
"github.com/pkg/errors"
yaml "gopkg.in/yaml.v2"
)
type kustomizationSpec struct {
APIVersion string `yaml:"apiVersion"`
Kind string `yaml:"kind"`
}
func kustomizationExists(directory string) (string, error) {
var filePath string
err := filepath.WalkDir(directory, func(path string, d fs.DirEntry, err error) error {
if err != nil {
return errors.WithMessagef(err, "walk dir '%s'", directory)
}
if filePath != "" {
return nil
}
if d.IsDir() {
return nil
}
file, err := os.OpenFile(path, os.O_RDWR, os.ModePerm)
if err != nil {
return errors.WithMessagef(err, "open file '%s'", path)
}
var spec kustomizationSpec
// no need to handle non-YAML files as the decoder does the right thing
err = yaml.NewDecoder(file).Decode(&spec)
if err != nil {
if errors.Cause(err) != io.EOF {
return errors.WithMessagef(err, "decode '%s'", path)
}
}
if strings.HasPrefix(spec.APIVersion, "kustomize.toolkit.fluxcd.io/") && spec.Kind == "Kustomization" {
filePath = path
}
return nil
})
if err != nil {
return "", errors.WithMessage(err, "walk directory")
}
return filePath, nil
}
func moveKustomizationToClusters(ctx context.Context, srcPath, root, service, env, namespace string) error {
destDir, err := kustomizationPath(root, env, namespace)
if err != nil {
return errors.WithMessage(err, "assemble kustomization path")
}
err = os.MkdirAll(destDir, os.ModePerm)
if err != nil {
return errors.WithMessagef(err, "create dest dir '%s'", destDir)
}
destPath, err := securejoin.SecureJoin(destDir, fmt.Sprintf("%s.yaml", service))
if err != nil {
return errors.WithMessage(err, "secure join destination path")
}
log.WithContext(ctx).Infof("moveKustomizationToClusters: destPath '%s'", destPath)
err = os.Rename(srcPath, destPath)
if err != nil {
return errors.WithMessagef(err, "move src '%s' to '%s'", srcPath, destPath)
}
return nil
}
func kustomizationPath(root, env, namespace string) (string, error) {
kustomizationPath := root // start with root
pathsToJoin := []string{
"clusters",
env,
namespace,
}
var err error
for _, p := range pathsToJoin {
kustomizationPath, err = securejoin.SecureJoin(kustomizationPath, p)
if err != nil {
return "", errors.WithMessagef(err, "join '%s' to path", p)
}
}
return kustomizationPath, nil
}