Fix import handling. Handle multiple packages per directory and save

each output package to a different file.
This commit is contained in:
Greg 2018-08-06 11:04:25 -04:00
parent 3329fe75df
commit bc06994bcf
4 changed files with 48 additions and 13 deletions

1
.gitignore vendored
View File

@ -1,3 +1,4 @@
test/basic/basic
test/basic/pgen.go
test/basic/pgen_aaa.go
test/basic/db

View File

@ -1,6 +1,7 @@
package main
import (
"path/filepath"
"log"
"go/ast"
"go/format"
@ -9,6 +10,7 @@ import (
"golang.org/x/tools/go/ast/astutil"
"os"
"regexp"
"strings"
)
type subspec struct {
@ -22,6 +24,7 @@ type Generator struct{
fspec, tspec, nspec subspec
nspecs []subspec
nodes *ast.File
name string
}
func subs(dst *string, specs []subspec) {
@ -83,17 +86,33 @@ func (g *Generator) Visit(node ast.Node) ast.Visitor {
return g
}
var (
qexp *regexp.Regexp
)
func init() {
err := os.Remove("pgen.go")
if err != nil && os.IsExist(err) {
log.Fatal("Removing pgen.go:",err)
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(`"`)
}
func NewGenerator() *Generator {
func NewGenerator(ns ...string) *Generator {
g := &Generator{}
g.firstone = true
g.fset = token.NewFileSet()
if len(ns) > 0 {
g.name = ns[0]
} else {
g.name = "main"
}
return g
}
@ -124,24 +143,29 @@ func (g *Generator) Add(newName, typName, typ string) {
g.firstone = false
}
func (g *Generator) Import(imports map[string]bool) {
func (g *Generator) Import(name string) {
if g.nodes == nil {
return
}
// strip quotation marks from imports
qexp := regexp.MustCompile(`"`)
for v := range imports {
v = qexp.ReplaceAllString(v,"")
astutil.AddImport(g.fset, g.nodes, v)
}
name = qexp.ReplaceAllString(name,"")
astutil.AddImport(g.fset, g.nodes, name)
}
func (g *Generator) Save() {
if g.nodes == nil {
return
}
of, err := os.Create("pgen.go")
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)
g.nodes.Name = ast.NewIdent(g.name)
}
if err != nil {
log.Fatal("Cannot open pgen.go")
}

View File

@ -113,13 +113,16 @@ func main() {
}
// run type checker on each package
for _,pkg := range pkgs {
log.Print("Processing package ",pkg.Name)
ts = make(map[string]tps)
chkpkg(pkg)
g := NewGenerator()
g := NewGenerator(pkg.Name)
for _,v := range ts {
g.Add(v.fun, v.name, v.typ)
}
g.Import(needImps)
for name := range needImps {
g.Import(imps[name])
}
// process template for each type identified and
// generate output
g.Save()

7
test/basic/other.go Normal file
View File

@ -0,0 +1,7 @@
package aaa
func Hi() {
y := persistFoo("y",7)
_ = y
}