Onset: version control where nobody waits and nothing gets lost. The on command, its core and onset-server.
| 1 | //! What a lazy workspace's mount shows, whatever serves it (FUSE on Linux, |
| 2 | //! NFS on macOS): the change's tree, each file fetched from the host the |
| 3 | //! first time it's opened, with the backing's files over it. Writes go to |
| 4 | //! the backing (copy-up); a file deleted from the tree is remembered as gone. |
| 5 |
| 6 | use std::collections::{BTreeMap, BTreeSet, HashMap}; |
| 7 | use std::ffi::{CString, OsStr}; |
| 8 | use std::fs; |
| 9 | use std::os::unix::ffi::OsStrExt; |
| 10 | use std::os::unix::fs::{MetadataExt, OpenOptionsExt, PermissionsExt}; |
| 11 | use std::path::{Path, PathBuf}; |
| 12 | use std::sync::Mutex; |
| 13 | use std::time::{Duration, SystemTime, UNIX_EPOCH}; |
| 14 |
| 15 | use anyhow::{Result, anyhow}; |
| 16 | use onset_core::Id; |
| 17 | use onset_core::tree::{Entry, EntryKind}; |
| 18 | use serde_json::json; |
| 19 |
| 20 | use super::{MTIME_NS, backing, ino}; |
| 21 | use crate::app::App; |
| 22 | use crate::objects::Store; |
| 23 | use crate::remote::Remote; |
| 24 | use crate::ws::{self, Index}; |
| 25 |
| 26 | /// An error for the system's mount call: an errno. |
| 27 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 28 | pub struct Errno(pub i32); |
| 29 |
| 30 | impl Errno { |
| 31 | pub const ENOENT: Errno = Errno(libc::ENOENT); |
| 32 | pub const EIO: Errno = Errno(libc::EIO); |
| 33 | pub const EINVAL: Errno = Errno(libc::EINVAL); |
| 34 | pub const EEXIST: Errno = Errno(libc::EEXIST); |
| 35 | pub const EISDIR: Errno = Errno(libc::EISDIR); |
| 36 | pub const ENOTDIR: Errno = Errno(libc::ENOTDIR); |
| 37 | pub const ENOTEMPTY: Errno = Errno(libc::ENOTEMPTY); |
| 38 | } |
| 39 |
| 40 | impl From<std::io::Error> for Errno { |
| 41 | fn from(e: std::io::Error) -> Errno { |
| 42 | Errno(e.raw_os_error().filter(|n| *n > 0).unwrap_or(libc::EIO)) |
| 43 | } |
| 44 | } |
| 45 |
| 46 | pub enum Node { |
| 47 | /// In the backing: written here, or fetched. |
| 48 | Real(fs::Metadata), |
| 49 | /// In the tree, not fetched yet: (entry, size). |
| 50 | File(Entry, u64), |
| 51 | Dir, |
| 52 | } |
| 53 |
| 54 | impl Node { |
| 55 | pub fn is_dir(&self) -> bool { |
| 56 | match self { |
| 57 | Node::Real(m) => m.is_dir(), |
| 58 | Node::File(..) => false, |
| 59 | Node::Dir => true, |
| 60 | } |
| 61 | } |
| 62 | } |
| 63 |
| 64 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 65 | pub enum Kind { |
| 66 | Dir, |
| 67 | File, |
| 68 | Link, |
| 69 | } |
| 70 |
| 71 | /// What a node shows, before FUSE or NFS puts it in its own words. Times are |
| 72 | /// in ns; a node's creation time is its modification time. |
| 73 | pub struct Attr { |
| 74 | pub ino: u64, |
| 75 | pub kind: Kind, |
| 76 | pub size: u64, |
| 77 | pub blocks: u64, |
| 78 | pub atime_ns: i64, |
| 79 | pub mtime_ns: i64, |
| 80 | pub ctime_ns: i64, |
| 81 | pub perm: u16, |
| 82 | pub nlink: u32, |
| 83 | pub uid: u32, |
| 84 | pub gid: u32, |
| 85 | } |
| 86 |
| 87 | /// A time to set: now, or a given one. |
| 88 | #[derive(Clone, Copy)] |
| 89 | pub enum SetTime { |
| 90 | Now, |
| 91 | At(SystemTime), |
| 92 | } |
| 93 |
| 94 | pub struct State { |
| 95 | inodes: HashMap<u64, String>, |
| 96 | paths: HashMap<String, u64>, |
| 97 | /// Paths in the tree deleted here (and everything under them). |
| 98 | gone: BTreeSet<String>, |
| 99 | /// Open files, for a mount that has opens (FUSE). |
| 100 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] |
| 101 | pub handles: HashMap<u64, fs::File>, |
| 102 | #[cfg_attr(not(target_os = "linux"), allow(dead_code))] |
| 103 | pub next_fh: u64, |
| 104 | } |
| 105 |
| 106 | pub struct Overlay { |
| 107 | pub backing: PathBuf, |
| 108 | files: BTreeMap<String, (Entry, u64)>, |
| 109 | dirs: HashMap<String, BTreeSet<String>>, |
| 110 | tree: Id, |
| 111 | store: Store, |
| 112 | remote: Remote, |
| 113 | pub state: Mutex<State>, |
| 114 | } |
| 115 |
| 116 | pub fn join(dir: &str, name: &str) -> String { |
| 117 | if dir.is_empty() { name.to_string() } else { format!("{dir}/{name}") } |
| 118 | } |
| 119 |
| 120 | pub fn parent(path: &str) -> &str { |
| 121 | path.rsplit_once('/').map(|(p, _)| p).unwrap_or("") |
| 122 | } |
| 123 |
| 124 | pub fn time(ns: i64) -> SystemTime { |
| 125 | UNIX_EPOCH + Duration::from_nanos(ns.max(0) as u64) |
| 126 | } |
| 127 |
| 128 | pub fn cpath(path: &Path) -> Result<CString, Errno> { |
| 129 | CString::new(path.as_os_str().as_bytes()).map_err(|_| Errno::EINVAL) |
| 130 | } |
| 131 |
| 132 | fn timespec(t: Option<SetTime>) -> libc::timespec { |
| 133 | match t { |
| 134 | None => libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_OMIT }, |
| 135 | Some(SetTime::Now) => libc::timespec { tv_sec: 0, tv_nsec: libc::UTIME_NOW }, |
| 136 | Some(SetTime::At(t)) => { |
| 137 | let d = t.duration_since(UNIX_EPOCH).unwrap_or_default(); |
| 138 | libc::timespec { tv_sec: d.as_secs() as libc::time_t, tv_nsec: d.subsec_nanos() as libc::c_long } |
| 139 | } |
| 140 | } |
| 141 | } |
| 142 |
| 143 | pub fn set_times(path: &Path, atime: Option<SetTime>, mtime: Option<SetTime>) -> Result<(), Errno> { |
| 144 | let c = cpath(path)?; |
| 145 | let times = [timespec(atime), timespec(mtime)]; |
| 146 | // SAFETY: a NUL-terminated path and two timespecs, as utimensat takes. |
| 147 | if unsafe { libc::utimensat(libc::AT_FDCWD, c.as_ptr(), times.as_ptr(), libc::AT_SYMLINK_NOFOLLOW) } != 0 { |
| 148 | return Err(Errno::from(std::io::Error::last_os_error())); |
| 149 | } |
| 150 | Ok(()) |
| 151 | } |
| 152 |
| 153 | fn io(e: std::io::Error) -> Errno { |
| 154 | Errno::from(e) |
| 155 | } |
| 156 |
| 157 | impl Overlay { |
| 158 | /// The overlay of the lazy workspace whose folder is `root`: its tree |
| 159 | /// (from the index it started with) and its backing. |
| 160 | pub fn load(app: &App, root: &Path) -> Result<Overlay> { |
| 161 | let w = super::workspace_at(app, root)?.filter(|w| w.path == root).ok_or_else(|| anyhow!("{} isn't a lazy workspace on this machine", root.display()))?; |
| 162 | let project = app.db.project(&w.project)?.ok_or_else(|| anyhow!("the workspace's project isn't known here"))?; |
| 163 | let dir = backing(&w.id); |
| 164 | let base = Index::load_from(&dir, "lazy-base").ok_or_else(|| anyhow!("{} has no lazy index", dir.display()))?; |
| 165 | let tree = base.tree.ok_or_else(|| anyhow!("{} has no tree", dir.display()))?; |
| 166 | let mut files = BTreeMap::new(); |
| 167 | let mut dirs: HashMap<String, BTreeSet<String>> = HashMap::new(); |
| 168 | dirs.insert(String::new(), BTreeSet::new()); |
| 169 | for (path, e) in base.entries { |
| 170 | let mut child = path.as_str(); |
| 171 | while let Some((parent, name)) = child.rsplit_once('/') { |
| 172 | dirs.entry(parent.to_string()).or_default().insert(name.to_string()); |
| 173 | child = parent; |
| 174 | } |
| 175 | dirs.entry(String::new()).or_default().insert(child.to_string()); |
| 176 | if e.entry.kind == EntryKind::Gitlink { |
| 177 | dirs.entry(path.clone()).or_default(); |
| 178 | } |
| 179 | files.insert(path, (e.entry, e.stat.size)); |
| 180 | } |
| 181 | let gone: BTreeSet<String> = fs::read_to_string(dir.join(ws::DIR).join("lazy-gone")).unwrap_or_default().lines().filter(|l| !l.is_empty()).map(str::to_string).collect(); |
| 182 | let mut state = State { inodes: HashMap::new(), paths: HashMap::new(), gone, handles: HashMap::new(), next_fh: 1 }; |
| 183 | state.inodes.insert(1, String::new()); |
| 184 | state.paths.insert(String::new(), 1); |
| 185 | Ok(Overlay { |
| 186 | backing: dir, |
| 187 | files, |
| 188 | dirs, |
| 189 | tree, |
| 190 | store: Store::open(&crate::paths::objects())?, |
| 191 | remote: Remote::for_project(&project), |
| 192 | state: Mutex::new(state), |
| 193 | }) |
| 194 | } |
| 195 |
| 196 | pub fn real(&self, path: &str) -> PathBuf { |
| 197 | if path.is_empty() { self.backing.clone() } else { self.backing.join(path) } |
| 198 | } |
| 199 |
| 200 | pub fn in_tree(&self, path: &str) -> bool { |
| 201 | self.files.contains_key(path) || self.dirs.contains_key(path) |
| 202 | } |
| 203 |
| 204 | /// Whether `path`, or a folder holding it, was deleted from the tree here. |
| 205 | fn hidden(&self, st: &State, path: &str) -> bool { |
| 206 | let mut p = path; |
| 207 | loop { |
| 208 | if st.gone.contains(p) { |
| 209 | return true; |
| 210 | } |
| 211 | match p.rsplit_once('/') { |
| 212 | Some((up, _)) => p = up, |
| 213 | None => return false, |
| 214 | } |
| 215 | } |
| 216 | } |
| 217 |
| 218 | pub fn find(&self, st: &State, path: &str) -> Option<Node> { |
| 219 | if let Ok(m) = fs::symlink_metadata(self.real(path)) { |
| 220 | return Some(Node::Real(m)); |
| 221 | } |
| 222 | if self.hidden(st, path) { |
| 223 | return None; |
| 224 | } |
| 225 | // A real file where a folder holding it was. |
| 226 | let mut p = path; |
| 227 | while let Some((up, _)) = p.rsplit_once('/') { |
| 228 | p = up; |
| 229 | if fs::symlink_metadata(self.real(p)).is_ok_and(|m| !m.is_dir()) { |
| 230 | return None; |
| 231 | } |
| 232 | } |
| 233 | match self.files.get(path) { |
| 234 | Some((e, _)) if e.kind == EntryKind::Gitlink => Some(Node::Dir), |
| 235 | Some((e, size)) => Some(Node::File(*e, *size)), |
| 236 | None if self.dirs.contains_key(path) => Some(Node::Dir), |
| 237 | None => None, |
| 238 | } |
| 239 | } |
| 240 |
| 241 | pub fn ino_of(&self, st: &mut State, path: &str) -> u64 { |
| 242 | if let Some(i) = st.paths.get(path) { |
| 243 | return *i; |
| 244 | } |
| 245 | let mut i = ino(path); |
| 246 | while st.inodes.get(&i).is_some_and(|p| p != path) { |
| 247 | i = i.wrapping_add(1).max(2); |
| 248 | } |
| 249 | st.inodes.insert(i, path.to_string()); |
| 250 | st.paths.insert(path.to_string(), i); |
| 251 | i |
| 252 | } |
| 253 |
| 254 | pub fn attr(&self, st: &mut State, path: &str, node: &Node) -> Attr { |
| 255 | let ino = self.ino_of(st, path); |
| 256 | let (uid, gid) = (unsafe { libc::getuid() }, unsafe { libc::getgid() }); |
| 257 | let base = Attr { |
| 258 | ino, |
| 259 | kind: Kind::Dir, |
| 260 | size: 0, |
| 261 | blocks: 0, |
| 262 | atime_ns: MTIME_NS, |
| 263 | mtime_ns: MTIME_NS, |
| 264 | ctime_ns: MTIME_NS, |
| 265 | perm: 0o755, |
| 266 | nlink: 2, |
| 267 | uid, |
| 268 | gid, |
| 269 | }; |
| 270 | match node { |
| 271 | Node::Real(m) => { |
| 272 | let kind = if m.is_dir() { |
| 273 | Kind::Dir |
| 274 | } else if m.file_type().is_symlink() { |
| 275 | Kind::Link |
| 276 | } else { |
| 277 | Kind::File |
| 278 | }; |
| 279 | Attr { |
| 280 | size: m.len(), |
| 281 | blocks: m.blocks(), |
| 282 | atime_ns: m.atime() * 1_000_000_000 + m.atime_nsec(), |
| 283 | mtime_ns: m.mtime() * 1_000_000_000 + m.mtime_nsec(), |
| 284 | ctime_ns: m.ctime() * 1_000_000_000 + m.ctime_nsec(), |
| 285 | kind, |
| 286 | perm: (m.mode() & 0o7777) as u16, |
| 287 | nlink: m.nlink() as u32, |
| 288 | uid: m.uid(), |
| 289 | gid: m.gid(), |
| 290 | ..base |
| 291 | } |
| 292 | } |
| 293 | Node::File(e, size) => Attr { |
| 294 | size: *size, |
| 295 | blocks: size.div_ceil(512), |
| 296 | kind: if e.kind == EntryKind::Link { Kind::Link } else { Kind::File }, |
| 297 | perm: match e.kind { |
| 298 | EntryKind::Exec => 0o755, |
| 299 | EntryKind::Link => 0o777, |
| 300 | _ => 0o644, |
| 301 | }, |
| 302 | nlink: 1, |
| 303 | ..base |
| 304 | }, |
| 305 | Node::Dir => base, |
| 306 | } |
| 307 | } |
| 308 |
| 309 | /// The names in folder `path`: the backing's and the tree's, some of |
| 310 | /// which may be gone (`find` says). |
| 311 | pub fn names(&self, path: &str) -> BTreeSet<String> { |
| 312 | let mut names = BTreeSet::new(); |
| 313 | if let Ok(read) = fs::read_dir(self.real(path)) { |
| 314 | for e in read.flatten() { |
| 315 | if let Some(n) = e.file_name().to_str() { |
| 316 | names.insert(n.to_string()); |
| 317 | } |
| 318 | } |
| 319 | } |
| 320 | if let Some(kids) = self.dirs.get(path) { |
| 321 | names.extend(kids.iter().cloned()); |
| 322 | } |
| 323 | names |
| 324 | } |
| 325 |
| 326 | /// What's in folder `path`: the backing's files over the tree's. |
| 327 | pub fn listing(&self, st: &State, path: &str) -> Vec<(String, Node)> { |
| 328 | self.names(path).into_iter().filter_map(|n| self.find(st, &join(path, &n)).map(|node| (n, node))).collect() |
| 329 | } |
| 330 |
| 331 | /// A file's content from the store, fetched from the host first if it isn't here. |
| 332 | pub fn content(&self, path: &str, entry: &Entry) -> Result<Vec<u8>> { |
| 333 | if let Ok(bytes) = self.store.read_file(&entry.id) { |
| 334 | return Ok(bytes); |
| 335 | } |
| 336 | let bundle = self.remote.post_for_bytes(&format!("/trees/{}/files", self.tree), &json!({ "paths": [path] }))?; |
| 337 | self.store.ingest(&bundle)?; |
| 338 | Ok(self.store.read_file(&entry.id)?) |
| 339 | } |
| 340 |
| 341 | pub fn real_dir(&self, path: &str) -> Result<(), Errno> { |
| 342 | fs::create_dir_all(self.real(path)).map_err(io) |
| 343 | } |
| 344 |
| 345 | /// A file in the tree, fetched into the backing: from here on it's an ordinary file. |
| 346 | pub fn copy_up(&self, path: &str, entry: &Entry) -> Result<(), Errno> { |
| 347 | let bytes = self.content(path, entry).map_err(|e| { |
| 348 | eprintln!("on mount: couldn't fetch {path}: {e:#}"); |
| 349 | Errno::EIO |
| 350 | })?; |
| 351 | self.real_dir(parent(path))?; |
| 352 | let real = self.real(path); |
| 353 | if entry.kind == EntryKind::Link { |
| 354 | std::os::unix::fs::symlink(OsStr::from_bytes(&bytes), &real).map_err(io)?; |
| 355 | } else { |
| 356 | fs::write(&real, &bytes).map_err(io)?; |
| 357 | fs::set_permissions(&real, fs::Permissions::from_mode(if entry.kind == EntryKind::Exec { 0o755 } else { 0o644 })).map_err(io)?; |
| 358 | } |
| 359 | // The time it showed before, so the index still knows it. |
| 360 | let shown = Some(SetTime::At(time(MTIME_NS))); |
| 361 | set_times(&real, shown, shown) |
| 362 | } |
| 363 |
| 364 | /// `path` and everything under it into the backing (before it moves). |
| 365 | fn copy_up_all(&self, st: &State, path: &str) -> Result<(), Errno> { |
| 366 | match self.find(st, path) { |
| 367 | Some(Node::File(e, _)) => self.copy_up(path, &e), |
| 368 | Some(node) if node.is_dir() => { |
| 369 | self.real_dir(path)?; |
| 370 | for (name, _) in self.listing(st, path) { |
| 371 | self.copy_up_all(st, &join(path, &name))?; |
| 372 | } |
| 373 | Ok(()) |
| 374 | } |
| 375 | _ => Ok(()), |
| 376 | } |
| 377 | } |
| 378 |
| 379 | fn save_gone(&self, st: &State) { |
| 380 | let text: String = st.gone.iter().map(|p| format!("{p}\n")).collect(); |
| 381 | let _ = fs::write(self.backing.join(ws::DIR).join("lazy-gone"), text); |
| 382 | } |
| 383 |
| 384 | pub fn path_of(&self, st: &State, ino: u64) -> Result<String, Errno> { |
| 385 | st.inodes.get(&ino).cloned().ok_or(Errno::ENOENT) |
| 386 | } |
| 387 |
| 388 | pub fn child(&self, st: &State, parent: u64, name: &OsStr) -> Result<String, Errno> { |
| 389 | let dir = self.path_of(st, parent)?; |
| 390 | let name = name.to_str().filter(|n| !n.is_empty() && !n.contains('/')).ok_or(Errno::EINVAL)?; |
| 391 | Ok(join(&dir, name)) |
| 392 | } |
| 393 |
| 394 | /// A file's mode, size and times, set; it's fetched first if it's in the tree. |
| 395 | pub fn setattr(&self, st: &State, path: &str, mode: Option<u32>, size: Option<u64>, open: Option<&fs::File>, atime: Option<SetTime>, mtime: Option<SetTime>) -> Result<(), Errno> { |
| 396 | match self.find(st, path).ok_or(Errno::ENOENT)? { |
| 397 | Node::File(e, _) => self.copy_up(path, &e)?, |
| 398 | Node::Dir => self.real_dir(path)?, |
| 399 | Node::Real(_) => {} |
| 400 | } |
| 401 | let real = self.real(path); |
| 402 | if let Some(m) = mode { |
| 403 | fs::set_permissions(&real, fs::Permissions::from_mode(m & 0o7777)).map_err(io)?; |
| 404 | } |
| 405 | if let Some(s) = size { |
| 406 | match open { |
| 407 | Some(f) => f.set_len(s).map_err(io)?, |
| 408 | None => fs::OpenOptions::new().write(true).open(&real).and_then(|f| f.set_len(s)).map_err(io)?, |
| 409 | } |
| 410 | } |
| 411 | if atime.is_some() || mtime.is_some() { |
| 412 | set_times(&real, atime, mtime)?; |
| 413 | } |
| 414 | Ok(()) |
| 415 | } |
| 416 |
| 417 | /// The target of link `path`. |
| 418 | pub fn readlink(&self, st: &State, path: &str) -> Result<Vec<u8>, Errno> { |
| 419 | match self.find(st, path) { |
| 420 | Some(Node::Real(_)) => fs::read_link(self.real(path)).map(|t| t.as_os_str().as_bytes().to_vec()).map_err(io), |
| 421 | Some(Node::File(e, _)) if e.kind == EntryKind::Link => self.content(path, &e).map_err(|_| Errno::EIO), |
| 422 | Some(_) => Err(Errno::EINVAL), |
| 423 | None => Err(Errno::ENOENT), |
| 424 | } |
| 425 | } |
| 426 |
| 427 | pub fn mkdir(&self, st: &State, path: &str, mode: u32) -> Result<(), Errno> { |
| 428 | if self.find(st, path).is_some() { |
| 429 | return Err(Errno::EEXIST); |
| 430 | } |
| 431 | self.real_dir(parent(path))?; |
| 432 | fs::create_dir(self.real(path)).map_err(io)?; |
| 433 | fs::set_permissions(self.real(path), fs::Permissions::from_mode(mode & 0o7777)).map_err(io) |
| 434 | } |
| 435 |
| 436 | pub fn unlink(&self, st: &mut State, path: String) -> Result<(), Errno> { |
| 437 | match self.find(st, &path).ok_or(Errno::ENOENT)? { |
| 438 | node if node.is_dir() => return Err(Errno::EISDIR), |
| 439 | Node::Real(_) => fs::remove_file(self.real(&path)).map_err(io)?, |
| 440 | _ => {} |
| 441 | } |
| 442 | if self.in_tree(&path) { |
| 443 | st.gone.insert(path); |
| 444 | self.save_gone(st); |
| 445 | } |
| 446 | Ok(()) |
| 447 | } |
| 448 |
| 449 | pub fn rmdir(&self, st: &mut State, path: String) -> Result<(), Errno> { |
| 450 | let node = self.find(st, &path).ok_or(Errno::ENOENT)?; |
| 451 | if !node.is_dir() { |
| 452 | return Err(Errno::ENOTDIR); |
| 453 | } |
| 454 | if !self.listing(st, &path).is_empty() { |
| 455 | return Err(Errno::ENOTEMPTY); |
| 456 | } |
| 457 | if let Node::Real(_) = node { |
| 458 | fs::remove_dir(self.real(&path)).map_err(io)?; |
| 459 | } |
| 460 | if self.in_tree(&path) { |
| 461 | st.gone.insert(path); |
| 462 | self.save_gone(st); |
| 463 | } |
| 464 | Ok(()) |
| 465 | } |
| 466 |
| 467 | pub fn symlink(&self, st: &State, path: &str, target: &Path) -> Result<(), Errno> { |
| 468 | if self.find(st, path).is_some() { |
| 469 | return Err(Errno::EEXIST); |
| 470 | } |
| 471 | self.real_dir(parent(path))?; |
| 472 | std::os::unix::fs::symlink(target, self.real(path)).map_err(io) |
| 473 | } |
| 474 |
| 475 | /// Moves `from` to `to`, fetching what it holds first. `noreplace` |
| 476 | /// refuses to replace what's at `to`. |
| 477 | pub fn rename(&self, st: &mut State, from: String, to: String, noreplace: bool) -> Result<(), Errno> { |
| 478 | if from == to { |
| 479 | return Ok(()); |
| 480 | } |
| 481 | if to.starts_with(&format!("{from}/")) { |
| 482 | return Err(Errno::EINVAL); |
| 483 | } |
| 484 | let src = self.find(st, &from).ok_or(Errno::ENOENT)?; |
| 485 | if let Some(dst) = self.find(st, &to) { |
| 486 | if noreplace { |
| 487 | return Err(Errno::EEXIST); |
| 488 | } |
| 489 | match (src.is_dir(), dst.is_dir()) { |
| 490 | (true, false) => return Err(Errno::ENOTDIR), |
| 491 | (false, true) => return Err(Errno::EISDIR), |
| 492 | (true, true) if !self.listing(st, &to).is_empty() => return Err(Errno::ENOTEMPTY), |
| 493 | _ => {} |
| 494 | } |
| 495 | if dst.is_dir() && fs::symlink_metadata(self.real(&to)).is_ok() { |
| 496 | fs::remove_dir(self.real(&to)).map_err(io)?; |
| 497 | } |
| 498 | } |
| 499 | self.copy_up_all(st, &from)?; |
| 500 | self.real_dir(parent(&to))?; |
| 501 | fs::rename(self.real(&from), self.real(&to)).map_err(io)?; |
| 502 | // What the tree has at either name stays out of sight. |
| 503 | for p in [&from, &to] { |
| 504 | if self.in_tree(p) { |
| 505 | st.gone.insert(p.clone()); |
| 506 | } |
| 507 | } |
| 508 | self.save_gone(st); |
| 509 | // Inodes the system holds follow the move. |
| 510 | let prefix = format!("{from}/"); |
| 511 | let moved: Vec<(String, u64)> = st.paths.iter().filter(|(p, _)| **p == from || p.starts_with(&prefix)).map(|(p, i)| (p.clone(), *i)).collect(); |
| 512 | let to_prefix = format!("{to}/"); |
| 513 | st.paths.retain(|p, _| *p != to && !p.starts_with(&to_prefix)); |
| 514 | for (old, i) in moved { |
| 515 | let new = format!("{to}{}", &old[from.len()..]); |
| 516 | st.paths.remove(&old); |
| 517 | st.paths.insert(new.clone(), i); |
| 518 | st.inodes.insert(i, new); |
| 519 | } |
| 520 | Ok(()) |
| 521 | } |
| 522 |
| 523 | /// A file of the workspace opened in the backing, fetched first if |
| 524 | /// it's in the tree. |
| 525 | pub fn open(&self, st: &State, path: &str, read: bool, write: bool, truncate: bool) -> Result<fs::File, Errno> { |
| 526 | match self.find(st, path).ok_or(Errno::ENOENT)? { |
| 527 | node if node.is_dir() => return Err(Errno::EISDIR), |
| 528 | Node::File(e, _) => self.copy_up(path, &e)?, |
| 529 | _ => {} |
| 530 | } |
| 531 | fs::OpenOptions::new().read(read).write(write).truncate(write && truncate).open(self.real(path)).map_err(io) |
| 532 | } |
| 533 |
| 534 | /// Creates (or opens) file `path`, read and write. `exclusive` refuses one that's there. |
| 535 | pub fn create(&self, st: &State, path: &str, mode: u32, exclusive: bool, truncate: bool) -> Result<fs::File, Errno> { |
| 536 | if exclusive && self.find(st, path).is_some() { |
| 537 | return Err(Errno::EEXIST); |
| 538 | } |
| 539 | if let Some(Node::File(e, _)) = self.find(st, path) { |
| 540 | self.copy_up(path, &e)?; |
| 541 | } |
| 542 | self.real_dir(parent(path))?; |
| 543 | fs::OpenOptions::new().read(true).write(true).create(true).truncate(truncate).mode(mode & 0o7777).open(self.real(path)).map_err(io) |
| 544 | } |
| 545 | } |
| 546 |