/
processor.go
88 lines (68 loc) · 1.6 KB
/
processor.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
package svg
import (
"github.com/mateussouzaweb/compactor/compactor"
"github.com/mateussouzaweb/compactor/os"
"github.com/mateussouzaweb/compactor/pkg/generic"
)
// Init processor
func Init(options *compactor.Options) error {
return os.NodeRequire("svgo", "svgo")
}
// Minify SVG content
func Minify(content string) (string, error) {
config := os.TemporaryFile("svgo.config.js")
file := os.TemporaryFile("svgo.svg")
defer os.Delete(config)
defer os.Delete(file)
settings := "module.exports = {plugins: [{ name: 'removeViewBox', active: false }]}"
err := os.Write(config, settings, 0775)
if err != nil {
return content, err
}
err = os.Write(file, content, 0775)
if err != nil {
return content, err
}
_, err = os.Exec(
"svgo",
"--quiet",
"--config", config,
"--input", file,
"--output", file,
)
if err != nil {
return content, err
}
content, err = os.Read(file)
return content, err
}
// Optimize processor
func Optimize(options *compactor.Options, file *compactor.File) error {
if !options.ShouldCompress(file.Path) {
return nil
}
content := file.Content
content, err := Minify(content)
if err != nil {
return err
}
destination := file.Destination
perm := file.Permission
err = os.Write(destination, content, perm)
if err != nil {
return err
}
return nil
}
// Plugin return the compactor plugin instance
func Plugin() *compactor.Plugin {
return &compactor.Plugin{
Namespace: "svg",
Extensions: []string{".svg"},
Init: Init,
Resolve: generic.Resolve,
Related: generic.Related,
Transform: generic.Transform,
Optimize: Optimize,
}
}