Unverified Commit fe47b7f0 authored by Will's avatar Will Committed by GitHub

Allow overriden types (#116)

This change will look at the destination package that codegen is being built into, and will skip generation of types that are already declared by files not prefixed with `ipldsch_`.

This isn't the cleanest escape-hatch, but it's a start.
parent 16fdc47a
package gengo
import (
"go/ast"
"go/parser"
"go/token"
"path"
"strings"
)
// getExternTypes provides a mapping of all types defined in the destination package.
// It is used by generate to not duplicate defined types to allow overriding of types.
func getExternTypes(pth string) (map[string]struct{}, error) {
set := token.NewFileSet()
packs, err := parser.ParseDir(set, pth, nil, 0)
if err != nil {
return nil, err
}
types := make(map[string]struct{})
for _, pack := range packs {
for fname, f := range pack.Files {
if strings.HasPrefix(path.Base(fname), "ipldsch_") {
continue
}
for _, d := range f.Decls {
if t, isType := d.(*ast.GenDecl); isType {
if t.Tok == token.TYPE {
for _, s := range t.Specs {
ts := s.(*ast.TypeSpec)
types[ts.Name.Name] = struct{}{}
}
}
}
}
}
}
return types, nil
}
......@@ -20,6 +20,12 @@ func Generate(pth string, pkgName string, ts schema.TypeSystem, adjCfg *AdjunctC
EmitInternalEnums(pkgName, f)
})
externs, err := getExternTypes(pth)
if err != nil {
// Consider warning that duplication may be present due to inability to parse destination.
externs = make(map[string]struct{})
}
// Local helper function for applying generation logic to each type.
// We will end up doing this more than once because in this layout, more than one file contains part of the story for each type.
applyToEachType := func(fn func(tg TypeGenerator, w io.Writer), f io.Writer) {
......@@ -28,7 +34,9 @@ func Generate(pth string, pkgName string, ts schema.TypeSystem, adjCfg *AdjunctC
types := ts.GetTypes()
keys := make(sortableTypeNames, 0, len(types))
for tn := range types {
keys = append(keys, tn)
if _, exists := externs[tn.String()]; !exists {
keys = append(keys, tn)
}
}
sort.Sort(keys)
for _, tn := range keys {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment