Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add support for recursively scanning directories #49

Merged
merged 5 commits into from
Jan 9, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,19 @@ use serde::{Deserialize, Serialize};
type Result<T> = std::result::Result<T, Box<dyn std::error::Error>>;

#[derive(Debug, Serialize, Deserialize, PartialEq)]
pub struct WatchConfig {}
pub struct WatchConfig {
pub include: Vec<String>,
pub exclude: Vec<String>,
pub max_depth: u8,
}

impl WatchConfig {
pub fn new() -> Self {
Self {}
Self {
include: vec![],
exclude: vec![],
max_depth: 255,
}
}
}

Expand Down Expand Up @@ -103,4 +111,4 @@ impl Config {
None => println!("{} is not being watched", path),
}
}
}
}
103 changes: 79 additions & 24 deletions src/poller.rs
Original file line number Diff line number Diff line change
@@ -1,38 +1,93 @@
use std::fs;
use std::path::Path;
use std::process;
use std::time::Instant;

use tokio::time;
use tracing::{error, info};

use crate::config::Config;
use crate::config::{Config, WatchConfig};
use crate::log::Operation;
use crate::snapshots;

/// Checks the provided `child_path` is a directory.
/// If either `includes` or `excludes` are set,
/// checks whether the path is included/excluded respectively.
fn is_valid_directory(base_path: &Path, child_path: &Path, value: &WatchConfig) -> bool {
if !child_path.is_dir() {
return false;
}

let includes = &value.include;
let excludes = &value.exclude;

let mut include = true;

if !excludes.is_empty() {
include = !excludes
.iter()
.any(|exclude| child_path.starts_with(base_path.join(exclude)));
}

if !include && !includes.is_empty() {
include = includes
.iter()
.any(|include| base_path.join(include).starts_with(child_path));
}

include
}

/// If the directory is a repo, attempts to create a snapshot.
/// Otherwise, recurses into each child directory.
#[tracing::instrument]
fn process_directory(path: &Path) {
let mut op: Option<snapshots::CaptureStatus> = None;
let mut error: Option<String> = None;
let start_time = Instant::now();

match snapshots::capture(path) {
Ok(Some(status)) => op = Some(status),
Ok(None) => (),
Err(err) => {
error = Some(format!("{}", err));
fn process_directory(base_path: &Path, current_path: &Path, value: &WatchConfig, depth: u8) {
if snapshots::is_repo(current_path) {
let mut op: Option<snapshots::CaptureStatus> = None;
let mut error: Option<String> = None;
let start_time = Instant::now();

match snapshots::capture(current_path) {
Ok(Some(status)) => op = Some(status),
Ok(None) => (),
Err(err) => {
error = Some(format!("{}", err));
}
}

let latency = (Instant::now() - start_time).as_secs_f32();
let repo = current_path
.to_str()
JakeStanger marked this conversation as resolved.
Show resolved Hide resolved
.unwrap_or("<invalid path>")
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: I don't terribly like using a null sentinel value here, seems like evades the type system.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think cargo format has authored that to me due to a line-break but it was already there. Happy to make changes while I'm here though. Not sure how to best handle this specific scenario as it's quite an edge case - any preferences?

.to_string();
let operation = Operation::Snapshot {
repo,
op,
error,
latency,
};
if operation.should_log() {
info!(operation = %serde_json::to_string(&operation).unwrap(),"info_operation")
}
} else {
if depth >= value.max_depth {
return;
}
}

let latency = (Instant::now() - start_time).as_secs_f32();
let repo = path.to_str().unwrap_or("<invalid path>").to_string();
let operation = Operation::Snapshot {
repo,
op,
error,
latency,
};
if operation.should_log() {
info!(operation = %serde_json::to_string(&operation).unwrap(),"info_operation")
if let Ok(paths) = fs::read_dir(current_path) {
paths
.filter_map(|entry| {
if let Ok(entry) = entry {
let child_path = entry.path();
if is_valid_directory(base_path, &child_path, value) {
return Some(child_path);
}
}

None
})
.for_each(|path| process_directory(base_path, path.as_path(), value, depth + 1));
}
}
}

Expand All @@ -47,9 +102,9 @@ fn do_task() {
process::exit(1);
}

for (key, _value) in config.repos {
for (key, value) in config.repos {
let path = Path::new(key.as_str());
process_directory(path);
process_directory(path, path, &value, 0);
}
}

Expand Down
4 changes: 4 additions & 0 deletions src/snapshots.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ impl fmt::Display for CaptureStatus {
}
}

pub fn is_repo(path: &Path) -> bool {
Repository::open(path).is_ok()
}

pub fn capture(path: &Path) -> Result<Option<CaptureStatus>, Error> {
let repo = Repository::open(path)?;
let head = repo.head()?.peel_to_commit()?;
Expand Down