forked from shaoshing/train
-
Notifications
You must be signed in to change notification settings - Fork 0
/
asset.go
250 lines (217 loc) · 6.4 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
package train
import (
"bytes"
"errors"
"fmt"
"io/ioutil"
"os"
"path"
"regexp"
"strconv"
"strings"
"github.com/shaoshing/train/interpreter"
)
func ReadAsset(assetUrl string) (result string, err error) {
filePath := ResolvePath(assetUrl)
fileExt := path.Ext(filePath)
switch fileExt {
case ".js", ".css", ".scss", ".sass", ".coffee":
if Config.BundleAssets {
data := bytes.NewBuffer([]byte(""))
contents := []string{}
_, err = ReadAssetsFunc(filePath, assetUrl, func(filePath string, content string) {
contents = append(contents, content)
})
if err != nil {
if !IsInProduction() {
fmt.Println(err)
}
return
}
data.Write([]byte(strings.Join(contents, "\n")))
result = string(data.Bytes())
} else {
result, err = ReadRawAndCompileAsset(filePath, assetUrl)
}
default:
err = errors.New("Unsupported Asset: " + assetUrl)
}
return
}
func compileSassAndCoffee(filePath string) (string, error) {
interpreter.Config.AssetsPath = Config.AssetsPath
interpreter.Config.SASS.LineNumbers = Config.SASS.LineNumbers
interpreter.Config.SASS.DebugInfo = Config.SASS.DebugInfo
interpreter.Config.Verbose = Config.Verbose
result, err := interpreter.Compile(filePath)
return result, err
}
var patterns = map[string](map[string]*regexp.Regexp){
".coffee": map[string]*regexp.Regexp{
"head": regexp.MustCompile(`(.*\n)*(\ *#\=\ *require\ +.*\n)+`),
"require": regexp.MustCompile(`^\ *#\=\ *require\ +`),
},
".js": map[string]*regexp.Regexp{
"head": regexp.MustCompile(`(.*\n)*(\ *\/\/\=\ *require\ +.*\n)+`),
"require": regexp.MustCompile(`^\ *\/\/\=\ *require\ +`),
},
".css": map[string]*regexp.Regexp{
"head": regexp.MustCompile(`(.*\n)*(\ *\*\=\ *require\ +.*\n)+(\ *\*\/\ *\n)`),
"require": regexp.MustCompile(`^\ *\*\=\ *require\ +`),
},
}
func patternExt(fileExt string) string {
switch fileExt {
case ".scss", ".sass":
return ".css"
}
return fileExt
}
func ReadAssetsFunc(filePath, assetUrl string, found func(filePath string, content string)) (filePaths []string, err error) {
fileExt := path.Ext(filePath)
fileExtPattern := patternExt(fileExt)
var cacheKey string
if cacheKey, err = generateCacheKey(filePath); err != nil {
err = errors.New("Asset Not Found: " + assetUrl)
return
}
requiredAssetUrls, content, hit := readFromCache(cacheKey)
if !hit {
content, err = ReadRawAsset(filePath, assetUrl)
if err != nil {
return
}
header := FindDirectivesHeader(&content, fileExtPattern)
content, err = ReadRawAndCompileAsset(filePath, assetUrl)
content = hotFixSASSCommentLines(content, fileExt)
if len(header) != 0 {
content = strings.Replace(content, header, "", 1)
for _, line := range strings.Split(header, "\n") {
if !patterns[fileExtPattern]["require"].Match([]byte(line)) {
continue
}
requiredAssetUrl := string(patterns[fileExtPattern]["require"].ReplaceAll([]byte(line), []byte("")))
if len(requiredAssetUrl) == 0 {
continue
}
requiredAssetUrls = append(requiredAssetUrls, requiredAssetUrl)
}
}
writeToCache(cacheKey, requiredAssetUrls, content)
}
for _, requiredAssetUrl := range requiredAssetUrls {
var paths []string
requiredFilePath := ResolvePath(requiredAssetUrl + fileExt)
requiredFileExt := path.Ext(requiredFilePath)
paths, err = ReadAssetsFunc(requiredFilePath, requiredAssetUrl+requiredFileExt, found)
if err != nil {
err = errors.New(fmt.Sprintf("%s\n--- required by %s", err.Error(), assetUrl))
return
}
filePaths = append(filePaths, paths...)
}
found(filePath, content)
filePaths = append(filePaths, filePath)
return
}
func FindDirectivesHeader(content *string, fileExt string) string {
return string(patterns[fileExt]["head"].Find([]byte(*content)))
}
var mapAlterExtensions = map[string]string{
".css": ".sass|.scss",
".sass": ".scss|.css",
".scss": ".sass|.css",
".js": ".coffee|.js.coffee",
".coffee": ".js",
}
// Find possible asset files.
// url = javascripts/asset.js
// if url exist
// => javascript/asset.js
// or url alternation exist
// => javascript/asset.coffee
func ResolvePath(assetUrl string) (assetPath string) {
fileExt := path.Ext(assetUrl)
if assetUrl[0] != '/' {
switch fileExt {
case ".js", ".coffee":
assetUrl = Config.AssetsUrl + "/javascripts/" + assetUrl
case ".css", ".sass", ".scss":
assetUrl = Config.AssetsUrl + "/javascripts/" + assetUrl
}
}
assetPath = string(strings.Replace(assetUrl, Config.AssetsUrl, "", 1))
assetPath = path.Clean(Config.AssetsPath + "/" + assetPath)
alterExts, hasAlterExt := mapAlterExtensions[fileExt]
if !isFileExist(assetPath) && hasAlterExt {
for _, alterExt := range strings.Split(alterExts, "|") {
alterPath := strings.Replace(assetPath, fileExt, alterExt, 1)
if isFileExist(alterPath) {
assetPath = alterPath
break
}
}
}
return
}
func isFileExist(path string) bool {
_, err := os.Stat(path)
return err == nil
}
// Hotfix SASS commet lines
// from:
// /*= require foo
// to:
// /*
// *= require foo
func hotFixSASSCommentLines(content string, fileExt string) string {
if fileExt == ".sass" {
return strings.Replace(content, "/*= require", "/*\n *= require", 1)
}
return content
}
func ReadRawAsset(filePath, assetUrl string) (result string, err error) {
content, _err := ioutil.ReadFile(filePath)
if _err != nil {
err = errors.New("Asset Not Found: " + assetUrl)
return
}
result = string(content)
return
}
// .js, .css read raw
// .coffee, .scss, .sass will compile
func ReadRawAndCompileAsset(filePath, assetUrl string) (result string, err error) {
fileExt := path.Ext(filePath)
if fileExt == ".scss" || fileExt == ".sass" || fileExt == ".coffee" {
result, err = compileSassAndCoffee(filePath)
} else {
result, err = ReadRawAsset(filePath, assetUrl)
}
return
}
type AssetCache struct {
RequiredUrls []string
Content string
}
var assetsCache = make(map[string]AssetCache)
func generateCacheKey(filePath string) (key string, err error) {
var info os.FileInfo
info, err = os.Stat(filePath)
if err != nil {
return
}
key = filePath + strconv.FormatInt(info.ModTime().Unix(), 10)
return
}
func readFromCache(key string) (requiredUrls []string, content string, hit bool) {
var cache AssetCache
if cache, hit = assetsCache[key]; hit {
requiredUrls = cache.RequiredUrls
content = cache.Content
}
return
}
func writeToCache(key string, requiredUrls []string, content string) {
assetsCache[key] = AssetCache{requiredUrls, content}
}