Add basic gitignore functionality

No support for wildcards and exact matches might screw up nested
directories. The Globbing functionality seems like its going to be a
pain to properly match up.
This commit is contained in:
Cameron Cordes
2020-05-20 15:38:26 -04:00
parent ee3e61b76d
commit 1229c05d8d
4 changed files with 60 additions and 9 deletions

View File

@@ -1,6 +1,6 @@
use rack::config::Config;
use rack::filematch::*;
use std::fs::{self, File};
use std::fs::{self, DirEntry, File};
use std::io;
use std::io::prelude::*;
use std::path::Path;
@@ -19,7 +19,9 @@ fn main() {
}
};
let results = traverse_dir(&config, path, |config, path| check_file(config, path));
let results = traverse_dir(&config, path, Option::None, |config, path| {
check_file(config, path)
});
match results {
Result::Ok(matches) if matches.len() == 0 => println!("No matches :("),
Result::Ok(matches) => print_report(&config, &matches),
@@ -30,15 +32,46 @@ fn main() {
fn traverse_dir(
config: &Config,
dir: &Path,
gitignore_entries: Option<Vec<String>>,
operation: fn(&Config, &Path) -> io::Result<FileMatch>,
) -> io::Result<Vec<FileMatch>> {
let mut matches: Vec<FileMatch> = Vec::new();
for entry in fs::read_dir(dir)? {
let entries = fs::read_dir(dir)?.collect::<Vec<io::Result<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 {
Some(g) => {
let file = io::BufReader::new(File::open(g.path())?);
file.lines()
.map(|line| line.unwrap().trim().to_owned())
.filter(|line| line.len() > 0 && !line.starts_with('#'))
.collect::<Vec<String>>()
}
None => gitignore_entries.unwrap_or(Vec::new()),
};
for entry in entries {
let entry = entry?;
let file_type = entry.file_type()?;
let path = entry.path().to_str().unwrap().to_owned();
if file_type.is_dir() {
let mut results = traverse_dir(&config, &entry.path(), operation)?;
if config.use_gitignore {
let should_ignore = gitignore.iter().find(|&line| path.contains(&line.clone()));
if should_ignore.unwrap_or(&String::from("")).len() > 0
|| entry.path().to_str().unwrap().contains("/.git")
{
continue;
}
}
// TODO: Should borrow gitignore instead of cloning..
let mut results =
traverse_dir(&config, &entry.path(), Some(gitignore.clone()), operation)?;
let has_results = results
.iter()
.filter({ |mat| mat.matches.len() > 0 })
@@ -49,6 +82,15 @@ fn traverse_dir(
matches.append(&mut results);
}
} else {
if config.use_gitignore {
let should_ignore = gitignore.iter().find(|&line| path.contains(&line.clone()));
if should_ignore.unwrap_or(&String::from("")).len() > 0
|| entry.path().to_str().unwrap().contains("/.git")
{
continue;
}
}
let result = operation(&config, &entry.path());
match result {
Result::Ok(result) if result.matches.len() > 0 => matches.push(result),