github.com/machinebox/remoto@v0.1.2-0.20191024144331-eff21a7d321f/cmd_generate.go (about) 1 package main 2 3 import ( 4 "fmt" 5 "io" 6 "io/ioutil" 7 "os" 8 "path/filepath" 9 10 "github.com/machinebox/remoto/generator" 11 "github.com/spf13/cobra" 12 ) 13 14 func init() { 15 var outputFile string 16 var generateCmd = &cobra.Command{ 17 Use: "generate definition template", 18 Short: "Generate source code from a template and remoto definition.", 19 Args: cobra.ExactArgs(2), 20 21 Run: func(cmd *cobra.Command, args []string) { 22 definition := args[0] 23 template := args[1] 24 f, err := os.Open(definition) 25 if err != nil { 26 fmt.Fprintf(os.Stderr, "%v\n", err) 27 os.Exit(1) 28 } 29 defer f.Close() 30 def, err := generator.Parse(f) 31 if err != nil { 32 fmt.Fprintf(os.Stderr, "parse: %v\n", err) 33 os.Exit(1) 34 } 35 var o io.Writer = os.Stdout 36 if outputFile != "" { 37 if err := os.MkdirAll(filepath.Dir(outputFile), 0777); err != nil { 38 fmt.Fprintf(os.Stderr, "%v\n", err) 39 os.Exit(1) 40 } 41 outFile, err := os.Create(outputFile) 42 if err != nil { 43 fmt.Fprintf(os.Stderr, "parse: %v\n", err) 44 os.Exit(1) 45 } 46 defer outFile.Close() 47 o = outFile 48 } 49 b, err := ioutil.ReadFile(template) 50 if err != nil { 51 fmt.Fprintf(os.Stderr, "template: %v\n", err) 52 os.Exit(1) 53 } 54 if err := generator.Render(o, template, string(b), def); err != nil { 55 fmt.Fprintf(os.Stderr, "render template: %v\n", err) 56 os.Exit(1) 57 } 58 }, 59 } 60 generateCmd.Flags().StringVarP(&outputFile, "output", "o", "", "output file (default stdout)") 61 rootCmd.AddCommand(generateCmd) 62 }