-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcmd_watch.go
More file actions
369 lines (318 loc) · 10.3 KB
/
cmd_watch.go
File metadata and controls
369 lines (318 loc) · 10.3 KB
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package main
import (
"bufio"
"embed"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"slices"
"strings"
"syscall"
"time"
"github.com/rsanheim/plur/autodetect"
"github.com/rsanheim/plur/config"
"github.com/rsanheim/plur/internal/buildinfo"
"github.com/rsanheim/plur/job"
"github.com/rsanheim/plur/logger"
"github.com/rsanheim/plur/watch"
)
// Embed the watcher binaries at compile time
//
//go:embed embedded/watcher/*
var watcherBinaries embed.FS
func runWatchInstall(force bool) error {
configPaths := config.InitConfigPaths()
return watch.InstallBinary(watcherBinaries, configPaths.BinDir, configPaths.PlurHome, force)
}
func printHelp() {
cmdWidth := 20
fmt.Println("Available commands")
fmt.Printf(" %-*s %s\n", cmdWidth, "[Enter]", "Run all tests")
fmt.Printf(" %-*s %s\n", cmdWidth, "debug", "Toggle debug mode")
fmt.Printf(" %-*s %s\n", cmdWidth, "help", "Show this help")
fmt.Printf(" %-*s %s\n", cmdWidth, "reload", "Reload plur")
fmt.Printf(" %-*s %s\n", cmdWidth, "exit (Ctrl-C)", "Exit watch mode")
fmt.Println()
}
// loadWatchConfiguration resolves job and watch mappings
func loadWatchConfiguration(cli *PlurCLI, explicitJobName string) (*autodetect.ResolveJobResult, []watch.WatchMapping, error) {
result, err := autodetect.ResolveJob(explicitJobName, cli.Job, nil)
if err != nil {
return nil, nil, err
}
// Use user's watches if provided, else from resolved result
watches := cli.WatchMappings
if len(watches) == 0 {
watches = result.Watches
}
logInheritedFields(result.Name, result.Inherited)
return result, watches, nil
}
// resetTerminal restores terminal to a known good state.
// This handles cases where jobs (like goreleaser with progress bars) may have
// left the terminal in raw mode with echo disabled.
func resetTerminal() {
cmd := exec.Command("stty", "sane")
cmd.Stdin = os.Stdin
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
_ = cmd.Run() // Best effort, ignore errors
}
// reload performs an atomic process replacement (Unix/Linux/macOS only)
// and also maintains same args & env, including the debug state from previous process
func reload(manager *watch.WatcherManager) error {
fmt.Println("Reloading plur...")
fmt.Println()
execPath, err := os.Executable()
if err != nil {
return fmt.Errorf("failed to get executable path: %w", err)
}
// Must cleanup before exec - defers won't run
manager.Stop()
resetTerminal()
args := os.Args
hasDebugFlag := slices.Contains(args, "--debug") || slices.Contains(args, "-d")
if logger.IsDebugEnabled() && !hasDebugFlag {
args = append(args, "--debug")
}
if !logger.IsDebugEnabled() && hasDebugFlag {
args = slices.DeleteFunc(args, func(arg string) bool {
return arg == "--debug" || arg == "-d"
})
}
env := os.Environ()
err = syscall.Exec(execPath, args, env)
if err != nil {
return fmt.Errorf("failed to exec new process: %w", err)
}
os.Exit(1)
return nil
}
func printWatchInfo(watchDirs []string) {
absoluteWatchDirs := make([]string, len(watchDirs))
for i, dir := range watchDirs {
absoluteWatchDirs[i], _ = filepath.Abs(dir)
}
fmt.Printf("plur %s ready and watching %v\n", buildinfo.GetVersionInfo(), strings.Join(absoluteWatchDirs, ", "))
fmt.Println()
}
func runWatchWithConfig(globalConfig *config.GlobalConfig, runCmd *WatchRunCmd, watchCmd *WatchCmd, cli *PlurCLI) error {
logger.Logger.Info("plur watch starting!", "version", buildinfo.GetVersionInfo())
result, watches, err := loadWatchConfiguration(cli, cli.Use)
if err != nil {
return fmt.Errorf("failed to load watch configuration: %w", err)
}
resolvedJob := result.Job
// Build jobs map for FindTargetsForFile - include all user-defined jobs
// plus the resolved job (for when auto-detection is used)
jobs := result.ResolvedJobs
if len(watches) > 0 {
logger.Logger.Info("Watch configuration loaded", "job", resolvedJob.Name, "watch_mappings", len(watches))
} else {
logger.Logger.Info("No watch mappings configured, file changes will not trigger tests")
}
debounceDelay := time.Duration(runCmd.Debounce) * time.Millisecond
logger.Logger.Debug("Debounce delay", "ms", runCmd.Debounce)
// Create debouncer and file event handler
debouncer := watch.NewDebouncer(debounceDelay)
var watchDirs []string
for _, mapping := range watches {
dir := mapping.SourceDir()
watchDirs = append(watchDirs, dir)
}
logger.Logger.Debug("Watch directories before filtering", "dirs", watchDirs)
watchDirs, err = watch.FilterDirectories(watchDirs)
if err != nil {
return fmt.Errorf("failed to filter watch directories: %w", err)
}
logger.Logger.Debug("Watch directories after filtering", "dirs", watchDirs)
if len(watchDirs) == 0 {
return fmt.Errorf("no directories to watch found in watch mappings")
}
globalIgnorePatterns := watchCmd.Ignore
if len(globalIgnorePatterns) == 0 {
globalIgnorePatterns = watch.DefaultIgnorePatterns
}
logger.Logger.Debug("Global watch ignore patterns", "patterns", globalIgnorePatterns)
projectName := "unknown"
if cwd, err := os.Getwd(); err == nil {
projectName = filepath.Base(cwd)
}
logger.Logger.Info("plur configuration info",
"project", projectName,
"directories", watchDirs,
"job", resolvedJob.Name,
"reason", result.Reason,
"watch", fmt.Sprintf("%+v", watches),
"debug", globalConfig.Debug,
"verbose", globalConfig.Verbose,
"debounce", runCmd.Debounce,
"timeout", runCmd.Timeout)
if runCmd.Timeout > 0 {
logger.Logger.Debug("plur in timeout mode - with auto exit after " + fmt.Sprintf("%d", runCmd.Timeout) + " seconds")
}
watcherPath, err := watch.GetWatcherBinaryPath(globalConfig.ConfigPaths.BinDir)
if err != nil {
return fmt.Errorf("failed to find watcher binary: %v", err)
}
watcherConfig := &watch.ManagerConfig{
Directories: watchDirs,
DebounceDelay: debounceDelay,
TimeoutSeconds: runCmd.Timeout,
}
// Create and start the watcher manager
manager := watch.NewWatcherManager(watcherConfig, watcherPath)
if err := manager.Start(); err != nil {
return err
}
defer manager.Stop()
var timeoutChan <-chan time.Time
if runCmd.Timeout > 0 {
timeoutChan = time.After(time.Duration(runCmd.Timeout) * time.Second)
}
// Set up signal handling for graceful shutdown
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM, syscall.SIGHUP)
stdinChan := make(chan string, 10)
go func() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
stdinChan <- line
}
}()
// Set up prompt channel - buffered to coalesce multiple prompt requests
promptChan := make(chan struct{}, 1)
showPrompt := func() {
select {
case promptChan <- struct{}{}:
default: // already queued, skip
}
}
// Set up reload channel - buffered to coalesce multiple reload requests
reloadChan := make(chan struct{}, 1)
triggerReload := func() {
select {
case reloadChan <- struct{}{}:
default: // already queued, skip
}
}
printWatchInfo(watchDirs)
printHelp()
showPrompt()
cwd, _ := os.Getwd()
if resolvedCwd, err := filepath.EvalSymlinks(cwd); err == nil {
if resolvedCwd != cwd {
logger.Logger.Debug("watch", "cwd_symlink_resolved", true, "original", cwd, "resolved", resolvedCwd)
}
cwd = resolvedCwd
}
// Create file event handler
handler := &watch.FileEventHandler{
Jobs: jobs,
Watches: watches,
CWD: cwd,
}
for {
select {
case input := <-stdinChan:
logger.Logger.Debug("received via stdin", "input", input)
switch input {
case "":
fmt.Println("Running all tests...")
cmd := job.BuildJobAllCmd(resolvedJob)
watch.RunCommand(cmd)
fmt.Println()
showPrompt()
case "help":
printHelp()
showPrompt()
case "reload":
logger.Logger.Debug("User requested process reload")
triggerReload()
case "debug":
logger.ToggleDebug()
if logger.IsDebugEnabled() {
fmt.Println("Debug output enabled")
} else {
fmt.Println("Debug output disabled")
}
showPrompt()
case "exit":
fmt.Println("Exiting watch mode...")
return nil
default:
fmt.Printf("Unknown command: '%s'\n", input)
printHelp()
showPrompt()
}
case event := <-manager.Events():
// Early filtering - skip events we don't care about
if event.PathType == "watcher" {
logger.Logger.Debug("watch", "fullPath", event.PathName, "event", event.EffectType, "type", event.PathType, "associated", fmt.Sprintf("%v", event.Associated))
continue
}
path, err := filepath.Rel(cwd, event.PathName)
if err != nil {
logger.Logger.Warn("watch", "fullPath", event.PathName, "event", event.EffectType, "type", event.PathType, "error", fmt.Sprintf("failed to get relative path: %v", err))
continue
}
if watch.IsIgnored(path, globalIgnorePatterns) {
continue
}
if event.EffectType != "modify" && event.EffectType != "create" {
continue
}
logger.Logger.Debug("watch", "path", path, "fullPath", event.PathName, "event", event.EffectType, "type", event.PathType)
// Debounce and process
debouncer.Debounce([]string{path}, func(paths []string) {
result := handler.HandleBatch(paths)
if result.ShouldReload {
triggerReload()
}
if len(result.ExecutedJobs) > 0 {
fmt.Println()
showPrompt()
}
})
case err := <-manager.Errors():
return fmt.Errorf("watcher error: %v", err)
case <-timeoutChan:
logger.Logger.Info("plur timeout reached, exiting!", "event", "timeout", "timeout", runCmd.Timeout)
fmt.Println("Timeout reached, exiting!")
return nil
case sig := <-sigChan:
switch sig {
case syscall.SIGINT:
fmt.Println("Received SIGINT, shutting down gracefully...")
return nil
case syscall.SIGTERM:
fmt.Println("Received SIGTERM, shutting down gracefully...")
return nil
case syscall.SIGHUP:
fmt.Println("Received SIGHUP, reloading plur...")
if err := reload(manager); err != nil {
logger.Logger.Error("Failed to reload", "error", err)
fmt.Println("Failed to reload:", err)
showPrompt()
continue
}
// reload() calls syscall.Exec which replaces process, so we never reach here on success
return nil
default:
fmt.Printf("Received signal %v, shutting down gracefully...\n", sig)
return nil
}
case <-promptChan:
fmt.Print("[plur] > ")
case <-reloadChan:
if err := reload(manager); err != nil {
logger.Logger.Error("Failed to reload", "error", err)
fmt.Println("Failed to reload:", err)
showPrompt()
}
}
}
}