-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
343 lines (308 loc) · 9.29 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
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
package main
import (
"bytes"
"fmt"
"go/ast"
"go/parser"
"go/token"
"io"
"os"
"os/exec"
"path/filepath"
"strings"
"time"
)
var (
verbose = false
)
func main() {
project := os.Getenv("GB_PROJECT_DIR")
//sanity
if project == "" {
panic("gb extensions should be launched with GB_PROJECT_DIR set")
}
//validate that gopherjs, pagegen are there
if err := validateExecutablesInPath(project); err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
//figure out args, if any
args := os.Args[1:]
if len(args) == 0 {
help()
os.Exit(0)
}
//walk each arg, assuming that they are golang package specs
for _, arg := range args {
//make sure everything is where we expect within arg
if err := validateProjectStructure(project, arg); err != nil {
os.Exit(1)
}
//gopherjs creates the js code
if err := gopherjsCompilation(project, arg); err != nil {
os.Exit(1)
}
//pagegen creates the HTML pages
if err := pageGeneration(project, arg); err != nil {
os.Exit(1)
}
}
}
func pageGeneration(project string, arg string) error {
templatePath := constructTemplatesPath(project, arg)
jsonFiles := []string{}
htmlFiles := []string{}
err := filepath.Walk(templatePath, func(path string, info os.FileInfo, err error) error {
if err != nil {
fmt.Fprintf(os.Stderr, "error walking %s: %v\n", path, err)
return err
}
//ignore the support dir
if info.IsDir() && info.Name() == "support" {
return filepath.SkipDir
}
//make sure that for each json there is an HTML
if strings.HasSuffix(info.Name(), ".json") {
parent := filepath.Dir(path)
root := strings.TrimSuffix(info.Name(), ".json")
_, err := os.Stat(filepath.Join(parent, root+".html"))
if err != nil {
fmt.Fprintf(os.Stderr, "unable to find corresponding html file for json file %s\n", path)
return fmt.Errorf("no html file for %s", path)
}
jsonFiles = append(jsonFiles, path)
htmlFiles = append(htmlFiles, filepath.Join(parent, root+".html"))
}
return nil
})
if verbose {
for i, json := range jsonFiles {
jsonShort := strings.TrimPrefix(json, constructPagesPath(project, arg))
html := htmlFiles[i]
htmlShort := strings.TrimPrefix(html, constructPagesPath(project, arg))
fmt.Printf("%d %s %s\n", i, jsonShort, htmlShort)
}
}
if err != nil {
fmt.Fprintf(os.Stderr, "Unable to walk directory %s: %v", templatePath, err)
return err
}
for i, jsonFile := range jsonFiles {
if !strings.HasPrefix(jsonFile, constructTemplatesPath(project, arg)) {
panic(fmt.Sprintf("unable to understand json path %s in template dir %s",
jsonFile, constructTemplatesPath(project, arg)))
}
html := strings.TrimPrefix(htmlFiles[i], constructTemplatesPath(project, arg))
json := strings.TrimPrefix(jsonFile, constructTemplatesPath(project, arg))
out := filepath.Join(constructStaticEnglishPath(project, arg), html)
support := filepath.Join(constructTemplatesPath(project, arg), "support")
criticalTime := time.Time{}
info, err := os.Stat(out)
if err == nil {
criticalTime = info.ModTime()
}
rebuild := false
rebuild = rebuild || fileAfter(filepath.Join(constructTemplatesPath(project, arg), html), criticalTime)
rebuild = rebuild || fileAfter(filepath.Join(constructTemplatesPath(project, arg), json), criticalTime)
rebuild = rebuild || anyDirectoryContentAfter(support, criticalTime)
if !rebuild {
continue //no point in running pagegen
}
fmt.Printf("gb seven5: rebuilding %s\n", out)
if err := launchPagegen("support",
constructTemplatesPath(project, arg),
html, json, out); err != nil {
return err
}
}
return nil
}
func fileAfter(path string, crit time.Time) bool {
info, err := os.Stat(path)
if err != nil {
return true
}
return info.ModTime().After(crit)
}
func anyDirectoryContentAfter(path string, crit time.Time) bool {
result := false
err := filepath.Walk(path, func(p string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if !result && info.ModTime().After(crit) {
result = true
}
return nil
})
if err != nil {
return true
}
return result
}
func gopherjsCompilation(project string, arg string) error {
//this the full path to the package from arg
dir := constructClientPackagePath(project, arg)
//find the gofiles in the package
gofiles, err := iterateDirs([]string{dir})
if err != nil {
return err
}
//find the gofiles that have a main()
pages := []string{}
for _, gofile := range gofiles {
hasMain, err := hasMainFunc(gofile)
if err != nil {
return err
}
if hasMain {
pages = append(pages, gofile)
}
}
//walk each page, compiling to the static/en/web
for _, page := range pages {
if !strings.HasPrefix(page, constructClientPackagePath(project, arg)) {
panic(fmt.Sprintf("unable to understand page path %s in package %s",
page, constructClientPackagePath(project, arg)))
}
suffix := strings.TrimPrefix(page, constructClientPackagePath(project, arg))
suffix = strings.TrimSuffix(suffix, ".go") + ".js" //output filename part
target := filepath.Join(constructStaticEnglishPath(project, arg), suffix)
if err := launchGopherjs(project, "build", "-m", "-o", target, page); err != nil {
return err
}
}
return nil
}
func iterateDirs(dirs []string) ([]string, error) {
gofiles := []string{}
for _, dir := range dirs {
err := filepath.Walk(dir, func(path string, info os.FileInfo, err error) error {
if err != nil {
fmt.Fprintf(os.Stderr, "error walking %s: %v\n", path, err)
return err
}
if strings.HasSuffix(info.Name(), ".go") {
gofiles = append(gofiles, path)
}
return nil
})
if err != nil {
return nil, err
}
}
return gofiles, nil
}
func hasMainFunc(path string) (bool, error) {
fset := token.NewFileSet() // positions are relative to fset
f, err := parser.ParseFile(fset, path, nil, 0)
if err != nil {
fmt.Fprintf(os.Stderr, "error parsing %s: %v", path, err)
return false, err
}
for _, decl := range f.Decls {
switch x := decl.(type) {
case *ast.FuncDecl:
if x.Name.String() == "main" {
return true, nil
}
}
}
return false, nil
}
func launchGopherjs(projectDir string, args ...string) error {
cmd := exec.Command("gopherjs", args...)
vendor := projectDir + string(os.PathSeparator) + "vendor"
bothDirs := projectDir + string(os.PathListSeparator) + vendor
cmd.Env = append(os.Environ(), "GOPATH="+bothDirs)
out, err := cmd.CombinedOutput()
fmt.Printf("%s", string(out))
return err
}
func launchPagegen(supportPath, templatesPath, htmlInFile, jsonFile, htmlOutFile string) error {
cmd := exec.Command("pagegen", "--support", supportPath, "--dir", templatesPath, "--start",
htmlInFile, "--json", jsonFile)
out, err := cmd.Output()
if err != nil {
if execError, ok := err.(*exec.ExitError); ok {
fmt.Fprintf(os.Stderr, "%s\n", string(execError.Stderr))
return execError
}
fmt.Fprintf(os.Stderr, "Unable to start pagegen process: %v\n", err)
return err
}
file, err := os.Create(htmlOutFile)
if err != nil {
fmt.Fprintf(os.Stderr, "unable to create output file %s: %v\n", htmlOutFile, err)
return err
}
buff := bytes.NewBuffer(out)
_, err = io.Copy(file, buff)
return err
}
func help() {
fmt.Printf("gb seven5 requires a package name to build client software from\n")
}
//
// SUPPORT FUNCS
//
func constructClientPackagePath(project string, arg string) string {
return filepath.Join(project, "src", arg, "client")
}
func constructPagesPath(project string, arg string) string {
return filepath.Join(project, "src", arg, "pages")
}
func constructTemplatesPath(project string, arg string) string {
return filepath.Join(project, "src", arg, "pages")
}
func constructSupportPath(project string, arg string) string {
return filepath.Join(project, "src", arg, "pages", "support")
}
func constructStaticEnglishPath(project string, arg string) string {
return filepath.Join(project, "src", arg, "static", "en", "web")
}
func validateClientPackage(projectDir string, arg string) error {
path := constructClientPackagePath(projectDir, arg)
_, err := os.Stat(path)
return err
}
func validatePagesDir(projectDir string, arg string) error {
path := constructPagesPath(projectDir, arg)
_, err := os.Stat(path)
return err
}
func validateStaticEnglishDir(projectDir string, arg string) error {
path := constructStaticEnglishPath(projectDir, arg)
_, err := os.Stat(path)
return err
}
func validateExecutablesInPath(projectDir string) error {
cmd := exec.Command("gopherjs")
cmd.Env = append(os.Environ(), "GOPATH="+projectDir)
if err := cmd.Run(); err != nil {
return err
}
cmd = exec.Command("pagegen")
return cmd.Run()
}
func validateProjectStructure(project string, arg string) error {
//validate that the packages provided have a client subpackage
//and the static/en/web directory, as expected
if err := validateClientPackage(project, arg); err != nil {
fmt.Fprintf(os.Stderr, "Unable to find client package in %s\n",
constructClientPackagePath(project, arg))
return err
}
if err := validateStaticEnglishDir(project, arg); err != nil {
fmt.Fprintf(os.Stderr, "Unable to find static/en/web directory, expected it to be %s\n",
constructStaticEnglishPath(project, arg))
return err
}
//make sure it has the pages dir
if err := validatePagesDir(project, arg); err != nil {
fmt.Fprintf(os.Stderr, "Unable to find pages directory, expected it to be %s\n",
constructPagesPath(project, arg))
return err
}
return nil
}