From 33821928c920fca1bbc5de4491e44037f4407258 Mon Sep 17 00:00:00 2001 From: Greg Date: Mon, 6 Aug 2018 12:11:15 -0400 Subject: [PATCH] Move all file handling into main.go. --- cmd/pgen/gen.go | 29 ++++------------------------- cmd/pgen/main.go | 30 +++++++++++++++++++++++++++++- 2 files changed, 33 insertions(+), 26 deletions(-) diff --git a/cmd/pgen/gen.go b/cmd/pgen/gen.go index 2e25d3c..c13cb4c 100644 --- a/cmd/pgen/gen.go +++ b/cmd/pgen/gen.go @@ -1,16 +1,14 @@ package main import ( - "path/filepath" + "io" "log" "go/ast" "go/format" "go/parser" "go/token" "golang.org/x/tools/go/ast/astutil" - "os" "regexp" - "strings" ) type subspec struct { @@ -91,16 +89,6 @@ var ( ) func init() { - fs,err := filepath.Glob("pgen*.go") - if err != nil { - log.Fatal("Glob error") - } - for _,f := range(fs) { - err := os.Remove(f) - if err != nil && os.IsExist(err) { - log.Fatal("Removing ",f,err) - } - } qexp = regexp.MustCompile(`"`) } @@ -153,24 +141,15 @@ func (g *Generator) Import(name string) { astutil.AddImport(g.fset, g.nodes, name) } -func (g *Generator) Save() { +func (g *Generator) Save(of io.Writer) { if g.nodes == nil { return } - var of *os.File - var err error - if g.name == "main" { - of, err = os.Create("pgen.go") - } else { - oname := strings.Join([]string{"pgen_",g.name,".go"},"") - of, err = os.Create(oname) + if g.name != "main" { g.nodes.Name = ast.NewIdent(g.name) } - if err != nil { - log.Fatal("Cannot open pgen.go") - } - err = format.Node(of,g.fset,g.nodes) + err := format.Node(of,g.fset,g.nodes) if err != nil { log.Fatal("Generate error:",err) } diff --git a/cmd/pgen/main.go b/cmd/pgen/main.go index e9b8cd0..1485719 100644 --- a/cmd/pgen/main.go +++ b/cmd/pgen/main.go @@ -7,6 +7,8 @@ import ( "go/token" "go/types" "log" + "os" + "path/filepath" "regexp" "strings" ) @@ -104,6 +106,18 @@ func init() { imps = make(map[string]string) needImps = make(map[string]bool) fset = token.NewFileSet() + + // clear out old generated files + fs,err := filepath.Glob("pgen*.go") + if err != nil { + log.Fatal("Glob error") + } + for _,f := range(fs) { + err := os.Remove(f) + if err != nil && os.IsExist(err) { + log.Fatal("Removing ",f,err) + } + } } func main() { @@ -116,6 +130,9 @@ func main() { log.Print("Processing package ",pkg.Name) ts = make(map[string]tps) chkpkg(pkg) + if len(ts) == 0 { + continue + } g := NewGenerator(pkg.Name) for _,v := range ts { g.Add(v.fun, v.name, v.typ) @@ -123,9 +140,20 @@ func main() { for name := range needImps { g.Import(imps[name]) } + var of *os.File + var err error + if pkg.Name == "main" { + of, err = os.Create("pgen.go") + } else { + oname := strings.Join([]string{"pgen_",pkg.Name,".go"},"") + of, err = os.Create(oname) + } + if err != nil { + log.Fatal("Cannot open output file: ",err) + } // process template for each type identified and // generate output - g.Save() + g.Save(of) } }