Skip to content

Commit

Permalink
add directory parsing
Browse files Browse the repository at this point in the history
  • Loading branch information
Mr-Leshiy committed Aug 19, 2024
1 parent a57e83e commit 713dc1b
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 16 deletions.
74 changes: 59 additions & 15 deletions hermes/crates/cbork/cddl-linter/src/cli.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,28 +16,72 @@ pub(crate) struct Cli {
impl Cli {
/// Execute the CLI
pub(crate) fn exec(self) {
if let Err(err) = check_file(&self.path) {
println!(
"{} {}:\n{}",
Emoji::new("🚨", "Errors"),
self.path.display(),
style(err).red()
);
exit(1);
let res = if self.path.is_file() {
check_file_with_print(&self.path)
} else {
println!(
"{} {}",
Emoji::new("✅", "Success"),
self.path.display(),
);
check_dir_with_print(&self.path)
};

if !res {
exit(1);
}
}
}

/// Check the CDDL file, return any errors
fn check_file(file_path: &PathBuf) -> anyhow::Result<()> {
let mut content = std::fs::read_to_string(file_path)?;
cddl_parser::parse_cddl(&mut content, &cddl_parser::Extension::CDDLParser)
.map_err(|e| anyhow::anyhow!("{e}"))?;
cddl_parser::parse_cddl(&mut content, &cddl_parser::Extension::CDDLParser)?;
Ok(())
}

/// Check the CDDL file, prints any errors into the stdout
fn check_file_with_print(file_path: &PathBuf) -> bool {
if let Err(e) = check_file(file_path) {
println!(
"{} {}:\n{}",
Emoji::new("🚨", "Errors"),
file_path.display(),
style(e).red()
);
false
} else {
println!("{} {}", Emoji::new("✅", "Success"), file_path.display(),);
true
}
}

/// CDDL file extension. Filter directory files to apply the linter only on the CDDL
/// files.
const CDDL_FILE_EXTENSION: &str = "cddl";

/// Check the directory, prints any errors into the stdout
fn check_dir_with_print(dir_path: &PathBuf) -> bool {
let fun = |dir_path| -> anyhow::Result<bool> {
let mut res = true;
for entry in std::fs::read_dir(dir_path)? {
let entry = entry?;
let path = entry.path();
if path.is_file() {
if path.extension().is_some_and(|e| e.eq(CDDL_FILE_EXTENSION)) {
res = check_file_with_print(&path);
}
} else if path.is_dir() {
res = check_dir_with_print(&path);
}
}
Ok(res)
};

if let Err(e) = fun(dir_path) {
println!(
"{} {}:\n{}",
Emoji::new("🚨", "Errors"),
dir_path.display(),
style(e).red()
);
false
} else {
true
}
}
1 change: 0 additions & 1 deletion hermes/crates/cbork/cddl-linter/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
//! CDDL linter cli tool
mod cli;
mod errors;

fn main() {
use clap::Parser;
Expand Down

0 comments on commit 713dc1b

Please sign in to comment.