Skip to content

Commit

Permalink
fix empty file being written (#26)
Browse files Browse the repository at this point in the history
  • Loading branch information
adikari authored Jul 6, 2023
1 parent e5d1f83 commit 0ce26f2
Showing 1 changed file with 17 additions and 29 deletions.
46 changes: 17 additions & 29 deletions cmd/export.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,12 +82,26 @@ func exportToFile(p ExportParams) error {
return errors.Wrap(err, "failed to get params")
}

w, err := getFileBuffer(p.output)
file := os.Stdout
if p.output != "" {
directory := filepath.Dir(p.output)

if _, err := os.Stat(directory); errors.Is(err, os.ErrNotExist) {
err := os.MkdirAll(directory, os.ModePerm)
if err != nil {
return errors.Wrap(err, "failed to write file")
}
}

if err != nil {
return errors.Wrap(err, "failed to write file")
if file, err = os.OpenFile(p.output, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
return errors.Wrap(err, "failed to open output file for writing")
}

defer file.Close()
defer file.Sync()
}

w := bufio.NewWriter(file)
defer w.Flush()

params := map[string]string{}
Expand Down Expand Up @@ -204,29 +218,3 @@ func configsToExport(configs []store.ConfigInput, keys []string) ([]store.Config

return result, nil
}

func getFileBuffer(output string) (*bufio.Writer, error) {
if output == "" {
return bufio.NewWriter(os.Stdout), nil
}

directory := filepath.Dir(output)

if _, err := os.Stat(directory); errors.Is(err, os.ErrNotExist) {
err := os.MkdirAll(directory, os.ModePerm)
if err != nil {
return nil, errors.Wrap(err, "failed to write file")
}
}

file, err := os.OpenFile(output, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)

if err != nil {
return nil, errors.Wrap(err, "failed to open output file for writing")
}

defer file.Close()
defer file.Sync()

return bufio.NewWriter(file), nil
}

0 comments on commit 0ce26f2

Please sign in to comment.