github.com/mineiros-io/terradoc@v0.0.9-0.20220711062319-018bd4ae81f5/cmd/terradoc/cli/generate.go (about) 1 package cli 2 3 import ( 4 "fmt" 5 "io" 6 "os" 7 8 "github.com/mineiros-io/terradoc/internal/parsers/docparser" 9 "github.com/mineiros-io/terradoc/internal/renderers/markdown" 10 ) 11 12 type GenerateCmd struct { 13 InputFile string `arg:"" required:"" help:"Input file." type:"existingfile"` 14 OutputFile string `name:"output" short:"o" optional:"" default:"-" help:"Output file to write resulting markdown to" type:"path"` 15 } 16 17 func (g GenerateCmd) Run() error { 18 r, rCloser, err := openInput(g.InputFile) 19 if err != nil { 20 return err 21 } 22 defer rCloser() 23 24 w, wCloser, err := getOutputWriter(g.OutputFile) 25 if err != nil { 26 return err 27 } 28 defer wCloser() 29 30 def, err := docparser.Parse(r, r.Name()) 31 if err != nil { 32 return fmt.Errorf("parsing input: %v", err) 33 } 34 35 err = markdown.Render(w, def) 36 if err != nil { 37 return fmt.Errorf("rendering document: %v", err) 38 } 39 40 return nil 41 } 42 43 func openInput(path string) (*os.File, func(), error) { 44 if path == "-" { 45 return os.Stdin, noopClose, nil 46 } 47 48 f, err := os.Open(path) 49 if err != nil { 50 return nil, nil, fmt.Errorf("opening input %q: %v", path, err) 51 } 52 53 closer := func() { 54 if err := f.Close(); err != nil { 55 fmt.Fprintf(os.Stderr, "closing input stream: %v", err) 56 } 57 } 58 59 return f, closer, nil 60 } 61 62 func getOutputWriter(filename string) (io.Writer, func(), error) { 63 if filename == "-" { 64 return os.Stdout, noopClose, nil 65 } 66 67 f, err := os.Create(filename) 68 if err != nil { 69 return nil, nil, err 70 } 71 72 closer := func() { 73 if err := f.Close(); err != nil { 74 fmt.Fprintf(os.Stderr, "closing output stream: %v", err) 75 } 76 } 77 78 return f, closer, nil 79 } 80 81 func noopClose() {}