use std::fmt;
use std::io;
use super::path::{NsPath, PathReason};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum InputReason {
UnexpectedData,
VersionOnCreate,
MountRoot,
MoveIntoSelf,
ReadOnlyUnderReadWrite,
DuplicateRoot,
}
impl InputReason {
fn describe(self) -> &'static str {
match self {
InputReason::UnexpectedData => "this operation takes no data",
InputReason::VersionOnCreate => "if_version is meaningless for an operation that creates",
InputReason::MountRoot => "the mount root has no parent and cannot be the target of this operation",
InputReason::MoveIntoSelf => "a directory cannot be moved into itself",
InputReason::DuplicateRoot => {
"two mounts are over the same host directory (access is per mount, so a write through one changes what the other reads)"
}
InputReason::ReadOnlyUnderReadWrite => {
"a ReadOnly mount cannot be nested under a ReadWrite mount (the parent could move it and write through the new name)"
}
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum Feature {
Write,
AtomicReplace,
Watch,
WatchOnMountAncestor,
}
impl Feature {
fn describe(self) -> &'static str {
match self {
Feature::Write => "write",
Feature::AtomicReplace => "atomic replace",
Feature::Watch => "watch",
Feature::WatchOnMountAncestor => "watch on a directory that is only a mount ancestor",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum NsErrorKind {
InvalidPath(PathReason),
InvalidInput(InputReason),
NotFound,
AlreadyExists,
NotADirectory,
IsADirectory,
NotEmpty,
PermissionDenied,
NotRegular,
HardLinked,
Escapes,
CaseCollision,
TooLarge,
VersionMismatch,
Unsupported(Feature),
CrossMount,
Io(io::ErrorKind),
}
#[derive(Clone, PartialEq, Eq)]
pub struct NsError {
kind: NsErrorKind,
path: Option<NsPath>,
}
impl NsError {
pub fn new(kind: NsErrorKind) -> Self {
NsError { kind, path: None }
}
pub fn at(kind: NsErrorKind, path: &NsPath) -> Self {
NsError {
kind,
path: Some(path.clone()),
}
}
pub fn kind(&self) -> NsErrorKind {
self.kind
}
pub fn path(&self) -> Option<&NsPath> {
self.path.as_ref()
}
#[must_use]
pub fn or_at(mut self, path: &NsPath) -> Self {
if self.path.is_none() {
self.path = Some(path.clone());
}
self
}
#[must_use]
pub(crate) fn rebased(mut self, mount: &NsPath) -> Self {
self.path = self.path.and_then(|p| p.rebase(mount).ok());
self
}
pub(crate) fn from_io(err: &io::Error, path: &NsPath) -> Self {
NsError::at(kind_from_io(err), path)
}
pub(crate) fn from_io_nopath(err: &io::Error) -> Self {
NsError::new(kind_from_io(err))
}
}
pub(crate) fn kind_from_io(err: &io::Error) -> NsErrorKind {
use io::ErrorKind as K;
match err.kind() {
K::NotFound => NsErrorKind::NotFound,
K::AlreadyExists => NsErrorKind::AlreadyExists,
K::PermissionDenied => NsErrorKind::PermissionDenied,
K::NotADirectory => NsErrorKind::NotADirectory,
K::IsADirectory => NsErrorKind::IsADirectory,
K::DirectoryNotEmpty => NsErrorKind::NotEmpty,
other => NsErrorKind::Io(other),
}
}
impl fmt::Display for NsErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
NsErrorKind::InvalidPath(r) => write!(f, "invalid path: {}", r.describe()),
NsErrorKind::InvalidInput(why) => write!(f, "invalid argument: {}", why.describe()),
NsErrorKind::NotFound => f.write_str("not found"),
NsErrorKind::AlreadyExists => f.write_str("already exists"),
NsErrorKind::NotADirectory => f.write_str("not a directory"),
NsErrorKind::IsADirectory => f.write_str("is a directory"),
NsErrorKind::NotEmpty => f.write_str("directory not empty (remove its entries first)"),
NsErrorKind::PermissionDenied => f.write_str("permission denied (read-only mount or no grant)"),
NsErrorKind::NotRegular => {
f.write_str("not a regular file or directory (a device, FIFO or socket is never opened)")
}
NsErrorKind::HardLinked => {
f.write_str("file has more than one hard link (refused: a write could change another name)")
}
NsErrorKind::Escapes => f.write_str(
"a symbolic link or reparse point was met (never followed; mount its target as its own root instead)",
),
NsErrorKind::CaseCollision => {
f.write_str("name differs only by case from an existing sibling (pick a distinct name)")
}
NsErrorKind::TooLarge => f.write_str("larger than the requested maximum (raise `max` or stream elsewhere)"),
NsErrorKind::VersionMismatch => {
f.write_str("version mismatch: the entry changed since it was read (re-read and retry)")
}
NsErrorKind::Unsupported(what) => write!(f, "unsupported by this backend: {}", what.describe()),
NsErrorKind::CrossMount => {
f.write_str("rename across mounts is not atomic and not done (copy, then remove)")
}
NsErrorKind::Io(k) => write!(f, "I/O error ({k})"),
}
}
}
impl fmt::Display for NsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.path {
Some(p) => write!(f, "{}: {}", p, self.kind),
None => write!(f, "{}", self.kind),
}
}
}
impl fmt::Debug for NsError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("NsError")
.field("kind", &self.kind)
.field("path", &self.path)
.finish()
}
}
impl std::error::Error for NsError {}
pub type NsResult<T> = Result<T, NsError>;