-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathpostprocess.go
71 lines (59 loc) · 1.52 KB
/
postprocess.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
package staticfiles
import (
"io/ioutil"
"path/filepath"
"regexp"
"strings"
)
var (
ignoreRegex = regexp.MustCompile(`^\w+:`)
urlPatterns = []*regexp.Regexp{
regexp.MustCompile(`url\(['"]?(?P<url>.*?)['"]?\)`),
regexp.MustCompile(`@import\s*['"](?P<url>.*?)['"]`),
regexp.MustCompile(`sourceMappingURL=(?P<url>[-\\.\w]+)`),
}
)
// PostProcessCSS fixes files references in CSS files to point
// to the hashed versions of the files in the following cases:
//
// @import "path/file.ext"
// url("path/file.ext")
// sourceMappingURL=file.ext.map
func PostProcessCSS(storage *Storage, file *StaticFile) error {
if filepath.Ext(file.Path) != ".css" {
return nil
}
buf, err := ioutil.ReadFile(file.Path)
if err != nil {
return err
}
content := string(buf)
changed := false
for _, regex := range urlPatterns {
content = regex.ReplaceAllStringFunc(content, func(s string) string {
url := findSubmatchGroup(regex, s, "url")
// Skip data URI schemes and absolute urls
if ignoreRegex.MatchString(url) {
return s
}
urlFileName := filepath.Base(url)
urlFilePath := filepath.ToSlash(filepath.Join(filepath.Dir(file.Path), url))
for _, file := range storage.FilesMap {
if file.Path == urlFilePath {
hashedName := filepath.Base(file.StoragePath)
s = strings.Replace(s, urlFileName, hashedName, 1)
changed = true
break
}
}
return s
})
}
if changed {
err = ioutil.WriteFile(file.StoragePath, []byte(content), 0)
if err != nil {
return err
}
}
return nil
}