-
Notifications
You must be signed in to change notification settings - Fork 0
/
handle_scss.go
99 lines (84 loc) · 2.33 KB
/
handle_scss.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
//go:build cgo
// +build cgo
package caddy_esbuild_plugin
import (
"bytes"
"fmt"
"github.com/evanw/esbuild/pkg/api"
libsass "github.com/wellington/go-libsass"
"os"
"path/filepath"
"time"
)
func (m *Esbuild) hasSassSupport() bool {
return true
}
type result struct {
sources []string
mtime time.Time
content string
}
func (m *Esbuild) createSassPlugin() *api.Plugin {
return &api.Plugin{
Name: "sass",
Setup: func(build api.PluginBuild) {
cache := make(map[string]result)
// Load ".txt" files and return an array of words
build.OnLoad(api.OnLoadOptions{Filter: `\.scss|sass$`},
func(args api.OnLoadArgs) (api.OnLoadResult, error) {
fileHandle, err := os.Open(args.Path)
if err != nil {
return api.OnLoadResult{}, fmt.Errorf("sass: unable to open file: %s", err)
}
if val, ok := cache[args.Path]; ok {
latestMTime := getLatestMtime(val.sources)
if latestMTime.Equal(val.mtime) {
return api.OnLoadResult{
Contents: &val.content,
Loader: api.LoaderCSS,
}, nil
}
}
contentBuffer := new(bytes.Buffer)
comp, err := libsass.New(contentBuffer, fileHandle)
if err != nil {
return api.OnLoadResult{}, fmt.Errorf("sass: unable to load libsass: %s", err)
}
cwd, _ := os.Getwd()
err = comp.Option(libsass.WithSyntax(libsass.SCSSSyntax), libsass.Path(args.Path), libsass.IncludePaths(append(m.NodePaths, filepath.Dir(args.Path), cwd)))
if err != nil {
return api.OnLoadResult{}, fmt.Errorf("sass: unable to set include path: %s", err)
}
err = comp.Run()
if err != nil {
return api.OnLoadResult{}, fmt.Errorf("sass: unable to compile: %s", err)
}
files := comp.Imports()
go m.watchFiles(files)
contents := contentBuffer.String()
files = append(files, args.Path)
latestMTime := getLatestMtime(files)
cache[args.Path] = result{
sources: files,
content: contents,
mtime: latestMTime,
}
return api.OnLoadResult{
Contents: &contents,
Loader: api.LoaderCSS,
}, nil
})
},
}
}
func getLatestMtime(files []string) time.Time {
var latestMTime time.Time
for _, path := range files {
mtime, _ := os.Stat(path)
modTime := mtime.ModTime()
if modTime.After(latestMTime) {
latestMTime = modTime
}
}
return latestMTime
}