diff --git a/crates/engine/src/cmd/browse.rs b/crates/engine/src/cmd/browse.rs index 0eb126c40f7..470b00bbd9b 100644 --- a/crates/engine/src/cmd/browse.rs +++ b/crates/engine/src/cmd/browse.rs @@ -409,7 +409,7 @@ fn create_folder(s: &mut Session, p: &Value) -> Result { return Err(bad(C, format!("{path} already exists: choose another name"))); } folder_on_disk("", &path).map_err(|e| bad(C, e))?; - let undo = crate::FolderMove { from: path.clone(), to: String::new() }; + let undo = crate::FolderMove { from: path.clone(), to: String::new(), on_disk: true }; if let Err(e) = s.commit_with_folder(&format!("Create Folder “{name}”"), Op::Batch { ops: vec![] }, undo) { let _ = remove_empty_folder(&path); return Err(e); @@ -555,7 +555,7 @@ pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result: let name = Path::new(to).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default(); let renamed = src.parent() == dst.parent(); let label = if renamed { format!("Rename Folder to “{name}”") } else { format!("Move Folder “{name}”") }; - let folder = crate::FolderMove { from: to.to_string(), to: from.to_string() }; + let folder = crate::FolderMove { from: to.to_string(), to: from.to_string(), on_disk: true }; if let Err(e) = s.commit_with_folder(&label, Op::Batch { ops }, folder) { // the catalog didn't take it: put the folder back where the photos still point let back = rename_folder_on_disk(to, from).err().map(|b| format!("; moving it back failed too: {b}")).unwrap_or_default(); diff --git a/crates/engine/src/cmd/library.rs b/crates/engine/src/cmd/library.rs index 4bf9654250e..81073eac143 100644 --- a/crates/engine/src/cmd/library.rs +++ b/crates/engine/src/cmd/library.rs @@ -15,6 +15,7 @@ mod specs; pub(crate) use filters::covers_other_disks; pub use import::{ImportRequest, import_batch_done, import_params, list_auto_import_folder}; +pub(crate) use selection::select_after_deletion; pub use specs::specs; #[cfg(test)] diff --git a/crates/engine/src/cmd/library/selection.rs b/crates/engine/src/cmd/library/selection.rs index 40130adb9d4..034466d1501 100644 --- a/crates/engine/src/cmd/library/selection.rs +++ b/crates/engine/src/cmd/library/selection.rs @@ -3,7 +3,7 @@ use super::{AlbumId, Flag, Op, PhotoId, Result, Selection, Session, Value, bad, /// The selection after photos left the view (deleted, or rated, flagged or labelled out of it). /// Its callers end an open edit (a slider drag) before their own change, as moving to the next /// photo does, so it is its own undo step and comes first. -pub(super) fn select_after_deletion(s: &mut Session, before: &[PhotoId]) { +pub(crate) fn select_after_deletion(s: &mut Session, before: &[PhotoId]) { let at = before.iter().position(|id| Some(*id) == s.selection.active); let remaining: std::collections::HashSet<_> = s.visible_cloned().into_iter().collect(); s.selection.ids.retain(|id| remaining.contains(id)); diff --git a/crates/engine/src/cmd/missing.rs b/crates/engine/src/cmd/missing.rs index 0c77d709cd9..c9d1ea78d14 100644 --- a/crates/engine/src/cmd/missing.rs +++ b/crates/engine/src/cmd/missing.rs @@ -156,13 +156,13 @@ fn relink(s: &mut Session, p: &Value) -> Result { } /// The stored content hash of a photo, without the `:dupN` suffix duplicates get. -fn stored_hash(p: &Photo) -> Option<&str> { +pub(crate) fn stored_hash(p: &Photo) -> Option<&str> { p.content_hash.as_deref().map(|h| h.split(':').next().unwrap_or(h)).filter(|h| !h.is_empty()) } /// The content hash of the file at `path` (as import computes it), if it can be read. Read in /// pieces: the file is whatever is on the disk, of any size. -fn file_hash(path: &str) -> Option { +pub(crate) fn file_hash(path: &str) -> Option { use std::io::Read; // the opened file must be regular (a FIFO or device would never end), and no more than its size at open is read let file = std::fs::File::open(path).ok()?; @@ -171,7 +171,7 @@ fn file_hash(path: &str) -> Option { } /// The content hash of what `r` gives, read in pieces (the hash import computes of the whole). -fn hash_reader(mut r: impl std::io::Read) -> Option { +pub(crate) fn hash_reader(mut r: impl std::io::Read) -> Option { let mut hasher = lightcraft_preview::Hasher128::new(); let mut piece = vec![0u8; 1 << 16]; loop { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index dd67b755f90..6fc2e4ecb01 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -74,6 +74,7 @@ pub mod print_pdf; pub mod profile_refs; pub mod proof; pub(crate) mod read_file; +pub mod relocate; pub mod rename; pub mod segment; pub mod sidecar; @@ -143,7 +144,8 @@ pub struct UndoEntry { pub label: String, pub op: Op, /// A folder to rename on disk (`from` → `to`) before `op` is applied: Rename / Move Folder - /// (whose `op` relinks the photos inside). Never overwrites; refused when `to` exists. An + /// (whose `op` relinks the photos inside; a located folder, `on_disk: false`, renames nothing + /// and only follows). Never overwrites; refused when `to` exists. An /// empty `to` removes the (empty) folder `from`, an empty `from` creates `to` (Create Folder). pub folder: Option, /// Inverses of logged path corrections from a partially failed history step. @@ -174,16 +176,20 @@ fn single_photo(op: &Op, depth: usize) -> Option { } } -/// A folder renamed or moved on disk as part of an undo step. +/// A folder renamed or moved on disk as part of an undo step, or (`on_disk: false`) a folder +/// located where it already is, which moves no file. #[derive(Clone, Debug, PartialEq, Eq)] pub struct FolderMove { pub from: String, pub to: String, + /// The step renames the folder on disk. `false` for a folder located where it already is + /// (`folder.updateLocation`): only the photos and the view follow, no file is touched. + pub on_disk: bool, } impl FolderMove { fn reversed(&self) -> Self { - Self { from: self.to.clone(), to: self.from.clone() } + Self { from: self.to.clone(), to: self.from.clone(), on_disk: self.on_disk } } } @@ -882,17 +888,19 @@ impl Session { rename::validate_sidecars(fs, &entry.retry_sidecars).map_err(|e| EngineError::Other(format!("can't move the files back: {e}")))?; // Repair discarded file steps before another path change can stale their exact paths. // Unrelated metadata history must remain usable while a sidecar is still unwritable. - if entry.folder.is_some() || !entry.retry_sidecars.is_empty() || !self.file_moves(&entry.op).is_empty() { + // the folder to rename on disk, if the step has one + let on_disk = entry.folder.as_ref().filter(|f| f.on_disk); + if on_disk.is_some() || !entry.retry_sidecars.is_empty() || !self.file_moves(&entry.op).is_empty() { self.repair_sidecars_with(fs).map_err(|e| EngineError::Other(format!("can't move the files back: {e}")))?; } rename::retry_sidecars(fs, &mut entry.retry_sidecars).map_err(|e| EngineError::Other(format!("can't move the files back: {e}")))?; let op = &entry.op; let folder = entry.folder.as_ref(); - if let Some(f) = folder { + if let Some(f) = on_disk { cmd::browse::folder_on_disk(&f.from, &f.to).map_err(|e| EngineError::Other(format!("can't move the folder back: {e}")))?; } let undo_folder = || { - if let Some(f) = folder { + if let Some(f) = on_disk { let _ = cmd::browse::folder_on_disk(&f.to, &f.from); } }; @@ -911,8 +919,10 @@ impl Session { } match self.apply_catalog(op.clone()) { Ok(inv) => { - if let Some(f) = folder { - cmd::browse::follow_folder(self, &f.from, &f.to); + match folder { + Some(f) if f.on_disk => cmd::browse::follow_folder(self, &f.from, &f.to), + Some(f) => relocate::follow_located(self, &f.from, &f.to), + None => {} } if entry.retry_inverse.is_empty() { Ok(inv) diff --git a/crates/engine/src/relocate.rs b/crates/engine/src/relocate.rs new file mode 100644 index 00000000000..973e863f0d7 --- /dev/null +++ b/crates/engine/src/relocate.rs @@ -0,0 +1,618 @@ +//! Locating a library folder that is somewhere else now (`folder.updateLocation`, issues #1112 and #1116). +//! +//! A folder of the library can stop being where the library looks for it without LightCraft +//! having moved it: it was renamed or moved in the file manager, its disk is mounted under +//! another name, or its catalog came from another computer (a Lightroom catalog written on +//! Windows names `D:\Photos\…`, which is nowhere on Linux). Synchronize Folder can only say the +//! folder isn't there. Locating it says where it is now: every photo below the old folder (those +//! in the folders inside it and in Recently Deleted too) points at the same place below the new +//! one, and what the library knows about the folders (their colour labels) goes along. Only the +//! catalog changes; no file is touched, and it is one undo step. +//! +//! It is done in three parts, so the app never waits on a disk in a frame: +//! +//! 1. [`Relocation::new`] reads the request against the session: it works out where each photo's +//! file would be and refuses what needs no disk to refuse (no file-system access). It keeps +//! the places and what the library recorded of the files, not the library. +//! 2. [`Relocation::look`] reads the disk, never the session, so it can run on a worker thread: +//! it tells for each place whether the photo's file is there. +//! 3. [`Located::commit`] relinks the photos, on the session as it is by then. +//! +//! Looking is the guard against choosing the wrong folder (one level too high or too low is the +//! likely mistake), and a file being at a place does not make it the photo's ([`Sought`]): +//! +//! * a place that is, as the library has it, the file of another photo of the folder (the new +//! place is inside the folder, or the folder inside it) is taken only when the file's content +//! is the photo's. Otherwise the step is refused, whatever was asked: the photo would show +//! the other photo's picture under its own edits. The same file can be reached by many paths +//! (other letter case on a disk that doesn't tell case apart, a link at or below either +//! folder), so while the folder is still on disk where the library has it, the photos' files +//! are told by what they are on disk ([`FileId`]), not by how their paths are spelled; a +//! place written with `..` is refused. (One share mounted twice is two disks to this.) +//! * a file inside the folder that was only looked at in Local is taken for the library's photo +//! coming to its place when its content is the photo's, where the library recorded that; +//! * a file of another size than the library recorded is not the file it knew: it is not counted +//! as found; +//! * a folder with none of the files is not the folder, and one with only some of them (or with +//! files of another size) is taken only on request (`incomplete`). Files that aren't there +//! then stay missing at the new place, where Synchronize Folder finds them. +//! +//! Paths are compared by folder identity ([`lightcraft_catalog::query::folder_key`]), not by +//! [`std::path::Path`]: on Linux and macOS `D:\Photos\a.jpg` is one file name to `Path`. + +use std::collections::{HashMap, HashSet}; +use std::path::{Path, PathBuf}; +use std::sync::atomic::Ordering::Relaxed; +use std::sync::{Arc, Mutex, PoisonError}; + +use lightcraft_catalog::query::{folder_key, folder_rest}; +use lightcraft_catalog::{Catalog, Filter, Op, PhotoId, Sort, Source}; +use serde_json::{Value, json}; + +use crate::import::ScanProgress; +use crate::{EngineError, FolderMove, Result, Session}; + +fn invalid(msg: impl Into) -> EngineError { + EngineError::Other(msg.into()) +} + +/// A request to locate folder `from` at `to`, checked as far as the session alone can tell. +pub struct Relocation { + /// The folder as the library knows it. + pub from: String, + /// Where it is said to be now (absolute, spelled the way this computer spells paths). + pub to: String, + /// The photos that would follow the folder. + photos: Vec, + /// The places [`Relocation::look`] looks at. + files: Vec, + /// Which library that is ([`Located::commit`] is for no other). + library: Arc<()>, +} + +/// A place a file of the folder would be, and what tells whether the file there is the photo's. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Sought { + pub path: String, + /// The size the library recorded for the file (0: none, as for photos of a catalog that + /// came from another app). + size: u64, + /// The contents the library recorded for the photos that would be here (a virtual copy + /// shares its photo's file); empty when it recorded none. + hashes: Vec, + /// Where the photos that would be here are now, as the library has them. + now: Vec, + /// The place is, as the library has it, the file of another photo of the folder: only its + /// content tells whose the file there is. + claimed: bool, + /// The place is a file of the folder that was only looked at in Local: nothing says it is + /// the photo's, so its content is asked where the library recorded the photo's. + browsed: bool, + /// A library photo's (not only one's in Recently Deleted or browsed in Local, which nobody + /// is looking for): counted in [`Located::total`]. + counted: bool, +} + +/// What is at a place ([`Sought`]). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +enum Seen { + /// No file. + Missing, + /// A file of the size the library recorded (of the photo's content, at a claimed place). + Same, + /// A file, and the library recorded no size to tell by. + Unverified, + /// A file of another size. + Different, + /// A file at a claimed place that is not known to be the photo's. + Claimed, +} + +/// What a file is on disk, however its path is spelled. +#[cfg(unix)] +type FileId = (u64, u64); +#[cfg(not(unix))] +type FileId = PathBuf; + +/// What the file or folder at `path` is on disk (links followed), if it is there. +fn file_id(path: &Path, meta: Option<&std::fs::Metadata>) -> Option { + #[cfg(unix)] + { + use std::os::unix::fs::MetadataExt; + let read; + let meta = match meta { + Some(m) => m, + None => { + read = std::fs::metadata(path).ok()?; + &read + } + }; + Some((meta.dev(), meta.ino())) + } + #[cfg(not(unix))] + { + // (no file id in std here: the path as the system spells it, links and letter case resolved) + let _ = meta; + std::fs::canonicalize(path).ok() + } +} + +/// The files of the folder's photos where the library has them now, by what they are on disk: +/// a file at the new place can be one of them under another path (a place inside the folder, a +/// link at or below either folder). Empty when the folder is not on disk where the library has +/// it (the usual case: nothing of `from` is looked at then). +fn files_now(photos: &[RelocatedPhoto], from: &str, progress: &ScanProgress) -> HashMap { + let mut out = HashMap::new(); + if file_id(Path::new(from), None).is_none() { + return out; + } + for r in photos { + if progress.cancel.load(Relaxed) { + break; + } + if let Some(id) = file_id(Path::new(&r.from), None) { + out.entry(id).or_insert_with(|| r.from.clone()); + } + } + out +} + +impl Sought { + /// What is at the place. `theirs`: the files of the folder's photos as they are on disk now + /// ([`files_now`]). + fn seen(&self, theirs: &HashMap) -> Seen { + let Ok(meta) = std::fs::metadata(&self.path) else { return Seen::Missing }; + if !meta.is_file() { + return Seen::Missing; + } + // another photo's file under another spelling of its path (a photo's own file, where + // the new place is another name for the folder itself, is its own) + let theirs = || { + !theirs.is_empty() && file_id(Path::new(&self.path), Some(&meta)).and_then(|id| theirs.get(&id)).is_some_and(|at| !self.now.contains(at)) + }; + if self.claimed || theirs() || (self.browsed && !self.hashes.is_empty()) { + // the photo's file has the photo's size and content (read only here, and in pieces: + // files shared by the two folders are rare, and reading every file of a folder on a + // network share takes hours) + let proven = !self.hashes.is_empty() + && (self.size == 0 || self.size == meta.len()) + && crate::cmd::missing::file_hash(&self.path).is_some_and(|c| self.hashes.iter().all(|h| *h == c)); + return if proven { Seen::Same } else { Seen::Claimed }; + } + match self.size { + 0 => Seen::Unverified, + n if n == meta.len() => Seen::Same, + _ => Seen::Different, + } + } +} + +/// What [`look_at`] saw at the places of the library's files. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct Tally { + /// Files that are there and not known to be other files… + pub found: usize, + /// …those among them the library recorded no size for. + pub unverified: usize, + /// Files there of another size than the library recorded. + pub different: usize, + /// Claimed places whose file is not known to be the photo's, and one of them. + claimed: usize, + claimed_example: Option, +} + +/// One photo of the folder and where its file is once the folder is located. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct RelocatedPhoto { + pub id: PhotoId, + /// Its file as the library has it; a photo that has left it by [`Located::commit`] is skipped. + pub from: String, + pub to: String, +} + +/// What [`Relocation::look`] found: the photos that would follow the folder, and how many of +/// the library's files are at the new place. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Located { + pub from: String, + pub to: String, + pub photos: Vec, + /// Files of library photos (not those in Recently Deleted or only browsed in Local; a + /// virtual copy shares its photo's file) that are at the new place and not known to be + /// other files… + pub found: usize, + /// …of this many. + pub total: usize, + /// Those of `found` the library recorded no size for: a file is there, and nothing tells + /// whether it is the photo's. + pub unverified: usize, + /// Files at the new place of another size than the library recorded (not in `found`). + pub different: usize, + /// The library the photos are of: one opened meanwhile is not touched. + library: Arc<()>, +} + +impl Relocation { + /// Read a request to locate folder `path` of the library at `to`. Refused: the startup disk, + /// a folder no library photo was imported from, a whole disk or a folder that holds disks + /// without `disk` (as for Synchronize Folder), the place the library already looks, and the + /// library's own folder, and a place where a file is already another photo's (one not of + /// this folder; two photos would share one file). No file-system access. + pub fn new(s: &Session, path: &str, to: &str, disk: bool) -> Result { + if cfg!(target_arch = "wasm32") { + // (no disk to look at: every folder would be "not a folder") + return Err(invalid("locating a folder is not supported in the web version: it has no disk to look for the photos' files on")); + } + if path.trim().is_empty() { + return Err(invalid("missing `folder`")); + } + if to.trim().is_empty() { + return Err(invalid("missing `path`")); + } + if lightcraft_catalog::folders::is_startup_disk(path) { + return Err(invalid("choose a folder, not the whole startup disk")); + } + let f = Filter { library_folder: Some(path.to_string()), ..Default::default() }; + let ids = s.catalog.query(&f, &Sort::default()); + if ids.is_empty() { + return Err(invalid(format!("{path}: no photo in the library was imported from it"))); + } + if !disk && (lightcraft_catalog::folders::is_disk_root(path) || crate::cmd::library::covers_other_disks(s, path, &ids)) { + return Err(invalid(format!("{path} is a whole disk or holds disks: pass `disk: true` to locate it"))); + } + let abs = std::path::absolute(to).map_err(|e| invalid(format!("{to}: {e}")))?; + // (one place has one spelling to compare by: `a/b/../b` is not told from `a/b` as written) + if abs.components().any(|c| matches!(c, std::path::Component::ParentDir)) { + return Err(invalid(format!("{to}: give the folder's full path, without `..`"))); + } + // (rebuilt from its parts: no trailing separator, so the photos' paths are joined cleanly) + let abs: PathBuf = abs.components().collect(); + let to = abs.to_string_lossy().to_string(); + if folder_key(path) == folder_key(&to) { + return Err(invalid(format!("{to} is where the library already looks for this folder"))); + } + if s.library.as_ref().is_some_and(|l| l.on_disk && abs.starts_with(&l.dir)) { + return Err(invalid(format!("{to} is inside the library's own folder, which is no place for photos"))); + } + let Destinations { photos, files } = destinations(&s.catalog, path, &to); + let moving: HashSet = photos.iter().map(|r| r.id).collect(); + let places: HashSet = photos.iter().map(|r| r.to.clone()).collect(); + // (said before any file is looked for; [`Located::commit`] asks again of the library as it is then) + giving_way(&s.catalog, &moving, &places, &to).map_err(invalid)?; + Ok(Relocation { from: path.to_string(), to, photos, files, library: Arc::clone(&s.library_identity) }) + } + + /// Whether the folder's files are at the new place. Reads the disk, never the session. + /// Refused when `to` is not a folder, or when a file there is another photo's of this + /// folder and not known to be the photo's that would point at it ([`Sought`]). + /// + /// `progress` counts the places looked at; with its `cancel` set the looking stops early + /// and is refused: what was seen until then says nothing. + pub fn look(self, progress: &ScanProgress) -> std::result::Result { + let Relocation { from, to, photos, files, library } = self; + if !Path::new(&to).is_dir() { + return Err(format!("{to} is not a folder")); + } + let total = files.iter().filter(|f| f.counted).count(); + let theirs = files_now(&photos, &from, progress); + // (a place only a photo in Recently Deleted or a kept Local record would point at is + // looked at where a file there can be another photo's) + let files: Vec = files.into_iter().filter(|f| f.counted || f.claimed || !theirs.is_empty()).collect(); + let Tally { found, unverified, different, claimed, claimed_example } = look_at(&files, &theirs, progress); + if progress.cancel.load(Relaxed) { + // (places not looked at may be other photos' files: what was seen says nothing) + return Err("locating the folder was stopped: nothing was changed".to_string()); + } + if let Some(first) = claimed_example { + let n = claimed; + let (s, verb, is) = if n == 1 { ("", "belongs", "is") } else { ("s", "belong", "are") }; + return Err(format!( + "{n} file{s} in {to} {verb} to other photos of this folder, or {is} another picture than the library recorded for the photo, as far as the library can tell (such as {first}): choose the folder its files are in now. \ + (The folder as the library has it and the chosen one share files; a file there is taken for a photo only when the library recorded the photo's content and the file has it.)" + )); + } + Ok(Located { from, to, photos, found, total, unverified, different, library }) + } + + /// The places [`Relocation::look`] looks at (tests). + #[cfg(test)] + pub(crate) fn files(&self) -> &[Sought] { + &self.files + } +} + +/// Where the photos of a folder would be, and the places to look at. +struct Destinations { + photos: Vec, + /// Each place once (a virtual copy shares its photo's file). + files: Vec, +} + +fn destinations(catalog: &Catalog, from: &str, to: &str) -> Destinations { + let base = PathBuf::from(to); + let mut photos: Vec = Vec::new(); + let mut files: Vec = Vec::new(); + let mut at: HashMap = HashMap::new(); + // A record of only having looked at a file in Local is no photo of the folder: it stays (the + // place on disk did not move), and gives way where a photo of the library comes to its file + // ([`giving_way`]) — also when that file is in a folder inside this one. + let browsed: HashSet = catalog + .photos() + .filter(|p| p.local && !p.deleted) + .filter_map(|p| match &p.source { + Source::File { path } if folder_rest(path, from).is_some() => Some(path.clone()), + _ => None, + }) + .collect(); + let looked: HashSet = catalog.local_records_of(&browsed).untouched.into_iter().collect(); + let mut looked_at: HashSet<&str> = HashSet::new(); + for p in catalog.photos() { + let Source::File { path } = &p.source else { continue }; + if looked.contains(&p.id) { + looked_at.insert(path.as_str()); + continue; + } + let Some(rest) = folder_rest(path, from).filter(|r| !r.is_empty()) else { continue }; + // joined by the platform, so the result is spelled like a path read from this disk + let dest = rest.iter().fold(base.clone(), |d, name| d.join(name)).to_string_lossy().to_string(); + let i = *at.entry(dest.clone()).or_insert_with(|| { + files.push(Sought { path: dest.clone(), size: 0, hashes: Vec::new(), now: Vec::new(), claimed: false, browsed: false, counted: false }); + files.len() - 1 + }); + if let Some(f) = files.get_mut(i) { + f.counted |= p.in_library(); + if !f.now.contains(path) { + f.now.push(path.clone()); + } + if f.size == 0 { + f.size = p.file_size; + } + if let Some(h) = crate::cmd::missing::stored_hash(p).filter(|h| !f.hashes.iter().any(|x| x == h)) { + f.hashes.push(h.to_string()); + } + } + photos.push(RelocatedPhoto { id: p.id, from: path.clone(), to: dest }); + } + // a place one of the photos is at now is that photo's file, as far as the library knows + let now: HashSet<&str> = photos.iter().map(|r| r.from.as_str()).collect(); + for f in &mut files { + f.claimed = now.contains(f.path.as_str()); + f.browsed = looked_at.contains(f.path.as_str()); + } + Destinations { photos, files } +} + +/// The records that give way when the photos `moving` point at `places` (every place one of +/// them would be, the library's or not), so that no file has two records: Local records of +/// those files that are only a record of having looked ([`Catalog::local_records_of`]). +/// Refused when a place is another photo's already — a library photo's, or one's in Recently +/// Deleted (restoring it would make two) — or a Local record's that holds something of the +/// person's. Paths are compared as written, as everywhere in the library. +fn giving_way(catalog: &Catalog, moving: &HashSet, places: &HashSet, to: &str) -> std::result::Result, String> { + let taken: Vec<&str> = catalog + .photos() + .filter(|p| (!p.local || p.deleted) && !moving.contains(&p.id)) + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.as_str()), + _ => None, + }) + .filter(|f| places.contains(*f)) + .collect(); + if let Some(first) = taken.first() { + let n = taken.len(); + let are = if n == 1 { "is" } else { "are" }; + return Err(format!( + "{n} file{} in {to} {are} already in the library, Recently Deleted included (such as {first}): the folder can't be located there", + plural(n) + )); + } + let local = catalog.local_records_of(places); + let kept: Vec<&(PhotoId, String)> = local.kept.iter().filter(|(id, _)| !moving.contains(id)).collect(); + if let Some((_, first)) = kept.first() { + let n = kept.len(); + let were = if n == 1 { "was" } else { "were" }; + return Err(format!( + "{n} file{} in {to} {were} rated, edited or put in an album while browsing it in Local (such as {first}): the library's photos can't take their place", + plural(n) + )); + } + Ok(local.untouched.into_iter().filter(|id| !moving.contains(id)).collect()) +} + +fn plural(n: usize) -> &'static str { + if n == 1 { "" } else { "s" } +} + +/// What is at each of `files`, looked at on several threads (a network share answers each +/// slowly). `progress.total` / `done` follow; stops early when `progress.cancel` is set, with +/// what was seen so far. +pub fn look_at(files: &[Sought], theirs: &HashMap, progress: &ScanProgress) -> Tally { + use std::sync::atomic::AtomicUsize; + progress.total.store(files.len(), Relaxed); + progress.done.store(0, Relaxed); + if cfg!(target_arch = "wasm32") { + return Tally::default(); + } + let cancel = &progress.cancel; + let (found, unverified, different, claimed, next) = + (AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0), AtomicUsize::new(0)); + let example: Mutex> = Mutex::new(None); + let work = || { + while !cancel.load(Relaxed) { + let Some(f) = files.get(next.fetch_add(1, Relaxed)) else { break }; + match f.seen(theirs) { + Seen::Claimed => { + claimed.fetch_add(1, Relaxed); + example.lock().unwrap_or_else(PoisonError::into_inner).get_or_insert_with(|| f.path.clone()); + } + // (a place only a photo in Recently Deleted or a Local record would point at is + // looked at for whose file it is, not counted) + _ if !f.counted => {} + Seen::Same => { + found.fetch_add(1, Relaxed); + } + Seen::Unverified => { + found.fetch_add(1, Relaxed); + unverified.fetch_add(1, Relaxed); + } + Seen::Different => { + different.fetch_add(1, Relaxed); + } + Seen::Missing => {} + } + progress.done.fetch_add(1, Relaxed); + } + }; + #[cfg(not(target_arch = "wasm32"))] + { + let n = crate::import::workers(files.len()); + if n > 1 { + std::thread::scope(|sc| { + // (a thread the system won't start: the others, or this one, do its share) + let started = (0..n).filter(|_| std::thread::Builder::new().spawn_scoped(sc, work).is_ok()).count(); + if started == 0 { + work(); + } + }); + } else { + work(); + } + } + #[cfg(target_arch = "wasm32")] + work(); + Tally { + found: found.into_inner(), + unverified: unverified.into_inner(), + different: different.into_inner(), + claimed: claimed.into_inner(), + claimed_example: example.into_inner().unwrap_or_else(PoisonError::into_inner), + } +} + +impl Located { + /// Why this is not (or not plainly) the folder, if it isn't: none of the files are there, or + /// only some (the others are not there, or are of another size than the library recorded) + /// and `incomplete` wasn't said. + pub fn refusal(&self, incomplete: bool) -> Option { + let Located { from, to, found, total, different, .. } = self; + // files of another size are said: they are what tells a disk laid out alike from the folder + let others = match *different { + 0 => String::new(), + 1 => "; 1 file there is not the one the library recorded (another size)".to_string(), + n => format!("; {n} files there are not the ones the library recorded (another size)"), + }; + if *found == 0 { + return Some(format!( + "none of the {total} file{} of {from} {} in {to}{others}: choose the folder it is now", + plural(*total), + if *total == 1 { "is" } else { "are" } + )); + } + (found < total && !incomplete).then(|| { + format!( + "only {found} of the {total} files of {from} are in {to}{others}: pass `incomplete: true` to locate it there anyway (files that aren't there stay missing)" + ) + }) + } + + /// Point the photos at the new place, with the folders' records, as one undo step (undo and + /// redo move no file). Checked against the session as it is now: a photo that is no longer + /// where [`Relocation::look`] saw it (relinked or removed meanwhile) is left alone, and what + /// is at the new place is asked again. Records of files there that were only browsed in + /// Local, untouched, go as the library's photos take their place (a file has one record; + /// otherwise Synchronize Folder would offer every file as new); undo brings them back. + /// → `{folder, path, relinked, found, unverified, different, notFound, replacedLocal}`. + pub fn commit(self, s: &mut Session, incomplete: bool) -> Result { + // (photo ids mean something else in another library) + if !Arc::ptr_eq(&self.library, &s.library_identity) { + return Err(invalid("another library was opened meanwhile: the folder was not located")); + } + if let Some(why) = self.refusal(incomplete) { + return Err(invalid(why)); + } + let Located { from, to, photos, found, total, unverified, different, .. } = self; + let before = s.visible_cloned(); + let mut ops: Vec = Vec::new(); + let mut moving: HashSet = HashSet::new(); + let mut places: HashSet = HashSet::new(); + for r in photos { + let Some(p) = s.catalog.photo(r.id) else { continue }; + if !matches!(&p.source, Source::File { path } if *path == r.from) { + continue; + } + moving.insert(r.id); + places.insert(r.to.clone()); + ops.push(Op::Relink { id: r.id, file_name: p.file_name.clone(), source: Source::File { path: r.to }, format: None }); + } + let relinked = ops.len(); + if relinked == 0 { + return Err(invalid(format!("{from} holds no photo any more: the library changed meanwhile"))); + } + // the library may have changed while the files were looked for (a folder browsed, a photo + // imported or relinked): what is at the new place is asked of it as it is now + let replaced = giving_way(&s.catalog, &moving, &places, &to).map_err(invalid)?; + // what the library knows about the folder (and those inside it) goes along, in the same + // step; what it knows about folders already at the new place stays + ops.extend(s.catalog.folder_records_located(&from, &to)); + ops.extend(replaced.iter().map(|id| Op::RemovePhoto { id: *id })); + let name = lightcraft_catalog::folders::folder_label(&to); + // (the undo direction: the new place → the old one; nothing is renamed on disk) + let back = FolderMove { from: to.clone(), to: from.clone(), on_disk: false }; + s.commit_with_folder(&format!("Locate Folder “{name}”"), Op::Batch { ops }, back)?; + follow_located(s, &from, &to); + if !replaced.is_empty() { + crate::cmd::library::select_after_deletion(s, &before); + } + Ok(json!({ + "folder": from, + "path": to, + "relinked": relinked, + "found": found, + "unverified": unverified, + "different": different, + "notFound": total.saturating_sub(found).saturating_sub(different), + "replacedLocal": replaced.len(), + })) + } +} + +/// After a folder was located (`from` → `to`), or that was undone: a library folder being shown +/// (as the source or in the filter) at or below `from` is shown at the same place below `to`, +/// if its photos left it. One that still holds photos is another folder that was there all +/// along (a folder of the library at the new place, chosen since) and stays. A folder browsed +/// in Local is a place on disk, which did not move, and stays too. +pub(crate) fn follow_located(s: &mut Session, from: &str, to: &str) { + let moved = |s: &Session, chosen: &Option| -> Option { + let c = chosen.as_deref()?; + let rest = folder_rest(c, from)?; + let f = Filter { library_folder: Some(c.to_string()), ..Default::default() }; + if !s.catalog.query(&f, &Sort::default()).is_empty() { + return None; + } + Some(rest.iter().fold(PathBuf::from(to), |p, name| p.join(name)).to_string_lossy().to_string()) + }; + if let Some(now) = moved(s, &s.library_folder) { + s.library_folder = Some(now); + } + if let Some(now) = moved(s, &s.filter.library_folder) { + s.filter.library_folder = Some(now); + } + if let Some(f) = s.shelved_filter.as_ref() + && let Some(now) = moved(s, &f.library_folder) + && let Some(f) = s.shelved_filter.as_mut() + { + f.library_folder = Some(now); + } +} + +/// The three parts in one go, on the calling thread, for a caller whose thread is its own to +/// spend: the `folder.updateLocation` command of the CLI and headless MCP (registered with the +/// app's part of this feature, which does the looking on a worker thread instead). +pub fn relocate(s: &mut Session, path: &str, to: &str, disk: bool, incomplete: bool) -> Result { + let plan = Relocation::new(s, path, to, disk)?; + let task = s.activity.start("relocate", "Locating folder", crate::activity::Cancel::No); + task.detail(&lightcraft_catalog::folders::folder_label(&plan.from)); + let located = plan.look(&ScanProgress::default()).map_err(invalid)?; + drop(task); + located.commit(s, incomplete) +} diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 958c1228712..91eb92dbb55 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -50,6 +50,7 @@ mod preview_prep; mod print; mod process; mod recheck; +mod relocate; mod segment; mod settings_files; mod shelved_folder; diff --git a/crates/engine/src/tests/relocate.rs b/crates/engine/src/tests/relocate.rs new file mode 100644 index 00000000000..6fb345e15d5 --- /dev/null +++ b/crates/engine/src/tests/relocate.rs @@ -0,0 +1,964 @@ +//! Locating a library folder that is somewhere else now (see [`crate::relocate`]; issue #1112). +//! +//! Scenarios, in the words of someone whose folder is not where the library looks for it: +//! +//! * Given a folder of the library that was moved or renamed outside LightCraft (or whose +//! catalog came from another computer), when the person says where it is now, its photos — +//! those in the folders inside it and in Recently Deleted too — point at the same places below +//! the new folder. No file is touched, and it is one undo step. +//! * A path written by Windows (`D:\Photos\…`) is located on a computer that spells paths `/…`. +//! * What the library knows about the folder (its colour label) and the folder being shown +//! follow; undo brings both back. +//! * A folder that holds none of the photos' files is refused: it is not the folder. One that +//! holds only some is refused unless the person says so; the others then stay missing there. +//! Looking for the files can run apart from the session, and can be stopped. +//! * A folder whose files the library already has is refused, as are the folder itself, the +//! library's own folder, a path that is no folder, and a folder that is not the library's. + +use std::path::{Path, PathBuf}; +use std::sync::atomic::Ordering; + +use lightcraft_catalog::{ColorLabel, Filter, Op, PhotoId, Source}; +use serde_json::{Value, json}; + +use crate::Session; +use crate::relocate::{Relocation, look_at}; + +/// A scratch folder that goes away with the test, however it ends. +struct Scratch(PathBuf); + +impl Scratch { + fn new(tag: &str) -> Scratch { + let dir = std::env::temp_dir().join(format!("lc-relocate-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + Scratch(dir) + } + fn path(&self, rel: &str) -> String { + self.0.join(rel).components().collect::().to_string_lossy().into_owned() + } +} + +impl Drop for Scratch { + fn drop(&mut self) { + let _ = std::fs::remove_dir_all(&self.0); + } +} + +/// A small procedural PNG (distinct per seed). +fn write_png(path: &str, seed: u8) { + let (w, h) = (24usize, 16usize); + let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i % w * 9) as u8, (i / w * 13) as u8, seed, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + std::fs::create_dir_all(Path::new(path).parent().unwrap()).unwrap(); + std::fs::write(path, bytes).unwrap(); +} + +/// A library holding `trip/a.png` and `trip/day1/b.png`. +fn library(dir: &Scratch) -> Session { + write_png(&dir.path("trip/a.png"), 1); + write_png(&dir.path("trip/day1/b.png"), 2); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("trip")]})).unwrap(); + assert_eq!(s.catalog.len(), 2); + s +} + +/// The folder moved away whole, outside LightCraft: `trip` is now `archive/journey`. +fn moved_away(dir: &Scratch) -> String { + std::fs::create_dir_all(dir.0.join("archive")).unwrap(); + std::fs::rename(dir.0.join("trip"), dir.0.join("archive/journey")).unwrap(); + dir.path("archive/journey") +} + +/// Where the library looks for each photo's file. +fn files(s: &Session) -> Vec { + let mut v: Vec = s + .catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => Some(path.clone()), + _ => None, + }) + .collect(); + v.sort(); + v +} + +/// [`crate::relocate::relocate`] with the parameters named as an agent would give them +/// (`{folder, path, disk?, incomplete?}`). +fn update_location(s: &mut Session, params: &Value) -> crate::Result { + let flag = |key: &str| params.get(key).and_then(Value::as_bool).unwrap_or(false); + let text = |key: &str| params[key].as_str().unwrap().to_string(); + crate::relocate::relocate(s, &text("folder"), &text("path"), flag("disk"), flag("incomplete")) +} + +fn relocate(s: &mut Session, from: &str, to: &str) -> Value { + update_location(s, &json!({"folder": from, "path": to})).unwrap() +} + +fn refused(s: &mut Session, params: Value) -> String { + let (before, steps) = (files(s), s.undo.len()); + let e = update_location(s, ¶ms).unwrap_err().to_string(); + assert_eq!(files(s), before, "a refusal changes nothing"); + assert_eq!(s.undo.len(), steps, "and leaves no undo step"); + e +} + +#[test] +fn a_folder_moved_outside_lightcraft_is_located_and_its_photos_follow() { + let dir = Scratch::new("follow"); + let mut s = library(&dir); + let now = moved_away(&dir); + assert_eq!(s.execute("library.missing", &json!({})).unwrap().as_array().unwrap().len(), 2, "both are missing first"); + + let r = relocate(&mut s, &dir.path("trip"), &now); + + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64(), r["notFound"].as_u64()), (Some(2), Some(2), Some(0)), "{r}"); + assert_eq!(r["path"], json!(now)); + assert_eq!(files(&s), [dir.path("archive/journey/a.png"), dir.path("archive/journey/day1/b.png")]); + assert!(s.execute("library.missing", &json!({})).unwrap().as_array().unwrap().is_empty(), "nothing is missing any more"); + let scan = s.execute("folder.scanChanges", &json!({"path": now})).unwrap(); + for key in ["new", "missing", "moved", "metadata"] { + assert!(scan[key].as_array().unwrap().is_empty(), "{key}: the library is up to date with the folder: {scan}"); + } +} + +#[test] +fn locating_is_one_undo_step_and_touches_no_file() { + let dir = Scratch::new("undo"); + let mut s = library(&dir); + let before = files(&s); + let now = moved_away(&dir); + let steps = s.undo.len(); + + relocate(&mut s, &dir.path("trip"), &now); + assert_eq!(s.undo.len(), steps + 1); + let after = files(&s); + + s.undo_step().unwrap(); + assert_eq!(files(&s), before, "undo points the photos back"); + assert!(Path::new(&now).join("a.png").is_file() && !dir.0.join("trip").exists(), "and moves nothing on disk"); + s.redo_step().unwrap(); + assert_eq!(files(&s), after); + assert!(Path::new(&now).join("day1/b.png").is_file() && !dir.0.join("trip").exists()); +} + +/// Point every photo of the library at the same place below `root`, as a catalog from +/// another computer would have it. +fn as_written_elsewhere(s: &mut Session, dir: &Scratch, root: &str, sep: &str) { + let ops = s + .catalog + .photos() + .filter_map(|p| match &p.source { + Source::File { path } => { + let rel: Vec = + Path::new(path).strip_prefix(&dir.0).unwrap().components().map(|c| c.as_os_str().to_string_lossy().into_owned()).collect(); + Some(Op::Relink { + id: p.id, + file_name: p.file_name.clone(), + source: Source::File { path: format!("{root}{}", rel.join(sep)) }, + format: None, + }) + } + _ => None, + }) + .collect(); + s.commit("elsewhere", Op::Batch { ops }).unwrap(); +} + +#[test] +fn a_folder_of_a_windows_catalog_is_located_on_this_computer() { + let dir = Scratch::new("windows"); + let mut s = library(&dir); + as_written_elsewhere(&mut s, &dir, "D:\\Photos\\", "\\"); + assert_eq!(files(&s), ["D:\\Photos\\trip\\a.png", "D:\\Photos\\trip\\day1\\b.png"]); + + let r = relocate(&mut s, "D:\\Photos\\trip", &dir.path("trip")); + + assert_eq!(r["relinked"], json!(2), "{r}"); + assert_eq!(files(&s), [dir.path("trip/a.png"), dir.path("trip/day1/b.png")], "spelled the way this computer spells paths"); +} + +#[test] +fn a_whole_disk_is_located_only_on_request() { + let dir = Scratch::new("disk"); + let mut s = library(&dir); + as_written_elsewhere(&mut s, &dir, "D:\\", "\\"); + + let e = refused(&mut s, json!({"folder": "D:\\", "path": dir.path("")})); + assert!(e.contains("disk: true"), "{e}"); + + let r = update_location(&mut s, &json!({"folder": "D:\\", "path": dir.path(""), "disk": true})).unwrap(); + assert_eq!(r["relinked"], json!(2), "{r}"); + assert_eq!(files(&s), [dir.path("trip/a.png"), dir.path("trip/day1/b.png")]); +} + +#[test] +fn photos_in_recently_deleted_follow_their_folder() { + let dir = Scratch::new("trash"); + let mut s = library(&dir); + let id = s.catalog.photos().find(|p| p.file_name == "a.png").map(|p| p.id).unwrap(); + s.execute("photo.delete", &json!({"ids": [id.0]})).unwrap(); + let now = moved_away(&dir); + + let r = relocate(&mut s, &dir.path("trip"), &now); + + // (the one in the trash is not looked for, but restoring it must find its file) + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64()), (Some(2), Some(1)), "{r}"); + assert_eq!(files(&s), [dir.path("archive/journey/a.png"), dir.path("archive/journey/day1/b.png")]); +} + +#[test] +fn the_folders_colour_labels_follow() { + let dir = Scratch::new("labels"); + let mut s = library(&dir); + s.execute("folder.label", &json!({"path": dir.path("trip"), "label": "red"})).unwrap(); + s.execute("folder.label", &json!({"path": dir.path("trip/day1"), "label": "blue"})).unwrap(); + let now = moved_away(&dir); + + relocate(&mut s, &dir.path("trip"), &now); + + assert_eq!(s.catalog.folder_color_label(&now), Some(ColorLabel::Red)); + assert_eq!(s.catalog.folder_color_label(&dir.path("archive/journey/day1")), Some(ColorLabel::Blue)); + assert_eq!(s.catalog.folder_color_label(&dir.path("trip")), None, "nothing is left at the old place"); + s.undo_step().unwrap(); + assert_eq!(s.catalog.folder_color_label(&dir.path("trip")), Some(ColorLabel::Red), "undo brings the labels back with the photos"); + assert_eq!(s.catalog.folder_color_label(&now), None); +} + +#[test] +fn the_folder_being_shown_follows_and_comes_back_on_undo() { + let dir = Scratch::new("shown"); + let mut s = library(&dir); + s.execute("library.source", &json!({"kind": "libraryFolder", "path": dir.path("trip/day1")})).unwrap(); + let now = moved_away(&dir); + + relocate(&mut s, &dir.path("trip"), &now); + assert_eq!(s.library_folder.as_deref(), Some(dir.path("archive/journey/day1").as_str())); + assert_eq!(s.visible().len(), 1, "its photo is still the one shown"); + + s.undo_step().unwrap(); + assert_eq!(s.library_folder.as_deref(), Some(dir.path("trip/day1").as_str())); + s.redo_step().unwrap(); + assert_eq!(s.library_folder.as_deref(), Some(dir.path("archive/journey/day1").as_str())); +} + +#[test] +fn the_filter_set_aside_by_enable_filters_follows_too() { + let dir = Scratch::new("shelved"); + let mut s = library(&dir); + let before = Filter { library_folder: Some(dir.path("trip/day1")), ..Default::default() }; + s.shelved_filter = Some(before); + let now = moved_away(&dir); + + relocate(&mut s, &dir.path("trip"), &now); + let shelved = |s: &Session| s.shelved_filter.as_ref().and_then(|f| f.library_folder.clone()); + assert_eq!(shelved(&s), Some(dir.path("archive/journey/day1"))); + + s.undo_step().unwrap(); + assert_eq!(shelved(&s), Some(dir.path("trip/day1"))); +} + +/// A folder named with a space at its edge is that folder, not the one without the space. +#[cfg(unix)] +#[test] +fn names_with_spaces_at_their_edge_are_not_trimmed() { + let dir = Scratch::new("edge-space"); + write_png(&dir.path("trip /a.png"), 1); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("trip ")]})).unwrap(); + std::fs::rename(dir.0.join("trip "), dir.0.join("moved ")).unwrap(); + + let r = relocate(&mut s, &dir.path("trip "), &dir.path("moved ")); + + assert_eq!(r["relinked"].as_u64(), Some(1), "{r}"); + assert_eq!(files(&s), [dir.path("moved /a.png")]); +} + +#[test] +fn a_folder_that_holds_none_of_the_photos_is_refused() { + let dir = Scratch::new("none"); + let mut s = library(&dir); + moved_away(&dir); + // one level too high: the files are in `archive/journey`, not in `archive` + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": dir.path("archive")})); + assert!(e.contains("none of the 2 files"), "{e}"); + // and saying "anyway" does not make it the folder + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": dir.path("archive"), "incomplete": true})); + assert!(e.contains("none of the 2 files"), "{e}"); +} + +#[test] +fn a_folder_that_holds_only_some_is_located_only_on_request() { + let dir = Scratch::new("some"); + let mut s = library(&dir); + let now = moved_away(&dir); + std::fs::remove_file(Path::new(&now).join("a.png")).unwrap(); + + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": now})); + assert!(e.contains("1 of the 2 files") && e.contains("incomplete: true"), "{e}"); + + let r = update_location(&mut s, &json!({"folder": dir.path("trip"), "path": now, "incomplete": true})).unwrap(); + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64(), r["notFound"].as_u64()), (Some(2), Some(1), Some(1)), "{r}"); + // the one that isn't there is missing at the new place, where Synchronize Folder finds it + let missing = s.execute("library.missing", &json!({})).unwrap(); + assert_eq!(missing.as_array().unwrap().len(), 1); + assert_eq!(missing[0]["path"], json!(dir.path("archive/journey/a.png"))); +} + +#[test] +fn a_folder_whose_files_the_library_already_has_is_refused() { + let dir = Scratch::new("taken"); + let mut s = library(&dir); + write_png(&dir.path("copy/a.png"), 3); + write_png(&dir.path("copy/day1/b.png"), 4); + s.execute("library.import", &json!({"paths": [dir.path("copy")]})).unwrap(); + assert_eq!(s.catalog.len(), 4); + std::fs::remove_dir_all(dir.0.join("trip")).unwrap(); + + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": dir.path("copy")})); + assert!(e.contains("already in the library"), "{e}"); +} + +#[test] +fn only_a_missing_or_moved_library_folder_and_a_real_folder_are_taken() { + let dir = Scratch::new("refusals"); + let mut s = library(&dir); + let trip = dir.path("trip"); + std::fs::create_dir_all(dir.0.join("empty")).unwrap(); + + for (params, why) in [ + (json!({"folder": trip, "path": trip}), "already looks"), + (json!({"folder": trip, "path": format!("{trip}{}", std::path::MAIN_SEPARATOR)}), "already looks"), + (json!({"folder": trip, "path": dir.path("nowhere")}), "is not a folder"), + (json!({"folder": trip, "path": dir.path("trip/a.png")}), "is not a folder"), + (json!({"folder": dir.path("empty"), "path": trip}), "no photo in the library"), + (json!({"folder": "/", "path": trip}), "startup disk"), + ] { + let e = refused(&mut s, params.clone()); + assert!(e.contains(why), "{params}: {e}"); + } +} + +#[test] +fn the_librarys_own_folder_is_no_place_for_photos() { + let dir = Scratch::new("own"); + write_png(&dir.path("trip/a.png"), 1); + let lib = dir.path("lib"); + let mut s = Session::new().with_fs(); + s.open_library(Path::new(&lib), false).unwrap(); + s.execute("library.import", &json!({"paths": [dir.path("trip")]})).unwrap(); + std::fs::create_dir_all(dir.0.join("lib/inside")).unwrap(); + + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": dir.path("lib/inside")})); + assert!(e.contains("library's own"), "{e}"); +} + +#[test] +fn the_plan_names_each_file_once_and_the_count_can_be_stopped() { + let dir = Scratch::new("count"); + let mut s = library(&dir); + // a virtual copy shares its photo's file: one file to look for + let id = s.catalog.photos().find(|p| p.file_name == "a.png").map(|p| p.id).unwrap(); + s.execute("photo.virtualCopy", &json!({"ids": [id.0]})).unwrap(); + let now = moved_away(&dir); + + let plan = Relocation::new(&s, &dir.path("trip"), &now, false).unwrap(); + assert_eq!(plan.files().len(), 2, "{:?}", plan.files()); + let progress = crate::import::ScanProgress::default(); + assert_eq!(look_at(plan.files(), &Default::default(), &progress).found, 2); + assert_eq!((progress.done.load(Ordering::Relaxed), progress.total.load(Ordering::Relaxed)), (2, 2)); + + // ✕ on its row in the activity stack + let stopped = crate::import::ScanProgress::default(); + stopped.cancel.store(true, Ordering::Relaxed); + assert_eq!(look_at(plan.files(), &Default::default(), &stopped).found, 0, "nothing more is looked for"); + + let r = relocate(&mut s, &dir.path("trip"), &now); + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64()), (Some(3), Some(2)), "the copy follows its photo: {r}"); + assert!(s.catalog.photo(PhotoId(id.0)).is_some()); +} + +#[test] +fn hostile_parameters_are_refused_not_crashed_on() { + let dir = Scratch::new("hostile"); + let mut s = library(&dir); + for params in [ + json!({"folder": "", "path": ""}), + json!({"folder": "..", "path": "."}), + json!({"folder": dir.path("trip"), "path": "\0"}), + json!({"folder": "\\\\?\\", "path": dir.path("trip"), "disk": true}), + ] { + refused(&mut s, params); + } +} + +#[test] +fn a_new_place_already_browsed_in_local_does_not_bring_its_files_in_twice() { + let dir = Scratch::new("browsed"); + let mut s = library(&dir); + let now = moved_away(&dir); + // looking for the photos, the person browsed the folder where they are now + s.execute("library.browse", &json!({"path": now})).unwrap(); + s.execute("library.browse", &json!({"path": dir.path("archive/journey/day1")})).unwrap(); + let records = s.catalog.len(); + assert!(records > 2, "browsing catalogued the files as Local records"); + + let r = relocate(&mut s, &dir.path("trip"), &now); + assert_eq!(r["relinked"], json!(2), "{r}"); + + let scan = s.execute("folder.scanChanges", &json!({"path": now})).unwrap(); + assert!(scan["new"].as_array().unwrap().is_empty(), "the library's photos are these files: {scan}"); + assert_eq!(s.catalog.photos().filter(|p| p.in_library()).count(), 2); +} + +#[test] +fn undo_brings_the_local_records_back_and_work_done_while_browsing_is_not_given_up() { + let dir = Scratch::new("browsed-undo"); + let mut s = library(&dir); + let now = moved_away(&dir); + s.execute("library.browse", &json!({"path": now})).unwrap(); + let records = s.catalog.len(); + let local = s.catalog.photos().find(|p| p.local).map(|p| p.id).unwrap(); + // the photo being looked at in Local is one of those that give way + s.execute("library.select", &json!({"ids": [local.0]})).unwrap(); + + let r = relocate(&mut s, &dir.path("trip"), &now); + assert_eq!(r["replacedLocal"], json!(records - 2), "{r}"); + assert!(s.catalog.photo(local).is_none()); + assert!(s.selection.ids.iter().all(|id| s.catalog.photo(*id).is_some()), "nothing that is gone stays selected"); + s.undo_step().unwrap(); + assert_eq!(s.catalog.len(), records, "undo brings the Local records back"); + assert_eq!(files(&s).iter().filter(|f| f.starts_with(&dir.path("trip"))).count(), 2); + + // a rating given while browsing is the person's work: the library's photo can't replace it + s.execute("library.select", &json!({"ids": [local.0]})).unwrap(); + s.execute("photo.rate", &json!({"rating": 4})).unwrap(); + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": now})); + assert!(e.contains("while browsing it in Local"), "{e}"); +} + +#[test] +fn what_was_found_is_not_applied_to_a_library_opened_meanwhile() { + let dir = Scratch::new("switched"); + let mut s = library(&dir); + let now = moved_away(&dir); + let located = Relocation::new(&s, &dir.path("trip"), &now, false).unwrap().look(&crate::import::ScanProgress::default()).unwrap(); + // File › Open Library while the files were looked for: its photo ids mean other photos + s.library_identity = std::sync::Arc::new(()); + let (before, steps) = (files(&s), s.undo.len()); + + let e = located.commit(&mut s, false).unwrap_err().to_string(); + + assert!(e.contains("another library"), "{e}"); + assert_eq!(files(&s), before, "nothing landed in the other library"); + assert_eq!(s.undo.len(), steps); +} + +#[test] +fn a_photo_relinked_while_the_files_were_looked_for_is_left_where_it_is() { + let dir = Scratch::new("meanwhile"); + let mut s = library(&dir); + let now = moved_away(&dir); + let located = Relocation::new(&s, &dir.path("trip"), &now, false).unwrap().look(&crate::import::ScanProgress::default()).unwrap(); + // meanwhile the person located one photo by hand, somewhere else + write_png(&dir.path("elsewhere/a.png"), 1); + let id = s.catalog.photos().find(|p| p.file_name == "a.png").map(|p| p.id).unwrap(); + s.execute("photo.relink", &json!({"id": id.0, "path": dir.path("elsewhere/a.png")})).unwrap(); + + let r = located.commit(&mut s, false).unwrap(); + + assert_eq!(r["relinked"], json!(1), "{r}"); + assert_eq!(files(&s), [dir.path("archive/journey/day1/b.png"), dir.path("elsewhere/a.png")], "its own choice stands"); +} + +/// What `look` found for `trip` → `to`, the files not yet relinked. +fn looked(s: &Session, dir: &Scratch, to: &str) -> crate::relocate::Located { + Relocation::new(s, &dir.path("trip"), to, false).unwrap().look(&crate::import::ScanProgress::default()).unwrap() +} + +#[test] +fn a_new_place_browsed_while_the_files_were_looked_for_still_has_one_record_per_file() { + let dir = Scratch::new("browsed-meanwhile"); + let mut s = library(&dir); + let now = moved_away(&dir); + let located = looked(&s, &dir, &now); + // meanwhile the person clicked the folder in Local + s.execute("library.browse", &json!({"path": now})).unwrap(); + let local = s.catalog.photos().filter(|p| p.local).count(); + assert!(local > 0); + + let r = located.commit(&mut s, false).unwrap(); + + assert_eq!(r["replacedLocal"], json!(local), "{r}"); + let mut seen = std::collections::HashSet::new(); + assert!(files(&s).into_iter().all(|f| seen.insert(f)), "one record per file: {:?}", files(&s)); +} + +#[test] +fn a_file_that_became_another_photos_while_the_files_were_looked_for_is_not_shared() { + let dir = Scratch::new("taken-meanwhile"); + let mut s = library(&dir); + write_png(&dir.path("other/x.png"), 9); + s.execute("library.import", &json!({"paths": [dir.path("other")]})).unwrap(); + let now = moved_away(&dir); + let located = looked(&s, &dir, &now); + // meanwhile another photo was pointed at one of the files + let other = s.catalog.photos().find(|p| p.file_name == "x.png").map(|p| p.id).unwrap(); + s.execute("photo.relink", &json!({"id": other.0, "path": dir.path("archive/journey/a.png")})).unwrap(); + let (before, steps) = (files(&s), s.undo.len()); + + let e = located.commit(&mut s, false).unwrap_err().to_string(); + + assert!(e.contains("already in the library"), "{e}"); + assert_eq!((files(&s), s.undo.len()), (before, steps), "nothing changed"); +} + +#[test] +fn a_browsed_record_in_recently_deleted_at_the_new_place_is_not_doubled() { + let dir = Scratch::new("local-trash"); + let mut s = library(&dir); + let now = moved_away(&dir); + s.execute("library.browse", &json!({"path": now})).unwrap(); + let local = s.catalog.photos().find(|p| p.local).map(|p| p.id).unwrap(); + s.catalog.apply(Op::SetDeleted { id: local, deleted: true }).unwrap(); + + // restoring it later would make a second photo of the file + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": now})); + assert!(e.contains("Recently Deleted included"), "{e}"); +} + +/// A library that also holds `archive/journey/phone/p.png` (labelled red), with the files of +/// `trip` moved into `archive/journey` behind its back. +fn moved_into_a_folder_of_the_library(dir: &Scratch) -> (Session, String) { + let mut s = library(dir); + write_png(&dir.path("archive/journey/phone/p.png"), 7); + s.execute("library.import", &json!({"paths": [dir.path("archive/journey/phone")]})).unwrap(); + s.execute("folder.label", &json!({"path": dir.path("archive/journey/phone"), "label": "red"})).unwrap(); + std::fs::rename(dir.0.join("trip/a.png"), dir.0.join("archive/journey/a.png")).unwrap(); + std::fs::rename(dir.0.join("trip/day1"), dir.0.join("archive/journey/day1")).unwrap(); + std::fs::remove_dir(dir.0.join("trip")).unwrap(); + (s, dir.path("archive/journey")) +} + +#[test] +fn folders_of_the_library_already_at_the_new_place_keep_their_labels() { + let dir = Scratch::new("labels-there"); + let (mut s, now) = moved_into_a_folder_of_the_library(&dir); + s.execute("folder.label", &json!({"path": dir.path("trip/day1"), "label": "blue"})).unwrap(); + + let r = relocate(&mut s, &dir.path("trip"), &now); + + assert_eq!(r["relinked"], json!(2), "{r}"); + assert_eq!(s.catalog.folder_color_label(&dir.path("archive/journey/phone")), Some(ColorLabel::Red), "it was there all along"); + assert_eq!(s.catalog.folder_color_label(&dir.path("archive/journey/day1")), Some(ColorLabel::Blue), "and the located one's came along"); + s.undo_step().unwrap(); + assert_eq!(s.catalog.folder_color_label(&dir.path("archive/journey/phone")), Some(ColorLabel::Red)); + assert_eq!(s.catalog.folder_color_label(&dir.path("trip/day1")), Some(ColorLabel::Blue)); +} + +#[test] +fn undo_leaves_a_view_that_did_not_move_where_it_is() { + let dir = Scratch::new("view-stays"); + let (mut s, now) = moved_into_a_folder_of_the_library(&dir); + relocate(&mut s, &dir.path("trip"), &now); + // a folder of the library that was at the new place all along, chosen since + let phone = dir.path("archive/journey/phone"); + s.execute("library.source", &json!({"kind": "libraryFolder", "path": phone})).unwrap(); + s.undo_step().unwrap(); + assert_eq!(s.library_folder.as_deref(), Some(phone.as_str()), "its photos never moved"); + s.redo_step().unwrap(); + assert_eq!(s.library_folder.as_deref(), Some(phone.as_str())); + + // and a folder browsed in Local is a place on disk + s.execute("library.browse", &json!({"path": dir.path("archive/journey/day1")})).unwrap(); + let browsed = s.browse.as_ref().map(|b| b.path.clone()); + assert!(browsed.is_some()); + s.undo_step().unwrap(); + assert_eq!(s.browse.as_ref().map(|b| b.path.clone()), browsed, "the folder on disk is where it was"); +} + +#[test] +fn a_folder_whose_files_went_into_a_folder_inside_it_is_located_there() { + let dir = Scratch::new("inside"); + let mut s = library(&dir); + // everything in `trip` was put into `trip/2019` + std::fs::create_dir_all(dir.0.join("2019")).unwrap(); + std::fs::rename(dir.0.join("trip/a.png"), dir.0.join("2019/a.png")).unwrap(); + std::fs::rename(dir.0.join("trip/day1"), dir.0.join("2019/day1")).unwrap(); + std::fs::rename(dir.0.join("2019"), dir.0.join("trip/2019")).unwrap(); + + let r = relocate(&mut s, &dir.path("trip"), &dir.path("trip/2019")); + + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64()), (Some(2), Some(2)), "{r}"); + assert_eq!(files(&s), [dir.path("trip/2019/a.png"), dir.path("trip/2019/day1/b.png")]); + s.undo_step().unwrap(); + assert_eq!(files(&s), [dir.path("trip/a.png"), dir.path("trip/day1/b.png")]); +} + +// ── Is the file there the photo's? (review of #1122) ───────────────────────────────────────── +// +// * A file being at the new place does not make it the photo's. A place that is, as the library +// has it, another photo's file of the same folder (the new place is inside the folder, or the +// folder inside it) is taken only when the file's content is the photo's; "anyway" does not +// cover it, and neither does a library that recorded no sizes or contents. +// * A file of another size than the library recorded is not counted as found: it is said, and +// taken only on request. A folder where no file is the library's is not the folder. + +/// A library holding `a/x.png` and `a/b/x.png`: the same name one level apart. +fn same_name_one_level_apart(dir: &Scratch) -> Session { + write_png(&dir.path("a/x.png"), 1); + write_png(&dir.path("a/b/x.png"), 2); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("a")]})).unwrap(); + assert_eq!(s.catalog.len(), 2); + s +} + +/// As a catalog from another app leaves its photos: no size and no content recorded. +fn forget_sizes_and_contents(s: &mut Session) { + let ops: Vec = s + .catalog + .photos() + // (a record of having looked in Local stays as browsing left it: untouched) + .filter(|p| !p.local) + .map(|p| Op::SetContent { + id: p.id, + width: p.width, + height: p.height, + file_size: 0, + content_hash: None, + preview_only: None, + preview_checked: String::new(), + }) + .collect(); + s.commit("Forget", Op::Batch { ops }).unwrap(); +} + +#[test] +fn a_place_inside_the_folder_never_gives_a_photo_another_photos_file() { + let dir = Scratch::new("nested"); + let mut s = same_name_one_level_apart(&dir); + // one level too low: `a/b/x.png` is the other photo's file, and nothing moved + for incomplete in [false, true] { + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": incomplete})); + assert!(e.contains("other photos of this folder") && e.contains(dir.path("a/b/x.png").as_str()), "incomplete {incomplete}: {e}"); + } +} + +#[test] +fn nor_when_the_library_recorded_no_size_and_no_content() { + let dir = Scratch::new("nested-blind"); + let mut s = same_name_one_level_apart(&dir); + forget_sizes_and_contents(&mut s); + for incomplete in [false, true] { + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": incomplete})); + assert!(e.contains("other photos of this folder"), "incomplete {incomplete}: {e}"); + } +} + +#[test] +fn nor_a_photo_in_recently_deleted() { + let dir = Scratch::new("nested-deleted"); + let mut s = same_name_one_level_apart(&dir); + write_png(&dir.path("a/k.png"), 3); + s.execute("library.import", &json!({"paths": [dir.path("a/k.png")]})).unwrap(); + let upper = s.catalog.photos().find(|p| matches!(&p.source, Source::File { path } if *path == dir.path("a/x.png"))).map(|p| p.id).unwrap(); + s.execute("photo.delete", &json!({"ids": [upper.0]})).unwrap(); + // `k.png` is in `a/b` too, so one of the library's two files is found there + std::fs::copy(dir.path("a/k.png"), dir.path("a/b/k.png")).unwrap(); + + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "restoring it would show the other photo's file: {e}"); +} + +#[test] +fn files_that_did_go_one_level_down_are_told_by_their_content() { + let dir = Scratch::new("shifted"); + let mut s = same_name_one_level_apart(&dir); + let upper = s.catalog.photos().find(|p| matches!(&p.source, Source::File { path } if *path == dir.path("a/x.png"))).map(|p| p.id).unwrap(); + // everything in `a` was put into `a/b`: `a/b/x.png` went to `a/b/b/x.png`, `a/x.png` to `a/b/x.png` + std::fs::create_dir_all(dir.0.join("a/b/b")).unwrap(); + std::fs::rename(dir.0.join("a/b/x.png"), dir.0.join("a/b/b/x.png")).unwrap(); + std::fs::rename(dir.0.join("a/x.png"), dir.0.join("a/b/x.png")).unwrap(); + + let r = relocate(&mut s, &dir.path("a"), &dir.path("a/b")); + + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64(), r["notFound"].as_u64()), (Some(2), Some(2), Some(0)), "{r}"); + assert!(matches!(&s.catalog.photo(upper).unwrap().source, Source::File { path } if *path == dir.path("a/b/x.png"))); + assert!(s.execute("library.missing", &json!({})).unwrap().as_array().unwrap().is_empty()); + + // without contents recorded nothing tells the two apart: refused rather than guessed + s.undo_step().unwrap(); + forget_sizes_and_contents(&mut s); + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b")})); + assert!(e.contains("other photos of this folder"), "{e}"); +} + +/// Another picture under the same name (not the size the library recorded). +fn write_other(path: &str) { + let (w, h) = (40usize, 30usize); + let data: Vec<[u8; 4]> = (0..w * h).map(|i| [(i * 7) as u8, (i * 3) as u8, (i / 5) as u8, 255]).collect(); + let img = lightcraft_raster::Rgba8 { width: w, height: h, data }; + let bytes = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap(); + assert_ne!(bytes.len() as u64, std::fs::metadata(path).unwrap().len(), "the test needs another size"); + std::fs::write(path, bytes).unwrap(); +} + +#[test] +fn a_file_of_another_size_is_not_counted_as_found() { + let dir = Scratch::new("other-size"); + let mut s = library(&dir); + let now = moved_away(&dir); + write_other(&dir.path("archive/journey/a.png")); + + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": now})); + assert!( + e.contains("1 of the 2 files") && e.contains("1 file there is not the one the library recorded") && e.contains("incomplete: true"), + "{e}" + ); + + // on request it is taken: the file was changed where it lies, as files are + let r = update_location(&mut s, &json!({"folder": dir.path("trip"), "path": now, "incomplete": true})).unwrap(); + assert_eq!( + (r["relinked"].as_u64(), r["found"].as_u64(), r["different"].as_u64(), r["notFound"].as_u64()), + (Some(2), Some(1), Some(1), Some(0)), + "{r}" + ); +} + +#[test] +fn a_folder_where_no_file_is_the_librarys_is_not_the_folder() { + let dir = Scratch::new("other-disk"); + let mut s = library(&dir); + let now = moved_away(&dir); + // the same names in the same folders, other pictures: another disk laid out alike + write_other(&dir.path("archive/journey/a.png")); + write_other(&dir.path("archive/journey/day1/b.png")); + + for incomplete in [false, true] { + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": now, "incomplete": incomplete})); + assert!( + e.contains("none of the 2 files") && e.contains("2 files there are not the ones the library recorded"), + "incomplete {incomplete}: {e}" + ); + } +} + +#[test] +fn a_file_whose_size_the_library_never_recorded_is_taken_and_said() { + let dir = Scratch::new("no-size"); + let mut s = library(&dir); + forget_sizes_and_contents(&mut s); + let now = moved_away(&dir); + write_other(&dir.path("archive/journey/a.png")); + + let r = relocate(&mut s, &dir.path("trip"), &now); + + assert_eq!((r["found"].as_u64(), r["unverified"].as_u64(), r["different"].as_u64()), (Some(2), Some(2), Some(0)), "{r}"); +} + +// ── The same place under another spelling (second review) ──────────────────────────────────── +// +// * A place inside the folder is the same place however it is written: with `..`, in other +// letter case on a disk that doesn't tell case apart, or through a link. +// * The folder inside the chosen one is the same mistake the other way round. +// * A file only browsed in Local at the new place is not "another photo": its record gives way. +// * Looking that was stopped found nothing out. + +fn at(s: &Session, path: &str) -> PhotoId { + s.catalog.photos().find(|p| matches!(&p.source, Source::File { path: q } if q == path)).map(|p| p.id).unwrap() +} + +#[test] +#[cfg(unix)] +fn a_place_written_with_dot_dot_is_refused() { + let dir = Scratch::new("dotdot"); + let mut s = same_name_one_level_apart(&dir); + let to = format!("{}{sep}b{sep}..{sep}b", dir.path("a"), sep = std::path::MAIN_SEPARATOR); + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": to, "incomplete": true})); + assert!(e.contains("`..`"), "{e}"); +} + +#[test] +fn a_place_inside_the_folder_in_other_letter_case_is_the_same_place() { + let dir = Scratch::new("case"); + write_png(&dir.path("a/x.png"), 1); + write_png(&dir.path("a/B/x.png"), 2); + if !Path::new(&dir.path("a/b/x.png")).is_file() { + lightcraft_testkit::skip!(System, "this disk tells `B` from `b`, so `a/b` is no folder"); + return; + } + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("a")]})).unwrap(); + for blind in [false, true] { + if blind { + forget_sizes_and_contents(&mut s); + } + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "blind {blind}: {e}"); + } +} + +#[cfg(unix)] +#[test] +fn a_link_to_a_place_inside_the_folder_is_the_same_place() { + let dir = Scratch::new("link"); + let mut s = same_name_one_level_apart(&dir); + std::os::unix::fs::symlink(dir.path("a/b"), dir.path("link")).unwrap(); + for blind in [false, true] { + if blind { + forget_sizes_and_contents(&mut s); + } + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("link"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "blind {blind}: {e}"); + } +} + +#[cfg(unix)] +#[test] +fn a_link_to_the_folder_itself_gives_no_photo_another_photos_file() { + let dir = Scratch::new("link-self"); + let mut s = library(&dir); + forget_sizes_and_contents(&mut s); + std::os::unix::fs::symlink(dir.path("trip"), dir.path("link")).unwrap(); + // every file there is the photo's own, under another name + let r = relocate(&mut s, &dir.path("trip"), &dir.path("link")); + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64()), (Some(2), Some(2)), "{r}"); +} + +#[test] +fn the_folder_inside_the_chosen_one_is_the_same_mistake() { + let dir = Scratch::new("too-high"); + write_png(&dir.path("a/b/x.png"), 1); + write_png(&dir.path("a/b/b/x.png"), 2); + write_png(&dir.path("a/b/k.png"), 3); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("a/b")]})).unwrap(); + std::fs::copy(dir.path("a/b/k.png"), dir.path("a/k.png")).unwrap(); + forget_sizes_and_contents(&mut s); + // one level too high: `a/b/x.png` would be taken for the photo of `a/b/b/x.png` + let e = refused(&mut s, json!({"folder": dir.path("a/b"), "path": dir.path("a"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "{e}"); +} + +#[test] +fn a_file_only_browsed_in_local_at_a_place_inside_the_folder_gives_way() { + let dir = Scratch::new("nested-local"); + write_png(&dir.path("a/x.png"), 1); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("a")]})).unwrap(); + let photo = at(&s, &dir.path("a/x.png")); + // the file went one level down, and the folder it is in now was looked at in Local + std::fs::create_dir_all(dir.0.join("a/b")).unwrap(); + std::fs::rename(dir.0.join("a/x.png"), dir.0.join("a/b/x.png")).unwrap(); + s.execute("library.browse", &json!({"path": dir.path("a/b")})).unwrap(); + assert_eq!(s.catalog.len(), 2, "the library's photo and the record of having looked"); + + for blind in [false, true] { + if blind { + s.undo_step().unwrap(); + forget_sizes_and_contents(&mut s); + } + let r = relocate(&mut s, &dir.path("a"), &dir.path("a/b")); + assert_eq!((r["relinked"].as_u64(), r["found"].as_u64(), r["replacedLocal"].as_u64()), (Some(1), Some(1), Some(1)), "blind {blind}: {r}"); + assert_eq!(files(&s), [dir.path("a/b/x.png")], "one record for the one file"); + assert!(s.catalog.photo(photo).is_some_and(|p| p.in_library())); + } +} + +#[test] +fn a_claimed_file_of_another_size_than_the_photos_is_not_read_to_be_refused() { + let dir = Scratch::new("claimed-size"); + let mut s = same_name_one_level_apart(&dir); + write_other(&dir.path("a/b/x.png")); + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "{e}"); +} + +#[test] +fn looking_that_was_stopped_found_nothing_out() { + let dir = Scratch::new("stopped"); + let s = library(&dir); + let now = moved_away(&dir); + let stopped = crate::import::ScanProgress::default(); + stopped.cancel.store(true, Ordering::Relaxed); + let e = Relocation::new(&s, &dir.path("trip"), &now, false).unwrap().look(&stopped).unwrap_err(); + assert!(e.contains("stopped"), "{e}"); +} + +#[test] +fn a_files_content_read_in_pieces_is_the_content_import_recorded() { + let bytes: Vec = (0..300_000u32).map(|i| (i.wrapping_mul(2_654_435_761) >> 13) as u8).collect(); + let pieces = crate::cmd::missing::hash_reader(&bytes[..]).unwrap(); + assert_eq!(pieces, lightcraft_preview::hash_bytes(&bytes).to_string()); +} + +// ── Third review: files shared below the two folders, and a browsed file that is another picture ─ + +#[cfg(unix)] +#[test] +fn a_link_inside_the_folder_to_the_chosen_place_is_seen() { + let dir = Scratch::new("link-below-from"); + write_png(&dir.path("big/2023/x.png"), 2); + write_png(&dir.path("pics/x.png"), 1); + std::os::unix::fs::symlink(dir.path("big/2023"), dir.path("pics/2023")).unwrap(); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("pics/x.png"), dir.path("pics/2023/x.png")]})).unwrap(); + assert_eq!(s.catalog.len(), 2); + for blind in [false, true] { + if blind { + forget_sizes_and_contents(&mut s); + } + // `big/2023/x.png` is the file of the photo at `pics/2023/x.png` + let e = refused(&mut s, json!({"folder": dir.path("pics"), "path": dir.path("big/2023"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "blind {blind}: {e}"); + } +} + +#[cfg(unix)] +#[test] +fn a_link_inside_the_chosen_place_back_to_the_folder_is_seen() { + let dir = Scratch::new("link-below-to"); + let mut s = Session::new().with_fs(); + write_png(&dir.path("a/x.png"), 1); + write_png(&dir.path("a/sub/x.png"), 2); + s.execute("library.import", &json!({"paths": [dir.path("a")]})).unwrap(); + std::fs::create_dir_all(dir.0.join("new")).unwrap(); + std::fs::copy(dir.path("a/x.png"), dir.path("new/x.png")).unwrap(); + std::os::unix::fs::symlink(dir.path("a"), dir.path("new/sub")).unwrap(); + for blind in [false, true] { + if blind { + forget_sizes_and_contents(&mut s); + } + // `new/sub/x.png` is `a/x.png`: the other photo's file + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("new"), "incomplete": true})); + assert!(e.contains("other photos of this folder"), "blind {blind}: {e}"); + } +} + +#[test] +fn a_browsed_file_inside_the_folder_that_is_another_picture_is_not_taken_for_the_photo() { + let dir = Scratch::new("nested-local-other"); + write_png(&dir.path("a/x.png"), 1); + let mut s = Session::new().with_fs(); + s.execute("library.import", &json!({"paths": [dir.path("a")]})).unwrap(); + // nothing moved: one level down lies another picture of the same name (and size), looked at in Local + write_png(&dir.path("a/b/x.png"), 2); + s.execute("library.browse", &json!({"path": dir.path("a/b")})).unwrap(); + + let e = refused(&mut s, json!({"folder": dir.path("a"), "path": dir.path("a/b"), "incomplete": true})); + assert!(e.contains("another picture than the library recorded"), "{e}"); +} + +#[test] +#[cfg(unix)] +fn a_relative_place_with_dot_dot_is_told_to_be_written_in_full() { + let dir = Scratch::new("dotdot-relative"); + // (Windows resolves `..` itself when it makes the path absolute: unix only, like the other `..` test) + let mut s = library(&dir); + let e = refused(&mut s, json!({"folder": dir.path("trip"), "path": ".."})); + assert!(e.contains("full path"), "{e}"); +}