1use std::fmt;
9use std::io;
10
11use super::path::{NsPath, PathReason};
12
13#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
16#[non_exhaustive]
17pub enum InputReason {
18 UnexpectedData,
20 VersionOnCreate,
22 MountRoot,
24 MoveIntoSelf,
26 ReadOnlyUnderReadWrite,
29 DuplicateRoot,
32}
33
34impl InputReason {
35 fn describe(self) -> &'static str {
36 match self {
37 InputReason::UnexpectedData => "this operation takes no data",
38 InputReason::VersionOnCreate => "if_version is meaningless for an operation that creates",
39 InputReason::MountRoot => "the mount root has no parent and cannot be the target of this operation",
40 InputReason::MoveIntoSelf => "a directory cannot be moved into itself",
41 InputReason::DuplicateRoot => {
42 "two mounts are over the same host directory (access is per mount, so a write through one changes what the other reads)"
43 }
44 InputReason::ReadOnlyUnderReadWrite => {
45 "a ReadOnly mount cannot be nested under a ReadWrite mount (the parent could move it and write through the new name)"
46 }
47 }
48 }
49}
50
51#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53#[non_exhaustive]
54pub enum Feature {
55 Write,
57 AtomicReplace,
59 Watch,
61 WatchOnMountAncestor,
63}
64
65impl Feature {
66 fn describe(self) -> &'static str {
67 match self {
68 Feature::Write => "write",
69 Feature::AtomicReplace => "atomic replace",
70 Feature::Watch => "watch",
71 Feature::WatchOnMountAncestor => "watch on a directory that is only a mount ancestor",
72 }
73 }
74}
75
76#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
78#[non_exhaustive]
79pub enum NsErrorKind {
80 InvalidPath(PathReason),
82 InvalidInput(InputReason),
85 NotFound,
87 AlreadyExists,
89 NotADirectory,
91 IsADirectory,
93 NotEmpty,
95 PermissionDenied,
97 NotRegular,
99 HardLinked,
101 Escapes,
104 CaseCollision,
106 TooLarge,
108 VersionMismatch,
110 Unsupported(Feature),
112 CrossMount,
114 Io(io::ErrorKind),
116}
117
118#[derive(Clone, PartialEq, Eq)]
120pub struct NsError {
121 kind: NsErrorKind,
122 path: Option<NsPath>,
123}
124
125impl NsError {
126 pub fn new(kind: NsErrorKind) -> Self {
128 NsError { kind, path: None }
129 }
130
131 pub fn at(kind: NsErrorKind, path: &NsPath) -> Self {
133 NsError {
134 kind,
135 path: Some(path.clone()),
136 }
137 }
138
139 pub fn kind(&self) -> NsErrorKind {
141 self.kind
142 }
143
144 pub fn path(&self) -> Option<&NsPath> {
146 self.path.as_ref()
147 }
148
149 #[must_use]
151 pub fn or_at(mut self, path: &NsPath) -> Self {
152 if self.path.is_none() {
153 self.path = Some(path.clone());
154 }
155 self
156 }
157
158 #[must_use]
160 pub(crate) fn rebased(mut self, mount: &NsPath) -> Self {
161 self.path = self.path.and_then(|p| p.rebase(mount).ok());
162 self
163 }
164
165 pub(crate) fn from_io(err: &io::Error, path: &NsPath) -> Self {
167 NsError::at(kind_from_io(err), path)
168 }
169
170 pub(crate) fn from_io_nopath(err: &io::Error) -> Self {
172 NsError::new(kind_from_io(err))
173 }
174}
175
176pub(crate) fn kind_from_io(err: &io::Error) -> NsErrorKind {
177 use io::ErrorKind as K;
178 match err.kind() {
179 K::NotFound => NsErrorKind::NotFound,
180 K::AlreadyExists => NsErrorKind::AlreadyExists,
181 K::PermissionDenied => NsErrorKind::PermissionDenied,
182 K::NotADirectory => NsErrorKind::NotADirectory,
183 K::IsADirectory => NsErrorKind::IsADirectory,
184 K::DirectoryNotEmpty => NsErrorKind::NotEmpty,
185 other => NsErrorKind::Io(other),
186 }
187}
188
189impl fmt::Display for NsErrorKind {
190 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
191 match self {
192 NsErrorKind::InvalidPath(r) => write!(f, "invalid path: {}", r.describe()),
193 NsErrorKind::InvalidInput(why) => write!(f, "invalid argument: {}", why.describe()),
194 NsErrorKind::NotFound => f.write_str("not found"),
195 NsErrorKind::AlreadyExists => f.write_str("already exists"),
196 NsErrorKind::NotADirectory => f.write_str("not a directory"),
197 NsErrorKind::IsADirectory => f.write_str("is a directory"),
198 NsErrorKind::NotEmpty => f.write_str("directory not empty (remove its entries first)"),
199 NsErrorKind::PermissionDenied => f.write_str("permission denied (read-only mount or no grant)"),
200 NsErrorKind::NotRegular => {
201 f.write_str("not a regular file or directory (a device, FIFO or socket is never opened)")
202 }
203 NsErrorKind::HardLinked => {
204 f.write_str("file has more than one hard link (refused: a write could change another name)")
205 }
206 NsErrorKind::Escapes => f.write_str(
207 "a symbolic link or reparse point was met (never followed; mount its target as its own root instead)",
208 ),
209 NsErrorKind::CaseCollision => {
210 f.write_str("name differs only by case from an existing sibling (pick a distinct name)")
211 }
212 NsErrorKind::TooLarge => f.write_str("larger than the requested maximum (raise `max` or stream elsewhere)"),
213 NsErrorKind::VersionMismatch => {
214 f.write_str("version mismatch: the entry changed since it was read (re-read and retry)")
215 }
216 NsErrorKind::Unsupported(what) => write!(f, "unsupported by this backend: {}", what.describe()),
217 NsErrorKind::CrossMount => {
218 f.write_str("rename across mounts is not atomic and not done (copy, then remove)")
219 }
220 NsErrorKind::Io(k) => write!(f, "I/O error ({k})"),
221 }
222 }
223}
224
225impl fmt::Display for NsError {
226 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227 match &self.path {
228 Some(p) => write!(f, "{}: {}", p, self.kind),
229 None => write!(f, "{}", self.kind),
230 }
231 }
232}
233
234impl fmt::Debug for NsError {
235 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
236 f.debug_struct("NsError")
237 .field("kind", &self.kind)
238 .field("path", &self.path)
239 .finish()
240 }
241}
242
243impl std::error::Error for NsError {}
244
245pub type NsResult<T> = Result<T, NsError>;