Handle the case where a path has no file extension
- ID
c68216c- date
2024-09-04 06:58:29+00:00- author
Alex Chan <alex@alexwlchan.net>- parent
907dafc- message
Handle the case where a path has no file extension- changed files
2 files, 27 additions, 6 deletions
Changed files
src/get_image_colors.rs (5939) → src/get_image_colors.rs (6101)
diff --git a/src/get_image_colors.rs b/src/get_image_colors.rs
index dfe4cd4..66cbedd 100644
--- a/src/get_image_colors.rs
+++ b/src/get_image_colors.rs
@@ -17,8 +17,11 @@ use image::{AnimationDecoder, DynamicImage, Frame, ImageFormat};
use palette::cast::from_component_slice;
use palette::{IntoColor, Lab, Srgba};
-pub fn get_image_colors(path: &PathBuf) -> Vec<Lab> {
- let format = image::ImageFormat::from_extension(path.extension().unwrap());
+pub fn get_image_colors(path: &PathBuf) -> Result<Vec<Lab>, &str> {
+ let format = match path.extension() {
+ Some(ext) => image::ImageFormat::from_extension(ext),
+ None => return Err("Path has no file extension, so could not determine image format"),
+ };
let f = match File::open(path) {
Ok(im) => im,
@@ -63,7 +66,7 @@ pub fn get_image_colors(path: &PathBuf) -> Vec<Lab> {
.map(|x| x.into_format::<_, f32>().into_color())
.collect();
- lab
+ Ok(lab)
}
fn get_bytes_for_static_image(img: DynamicImage) -> Vec<u8> {
@@ -160,11 +163,11 @@ mod test {
// processed correctly.
#[test]
fn it_gets_colors_for_mri_fruit() {
- get_image_colors(&PathBuf::from("./src/tests/garlic.gif"));
+ get_image_colors(&PathBuf::from("./src/tests/garlic.gif")).unwrap();
}
#[test]
fn get_colors_for_webp() {
- get_image_colors(&PathBuf::from("./src/tests/purple.webp"));
+ get_image_colors(&PathBuf::from("./src/tests/purple.webp")).unwrap();
}
}
src/main.rs (8922) → src/main.rs (9423)
diff --git a/src/main.rs b/src/main.rs
index 3dc25cd..830e32d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -31,7 +31,13 @@ struct Cli {
fn main() {
let cli = Cli::parse();
- let lab: Vec<Lab> = get_image_colors::get_image_colors(&cli.path);
+ let lab: Vec<Lab> = match get_image_colors::get_image_colors(&cli.path) {
+ Ok(lab) => lab,
+ Err(e) => {
+ eprintln!("{}", e);
+ std::process::exit(1);
+ }
+ };
let dominant_colors = find_dominant_colors::find_dominant_colors(&lab, cli.max_colours);
@@ -241,6 +247,18 @@ mod tests {
}
#[test]
+ fn it_fails_if_you_pass_a_path_without_a_file_extension() {
+ let output = get_failure(&["./src/tests/noextension"]);
+
+ assert_eq!(output.exit_code, 1);
+ assert_eq!(output.stdout, "");
+ assert_eq!(
+ output.stderr,
+ "Path has no file extension, so could not determine image format\n"
+ );
+ }
+
+ #[test]
fn it_chooses_the_right_color_for_a_dark_background() {
let output = get_success(&[
"src/tests/stripes.png",