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

fix empty file being written #26

Merged
merged 1 commit into from
Jul 6, 2023
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
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
}