Use depth first search for files

This commit is contained in:
Cameron Cordes
2021-02-15 18:06:53 -05:00
parent 4ef70979bc
commit e899cd2648

View File

@@ -20,6 +20,11 @@ mod rack {
matches: Vec<FileMatch>,
}
struct Traversal {
dirs: Vec<DirEntry>,
entries: Vec<DirEntry>,
}
impl Rack {
pub fn new() -> Self {
Rack {
@@ -52,11 +57,12 @@ mod rack {
dir: &PathBuf,
gitignore_entries: Option<Vec<String>>,
) -> io::Result<()> {
let entries = fs::read_dir(dir)?.collect::<Vec<io::Result<DirEntry>>>();
let mut entries: Vec<DirEntry> = fs::read_dir(dir)?
.filter_map(|e| e.ok())
.collect::<Vec<DirEntry>>();
let gitignore: Option<&DirEntry> = entries
.iter()
.filter_map(|entry| entry.as_ref().ok())
.find(|entry| entry.path().file_name().unwrap() == ".gitignore");
let gitignore = match gitignore {
@@ -70,8 +76,15 @@ mod rack {
None => gitignore_entries.unwrap_or_default(),
};
for entry in entries {
let entry = entry?;
let mut initial = Vec::new();
initial.append(&mut entries);
let mut traversal = Traversal {
dirs: initial,
entries: Vec::new(),
};
while !traversal.dirs.is_empty() {
let entry = traversal.dirs.pop().unwrap();
let file_type = entry.file_type()?;
let path = entry.path();
let path = path.to_str().unwrap();
@@ -80,20 +93,26 @@ mod rack {
continue;
}
// TODO: Should borrow gitignore instead of cloning..
self.traverse_dir(&entry.path(), Some(gitignore.clone()))?;
if let Ok(mut contents) = Rack::get_dir_entries(path) {
traversal.dirs.append(&mut contents);
}
} else {
if self.should_ignore(&gitignore, path, &entry) {
continue;
}
let result = self.check_file(&entry.path());
match result {
Result::Ok(result) if !result.matches.is_empty() => self.matches.push(result),
_ => (),
}
traversal.entries.push(entry);
}
}
let mut results = traversal
.entries
.iter()
.filter_map(|e| self.check_file(&e.path()).ok())
.filter(|mat| mat.matches.len() > 0)
.collect::<Vec<FileMatch>>();
self.matches.append(&mut results);
Ok(())
}
@@ -110,6 +129,14 @@ mod rack {
false
}
fn get_dir_entries(entry: &str) -> io::Result<Vec<DirEntry>> {
let entries = fs::read_dir(entry)?
.filter_map(|e| e.ok())
.collect::<Vec<DirEntry>>();
Ok(entries)
}
fn check_file(&self, path: &Path) -> io::Result<FileMatch> {
let mut pattern = self.config.pattern.clone();
@@ -148,7 +175,9 @@ mod rack {
})
}
fn print_report(&self) {
fn print_report(&mut self) {
self.matches
.sort_by(|l, r| l.file_name.partial_cmp(&r.file_name).unwrap());
for file in &self.matches {
file.print(&self.config)
}