func getTypewriterImports(c config) (typewriter.ImportSpecSet, error) { imports := typewriter.NewImportSpecSet() // check for existence of custom file if src, err := os.Open(c.customName); err == nil { defer src.Close() // custom file exists, parse its imports fset := token.NewFileSet() f, err := parser.ParseFile(fset, "", src, parser.ImportsOnly) if err != nil { return imports, err } // convert ast imports into ImportSpecs for _, v := range f.Imports { imp := typewriter.ImportSpec{ Name: v.Name.Name, Path: strings.Trim(v.Path.Value, `"`), // lose the quotes } imports.Add(imp) } } else { // doesn't exist, use standard (clone it) imports = stdImports.Clone() } return imports, nil }
func run(c config) error { imports := typewriter.NewImportSpecSet( typewriter.ImportSpec{Path: "fmt"}, typewriter.ImportSpec{Path: "os"}, typewriter.ImportSpec{Path: "regexp"}, typewriter.ImportSpec{Path: "github.com/rickb777/typewriter"}, ) return execute(runStandard, c, imports, runTmpl) }
package main import ( "io" "os" "github.com/rickb777/typewriter" ) type config struct { out io.Writer customName string *typewriter.Config } var defaultConfig = config{ out: os.Stdout, customName: "_gen.go", Config: &typewriter.Config{}, } // keep in sync with imports.go var stdImports = typewriter.NewImportSpecSet( typewriter.ImportSpec{Name: "_", Path: "github.com/rickb777/slice"}, typewriter.ImportSpec{Name: "_", Path: "github.com/rickb777/stringer"}, )
func TestRun(t *testing.T) { // use custom name so test won't interfere with a real _gen.go c := defaultConfig c.customName = "_gen_run_test.go" sliceName := "dummy_slice_test.go" fooName := "dummy_foo_test.go" // standard run if err := run(c); err != nil { t.Fatal(err) } // gen file should exist if _, err := os.Stat(sliceName); err != nil { t.Error(err) } // foo file should not exist, not a standard typewriter if _, err := os.Stat(fooName); err == nil { t.Errorf("%s should not have been generated", fooName) } // remove just-gen'd file if err := os.Remove(sliceName); err != nil { t.Fatal(err) } // create a custom typewriter import file imports := typewriter.NewImportSpecSet( typewriter.ImportSpec{Name: "_", Path: "github.com/rickb777/foowriter"}, ) if err := createCustomFile(c, imports); err != nil { t.Fatal(err) } // custom run if err := run(c); err != nil { t.Error(err) } // clean up custom file, no longer needed if err := os.Remove(c.customName); err != nil { t.Fatal(err) } // foo file should exist if _, err := os.Stat(fooName); err != nil { t.Error(err) } // clean up foo file if err := os.Remove(fooName); err != nil { t.Fatal(err) } // gen file should not exist, because it was not included in the custom file if _, err := os.Stat(sliceName); err == nil { t.Errorf("%s should not have been generated", sliceName) } }