Skip to content

Commit

Permalink
Implements List Input + Error Cleanup (#11)
Browse files Browse the repository at this point in the history
* Implements support for list input

It is not inconcievable to want to cut more then one directory in one
go, particulary in the case of downstreams.

I'm not 100% that we should be avoiding just targeting the whole project
in cases like ss13, but a list input is pretty easy to implement so may
as well.

I am considering doing the same thing to the templates string but that
is mildly more complex.

* Some nicety stuff, cleans up weird erorr work

We were defining a new error type and then casting it to another,
different error type immediately.

There's no reason to do this because we have an existing error type
system that handles this kind of casting better. Should just be usin
that
  • Loading branch information
LemonInTheDark authored Aug 30, 2024
1 parent 268e553 commit 495405b
Show file tree
Hide file tree
Showing 4 changed files with 67 additions and 40 deletions.
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

0 comments on commit 495405b

Please sign in to comment.