-
Notifications
You must be signed in to change notification settings - Fork 172
/
Copy pathexport.go
136 lines (113 loc) · 3.55 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
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
package main
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"github.com/go-clix/cli"
"github.com/grafana/tanka/pkg/tanka"
)
// BelRune is a string of the Ascii character BEL which made computers ring in ancient times
// We use it as "magic" char for the subfolder creation as it is a non printable character and thereby will never be
// in a valid filepath by accident. Only when we include it.
const BelRune = string(rune(7))
func exportCmd() *cli.Command {
args := workflowArgs
args.Validator = cli.ValidateExact(2)
cmd := &cli.Command{
Use: "export <environment> <outputDir>",
Short: "write each resources as a YAML file",
Args: args,
}
vars := workflowFlags(cmd.Flags())
getExtCode := extCodeParser(cmd.Flags())
format := cmd.Flags().String("format", "{{.apiVersion}}.{{.kind}}-{{.metadata.name}}", "https://tanka.dev/exporting#filenames")
extension := cmd.Flags().String("extension", "yaml", "File extension")
merge := cmd.Flags().Bool("merge", false, "Allow merging with existing directory")
templateFuncMap := template.FuncMap{
"lower": func(s string) string {
return strings.ToLower(s)
},
}
cmd.Run = func(cmd *cli.Command, args []string) error {
// dir must be empty
to := args[1]
empty, err := dirEmpty(to)
if err != nil {
return fmt.Errorf("Checking target dir: %s", err)
}
if !empty && !*merge {
return fmt.Errorf("Output dir `%s` not empty. Pass --merge to ignore this", to)
}
// exit early if the template is bad
// Replace all os.path separators in string with BelRune for creating subfolders
replacedFormat := strings.Replace(*format, string(os.PathSeparator), BelRune, -1)
tmpl, err := template.New("").Funcs(templateFuncMap).Parse(replacedFormat)
if err != nil {
return fmt.Errorf("Parsing name format: %s", err)
}
// get the manifests
res, err := tanka.Show(args[0],
tanka.WithExtCode(getExtCode()),
tanka.WithTargets(stringsToRegexps(vars.targets)),
)
if err != nil {
return 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)
}
// Replace all os.path separators in string in order to not accidentally create subfolders
name := strings.Replace(buf.String(), string(os.PathSeparator), "-", -1)
// Replace the BEL character inserted with a path separator again in order to create a subfolder
name = strings.Replace(name, BelRune, string(os.PathSeparator), -1)
// Create all subfolders in path
path := filepath.Join(to, name+"."+*extension)
// Abort if already exists
if ok, err := fileExists(path); err != nil {
return err
} else if !ok {
return fmt.Errorf("File '%s' already exists. Aborting", path)
}
// Write file
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return fmt.Errorf("creating filepath '%s': %s", filepath.Dir(path), err)
}
data := m.String()
if err := ioutil.WriteFile(path, []byte(data), 0644); err != nil {
return fmt.Errorf("writing manifest: %s", err)
}
}
return nil
}
return cmd
}
func fileExists(name string) (bool, error) {
_, err := os.Stat(name)
if os.IsNotExist(err) {
return false, nil
}
return err != nil, err
}
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
}