-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathscan_folder.rs
More file actions
63 lines (52 loc) · 1.74 KB
/
Copy pathscan_folder.rs
File metadata and controls
63 lines (52 loc) · 1.74 KB
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
use std::path::{Path, PathBuf};
use crate::common::lazy::CONFIG;
use crate::common::types::FileExtension;
use regex::{Error as RegexError, Regex};
use walkdir::WalkDir;
fn pattern_to_regex(pattern: &str) -> Result<Regex, RegexError> {
let pattern = pattern.replace('.', "\\.");
let pattern = pattern.replace('*', ".*");
let pattern = format!("^{pattern}$");
Regex::new(&pattern)
}
fn is_match(pattern: &str, path: &Path) -> bool {
let regex = pattern_to_regex(pattern);
if regex.is_err() {
let invalid_pattern =
format!("Invalid ignore path pattern found in the ignore file - pattern: ${pattern}, path: ${path:?}");
panic!("{invalid_pattern}");
}
let regex = regex.unwrap();
if pattern.starts_with('!') {
!regex.is_match(path.to_str().unwrap())
} else {
regex.is_match(path.to_str().unwrap())
}
}
pub fn scan_folder<'a>(folder: &'a PathBuf, file_extension: &'a FileExtension) -> Vec<PathBuf> {
let ignore_paths = &CONFIG.ignore_patterns;
let node_modules_path = folder.join(Path::new("node_modules"));
let path = Path::new(folder);
let result: Vec<_> = WalkDir::new(path)
.follow_links(true)
.into_iter()
.filter_map(|e| e.ok())
.filter(|entry| {
// 1. ignore node modules
if entry.path().starts_with(node_modules_path.as_path()) {
return false;
}
// 2. any custom ignore paths set by user should be ignored
let should_ignore = ignore_paths
.iter()
.any(|ignore| is_match(ignore.as_str(), entry.path()));
if should_ignore {
return false;
}
let f_name = entry.file_name().to_string_lossy();
f_name.ends_with(file_extension.to_string().as_str())
})
.map(|entry| entry.path().to_owned())
.collect();
result
}