-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy pathexport.go
89 lines (77 loc) · 1.91 KB
/
export.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
package main
import (
"bytes"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/spf13/cobra"
"github.com/grafana/tanka/pkg/tanka"
)
func exportCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "export <environment> <outputDir>",
Short: "write each resources as a YAML file",
Args: cobra.ExactArgs(2),
Annotations: map[string]string{
"args": "baseDir",
},
}
vars := workflowFlags(cmd.Flags())
getExtCode := extCodeParser(cmd.Flags())
format := cmd.Flags().String("format", "{{.apiVersion}}.{{.kind}}-{{.metadata.name}}", "https://tanka.dev/exporting#filenames")
cmd.Run = func(cmd *cobra.Command, args []string) {
// dir must be empty
to := args[1]
empty, err := dirEmpty(to)
if err != nil {
log.Fatalln("Checking target dir:", err)
}
if !empty {
log.Fatalln("Target dir", to, "not empty. Aborting.")
}
// exit early if the template is bad
tmpl, err := template.New("").Parse(*format)
if err != nil {
log.Fatalln("Parsing name format:", err)
}
// get the manifests
res, err := tanka.Show(args[0],
tanka.WithExtCode(getExtCode()),
tanka.WithTargets(stringsToRegexps(vars.targets)...),
)
if err != nil {
log.Fatalln(err)
}
// write each to a file
for _, m := range res {
buf := bytes.Buffer{}
if err := tmpl.Execute(&buf, m); err != nil {
log.Fatalln("executing name template:", err)
}
name := strings.Replace(buf.String(), "/", "-", -1)
data := m.String()
if err := ioutil.WriteFile(filepath.Join(to, name+".yaml"), []byte(data), 0644); err != nil {
log.Fatalln("Writing manifest:", err)
}
}
}
return cmd
}
func dirEmpty(dir string) (bool, error) {
f, err := os.Open(dir)
if os.IsNotExist(err) {
return true, os.MkdirAll(dir, os.ModePerm)
} else if err != nil {
return false, err
}
defer f.Close()
_, err = f.Readdirnames(1)
if err == io.EOF {
return true, nil
}
return false, err
}