From cbfa3fe56fd41cab2acd30cc2b99c4d404b39064 Mon Sep 17 00:00:00 2001 From: Michael Masson Date: Thu, 20 May 2021 13:42:40 -0400 Subject: [PATCH] feat(cmd): automatically create parent folders for output file (#36) Co-authored-by: Michael Masson --- cmd/gomarkdoc/command.go | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/cmd/gomarkdoc/command.go b/cmd/gomarkdoc/command.go index c47ae5f..79cc493 100644 --- a/cmd/gomarkdoc/command.go +++ b/cmd/gomarkdoc/command.go @@ -441,7 +441,7 @@ func writeOutput(specs []*PackageSpec, opts commandOptions) error { return err } default: - if err := ioutil.WriteFile(fileName, []byte(text), 0755); err != nil { + if err := writeFile(fileName, text); err != nil { return fmt.Errorf("failed to write output file %s: %w", fileName, err) } } @@ -450,6 +450,22 @@ func writeOutput(specs []*PackageSpec, opts commandOptions) error { return nil } +func writeFile(fileName string, text string) error { + folder := filepath.Dir(fileName) + + if folder != "" { + if err := os.MkdirAll(folder, 0755); err != nil { + return fmt.Errorf("failed to create folder %s: %w", folder, err) + } + } + + if err := ioutil.WriteFile(fileName, []byte(text), 0755); err != nil { + return fmt.Errorf("failed to write file %s: %w", fileName, err) + } + + return nil +} + func checkFile(b *bytes.Buffer, path string) error { checkErr := errors.New("output does not match current files. Did you forget to run gomarkdoc?")