turnstiles/
utils.rs

1use anyhow::{bail, Result};
2use std::{ffi::OsStr, path::PathBuf};
3pub fn filename_to_details(path_str: &str) -> Result<(String, String)> {
4    // TODO: make this std::io::err as well for consistency?
5    let pathbuf = PathBuf::from(path_str);
6
7    let filename: String = match pathbuf.file_name() {
8        None => bail!("Could not get filename"),
9        Some(f_osstr) => safe_unwrap_osstr(f_osstr)?,
10    };
11
12    let parent = match pathbuf.parent() {
13        None => "/",
14        Some(s) => match s.to_str() {
15            None => bail!("Could not convert OsStr to &str"),
16            Some("") => ".",
17            Some(s) => s,
18        },
19    }
20    .to_string();
21    Ok((filename, parent))
22}
23
24pub fn safe_unwrap_osstr(s: &OsStr) -> Result<String, std::io::Error> {
25    // Had just used bail here before but really only can return std::io::Error from all of this stuff...
26    let string = match s.to_str() {
27        None => {
28            return Err(std::io::Error::new(
29                std::io::ErrorKind::InvalidData,
30                "Could not convert OsStr to &str",
31            ))
32        }
33        Some(f_str) => f_str.to_string(),
34    };
35    Ok(string)
36}