Skip to content

Commit a1df9fa

Browse files
authored
feat(cli): skip export dir-empty check (#314)
* feat(cli): skip export dir-empty check Adds a `--force` flag to `tk export` to skip the check that makes sure the output dir is empty. This can be used to merge resources of multiple environments into a single tree * feat: check for file existence
1 parent 5bc160a commit a1df9fa

File tree

1 file changed

+20
-3
lines changed

1 file changed

+20
-3
lines changed

cmd/tk/export.go

+20-3
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ func exportCmd() *cli.Command {
3636
getExtCode := extCodeParser(cmd.Flags())
3737
format := cmd.Flags().String("format", "{{.apiVersion}}.{{.kind}}-{{.metadata.name}}", "https://tanka.dev/exporting#filenames")
3838
extension := cmd.Flags().String("extension", "yaml", "File extension")
39+
merge := cmd.Flags().Bool("merge", false, "Allow merging with existing directory")
3940

4041
templateFuncMap := template.FuncMap{
4142
"lower": func(s string) string {
@@ -50,8 +51,8 @@ func exportCmd() *cli.Command {
5051
if err != nil {
5152
return fmt.Errorf("Checking target dir: %s", err)
5253
}
53-
if !empty {
54-
return fmt.Errorf("Target dir `%s` not empty. Aborting.", to)
54+
if !empty && !*merge {
55+
return fmt.Errorf("Output dir `%s` not empty. Pass --merge to ignore this", to)
5556
}
5657

5758
// exit early if the template is bad
@@ -87,10 +88,18 @@ func exportCmd() *cli.Command {
8788

8889
// Create all subfolders in path
8990
path := filepath.Join(to, name+"."+*extension)
91+
92+
// Abort if already exists
93+
if ok, err := fileExists(path); err != nil {
94+
return err
95+
} else if !ok {
96+
return fmt.Errorf("File '%s' already exists. Aborting", path)
97+
}
98+
99+
// Write file
90100
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
91101
return fmt.Errorf("creating filepath '%s': %s", filepath.Dir(path), err)
92102
}
93-
94103
data := m.String()
95104
if err := ioutil.WriteFile(path, []byte(data), 0644); err != nil {
96105
return fmt.Errorf("writing manifest: %s", err)
@@ -102,6 +111,14 @@ func exportCmd() *cli.Command {
102111
return cmd
103112
}
104113

114+
func fileExists(name string) (bool, error) {
115+
_, err := os.Stat(name)
116+
if os.IsNotExist(err) {
117+
return false, nil
118+
}
119+
return err != nil, err
120+
}
121+
105122
func dirEmpty(dir string) (bool, error) {
106123
f, err := os.Open(dir)
107124
if os.IsNotExist(err) {

0 commit comments

Comments
 (0)