Move all file handling into main.go.

This commit is contained in:
Greg 2018-08-06 12:11:15 -04:00
parent 62c409292b
commit 33821928c9
2 changed files with 33 additions and 26 deletions

View File

@ -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)
}

View File

@ -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)
}
}