-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Packer.go
90 lines (70 loc) · 1.93 KB
/
Packer.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
package pack
import (
"fmt"
"os"
"path"
"path/filepath"
"github.com/aerogo/flow/jobqueue"
jsoniter "github.com/json-iterator/go"
)
// Packer packs the assets for your app.
type Packer struct {
Compilers []AssetCompiler
Root string
Config Configuration
Verbose bool
}
// New creates a new packer.
func New(root string) *Packer {
packer := &Packer{
Root: root,
}
// Load configuration if config.json exists.
_ = packer.loadConfig(path.Join(packer.Root, "config.json"))
return packer
}
// Run starts packing.
func (packer *Packer) Run() error {
// Map file extensions to their corresponding worker pool
workerPools := make(map[string]*jobqueue.JobQueue)
for _, compiler := range packer.Compilers {
workerPools[compiler.Extension] = compiler.Jobs
}
err := eachFileIn(packer.Root, func(file string) {
// Check if we have a compiler registered for that file type
workerPool, exists := workerPools[filepath.Ext(file)]
if !exists {
return
}
// Make sure we always use linux style path separators
file = filepath.ToSlash(file)
// Queue up work by sending the file path to the compiler
workerPool.Queue(file)
})
if err != nil {
return err
}
// Now that the work is queued up,
// we can wait for each job queue to finish the work.
for index, compiler := range packer.Compilers {
// Wait for jobs to finish
results := compiler.Jobs.Wait()
// Let the compiler do compiler-specific stuff with the results
compiler.ProcessResults(results)
// Add an empty line separator to make the output prettier
if packer.Verbose && len(results) > 0 && index != len(packer.Compilers)-1 {
fmt.Println()
}
}
return nil
}
// loadConfig loads the pack configuration from the given file.
func (packer *Packer) loadConfig(fileName string) error {
file, err := os.Open(fileName)
if err != nil {
return err
}
defer file.Close()
decoder := jsoniter.NewDecoder(file)
return decoder.Decode(&packer.Config)
}