func gen(t *testing.T, code string, types string) string { file := getFile(t, code) c, err := concrete.New(types) assert.NoError(t, err) gen := New(file, c) assert.NoError(t, err) var buf bytes.Buffer err = gen.Do("", &buf) assert.NoError(t, err) return buf.String() }
func main() { tem := flag.String("tem", "", "name of the template go file") out := flag.String("out", "", "name of the new source file") pac := flag.String("pac", "", "package name in the created file") gen := flag.String("gen", "", "concrete types e.g string,int;string,double64") imp := flag.Bool("imp", true, "run go imports") flag.Parse() // read the source file fset := token.NewFileSet() ast, err := parser.ParseFile(fset, *tem, nil, parser.ParseComments) if err != nil { fmt.Println("reading source file: ", err) return } // prepeare the concrete types c, err := concrete.New(*gen) if err != nil { fmt.Println("processing concrete types: ", err) return } // create output name outName, err := names.CreateOutName(*out, *tem, message) if err != nil { fmt.Println(err) return } packageName, err := names.GetPackageName(*pac, outName) if err != nil { fmt.Println(err) return } // generify the source file gener := generify.New(ast, c) var buffer = new(bytes.Buffer) buffer.WriteString(message) err = gener.Do(packageName, buffer) if err != nil { fmt.Println(err) return } var output []byte if *imp { // run go imports output, err = imports.Process("", buffer.Bytes(), nil) if err != nil { fmt.Println("go imports has an error, try -imp=false: ", err) return } } else { output = buffer.Bytes() } // write the output file, err := os.Create(outName) if err != nil { fmt.Println("error creating output file: ", err) return } defer file.Close() _, err = file.Write(output) if err != nil { fmt.Println("error writing output file: ", err) return } fmt.Println("generated ", outName) }