fernctl/commands/watch.rs
1//! # Configuration Watch Command
2//!
3//! The `watch` command monitors a TOML configuration file for changes and
4//! automatically converts it to JSON when modifications are detected. This
5//! enables a live-reload workflow where users can edit their configuration
6//! and immediately see changes reflected in the running shell.
7//!
8//! ## Usage
9//!
10//! ```bash
11//! # Watch default config location
12//! fernctl watch
13//!
14//! # Watch a specific file
15//! fernctl watch --config ./my-config.toml
16//!
17//! # Custom output location
18//! fernctl watch --config config.toml --output theme.json
19//!
20//! # Adjust debounce timing (milliseconds)
21//! fernctl watch --debounce 200
22//!
23//! # Disable desktop notifications
24//! fernctl watch --quiet
25//! ```
26//!
27//! ## How It Works
28//!
29//! The watch command uses operating system facilities to efficiently monitor
30//! files for changes:
31//!
32//! | Platform | Technology |
33//! |----------|------------|
34//! | Linux | inotify |
35//! | macOS | FSEvents |
36//! | Windows | ReadDirectoryChangesW |
37//!
38//! This is more efficient than polling — the process sleeps until the OS
39//! signals that the file has changed.
40//!
41//! ## Event Flow
42//!
43//! ```text
44//! ┌─────────────────────────────────────────────────────────────────────┐
45//! │ Watch Loop │
46//! │ │
47//! │ ┌──────────────┐ ┌──────────────┐ ┌──────────────────────────┐│
48//! │ │ inotify │ │ Debounce │ │ Convert & Notify ││
49//! │ │ (or equiv) │──▶│ (100ms) │──▶│ ││
50//! │ └──────────────┘ └──────────────┘ │ ┌─────────┐ ││
51//! │ ▲ │ │ Parse │ ││
52//! │ │ │ │ TOML │ ││
53//! │ │ │ └────┬────┘ ││
54//! │ File modified │ │ ││
55//! │ by user │ ▼ ││
56//! │ │ ┌─────────┐ ││
57//! │ │ │Validate │ ││
58//! │ │ └────┬────┘ ││
59//! │ │ │ ││
60//! │ │ ▼ ││
61//! │ │ ┌─────────┐ ┌────────┐ ││
62//! │ │ │ Write │ │ Notify │ ││
63//! │ │ │ JSON │──▶│ User │ ││
64//! │ │ └─────────┘ └────────┘ ││
65//! │ └──────────────────────────┘│
66//! └─────────────────────────────────────────────────────────────────────┘
67//! ```
68//!
69//! ## Debouncing
70//!
71//! Editors often trigger multiple file system events when saving a file:
72//!
73//! 1. File truncated (write begins)
74//! 2. Data written
75//! 3. File closed
76//! 4. Metadata updated
77//!
78//! Without debouncing, we might try to parse a half-written file. The
79//! debouncer waits for events to settle before processing:
80//!
81//! ```text
82//! Events: ┃━━━━━━━━━━┃ ┃━━━━┃ ┃
83//! │ truncate │ │write│ │
84//! │ modify │ │close│ │
85//! Time: ──────────────────────────────────────────────▶
86//! 0ms 10ms 50ms 100ms (debounce expires)
87//! │
88//! ▼
89//! Process file
90//! ```
91//!
92//! ## Error Handling
93//!
94//! The watch command is designed to be resilient — configuration errors
95//! should not crash the watcher. Instead:
96//!
97//! | Error Type | Behavior |
98//! |------------|----------|
99//! | Parse error | Notify user, keep watching |
100//! | Validation error | Notify user, keep watching |
101//! | File deleted | Notify user, keep watching |
102//! | Watch system error | Exit with error |
103//!
104//! This allows users to fix mistakes without restarting the watcher:
105//!
106//! ```text
107//! $ fernctl watch
108//! Watching ~/.config/fern/config.toml...
109//!
110//! [14:32:01] ✓ Config reloaded
111//! [14:32:15] ✗ Parse error at line 5 (keep editing...)
112//! [14:32:28] ✓ Config reloaded
113//! ```
114//!
115//! ## Desktop Notifications
116//!
117//! When notifications are enabled (the default), the watch command sends
118//! desktop notifications via the freedesktop.org notification spec:
119//!
120//! | Scenario | Notification |
121//! |----------|--------------|
122//! | Success | "Config Reloaded" (info) |
123//! | Warning | "Unknown Key: colour" (warning) |
124//! | Error | "Invalid Color: #gg0000" (error) |
125//!
126//! These appear in whatever notification daemon is running (fern-shell's
127//! own notification center, dunst, mako, etc.).
128//!
129//! ## Integration with QuickShell
130//!
131//! QuickShell watches the JSON file using its own `FileView` component.
132//! When we write a new JSON file, QuickShell automatically reloads:
133//!
134//! ```text
135//! ┌────────────┐ ┌─────────────┐ ┌────────────────┐
136//! │ User │ │ fernctl │ │ QuickShell │
137//! │ edits │──────▶ watch │──────▶│ reloads │
138//! │ TOML │ │ writes │ │ UI updates │
139//! └────────────┘ │ JSON │ └────────────────┘
140//! └─────────────┘
141//! ```
142//!
143//! No IPC is needed — file watching on both sides creates a clean
144//! decoupled architecture.
145//!
146//! ## Exit Codes
147//!
148//! | Code | Meaning |
149//! |------|---------|
150//! | `0` | Normal exit (Ctrl+C) |
151//! | `1` | Initialization error (file not found, etc.) |
152//! | `2` | Watch system error |
153//!
154//! ## Programmatic Usage
155//!
156//! ```rust,ignore
157//! use fernctl::commands::watch::{run, WatchOptions, WatchEvent};
158//! use fernctl::adapters::{TomlConfigAdapter, FileSystemAdapter};
159//!
160//! let config_adapter = TomlConfigAdapter::new();
161//! let persist_adapter = FileSystemAdapter::new();
162//!
163//! let options = WatchOptions {
164//! debounce_ms: 100,
165//! notify_on_success: true,
166//! notify_on_error: true,
167//! verbose: true,
168//! };
169//!
170//! // Run the watch loop (blocks until interrupted)
171//! run(
172//! &config_path,
173//! &json_path,
174//! options,
175//! &config_adapter,
176//! &persist_adapter,
177//! |event| {
178//! // Custom event handler
179//! match event {
180//! WatchEvent::Reloaded { warnings } => { /* ... */ }
181//! WatchEvent::Error { error } => { /* ... */ }
182//! }
183//! },
184//! )?;
185//! ```
186//!
187//! ## Resource Usage
188//!
189//! The watch command is designed to be lightweight:
190//!
191//! - **CPU**: Near-zero when idle (event-driven, not polling)
192//! - **Memory**: ~5-10 MB baseline
193//! - **File descriptors**: 2-3 per watched file
194//!
195//! It's safe to run indefinitely in the background.
196
197use crate::error::{FernError, Notification, Notifiable, Result, Severity};
198use crate::ports::inbound::ConfigPort;
199use crate::ports::outbound::PersistPort;
200use notify_debouncer_mini::{new_debouncer, notify::RecursiveMode, DebounceEventResult};
201use std::path::Path;
202use std::sync::mpsc::{channel, Receiver};
203use std::time::Duration;
204
205/// Options for the watch command.
206///
207/// These options control the behavior of file watching, notification delivery,
208/// and output verbosity.
209///
210/// # Example
211///
212/// ```rust
213/// use fernctl::commands::watch::WatchOptions;
214///
215/// let options = WatchOptions {
216/// debounce_ms: 200, // Wait 200ms for events to settle
217/// notify_on_success: true,
218/// notify_on_error: true,
219/// verbose: false,
220/// };
221/// ```
222///
223/// # Default Values
224///
225/// | Option | Default | Rationale |
226/// |--------|---------|-----------|
227/// | `debounce_ms` | 100 | Fast enough to feel responsive, slow enough to debounce |
228/// | `notify_on_success` | true | User wants feedback that changes were applied |
229/// | `notify_on_error` | true | Errors should be visible |
230/// | `verbose` | false | Terminal output is opt-in |
231#[derive(Debug, Clone)]
232pub struct WatchOptions {
233 /// Debounce duration in milliseconds.
234 ///
235 /// After a file change is detected, the watcher waits this long for
236 /// additional events before processing. This prevents multiple conversions
237 /// when editors save files in multiple steps.
238 ///
239 /// Recommended values:
240 /// - 50-100ms for fast editors (vim, emacs)
241 /// - 100-200ms for slower editors or network filesystems
242 pub debounce_ms: u64,
243
244 /// Whether to send a notification on successful reload.
245 ///
246 /// When `true`, a brief notification confirms each successful conversion.
247 /// Set to `false` for a quieter experience.
248 pub notify_on_success: bool,
249
250 /// Whether to send a notification on errors.
251 ///
252 /// When `true`, parse errors and validation failures trigger notifications.
253 /// Strongly recommended to keep this enabled.
254 pub notify_on_error: bool,
255
256 /// Whether to print events to the terminal.
257 ///
258 /// When enabled, each event is logged with a timestamp:
259 /// ```text
260 /// [14:32:01] Config reloaded
261 /// [14:32:15] Error: invalid color at line 5
262 /// ```
263 pub verbose: bool,
264}
265
266impl Default for WatchOptions {
267 fn default() -> Self {
268 Self {
269 debounce_ms: 100,
270 notify_on_success: true,
271 notify_on_error: true,
272 verbose: false,
273 }
274 }
275}
276
277/// Events emitted during the watch loop.
278///
279/// These events can be used to implement custom notification handling
280/// or logging behavior.
281///
282/// # Example
283///
284/// ```rust,ignore
285/// match event {
286/// WatchEvent::Reloaded { warnings, bytes_written } => {
287/// println!("Reloaded! {} warnings, {} bytes", warnings.len(), bytes_written);
288/// }
289/// WatchEvent::Error { error, notification } => {
290/// eprintln!("Error: {}", error);
291/// desktop_notify(¬ification);
292/// }
293/// WatchEvent::Started { input, output } => {
294/// println!("Watching {} -> {}", input.display(), output.display());
295/// }
296/// }
297/// ```
298#[derive(Debug)]
299pub enum WatchEvent {
300 /// The watch loop has started.
301 Started {
302 /// Path being watched.
303 input: std::path::PathBuf,
304 /// Path where JSON is written.
305 output: std::path::PathBuf,
306 },
307
308 /// Configuration was successfully reloaded.
309 Reloaded {
310 /// Warnings encountered during validation (non-fatal).
311 warnings: Vec<String>,
312 /// Number of bytes written to the output file.
313 bytes_written: usize,
314 },
315
316 /// An error occurred during reload.
317 ///
318 /// The watcher continues running after errors — this is not fatal.
319 Error {
320 /// The error that occurred.
321 error: FernError,
322 /// A notification ready to send to the desktop.
323 notification: Notification,
324 },
325
326 /// File system event received but debouncing.
327 ///
328 /// Only emitted in verbose mode.
329 Debouncing,
330}
331
332/// A callback function for watch events.
333///
334/// Implement this to customize how events are handled during watching.
335pub type EventHandler = dyn Fn(WatchEvent);
336
337/// Runs the configuration watch loop.
338///
339/// This function blocks, continuously watching the input file and converting
340/// it to JSON when changes are detected. It only returns on unrecoverable
341/// errors or when interrupted.
342///
343/// # Arguments
344///
345/// * `input` — Path to the TOML configuration file to watch
346/// * `output` — Path where JSON output will be written
347/// * `options` — Watch configuration options
348/// * `config_adapter` — Adapter for parsing TOML
349/// * `persist_adapter` — Adapter for writing JSON
350///
351/// # Returns
352///
353/// - `Ok(())` — Watch loop exited cleanly (interrupted)
354/// - `Err(FernError)` — Unrecoverable error (e.g., watch system failure)
355///
356/// # Errors
357///
358/// Returns an error if:
359/// - The input file does not exist at startup
360/// - The file watcher cannot be initialized (e.g., too many open files)
361/// - The parent directory of the output file doesn't exist
362///
363/// Configuration errors during the watch loop do **not** cause this function
364/// to return an error — they are reported via notification and logged.
365///
366/// # Example
367///
368/// ```rust,ignore
369/// use fernctl::commands::watch::{run, WatchOptions};
370/// use fernctl::adapters::{TomlConfigAdapter, FileSystemAdapter};
371/// use std::path::Path;
372///
373/// let config_adapter = TomlConfigAdapter::new();
374/// let persist_adapter = FileSystemAdapter::new();
375/// let options = WatchOptions::default();
376///
377/// // This blocks until Ctrl+C
378/// run(
379/// Path::new("~/.config/fern/config.toml"),
380/// Path::new("~/.config/fern/config.json"),
381/// options,
382/// &config_adapter,
383/// &persist_adapter,
384/// )?;
385/// ```
386///
387/// # Graceful Shutdown
388///
389/// The watch loop responds to SIGINT (Ctrl+C) by exiting cleanly. No special
390/// cleanup is required — in-progress writes are completed atomically before
391/// the function returns.
392///
393/// # Thread Safety
394///
395/// This function is not async and blocks the calling thread. For async usage,
396/// wrap it in a blocking task:
397///
398/// ```rust,ignore
399/// tokio::task::spawn_blocking(|| {
400/// watch::run(&input, &output, options, &config, &persist)
401/// }).await?;
402/// ```
403pub fn run<P, Q>(
404 input: P,
405 output: Q,
406 options: WatchOptions,
407 config_adapter: &impl ConfigPort,
408 persist_adapter: &impl PersistPort,
409) -> Result<()>
410where
411 P: AsRef<Path>,
412 Q: AsRef<Path>,
413{
414 let input = input.as_ref();
415 let output = output.as_ref();
416
417 // Verify input exists
418 if !input.exists() {
419 return Err(FernError::io(
420 format!("config file not found: {}", input.display()),
421 std::io::Error::new(std::io::ErrorKind::NotFound, "file not found"),
422 ));
423 }
424
425 // Set up the file watcher with debouncing
426 let (tx, rx): (_, Receiver<DebounceEventResult>) = channel();
427
428 let mut debouncer = new_debouncer(Duration::from_millis(options.debounce_ms), tx)
429 .map_err(|e| FernError::watch(format!("failed to create file watcher: {e}")))?;
430
431 debouncer
432 .watcher()
433 .watch(input, RecursiveMode::NonRecursive)
434 .map_err(|e| FernError::watch(format!("failed to watch file: {e}")))?;
435
436 // Log startup
437 if options.verbose {
438 eprintln!(
439 "Watching {} -> {}",
440 input.display(),
441 output.display()
442 );
443 eprintln!("Press Ctrl+C to stop");
444 }
445
446 // Initial conversion
447 if let Err(e) = convert_and_report(input, output, &options, config_adapter, persist_adapter) {
448 if options.verbose {
449 eprintln!("[initial] Error: {e}");
450 }
451 // Don't exit on initial error — start watching anyway
452 }
453
454 // Watch loop
455 loop {
456 match rx.recv() {
457 Ok(Ok(events)) => {
458 // Check if any events are relevant to our file
459 let relevant = events.iter().any(|e| e.path == input);
460 if !relevant {
461 continue;
462 }
463
464 if options.verbose {
465 eprintln!("[{}] File changed, converting...", timestamp());
466 }
467
468 if let Err(e) =
469 convert_and_report(input, output, &options, config_adapter, persist_adapter)
470 {
471 if options.verbose {
472 eprintln!("[{}] Error: {e}", timestamp());
473 }
474 // Continue watching — don't exit on config errors
475 }
476 }
477 Ok(Err(error)) => {
478 // Debouncer error (usually recoverable)
479 if options.verbose {
480 eprintln!("[{}] Watch warning: {error}", timestamp());
481 }
482 }
483 Err(e) => {
484 // Channel closed — watcher died
485 return Err(FernError::watch(format!("watcher channel closed: {e}")));
486 }
487 }
488 }
489}
490
491/// Converts the config and reports the result.
492///
493/// This is the core conversion logic extracted for reuse between initial
494/// conversion and watch-triggered conversions.
495fn convert_and_report(
496 input: &Path,
497 output: &Path,
498 options: &WatchOptions,
499 config_adapter: &impl ConfigPort,
500 persist_adapter: &impl PersistPort,
501) -> Result<()> {
502 // Load and validate
503 let raw = config_adapter.load_from_file(input)?;
504 let validated = raw.validate()?;
505
506 // Collect warnings
507 let warnings: Vec<String> = validated.warnings().iter().map(ToString::to_string).collect();
508
509 // Report warnings
510 for warning in &warnings {
511 if options.verbose {
512 eprintln!("[{}] Warning: {}", timestamp(), warning);
513 }
514 if options.notify_on_error {
515 // Warnings are non-fatal but should be shown
516 send_notification(&Notification::warning("Config Warning", warning));
517 }
518 }
519
520 // Convert and persist
521 let theme = validated.into_theme();
522 persist_adapter.save_theme(&theme, output)?;
523
524 // Report success
525 if options.verbose {
526 eprintln!(
527 "[{}] Converted {} -> {}",
528 timestamp(),
529 input.display(),
530 output.display(),
531 );
532 }
533
534 if options.notify_on_success {
535 send_notification(&Notification::info(
536 "Config Reloaded",
537 format!("Updated {}", output.display()),
538 ));
539 }
540
541 Ok(())
542}
543
544/// Sends a desktop notification.
545///
546/// This function attempts to send a notification via the system notification
547/// daemon. It fails silently if notifications are unavailable.
548fn send_notification(notification: &Notification) {
549 // Use notify-send as a fallback until we have proper D-Bus integration
550 // This is a simple implementation that works on most Linux desktops
551 let urgency = match notification.severity {
552 Severity::Info => "low",
553 Severity::Warning => "normal",
554 Severity::Error | Severity::Fatal => "critical",
555 };
556
557 let mut body = notification.body.clone();
558 if let Some(suggestion) = ¬ification.suggestion {
559 body.push_str("\n\n");
560 body.push_str(suggestion);
561 }
562
563 // Fire and forget — don't block on notification delivery
564 let _ = std::process::Command::new("notify-send")
565 .arg("--app-name=fernctl")
566 .arg(format!("--urgency={urgency}"))
567 .arg(¬ification.title)
568 .arg(&body)
569 .spawn();
570}
571
572/// Returns the current time formatted for log output.
573fn timestamp() -> String {
574 // Simple timestamp without external dependency
575 // In production, consider using chrono or time crate
576 use std::time::SystemTime;
577
578 let now = SystemTime::now()
579 .duration_since(SystemTime::UNIX_EPOCH)
580 .unwrap_or_default();
581
582 let secs = now.as_secs();
583 let hours = (secs / 3600) % 24;
584 let mins = (secs / 60) % 60;
585 let secs = secs % 60;
586
587 format!("{hours:02}:{mins:02}:{secs:02}")
588}
589
590/// Callback wrapper that sends errors as notifications.
591///
592/// This helper implements the common pattern of converting errors to
593/// notifications and sending them:
594///
595/// ```rust,ignore
596/// let result = some_operation();
597/// notify_on_error(result, &options)?;
598/// ```
599#[allow(dead_code)]
600fn notify_on_error<T>(result: Result<T>, options: &WatchOptions) -> Result<T> {
601 match result {
602 Ok(v) => Ok(v),
603 Err(e) => {
604 if options.notify_on_error {
605 send_notification(&e.to_notification());
606 }
607 Err(e)
608 }
609 }
610}
611
612#[cfg(test)]
613mod tests {
614 use super::*;
615
616 #[test]
617 fn watch_options_default() {
618 let opts = WatchOptions::default();
619 assert_eq!(opts.debounce_ms, 100);
620 assert!(opts.notify_on_success);
621 assert!(opts.notify_on_error);
622 assert!(!opts.verbose);
623 }
624
625 #[test]
626 fn timestamp_format() {
627 let ts = timestamp();
628 // Should be HH:MM:SS format
629 assert_eq!(ts.len(), 8);
630 assert_eq!(ts.chars().nth(2), Some(':'));
631 assert_eq!(ts.chars().nth(5), Some(':'));
632 }
633}