Skip to content

Commit

Permalink
feat: Organize helper modules under util/
Browse files Browse the repository at this point in the history
This is intended to help clarify the folder structure in Hipcheck. We
have some helper logic that wraps `std` functionality with nicer error
messages, or extends iterators with helpful new methods, and those can
now be found under the `util/` directory.

Signed-off-by: Andrew Lilley Brinker <[email protected]>
  • Loading branch information
alilleybrinker committed May 7, 2024
1 parent b97af17 commit b341a35
Show file tree
Hide file tree
Showing 12 changed files with 84 additions and 122 deletions.
2 changes: 1 addition & 1 deletion hipcheck/src/analysis/metric/affiliation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ use crate::data::git::Commit;
use crate::data::git::CommitContributorView;
use crate::error::Error;
use crate::error::Result;
use crate::filesystem as file;
use crate::hc_error;
use crate::util::fs as file;
use serde::de::Error as SerdeError;
use serde::de::Visitor;
use serde::Deserialize;
Expand Down
2 changes: 1 addition & 1 deletion hipcheck/src/analysis/metric/binary_detector/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ pub use query::*;

use crate::context::Context;
use crate::error::Result;
use crate::filesystem::read_toml;
use crate::hc_error;
use crate::util::fs::read_toml;
use content_inspector::inspect;
use content_inspector::ContentType;
use serde::de::Visitor;
Expand Down
2 changes: 1 addition & 1 deletion hipcheck/src/analysis/metric/linguist/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ pub use query::*;

use crate::context::Context as _;
use crate::error::Result;
use crate::filesystem::read_toml;
use crate::util::fs::read_toml;
use serde::de::Visitor;
use serde::Deserialize;
use serde::Deserializer;
Expand Down
2 changes: 1 addition & 1 deletion hipcheck/src/analysis/metric/typo.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use crate::context::Context as _;
use crate::data::Dependencies;
use crate::data::Lang;
use crate::error::Result;
use crate::filesystem as file;
use crate::util::fs as file;
use maplit::hashmap;
use serde::Deserialize;
use serde::Serialize;
Expand Down
2 changes: 1 addition & 1 deletion hipcheck/src/analysis/session/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,13 +37,13 @@ use crate::data::ModuleProviderStorage;
use crate::data::PullRequestReviewProviderStorage;
use crate::error::Error;
use crate::error::Result;
use crate::filesystem::create_dir_all;
use crate::hc_error;
use crate::report::Format;
use crate::report::ReportParams;
use crate::report::ReportParamsStorage;
use crate::shell::Phase;
use crate::shell::Shell;
use crate::util::fs::create_dir_all;
use crate::version::get_version;
use crate::version::VersionQuery;
use crate::version::VersionQueryStorage;
Expand Down
2 changes: 1 addition & 1 deletion hipcheck/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
use crate::context::Context;
use crate::error::Result;
use crate::filesystem as file;
use crate::util::fs as file;
use crate::BINARY_CONFIG_FILE;
use crate::F64;
use crate::LANGS_FILE;
Expand Down
2 changes: 1 addition & 1 deletion hipcheck/src/data/npm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ use crate::command_util::log_args;
use crate::command_util::DependentProgram;
use crate::context::Context;
use crate::error::Result;
use crate::filesystem as file;
use crate::hc_error;
use crate::util::fs as file;
use pathbuf::pathbuf;
use serde::Deserialize;
use std::collections::HashMap;
Expand Down
8 changes: 3 additions & 5 deletions hipcheck/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,13 @@ mod config;
mod context;
mod data;
mod error;
mod filesystem;
mod report;
mod shell;
#[cfg(test)]
mod test_util;
#[cfg(test)]
mod tests;
mod try_any;
mod try_filter;
mod util;
mod version;

use crate::analysis::report_builder::build_pr_report;
Expand All @@ -38,6 +36,8 @@ use crate::shell::ColorChoice;
use crate::shell::Output;
use crate::shell::Shell;
use crate::shell::Verbosity;
use crate::util::iter::TryAny;
use crate::util::iter::TryFilter;
use clap::Arg;
use clap::ArgAction;
use clap::Command;
Expand All @@ -50,8 +50,6 @@ use std::path::Path;
use std::path::PathBuf;
use std::process::exit;
use std::str::FromStr;
use try_any::TryAny;
use try_filter::TryFilter;

/// Entry point for Hipcheck.
///
Expand Down
73 changes: 0 additions & 73 deletions hipcheck/src/try_any.rs

This file was deleted.

6 changes: 6 additions & 0 deletions hipcheck/src/util.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
// SPDX-License-Identifier: Apache-2.0

//! Utility methods and types used throughout Hipcheck.
pub mod fs;
pub mod iter;
33 changes: 0 additions & 33 deletions hipcheck/src/filesystem.rs → hipcheck/src/util/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use crate::error::Result;
use crate::hc_error;
use serde::de::DeserializeOwned;
use std::fs;
use std::fs::File;
use std::ops::Not;
use std::path::Path;

Expand Down Expand Up @@ -44,28 +43,7 @@ pub fn read_json<P: AsRef<Path>, T: DeserializeOwned>(path: P) -> Result<T> {
.with_context(|| format!("failed to read as JSON '{}'", path.display()))
}

/// Write to a file.
#[allow(dead_code)]
pub fn write<P: AsRef<Path>, C: AsRef<[u8]>>(path: P, contents: C) -> Result<()> {
fn inner(path: &Path, contents: &[u8]) -> Result<()> {
fs::write(path, contents).with_context(|| format!("failed to write '{}'", path.display()))
}

inner(path.as_ref(), contents.as_ref())
}

/// Open an existing file.
#[allow(dead_code)]
pub fn open<P: AsRef<Path>>(path: P) -> Result<File> {
fn inner(path: &Path) -> Result<File> {
File::open(path).with_context(|| format!("failed to open file '{}'", path.display()))
}

inner(path.as_ref())
}

/// Create a directory and missing parents.
#[allow(dead_code)]
pub fn create_dir_all<P: AsRef<Path>>(path: P) -> Result<()> {
fn inner(path: &Path) -> Result<()> {
fs::create_dir_all(path)
Expand All @@ -75,17 +53,6 @@ pub fn create_dir_all<P: AsRef<Path>>(path: P) -> Result<()> {
inner(path.as_ref())
}

/// Remove a directory and any children.
#[allow(dead_code)]
pub fn remove_dir_all<P: AsRef<Path>>(path: P) -> Result<()> {
fn inner(path: &Path) -> Result<()> {
fs::remove_dir_all(path)
.with_context(|| format!("failed to remove directory '{}'", path.display()))
}

inner(path.as_ref())
}

/// Check that a given path exists.
pub fn exists<P: AsRef<Path>>(path: P) -> Result<()> {
fn inner(path: &Path) -> Result<()> {
Expand Down
72 changes: 68 additions & 4 deletions hipcheck/src/try_filter.rs → hipcheck/src/util/iter.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,25 @@
// SPDX-License-Identifier: Apache-2.0

//! A struct and trait for performing fallible filtering of Iterators.
//! Iterator extension traits.
/// A fallible analogue of the `Iterator::any` method
pub trait TryAny: Iterator {
fn try_any<F, E>(&mut self, mut f: F) -> Result<bool, E>
where
F: FnMut(<Self as Iterator>::Item) -> Result<bool, E>,
{
for t in self {
match f(t) {
Ok(false) => continue,
result => return result,
}
}

Ok(false)
}
}

impl<I: Iterator> TryAny for I {}

/// Represents an iterator and a fallible criterion for filtering it
pub struct FallibleFilter<I, P, E>
Expand Down Expand Up @@ -62,7 +81,17 @@ impl<I: Iterator> TryFilter for I {}
mod tests {
use super::*;

fn odd_not_three(n: &usize) -> Result<bool, String> {
fn odd_not_three(n: usize) -> Result<bool, String> {
if n == 3 {
Err(String::from("Error"))
} else if n % 2 == 1 {
Ok(true)
} else {
Ok(false)
}
}

fn odd_not_three_ref(n: &usize) -> Result<bool, String> {
if *n == 3 {
Err(String::from("Error"))
} else if *n % 2 == 1 {
Expand All @@ -72,13 +101,48 @@ mod tests {
}
}

#[test]
fn any_ok_true() {
let v = vec![2, 4, 5];

let result = v.into_iter().try_any(odd_not_three).unwrap();

assert!(result);
}

#[test]
fn any_ok_true_with_three() {
let v = vec![2, 4, 5, 3];

let result = v.into_iter().try_any(odd_not_three).unwrap();

assert!(result);
}

#[test]
fn any_ok_false() {
let v = vec![2, 4, 6, 8, 10];

let result = v.into_iter().try_any(odd_not_three).unwrap();

assert!(!result);
}

#[test]
#[should_panic]
fn any_err() {
let v = vec![2, 4, 3, 1, 5, 7, 9];

v.into_iter().try_any(odd_not_three).unwrap();
}

#[test]
fn filter_ok() {
let v = vec![1, 2, 4, 5];

let result = v
.into_iter()
.try_filter(odd_not_three)
.try_filter(odd_not_three_ref)
.collect::<Result<Vec<_>, String>>()
.unwrap();

Expand All @@ -91,7 +155,7 @@ mod tests {
let v = vec![2, 4, 6, 8, 3, 10];

v.into_iter()
.try_filter(odd_not_three)
.try_filter(odd_not_three_ref)
.collect::<Result<Vec<_>, String>>()
.unwrap();
}
Expand Down

0 comments on commit b341a35

Please sign in to comment.