-
Notifications
You must be signed in to change notification settings - Fork 5
/
gen.go
110 lines (90 loc) · 1.96 KB
/
gen.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package gen
import (
"io/ioutil"
"os"
"path/filepath"
"github.com/mmcloughlin/avo/build"
"github.com/mmcloughlin/avo/printer"
"github.com/mmcloughlin/ec3/asm"
"github.com/mmcloughlin/ec3/internal/tmpl"
)
// GeneratedBy is the name used in code generation warnings.
const GeneratedBy = "ec3"
type File struct {
Path string
Source []byte
}
type Files []File
func Merge(collections ...Files) Files {
m := Files{}
for _, collection := range collections {
m = append(m, collection...)
}
return m
}
func (f *Files) Add(path string, src []byte) {
*f = append(*f, File{
Path: path,
Source: src,
})
}
func (f *Files) CompileAsm(pkg, prefix string, ctx *build.Context) error {
s, err := asm.Compile(ctx)
if err != nil {
return err
}
cfg := printer.Config{
Pkg: pkg,
Name: GeneratedBy,
}
// Stubs.
stubs, err := printer.NewStubs(cfg).Print(s)
if err != nil {
return err
}
f.Add(prefix+".go", stubs)
// Assembly.
goasm, err := printer.NewGoAsm(cfg).Print(s)
if err != nil {
return err
}
f.Add(prefix+".s", goasm)
return nil
}
func (f *Files) AddTemplates(env tmpl.Environment, filenames []string, transforms []tmpl.Transform) error {
// Build template package.
pkg, err := env.Package(filenames...)
if err != nil {
return err
}
// Apply transforms.
err = pkg.Apply(transforms...)
if err != nil {
return err
}
// Add to file set.
for filename, t := range pkg.Templates() {
src, err := t.Bytes()
if err != nil {
return err
}
f.Add(filename, src)
}
return nil
}
// Output writes bundled files to disk rooted at path. Directories are created as necessary.
func (f Files) Output(path string) error {
for _, file := range f {
// Ensure directory exists.
filename := filepath.Join(path, file.Path)
dir := filepath.Dir(filename)
if err := os.MkdirAll(dir, 0750); err != nil {
return err
}
// Write file.
if err := ioutil.WriteFile(filename, file.Source, 0644); err != nil {
return err
}
}
return nil
}