-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathjs.go
128 lines (106 loc) · 2.39 KB
/
js.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
package packer
import (
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"strings"
)
type JSCompiler struct {
options JSOptions
cache map[string]bool
}
type JSOptions struct {
Libs []string `json:"libs"`
Deps []string `json:"deps"`
Modules []string `json:"modules"`
WrapDocReady bool `json:"wrap_doc_ready"`
Minify bool `json:"minify"`
Output string `json:"output"`
}
func NewJSCompiler(options JSOptions) *JSCompiler {
return &JSCompiler{options: options, cache: make(map[string]bool)}
}
func (c *JSCompiler) Run(path string) error {
if filepath.Ext(path) != ".js" {
return nil
}
defer c.reset()
libs, err := c.compile(c.options.Libs...)
if err != nil {
return err
}
deps, err := c.compile(c.options.Deps...)
if err != nil {
return err
}
modules, err := c.compile(c.options.Modules...)
if err != nil {
return err
}
if c.options.WrapDocReady {
modules = fmt.Sprintf("$(function(){\n%s});", modules)
}
if c.options.Minify {
minified, err := c.minify(deps + modules)
if err != nil {
return err
}
return c.saveOutput(libs + minified)
}
return c.saveOutput(libs + deps + modules)
}
func (c *JSCompiler) compile(path ...string) (string, error) {
var sb strings.Builder
for _, p := range path {
files, err := getFilesFromPath(p)
if err != nil {
return "", err
}
for _, f := range files {
if c.cache[f] {
continue
}
c.cache[f] = true
b, err := ioutil.ReadFile(f)
if err != nil {
return "", err
}
sb.Write(b)
if !strings.HasSuffix(sb.String(), "\n") {
sb.WriteString("\n")
}
}
}
return sb.String(), nil
}
func (c *JSCompiler) minify(s string) (string, error) {
f, err := os.CreateTemp("", "minify")
if err != nil {
return "", err
}
defer os.Remove(f.Name())
defer f.Close()
if _, err := f.WriteString(s); err != nil {
return "", err
}
// TODO: stderr handling
if err := exec.Command("uglifyjs", f.Name(), "-o", f.Name()).Run(); err != nil {
return "", err
}
if _, err := f.Seek(0, 0); err != nil {
return "", err
}
b, err := ioutil.ReadAll(f)
return string(b), err
}
func (c *JSCompiler) reset() {
c.cache = make(map[string]bool)
}
func (c *JSCompiler) saveOutput(s string) error {
if err := os.MkdirAll(filepath.Dir(c.options.Output), os.ModePerm); err != nil {
return err
}
return ioutil.WriteFile(hashFileName(c.options.Output), []byte(s), 0644)
}