use crate::containerization::strings;
use crate::platform;
use crate::platform::ffi;
use std::fmt;
use std::io;
const OPTION_PREFIX: &str = "x-containerization.subpath=";
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Error {
Invalid { subpath: String, reason: String },
Missing { options: Vec<String> },
NotBind,
Resolve { subpath: String, errno: i32 },
}
impl fmt::Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Invalid { subpath, reason } => write!(formatter, "invalid subpath '{subpath}': {reason}"),
Self::Missing { options } => write!(formatter, "no subpath option in {options:?}"),
Self::NotBind => formatter.write_str("a subpath needs a non-recursive bind mount"),
Self::Resolve { subpath, errno } => write!(
formatter,
"subpath '{subpath}': cannot be opened: {}",
io::Error::from_raw_os_error(*errno)
),
}
}
}
impl std::error::Error for Error {}
pub fn to_mount_option(subpath: &str) -> String {
format!("{OPTION_PREFIX}{subpath}")
}
pub fn is_subpath_mount(options: &[&str]) -> Result<bool, crate::error::Error> {
platform::outcome(
ffi::cz_volume_subpath_is_subpath_mount(strings(options)),
"check the mount options for a subpath",
)
.map(|outcome| outcome.boolean())
}
pub fn extract(options: &[&str]) -> Result<(String, Vec<String>), crate::error::Error> {
platform::outcome(
ffi::cz_volume_subpath_extract(strings(options)),
"take the subpath from the mount options",
)
.map(|outcome| outcome.volume_subpath_extracted())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn says_what_swift_says() {
assert_eq!(
Error::Invalid {
subpath: "/abs".into(),
reason: "it is absolute".into()
}
.to_string(),
"invalid subpath '/abs': it is absolute"
);
assert_eq!(
Error::Missing {
options: vec!["bind".into(), "ro".into()]
}
.to_string(),
r#"no subpath option in ["bind", "ro"]"#
);
assert_eq!(Error::NotBind.to_string(), "a subpath needs a non-recursive bind mount");
}
#[test]
fn carries_a_subpath_as_a_mount_option() {
assert_eq!(to_mount_option("data/cache"), "x-containerization.subpath=data/cache");
}
}