Skip to content

Commit

Permalink
Refactor: Simplify codebase
Browse files Browse the repository at this point in the history
  • Loading branch information
allaboutevemirolive committed Oct 7, 2024
1 parent f0facc5 commit 03c2755
Show file tree
Hide file tree
Showing 5 changed files with 87 additions and 160 deletions.
74 changes: 72 additions & 2 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,3 +20,4 @@ anyhow = "1.0.86"
tracing = "0.1.40"
tracing-subscriber = "0.3.18"
globset = "0.4.14"
ignore = "0.4.23"
151 changes: 0 additions & 151 deletions src/config/ignore.rs
Original file line number Diff line number Diff line change
@@ -1,152 +1 @@
use globset::{GlobBuilder, GlobMatcher};
use std::fs::{self, DirEntry};
use std::path::{Path, PathBuf};

#[derive(Debug)]
pub struct GitIgnore {
pat: Vec<GlobMatcher>,
}

impl GitIgnore {
pub fn new() -> Self {
Self { pat: Vec::new() }
}

pub fn parse_gitignore<P>(&mut self, path: P) -> Self
where
P: AsRef<Path>,
{
let content = fs::read_to_string(path).expect("Failed to read .gitignore");
let pat = content
.lines()
.filter_map(|line| {
if line.trim().is_empty() || line.starts_with('#') {
None
} else {
Some(
GlobBuilder::new(line)
.build()
.expect("Invalid glob pattern")
.compile_matcher(),
)
}
})
.collect();

Self { pat }
}

// TODO:
pub fn should_ignore(&self, entry: &DirEntry) -> bool {
let entry_path = entry.path();
let mut matched = false;
for m in &self.pat {
if m.is_match(&entry_path) {
matched = true;
dbg!(m.glob().regex());
}
}
dbg!(&entry_path);
matched
}

pub fn get_filtered_entries<P>(&self, path: P) -> Vec<DirEntry>
where
P: AsRef<Path>,
{
fs::read_dir(path)
.expect("Failed to read directory")
.filter_map(Result::ok)
.filter(|entry| !self.should_ignore(entry))
.collect()
}
}

#[cfg(test)]
mod tests {
use super::*;
use std::fs::File;
use std::io::Write;
use tempfile::tempdir;

fn create_test_file(path: &Path) {
let mut file = File::create(path).expect("Failed to create test file");
writeln!(file, "test").expect("Failed to write to test file");
}

fn setup_test_directory() -> tempfile::TempDir {
let dir = tempdir().expect("Failed to create temp directory");

let gitignore_path = dir.path().join(".gitignore");
let test_file_path = dir.path().join("test.txt");
let sub_dir_path = dir.path().join("sub_dir");
let sub_file_path = sub_dir_path.join("test2.txt");

fs::create_dir(&sub_dir_path).expect("Failed to create sub directory");
create_test_file(&gitignore_path);
create_test_file(&test_file_path);
create_test_file(&sub_file_path);

let mut file = File::create(&gitignore_path).expect("Failed to create .gitignore");
writeln!(file, "test.txt\nsub_dir/").expect("Failed to write to .gitignore");

dir
}

#[test]
fn test_parse_gitignore() {
let dir = setup_test_directory();
let mut gitignore = GitIgnore::new();
gitignore = gitignore.parse_gitignore(dir.path().join(".gitignore"));

assert_eq!(gitignore.pat.len(), 2);
}

// cargo test -- test_should_ignore --nocapture
#[test]
fn test_should_ignore() {
let dir = setup_test_directory();
let mut gitignore = GitIgnore::new();
gitignore = gitignore.parse_gitignore(dir.path().join(".gitignore"));

let test_file = fs::read_dir(dir.path())
.unwrap()
.find(|entry| entry.as_ref().unwrap().file_name() == "test.txt")
.unwrap()
.unwrap();

let sub_dir = fs::read_dir(dir.path())
.unwrap()
.find(|entry| entry.as_ref().unwrap().file_name() == "sub_dir")
.unwrap()
.unwrap();

dbg!(&test_file);
// dbg!(&gitignore);
dbg!(&sub_dir);

dbg!(gitignore.should_ignore(&test_file));
dbg!(gitignore.should_ignore(&sub_dir));

assert!(gitignore.should_ignore(&test_file));
assert!(gitignore.should_ignore(&sub_dir));
}

// cargo test -- test_get_filtered_entries --nocapture
#[test]
fn test_get_filtered_entries() {
let dir = setup_test_directory();
let mut gitignore = GitIgnore::new();
gitignore = gitignore.parse_gitignore(dir.path().join(".gitignore"));

let entries = gitignore.get_filtered_entries(dir.path());

dbg!(&entries);

assert_eq!(entries.len(), 3);
assert!(entries
.iter()
.any(|entry| entry.file_name() == ".gitignore"));
assert!(entries.iter().any(|entry| entry.file_name() == "sub_dir"));
}
}
11 changes: 9 additions & 2 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ mod report;
mod tree;
mod walk;

use ignore::gitignore::GitignoreBuilder;
use report::stats::ReportMode;

macro_rules! trace {
Expand Down Expand Up @@ -76,7 +77,7 @@ fn build_and_print_tree_head<'tr, 'a>(
.into_builder()
.context("Failed to build base directory path")?;
tr.path_builder.append_root();
tr.print_head()?;
tr.handle_header()?;

Ok(())
}
Expand All @@ -87,8 +88,14 @@ fn iterate_directories_and_print_report<'tr, 'a>(
report_mode: ReportMode,
) -> anyhow::Result<()> {
tracing::info!("Ready to iterate directories");

let path_ignore = tr.path_builder.base_path();

let mut builder = GitignoreBuilder::new(path_ignore.clone().as_path());
builder.add(path_ignore.join(".gitignore"));

tr.walk_dir(tr.path_builder.base_path())?;
tr.print_report(report_mode)?;
tr.handle_report(report_mode)?;

Ok(())
}
10 changes: 5 additions & 5 deletions src/walk/tr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,7 +115,7 @@ impl<'tr, 'a> TreeCtxt<'tr, 'a> {
if let Some(size) = visitor.size() {
self.dir_stats.add_size(size);
}
self.print_info(visitor.metadata())?;
self.handle_info(visitor.metadata())?;
Ok(())
}

Expand Down Expand Up @@ -200,7 +200,7 @@ impl<'tr, 'a> TreeCtxt<'tr, 'a> {
}

#[cfg(unix)]
pub fn print_head(&mut self) -> anyhow::Result<()> {
pub fn handle_header(&mut self) -> anyhow::Result<()> {
use std::os::unix::fs::MetadataExt;
tracing::info!("Print directory header");

Expand All @@ -209,7 +209,7 @@ impl<'tr, 'a> TreeCtxt<'tr, 'a> {
let fmeta = self.path_builder.metadata()?;

self.dir_stats.add_size(fmeta.size());
self.print_info(&fmeta)?;
self.handle_info(&fmeta)?;
self.rg.blue(self.buf)?;
self.buf
.print_header(&fmeta, &base_path, &file_name, self.rg.head)?;
Expand All @@ -218,7 +218,7 @@ impl<'tr, 'a> TreeCtxt<'tr, 'a> {
Ok(())
}

pub fn print_info(&mut self, meta: &std::fs::Metadata) -> anyhow::Result<()> {
pub fn handle_info(&mut self, meta: &std::fs::Metadata) -> anyhow::Result<()> {
tracing::info!("Print entry's information");
self.buf.print_permission(meta, self.rg.pms)?;
self.buf.print_btime(meta, self.rg.btime)?;
Expand All @@ -230,7 +230,7 @@ impl<'tr, 'a> TreeCtxt<'tr, 'a> {
Ok(())
}

pub fn print_report(&mut self, report_mode: report::stats::ReportMode) -> anyhow::Result<()> {
pub fn handle_report(&mut self, report_mode: report::stats::ReportMode) -> anyhow::Result<()> {
tracing::info!("Print reports");
self.buf.newline()?;
self.dir_stats.accumulate_items();
Expand Down

0 comments on commit 03c2755

Please sign in to comment.