-
Notifications
You must be signed in to change notification settings - Fork 1
/
files.go
99 lines (84 loc) · 2.12 KB
/
files.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
package main
import (
"bytes"
"fmt"
"html/template"
"io"
"os"
"path/filepath"
minify "github.com/tdewolff/minify/v2"
cssminify "github.com/tdewolff/minify/v2/css"
htmlminify "github.com/tdewolff/minify/v2/html"
)
var minifier = minify.New()
func init() {
minifier.AddFunc("text/css", cssminify.Minify)
minifier.Add("text/html", &htmlminify.Minifier{
KeepDocumentTags: true,
KeepQuotes: true,
KeepEndTags: true,
})
}
func createFile(path string) (*os.File, error) {
return os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o400)
}
func writeTemplateToFile(
sourceTemplate *template.Template,
data any,
outputFolder, path string,
minifyOutput bool,
) error {
file, err := createFile(filepath.Join(outputFolder, path))
if err != nil {
return err
}
defer file.Close()
if minifyOutput {
// minify.Writer sadly doesn't work, the files end up empty.
templateBuffer := &bytes.Buffer{}
if err := sourceTemplate.Execute(templateBuffer, data); err != nil {
return fmt.Errorf("error executing template '%s': %w", sourceTemplate.Name(), err)
}
if err := minifier.Minify("text/html", file, templateBuffer); err != nil {
return fmt.Errorf("error minifying template '%s': %w", sourceTemplate.Name(), err)
}
} else {
if err := sourceTemplate.Execute(file, data); err != nil {
return fmt.Errorf("error executing template '%s': %w", sourceTemplate.Name(), err)
}
}
return nil
}
func copyDataIntoFile(source io.Reader, targetPath string) error {
target, err := createFile(targetPath)
if err != nil {
return err
}
defer target.Close()
_, err = io.Copy(target, source)
return err
}
func copyFileByPath(sourcePath, targetPath string) error {
source, err := os.Open(sourcePath)
if err != nil {
return err
}
defer source.Close()
return copyDataIntoFile(source, targetPath)
}
func createDirectories(paths ...string) error {
for _, path := range paths {
if err := os.MkdirAll(path, 0o755); err != nil {
return err
}
}
return nil
}
func removeAll(paths ...string) error {
for _, path := range paths {
if err := os.RemoveAll(path); err != nil {
return err
}
}
return nil
}