diff --git a/apps/origin-src/benches/workspace.rs b/apps/origin-src/benches/workspace.rs index 54e8c03c..78da260d 100644 --- a/apps/origin-src/benches/workspace.rs +++ b/apps/origin-src/benches/workspace.rs @@ -48,7 +48,7 @@ fn from_store(bencher: Bencher<'_, '_>) { .with_inputs(|| tempfile::tempdir().unwrap()) .bench_local_refs(|workspace| { Worktree::new(workspace.path(), &store) - .checkout(&MAIN.changes) + .checkout(&MAIN.changes, None) .unwrap(); }); } diff --git a/apps/origin-src/src/workspace/land.rs b/apps/origin-src/src/workspace/land.rs index 71b2f039..95fa3b38 100644 --- a/apps/origin-src/src/workspace/land.rs +++ b/apps/origin-src/src/workspace/land.rs @@ -136,16 +136,16 @@ impl Workspace { /// snapshotted, or the change cannot be written or checked out. pub fn new_on(&mut self, target: &TargetName, description: &str) -> Result<(), WorkspaceError> { let working_copy = self.refresh()?; - self.start_on(target, description, working_copy.revision.snapshot) + self.start_on(&working_copy, target, description) } /// Starts a change described by `description` on the tip of `target`, - /// and checks it out over the files of `files`. + /// and checks it out over the working copy's files. fn start_on( &mut self, + working_copy: &WorkingCopy, target: &TargetName, description: &str, - files: TreeId, ) -> Result<(), WorkspaceError> { let tip = self .store @@ -162,9 +162,13 @@ impl Workspace { author: self.config.user(), }; let encoded = revision.encode(); - self.write(&[vec![description], vec![encoded.clone()]])?; - self.checkout(files, revision.snapshot)?; - self.point_at(encoded.id().into())?; + let id = encoded.id().into(); + self.switch_to( + working_copy, + id, + &revision, + &[vec![description], vec![encoded]], + )?; println!("Working copy: {}", self.headline(&revision)?); println!("On top of: {}", self.describe_base(revision.base)?); Ok(()) @@ -193,7 +197,6 @@ impl Workspace { landings: &[Landing], ) -> Result<(), WorkspaceError> { let revision = &working_copy.revision; - let files = revision.snapshot; // A change the target already had is as good as landed. let landed = |change: ChangeId| { landings.iter().any(|landing| match landing { @@ -204,7 +207,7 @@ impl Workspace { }) }; if landed(revision.change) { - return self.start_on(onto, "", files); + return self.start_on(working_copy, onto, ""); } for landing in landings { if let Landing::Pending(Pending { @@ -216,12 +219,9 @@ impl Workspace { && *rebased != working_copy.id { let rebased = *rebased; - self.checkout(files, self.store.get(rebased)?.snapshot)?; - self.point_at(rebased)?; - println!( - "Working copy: {}", - self.headline(&self.store.get(rebased)?)? - ); + let revision: Revision = self.store.get(rebased)?; + self.switch_to(working_copy, rebased, &revision, &[])?; + println!("Working copy: {}", self.headline(&revision)?); return Ok(()); } } @@ -265,9 +265,10 @@ impl Workspace { ..current.clone() }; let encoded = revision.encode(); - self.write(&[merge.trees, vec![encoded.clone()]])?; - self.checkout(current.snapshot, revision.snapshot)?; - self.point_at(encoded.id().into())?; + // Checking the revision out reads its trees. + self.write(&[merge.trees])?; + let id = encoded.id().into(); + self.switch_to(working_copy, id, &revision, &[vec![encoded]])?; println!("Working copy: {}", self.headline(&revision)?); println!("On top of: {}", self.describe_base(revision.base)?); Ok(()) diff --git a/apps/origin-src/src/workspace/mod.rs b/apps/origin-src/src/workspace/mod.rs index 11070df6..f3c419fd 100644 --- a/apps/origin-src/src/workspace/mod.rs +++ b/apps/origin-src/src/workspace/mod.rs @@ -17,6 +17,12 @@ //! `workspace` file naming it. Only the statements a new revision needs, //! such as its unresolved conflicts, come before it, so it's never found //! without them. +//! +//! A command that moves the working copy to a new revision, such as a +//! merge, checks its files out before it writes the revision. A file edited +//! in the meantime refuses the checkout, which then takes back the files it +//! changed, leaving those edited as they are: the working copy and its +//! change stay where they were, and the command can run again. mod annotate; mod land; @@ -70,6 +76,8 @@ struct WorkingCopy { /// The files as the snapshot found them: the draft, which is the /// revision's snapshot once recorded. files: TreeId, + /// The stat cache of the snapshot, which proves files unedited since. + cache: StatCache, /// Keeps garbage collection away from the objects the snapshot found /// stored, until the command that saves it is done. _held: LockedFile, @@ -213,13 +221,17 @@ impl Workspace { let held = self.store.hold_objects()?; let revision: Revision = self.store.get(self.revision)?; let path = self.meta("state"); - let (files, cache) = - Worktree::new(&self.root, &self.store).snapshot(&StatCache::load(&path))?; - if let Some(cache) = cache { - cache - .save(&path) - .map_err(|source| WorkspaceError::io(&path, source))?; - } + let loaded = StatCache::load(&path); + let (files, cache) = Worktree::new(&self.root, &self.store).snapshot(&loaded)?; + let cache = match cache { + Some(cache) => { + cache + .save(&path) + .map_err(|source| WorkspaceError::io(&path, source))?; + cache + } + None => loaded, + }; let index = Index::open(&self.store)?; let conflicts = self .conflicts(self.revision, &revision)? @@ -231,6 +243,7 @@ impl Workspace { conflicts, index, files, + cache, _held: held, }) } @@ -346,10 +359,52 @@ impl Workspace { Ok(()) } + /// Moves the working copy, whose files `working_copy` found, to + /// `revision`, `to`: checks it out over them, then writes `unwritten`, + /// the layers that write it if it's new, and makes it the working copy. + /// A checkout that fails, such as one refused by a file edited since + /// the snapshot, writes nothing, and takes back the files it changed as + /// best it can, so the working copy and its change stay where they + /// were. + fn switch_to( + &mut self, + working_copy: &WorkingCopy, + to: RevisionId, + revision: &Revision, + unwritten: &[Vec], + ) -> Result<(), WorkspaceError> { + let checkout = self.checkout( + working_copy.files, + revision.snapshot, + Some(&working_copy.cache), + ); + if let Err(error) = checkout { + // Best effort: the checkout's error says what went wrong. + let _ = self.restore(revision.snapshot, working_copy.files); + return Err(error); + } + self.write(unwritten)?; + self.point_at(to) + } + + /// Makes the files still as `from` has them match `to`, durably, and + /// leaves those edited since as they are. + fn restore(&self, from: TreeId, to: TreeId) -> Result<(), WorkspaceError> { + let changes = self.store.diff(from, to)?; + Ok(Worktree::new(&self.root, &self.store).restore(&changes)?) + } + /// Makes the files match `to`, given that they match `from`, durably. - fn checkout(&self, from: TreeId, to: TreeId) -> Result<(), WorkspaceError> { + /// With `unchanged`, the stat cache of the snapshot that found `from`, + /// it changes nothing if a file it changes was edited since. + fn checkout( + &self, + from: TreeId, + to: TreeId, + unchanged: Option<&StatCache>, + ) -> Result<(), WorkspaceError> { let changes = self.store.diff(from, to)?; - Ok(Worktree::new(&self.root, &self.store).checkout(&changes)?) + Ok(Worktree::new(&self.root, &self.store).checkout(&changes, unchanged)?) } /// `origin status`: prints the working copy's change, what it is on @@ -569,8 +624,7 @@ impl Workspace { let head = Self::single_head(index, change)?; let revision: Revision = self.store.get(head)?; if head != working_copy.id { - self.checkout(working_copy.revision.snapshot, revision.snapshot)?; - self.point_at(head)?; + self.switch_to(&working_copy, head, &revision, &[])?; } println!("Working copy: {}", self.headline(&revision)?); Ok(()) @@ -636,9 +690,7 @@ impl Workspace { let mut layers = self.revision_layers(vec![reason, empty], &encoded, &conflicts); // Published before the revision that replaces the change. layers[1].push(statement); - self.write(&layers)?; - self.checkout(working_copy.revision.snapshot, revision.snapshot)?; - self.point_at(encoded.id().into())?; + self.switch_to(&working_copy, encoded.id().into(), &revision, &layers)?; println!("Abandoned change {}", change.short()); println!("Working copy: {}", self.headline(&revision)?); println!("On top of: {}", self.describe_base(revision.base)?); @@ -709,10 +761,11 @@ impl Workspace { }; let encoded = revision.encode(); let id = encoded.id().into(); - self.write(&self.revision_layers(Vec::new(), &encoded, &conflicts))?; + let layers = self.revision_layers(Vec::new(), &encoded, &conflicts); if change == working_copy.revision.change { - self.checkout(working_copy.revision.snapshot, revision.snapshot)?; - self.point_at(id)?; + self.switch_to(&working_copy, id, &revision, &layers)?; + } else { + self.write(&layers)?; } println!( "Converged change {}: revision {} evolves from {}, merging their files", diff --git a/apps/origin-src/src/worktree.rs b/apps/origin-src/src/worktree.rs index d27cd7cf..8ab27599 100644 --- a/apps/origin-src/src/worktree.rs +++ b/apps/origin-src/src/worktree.rs @@ -6,8 +6,9 @@ //! blob id, so only files whose metadata changed are read and hashed, and //! every phase runs in parallel. //! -//! Checkouts write files from the store, in parallel, and the files they -//! write are durable once they return. +//! Checkouts write files from the store. They never overwrite an edit made +//! since the working copy was last snapshotted, and the files they write are +//! durable once they return. use std::collections::{BTreeSet, HashMap}; use std::ffi::OsStr; @@ -47,7 +48,15 @@ struct Stat { } impl Stat { - fn new(kind: EntryKind, metadata: &fs::Metadata) -> Self { + /// The metadata of a file, from `lstat`. + fn new(metadata: &fs::Metadata) -> Self { + let kind = if metadata.is_symlink() { + EntryKind::Symlink + } else if metadata.mode() & 0o111 != 0 { + EntryKind::Executable + } else { + EntryKind::File + }; Self { kind, size: metadata.size(), @@ -58,10 +67,51 @@ impl Stat { } } +/// A file a checkout changes, as it found it, unedited since the snapshot +/// the checkout starts from: its metadata, or `None` where there was no file. +/// A directory where a file goes counts as none: the checkout removes the +/// files it holds first, then the directory, unless it still holds +/// something (see [`Worktree::remove`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +struct Seen(Option); + +impl Seen { + /// What is at `path`. + fn at(path: &Path) -> Result { + match fs::symlink_metadata(path) { + Ok(metadata) if metadata.is_dir() => Ok(Self(None)), + Ok(metadata) => Ok(Self(Some(Stat::new(&metadata)))), + Err(error) + if matches!( + error.kind(), + io::ErrorKind::NotFound | io::ErrorKind::NotADirectory + ) => + { + Ok(Self(None)) + } + Err(source) => Err(SnapshotError::Io { + path: path.to_owned(), + source, + }), + } + } + + /// Fails with [`SnapshotError::Edited`] unless the file at `path` is + /// still as `seen`, if it was seen. + fn check(seen: Option, path: &Path) -> Result<(), SnapshotError> { + match seen { + Some(seen) if Self::at(path)? != seen => Err(SnapshotError::Edited(path.to_owned())), + _ => Ok(()), + } + } +} + /// A file a checkout writes. struct Write { path: PathBuf, entry: TreeEntry, + /// The file there, as found unedited, if the checkout checks. + seen: Option, } /// The stat cache: what each file looked like when it was last hashed, and @@ -94,11 +144,15 @@ impl StatCache { /// Files modified shortly before the previous scan started ("racy" /// files) are never trusted, since they may have changed again without /// their metadata changing. They are rehashed until they settle. - fn get(&self, path: &RepoPath, stat: &Stat) -> Option { - let (cached, id) = self.files.get(path.as_str())?; - let settled = - stat.mtime.max(stat.ctime) < self.scanned_at.saturating_sub(Self::RACY_MARGIN); - (cached == stat && settled).then_some(*id) + fn get(&self, path: &str, stat: &Stat) -> Option { + let (cached, id) = self.files.get(path)?; + (cached == stat && self.settled(stat)).then_some(*id) + } + + /// Whether a file with this metadata had last changed long enough + /// before the scan for its entry to be trusted. + fn settled(&self, stat: &Stat) -> bool { + stat.mtime.max(stat.ctime) < self.scanned_at.saturating_sub(Self::RACY_MARGIN) } /// Loads the cache, treating a missing or unreadable one as empty: the @@ -213,14 +267,13 @@ enum Child { /// What listing a directory says an entry is. enum Listed { Dir, - File { symlink: bool }, + File, } /// A file found by the walk, not yet examined. struct FoundFile { path: RepoPath, absolute: PathBuf, - symlink: bool, } /// What examining a file found. @@ -351,12 +404,8 @@ impl<'a, P: Platform> Worktree<'a, P> { }); Child::Dir(dirs.len() - 1) } - Listed::File { symlink } => { - files.push(FoundFile { - path, - absolute, - symlink, - }); + Listed::File => { + files.push(FoundFile { path, absolute }); Child::File(files.len() - 1) } }; @@ -396,9 +445,7 @@ impl<'a, P: Platform> Worktree<'a, P> { let listed = if file_type.is_dir() { Listed::Dir } else if file_type.is_file() || file_type.is_symlink() { - Listed::File { - symlink: file_type.is_symlink(), - } + Listed::File } else { // Sockets, FIFOs and devices have no content to track. continue; @@ -414,23 +461,15 @@ impl<'a, P: Platform> Worktree<'a, P> { path: file.absolute.clone(), source, }; - let metadata = fs::symlink_metadata(&file.absolute).map_err(io_error)?; - let kind = if file.symlink { - EntryKind::Symlink - } else if metadata.mode() & 0o111 != 0 { - EntryKind::Executable - } else { - EntryKind::File - }; - let stat = Stat::new(kind, &metadata); - if let Some(id) = cache.get(&file.path, &stat) { + let stat = Stat::new(&fs::symlink_metadata(&file.absolute).map_err(io_error)?); + if let Some(id) = cache.get(file.path.as_str(), &stat) { return Ok(Examined { stat, id, blob: None, }); } - let blob = if file.symlink { + let blob = if stat.kind == EntryKind::Symlink { let target = fs::read_link(&file.absolute).map_err(io_error)?; EncodedObject::blob(target.as_os_str().as_bytes()) } else { @@ -478,18 +517,74 @@ impl<'a, P: Platform> Worktree<'a, P> { /// returns, the files and directories it changed are durable, at the /// cost of one batch sync. /// + /// With `unchanged`, the stat cache of the snapshot the changes start + /// from, it first checks that no file it changes was edited since, and + /// changes nothing if one was: a file created where it writes one, or a + /// file it removes or replaces whose metadata changed, unless its + /// content didn't. It checks each file again just before it replaces + /// it, and stops at one edited in between, or at a directory where it + /// writes a file that holds what it doesn't track. + /// /// # Errors /// - /// Fails if a file's content cannot be read from the store, or a file - /// cannot be removed, written or synced. - pub fn checkout(&self, changes: &[FileChange]) -> Result<(), SnapshotError> { + /// Fails with [`SnapshotError::Edited`] if a file changed since the + /// snapshot, if a file's content cannot be read from the store, or a + /// file cannot be removed, written or synced. + pub fn checkout( + &self, + changes: &[FileChange], + unchanged: Option<&StatCache>, + ) -> Result<(), SnapshotError> { if changes.is_empty() { return Ok(()); } + let seen = unchanged + .map(|cache| Self::par_map(changes, |change| self.check_unchanged(change, cache))) + .transpose()?; + self.apply(changes, seen.as_deref()) + } + + /// Makes the files match a snapshot like [`Worktree::checkout`], but + /// only those still as `changes` start from, by content: it leaves the + /// others as they are. Files a move cut short left on either side, or + /// edited since, so end up on one side, and no edit is lost. + /// + /// # Errors + /// + /// Fails like [`Worktree::checkout`]. + pub fn restore(&self, changes: &[FileChange]) -> Result<(), SnapshotError> { + let cache = StatCache::default(); + let seen = Self::par_map(changes, |change| { + match self.check_unchanged(change, &cache) { + Ok(seen) => Ok(Some(seen)), + Err(SnapshotError::Edited(_)) => Ok(None), + Err(error) => Err(error), + } + })?; + let (changes, seen): (Vec<_>, Vec<_>) = changes + .iter() + .zip(seen) + .filter_map(|(change, seen)| Some((change.clone(), seen?))) + .unzip(); + if changes.is_empty() { + return Ok(()); + } + self.apply(&changes, Some(&seen)) + } + + /// Checks `changes` out, as [`Worktree::checkout`] explains. With + /// `seen`, the files as found unedited, one per change, it stops at a + /// file edited since. + fn apply(&self, changes: &[FileChange], seen: Option<&[Seen]>) -> Result<(), SnapshotError> { + let seen = |index: usize| seen.map(|seen| seen[index]); // Removing first frees the paths of files that become directories, // and of directories that become files. - for change in changes.iter().filter(|change| change.new.is_none()) { + for (index, change) in changes.iter().enumerate() { + if change.new.is_some() { + continue; + } let path = self.absolute(&change.path); + Seen::check(seen(index), &path)?; Self::remove(&path)?; for dir in path.ancestors().skip(1) { // Stops at the first directory that isn't empty, or the root. @@ -500,10 +595,12 @@ impl<'a, P: Platform> Worktree<'a, P> { } let writes: Vec<_> = changes .iter() - .filter_map(|change| { + .enumerate() + .filter_map(|(index, change)| { Some(Write { path: self.absolute(&change.path), entry: change.new?, + seen: seen(index), }) }) .collect(); @@ -567,6 +664,49 @@ impl<'a, P: Platform> Worktree<'a, P> { .collect() } + /// Fails with [`SnapshotError::Edited`] if the file `change` changes was + /// edited since the snapshot `cache` is of, which `change` starts from. + /// Returns the file as it found it. + fn check_unchanged( + &self, + change: &FileChange, + cache: &StatCache, + ) -> Result { + let path = self.absolute(&change.path); + let seen = Seen::at(&path)?; + let unchanged = match (seen.0, change.old) { + (None, None) => true, + (Some(stat), Some(old)) => { + cache.get(change.path.as_str(), &stat) == Some(old.id) + || Self::holds(&change.path, &path, old)? + } + _ => false, + }; + if unchanged { + Ok(seen) + } else { + Err(SnapshotError::Edited(path)) + } + } + + /// Whether the file at `absolute`, `path` in the working copy, has the + /// content and kind of `entry`, read and hashed: for files the cache + /// doesn't vouch for, such as those edited just before the snapshot. A + /// socket, FIFO or device has neither. + fn holds(path: &RepoPath, absolute: &Path, entry: TreeEntry) -> Result { + let tracked = fs::symlink_metadata(absolute) + .is_ok_and(|metadata| metadata.is_file() || metadata.is_symlink()); + if !tracked { + return Ok(false); + } + let file = FoundFile { + path: path.clone(), + absolute: absolute.to_owned(), + }; + let examined = Self::examine(&file, &StatCache::default())?; + Ok(examined.id == entry.id && examined.stat.kind == entry.kind) + } + /// Makes what a checkout of `changes` wrote, `writes`, durable: the /// files, but symlinks, whose content their directory holds, and every /// directory up to the root whose entries may have changed. @@ -598,26 +738,40 @@ impl<'a, P: Platform> Worktree<'a, P> { self.root.join(path.as_str()) } - /// Removes a file, if it's there. + /// Removes a file, if it's there. A directory there, where a checkout + /// writes a file, goes if it's empty: the checkout removed the files it + /// held first. One that still holds something holds what no snapshot + /// tracks, such as a `.git`, a FIFO or a file created since, which + /// counts as edited. fn remove(path: &Path) -> Result<(), SnapshotError> { + let io_error = |source| SnapshotError::Io { + path: path.to_owned(), + source, + }; match fs::remove_file(path) { - Err(error) if error.kind() != io::ErrorKind::NotFound => Err(SnapshotError::Io { - path: path.to_owned(), - source: error, - }), - _ => Ok(()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(_) if path.symlink_metadata().is_ok_and(|found| found.is_dir()) => { + match fs::remove_dir(path) { + Err(error) if error.kind() == io::ErrorKind::DirectoryNotEmpty => { + Err(SnapshotError::Edited(path.to_owned())) + } + removed => removed.map_err(io_error), + } + } + removed => removed.map_err(io_error), } } /// Writes the file `write` describes, whose directory exists, replacing - /// any file there. + /// any file there, unless it was edited since it was seen. fn write_file(&self, write: &Write) -> Result<(), SnapshotError> { - let Write { path, entry } = write; + let Write { path, entry, seen } = write; let (path, entry) = (path.as_path(), *entry); let io_error = |source| SnapshotError::Io { path: path.to_owned(), source, }; + Seen::check(*seen, path)?; // Never write through a symlink, or keep the old file's mode. Self::remove(path)?; let blob = self.store.read(entry.id)?; @@ -703,6 +857,13 @@ pub enum SnapshotError { /// A file name cannot appear in a tree. #[error("cannot track {}: invalid file name", .0.display())] UntrackableName(PathBuf), + /// A checkout found a file edited since the snapshot it starts from, + /// and changed nothing. + #[error( + "{} changed while origin was moving the working copy, which stays where it was: run the command again", + .0.display() + )] + Edited(PathBuf), /// Objects cannot be read or stored. #[error(transparent)] Store(#[from] StoreError), @@ -917,15 +1078,128 @@ mod tests { // Back to the old snapshot, then forward to the new one. let worktree = fixture.worktree(); worktree - .checkout(&fixture.store.diff(new, old).unwrap()) + .checkout(&fixture.store.diff(new, old).unwrap(), None) .unwrap(); assert!(!fixture.dir.path().join("swap/inner").exists()); let (back, cache) = fixture.snapshot(&cache); assert_eq!(back, old); worktree - .checkout(&fixture.store.diff(old, new).unwrap()) + .checkout(&fixture.store.diff(old, new).unwrap(), None) .unwrap(); assert!(!fixture.dir.path().join("gone").exists(), "emptied dirs go"); assert_eq!(fixture.snapshot(&cache).0, new); } + + #[test] + fn checkouts_never_overwrite_edits_made_since_the_snapshot() { + let fixture = Fixture::new(); + fixture.write("kept", "kept"); + fixture.write("changed", "before"); + let (old, _) = fixture.snapshot(&StatCache::default()); + fixture.write("changed", "after"); + fixture.write("added", "added"); + let (new, _) = fixture.snapshot(&StatCache::default()); + let back = fixture.store.diff(new, old).unwrap(); + let worktree = fixture.worktree(); + + // Snapshotted, then edited again before the checkout. + let (_, cache) = fixture.snapshot(&StatCache::default()); + fixture.write("changed", "edited since"); + let error = worktree.checkout(&back, Some(&cache)).unwrap_err(); + assert!( + matches!(&error, SnapshotError::Edited(path) if path.ends_with("changed")), + "{error}" + ); + assert_eq!( + fs::read_to_string(fixture.dir.path().join("added")).unwrap(), + "added", + "nothing changed" + ); + + // Edited back, it is as snapshotted: its content tells. + fixture.write("changed", "after"); + worktree.checkout(&back, Some(&cache)).unwrap(); + assert_eq!(fixture.snapshot(&StatCache::default()).0, old); + + // A file created where the checkout writes one. + let (_, cache) = fixture.snapshot(&StatCache::default()); + fixture.write("added", "created since"); + let forward = fixture.store.diff(old, new).unwrap(); + assert!(matches!( + worktree.checkout(&forward, Some(&cache)), + Err(SnapshotError::Edited(_)) + )); + assert_eq!( + fs::read_to_string(fixture.dir.path().join("added")).unwrap(), + "created since" + ); + } + + #[test] + fn checkouts_stop_at_a_file_edited_while_they_run() { + let fixture = Fixture::new(); + fixture.write("file", "before"); + let (old, _) = fixture.snapshot(&StatCache::default()); + fixture.write("file", "after"); + let (new, cache) = fixture.snapshot(&StatCache::default()); + let back = fixture.store.diff(new, old).unwrap(); + let worktree = fixture.worktree(); + + // Found unedited, then edited before the checkout replaces it. + let seen: Vec<_> = back + .iter() + .map(|change| worktree.check_unchanged(change, &cache).unwrap()) + .collect(); + fixture.write("file", "edited meanwhile"); + let error = worktree.apply(&back, Some(&seen)).unwrap_err(); + assert!(matches!(error, SnapshotError::Edited(_)), "{error}"); + assert_eq!( + fs::read_to_string(fixture.dir.path().join("file")).unwrap(), + "edited meanwhile" + ); + } + + #[test] + fn checkouts_turn_files_into_directories_and_back() { + let fixture = Fixture::new(); + fixture.write("a", "file"); + let (file, _) = fixture.snapshot(&StatCache::default()); + fs::remove_file(fixture.dir.path().join("a")).unwrap(); + fixture.write("a/b", "in a directory"); + let (dir, cache) = fixture.snapshot(&StatCache::default()); + let worktree = fixture.worktree(); + + let back = fixture.store.diff(dir, file).unwrap(); + worktree.checkout(&back, Some(&cache)).unwrap(); + let (found, cache) = fixture.snapshot(&StatCache::default()); + assert_eq!(found, file); + let forth = fixture.store.diff(file, dir).unwrap(); + worktree.checkout(&forth, Some(&cache)).unwrap(); + assert_eq!(fixture.snapshot(&StatCache::default()).0, dir); + } + + #[test] + fn restoring_keeps_files_edited_since() { + let fixture = Fixture::new(); + for path in ["unmoved", "moved", "edited"] { + fixture.write(path, "old"); + } + let (old, _) = fixture.snapshot(&StatCache::default()); + for path in ["unmoved", "moved", "edited", "added"] { + fixture.write(path, "new"); + } + let (new, _) = fixture.snapshot(&StatCache::default()); + let changes = fixture.store.diff(old, new).unwrap(); + + // A move cut short, then edits. + fixture.write("unmoved", "old"); + fixture.write("edited", "edited"); + fixture.write("added", "created"); + fixture.worktree().restore(&changes).unwrap(); + let read = |path| fs::read_to_string(fixture.dir.path().join(path)).unwrap(); + assert_eq!(read("unmoved"), "new"); + assert_eq!(read("moved"), "new"); + assert_eq!(read("edited"), "edited"); + assert_eq!(read("added"), "created"); + } } diff --git a/apps/origin-src/tests/cli.rs b/apps/origin-src/tests/cli.rs index 17bb0a99..1bbff083 100644 --- a/apps/origin-src/tests/cli.rs +++ b/apps/origin-src/tests/cli.rs @@ -2,7 +2,7 @@ use std::fs; use std::io::Write; -use std::os::unix::fs::PermissionsExt; +use std::os::unix::fs::{MetadataExt, PermissionsExt}; use std::path::Path; use std::process::{Command, Output, Stdio}; use std::slice; @@ -210,6 +210,34 @@ fn edit_switches_the_files_to_another_change() { assert!(repo.fails(&["edit", "zz"]).contains("is not a change id")); } +#[test] +fn a_directory_holding_untracked_files_refuses_to_become_a_file() { + let repo = Repo::new(); + repo.write("a", "a file\n"); + repo.ok(&["describe", "File"]); + let file = repo.change(); + repo.ok(&["new", "Directory"]); + fs::remove_file(repo.path("a")).unwrap(); + repo.write("a/b", "in a directory\n"); + repo.ok(&["describe", "Directory"]); + let pointer = repo.path(".origin/workspace"); + let revision = fs::read_to_string(&pointer).unwrap(); + // Another tool's repository in it, which no snapshot tracks. + repo.write("a/.git/HEAD", "ref\n"); + + let refused = repo.fails(&["edit", &file]); + assert!( + refused.contains("changed while origin was moving"), + "{refused}" + ); + // The files it removed are back, and the working copy stays. + assert_eq!(repo.read("a/b"), "in a directory\n"); + assert_eq!(repo.read("a/.git/HEAD"), "ref\n"); + let status = repo.ok(&["status"]); + assert!(status.contains(" Directory\n"), "{status}"); + assert_eq!(fs::read_to_string(&pointer).unwrap(), revision); +} + #[test] fn divergence_shows_until_converged() { let repo = Repo::new(); @@ -945,6 +973,31 @@ fn statements_are_promoted_where_their_inputs_are_unchanged() { ); } +#[test] +fn a_move_that_fails_takes_its_files_back() { + let repo = Repo::new(); + repo.write("ro/keep", "keep\n"); + repo.write("ro/new", "new\n"); + let first = repo.change(); + repo.ok(&["new"]); + let second = repo.change(); + fs::remove_file(repo.path("ro/new")).unwrap(); + repo.write("extra", "extra\n"); + // Moving back removes `extra`, then fails to write in `ro`, unless + // this runs as root, who writes there anyway. + if fs::metadata(repo.path("extra")).unwrap().uid() == 0 { + return; + } + fs::set_permissions(repo.path("ro"), fs::Permissions::from_mode(0o555)).unwrap(); + let refused = repo.fails(&["edit", &first]); + fs::set_permissions(repo.path("ro"), fs::Permissions::from_mode(0o755)).unwrap(); + assert!(refused.contains("ro/new"), "{refused}"); + assert_eq!(repo.read("extra"), "extra\n", "taken back"); + assert_eq!(repo.change(), second); + let status = repo.ok(&["status"]); + assert!(status.ends_with("A extra\nD ro/new\n"), "{status}"); +} + #[test] fn landing_moves_the_working_copy_onto_the_target() { let repo = Repo::new();