forked from kamiyaa/joshuto
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmimetype.rs
57 lines (48 loc) · 1.38 KB
/
mimetype.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
use std::path::Path;
use std::{io, process::Command};
use crate::error::{JoshutoError, JoshutoErrorKind, JoshutoResult};
pub struct Mimetype {
_type: String,
_subtype: String,
}
impl Mimetype {
pub fn new(ttype: String, subtype: String) -> Self {
Self {
_type: ttype,
_subtype: subtype,
}
}
pub fn get_type(&self) -> &str {
&self._type
}
pub fn get_subtype(&self) -> &str {
&self._subtype
}
}
pub fn get_mimetype(p: &Path) -> JoshutoResult<Mimetype> {
let res = Command::new("file")
.arg("--mime-type")
.arg("-Lb")
.arg(p)
.output();
let output = res?;
if !output.status.success() {
let stderr_msg = String::from_utf8_lossy(&output.stderr).to_string();
let error = JoshutoError::new(
JoshutoErrorKind::Io(io::ErrorKind::InvalidInput),
stderr_msg,
);
return Err(error);
}
let stdout_msg = String::from_utf8_lossy(&output.stdout).to_string();
match stdout_msg.trim().split_once('/') {
Some((ttype, subtype)) => Ok(Mimetype::new(ttype.to_string(), subtype.to_string())),
None => {
let error = JoshutoError::new(
JoshutoErrorKind::Io(io::ErrorKind::InvalidInput),
"Unknown mimetype".to_string(),
);
Err(error)
}
}
}