1use std::collections::{HashMap, HashSet};
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11use std::sync::atomic::{AtomicBool, Ordering};
12use std::sync::mpsc::RecvTimeoutError;
13use std::time::{Duration, Instant};
14
15use import_lint::{Access, FileModuleInfo, LintConfig, ModuleGraph, ProjectResolver, Provenance};
16use notify::event::{AccessKind, AccessMode, MetadataKind, ModifyKind};
17use notify::{Config as NotifyConfig, EventKind, PollWatcher, RecursiveMode, Watcher};
18use notify_debouncer_full::{
19 DebounceEventResult, DebouncedEvent, Debouncer, FileIdCache, NoCache, new_debouncer,
20 new_debouncer_opt,
21};
22use oxc_allocator::AllocatorPool;
23use oxc_str::CompactStr;
24
25use crate::output::RenderedDiagnostic;
26use crate::overlay::Overlays;
27use crate::report::{ReportOptions, diagnostics_by_file, finish_report};
28use crate::runner::{self, ExtractionCache, RunnerOptions};
29use crate::setup::{self, ConfigLoadError};
30use crate::source_type::source_type_for_path;
31
32#[derive(Debug, Clone, PartialEq, Eq)]
37pub enum ChangeKind {
38 ContentEdit(PathBuf),
40 Structural,
45 ConfigChanged,
47 TsconfigChanged,
49}
50
51pub struct WatchSessionOptions {
55 pub cli_paths: Vec<PathBuf>,
56 pub explicit_config: Option<PathBuf>,
57 pub cli_tsconfig: Option<PathBuf>,
58 pub report_unresolved: bool,
59 pub quiet: bool,
60 pub cwd: PathBuf,
61}
62
63pub struct CycleOutcome {
66 pub diagnostics: Vec<RenderedDiagnostic>,
67 pub has_error: bool,
68 pub rechecked_files: usize,
72 pub extracted_files: usize,
75 pub linted_files: Vec<PathBuf>,
79 pub duration: Duration,
80 pub config_error: Option<String>,
85}
86
87#[derive(Debug, Clone, Default, PartialEq, Eq)]
91pub struct WatchTargets {
92 pub roots: Vec<PathBuf>,
93 pub config_path: Option<PathBuf>,
94 pub tsconfig_path: Option<PathBuf>,
95 pub package_json_path: Option<PathBuf>,
96}
97
98impl WatchTargets {
99 fn all_paths(&self) -> Vec<PathBuf> {
100 let mut paths = self.roots.clone();
101 paths.extend(self.config_path.iter().cloned());
102 paths.extend(self.tsconfig_path.iter().cloned());
103 paths.extend(self.package_json_path.iter().cloned());
104 paths
105 }
106}
107
108pub struct WatchSession {
113 cli_paths: Vec<PathBuf>,
114 explicit_config: Option<PathBuf>,
115 cli_tsconfig: Option<PathBuf>,
116 report_unresolved: bool,
117 quiet: bool,
118 cwd: PathBuf,
119
120 config: LintConfig,
121 project_root: PathBuf,
122 config_path: Option<PathBuf>,
123
124 roots: Vec<PathBuf>,
125 tsconfig_path: Option<PathBuf>,
126
127 resolver: ProjectResolver,
128 pool: AllocatorPool,
129 extraction_cache: ExtractionCache,
130 walked_paths: Vec<PathBuf>,
131
132 overlays: Overlays,
138
139 graph: ModuleGraph,
145 diagnostics_map: HashMap<PathBuf, Vec<RenderedDiagnostic>>,
153
154 last_diagnostics: Vec<RenderedDiagnostic>,
155 last_has_error: bool,
156}
157
158struct WalkAndResolver {
163 roots: Vec<PathBuf>,
164 tsconfig_path: Option<PathBuf>,
165 resolver: ProjectResolver,
166 walked_paths: Vec<PathBuf>,
167 initial: runner::Extracted,
168}
169
170fn build_walk_and_resolver(
171 cli_paths: &[PathBuf],
172 cli_tsconfig: Option<&Path>,
173 config: &LintConfig,
174 project_root: &Path,
175 pool: &AllocatorPool,
176 cache: &mut ExtractionCache,
177 overlays: &Overlays,
178) -> WalkAndResolver {
179 let roots = setup::compute_roots(cli_paths, config, project_root);
180 let tsconfig_path = setup::compute_tsconfig(cli_tsconfig, config, project_root);
181 let self_reference_mode = setup::compute_self_reference_mode(config);
182
183 let runner_options = RunnerOptions {
184 roots: roots.clone(),
185 project_root: project_root.to_path_buf(),
186 tsconfig: tsconfig_path.clone(),
187 self_reference_mode,
188 exclude: config.exclude.clone(),
189 };
190
191 let walked_paths = crate::walk::walk_with_excludes(
192 &runner_options.roots,
193 Some(runner_options.project_root.as_path()),
194 &runner_options.exclude,
195 );
196 let initial = runner::extract_with_cache(&walked_paths, pool, cache, overlays);
197 let resolver =
198 runner::build_resolver_from_files(&runner_options, &walked_paths, &initial.files);
199
200 WalkAndResolver {
201 roots,
202 tsconfig_path,
203 resolver,
204 walked_paths,
205 initial,
206 }
207}
208
209struct RecheckStats {
210 rechecked_files: usize,
211 extracted_files: usize,
212 linted_files: Vec<PathBuf>,
213}
214
215impl WatchSession {
216 pub fn new(options: WatchSessionOptions) -> Result<Self, ConfigLoadError> {
225 let loaded = setup::load_config(options.explicit_config.as_deref(), &options.cwd)?;
226 let pool = AllocatorPool::new(rayon::current_num_threads());
227 let mut cache = ExtractionCache::new();
228 let overlays = Overlays::default();
229
230 let built = build_walk_and_resolver(
231 &options.cli_paths,
232 options.cli_tsconfig.as_deref(),
233 &loaded.config,
234 &loaded.project_root,
235 &pool,
236 &mut cache,
237 &overlays,
238 );
239
240 let mut session = WatchSession {
241 cli_paths: options.cli_paths,
242 explicit_config: options.explicit_config,
243 cli_tsconfig: options.cli_tsconfig,
244 report_unresolved: options.report_unresolved,
245 quiet: options.quiet,
246 cwd: options.cwd,
247
248 config: loaded.config,
249 project_root: loaded.project_root,
250 config_path: loaded.config_path,
251
252 roots: built.roots,
253 tsconfig_path: built.tsconfig_path,
254
255 resolver: built.resolver,
256 pool,
257 extraction_cache: cache,
258 walked_paths: built.walked_paths,
259 overlays,
260
261 graph: ModuleGraph::build(Vec::new(), HashMap::new(), HashSet::new()),
262 diagnostics_map: HashMap::new(),
263
264 last_diagnostics: Vec::new(),
265 last_has_error: false,
266 };
267 session.full_recheck(built.initial);
268 Ok(session)
269 }
270
271 pub fn set_overlay(&mut self, path: PathBuf, content: String) {
286 self.overlays.set(path, content);
287 }
288
289 pub fn clear_overlay(&mut self, path: &Path) -> bool {
294 self.overlays.clear(path)
295 }
296
297 pub fn last_diagnostics(&self) -> &[RenderedDiagnostic] {
300 &self.last_diagnostics
301 }
302
303 pub fn last_has_error(&self) -> bool {
304 self.last_has_error
305 }
306
307 pub fn watch_targets(&self) -> WatchTargets {
311 let package_json = self.project_root.join("package.json");
312 let covered_by_a_root = self.roots.iter().any(|root| package_json.starts_with(root));
313 WatchTargets {
314 roots: self.roots.clone(),
315 config_path: self.config_path.clone(),
316 tsconfig_path: self.tsconfig_path.clone(),
317 package_json_path: (!covered_by_a_root).then_some(package_json),
318 }
319 }
320
321 pub fn run_cycle(&mut self, changes: &[ChangeKind]) -> CycleOutcome {
342 let start = Instant::now();
343 let mut config_error = None;
344 let mut need_full_reload = changes
345 .iter()
346 .any(|c| matches!(c, ChangeKind::TsconfigChanged | ChangeKind::Structural));
347
348 if changes
349 .iter()
350 .any(|c| matches!(c, ChangeKind::ConfigChanged))
351 {
352 match setup::load_config(self.explicit_config.as_deref(), &self.cwd) {
353 Ok(loaded) => {
354 self.config = loaded.config;
355 self.project_root = loaded.project_root;
356 self.config_path = loaded.config_path;
357 need_full_reload = true;
358 }
359 Err(err) => {
360 config_error = Some(err.to_string());
361 }
362 }
363 }
364
365 let stats = if need_full_reload {
366 let initial = self.full_reload();
367 self.full_recheck(initial)
368 } else {
369 let changed_paths: Vec<PathBuf> = changes
370 .iter()
371 .filter_map(|change| match change {
372 ChangeKind::ContentEdit(path) => Some(path.clone()),
373 _ => None,
374 })
375 .collect();
376 match self.run_fast_cycle(&changed_paths) {
377 Some(stats) => stats,
378 None => {
379 let initial = self.full_reload();
380 self.full_recheck(initial)
381 }
382 }
383 };
384
385 CycleOutcome {
386 diagnostics: self.last_diagnostics.clone(),
387 has_error: self.last_has_error,
388 rechecked_files: stats.rechecked_files,
389 extracted_files: stats.extracted_files,
390 linted_files: stats.linted_files,
391 duration: start.elapsed(),
392 config_error,
393 }
394 }
395
396 fn full_reload(&mut self) -> runner::Extracted {
401 let built = build_walk_and_resolver(
402 &self.cli_paths,
403 self.cli_tsconfig.as_deref(),
404 &self.config,
405 &self.project_root,
406 &self.pool,
407 &mut self.extraction_cache,
408 &self.overlays,
409 );
410 self.roots = built.roots;
411 self.tsconfig_path = built.tsconfig_path;
412 self.resolver = built.resolver;
413 self.walked_paths = built.walked_paths;
414 built.initial
415 }
416
417 fn full_recheck(&mut self, initial: runner::Extracted) -> RecheckStats {
424 let outcome = runner::extract_and_link_from(
425 &self.walked_paths,
426 initial,
427 &self.resolver,
428 &self.pool,
429 &mut self.extraction_cache,
430 &self.overlays,
431 );
432 let rechecked_files = crate::timing::phase("rechecked_files_count", || {
433 outcome
434 .graph
435 .lint_targets
436 .iter()
437 .filter(|path| outcome.graph.file(path).is_some())
438 .count()
439 });
440 let extracted_files = outcome.extracted_files;
441 let linted_files: Vec<PathBuf> = crate::timing::phase("linted_files_clone", || {
442 outcome.graph.lint_targets.iter().cloned().collect()
443 });
444
445 self.graph = outcome.graph;
446
447 let targets: Vec<&Path> = self
448 .graph
449 .lint_targets
450 .iter()
451 .map(PathBuf::as_path)
452 .collect();
453 self.diagnostics_map = crate::timing::phase("build_report_total", || {
454 diagnostics_by_file(
455 &self.graph,
456 &self.config,
457 &self.project_root,
458 &ReportOptions {
459 report_unresolved: self.report_unresolved,
460 quiet: self.quiet,
461 },
462 &targets,
463 &self.overlays,
464 )
465 });
466 self.compose_from_map();
467
468 RecheckStats {
469 rechecked_files,
470 extracted_files,
471 linted_files,
472 }
473 }
474
475 fn run_fast_cycle(&mut self, changed_paths: &[PathBuf]) -> Option<RecheckStats> {
494 let mut unique_paths: Vec<PathBuf> = changed_paths.to_vec();
495 unique_paths.sort();
496 unique_paths.dedup();
497
498 for path in &unique_paths {
499 self.extraction_cache.remove(path);
500 }
501 let extracted = runner::extract_with_cache(
502 &unique_paths,
503 &self.pool,
504 &mut self.extraction_cache,
505 &self.overlays,
506 );
507 let extracted_files = extracted.extracted_files;
508
509 let mut new_files: HashMap<PathBuf, Arc<FileModuleInfo>> = HashMap::new();
510 for info in extracted.files {
511 new_files.insert(info.path.clone(), info);
512 }
513
514 for path in &unique_paths {
515 if !new_files.contains_key(path) || !self.graph.files.contains_key(path) {
516 return None;
517 }
518 }
519 for path in &unique_paths {
520 if self.graph.files[path].ambient_modules != new_files[path].ambient_modules {
521 return None;
522 }
523 }
524
525 let mut surface_changed: HashSet<PathBuf> = HashSet::new();
529 for path in &unique_paths {
530 if export_surface(&self.graph.files[path]) != export_surface(&new_files[path]) {
531 surface_changed.insert(path.clone());
532 }
533 }
534
535 for path in &unique_paths {
539 let old_info = self.graph.files[path].clone();
540 for specifier in &old_info.specifiers {
541 let key = (path.clone(), specifier.clone());
542 if let Some(Provenance::Internal(target)) = self.graph.resolutions.remove(&key) {
543 if let Some(set) = self.graph.importers.get_mut(&target) {
544 set.remove(path);
545 }
546 if let Some(set) = self.graph.star_importers.get_mut(&target) {
547 set.remove(path);
548 }
549 }
550 }
551
552 let new_info = new_files.remove(path).expect("checked above");
553 let star_specifiers: HashSet<&CompactStr> = new_info.star_exports.iter().collect();
554
555 for specifier in &new_info.specifiers {
556 let provenance = self.resolver.resolve(path, specifier);
557 if let Provenance::Internal(target) = &provenance {
558 if !self.graph.files.contains_key(target) {
559 return None;
562 }
563 self.graph
564 .importers
565 .entry(target.clone())
566 .or_default()
567 .insert(path.clone());
568 if star_specifiers.contains(specifier) {
569 self.graph
570 .star_importers
571 .entry(target.clone())
572 .or_default()
573 .insert(path.clone());
574 }
575 }
576 self.graph
577 .resolutions
578 .insert((path.clone(), specifier.clone()), provenance);
579 }
580
581 self.graph.files.insert(path.clone(), new_info);
582 }
583
584 let mut dirty: HashSet<PathBuf> = unique_paths.iter().cloned().collect();
587 for path in &unique_paths {
588 if surface_changed.contains(path) {
589 propagate_star_closure(&self.graph, path, &mut dirty);
590 }
591 }
592 dirty.retain(|path| self.graph.lint_targets.contains(path));
593
594 let dirty_refs: Vec<&Path> = dirty.iter().map(PathBuf::as_path).collect();
595 let dirty_result = crate::timing::phase("build_report_total", || {
596 diagnostics_by_file(
597 &self.graph,
598 &self.config,
599 &self.project_root,
600 &ReportOptions {
601 report_unresolved: self.report_unresolved,
602 quiet: self.quiet,
603 },
604 &dirty_refs,
605 &self.overlays,
606 )
607 });
608 self.diagnostics_map.extend(dirty_result);
609 self.compose_from_map();
610
611 let linted_files: Vec<PathBuf> = self.graph.lint_targets.iter().cloned().collect();
612
613 Some(RecheckStats {
614 rechecked_files: dirty.len(),
615 extracted_files,
616 linted_files,
617 })
618 }
619
620 fn compose_from_map(&mut self) {
627 let report = finish_report(
628 self.diagnostics_map.values().flatten().cloned(),
629 &ReportOptions {
630 report_unresolved: self.report_unresolved,
631 quiet: self.quiet,
632 },
633 );
634 self.last_diagnostics = report.diagnostics;
635 self.last_has_error = report.has_error;
636 }
637}
638
639#[derive(PartialEq, Eq)]
645struct ExportSurface {
646 export_table: HashMap<CompactStr, Option<Access>>,
647 star_exports: Vec<CompactStr>,
648}
649
650fn export_surface(info: &FileModuleInfo) -> ExportSurface {
651 ExportSurface {
652 export_table: info
653 .export_table
654 .iter()
655 .map(|(name, export)| (name.clone(), export.access))
656 .collect(),
657 star_exports: info.star_exports.clone(),
658 }
659}
660
661fn propagate_star_closure(graph: &ModuleGraph, start: &Path, dirty: &mut HashSet<PathBuf>) {
669 let mut visited_barrels: HashSet<PathBuf> = HashSet::new();
670 let mut stack: Vec<PathBuf> = vec![start.to_path_buf()];
671 while let Some(file) = stack.pop() {
672 if let Some(direct_importers) = graph.importers.get(&file) {
673 dirty.extend(direct_importers.iter().cloned());
674 }
675 if let Some(barrels) = graph.star_importers.get(&file) {
676 for barrel in barrels {
677 if visited_barrels.insert(barrel.clone()) {
678 stack.push(barrel.clone());
679 }
680 }
681 }
682 }
683}
684
685pub fn classify_event(event: &DebouncedEvent, watch: &WatchTargets) -> Vec<ChangeKind> {
704 match event.kind {
705 EventKind::Create(_) | EventKind::Remove(_) => vec![ChangeKind::Structural],
706 EventKind::Modify(ModifyKind::Name(_)) => vec![ChangeKind::Structural],
707 EventKind::Modify(ModifyKind::Metadata(
708 MetadataKind::Permissions | MetadataKind::Ownership | MetadataKind::AccessTime,
709 )) => Vec::new(),
710 EventKind::Modify(_) => event
711 .paths
712 .iter()
713 .filter_map(|path| classify_path(path, watch))
714 .collect(),
715 EventKind::Access(AccessKind::Close(AccessMode::Write)) => event
716 .paths
717 .iter()
718 .filter_map(|path| classify_path(path, watch))
719 .collect(),
720 EventKind::Access(_) | EventKind::Other | EventKind::Any => Vec::new(),
721 }
722}
723
724fn classify_path(path: &Path, watch: &WatchTargets) -> Option<ChangeKind> {
725 if path.file_name().is_some_and(|name| name == "package.json") {
726 return Some(ChangeKind::Structural);
727 }
728 if watch.config_path.as_deref() == Some(path) {
729 return Some(ChangeKind::ConfigChanged);
730 }
731 if watch.tsconfig_path.as_deref() == Some(path) {
732 return Some(ChangeKind::TsconfigChanged);
733 }
734 if source_type_for_path(path).is_some() {
735 return Some(ChangeKind::ContentEdit(path.to_path_buf()));
736 }
737 None
738}
739
740pub fn watch_loop(
755 session: &mut WatchSession,
756 debounce: Duration,
757 poll_interval: Option<Duration>,
758 shutdown: &Arc<AtomicBool>,
759 mut on_cycle: impl FnMut(&CycleOutcome),
760) -> notify::Result<()> {
761 let (tx, rx) = std::sync::mpsc::channel::<DebounceEventResult>();
762 let poll_shutdown_every = Duration::from_millis(200).min(debounce);
765
766 match poll_interval {
767 Some(interval) => {
768 let config = NotifyConfig::default().with_poll_interval(interval);
769 let mut debouncer =
770 new_debouncer_opt::<_, PollWatcher, NoCache>(debounce, None, tx, NoCache, config)?;
771 let mut watched = session.watch_targets();
772 register_watches(&mut debouncer, &watched);
773 run_event_loop(
774 &mut debouncer,
775 &rx,
776 poll_shutdown_every,
777 shutdown,
778 session,
779 &mut watched,
780 &mut on_cycle,
781 );
782 }
783 None => {
784 let mut debouncer = new_debouncer(debounce, None, tx)?;
785 let mut watched = session.watch_targets();
786 register_watches(&mut debouncer, &watched);
787 run_event_loop(
788 &mut debouncer,
789 &rx,
790 poll_shutdown_every,
791 shutdown,
792 session,
793 &mut watched,
794 &mut on_cycle,
795 );
796 }
797 }
798
799 Ok(())
800}
801
802fn register_watches<T: Watcher, C: FileIdCache>(
803 debouncer: &mut Debouncer<T, C>,
804 targets: &WatchTargets,
805) {
806 for root in &targets.roots {
807 if !root.exists() {
808 eprintln!(
809 "import-lint: {}: no such file or directory, not watching",
810 root.display()
811 );
812 continue;
813 }
814 if let Err(err) = debouncer.watch(root, RecursiveMode::Recursive) {
815 eprintln!("import-lint: failed to watch {}: {err}", root.display());
816 }
817 }
818 for extra in [
819 &targets.config_path,
820 &targets.tsconfig_path,
821 &targets.package_json_path,
822 ]
823 .into_iter()
824 .flatten()
825 {
826 if !extra.is_file() {
827 continue;
828 }
829 if let Err(err) = debouncer.watch(extra, RecursiveMode::NonRecursive) {
830 eprintln!("import-lint: failed to watch {}: {err}", extra.display());
831 }
832 }
833}
834
835fn reconcile_watches<T: Watcher, C: FileIdCache>(
841 debouncer: &mut Debouncer<T, C>,
842 old: &WatchTargets,
843 new: &WatchTargets,
844) {
845 let new_paths = new.all_paths();
846 for path in old.all_paths() {
847 if !new_paths.contains(&path) {
848 let _ = debouncer.unwatch(&path);
849 }
850 }
851 let old_paths = old.all_paths();
852 for path in new_paths {
853 if old_paths.contains(&path) || !path.exists() {
854 continue;
855 }
856 let mode = if new.roots.contains(&path) {
857 RecursiveMode::Recursive
858 } else {
859 RecursiveMode::NonRecursive
860 };
861 let _ = debouncer.watch(&path, mode);
862 }
863}
864
865#[allow(clippy::too_many_arguments)]
866fn run_event_loop<T: Watcher, C: FileIdCache>(
867 debouncer: &mut Debouncer<T, C>,
868 rx: &std::sync::mpsc::Receiver<DebounceEventResult>,
869 recv_tick: Duration,
870 shutdown: &Arc<AtomicBool>,
871 session: &mut WatchSession,
872 watched: &mut WatchTargets,
873 on_cycle: &mut impl FnMut(&CycleOutcome),
874) {
875 loop {
876 if shutdown.load(Ordering::Relaxed) {
877 return;
878 }
879
880 match rx.recv_timeout(recv_tick) {
881 Ok(Ok(events)) => {
882 let changes: Vec<ChangeKind> = events
883 .iter()
884 .flat_map(|event| classify_event(event, watched))
885 .collect();
886 if changes.is_empty() {
887 continue;
888 }
889 let outcome = session.run_cycle(&changes);
890 on_cycle(&outcome);
891
892 let new_watched = session.watch_targets();
893 if new_watched != *watched {
894 reconcile_watches(debouncer, watched, &new_watched);
895 *watched = new_watched;
896 }
897 }
898 Ok(Err(errors)) => {
899 for err in errors {
900 eprintln!("import-lint: watch error: {err}");
901 }
902 }
903 Err(RecvTimeoutError::Timeout) => {}
904 Err(RecvTimeoutError::Disconnected) => return,
905 }
906 }
907}
908
909#[cfg(test)]
910mod classify_tests {
911 use super::*;
912 use notify::Event;
913 use notify::event::{CreateKind, RemoveKind, RenameMode};
914 use std::time::Instant;
915
916 fn debounced(kind: EventKind, paths: &[&str]) -> DebouncedEvent {
917 let mut event = Event::new(kind);
918 for path in paths {
919 event = event.add_path(PathBuf::from(path));
920 }
921 DebouncedEvent::new(event, Instant::now())
922 }
923
924 fn targets() -> WatchTargets {
925 WatchTargets {
926 roots: vec![PathBuf::from("/proj/src")],
927 config_path: Some(PathBuf::from("/proj/.importlintrc.jsonc")),
928 tsconfig_path: Some(PathBuf::from("/proj/tsconfig.json")),
929 package_json_path: Some(PathBuf::from("/proj/package.json")),
930 }
931 }
932
933 #[test]
934 fn create_is_structural_regardless_of_path() {
935 let event = debounced(EventKind::Create(CreateKind::File), &["/proj/src/new.ts"]);
936 assert_eq!(
937 classify_event(&event, &targets()),
938 vec![ChangeKind::Structural]
939 );
940 }
941
942 #[test]
943 fn remove_is_structural() {
944 let event = debounced(EventKind::Remove(RemoveKind::File), &["/proj/src/gone.ts"]);
945 assert_eq!(
946 classify_event(&event, &targets()),
947 vec![ChangeKind::Structural]
948 );
949 }
950
951 #[test]
952 fn rename_is_structural() {
953 let event = debounced(
954 EventKind::Modify(ModifyKind::Name(RenameMode::Both)),
955 &["/proj/src/old.ts", "/proj/src/new.ts"],
956 );
957 assert_eq!(
958 classify_event(&event, &targets()),
959 vec![ChangeKind::Structural]
960 );
961 }
962
963 #[test]
964 fn data_modify_of_a_source_file_is_content_edit() {
965 let event = debounced(
966 EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
967 &["/proj/src/a.ts"],
968 );
969 assert_eq!(
970 classify_event(&event, &targets()),
971 vec![ChangeKind::ContentEdit(PathBuf::from("/proj/src/a.ts"))]
972 );
973 }
974
975 #[test]
976 fn close_write_of_a_source_file_is_content_edit() {
977 let event = debounced(
978 EventKind::Access(AccessKind::Close(AccessMode::Write)),
979 &["/proj/src/a.ts"],
980 );
981 assert_eq!(
982 classify_event(&event, &targets()),
983 vec![ChangeKind::ContentEdit(PathBuf::from("/proj/src/a.ts"))]
984 );
985 }
986
987 #[test]
988 fn access_open_is_ignored() {
989 let event = debounced(
990 EventKind::Access(AccessKind::Open(AccessMode::Read)),
991 &["/proj/src/a.ts"],
992 );
993 assert_eq!(classify_event(&event, &targets()), Vec::<ChangeKind>::new());
994 }
995
996 #[test]
1003 fn metadata_write_time_modify_is_content_edit() {
1004 let event = debounced(
1005 EventKind::Modify(ModifyKind::Metadata(notify::event::MetadataKind::WriteTime)),
1006 &["/proj/src/a.ts"],
1007 );
1008 assert_eq!(
1009 classify_event(&event, &targets()),
1010 vec![ChangeKind::ContentEdit(PathBuf::from("/proj/src/a.ts"))]
1011 );
1012 }
1013
1014 #[test]
1015 fn metadata_permissions_modify_is_ignored() {
1016 let event = debounced(
1017 EventKind::Modify(ModifyKind::Metadata(
1018 notify::event::MetadataKind::Permissions,
1019 )),
1020 &["/proj/src/a.ts"],
1021 );
1022 assert_eq!(classify_event(&event, &targets()), Vec::<ChangeKind>::new());
1023 }
1024
1025 #[test]
1026 fn metadata_access_time_modify_is_ignored() {
1027 let event = debounced(
1028 EventKind::Modify(ModifyKind::Metadata(
1029 notify::event::MetadataKind::AccessTime,
1030 )),
1031 &["/proj/src/a.ts"],
1032 );
1033 assert_eq!(classify_event(&event, &targets()), Vec::<ChangeKind>::new());
1034 }
1035
1036 #[test]
1037 fn package_json_modify_is_structural_even_nested() {
1038 let event = debounced(
1039 EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
1040 &["/proj/src/nested/package.json"],
1041 );
1042 assert_eq!(
1043 classify_event(&event, &targets()),
1044 vec![ChangeKind::Structural]
1045 );
1046 }
1047
1048 #[test]
1049 fn config_path_modify_is_config_changed() {
1050 let event = debounced(
1051 EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
1052 &["/proj/.importlintrc.jsonc"],
1053 );
1054 assert_eq!(
1055 classify_event(&event, &targets()),
1056 vec![ChangeKind::ConfigChanged]
1057 );
1058 }
1059
1060 #[test]
1061 fn tsconfig_path_modify_is_tsconfig_changed() {
1062 let event = debounced(
1063 EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
1064 &["/proj/tsconfig.json"],
1065 );
1066 assert_eq!(
1067 classify_event(&event, &targets()),
1068 vec![ChangeKind::TsconfigChanged]
1069 );
1070 }
1071
1072 #[test]
1073 fn modify_of_an_unrecognized_extension_is_ignored() {
1074 let event = debounced(
1075 EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
1076 &["/proj/src/readme.md"],
1077 );
1078 assert_eq!(classify_event(&event, &targets()), Vec::<ChangeKind>::new());
1079 }
1080
1081 #[test]
1082 fn event_with_no_special_kind_is_ignored() {
1083 let event = debounced(EventKind::Other, &["/proj/src/a.ts"]);
1084 assert_eq!(classify_event(&event, &targets()), Vec::<ChangeKind>::new());
1085 }
1086
1087 #[test]
1088 fn multiple_paths_classify_independently() {
1089 let event = debounced(
1090 EventKind::Modify(ModifyKind::Data(notify::event::DataChange::Any)),
1091 &["/proj/src/a.ts", "/proj/tsconfig.json", "/proj/README.md"],
1092 );
1093 let mut got = classify_event(&event, &targets());
1094 got.sort_by_key(|c| format!("{c:?}"));
1095 let mut want = vec![
1096 ChangeKind::ContentEdit(PathBuf::from("/proj/src/a.ts")),
1097 ChangeKind::TsconfigChanged,
1098 ];
1099 want.sort_by_key(|c| format!("{c:?}"));
1100 assert_eq!(got, want);
1101 }
1102}