use core::fmt;
use globset::{Glob, GlobSet, GlobSetBuilder};
use std::path::{Path, PathBuf};
const DEFAULT_IGNORE_GLOBS: &[&str] = &[
"**/.*",
"**/.*/**",
"**/node_modules/**",
"**/logs/**",
"**/pids/**",
];
const MATCH_EVERYTHING: &str = "**";
pub(crate) fn own_log_ignores<'a>(
root: &Path,
logs: impl IntoIterator<Item = &'a Path>,
) -> Vec<String> {
logs.into_iter()
.filter_map(|log| literal_glob_under(root, log))
.collect()
}
fn literal_glob_under(root: &Path, path: &Path) -> Option<String> {
let relative = canonical_parent_of(path);
let relative = relative.strip_prefix(root).ok()?;
let mut pattern = String::new();
for component in relative.iter() {
if !pattern.is_empty() {
pattern.push('/');
}
pattern.push_str(&globset::escape(component.to_str()?));
}
(!pattern.is_empty()).then_some(pattern)
}
fn canonical_parent_of(path: &Path) -> PathBuf {
let (Some(parent), Some(file)) = (path.parent(), path.file_name()) else {
return path.to_path_buf();
};
std::fs::canonicalize(parent).map_or_else(|_| path.to_path_buf(), |dir| dir.join(file))
}
#[derive(Debug)]
pub struct WatchFilter {
include: GlobSet,
ignore: GlobSet,
}
fn build_glob_set(patterns: &[&str]) -> Result<GlobSet, WatchFilterError> {
let mut builder = GlobSetBuilder::new();
for pattern in patterns {
let glob = Glob::new(pattern).map_err(|err| WatchFilterError::Glob {
pattern: (*pattern).to_string(),
reason: err.to_string(),
})?;
builder.add(glob);
}
builder.build().map_err(|err| {
WatchFilterError::Glob {
pattern: patterns.join(", "),
reason: err.to_string(),
}
})
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum WatchFilterError {
Glob {
pattern: String,
reason: String,
},
}
impl fmt::Display for WatchFilterError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Glob { pattern, reason } => {
write!(f, "invalid watch pattern `{pattern}`: {reason}")
}
}
}
}
impl core::error::Error for WatchFilterError {}
#[derive(Debug)]
pub(super) struct RootedFilter {
pub(super) root: PathBuf,
pub(super) filter: WatchFilter,
}
impl RootedFilter {
pub(super) fn triggers(&self, path: &Path) -> bool {
let Ok(relative) = path.strip_prefix(&self.root) else {
return false;
};
if relative.as_os_str().is_empty() {
return false;
}
self.filter.triggers(relative)
}
}
impl WatchFilter {
pub fn new(
watch_options: &[String],
ignore_watch: &[String],
) -> Result<Self, WatchFilterError> {
let include_patterns: Vec<&str> = if watch_options.is_empty() {
vec![MATCH_EVERYTHING]
} else {
watch_options.iter().map(String::as_str).collect()
};
let ignore_patterns: Vec<&str> = DEFAULT_IGNORE_GLOBS
.iter()
.copied()
.chain(ignore_watch.iter().map(String::as_str))
.collect();
Ok(Self {
include: build_glob_set(&include_patterns)?,
ignore: build_glob_set(&ignore_patterns)?,
})
}
#[must_use]
pub fn triggers(&self, path: &Path) -> bool {
self.include.is_match(path) && !self.ignore.is_match(path)
}
}
#[cfg(test)]
mod tests {
use core::time::Duration;
use std::path::{Path, PathBuf};
use super::*;
use crate::fake::ProcScript;
use super::super::testing::*;
#[test]
fn empty_watch_options_matches_every_path() {
let filter = WatchFilter::new(&[], &[]).unwrap();
assert!(filter.triggers(Path::new("top.txt")));
assert!(filter.triggers(Path::new("src/a/b.rs")));
}
#[test]
fn an_explicit_pattern_matches_its_own_tree_and_nothing_else() {
let filter = WatchFilter::new(&["src/**/*.rs".to_string()], &[]).unwrap();
assert!(filter.triggers(Path::new("src/a/b.rs")));
assert!(!filter.triggers(Path::new("src/a/b.txt")));
assert!(!filter.triggers(Path::new("other/a.rs")));
}
#[test]
fn default_ignores_beat_an_explicit_include() {
let filter = WatchFilter::new(&["**".to_string()], &[]).unwrap();
assert!(!filter.triggers(Path::new(".git/index")));
assert!(!filter.triggers(Path::new("node_modules/x/y.js")));
}
#[test]
fn an_ignore_watch_entry_beats_an_include() {
let filter = WatchFilter::new(&["**".to_string()], &["dist/**".to_string()]).unwrap();
assert!(!filter.triggers(Path::new("dist/bundle.js")));
assert!(filter.triggers(Path::new("src/main.rs")));
}
#[test]
fn a_pattern_matching_nothing_never_triggers() {
let filter = WatchFilter::new(&["nomatch/**/*.foo".to_string()], &[]).unwrap();
assert!(!filter.triggers(Path::new("src/main.rs")));
}
#[test]
fn an_invalid_glob_is_rejected_with_its_pattern() {
let err = WatchFilter::new(&["[".to_string()], &[]).unwrap_err();
let WatchFilterError::Glob { pattern, reason } = err;
assert_eq!(pattern, "[");
assert!(!reason.is_empty());
let _: &dyn core::error::Error = &WatchFilterError::Glob {
pattern: "[".to_string(),
reason: "boom".to_string(),
};
}
#[test]
fn watch_filter_error_display_names_the_pattern_and_its_reason() {
let err = WatchFilterError::Glob {
pattern: "[".to_string(),
reason: "unclosed character class".to_string(),
};
assert_eq!(
err.to_string(),
"invalid watch pattern `[`: unclosed character class"
);
}
#[test]
fn a_path_outside_the_root_never_triggers() {
let filter = RootedFilter {
root: PathBuf::from("/watched"),
filter: WatchFilter::new(&[], &[]).unwrap(),
};
assert!(!filter.triggers(Path::new("/elsewhere/file.rs")));
assert!(filter.triggers(Path::new("/watched/file.rs")));
}
#[test]
fn the_root_itself_never_triggers_however_wide_the_watch_options() {
let filter = matches_everything(PathBuf::from("/watched"));
assert!(!filter.triggers(Path::new("/watched")));
assert!(filter.triggers(Path::new("/watched/other/a.txt")));
}
#[test]
fn own_log_ignores_covers_only_the_paths_under_the_root() {
let root = tempfile::tempdir().unwrap();
let elsewhere = tempfile::tempdir().unwrap();
let canonical = std::fs::canonicalize(root.path()).unwrap();
let inside = root.path().join("app[0].log");
let outside = elsewhere.path().join("web-0-out.log");
let ignores = own_log_ignores(&canonical, [inside.as_path(), outside.as_path()]);
assert_eq!(ignores, vec!["app[[]0[]].log".to_string()]);
let filter = WatchFilter::new(&[], &ignores).unwrap();
assert!(!filter.triggers(Path::new("app[0].log")));
assert!(filter.triggers(Path::new("app0.log")));
assert!(filter.triggers(Path::new("src/main.rs")));
}
#[tokio::test(start_paused = true)]
async fn a_batch_of_only_ignored_paths_produces_no_restart() {
let (handle, mut rx, _dir) = spawn_test_fixture(vec![ProcScript::never_exits(); 2]);
let name = "web";
start_app(&handle, name, 1).await;
let root = PathBuf::from("/watched");
let (tx, group) = spawn_group_matching_everything(&root, name, &handle);
tx.send(changed(vec![root.join(".git/index")])).unwrap();
assert_no_restart_within(&mut rx, name, Duration::from_secs(5)).await;
group.abort();
}
}