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

Implements List Input + Error Cleanup #11

Merged
merged 3 commits into from
Aug 30, 2024
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
4 changes: 4 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,7 @@ rustflags = ["-C", "target-feature=+crt-static"]

[target.x86_64-unknown-linux-musl]
rustflags = ["-C", "target-feature=+crt-static"]

[profile.profiling]
inherits = "release"
debug = true
79 changes: 58 additions & 21 deletions hypnagogic_cli/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,8 +53,9 @@ struct Args {
/// Location of the templates folder
#[arg(short, long, default_value_t = String::from("templates"))]
templates: String,
/// Input directory/file
input: String,
/// List of space separated output directory/file(s)
#[arg(num_args = 1.., value_delimiter = ' ', required = true)]
input: Vec<String>,
}

const VERSION: &str = env!("CARGO_PKG_VERSION");
Expand Down Expand Up @@ -96,27 +97,62 @@ fn main() -> Result<()> {
tracing::subscriber::set_global_default(subscriber)?;
};

if !Path::new(&input).exists() {
return Err(anyhow!("Input path does not exist!"));
}
let mut invalid_paths: Vec<String> = vec![];
let mut inaccessible_paths: Vec<std::io::Error> = vec![];
let files_to_process: Vec<PathBuf> = input
.into_iter()
.filter_map(|potential_path| {
if !Path::new(&potential_path).exists() {
invalid_paths.push(potential_path);
return None;
}

let files_to_process: Vec<PathBuf> = if metadata(&input)?.is_file() {
vec![Path::new(&input).to_path_buf()]
} else {
WalkDir::new(&input)
.into_iter()
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file())
.filter(|e| {
if let Some(extension) = e.path().extension() {
extension == "toml"
} else {
false
let metadata = match metadata(&potential_path) {
Ok(data) => data,
Err(error) => {
inaccessible_paths.push(error);
return None;
}
})
.map(|e| e.into_path())
.collect()
};
};
if metadata.is_file() {
return Some(vec![Path::new(&potential_path).to_path_buf()]);
}
Some(
WalkDir::new(potential_path)
.into_iter()
.filter_map(Result::ok)
.filter(|e| e.file_type().is_file())
.filter(|e| {
if let Some(extension) = e.path().extension() {
extension == "toml"
} else {
false
}
})
.map(|e| e.into_path())
.collect(),
)
})
.flatten()
.collect();

if !invalid_paths.is_empty() || !inaccessible_paths.is_empty() {
let mut error_text = if !invalid_paths.is_empty() {
format!(
"The input path(s) [{}] do not exist",
invalid_paths.join(", ")
)
} else {
"".to_string()
};
if !inaccessible_paths.is_empty() {
error_text = inaccessible_paths
.iter()
.fold(error_text, |acc, elem| format!("{}\n{}", acc, elem));
}
return Err(anyhow!("{}", error_text));
}

debug!(files = ?files_to_process, "Files to process");

let num_files = files_to_process.len();
Expand Down Expand Up @@ -183,6 +219,7 @@ fn process_icon(
match err {
ConfigError::Template(template_err) => {
match template_err {
TemplateError::NoTemplateDir(dir_path) => Error::NoTemplateFolder(dir_path),
TemplateError::FailedToFindTemplate(template_string, expected_path) => {
Error::TemplateNotFound {
source_config,
Expand Down
2 changes: 2 additions & 0 deletions hypnagogic_core/src/config/template_resolver/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ use toml::Value;

#[derive(Debug, Error)]
pub enum TemplateError {
#[error("Template dir not found while creating FileResolver {0}")]
NoTemplateDir(PathBuf),
#[error("Failed to find template: `{0}`, expected `{1}`")]
FailedToFindTemplate(String, PathBuf),
#[error("Generic toml parse error while resolving template: {0}")]
Expand Down
22 changes: 3 additions & 19 deletions hypnagogic_core/src/config/template_resolver/file_resolver.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
use core::default::Default;
use core::result::Result::{Err, Ok};
use std::fmt::Formatter;
use std::fs;
use std::path::{Path, PathBuf};

Expand All @@ -16,28 +15,13 @@ pub struct FileResolver {
path: PathBuf,
}

#[derive(Debug)]
pub struct NoTemplateDirError(PathBuf);

impl std::fmt::Display for NoTemplateDirError {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
write!(
f,
"Template dir not found while creating FileResolver: {:?}",
self.0
)
}
}

impl std::error::Error for NoTemplateDirError {}

impl FileResolver {
/// Creates a new `FileResolver` with the given path
/// # Errors
/// Returns an error if `path` does not exist.
pub fn new(path: &Path) -> Result<Self, NoTemplateDirError> {
let pathbuf =
fs::canonicalize(path).map_err(|_e| NoTemplateDirError(path.to_path_buf()))?;
pub fn new(path: &Path) -> Result<Self, TemplateError> {
let pathbuf = fs::canonicalize(path)
.map_err(|_e| TemplateError::NoTemplateDir(path.to_path_buf()))?;
Ok(FileResolver { path: pathbuf })
}
}
Expand Down
Loading