Skip to content

Commit

Permalink
refactor: Move parser configuration and add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jpedroh committed Nov 27, 2023
1 parent 3a93e1c commit 8f0c776
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 18 deletions.
25 changes: 7 additions & 18 deletions bin/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
use std::{error::Error, ffi::OsStr, fs};
mod parser_configuration;

use std::{error::Error, fs};

use clap::Parser;

Expand All @@ -22,28 +24,15 @@ struct Args {
merge_path: std::path::PathBuf,
}

fn get_parser_configuration_by_file_path(
file_path: &std::path::PathBuf,
) -> Result<parsing::ParserConfiguration, String> {
file_path
.extension()
.and_then(OsStr::to_str)
.and_then(|extension| match extension {
"java" => Some(model::Language::Java),
_ => None,
})
.map(parsing::ParserConfiguration::from)
.ok_or(format!("Could not retrieve parsing configuration for file {}", file_path.display()))
}

fn main() -> Result<(), Box<dyn Error>> {
let args = Args::parse();

let base = fs::read_to_string(&args.base_path)?;
let left = fs::read_to_string(args.left_path)?;
let right = fs::read_to_string(args.right_path)?;

let parser_configuration = get_parser_configuration_by_file_path(&args.base_path)?;

let parser_configuration =
parser_configuration::get_parser_configuration_by_file_path(&args.base_path)?;

let base_tree = parsing::parse_string(&base, &parser_configuration).unwrap();
let left_tree = parsing::parse_string(&left, &parser_configuration).unwrap();
Expand Down
33 changes: 33 additions & 0 deletions bin/src/parser_configuration.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
pub fn get_parser_configuration_by_file_path(
file_path: &std::path::Path,
) -> Result<parsing::ParserConfiguration, String> {
file_path
.extension()
.and_then(std::ffi::OsStr::to_str)
.and_then(|extension| match extension {
"java" => Some(model::Language::Java),
_ => None,
})
.map(parsing::ParserConfiguration::from)
.ok_or(format!(
"Could not retrieve parsing configuration for file {}",
file_path.display()
))
}

#[cfg(test)]
mod tests {
use crate::parser_configuration::get_parser_configuration_by_file_path;

#[test]
fn if_the_file_extension_has_no_parser_available_it_returns_error() {
let file_path = std::path::PathBuf::from("/path/without/extension");
assert!(get_parser_configuration_by_file_path(&file_path).is_err())
}

#[test]
fn if_the_file_extension_has_a_parser_available_it_returns_error() {
let file_path = std::path::PathBuf::from("/path/for/java/file/Example.java");
assert!(get_parser_configuration_by_file_path(&file_path).is_ok())
}
}

0 comments on commit 8f0c776

Please sign in to comment.