Skip to content

Commit

Permalink
fix(filetype): infer after checking file ext (#23)
Browse files Browse the repository at this point in the history
We error out if trying to sort a directory with the image "a.jpg" which
is constructed with "echo a>a.jpg".

With this patch, "a.jpg" would be ignored and not cause an error,
allowing image-sorter to continue with proper image files.
  • Loading branch information
chelmertz authored Sep 3, 2024
1 parent c0c9795 commit 1532584
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
7 changes: 7 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ subprocess = "0.2.6"
ratatui = { version = "0.23", default-features = false, features = ["termion"] }
termion = "2.0.1"
crossbeam-channel = "0.5.0"
infer = "0.3"
expanduser = "1.2.2"

[[bin]]
Expand Down
23 changes: 21 additions & 2 deletions src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -258,9 +258,28 @@ impl App {
}

fn is_image(file: &Path) -> bool {
// first, a quick check for the file extension
let image_exts = ["jpeg", "jpg", "png"];
file.extension().map_or(false, |f| {
let looks_like_image = file.extension().map_or(false, |f| {
image_exts.iter().any(|ext| f.to_str() == Some(ext))
})
});
if !looks_like_image {
return false;
}

// second, check the file's mime type by reading the first few bytes
let kind = infer::get_from_path(file);
if kind.is_err() {
// could not read file
return false;
}
let kind = kind.unwrap();
if kind.is_none() {
// unknown file type
return false;
}

let kind = kind.unwrap();
matches!(kind.mime_type(), "image/jpeg" | "image/png")
}
}

0 comments on commit 1532584

Please sign in to comment.