github.com/tobgu/qframe@v0.4.0/cmd/qfgenerate/main.go (about) 1 package main 2 3 import ( 4 "bytes" 5 "flag" 6 "fmt" 7 "go/format" 8 "os" 9 10 bgenerator "github.com/tobgu/qframe/internal/bcolumn" 11 egenerator "github.com/tobgu/qframe/internal/ecolumn" 12 fgenerator "github.com/tobgu/qframe/internal/fcolumn" 13 igenerator "github.com/tobgu/qframe/internal/icolumn" 14 qfgenerator "github.com/tobgu/qframe/internal/qframe/generator" 15 sgenerator "github.com/tobgu/qframe/internal/scolumn" 16 "github.com/tobgu/qframe/qerrors" 17 ) 18 19 /* 20 Simple code generator used in various places to reduce code duplication 21 */ 22 23 func main() { 24 dstFile := flag.String("dst-file", "", "File that the code should be generated to") 25 source := flag.String("source", "", "Which package that code should be generated for") 26 flag.Parse() 27 28 if *dstFile == "" { 29 panic("Destination file must be given") 30 } 31 32 generators := map[string]func() (*bytes.Buffer, error){ 33 "idoc": igenerator.GenerateDoc, 34 "ifilter": igenerator.GenerateFilters, 35 "fdoc": fgenerator.GenerateDoc, 36 "ffilter": fgenerator.GenerateFilters, 37 "bdoc": bgenerator.GenerateDoc, 38 "bfilter": bgenerator.GenerateFilters, 39 "edoc": egenerator.GenerateDoc, 40 "efilter": egenerator.GenerateFilters, 41 "sdoc": sgenerator.GenerateDoc, 42 "sfilter": sgenerator.GenerateFilters, 43 "qframe": qfgenerator.GenerateQFrame, 44 } 45 46 generator, ok := generators[*source] 47 if !ok { 48 panic(fmt.Sprintf("Unknown source: \"%s\"", *source)) 49 } 50 51 buf, err := generator() 52 if err != nil { 53 panic(err) 54 } 55 56 if err := writeFile(buf, *dstFile); err != nil { 57 panic(err) 58 } 59 } 60 61 func writeFile(buf *bytes.Buffer, file string) error { 62 if file == "" { 63 return qerrors.New("writeFile", "Output file must be specified") 64 } 65 66 f, err := os.Create(file) 67 if err != nil { 68 return err 69 } 70 defer f.Close() 71 72 // The equivalent of "go fmt" before writing content 73 src := buf.Bytes() 74 fmtSrc, err := format.Source(src) 75 if err != nil { 76 os.Stdout.WriteString(string(src)) 77 return qerrors.Propagate("Format error", err) 78 } 79 80 _, err = f.Write(fmtSrc) 81 return err 82 }