use std::collections::BTreeSet;
use super::{AggregatedPluginResult, PathRuleIndex};
#[derive(Debug, Clone)]
pub struct UsedExportNames {
rules: PathRuleIndex<Vec<String>>,
}
impl UsedExportNames {
#[must_use]
pub fn names_for(&self, rel_path: &str) -> BTreeSet<&str> {
self.rules
.matching(rel_path)
.into_iter()
.flat_map(|exports| exports.iter().map(String::as_str))
.collect()
}
}
impl AggregatedPluginResult {
#[must_use]
pub fn used_export_names(&self) -> UsedExportNames {
UsedExportNames {
rules: PathRuleIndex::build(
self.used_exports
.iter()
.map(|rule| (&rule.rule.path, rule.rule.exports.clone())),
"used_exports pattern",
),
}
}
}
#[cfg(test)]
mod tests {
use super::super::{PluginUsedExportRule, UsedExportRule};
use super::*;
fn result(rules: Vec<PluginUsedExportRule>) -> AggregatedPluginResult {
AggregatedPluginResult {
used_exports: rules,
..AggregatedPluginResult::default()
}
}
#[test]
fn names_for_a_path_join_each_matching_rule() {
let names = result(vec![
PluginUsedExportRule::new(
"nextjs",
UsedExportRule::new("app/**/page.{ts,tsx}", ["default", "revalidate"]),
),
PluginUsedExportRule::new("nextjs", UsedExportRule::new("app/**/*.tsx", ["dynamic"])),
PluginUsedExportRule::new(
"tanstack-router",
UsedExportRule::new("src/routes/**/*.tsx", ["Route"]),
),
])
.used_export_names();
assert_eq!(
names.names_for("app/blog/page.tsx"),
BTreeSet::from(["default", "dynamic", "revalidate"])
);
assert_eq!(
names.names_for("src/routes/index.tsx"),
BTreeSet::from(["Route"])
);
assert!(names.names_for("src/lib/math.ts").is_empty());
}
#[test]
fn an_excluded_glob_and_an_invalid_glob_match_no_file() {
let names = result(vec![
PluginUsedExportRule::new(
"tanstack-router",
UsedExportRule::new("src/routes/**/*.tsx", ["Route"])
.with_excluded_globs(["src/routes/**/-*.tsx"]),
),
PluginUsedExportRule::new("broken", UsedExportRule::new("src/[", ["config"])),
])
.used_export_names();
assert_eq!(
names.names_for("src/routes/posts.tsx"),
BTreeSet::from(["Route"])
);
assert!(names.names_for("src/routes/-helper.tsx").is_empty());
assert!(names.names_for("src/[").is_empty());
}
}