/
main.go
235 lines (197 loc) · 5.32 KB
/
main.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
// Copyright 2013 Bobby Powers. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package main
import (
"bufio"
"bytes"
"flag"
"fmt"
"github.com/bpowers/boosd/boosd"
"github.com/davecheney/gogo/build"
"github.com/davecheney/gogo/project"
"go/ast"
"go/format"
"go/token"
"io"
"io/ioutil"
"log"
"os"
"path"
"runtime"
)
const usage = `Usage: %s [OPTION...]
Compile system dynamics models.
Options:
`
const (
// FIXME: this is $GOPATH/src/github.com - non-hardcode this
GithubDir = "/var/unsecure/src/github.com"
)
var (
outPath string
)
func init() {
flag.Usage = func() {
fmt.Fprintf(os.Stderr, usage, os.Args[0])
flag.PrintDefaults()
}
flag.StringVar(&outPath, "o", "model.out",
"file name to use as output")
flag.Parse()
}
func main() {
var filename string
var in *bufio.Reader
var err error
// use the file if there is an argument, otherwise use stdin
if flag.NArg() == 0 {
filename = "stdin"
in = bufio.NewReader(os.NewFile(0, "stdin"))
} else {
filename = flag.Arg(0)
f, err := os.Open(filename)
if err != nil {
log.Fatal("Open:", err)
}
defer f.Close()
if fi, err := f.Stat(); err != nil || fi.IsDir() {
log.Fatalf("err(%s) or %s IsDir", err, filename)
}
in = bufio.NewReader(f)
}
goSource, err := transliterate(filename, in)
if err != nil {
log.Fatalf("%s", err)
}
err = compileAndLink(goSource, outPath)
if err != nil {
log.Fatalf("compileAndLink('%s')", goSource, err)
}
}
// copyFile copies the file at path 'from' to path 'to', overwriting
// the file at 'to' if it already exists.
func copyFile(from, to string) error {
fromF, err := os.Open(from)
if err != nil {
return fmt.Errorf("Open(%s): %s", from, err)
}
defer fromF.Close()
toF, err := os.OpenFile(to, os.O_CREATE|os.O_WRONLY, 0755)
if err != nil {
return fmt.Errorf("Open(%s): %s", to, err)
}
defer toF.Close()
_, err = io.Copy(toF, fromF)
return err
}
// mustGetwd returns the current working directory, panicing on error.
func mustGetwd() string {
cwd, err := os.Getwd()
if err != nil {
panic(err)
}
return cwd
}
// gofmt takes the given, valid, Go AST and returns a
// canonically-formatted go program in a byte-array, or an error.
func gofmt(f *ast.File) ([]byte, error) {
fset := token.NewFileSet()
var buf bytes.Buffer
if err := format.Node(&buf, fset, f); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
// transliterate takes an input stream and a name and returns a byte
// buffer containing valid & gofmt'ed source code, or an error. The
// name is used purely for diagnostic purposes
func transliterate(name string, in io.Reader) ([]byte, error) {
fset := token.NewFileSet()
// dump in the file
mdlSrc, err := ioutil.ReadAll(in)
if err != nil {
return nil, fmt.Errorf("ReadAll(%v): %s", in, err)
}
fsetFile := fset.AddFile(name, fset.Base(), len(mdlSrc))
// and parse
pkg, err := boosd.Parse(fsetFile, string(mdlSrc))
if err != nil {
return nil, fmt.Errorf("Parse(%v): %s", name, err)
}
if pkg.NErrors > 0 {
return nil, fmt.Errorf("There were errors parsing the file")
}
goSource, err := boosd.GenGo(pkg)
if err != nil {
log.Fatalf("GenGo(%v): %s", pkg, err)
}
src, err := gofmt(goSource)
if err != nil {
log.Fatalf("gofmtFile(%v): %s", goSource, err)
}
return src, nil
}
// mkdir joins the components into a path and creates that path with
// the given octal permissions. Parent directories must already
// exist.
func mkdir(perm os.FileMode, components ...string) error {
p := path.Join(components...)
if err := os.Mkdir(p, perm); err != nil {
return fmt.Errorf("os.Mkdir(%s, %d): %s", p, perm, err)
}
return nil
}
// compileAndLink compiles and links the given source, returning a
// path to the given binary, or an error.
func compileAndLink(src []byte, outPath string) error {
workDir, err := ioutil.TempDir("", "boosd_temp")
if err != nil {
return fmt.Errorf("ioutil.TempDir: %s", err)
}
if err = mkdir(0700, workDir, ".gogo"); err != nil {
return err
}
if err = mkdir(0700, workDir, "bin"); err != nil {
return err
}
if err = mkdir(0700, workDir, "src"); err != nil {
return err
}
if err = mkdir(0700, workDir, "src", "main"); err != nil {
return err
}
proj, err := project.NewProject(workDir)
if err != nil {
return fmt.Errorf("NewProject(%s): %s", workDir, err)
}
ctx, err := build.NewDefaultContext(proj)
if err != nil {
return fmt.Errorf("NewDefaultContext(): %s", err)
}
defer ctx.Destroy()
if err = os.Symlink(GithubDir, path.Join(workDir, "src", "github.com")); err != nil {
return fmt.Errorf("symlink: %s", err)
}
srcPath := path.Join(workDir, "src", "main", "main.go")
f, err := os.Create(srcPath)
if err != nil {
return fmt.Errorf("Create(%s): %s", srcPath, err)
}
f.Write(src)
// this Close is not deferred so that we're sure the contents are flushed to
// the kernel before buid.Build is called.
f.Close()
goPkg, err := ctx.ResolvePackage(runtime.GOOS, runtime.GOARCH, "main").Result()
if err != nil {
return fmt.Errorf("ResolvePackage(main): %s", err)
}
if err = build.Build(ctx, goPkg).Result(); err != nil {
return fmt.Errorf("Build: %s", err)
}
exePath := path.Join(ctx.Bindir(), "main")
if err = copyFile(exePath, outPath); err != nil {
return fmt.Errorf("copyFile('%s', '%s'): %s", exePath, outPath, err)
}
return nil
}