-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathbuild.go
459 lines (373 loc) · 9.46 KB
/
build.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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
package aspen
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path"
"path/filepath"
"strings"
"text/template"
)
var (
SiteIndexFilename = ".aspen-go-index.json"
DefaultGenPackage = "aspen_go_gen"
DefaultOutputGopath = ""
genServerTemplate = template.Must(template.New("aspen-genserver").Parse(`
package main
// GENERATED FILE - DO NOT EDIT
// Rebuild with aspen-go-build!
import (
"github.com/gittip/aspen-go"
_ "{{.GenPackage}}"
)
func main() {
aspen.RunServerMain("{{.WwwRoot}}",
"{{.GenServerBind}}", "{{.GenPackage}}",
"{{.CharsetDynamic}}", "{{.CharsetStatic}}",
"{{.IndicesString}}", {{.ListDirs}}, {{.Debug}})
}
`))
)
type siteBuilder struct {
// also used as defaults in generated server binary
WwwRoot string
GenPackage string
GenServerBind string
CharsetStatic string
CharsetDynamic string
Indices []string
ListDirs bool
Debug bool
// used primarily for compile time
OutputGopath string
Format bool
Compile bool
goexe string
walker *treeWalker
packagePath string
genServer string
index *siteIndex
}
type SiteBuilderCfg struct {
WwwRoot string
OutputGopath string
GenPackage string
GenServerBind string
Format bool
MkOutDir bool
Compile bool
CharsetStatic string
CharsetDynamic string
Indices []string
ListDirs bool
Debug bool
}
type siteIndex struct {
WwwRoot string `json:"root_dir"`
Simplates map[string]*simplateSummary `json:"simplates"`
}
type simplateSummary struct {
Type string `json:"type"`
ContentType string `json:"content_type"`
}
func init() {
*(&DefaultOutputGopath) = strings.Split(os.Getenv("GOPATH"), ":")[0]
}
func newSiteBuilder(cfg *SiteBuilderCfg) (*siteBuilder, error) {
var (
err error
goexe string
)
rootDir, err := filepath.Abs(cfg.WwwRoot)
if err != nil {
return nil, err
}
outPath, err := filepath.Abs(cfg.OutputGopath)
if err != nil {
return nil, err
}
genPkg := cfg.GenPackage
if len(genPkg) == 0 {
genPkg = DefaultGenPackage
}
if cfg.Compile || cfg.Format {
goexe, err = exec.LookPath("go")
if err != nil {
return nil, err
}
}
if cfg.MkOutDir {
err = os.MkdirAll(outPath, os.ModeDir|(os.FileMode)(0755))
if err != nil {
return nil, err
}
} else {
outPathFi, err := os.Stat(outPath)
if err != nil {
return nil, err
}
if !outPathFi.IsDir() {
return nil, fmt.Errorf("Invalid build output directory specified: %v", outPath)
}
}
debugf("Creating new tree walker with package name %q, root dir %q", genPkg, rootDir)
walker, err := newTreeWalker(genPkg, rootDir)
if err != nil {
return nil, err
}
sb := &siteBuilder{
WwwRoot: rootDir,
OutputGopath: outPath,
GenPackage: genPkg,
GenServerBind: cfg.GenServerBind,
Format: cfg.Format,
Compile: cfg.Compile,
CharsetDynamic: cfg.CharsetDynamic,
CharsetStatic: cfg.CharsetStatic,
Indices: cfg.Indices,
ListDirs: cfg.ListDirs,
Debug: cfg.Debug,
goexe: goexe,
walker: walker,
packagePath: path.Join(outPath, "src", genPkg),
genServer: fmt.Sprintf("%s/%s-http-server", genPkg, genPkg),
index: &siteIndex{
WwwRoot: rootDir,
Simplates: map[string]*simplateSummary{},
},
}
debugf("Initialized site builder: %+v from cfg %+v", sb, cfg)
return sb, nil
}
func (me *siteBuilder) writeOneSource(simplate *simplate) error {
if simplate.Type == SimplateTypeStatic {
debugf("Site builder skipping write of static simplate %q",
simplate.Filename)
return nil
}
outname := path.Join(me.packagePath, simplate.OutputName())
debugf("Writing source for %v to %v\n", simplate.Filename, outname)
outnameParent := path.Dir(outname)
_, err := os.Stat(outnameParent)
if err != nil {
err = os.MkdirAll(outnameParent, os.ModeDir|(os.FileMode)(0755))
if err != nil {
return err
}
}
outf, err := os.Create(outname)
if err != nil {
return err
}
debugf(" --> Executing simplate for %v\n", simplate.Filename)
err = simplate.Execute(outf)
if err != nil {
return err
}
debugf(" --> Done executing simplate for %v\n", simplate.Filename)
err = outf.Close()
if err != nil {
return err
}
debugf(" --> Returning nil after writing %v\n", outname)
return nil
}
func (me *siteBuilder) writeGenServer() error {
dirname := path.Join(me.OutputGopath, "src", me.genServer)
err := os.MkdirAll(dirname, os.ModeDir|(os.FileMode)(0755))
if err != nil {
return err
}
mainGo := path.Join(dirname, "main.go")
debugf("Site builder writing generated server to %q", mainGo)
fd, err := os.Create(mainGo)
if err != nil {
return err
}
defer fd.Close()
err = genServerTemplate.Execute(fd, me)
if err != nil {
return err
}
return nil
}
func (me *siteBuilder) writeSources() error {
debugf("Site builder writing sources")
simplates, err := me.walker.Simplates()
if err != nil {
return err
}
for simplate := range simplates {
if simplate == nil {
// assume `walker.Simplates()` assigned error to same address
// as one above?
return err
}
debugf("Site builder about to write source for %v simplate %q",
simplate.Type, simplate.Filename)
err := me.writeOneSource(simplate)
if err != nil {
return err
}
me.indexSimplate(simplate)
}
err = me.dumpSiteIndex()
if err != nil {
return err
}
err = me.writeGenServer()
if err != nil {
return err
}
return nil
}
func (me *siteBuilder) indexSimplate(simplate *simplate) {
me.index.Simplates[fmt.Sprintf("/%v", simplate.Filename)] = &simplateSummary{
Type: simplate.Type,
ContentType: simplate.ContentType,
}
}
func (me *siteBuilder) dumpSiteIndex() error {
idxPath := path.Join(me.WwwRoot, SiteIndexFilename)
debugf("Site builder dumping site index to %q", idxPath)
out, err := os.Create(idxPath)
if err != nil {
return err
}
encoded, err := json.MarshalIndent(me.index, "", " ")
if err != nil {
return err
}
_, err = out.Write(encoded)
if err != nil {
return err
}
err = out.Close()
if err != nil {
return err
}
return nil
}
func (me *siteBuilder) compileSources() error {
debugf("Site builder compiling sources")
origGopath := os.Getenv("GOPATH")
err := os.Setenv("GOPATH", fmt.Sprintf("%s:%s", me.OutputGopath, origGopath))
if err != nil {
return err
}
defer os.Setenv("GOPATH", origGopath)
installPkgCmd := exec.Command(me.goexe, "install", me.GenPackage)
installPkgCmd.Stdout = os.Stdout
installPkgCmd.Stderr = os.Stderr
err = installPkgCmd.Run()
if err != nil {
return err
}
installBinCmd := exec.Command(me.goexe, "install", me.genServer)
installBinCmd.Stdout = os.Stdout
installPkgCmd.Stderr = os.Stderr
err = installBinCmd.Run()
if err != nil {
return err
}
return nil
}
func (me *siteBuilder) formatOneSource(sourceFile string) error {
origGopath := os.Getenv("GOPATH")
err := os.Setenv("GOPATH", me.OutputGopath)
if err != nil {
return err
}
defer os.Setenv("GOPATH", origGopath)
formatCmd := exec.Command(me.goexe, "fmt", me.GenPackage)
formatCmd.Stdout = os.Stdout
formatCmd.Stderr = os.Stderr
err = formatCmd.Run()
if err != nil {
return err
}
return nil
}
func (me *siteBuilder) formatSources(sources []string) error {
debugf("Site builder formatting sources")
for _, source := range sources {
err := me.formatOneSource(source)
if err != nil {
return err
}
}
return nil
}
func (me *siteBuilder) sourcesList() ([]string, error) {
return filepath.Glob(path.Join(me.packagePath, "*.go"))
}
func (me *siteBuilder) ensureSourcesWritten() ([]string, error) {
sources, err := me.sourcesList()
if err != nil {
return sources, err
}
if len(sources) == 0 {
return sources, fmt.Errorf("No sources found in %q", me.packagePath)
}
return sources, nil
}
func (me *siteBuilder) Build() error {
err := me.writeSources()
if err != nil {
return err
}
sources, err := me.ensureSourcesWritten()
if err != nil {
return err
}
if me.Format {
err = me.formatSources(sources)
if err != nil {
return err
}
}
if me.Compile {
err = me.compileSources()
if err != nil {
return err
}
}
return nil
}
func (me *siteBuilder) IndicesString() string {
return strings.Join(me.Indices, ",")
}
/*
Build non-static simplates found in the given document root
(SiteBuilderCfg.WwwRoot) into Go sources written to the src dir of a given
GOPATH entry (SiteBuilderCfg.OutputGopath). The generated package
(SiteBuilderCfg.GenPackage) will be used as the output source directory name
and written as the package declaration for each generated Go source file. An
http server source will also be written to a directory nested within the
generated package.
Sources may be formatted via `gofmt` by setting the passed-in
SiteBuilderCfg.Format to true. The generated package and http executable may
be automatically compiled by setting the passed-in SiteBuilderCfg.Compile to
true.
The generated server will support the following options, defaulted to the values
passed to BuildMain:
--www_root, -w: Filesystem path of the document publishing root
--network_address, -a: The IPv4 or IPv6 address to which the generated server
will bind by default
--debug, -x: Print debugging output
*/
func BuildMain(cfg *SiteBuilderCfg) int {
SetDebug(cfg.Debug)
builder, err := newSiteBuilder(cfg)
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
return 1
}
err = builder.Build()
if err != nil {
fmt.Fprintf(os.Stderr, "ERROR: %v\n", err)
return 2
}
return 0
}