Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(cli): skip export dir-empty check #314

Merged
merged 2 commits into from
Jul 6, 2020
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 20 additions & 3 deletions cmd/tk/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ func exportCmd() *cli.Command {
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 {
Expand All @@ -50,8 +51,8 @@ func exportCmd() *cli.Command {
if err != nil {
return fmt.Errorf("Checking target dir: %s", err)
}
if !empty {
return fmt.Errorf("Target dir `%s` not empty. Aborting.", to)
if !empty && !*merge {
return fmt.Errorf("Output dir `%s` not empty. Pass --merge to ignore this", to)
}

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

// 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)
Expand All @@ -102,6 +111,14 @@ func exportCmd() *cli.Command {
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) {
Expand Down