use glob::Pattern;
#[derive(Debug, Clone)]
pub struct SafetyPreset {
patterns: Vec<Pattern>,
}
impl SafetyPreset {
pub fn new() -> Self {
let pattern_strings = Self::default_patterns();
let patterns = pattern_strings
.iter()
.filter_map(|p| Pattern::new(p).ok())
.collect();
SafetyPreset { patterns }
}
pub fn default_patterns() -> Vec<&'static str> {
vec![
".env",
".env.*",
".ssh/**",
"**/.ssh/**",
"*.pem",
"*.key",
"*.p12",
"*.pfx",
"*_rsa",
"*_dsa",
"*_ecdsa",
"*_ed25519",
"id_*",
"*.crt",
"*.cer",
"*.der",
"*.keystore",
"*.jks",
"credentials",
"credentials.*",
"**/credentials",
"**/credentials.*",
"secrets",
"secrets.*",
"**/secrets",
"**/secrets.*",
"target/**",
"**/target/**",
"node_modules/**",
"**/node_modules/**",
"vendor/**",
"**/vendor/**",
"dist/**",
"**/dist/**",
"build/**",
"**/build/**",
".build/**",
"**/.build/**",
"out/**",
"**/out/**",
".npm/**",
"**/.npm/**",
".yarn/**",
"**/.yarn/**",
".pnpm-store/**",
"**/.pnpm-store/**",
".idea/**",
"**/.idea/**",
".vscode/**",
"**/.vscode/**",
"*.swp",
"*.swo",
"*~",
".DS_Store",
"Thumbs.db",
"desktop.ini",
".cache/**",
"**/.cache/**",
"__pycache__/**",
"**/__pycache__/**",
"*.pyc",
".git/**",
"**/.git/**",
"logs/**",
"**/logs/**",
"*.log",
"tmp/**",
"**/tmp/**",
"temp/**",
"**/temp/**",
]
}
pub fn matches(&self, path: &str) -> bool {
let normalized_path = path.replace('\\', "/");
self.patterns
.iter()
.any(|pattern| pattern.matches(&normalized_path))
}
}
impl Default for SafetyPreset {
fn default() -> Self {
Self::new()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_safety_preset_matches() {
let preset = SafetyPreset::new();
assert!(preset.matches(".env"));
assert!(preset.matches(".env.local"));
assert!(preset.matches(".env.production"));
assert!(preset.matches(".ssh/id_rsa"));
assert!(preset.matches("home/.ssh/config"));
assert!(preset.matches("server.pem"));
assert!(preset.matches("private.key"));
assert!(preset.matches("id_rsa"));
assert!(preset.matches("target/debug/app"));
assert!(preset.matches("node_modules/package/index.js"));
assert!(preset.matches("project/node_modules/lib.js"));
assert!(preset.matches(".DS_Store"));
assert!(preset.matches("Thumbs.db"));
assert!(!preset.matches("src/main.rs"));
assert!(!preset.matches("README.md"));
assert!(!preset.matches("Cargo.toml"));
}
}