Skip to content

Commit

Permalink
Allow overriden types (#116)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
willscott committed Nov 30, 2020
1 parent 16fdc47 commit fe47b7f
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 1 deletion.
40 changes: 40 additions & 0 deletions schema/gen/go/externUtil.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
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
}
10 changes: 9 additions & 1 deletion schema/gen/go/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand All @@ -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 {
Expand Down

0 comments on commit fe47b7f

Please sign in to comment.