generate.go 1.2 KB
Newer Older
Eric Myhre's avatar
Eric Myhre committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
package gengo

import (
	"io"
	"os"
	"path/filepath"

	"github.com/ipld/go-ipld-prime/schema"
)

func Generate(pth string, pkgName string, ts schema.TypeSystem, adjCfg *AdjunctCfg) {
	// Emit fixed bits.
	withFile(filepath.Join(pth, "minima.go"), func(f io.Writer) {
		EmitInternalEnums(pkgName, f)
	})

	// Emit a file for each type.
	for _, typ := range ts.GetTypes() {
		withFile(filepath.Join(pth, "t"+typ.Name().String()+".go"), func(f io.Writer) {
			EmitFileHeader(pkgName, f)
			switch t2 := typ.(type) {
Eric Myhre's avatar
Eric Myhre committed
22 23
			case schema.TypeInt:
				EmitEntireType(NewIntReprIntGenerator(pkgName, t2, adjCfg), f)
Eric Myhre's avatar
Eric Myhre committed
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
			case schema.TypeString:
				EmitEntireType(NewStringReprStringGenerator(pkgName, t2, adjCfg), f)
			case schema.TypeStruct:
				switch t2.RepresentationStrategy().(type) {
				case schema.StructRepresentation_Map:
					EmitEntireType(NewStructReprMapGenerator(pkgName, t2, adjCfg), f)
				default:
					panic("unrecognized struct representation strategy")
				}
			default:
				panic("add more type switches here :)")
			}
		})
	}
}

func withFile(filename string, fn func(io.Writer)) {
	f, err := os.OpenFile(filename, os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0644)
	if err != nil {
		panic(err)
	}
	defer f.Close()
	fn(f)
}