/
asset.go
306 lines (289 loc) · 7.42 KB
/
asset.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
package beego_assets
import (
"os"
"bufio"
"io"
"errors"
"path"
"strings"
"html/template"
"path/filepath"
"github.com/tdewolff/minify"
"regexp"
)
var minifier = minify.New()
var parsedAssets = map[string]map[AssetType]*Asset{}
type Asset struct {
assetName string
assetType AssetType
needMinify bool
needCombine bool
Include_files []string
result []assetFile
}
// Find asset and parse it
func (this *Asset) parse() error {
assetPath, err := this.findAssetPath()
if err != nil {
return err
}
file, err := os.OpenFile(assetPath, os.O_RDONLY, 0666)
if err != nil {
return err
}
asset_reader := bufio.NewReader(file)
for {
_line, _, err := asset_reader.ReadLine()
if err == io.EOF {
break
}
line := string(_line)
var prefix string
if this.assetType == ASSET_JAVASCRIPT {
prefix = "//= require "
}else {
prefix = "/*= require "
}
if strings.HasPrefix(line, prefix) {
include_file := line[len(prefix):]
file, err := this.findIncludeFilePath(include_file)
if err != nil {
Warning("%v \"%v\" can't find required file \"%v\"", this.assetType.String(), this.assetName, include_file)
continue
}
this.Include_files = append(this.Include_files, file)
}
}
return nil
}
// Search for asset file in Config.AssetsLocations locations list
func (this *Asset) findAssetPath() (string, error) {
for _, value := range Config.AssetsLocations {
file_path := path.Join(value, this.assetName) + this.assetExt()
if _, err := os.Stat(file_path); !os.IsNotExist(err) {
if _, err := os.Stat(file_path); !os.IsNotExist(err) {
return file_path, nil
}
return file_path, nil
}
}
return "", errors.New("Can't find asset ")
}
// Search for asset included file in Config.PublicDirs locations list.
func (this *Asset) findIncludeFilePath(file string) (string, error) {
var extensions []string;
if val, ok := Config.extensions[this.assetType]; ok {
extensions = val
}
for _, value := range Config.PublicDirs {
for _, ext := range extensions {
file_path := path.Join(value, file) + ext
if stat, err := os.Stat(file_path); !os.IsNotExist(err) {
stat.ModTime()
return file_path, nil
}
}
}
return "", errors.New("Can't find file")
}
func (this *Asset) assetExt() string {
switch this.assetType {
case ASSET_JAVASCRIPT : return ".js"
case ASSET_STYLESHEET: return ".css"
default: return ""
}
}
func (this *Asset) build() {
if cbcks, ok := Config.preLoadCallbacks[this.assetType]; ok {
for _, value := range cbcks {
err := value(this)
if err != nil {
Error(err.Error())
return
}
}
}
this.result = this.readAllIncludeFiles()
if !this.needCombine && !this.needMinify {
return
}
if this.assetType == ASSET_STYLESHEET {
this.replaceRelLinks()
}
if cbcks, ok := Config.preBuildCallbacks[this.assetType]; ok {
for _, value := range cbcks {
err := value(this.result, this)
if err != nil {
Error(err.Error())
return
}
}
}
if this.needMinify {
this.minify()
}
if this.needCombine {
this.combine()
}
if cbcks, ok := Config.afterBuildCallbacks[this.assetType]; ok {
for _, value := range cbcks {
err := value(this.result, this)
if err != nil {
Error(err.Error())
return
}
}
}
this.writeResultToFiles()
}
func (this *Asset) minify() {
var minifyHandler func(string) (string, error)
if this.assetType == ASSET_JAVASCRIPT {
minifyHandler = MinifyJavascript
}else {
minifyHandler = MinifyStylesheet
}
for i, assetFile := range this.result {
file_name := filepath.Base(assetFile.Path)
file_ext := filepath.Ext(file_name)
file_name = file_name[:len(file_name) - len(file_ext)]
file_hash := GetAssetFileHash(&assetFile.Body)
minified_path := filepath.Join(Config.TempDir, file_name + "-" + file_hash + file_ext)
minified_body, err := minifyHandler(assetFile.Body)
if err != nil {
Error(err.Error())
} else {
this.result[i].Path = minified_path
this.result[i].Body = minified_body
}
}
}
func (this *Asset) combine() {
var files_devider string
if this.assetType == ASSET_JAVASCRIPT {
files_devider = ";"
}
result := make([]string, len(this.result))
for i, assetFile := range this.result {
result[i] = assetFile.Body
}
s_result := strings.Join(result, files_devider)
combined_path := filepath.Join(Config.TempDir, this.assetName + "-" + GetAssetFileHash(&s_result) + this.assetExt())
this.result = []assetFile{assetFile{Path:combined_path, Body:s_result}}
}
// Read all files from Include files and return map[path_to_file]body
func (this *Asset) readAllIncludeFiles() []assetFile {
result := []assetFile{}
for _, path := range this.Include_files {
file, err := os.OpenFile(path, os.O_RDONLY, 0766)
if err != nil {
Warning("Can't open file %s. %v", path, err)
}
file_body := ""
file_reader := bufio.NewReader(file)
for {
line, _, err := file_reader.ReadLine()
if err == io.EOF {
break
}
file_body += string(line) + "\n"
}
result = append(result, assetFile{Path:path, Body:file_body})
file.Close()
}
return result
}
func (this *Asset) writeResultToFiles() {
for _, assetFile := range this.result {
path_dir := filepath.Dir(assetFile.Path)
err := os.MkdirAll(path_dir, 0766)
if err != nil {
Error(path_dir)
continue
}
file, err := os.OpenFile(assetFile.Path, os.O_CREATE | os.O_TRUNC | os.O_WRONLY, 0766)
if err != nil {
Error("Can't write result file: %v", err)
}
_, err = file.WriteString(assetFile.Body)
if err != nil {
Error("Can't write body to result file: %v", err)
}
file.Close()
}
}
func (this *Asset) replaceRelLinks() {
regex, err := regexp.Compile("url\\( *['\"]? *(\\/?(?:(?:\\.{1,2}|[a-zA-Z0-9-_.]+)\\/)*[a-zA-Z0-9-_.]+\\.[a-zA-Z0-9-_.]+)(?:\\?.+?)? *['\"]? *\\)")
if err != nil {
Error(err.Error())
return
}
for i, assetFile := range this.result {
file_dir := filepath.Dir(assetFile.Path)
urls := regex.FindAllStringSubmatch(assetFile.Body, -1)
for _, mathces := range urls {
url_dir := mathces[1]
abs_path := filepath.Join("/", file_dir, url_dir)
assetFile.Body = strings.Replace(assetFile.Body, url_dir, abs_path, -1)
}
this.result[i] = assetFile
}
}
// Return html string of result
func (this *Asset) buildHTML() template.HTML {
var tag_fn func(string) template.HTML
switch this.assetType {
case ASSET_JAVASCRIPT:
tag_fn = js_tag
case ASSET_STYLESHEET:
tag_fn = css_tag
default:
Error("Unknown asset type")
return ""
}
var result template.HTML
for _, assetFile := range this.result {
result += tag_fn("/" + assetFile.Path)
}
return result
}
func getAsset(assetName string, assetType AssetType) (*Asset, error) {
// Check if this asset already built ( only if production mode enabled )
if Config.ProductionMode {
if v, ok := parsedAssets[assetName]; ok {
if asset, ok := v[assetType]; ok {
return asset, nil
}
}
}
result := new(Asset)
result.assetType = assetType
result.assetName = assetName
if assetType == ASSET_JAVASCRIPT {
if Config.MinifyJS {
result.needMinify = true
}
if Config.CombineJS {
result.needCombine = true
}
}else {
if Config.MinifyCSS {
result.needMinify = true
}
if Config.CombineCSS {
result.needCombine = true
}
}
err := result.parse()
if err == nil {
// Add asset to cache ( only if production mode enabled )
if Config.ProductionMode {
if _, ok := parsedAssets[assetName]; !ok {
parsedAssets[assetName] = map[AssetType]*Asset{}
}
parsedAssets[assetName][assetType] = result
}
}
result.build()
return result, err
}