specsync 4.2.0

Bidirectional spec-to-code validation with schema column checking — 11 languages, single binary
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use std::path::{Path, PathBuf};
use std::sync::mpsc;
use std::time::{Duration, Instant};

use colored::Colorize;
use notify::{EventKind, RecursiveMode};
use notify_debouncer_full::{DebouncedEvent, new_debouncer};

use crate::config::load_config;

/// Run the check command in watch mode, re-running on file changes.
/// Uses the hash cache to skip unchanged specs on subsequent runs.
pub fn run_watch(root: &Path, strict: bool, require_coverage: Option<usize>) {
    let config = load_config(root);
    let specs_dir = root.join(&config.specs_dir);
    let source_dirs: Vec<PathBuf> = config.source_dirs.iter().map(|d| root.join(d)).collect();

    // Collect directories to watch
    let mut watch_dirs: Vec<PathBuf> = Vec::new();
    if specs_dir.is_dir() {
        watch_dirs.push(specs_dir.clone());
    }
    for dir in &source_dirs {
        if dir.is_dir() {
            watch_dirs.push(dir.clone());
        }
    }

    if watch_dirs.is_empty() {
        eprintln!(
            "{} No directories to watch (specs_dir={}, source_dirs={:?})",
            "Error:".red(),
            config.specs_dir,
            config.source_dirs
        );
        std::process::exit(1);
    }

    // Initial run with --force to validate everything
    print_separator(None);
    run_check(root, strict, require_coverage, true);

    // Set up debounced file watcher
    let (tx, rx) = mpsc::channel();
    let mut debouncer = new_debouncer(
        Duration::from_millis(500),
        None,
        move |events| match events {
            Ok(evts) => {
                for evt in evts {
                    let _ = tx.send(evt);
                }
            }
            Err(errs) => {
                for e in errs {
                    eprintln!("{} watcher error: {e}", "Error:".red());
                }
            }
        },
    )
    .expect("Failed to create file watcher");

    for dir in &watch_dirs {
        debouncer
            .watch(dir, RecursiveMode::Recursive)
            .unwrap_or_else(|e| {
                eprintln!("{} Failed to watch {}: {e}", "Error:".red(), dir.display());
            });
    }

    println!(
        "\n{} Watching for changes in: {}",
        ">>>".cyan(),
        watch_dirs
            .iter()
            .map(|d| d.strip_prefix(root).unwrap_or(d).display().to_string())
            .collect::<Vec<_>>()
            .join(", ")
    );
    if strict {
        println!(
            "{} Strict mode active — all specs will be re-validated on each run",
            ">>>".cyan()
        );
    } else {
        println!(
            "{} Hash cache active — only changed specs will be re-validated",
            ">>>".cyan()
        );
    }
    println!("{} Press Ctrl+C to stop\n", ">>>".cyan());

    // Event loop
    let mut last_run = Instant::now();
    while let Ok(event) = rx.recv() {
        // Skip non-modify events
        if !is_relevant_event(&event) {
            continue;
        }

        // Extra debounce: don't re-run if we just ran
        if last_run.elapsed() < Duration::from_millis(300) {
            continue;
        }

        let changed_file: Option<String> = event
            .paths
            .first()
            .and_then(|p: &PathBuf| p.strip_prefix(root).ok())
            .map(|p: &Path| p.display().to_string());

        // Drain any remaining queued events
        while rx.try_recv().is_ok() {}

        print_separator(changed_file.as_deref());
        // Subsequent runs use hash cache (no --force), only re-validating changed specs
        run_check(root, strict, require_coverage, false);
        last_run = Instant::now();

        println!(
            "\n{} Watching for changes... (Ctrl+C to stop)",
            ">>>".cyan()
        );
    }
}

fn is_relevant_event(event: &DebouncedEvent) -> bool {
    matches!(
        event.kind,
        EventKind::Create(_) | EventKind::Modify(_) | EventKind::Remove(_)
    )
}

fn print_separator(changed_file: Option<&str>) {
    // Clear screen
    print!("\x1B[2J\x1B[1;1H");

    println!(
        "{}",
        "════════════════════════════════════════════════════════════".cyan()
    );
    if let Some(file) = changed_file {
        println!("{} Changed: {}", ">>>".cyan(), file.bold());
    } else {
        println!("{} Initial run (full validation)", ">>>".cyan());
    }
    println!(
        "{}",
        "════════════════════════════════════════════════════════════".cyan()
    );
}

fn build_check_args(
    root: &Path,
    strict: bool,
    require_coverage: Option<usize>,
    force: bool,
) -> Vec<std::ffi::OsString> {
    let mut args: Vec<std::ffi::OsString> = Vec::new();
    args.push("check".into());
    args.push("--root".into());
    args.push(root.as_os_str().to_owned());
    if strict {
        args.push("--strict".into());
    }
    if force {
        args.push("--force".into());
    }
    if let Some(cov) = require_coverage {
        args.push("--require-coverage".into());
        args.push(cov.to_string().into());
    }
    args
}

fn run_check(root: &Path, strict: bool, require_coverage: Option<usize>, force: bool) {
    // Fork a child process to isolate exit calls from the check command.
    use std::process::Command;

    let start = Instant::now();
    let args = build_check_args(root, strict, require_coverage, force);
    let mut cmd = Command::new(std::env::current_exe().expect("Cannot find current executable"));
    for arg in &args {
        cmd.arg(arg);
    }

    match cmd.status() {
        Ok(status) => {
            let elapsed = start.elapsed();
            if status.success() {
                println!(
                    "\n{} ({}ms)",
                    "All checks passed!".green().bold(),
                    elapsed.as_millis()
                );
            } else {
                println!(
                    "\n{} ({}ms)",
                    "Some checks failed.".red().bold(),
                    elapsed.as_millis()
                );
            }
        }
        Err(e) => {
            eprintln!("{} Failed to run check: {e}", "Error:".red());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use notify::event::{AccessKind, CreateKind, ModifyKind, RemoveKind};
    use std::path::PathBuf;
    use tempfile::TempDir;

    fn make_event(kind: EventKind) -> DebouncedEvent {
        DebouncedEvent {
            event: notify::Event {
                kind,
                paths: vec![],
                attrs: Default::default(),
            },
            time: Instant::now(),
        }
    }

    fn make_event_with_path(kind: EventKind, path: PathBuf) -> DebouncedEvent {
        DebouncedEvent {
            event: notify::Event {
                kind,
                paths: vec![path],
                attrs: Default::default(),
            },
            time: Instant::now(),
        }
    }

    // --- is_relevant_event ---

    #[test]
    fn test_is_relevant_event_create() {
        let event = make_event(EventKind::Create(CreateKind::File));
        assert!(is_relevant_event(&event));
    }

    #[test]
    fn test_is_relevant_event_modify() {
        let event = make_event(EventKind::Modify(ModifyKind::Data(
            notify::event::DataChange::Content,
        )));
        assert!(is_relevant_event(&event));
    }

    #[test]
    fn test_is_relevant_event_remove() {
        let event = make_event(EventKind::Remove(RemoveKind::File));
        assert!(is_relevant_event(&event));
    }

    #[test]
    fn test_is_relevant_event_rejects_access() {
        let event = make_event(EventKind::Access(AccessKind::Read));
        assert!(!is_relevant_event(&event));
    }

    #[test]
    fn test_is_relevant_event_rejects_other() {
        let event = make_event(EventKind::Other);
        assert!(!is_relevant_event(&event));
    }

    #[test]
    fn test_is_relevant_event_create_any() {
        let event = make_event(EventKind::Create(CreateKind::Any));
        assert!(is_relevant_event(&event));
    }

    // --- build_check_args ---

    #[test]
    fn test_build_check_args_basic() {
        let tmp = TempDir::new().unwrap();
        let args = build_check_args(tmp.path(), false, None, false);
        let strs: Vec<String> = args
            .iter()
            .map(|a| a.to_string_lossy().to_string())
            .collect();
        assert_eq!(strs[0], "check");
        assert_eq!(strs[1], "--root");
        assert_eq!(strs[2], tmp.path().to_string_lossy());
        assert_eq!(strs.len(), 3);
    }

    #[test]
    fn test_build_check_args_strict() {
        let tmp = TempDir::new().unwrap();
        let args = build_check_args(tmp.path(), true, None, false);
        let strs: Vec<String> = args
            .iter()
            .map(|a| a.to_string_lossy().to_string())
            .collect();
        assert!(strs.contains(&"--strict".to_string()));
        assert!(!strs.contains(&"--force".to_string()));
    }

    #[test]
    fn test_build_check_args_force() {
        let tmp = TempDir::new().unwrap();
        let args = build_check_args(tmp.path(), false, None, true);
        let strs: Vec<String> = args
            .iter()
            .map(|a| a.to_string_lossy().to_string())
            .collect();
        assert!(strs.contains(&"--force".to_string()));
        assert!(!strs.contains(&"--strict".to_string()));
    }

    #[test]
    fn test_build_check_args_require_coverage() {
        let tmp = TempDir::new().unwrap();
        let args = build_check_args(tmp.path(), false, Some(80), false);
        let strs: Vec<String> = args
            .iter()
            .map(|a| a.to_string_lossy().to_string())
            .collect();
        assert!(strs.contains(&"--require-coverage".to_string()));
        assert!(strs.contains(&"80".to_string()));
    }

    #[test]
    fn test_build_check_args_all_flags() {
        let tmp = TempDir::new().unwrap();
        let args = build_check_args(tmp.path(), true, Some(95), true);
        let strs: Vec<String> = args
            .iter()
            .map(|a| a.to_string_lossy().to_string())
            .collect();
        assert!(strs.contains(&"--strict".to_string()));
        assert!(strs.contains(&"--force".to_string()));
        assert!(strs.contains(&"--require-coverage".to_string()));
        assert!(strs.contains(&"95".to_string()));
        assert_eq!(strs.len(), 7); // check --root <path> --strict --force --require-coverage 95
    }

    // --- run_watch empty directories ---

    #[test]
    fn test_run_watch_collects_watch_dirs() {
        // Verify that the watch directory collection logic works correctly
        let tmp = TempDir::new().unwrap();
        let specs_dir = tmp.path().join("specs");
        let src_dir = tmp.path().join("src");
        std::fs::create_dir_all(&specs_dir).unwrap();
        std::fs::create_dir_all(&src_dir).unwrap();

        // Write a basic config
        let config_content = r#"{"specsDir": "specs", "sourceDirs": ["src"]}"#;
        std::fs::write(tmp.path().join("specsync.json"), config_content).unwrap();

        let config = load_config(tmp.path());
        let specs = tmp.path().join(&config.specs_dir);
        let source_dirs: Vec<PathBuf> = config
            .source_dirs
            .iter()
            .map(|d| tmp.path().join(d))
            .collect();

        let mut watch_dirs: Vec<PathBuf> = Vec::new();
        if specs.is_dir() {
            watch_dirs.push(specs);
        }
        for dir in &source_dirs {
            if dir.is_dir() {
                watch_dirs.push(dir.clone());
            }
        }

        assert_eq!(watch_dirs.len(), 2);
    }

    #[test]
    fn test_run_watch_empty_dirs_detected() {
        // Verify that empty watch dirs are detected
        let tmp = TempDir::new().unwrap();
        // No specs or source dirs exist
        let config_content = r#"{"specsDir": "specs", "sourceDirs": ["src"]}"#;
        std::fs::write(tmp.path().join("specsync.json"), config_content).unwrap();

        let config = load_config(tmp.path());
        let specs = tmp.path().join(&config.specs_dir);
        let source_dirs: Vec<PathBuf> = config
            .source_dirs
            .iter()
            .map(|d| tmp.path().join(d))
            .collect();

        let mut watch_dirs: Vec<PathBuf> = Vec::new();
        if specs.is_dir() {
            watch_dirs.push(specs);
        }
        for dir in &source_dirs {
            if dir.is_dir() {
                watch_dirs.push(dir.clone());
            }
        }

        assert!(watch_dirs.is_empty());
    }

    // --- event path extraction ---

    #[test]
    fn test_event_path_extraction() {
        let root = PathBuf::from("/project");
        let event = make_event_with_path(
            EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Content)),
            PathBuf::from("/project/specs/auth/auth.spec.md"),
        );

        let changed_file: Option<String> = event
            .paths
            .first()
            .and_then(|p| p.strip_prefix(&root).ok())
            .map(|p| p.display().to_string());

        assert_eq!(changed_file, Some("specs/auth/auth.spec.md".to_string()));
    }

    #[test]
    fn test_event_path_extraction_no_paths() {
        let root = PathBuf::from("/project");
        let event = make_event(EventKind::Create(CreateKind::File));

        let changed_file: Option<String> = event
            .paths
            .first()
            .and_then(|p| p.strip_prefix(&root).ok())
            .map(|p| p.display().to_string());

        assert_eq!(changed_file, None);
    }
}