Skip to content
This repository was archived by the owner on Apr 9, 2023. It is now read-only.

Commit 9bc1f46

Browse files
authored
Merge pull request #7 from bupknar/master
Let from_filepath return None on nonexistent file instead of panicking
2 parents 8910bdd + a44d219 commit 9bc1f46

File tree

2 files changed

+20
-4
lines changed

2 files changed

+20
-4
lines changed

src/lib.rs

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -614,7 +614,8 @@ pub fn from_filepath_node(parentnode: NodeIndex, filepath: &Path) -> Option<MIME
614614
/// Gets the type of a file from a filepath.
615615
///
616616
/// Does not look at file name or extension, just the contents.
617-
/// Returns MIME as string.
617+
/// Returns MIME as string wrapped in Some if a type matches, or
618+
/// None if the file is not found or cannot be opened.
618619
///
619620
/// # Examples
620621
/// ```rust
@@ -625,16 +626,16 @@ pub fn from_filepath_node(parentnode: NodeIndex, filepath: &Path) -> Option<MIME
625626
///
626627
/// // Find the MIME type of the GIF
627628
/// let result = tree_magic::from_filepath(path);
628-
/// assert_eq!(result, "image/gif");
629+
/// assert_eq!(result, Some("image/gif"));
629630
/// ```
630-
pub fn from_filepath(filepath: &Path) -> MIME {
631+
pub fn from_filepath(filepath: &Path) -> Option<MIME> {
631632

632633
let node = match TYPE.graph.externals(Incoming).next() {
633634
Some(foundnode) => foundnode,
634635
None => panic!("No filetype definitions are loaded.")
635636
};
636637

637-
from_filepath_node(node, filepath).unwrap()
638+
from_filepath_node(node, filepath)
638639
}
639640

640641
/// Determines if a MIME is an alias of another MIME

tests/from_filepath.rs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
mod from_filepath {
2+
3+
extern crate tree_magic;
4+
5+
use std::path::Path;
6+
7+
#[test]
8+
fn nonexistent_file_returns_none() {
9+
assert_eq!(
10+
tree_magic::from_filepath(Path::new("this/file/does/not/exist")),
11+
None
12+
);
13+
}
14+
15+
}

0 commit comments

Comments
 (0)