-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrestache.go
331 lines (283 loc) · 7.26 KB
/
restache.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
package restache
import (
"fmt"
"os"
"path/filepath"
"runtime"
"sync"
"time"
"github.com/tetsuo/toposort"
"golang.org/x/sync/errgroup"
)
type Option func(*config)
type config struct {
includes []string
parallelism int
onEmit func(Artifact)
}
func WithParallelism(parallelism int) Option {
return func(cfg *config) {
cfg.parallelism = parallelism
}
}
func WithIncludes(includes []string) Option {
return func(cfg *config) {
cfg.includes = includes
}
}
func WithCallback(onEmit func(Artifact)) Option {
return func(cfg *config) {
cfg.onEmit = onEmit
}
}
func ParseFile(path string) (node *Node, err error) {
var f *os.File
f, err = os.Open(path)
if err != nil {
err = fmt.Errorf("error opening file %s: %w", path, err)
return
}
defer f.Close()
node, err = Parse(f)
if err != nil {
err = fmt.Errorf("error parsing file %s: %w", path, err)
}
return
}
func readConfig(cfg *config, inputDir string, opts ...Option) (int, error) {
for _, opt := range opts {
opt(cfg)
}
includes := cfg.includes
var err error
n := len(includes)
if n == 0 {
pat := filepath.Join(inputDir, "*")
includes, err = filepath.Glob(pat)
if err != nil {
return 0, fmt.Errorf("invalid glob %q: %v", pat, err)
}
n = len(includes)
if n == 0 {
return 0, fmt.Errorf("no input files found in directory %q", inputDir)
}
for i, f := range includes {
includes[i] = filepath.Base(f)
}
}
if cfg.parallelism == 0 {
cfg.parallelism = runtime.NumCPU()
}
return n, nil
}
func parseModule(inputDir string, includes []string, parallelism int) ([]*Node, error) {
var err error
n := len(includes)
entries := make([]*fileParser, n)
lookupTable := make(map[string]int, n)
for i, path := range includes {
entries[i], err = newFileParser(filepath.Join(inputDir, path))
if err != nil {
return nil, err
}
lookupTable[entries[i].tag] = i
}
var g errgroup.Group
g.SetLimit(parallelism)
for _, e := range entries {
e.lookup = lookupTable
g.Go(e.parse)
}
if err := g.Wait(); err != nil {
return nil, err
}
sort := false
// Before sorting collect imports:
for _, e := range entries {
if e.doc.Attr != nil {
j := 0
for i, other := range e.afters {
// Recursive?
if entries[other].tag == e.tag {
e.doc.DataAtom = 1
continue
}
e.afters[j] = e.afters[i]
e.doc.Attr[j] = Attribute{
Key: entries[other].tag,
Val: entries[other].stem,
}
j++
}
if e.doc.DataAtom == 1 {
e.afters = e.afters[:j]
e.doc.Attr = e.doc.Attr[:j]
}
if j > 0 {
sort = true
}
}
}
if sort {
if err := toposort.BFS(entries); err != nil {
// TODO: will detect recursive entries earlier; this only returns ErrCircular,
// should rather panic after recursive detection.
return nil, fmt.Errorf("error sorting files in %s: %w", inputDir, err)
}
}
nodes := make([]*Node, n)
for i, entry := range entries {
nodes[i] = entry.doc
}
return nodes, nil
}
// ParseModule reads the provided directory for files listed in includes, parses each file to
// build a dependency graph, and returns a slice of components in topologically sorted order.
func ParseModule(inputDir string, opts ...Option) ([]*Node, error) {
if inputDir == "" {
return nil, fmt.Errorf("input directory path is empty")
}
absInputDir, err := toAbsPath(inputDir)
if err != nil {
return nil, fmt.Errorf("failed to resolve input directory %q: %v", inputDir, err)
}
cfg := config{}
n, err := readConfig(&cfg, absInputDir, opts...)
if err != nil {
return nil, err
}
return parseModule(absInputDir, cfg.includes, min(n, cfg.parallelism))
}
type Artifact struct {
Source string
Path string
Bytes int
Elapsed time.Duration
}
func TranspileFile(inputFile, outputFile string) (Artifact, error) {
if inputFile == "" {
return Artifact{}, fmt.Errorf("input file path is empty")
}
absInputFile, err := toAbsPath(inputFile)
if err != nil {
return Artifact{}, fmt.Errorf("failed to resolve input file %q: %v", inputFile, err)
}
absInputDir := filepath.Dir(absInputFile)
start := time.Now()
e, err := newFileParser(absInputFile)
if err != nil {
return Artifact{}, err // returns descriptive error
}
e.lookup = map[string]int{e.tag: 0}
if err := e.parse(); err != nil {
return Artifact{}, err // returns descriptive error
}
var absOutputFile string
if outputFile == "" {
absOutputFile = filepath.Join(absInputDir, e.stem+".jsx")
} else {
absOutputFile, err = toAbsPath(outputFile)
if err != nil {
return Artifact{}, fmt.Errorf("failed to resolve absolute path for output file %q: %v", outputFile, err)
}
}
if written, err := renderToFile(absOutputFile, e.doc); err != nil {
return Artifact{}, err
} else {
return Artifact{
Path: absOutputFile,
Bytes: written,
Source: absInputFile,
Elapsed: time.Since(start),
}, nil
}
}
func renderToFile(absPath string, n *Node) (int, error) {
f, err := os.Create(absPath)
if err != nil {
return 0, fmt.Errorf("could not create output file %q: %v", absPath, err)
}
defer f.Close()
if written, err := Render(f, n); err != nil {
return 0, fmt.Errorf("failed to write output file %q: %v", absPath, err)
} else {
return written, nil
}
}
func TranspileModule(inputDir string, outputDir string, opts ...Option) ([]Artifact, error) {
if inputDir == "" {
return nil, fmt.Errorf("input directory path is empty")
}
absInputDir, err := toAbsPath(inputDir)
if err != nil {
return nil, fmt.Errorf("failed to resolve input directory %q: %v", inputDir, err)
}
cfg := config{}
n, err := readConfig(&cfg, absInputDir, opts...)
if err != nil {
return nil, err
}
parallelism := min(n, cfg.parallelism)
var absOutputDir string
if outputDir == "" {
absOutputDir = absInputDir
} else {
absOutputDir, err = toAbsPath(outputDir)
if err != nil {
return nil, fmt.Errorf("failed to resolve absolute path for output directory %q: %v", outputDir, err)
}
}
start := time.Now()
nodes, err := parseModule(inputDir, cfg.includes, parallelism)
if err != nil {
return nil, fmt.Errorf("parse module %q: %v", inputDir, err)
}
diff := time.Since(start)
var mu sync.Mutex
artifacts := make([]Artifact, n)
var g errgroup.Group
g.SetLimit(min(n, cfg.parallelism))
for i, node := range nodes {
node := node
i := i
start := time.Now()
g.Go(func() error {
// parseModule guarantees that node.Path is always at least length 2 (stem, ext),
// otherwise this might panic on certain input files:
outfile := filepath.Join(absOutputDir, node.Path[:len(node.Path)-1][0].Key) + ".jsx"
dst, err := os.Create(outfile)
if err != nil {
return fmt.Errorf("could not create file %q: %v", outfile, err)
}
if written, err := Render(dst, node); err != nil {
dst.Close()
return fmt.Errorf("failed to write file %q: %v", outfile, err)
} else {
dst.Close()
art := Artifact{Path: outfile, Bytes: written, Elapsed: time.Since(start) + diff}
mu.Lock()
artifacts[i] = art
mu.Unlock()
if cfg.onEmit != nil {
cfg.onEmit(art)
}
}
return nil
})
}
if err := g.Wait(); err != nil {
return nil, err
}
return artifacts, nil
}
func toAbsPath(path string) (string, error) {
if !filepath.IsAbs(path) {
absPath, err := filepath.Abs(path)
if err != nil {
return "", err
} else {
return absPath, nil
}
}
return path, nil
}