-
-
Notifications
You must be signed in to change notification settings - Fork 231
/
eventhandler.go
294 lines (268 loc) · 8.99 KB
/
eventhandler.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package generatecmd
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"fmt"
"go/format"
"log/slog"
"os"
"path"
"path/filepath"
"strings"
"sync"
"time"
"github.com/a-h/templ/cmd/templ/visualize"
"github.com/a-h/templ/generator"
"github.com/a-h/templ/parser/v2"
"github.com/fsnotify/fsnotify"
)
func NewFSEventHandler(
log *slog.Logger,
dir string,
devMode bool,
genOpts []generator.GenerateOpt,
genSourceMapVis bool,
keepOrphanedFiles bool,
toStdout bool,
) *FSEventHandler {
if !path.IsAbs(dir) {
dir, _ = filepath.Abs(dir)
}
fseh := &FSEventHandler{
Log: log,
dir: dir,
fileNameToLastModTime: make(map[string]time.Time),
fileNameToLastModTimeMutex: &sync.Mutex{},
fileNameToError: make(map[string]struct{}),
fileNameToErrorMutex: &sync.Mutex{},
hashes: make(map[string][sha256.Size]byte),
hashesMutex: &sync.Mutex{},
genOpts: genOpts,
genSourceMapVis: genSourceMapVis,
DevMode: devMode,
keepOrphanedFiles: keepOrphanedFiles,
writer: writeToFile,
}
if toStdout {
fseh.writer = writeToStdout
}
if devMode {
fseh.genOpts = append(fseh.genOpts, generator.WithExtractStrings())
}
return fseh
}
type FSEventHandler struct {
Log *slog.Logger
// dir is the root directory being processed.
dir string
fileNameToLastModTime map[string]time.Time
fileNameToLastModTimeMutex *sync.Mutex
fileNameToError map[string]struct{}
fileNameToErrorMutex *sync.Mutex
hashes map[string][sha256.Size]byte
hashesMutex *sync.Mutex
genOpts []generator.GenerateOpt
genSourceMapVis bool
DevMode bool
Errors []error
keepOrphanedFiles bool
writer func(string, []byte) error
}
func writeToFile(fileName string, contents []byte) error {
return os.WriteFile(fileName, contents, 0o644)
}
func writeToStdout(_ string, contents []byte) error {
_, err := os.Stdout.Write(contents)
return err
}
func (h *FSEventHandler) HandleEvent(ctx context.Context, event fsnotify.Event) (goUpdated, textUpdated bool, err error) {
// Handle _templ.go files.
if !event.Has(fsnotify.Remove) && strings.HasSuffix(event.Name, "_templ.go") {
_, err = os.Stat(strings.TrimSuffix(event.Name, "_templ.go") + ".templ")
if !os.IsNotExist(err) {
return false, false, err
}
// File is orphaned.
if h.keepOrphanedFiles {
return false, false, nil
}
h.Log.Debug("Deleting orphaned Go file", slog.String("file", event.Name))
if err = os.Remove(event.Name); err != nil {
h.Log.Warn("Failed to remove orphaned file", slog.Any("error", err))
}
return true, false, nil
}
// Handle _templ.txt files.
if !event.Has(fsnotify.Remove) && strings.HasSuffix(event.Name, "_templ.txt") {
if h.DevMode {
// Don't delete the file if we're in dev mode, but mark that text was updated.
return false, true, nil
}
h.Log.Debug("Deleting watch mode file", slog.String("file", event.Name))
if err = os.Remove(event.Name); err != nil {
h.Log.Warn("Failed to remove watch mode text file", slog.Any("error", err))
return false, false, nil
}
return false, false, nil
}
// Handle .templ files.
if !strings.HasSuffix(event.Name, ".templ") {
return false, false, nil
}
// If the file hasn't been updated since the last time we processed it, ignore it.
if !h.UpsertLastModTime(event.Name) {
h.Log.Debug("Skipping file because it wasn't updated", slog.String("file", event.Name))
return false, false, nil
}
// Start a processor.
start := time.Now()
goUpdated, textUpdated, diag, err := h.generate(ctx, event.Name)
if err != nil {
h.Log.Error(
"Error generating code",
slog.String("file", event.Name),
slog.Any("error", err),
)
h.SetError(event.Name, true)
return goUpdated, textUpdated, fmt.Errorf("failed to generate code for %q: %w", event.Name, err)
}
if len(diag) > 0 {
for _, d := range diag {
h.Log.Warn(d.Message,
slog.String("from", fmt.Sprintf("%d:%d", d.Range.From.Line, d.Range.From.Col)),
slog.String("to", fmt.Sprintf("%d:%d", d.Range.To.Line, d.Range.To.Col)),
)
}
return
}
if errorCleared, errorCount := h.SetError(event.Name, false); errorCleared {
h.Log.Info("Error cleared", slog.String("file", event.Name), slog.Int("errors", errorCount))
}
h.Log.Debug("Generated code", slog.String("file", event.Name), slog.Duration("in", time.Since(start)))
return goUpdated, textUpdated, nil
}
func (h *FSEventHandler) SetError(fileName string, hasError bool) (previouslyHadError bool, errorCount int) {
h.fileNameToErrorMutex.Lock()
defer h.fileNameToErrorMutex.Unlock()
_, previouslyHadError = h.fileNameToError[fileName]
delete(h.fileNameToError, fileName)
if hasError {
h.fileNameToError[fileName] = struct{}{}
}
return previouslyHadError, len(h.fileNameToError)
}
func (h *FSEventHandler) UpsertLastModTime(fileName string) (updated bool) {
fileInfo, err := os.Stat(fileName)
if err != nil {
return false
}
h.fileNameToLastModTimeMutex.Lock()
defer h.fileNameToLastModTimeMutex.Unlock()
lastModTime := h.fileNameToLastModTime[fileName]
if !fileInfo.ModTime().After(lastModTime) {
return false
}
h.fileNameToLastModTime[fileName] = fileInfo.ModTime()
return true
}
func (h *FSEventHandler) UpsertHash(fileName string, hash [sha256.Size]byte) (updated bool) {
h.hashesMutex.Lock()
defer h.hashesMutex.Unlock()
lastHash := h.hashes[fileName]
if lastHash == hash {
return false
}
h.hashes[fileName] = hash
return true
}
// generate Go code for a single template.
// If a basePath is provided, the filename included in error messages is relative to it.
func (h *FSEventHandler) generate(ctx context.Context, fileName string) (goUpdated, textUpdated bool, diagnostics []parser.Diagnostic, err error) {
t, err := parser.Parse(fileName)
if err != nil {
return false, false, nil, fmt.Errorf("%s parsing error: %w", fileName, err)
}
targetFileName := strings.TrimSuffix(fileName, ".templ") + "_templ.go"
// Only use relative filenames to the basepath for filenames in runtime error messages.
absFilePath, err := filepath.Abs(fileName)
if err != nil {
return false, false, nil, fmt.Errorf("failed to get absolute path for %q: %w", fileName, err)
}
relFilePath, err := filepath.Rel(h.dir, absFilePath)
if err != nil {
return false, false, nil, fmt.Errorf("failed to get relative path for %q: %w", fileName, err)
}
// Convert Windows file paths to Unix-style for consistency.
relFilePath = filepath.ToSlash(relFilePath)
var b bytes.Buffer
sourceMap, literals, err := generator.Generate(t, &b, append(h.genOpts, generator.WithFileName(relFilePath))...)
if err != nil {
return false, false, nil, fmt.Errorf("%s generation error: %w", fileName, err)
}
formattedGoCode, err := format.Source(b.Bytes())
if err != nil {
return false, false, nil, fmt.Errorf("%s source formatting error: %w", fileName, err)
}
// Hash output, and write out the file if the goCodeHash has changed.
goCodeHash := sha256.Sum256(formattedGoCode)
if h.UpsertHash(targetFileName, goCodeHash) {
goUpdated = true
if err = h.writer(targetFileName, formattedGoCode); err != nil {
return false, false, nil, fmt.Errorf("failed to write target file %q: %w", targetFileName, err)
}
}
// Add the txt file if it has changed.
if len(literals) > 0 {
txtFileName := strings.TrimSuffix(fileName, ".templ") + "_templ.txt"
txtHash := sha256.Sum256([]byte(literals))
if h.UpsertHash(txtFileName, txtHash) {
textUpdated = true
if err = os.WriteFile(txtFileName, []byte(literals), 0o644); err != nil {
return false, false, nil, fmt.Errorf("failed to write string literal file %q: %w", txtFileName, err)
}
}
}
parsedDiagnostics, err := parser.Diagnose(t)
if err != nil {
return goUpdated, textUpdated, nil, fmt.Errorf("%s diagnostics error: %w", fileName, err)
}
if h.genSourceMapVis {
err = generateSourceMapVisualisation(ctx, fileName, targetFileName, sourceMap)
}
return goUpdated, textUpdated, parsedDiagnostics, err
}
func generateSourceMapVisualisation(ctx context.Context, templFileName, goFileName string, sourceMap *parser.SourceMap) error {
if err := ctx.Err(); err != nil {
return err
}
var templContents, goContents []byte
var templErr, goErr error
var wg sync.WaitGroup
wg.Add(2)
go func() {
defer wg.Done()
templContents, templErr = os.ReadFile(templFileName)
}()
go func() {
defer wg.Done()
goContents, goErr = os.ReadFile(goFileName)
}()
wg.Wait()
if templErr != nil {
return templErr
}
if goErr != nil {
return templErr
}
targetFileName := strings.TrimSuffix(templFileName, ".templ") + "_templ_sourcemap.html"
w, err := os.Create(targetFileName)
if err != nil {
return fmt.Errorf("%s sourcemap visualisation error: %w", templFileName, err)
}
defer w.Close()
b := bufio.NewWriter(w)
defer b.Flush()
return visualize.HTML(templFileName, string(templContents), string(goContents), sourceMap).Render(ctx, b)
}