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?")