mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-30 18:24:40 +01:00
Merge pull request #2419 from nledford/perf-import-sidecars
PERF-SIDECARS: imports and moves answer sidecar lookups from the folder listing
This commit is contained in:
23 files changed
+1190
-36
No files matched your search
@@ -47,6 +47,8 @@ mod types;
|
||||
pub(crate) use commit::workers;
|
||||
pub use commit::{batch_size, civil, commit_prepared, system_clock};
|
||||
pub use defaults::{CameraDefault, ImportDefaults, apply_import_defaults, has_import_look, import_defaults};
|
||||
#[cfg(test)]
|
||||
use files::expand_knowing;
|
||||
pub use files::{
|
||||
EXTENSIONS, Expansion, LAUNCH_PROBE_LIMIT, LaunchPath, accept_list, expand, expand_report, expand_within, is_supported, launch_deadline,
|
||||
launch_path, launch_path_until,
|
||||
@@ -68,6 +70,13 @@ pub use types::{
|
||||
OnDeleted, Organize,
|
||||
};
|
||||
|
||||
mod listed_folders;
|
||||
pub use listed_folders::ListedFolders;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "import/tests_listed_folders.rs"]
|
||||
mod tests_listed_folders;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "import/tests_known.rs"]
|
||||
mod tests_known;
|
||||
|
||||
@@ -114,14 +114,42 @@ pub fn expand_report(paths: &[String], skip: Option<&Path>, limits: crate::walk:
|
||||
|
||||
/// ([`expand_report`], handing the listing of every folder that is walked to `note`, as
|
||||
/// [`expand_noting`] does.)
|
||||
fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits, mut note: Option<crate::walk::NoteFolder>) -> Expansion {
|
||||
fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::walk::Limits, note: Option<crate::walk::NoteFolder>) -> Expansion {
|
||||
expand_report_knowing(paths, skip, limits, note, false, &|_| false)
|
||||
}
|
||||
|
||||
/// [`expand_noting`], taking the paths `known_file` says are files as files without asking the
|
||||
/// disk (a review hands over thousands of them, and telling a file from a folder is a round trip
|
||||
/// each on a network share). With `timed`, each folder's modification time goes to `note` too
|
||||
/// ([`crate::walk::files_in_noting_timed`]).
|
||||
pub(super) fn expand_knowing(
|
||||
paths: &[String],
|
||||
skip: Option<&Path>,
|
||||
limits: crate::walk::Limits,
|
||||
note: Option<crate::walk::NoteFolder>,
|
||||
timed: bool,
|
||||
known_file: &dyn Fn(&Path) -> bool,
|
||||
) -> (Vec<String>, bool) {
|
||||
let e = expand_report_knowing(paths, skip, limits, note, timed, known_file);
|
||||
(e.files, e.truncated)
|
||||
}
|
||||
|
||||
/// [`expand_knowing`] keeping the walks' diagnostics ([`Expansion`]).
|
||||
pub(super) fn expand_report_knowing(
|
||||
paths: &[String],
|
||||
skip: Option<&Path>,
|
||||
limits: crate::walk::Limits,
|
||||
mut note: Option<crate::walk::NoteFolder>,
|
||||
timed: bool,
|
||||
known_file: &dyn Fn(&Path) -> bool,
|
||||
) -> Expansion {
|
||||
let mut out = Expansion::default();
|
||||
for p in paths {
|
||||
let p = Path::new(p);
|
||||
if skip.is_some_and(|s| p == s) {
|
||||
continue;
|
||||
}
|
||||
if p.is_dir() {
|
||||
if !known_file(p) && p.is_dir() {
|
||||
// XMP sidecars are read with their photos, not skipped: they are left out of the count
|
||||
let mut sidecars = 0usize;
|
||||
let keep = |f: &Path| {
|
||||
@@ -132,6 +160,7 @@ fn expand_report_noting(paths: &[String], skip: Option<&Path>, limits: crate::wa
|
||||
keep
|
||||
};
|
||||
let w = match note.as_mut() {
|
||||
Some(note) if timed => crate::walk::files_in_noting_timed(p, skip, limits, keep, &mut **note),
|
||||
Some(note) => crate::walk::files_in_noting(p, skip, limits, keep, &mut **note),
|
||||
None => crate::walk::files_in(p, skip, limits, keep),
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use super::commit::{How, Plan, Slot, Transfer, commit_prepared, name_family, run_transfers, system_clock};
|
||||
use super::files::{Seen, expand, probe_all, reusable_probes, sidecars_of};
|
||||
use super::files::{Seen, expand_knowing, probe_all, reusable_probes, sidecars_of};
|
||||
use super::types::{FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, Kept, OnDeleted};
|
||||
use super::{HashMap, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source};
|
||||
use super::{HashMap, ListedFolders, MediaKind, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source};
|
||||
|
||||
/// Import files/folders. See the module docs.
|
||||
pub fn import(s: &mut Session, paths: &[String], mode: ImportMode) -> crate::Result<ImportReport> {
|
||||
@@ -45,7 +45,9 @@ pub struct ImportJob {
|
||||
file_bytes: Option<crate::merge::ByteReader>,
|
||||
/// Probes from a preceding scan (not read again).
|
||||
pub(super) cache: HashMap<String, ProbeInfo>,
|
||||
naming: crate::sidecar::SidecarNaming,
|
||||
pub(super) naming: crate::sidecar::SidecarNaming,
|
||||
/// The `.xmp` names in the folders [`ImportJob::expand`] listed.
|
||||
pub(super) listed: ListedFolders,
|
||||
now: String,
|
||||
/// Next rename number; `None` once the final representable value has been reserved.
|
||||
seq: Option<usize>,
|
||||
@@ -198,6 +200,7 @@ impl ImportJob {
|
||||
file_bytes: s.media.file_bytes.clone(),
|
||||
cache: std::mem::take(&mut s.import_probes),
|
||||
naming: s.xmp.naming,
|
||||
listed: ListedFolders::default(),
|
||||
now: (s.clock)(),
|
||||
total: Default::default(),
|
||||
done: Default::default(),
|
||||
@@ -215,10 +218,35 @@ impl ImportJob {
|
||||
self.prepare_files(files, cancel)
|
||||
}
|
||||
|
||||
/// Hand the job the folders the review that started it listed ([`ScanOutput::listed`]).
|
||||
#[must_use]
|
||||
pub fn with_listed(mut self, listed: ListedFolders) -> Self {
|
||||
self.listed = listed;
|
||||
self
|
||||
}
|
||||
|
||||
/// Expand `paths` (folders recursively, the library's own folder skipped) into the files an
|
||||
/// import would handle; counted in [`ImportJob::total`].
|
||||
pub fn expand(&self, paths: &[String]) -> Vec<String> {
|
||||
let files = expand(paths, self.lib_dir.as_deref());
|
||||
pub fn expand(&mut self, paths: &[String]) -> Vec<String> {
|
||||
// (a file the review listed is a file: no round trip to a share to ask)
|
||||
let mut listed = std::mem::take(&mut self.listed);
|
||||
let mut walked = ListedFolders::default();
|
||||
// (the folders' times are looked at now, not as an earlier batch found them)
|
||||
listed.new_batch();
|
||||
let (files, _) = expand_knowing(
|
||||
paths,
|
||||
self.lib_dir.as_deref(),
|
||||
crate::walk::Limits::default(),
|
||||
Some(&mut |dir, names, complete, modified| {
|
||||
walked.note(dir, names, complete, modified);
|
||||
true
|
||||
}),
|
||||
true,
|
||||
&|p| listed.is_known_file(p),
|
||||
);
|
||||
listed.absorb(walked);
|
||||
listed.forget_files();
|
||||
self.listed = listed;
|
||||
self.total.fetch_add(files.len(), std::sync::atomic::Ordering::Relaxed);
|
||||
files
|
||||
}
|
||||
@@ -254,6 +282,7 @@ impl ImportJob {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
// the library as it was, kept for the ownership of the shared stem sidecars below
|
||||
let library = self.look_up_library();
|
||||
self.listed.new_batch();
|
||||
let opts = self.opts.clone();
|
||||
let mode = self.mode;
|
||||
let mut out = Prepared { scanned: files.len(), items: Vec::new() };
|
||||
@@ -307,8 +336,7 @@ impl ImportJob {
|
||||
.map(|(f, _)| f.as_str())
|
||||
.collect();
|
||||
let mut found =
|
||||
sidecars_of(&asked, cancel, |f| if known.contains(f) { None } else { crate::sidecar::find_sidecar_for_import(&stems, self.naming, f) })
|
||||
.into_iter();
|
||||
sidecars_of(&asked, cancel, |f| if known.contains(f) { None } else { self.listed.find_for_import(&stems, self.naming, f) }).into_iter();
|
||||
// Files are planned one by one, in order (duplicates, sidecars, names, folders); their
|
||||
// copies or moves — the slow part, reading and writing every byte and verifying it — are
|
||||
// collected and run on several threads (issue #367), then their outcomes take their places.
|
||||
|
||||
@@ -0,0 +1,166 @@
|
||||
//! What an import (or the review before it) learned of the folders it listed: the files in them
|
||||
//! and the `.xmp` names.
|
||||
//!
|
||||
//! Looking for a photo's sidecar asks the disk about up to nine names ([`sidecar_candidates`]).
|
||||
//! On a network share a name that is not there costs a round trip as much as one that is, so a
|
||||
//! folder with no `.xmp` at all cost nine for each of its photos. Telling a file from a folder
|
||||
//! (`is_dir`) is a round trip too, for each of the thousands of files a review hands over. The
|
||||
//! listing that found those files already has both answers.
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::ffi::OsString;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use crate::sidecar::{SidecarNaming, find_sidecar, sidecar_candidates};
|
||||
use crate::walk::EntryKind;
|
||||
|
||||
/// One listed folder.
|
||||
#[derive(Debug, Default)]
|
||||
struct Folder {
|
||||
/// The names listed as files (links are not: the disk says where they lead).
|
||||
files: HashSet<String>,
|
||||
/// The `.xmp` names, lower-cased. Only for a folder that was listed completely, with plain
|
||||
/// ASCII names (the names a file system treats alike in other cases are the ones we can fold
|
||||
/// ourselves): for any other the disk decides, as before.
|
||||
xmp: Option<HashSet<String>>,
|
||||
/// The folder's modification time when it was listed: a file added, removed or replaced since
|
||||
/// changes it, and the `.xmp` and file names are then not trusted (a listing taken by a review
|
||||
/// can be hours old).
|
||||
modified: Option<SystemTime>,
|
||||
}
|
||||
|
||||
/// The folders listed so far (see the module docs). The review's scan hands its listing to the
|
||||
/// import that review starts ([`crate::import::ImportJob::with_listed`]), and nowhere else.
|
||||
/// The `.xmp` names and the file names of a folder are trusted only while its modification time
|
||||
/// is what it was when it was listed (looked at once per folder per batch: [`ListedFolders::new_batch`]); a
|
||||
/// volume whose folders keep no usable time (it can't be read) is probed as before.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ListedFolders {
|
||||
folders: HashMap<PathBuf, Folder>,
|
||||
/// folder → whether its time is still the listed one, for the batch being handled.
|
||||
checked: Mutex<HashMap<PathBuf, bool>>,
|
||||
/// How often the disk was asked after all about a sidecar (for the tests).
|
||||
pub(crate) asked: AtomicUsize,
|
||||
/// How many folders' times were looked at (for the tests).
|
||||
pub(crate) looked: AtomicUsize,
|
||||
/// The threads that looked a sidecar up for an import (for the tests: the lookups of a batch are
|
||||
/// not made one after another by the thread that plans it).
|
||||
#[cfg(test)]
|
||||
pub(crate) lookers: Mutex<HashSet<std::thread::ThreadId>>,
|
||||
}
|
||||
|
||||
impl ListedFolders {
|
||||
/// Take the listing of `folder` from the walk ([`crate::walk::files_in_noting`]), with the
|
||||
/// folder's time as the walk read it before listing (`None`: too recent to vouch for, or unreadable).
|
||||
pub(crate) fn note(&mut self, folder: &Path, entries: Vec<(OsString, EntryKind)>, complete: bool, modified: Option<SystemTime>) {
|
||||
let mut listed = Folder { modified, ..Default::default() };
|
||||
let mut xmp = (complete && listed.modified.is_some()).then(HashSet::new);
|
||||
for (name, kind) in entries {
|
||||
// (a name that is no text is not one a path can be compared with)
|
||||
let Some(name) = name.to_str() else {
|
||||
xmp = None;
|
||||
continue;
|
||||
};
|
||||
if let Some(set) = &mut xmp {
|
||||
if name.is_ascii() {
|
||||
let lower = name.to_ascii_lowercase();
|
||||
if lower.ends_with(".xmp") {
|
||||
set.insert(lower);
|
||||
}
|
||||
} else {
|
||||
// (not ours to say what another name's other case is)
|
||||
xmp = None;
|
||||
}
|
||||
}
|
||||
if kind == EntryKind::File && crate::import::is_supported(Path::new(name)) {
|
||||
listed.files.insert(name.to_string());
|
||||
}
|
||||
}
|
||||
listed.xmp = xmp;
|
||||
self.folders.insert(folder.to_path_buf(), listed);
|
||||
}
|
||||
|
||||
/// A new batch of files is handled: look at the folders' times again. A folder's time is looked at
|
||||
/// once per batch, by the first lookup in it (a look for each photo would cost the round trip each
|
||||
/// that the listing saves), so a sidecar added there while the batch is handled is not seen until
|
||||
/// the next batch.
|
||||
pub(crate) fn new_batch(&self) {
|
||||
self.checked.lock().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
}
|
||||
|
||||
/// The names of files are needed to take a path for a file (once the files are expanded, no more).
|
||||
pub(crate) fn forget_files(&mut self) {
|
||||
for f in self.folders.values_mut() {
|
||||
f.files = HashSet::new();
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `dir` is as it was listed.
|
||||
fn unchanged(&self, dir: &Path, listed: Option<SystemTime>) -> bool {
|
||||
// (no time to compare with: not trusted, and the disk is not asked)
|
||||
let Some(listed) = listed else { return false };
|
||||
let mut checked = self.checked.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if let Some(known) = checked.get(dir) {
|
||||
return *known;
|
||||
}
|
||||
self.looked.fetch_add(1, Ordering::Relaxed);
|
||||
let now = std::fs::metadata(dir).and_then(|m| m.modified()).ok();
|
||||
let same = now == Some(listed);
|
||||
checked.insert(dir.to_path_buf(), same);
|
||||
same
|
||||
}
|
||||
|
||||
/// Take over `walked`'s folders, which are newer than the ones held for them.
|
||||
pub(crate) fn absorb(&mut self, walked: ListedFolders) {
|
||||
self.folders.extend(walked.folders);
|
||||
}
|
||||
|
||||
/// Whether a listing says `path` is a file, as it was found: the disk need not be asked.
|
||||
/// Only while its folder is as it was listed (a file may have been replaced by a folder since;
|
||||
/// a folder with no usable time is never trusted).
|
||||
pub(crate) fn is_known_file(&self, path: &Path) -> bool {
|
||||
let (Some(dir), Some(name)) = (path.parent(), path.file_name().and_then(|n| n.to_str())) else { return false };
|
||||
// (the path ends in that name: no `/.` or separator after it, which the disk would resolve)
|
||||
path.to_str().is_some_and(|p| p.ends_with(name))
|
||||
&& self.folders.get(dir).is_some_and(|f| f.files.contains(name) && self.unchanged(dir, f.modified))
|
||||
}
|
||||
|
||||
/// Whether the listing of `original`'s folder shows that none of its sidecar names is there.
|
||||
/// `false` where it can't say: the folder was not listed (or not completely), or a name is
|
||||
/// one the disk may resolve another way.
|
||||
fn rules_out(&self, original: &str, naming: SidecarNaming) -> bool {
|
||||
let path = Path::new(original);
|
||||
let Some(dir) = path.parent() else { return false };
|
||||
let Some((xmp, modified)) = self.folders.get(dir).and_then(|f| Some((f.xmp.as_ref()?, f.modified))) else { return false };
|
||||
let Some(name) = path.file_name().and_then(|n| n.to_str()) else { return false };
|
||||
if !original.ends_with(name) || crate::sync::asks_the_disk(name) || !crate::sync::plain_name(name) || !self.unchanged(dir, modified) {
|
||||
return false;
|
||||
}
|
||||
sidecar_candidates(original, naming)
|
||||
.all(|c| c.file_name().and_then(|n| n.to_str()).is_some_and(|n| crate::sync::plain_name(n) && !xmp.contains(&n.to_ascii_lowercase())))
|
||||
}
|
||||
|
||||
/// [`crate::sidecar::find_sidecar_for_import`], without asking the disk where the listing shows
|
||||
/// there is none: a file that owns its stem sidecar ([`crate::sidecar::ImportStems`]) is looked
|
||||
/// up as [`ListedFolders::find`] does; one that doesn't reads only its own `<file>.xmp`.
|
||||
pub(crate) fn find_for_import(&self, stems: &crate::sidecar::ImportStems, naming: SidecarNaming, original: &str) -> Option<PathBuf> {
|
||||
#[cfg(test)]
|
||||
self.lookers.lock().unwrap_or_else(|e| e.into_inner()).insert(std::thread::current().id());
|
||||
if stems.owns(original) {
|
||||
return self.find(original, naming);
|
||||
}
|
||||
self.asked.fetch_add(1, Ordering::Relaxed);
|
||||
crate::sidecar::find_sidecar_for_import(stems, naming, original)
|
||||
}
|
||||
|
||||
/// [`find_sidecar`], without asking the disk where the listing shows there is none.
|
||||
pub(crate) fn find(&self, original: &str, naming: SidecarNaming) -> Option<PathBuf> {
|
||||
if self.rules_out(original, naming) {
|
||||
return None;
|
||||
}
|
||||
self.asked.fetch_add(1, Ordering::Relaxed);
|
||||
find_sidecar(original, naming)
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::files::{Seen, expand, expand_report, is_supported, probe_all, reusable_probes};
|
||||
use super::files::{Seen, expand, expand_report_knowing, is_supported, probe_all, reusable_probes};
|
||||
use super::types::ImportCandidate;
|
||||
use super::{HashMap, Path, PathBuf, PhotoId, ProbeInfo, Session, Source};
|
||||
use super::{HashMap, ListedFolders, Path, PathBuf, PhotoId, ProbeInfo, Session, Source};
|
||||
|
||||
/// What a [`scan`] needs from the session, so it can run on another thread (a folder on a network
|
||||
/// share can take minutes to read).
|
||||
@@ -12,6 +12,8 @@ pub struct ScanInput {
|
||||
/// ([`library_hashes`]), on the scan's thread.
|
||||
library: std::sync::Arc<lightcraft_catalog::Catalog>,
|
||||
cache: HashMap<String, ProbeInfo>,
|
||||
/// The folders the scan listed, for the import that follows.
|
||||
listed: ListedFolders,
|
||||
}
|
||||
|
||||
/// The library's photos of `files`: path → (photo, its summary as a candidate that is there
|
||||
@@ -83,6 +85,8 @@ pub struct ScanOutput {
|
||||
pub unreadable: usize,
|
||||
/// Files inside the folders that are not a supported photo type (XMP sidecars not counted).
|
||||
pub unsupported: usize,
|
||||
/// The folders the scan listed (kept with the probes, for the import that follows).
|
||||
pub listed: ListedFolders,
|
||||
}
|
||||
|
||||
impl ScanInput {
|
||||
@@ -91,7 +95,13 @@ impl ScanInput {
|
||||
// (no table of the library here: this is the session's thread, and the library may hold
|
||||
// millions of photos. The scan looks up what it finds)
|
||||
let library = std::sync::Arc::new(s.catalog.clone());
|
||||
let input = ScanInput { probe: s.media.file_probe.clone(), skip, library, cache: std::mem::take(&mut s.import_probes) };
|
||||
let input = ScanInput {
|
||||
probe: s.media.file_probe.clone(),
|
||||
skip,
|
||||
library,
|
||||
cache: std::mem::take(&mut s.import_probes),
|
||||
listed: ListedFolders::default(),
|
||||
};
|
||||
(input, paths.to_vec())
|
||||
}
|
||||
|
||||
@@ -303,8 +313,21 @@ pub fn scan_report(s: &mut Session, paths: &[String]) -> ScanOutput {
|
||||
|
||||
/// [`scan`] without the session, so it can run on a worker thread. Stops early (returning what it
|
||||
/// has) when `progress.cancel` is set.
|
||||
pub fn scan_with(input: ScanInput, paths: &[String], progress: &ScanProgress) -> ScanOutput {
|
||||
let expansion = expand_report(paths, input.skip.as_deref(), crate::walk::Limits::default());
|
||||
pub fn scan_with(mut input: ScanInput, paths: &[String], progress: &ScanProgress) -> ScanOutput {
|
||||
let listed = &mut input.listed;
|
||||
let expansion = expand_report_knowing(
|
||||
paths,
|
||||
input.skip.as_deref(),
|
||||
crate::walk::Limits::default(),
|
||||
// (always `true`: nothing here stops the walk. `progress.cancel` is read only once it is over, in
|
||||
// `scan_files`, which stops the probing and returns what it has)
|
||||
Some(&mut |dir, names, complete, modified| {
|
||||
listed.note(dir, names, complete, modified);
|
||||
true
|
||||
}),
|
||||
true,
|
||||
&|_| false,
|
||||
);
|
||||
let mut out = scan_files(input, expansion.files, progress);
|
||||
out.truncated = expansion.truncated;
|
||||
out.unreadable = expansion.unreadable;
|
||||
@@ -314,7 +337,7 @@ pub fn scan_with(input: ScanInput, paths: &[String], progress: &ScanProgress) ->
|
||||
|
||||
/// [`scan_with`] for files that were found already (`paths` expanded, [`expand`]). The walks'
|
||||
/// diagnostics ([`ScanOutput::truncated`] and friends) are left empty: who expanded the paths has
|
||||
/// them ([`expand_report`]).
|
||||
/// them ([`expand_report`](super::files::expand_report)).
|
||||
pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &ScanProgress) -> ScanOutput {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
let by_path = library_files(&input.library, &files);
|
||||
@@ -376,5 +399,5 @@ pub(crate) fn scan_files(mut input: ScanInput, files: Vec<String>, progress: &Sc
|
||||
out.push(c);
|
||||
}
|
||||
// (the walks' diagnostics are [`scan_with`]'s: these files were found already)
|
||||
ScanOutput { candidates: out, probes: kept, truncated: false, unreadable: 0, unsupported: 0 }
|
||||
ScanOutput { candidates: out, probes: kept, truncated: false, unreadable: 0, unsupported: 0, listed: input.listed }
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
//! An import asks the disk for a photo's sidecar only where the folder's listing leaves room for
|
||||
//! one: on a network share every name asked about is a round trip, found or not.
|
||||
use super::*;
|
||||
use crate::sidecar::SidecarNaming;
|
||||
use std::sync::atomic::{AtomicBool, Ordering::Relaxed};
|
||||
|
||||
fn scratch(tag: &str) -> PathBuf {
|
||||
let d = std::env::temp_dir().join(format!("lc-listed-sidecars-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&d);
|
||||
std::fs::create_dir_all(&d).unwrap();
|
||||
d
|
||||
}
|
||||
|
||||
/// Make `dir` and the folders in it an hour old, so the walk vouches for their times
|
||||
/// (`walk::TIME_GRAIN`, two seconds) without the test waiting.
|
||||
fn settle(dir: &Path) {
|
||||
let hour_ago = std::time::SystemTime::now() - std::time::Duration::from_secs(3600);
|
||||
for e in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
if e.file_type().is_ok_and(|t| t.is_dir()) {
|
||||
settle(&e.path());
|
||||
}
|
||||
}
|
||||
set_folder_time(dir, hour_ago);
|
||||
}
|
||||
|
||||
/// Set a folder's modification time (Unix: a plain handle; Windows: one opened for attributes,
|
||||
/// with backup semantics, which is how a folder is opened there).
|
||||
fn set_folder_time(dir: &Path, at: std::time::SystemTime) {
|
||||
#[cfg(windows)]
|
||||
let handle = {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
// FILE_WRITE_ATTRIBUTES, FILE_FLAG_BACKUP_SEMANTICS
|
||||
std::fs::OpenOptions::new().write(true).access_mode(0x100).custom_flags(0x0200_0000).open(dir)
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let handle = std::fs::File::open(dir);
|
||||
handle.unwrap().set_modified(at).unwrap();
|
||||
}
|
||||
|
||||
fn modified(dir: &Path) -> Option<std::time::SystemTime> {
|
||||
std::fs::metadata(dir).and_then(|m| m.modified()).ok()
|
||||
}
|
||||
|
||||
fn xmp(rating: u8) -> String {
|
||||
format!(
|
||||
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
|
||||
<rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="{rating}"/></rdf:RDF></x:xmpmeta>"#
|
||||
)
|
||||
}
|
||||
|
||||
/// An import of files that are not read (the probe says "a JPEG") with the naming `naming`.
|
||||
fn job(naming: SidecarNaming) -> ImportJob {
|
||||
let mut s = Session::new();
|
||||
let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap();
|
||||
job.naming = naming;
|
||||
job.probe = Some(std::sync::Arc::new(|_: &str| Ok(ProbeInfo { format: "JPEG".into(), ..ProbeInfo::default() })));
|
||||
job
|
||||
}
|
||||
|
||||
/// (file name → the rating its sidecar gave, `None`: no sidecar) in the order imported.
|
||||
fn ratings(p: Prepared) -> Vec<(String, Option<u8>)> {
|
||||
p.items
|
||||
.into_iter()
|
||||
.map(|i| match i {
|
||||
PreparedItem::Ready(r) => (Path::new(&r.path).file_name().unwrap().to_string_lossy().to_string(), r.sidecar.and_then(|sc| sc.rating)),
|
||||
other => panic!("not ready: {other:?}"),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Given folders listed completely that hold no `.xmp`, when their files are imported, then no
|
||||
/// sidecar name is asked of the disk (it was nine names for every file); and files named one by
|
||||
/// one, whose folders nobody listed, are asked about as before.
|
||||
#[test]
|
||||
fn a_listed_folder_without_sidecars_is_not_asked_about_them() {
|
||||
let root = scratch("none");
|
||||
let mut named = Vec::new();
|
||||
for folder in 0..50 {
|
||||
let dir = root.join(format!("f{folder:02}"));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for n in 0..20 {
|
||||
let f = dir.join(format!("IMG_{n:04}.jpg"));
|
||||
std::fs::write(&f, b"x").unwrap();
|
||||
named.push(f.to_string_lossy().to_string());
|
||||
}
|
||||
}
|
||||
settle(&root);
|
||||
let cancel = AtomicBool::new(false);
|
||||
|
||||
let mut listed = job(SidecarNaming::Stem);
|
||||
let p = listed.prepare(&[root.to_string_lossy().to_string()], &cancel);
|
||||
assert_eq!(p.items.len(), 1000);
|
||||
assert_eq!(listed.listed.asked.load(Relaxed), 0, "1,000 files in 50 listed folders: no disk probe");
|
||||
|
||||
let mut by_name = job(SidecarNaming::Stem);
|
||||
let p = by_name.prepare(&named, &cancel);
|
||||
assert_eq!(p.items.len(), 1000);
|
||||
assert_eq!(by_name.listed.asked.load(Relaxed), 1000, "files named directly keep their disk probes");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Given sidecars in every case and naming, when the folder is imported, then each is read, and
|
||||
/// only the photo without one is not asked about.
|
||||
#[test]
|
||||
fn sidecars_in_the_listing_are_read_in_any_case() {
|
||||
for naming in [SidecarNaming::Stem, SidecarNaming::Full] {
|
||||
let root = scratch("cases");
|
||||
let write = |name: &str, rating: u8| std::fs::write(root.join(name), xmp(rating)).unwrap();
|
||||
for p in ["a.jpg", "b.jpg", "c.jpg", "d.jpg", "e.jpg", "f.jpg"] {
|
||||
std::fs::write(root.join(p), b"x").unwrap();
|
||||
}
|
||||
write("a.xmp", 1);
|
||||
write("b.XMP", 2);
|
||||
write("c.Xmp", 3);
|
||||
write("d.jpg.xmp", 4);
|
||||
write("e.JPG.XMP", 5);
|
||||
settle(&root);
|
||||
let mut job = job(naming);
|
||||
let found = ratings(job.prepare(&[root.to_string_lossy().to_string()], &AtomicBool::new(false)));
|
||||
let expect: Vec<(String, Option<u8>)> =
|
||||
[("a.jpg", Some(1)), ("b.jpg", Some(2)), ("c.jpg", Some(3)), ("d.jpg", Some(4)), ("e.jpg", Some(5)), ("f.jpg", None)]
|
||||
.into_iter()
|
||||
.map(|(n, r)| (n.to_string(), r))
|
||||
.collect();
|
||||
let mut found = found;
|
||||
found.sort();
|
||||
assert_eq!(found, expect, "{naming:?}");
|
||||
assert_eq!(job.listed.asked.load(Relaxed), 5, "{naming:?}: the five with a sidecar are asked about, f.jpg is not");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
|
||||
/// A folder the walk did not list completely, or whose names the listing can't compare as the
|
||||
/// disk does (not ASCII), is not trusted: its photos are asked about as before.
|
||||
#[test]
|
||||
fn a_listing_that_cannot_say_leaves_the_disk_to_decide() {
|
||||
let root = scratch("cannot-say");
|
||||
let (whole, partial, accents) = (root.join("whole"), root.join("partial"), root.join("accents"));
|
||||
for d in [&whole, &partial, &accents] {
|
||||
std::fs::create_dir_all(d).unwrap();
|
||||
}
|
||||
let in_ = |d: &Path, n: &str| d.join(n).to_string_lossy().to_string();
|
||||
let mut l = listed_folders::ListedFolders::default();
|
||||
let file = |n: &str| (std::ffi::OsString::from(n), crate::walk::EntryKind::File);
|
||||
l.note(&partial, vec![file("a.jpg")], false, modified(&partial));
|
||||
l.note(&accents, vec![file("é.jpg"), file("a.jpg")], true, modified(&accents));
|
||||
l.note(&whole, vec![file("a.jpg"), file("b.xmp")], true, modified(&whole));
|
||||
let naming = SidecarNaming::Stem;
|
||||
// (a folder that is not on disk any more has no time to compare: asked about, too)
|
||||
l.note(Path::new("/p/gone"), vec![file("a.jpg")], true, Some(std::time::SystemTime::UNIX_EPOCH));
|
||||
// (a folder too recent to vouch for, as the walk reports it: no time)
|
||||
let recent = root.join("recent");
|
||||
std::fs::create_dir_all(&recent).unwrap();
|
||||
l.note(&recent, vec![file("a.jpg")], true, None);
|
||||
let cases = [
|
||||
in_(&partial, "a.jpg"),
|
||||
in_(&accents, "a.jpg"),
|
||||
in_(&root.join("unlisted"), "a.jpg"),
|
||||
in_(&whole, "b.jpg"),
|
||||
in_(&whole, "a~1.jpg"),
|
||||
in_(&whole, "nul.jpg"),
|
||||
"/p/gone/a.jpg".to_string(),
|
||||
in_(&recent, "a.jpg"),
|
||||
];
|
||||
for original in &cases {
|
||||
let before = l.asked.load(Relaxed);
|
||||
assert!(l.find(original, naming).is_none());
|
||||
assert_eq!(l.asked.load(Relaxed), before + 1, "{original}: the disk is asked");
|
||||
}
|
||||
let before = l.asked.load(Relaxed);
|
||||
assert!(l.find(&in_(&whole, "a.jpg"), naming).is_none());
|
||||
assert_eq!(l.asked.load(Relaxed), before, "a listed folder with no a.xmp: the disk is not asked");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Given a review (the scan before the Add Photos dialog) of folders without sidecars, and an
|
||||
/// import of the files it listed, when the files are handled, then neither a sidecar name nor
|
||||
/// "is it a folder" is asked of the disk for them; and the sidecar the review's listing shows is
|
||||
/// read.
|
||||
#[test]
|
||||
fn an_import_after_a_review_trusts_the_folders_the_review_listed() {
|
||||
let root = scratch("review");
|
||||
for folder in 0..20 {
|
||||
let dir = root.join(format!("f{folder:02}"));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for n in 0..10 {
|
||||
std::fs::write(dir.join(format!("IMG_{n:04}.jpg")), b"x").unwrap();
|
||||
}
|
||||
}
|
||||
std::fs::write(root.join("f07").join("IMG_0003.xmp"), xmp(4)).unwrap();
|
||||
settle(&root);
|
||||
let mut s = Session::new();
|
||||
s.media.file_probe = Some(std::sync::Arc::new(|_: &str| Ok(ProbeInfo { format: "JPEG".into(), file_size: 1, ..ProbeInfo::default() })));
|
||||
let (input, paths) = ScanInput::new(&mut s, &[root.to_string_lossy().to_string()]);
|
||||
let out = scan_with(input, &paths, &ScanProgress::default());
|
||||
let selected: Vec<String> = out.candidates.iter().map(|c| c.path.clone()).collect();
|
||||
assert_eq!(selected.len(), 200);
|
||||
// (what the app does with the scan's output)
|
||||
s.import_probes = out.probes;
|
||||
let listed = out.listed;
|
||||
|
||||
let mut job = ImportJob::new(&mut s, ImportOptions { mode: ImportMode::Add, ..ImportOptions::default() }).unwrap().with_listed(listed);
|
||||
let p = job.prepare(&selected, &AtomicBool::new(false));
|
||||
assert_eq!(job.listed.asked.load(Relaxed), 1, "only the photo with a sidecar in the listing is asked about");
|
||||
let found = ratings(p);
|
||||
assert_eq!(found.len(), 200);
|
||||
assert_eq!(found.iter().filter(|(_, r)| r.is_some()).collect::<Vec<_>>(), [&("IMG_0003.jpg".to_string(), Some(4))]);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// A path the listing calls a file is not asked about (here the disk holds a folder by that
|
||||
/// name, which only a look at the disk would find) while its folder is as it was listed; one it
|
||||
/// does not list still is.
|
||||
#[test]
|
||||
fn a_file_the_listing_does_not_know_is_still_checked() {
|
||||
let root = scratch("known");
|
||||
for name in ["known.jpg", "unknown.jpg"] {
|
||||
std::fs::create_dir_all(root.join(name)).unwrap();
|
||||
std::fs::write(root.join(name).join("inner.jpg"), b"x").unwrap();
|
||||
}
|
||||
settle(&root);
|
||||
let mut job = job(SidecarNaming::Stem);
|
||||
// (the folder is as listed: its time is the one the listing holds)
|
||||
job.listed.note(&root, vec![("known.jpg".into(), crate::walk::EntryKind::File)], true, modified(&root));
|
||||
let (known, unknown) = (root.join("known.jpg"), root.join("unknown.jpg"));
|
||||
let files = job.expand(&[known.to_string_lossy().to_string(), unknown.to_string_lossy().to_string()]);
|
||||
assert_eq!(files, [known.to_string_lossy().to_string(), unknown.join("inner.jpg").to_string_lossy().to_string()]);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Given a review whose listing was kept, when a sidecar appears in a folder afterwards (the
|
||||
/// review was left open, or cancelled, and something else added it), then the import that gets
|
||||
/// the listing still reads it: a folder that changed since it was listed is probed.
|
||||
#[test]
|
||||
fn a_folder_that_changed_since_it_was_listed_is_probed() {
|
||||
let root = scratch("stale");
|
||||
for n in 0..3 {
|
||||
std::fs::write(root.join(format!("a{n}.jpg")), b"x").unwrap();
|
||||
}
|
||||
settle(&root);
|
||||
let mut walked = ListedFolders::default();
|
||||
let (files, _) = expand_knowing(
|
||||
&[root.to_string_lossy().to_string()],
|
||||
None,
|
||||
crate::walk::Limits::default(),
|
||||
Some(&mut |dir, names, complete, modified| {
|
||||
walked.note(dir, names, complete, modified);
|
||||
true
|
||||
}),
|
||||
true,
|
||||
&|_| false,
|
||||
);
|
||||
assert_eq!(files.len(), 3);
|
||||
// a sidecar arrives, more than a clock tick after the listing
|
||||
std::fs::write(root.join("a1.xmp"), xmp(5)).unwrap();
|
||||
let mut job = job(SidecarNaming::Stem).with_listed(walked);
|
||||
let found = ratings(job.prepare_files(files, &AtomicBool::new(false)));
|
||||
assert_eq!(found.iter().filter(|(_, r)| *r == Some(5)).count(), 1, "{found:?}");
|
||||
assert_eq!(job.listed.asked.load(Relaxed), 3, "the folder is asked about, photo by photo");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// A batch looks at the time of each folder its files are in, once: not once per file, and not
|
||||
/// once per folder that was listed.
|
||||
#[test]
|
||||
fn a_batch_looks_at_each_of_its_folders_once() {
|
||||
let root = scratch("looks");
|
||||
for folder in 0..50 {
|
||||
let dir = root.join(format!("f{folder:02}"));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
for n in 0..20 {
|
||||
std::fs::write(dir.join(format!("IMG_{n:04}.jpg")), b"x").unwrap();
|
||||
}
|
||||
}
|
||||
settle(&root);
|
||||
let mut job = job(SidecarNaming::Stem);
|
||||
let files = job.expand(&[root.to_string_lossy().to_string()]);
|
||||
assert_eq!(files.len(), 1000);
|
||||
let in_folders = |names: &[&str]| -> Vec<String> {
|
||||
files.iter().filter(|f| Path::new(f).parent().and_then(Path::file_name).is_some_and(|d| names.iter().any(|n| d == *n))).cloned().collect()
|
||||
};
|
||||
let cancel = AtomicBool::new(false);
|
||||
let first = job.prepare_files(in_folders(&["f00", "f01"]), &cancel);
|
||||
assert_eq!(first.items.len(), 40);
|
||||
assert_eq!(job.listed.looked.load(Relaxed), 2, "40 files in 2 of the 50 listed folders");
|
||||
job.prepare_files(in_folders(&["f01", "f02", "f03"]), &cancel);
|
||||
assert_eq!(job.listed.looked.load(Relaxed), 2 + 3, "the next batch looks again, at its own 3");
|
||||
assert_eq!(job.listed.asked.load(Relaxed), 0);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Given photos named one by one (no listing to rule a sidecar out), when a batch of them is
|
||||
/// handled, then their sidecars are not looked up one after another by the thread that plans the
|
||||
/// batch: each is a few names asked of the disk, a round trip apiece on a network share, so the
|
||||
/// lookups of a batch run together (`sidecars_of`).
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
#[test]
|
||||
fn a_batchs_sidecars_are_looked_up_off_the_thread_that_plans_it() {
|
||||
let root = scratch("lookers");
|
||||
let files: Vec<String> = (0..6)
|
||||
.map(|n| {
|
||||
let f = root.join(format!("IMG_{n:04}.jpg"));
|
||||
std::fs::write(&f, b"x").unwrap();
|
||||
f.to_string_lossy().to_string()
|
||||
})
|
||||
.collect();
|
||||
let mut job = job(SidecarNaming::Stem);
|
||||
let prepared = job.prepare_files(files, &AtomicBool::new(false));
|
||||
assert_eq!(prepared.items.len(), 6);
|
||||
assert_eq!(job.listed.asked.load(Relaxed), 6, "each photo's sidecar is asked of the disk");
|
||||
let lookers = job.listed.lookers.lock().unwrap();
|
||||
assert!(!lookers.is_empty(), "no lookups were made");
|
||||
assert!(!lookers.contains(&std::thread::current().id()), "a lookup was made by the thread that plans the batch, one after another");
|
||||
drop(lookers);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Given a folder listed in the same clock tick as its files were made, when a sidecar is
|
||||
/// written into it right after the listing and the folder's time reads as it did before (a
|
||||
/// volume that keeps folder times to the second or two), then the import still reads it: a
|
||||
/// time too recent to vouch for is not trusted. (The test puts the folder's time back.)
|
||||
#[test]
|
||||
fn a_sidecar_written_in_the_tick_of_the_listing_is_read() {
|
||||
let root = scratch("racy");
|
||||
for n in 0..3 {
|
||||
std::fs::write(root.join(format!("a{n}.jpg")), b"x").unwrap();
|
||||
}
|
||||
let at_listing = modified(&root).unwrap();
|
||||
let mut walked = ListedFolders::default();
|
||||
let (files, _) = expand_knowing(
|
||||
&[root.to_string_lossy().to_string()],
|
||||
None,
|
||||
crate::walk::Limits::default(),
|
||||
Some(&mut |dir, names, complete, modified| {
|
||||
walked.note(dir, names, complete, modified);
|
||||
true
|
||||
}),
|
||||
true,
|
||||
&|_| false,
|
||||
);
|
||||
std::fs::write(root.join("a1.xmp"), xmp(5)).unwrap();
|
||||
set_folder_time(&root, at_listing);
|
||||
let mut job = job(SidecarNaming::Stem).with_listed(walked);
|
||||
let found = ratings(job.prepare_files(files, &AtomicBool::new(false)));
|
||||
assert_eq!(found.iter().filter(|(_, r)| *r == Some(5)).count(), 1, "{found:?}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// Given a review whose listing was kept, when a listed file is replaced by a folder holding a
|
||||
/// photo afterwards, then the import's expansion walks that folder: a name in a folder that
|
||||
/// changed since it was listed is not trusted to still be a file.
|
||||
#[test]
|
||||
fn a_listed_file_replaced_by_a_folder_is_expanded() {
|
||||
let root = scratch("replaced");
|
||||
for n in 0..3 {
|
||||
std::fs::write(root.join(format!("a{n}.jpg")), b"x").unwrap();
|
||||
}
|
||||
settle(&root);
|
||||
let mut walked = ListedFolders::default();
|
||||
let (files, _) = expand_knowing(
|
||||
&[root.to_string_lossy().to_string()],
|
||||
None,
|
||||
crate::walk::Limits::default(),
|
||||
Some(&mut |dir, names, complete, modified| {
|
||||
walked.note(dir, names, complete, modified);
|
||||
true
|
||||
}),
|
||||
true,
|
||||
&|_| false,
|
||||
);
|
||||
assert_eq!(files.len(), 3);
|
||||
std::fs::remove_file(root.join("a1.jpg")).unwrap();
|
||||
std::fs::create_dir(root.join("a1.jpg")).unwrap();
|
||||
std::fs::write(root.join("a1.jpg").join("inside.jpg"), b"x").unwrap();
|
||||
let mut job = job(SidecarNaming::Stem).with_listed(walked);
|
||||
// (the paths handed to the import are the files the review listed)
|
||||
let found = job.expand(&files);
|
||||
assert!(found.iter().any(|f| f.ends_with("inside.jpg")), "{found:?}");
|
||||
assert_eq!(found.len(), 3, "{found:?}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
/// A folder noted with no time (too recent to vouch for, or the volume keeps none) is not
|
||||
/// trusted, and finding that out costs no look at the disk.
|
||||
#[test]
|
||||
fn a_folder_without_a_listed_time_costs_no_look() {
|
||||
let root = scratch("no-time");
|
||||
std::fs::write(root.join("a.jpg"), b"x").unwrap();
|
||||
let mut l = ListedFolders::default();
|
||||
l.note(&root, vec![("a.jpg".into(), crate::walk::EntryKind::File)], true, None);
|
||||
assert!(!l.is_known_file(&root.join("a.jpg")));
|
||||
assert_eq!(l.looked.load(Relaxed), 0);
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
@@ -38,9 +38,9 @@ mod plan;
|
||||
mod sidecar;
|
||||
mod tokens;
|
||||
|
||||
pub(crate) use fs::{MoveFs, RealFs};
|
||||
#[cfg(test)]
|
||||
use fs::{folded_path, same_contents};
|
||||
use fs::{LIST_FOLDER_AT, ListedSources, folded_path, same_contents};
|
||||
pub(crate) use fs::{MoveFs, RealFs};
|
||||
pub(crate) use moves::move_all;
|
||||
#[cfg(test)]
|
||||
pub(crate) use moves::move_file_with;
|
||||
@@ -71,5 +71,9 @@ pub struct RenamePlan {
|
||||
pub to_path: Option<String>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "rename/tests_listed_sources.rs"]
|
||||
mod tests_listed_sources;
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) mod tests;
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::sidecar::PacketVersion;
|
||||
use super::{Path, PathBuf, SidecarNaming};
|
||||
use super::{HashMap, HashSet, Path, PathBuf, SidecarNaming};
|
||||
|
||||
/// Every sidecar that may belong to `path` (both naming conventions, `.xmp` and `.XMP`).
|
||||
pub(super) fn sidecars(path: &str) -> Vec<(PathBuf, SidecarNaming, bool)> {
|
||||
@@ -41,6 +41,18 @@ pub(crate) trait MoveFs {
|
||||
Err(_) => true,
|
||||
}
|
||||
}
|
||||
/// The names in folder `dir`, or `None` when it can't be listed or holds more than `budget`
|
||||
/// entries (it stops reading at that many, so a huge folder is never collected).
|
||||
fn list_dir(&self, dir: &Path, budget: usize) -> Option<Vec<std::ffi::OsString>> {
|
||||
let mut names = Vec::new();
|
||||
for entry in std::fs::read_dir(dir).ok()? {
|
||||
if names.len() == budget {
|
||||
return None;
|
||||
}
|
||||
names.push(entry.ok()?.file_name());
|
||||
}
|
||||
Some(names)
|
||||
}
|
||||
/// Content observed in a packet, independent of its pathname or inode. Model volumes
|
||||
/// override this; disk implementations stream a bounded buffer without retaining the XML.
|
||||
fn packet_version(&self, path: &Path) -> std::io::Result<PacketVersion> {
|
||||
@@ -199,6 +211,134 @@ fn open_regular(a: &Path, checked: &std::fs::Metadata) -> std::io::Result<std::f
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
/// A folder with this many photos leaving it is listed once, and its photos' sidecars are looked
|
||||
/// for in that listing: asking the disk for four names per photo costs a round trip each on a
|
||||
/// network share, found or not. Fewer photos are probed one by one.
|
||||
pub(super) const LIST_FOLDER_AT: usize = 8;
|
||||
|
||||
/// Directory entries the folder listings of one move may collect in all: the walk's own bound
|
||||
/// ([`crate::walk::MAX_ENTRIES`]). A folder past what is left of it isn't listed, and its photos
|
||||
/// are probed one by one as before.
|
||||
const LIST_ENTRIES_AT_MOST: usize = crate::walk::MAX_ENTRIES;
|
||||
|
||||
/// `inner`, with the question "is this sidecar a file?" answered from one listing of each folder
|
||||
/// that many photos leave ([`LIST_FOLDER_AT`]) where the listing can vouch for a "no": the folder was
|
||||
/// listed whole, and its names are all ASCII (a file system may treat other names alike in other
|
||||
/// cases), and the name is a plain one ([`crate::sync::plain_name`], no device names). A name the
|
||||
/// listing holds (in any case), a folder not listed or not listed whole, and every other question
|
||||
/// go to `inner` as before. A sidecar a move or copy brings into a listed folder is added to its names.
|
||||
pub(super) struct ListedSources<'a> {
|
||||
inner: &'a dyn MoveFs,
|
||||
/// folder → the `.xmp` names in it, lower-cased.
|
||||
pub(super) folders: std::cell::RefCell<HashMap<PathBuf, HashSet<String>>>,
|
||||
}
|
||||
|
||||
impl<'a> ListedSources<'a> {
|
||||
pub(super) fn new(inner: &'a dyn MoveFs, moves: &[(String, String)]) -> Self {
|
||||
Self::with_budget(inner, moves, LIST_ENTRIES_AT_MOST)
|
||||
}
|
||||
|
||||
/// As [`Self::new`], with at most `budget` directory entries listed over all folders.
|
||||
pub(super) fn with_budget(inner: &'a dyn MoveFs, moves: &[(String, String)], mut budget: usize) -> Self {
|
||||
let mut leaving: HashMap<&Path, usize> = HashMap::new();
|
||||
for (from, _) in moves {
|
||||
if let Some(dir) = Path::new(from).parent().filter(|d| !d.as_os_str().is_empty()) {
|
||||
*leaving.entry(dir).or_default() += 1;
|
||||
}
|
||||
}
|
||||
let mut folders = HashMap::new();
|
||||
for (dir, n) in leaving {
|
||||
if n < LIST_FOLDER_AT {
|
||||
continue;
|
||||
}
|
||||
let Some(names) = inner.list_dir(dir, budget) else { continue };
|
||||
// (an override that lists more than the budget it was given breaks the contract: not trusted)
|
||||
let Some(left) = budget.checked_sub(names.len()) else { continue };
|
||||
budget = left;
|
||||
// (any name that is no ASCII text: the listing can't say what another name's other case is)
|
||||
let xmp: Option<HashSet<String>> = names
|
||||
.iter()
|
||||
.map(|n| n.to_str().filter(|n| n.is_ascii()).map(str::to_ascii_lowercase))
|
||||
.collect::<Option<Vec<_>>>()
|
||||
.map(|v| v.into_iter().filter(|n| n.ends_with(".xmp")).collect());
|
||||
if let Some(xmp) = xmp {
|
||||
folders.insert(dir.to_path_buf(), xmp);
|
||||
}
|
||||
}
|
||||
ListedSources { inner, folders: std::cell::RefCell::new(folders) }
|
||||
}
|
||||
|
||||
/// Whether the listing shows `p`, a sidecar name, is not there.
|
||||
fn surely_absent(&self, p: &Path) -> bool {
|
||||
let folders = self.folders.borrow();
|
||||
let (Some(xmp), Some(name)) = (p.parent().and_then(|d| folders.get(d)), p.file_name().and_then(|n| n.to_str())) else { return false };
|
||||
p.to_str().is_some_and(|s| s.ends_with(name))
|
||||
&& name.len() > ".xmp".len()
|
||||
&& name.to_ascii_lowercase().ends_with(".xmp")
|
||||
&& crate::sync::plain_name(name)
|
||||
&& !crate::sync::asks_the_disk(name)
|
||||
&& !xmp.contains(&name.to_ascii_lowercase())
|
||||
}
|
||||
|
||||
/// A file arrived at `p`: a `.xmp` joins its folder's names (one that leaves changes nothing:
|
||||
/// a name listed that is gone is asked about, and found missing, as before).
|
||||
fn arrived(&self, p: &Path) {
|
||||
let Some(dir) = p.parent() else { return };
|
||||
let mut folders = self.folders.borrow_mut();
|
||||
let Some(xmp) = folders.get_mut(dir) else { return };
|
||||
match p.file_name().and_then(|n| n.to_str()).filter(|n| n.is_ascii()) {
|
||||
Some(name) if name.to_ascii_lowercase().ends_with(".xmp") => {
|
||||
xmp.insert(name.to_ascii_lowercase());
|
||||
}
|
||||
Some(_) => {}
|
||||
None => {
|
||||
folders.remove(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MoveFs for ListedSources<'_> {
|
||||
fn exists(&self, p: &Path) -> bool {
|
||||
self.inner.exists(p)
|
||||
}
|
||||
fn is_file(&self, p: &Path) -> bool {
|
||||
!self.surely_absent(p) && self.inner.is_file(p)
|
||||
}
|
||||
fn same_file(&self, a: &Path, b: &Path) -> bool {
|
||||
self.inner.same_file(a, b)
|
||||
}
|
||||
fn rename_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> {
|
||||
let moved = self.inner.rename_no_replace(a, b);
|
||||
if moved.is_ok() {
|
||||
self.arrived(b);
|
||||
}
|
||||
moved
|
||||
}
|
||||
fn copy_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> {
|
||||
let copied = self.inner.copy_no_replace(a, b);
|
||||
if copied.is_ok() {
|
||||
self.arrived(b);
|
||||
}
|
||||
copied
|
||||
}
|
||||
fn remove_file(&self, p: &Path) -> std::io::Result<()> {
|
||||
self.inner.remove_file(p)
|
||||
}
|
||||
fn stem_sibling(&self, sidecar: &Path) -> Option<String> {
|
||||
self.inner.stem_sibling(sidecar)
|
||||
}
|
||||
fn listed(&self, p: &Path) -> bool {
|
||||
self.inner.listed(p)
|
||||
}
|
||||
fn list_dir(&self, dir: &Path, budget: usize) -> Option<Vec<std::ffi::OsString>> {
|
||||
self.inner.list_dir(dir, budget)
|
||||
}
|
||||
fn packet_version(&self, path: &Path) -> std::io::Result<PacketVersion> {
|
||||
self.inner.packet_version(path)
|
||||
}
|
||||
}
|
||||
|
||||
/// Move `a` to `b` on another volume: copy (never replacing), compare the copy with the original
|
||||
/// byte for byte, and only then remove the original. A copy that doesn't match is removed.
|
||||
fn move_across_volumes(fs: &RealFs, a: &Path, b: &Path) -> std::io::Result<()> {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
use super::fs::{MoveFs, RealFs, folded_path, is_respelling, move_one, sidecars};
|
||||
use super::fs::{ListedSources, MoveFs, RealFs, folded_path, is_respelling, move_one, sidecars};
|
||||
use super::sidecar::{RetainedPacket, SidecarMove, advance_packets, note_companions, packet_aliases};
|
||||
use super::{HashMap, HashSet, Op, Path, PathBuf, SidecarNaming, Source};
|
||||
|
||||
@@ -123,6 +123,8 @@ pub(crate) struct BatchMoveError {
|
||||
/// Move the files `moves` names, all or nothing: after a failure the earlier moves are undone.
|
||||
/// Moves that can't be undone (e.g. the network share went away) are reported, not ignored.
|
||||
pub(crate) fn move_all(fs: &dyn MoveFs, moves: &[(String, String)]) -> std::result::Result<(), BatchMoveError> {
|
||||
let listed = ListedSources::new(fs, moves);
|
||||
let fs: &dyn MoveFs = &listed;
|
||||
let mut done: Vec<&(String, String)> = Vec::new();
|
||||
for m in moves {
|
||||
let Err(e) = move_file_with(fs, &m.0, &m.1) else {
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Moving photos out of a folder asks the disk for their sidecars only where a listing of the
|
||||
//! folder leaves room for one: on a network share each name asked about is a round trip.
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
/// The disk, counting the questions about `.xmp` names and the listings.
|
||||
struct Counting {
|
||||
can_list: bool,
|
||||
/// `list_dir` returns every name whatever the budget (an override that breaks the contract).
|
||||
ignores_budget: bool,
|
||||
xmp_asked: Cell<usize>,
|
||||
listings: Cell<usize>,
|
||||
}
|
||||
|
||||
impl Counting {
|
||||
fn new(can_list: bool) -> Self {
|
||||
Counting { can_list, ignores_budget: false, xmp_asked: Cell::new(0), listings: Cell::new(0) }
|
||||
}
|
||||
|
||||
fn ignoring_the_budget() -> Self {
|
||||
Counting { ignores_budget: true, ..Counting::new(true) }
|
||||
}
|
||||
}
|
||||
|
||||
impl MoveFs for Counting {
|
||||
fn exists(&self, p: &Path) -> bool {
|
||||
RealFs.exists(p)
|
||||
}
|
||||
fn is_file(&self, p: &Path) -> bool {
|
||||
if p.extension().is_some_and(|e| e.eq_ignore_ascii_case("xmp")) {
|
||||
self.xmp_asked.set(self.xmp_asked.get() + 1);
|
||||
}
|
||||
RealFs.is_file(p)
|
||||
}
|
||||
fn same_file(&self, a: &Path, b: &Path) -> bool {
|
||||
RealFs.same_file(a, b)
|
||||
}
|
||||
fn rename_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> {
|
||||
RealFs.rename_no_replace(a, b)
|
||||
}
|
||||
fn copy_no_replace(&self, a: &Path, b: &Path) -> std::io::Result<()> {
|
||||
RealFs.copy_no_replace(a, b)
|
||||
}
|
||||
fn remove_file(&self, p: &Path) -> std::io::Result<()> {
|
||||
RealFs.remove_file(p)
|
||||
}
|
||||
fn stem_sibling(&self, sidecar: &Path) -> Option<String> {
|
||||
RealFs.stem_sibling(sidecar)
|
||||
}
|
||||
fn list_dir(&self, dir: &Path, budget: usize) -> Option<Vec<std::ffi::OsString>> {
|
||||
self.listings.set(self.listings.get() + 1);
|
||||
let budget = if self.ignores_budget { usize::MAX } else { budget };
|
||||
if self.can_list { RealFs.list_dir(dir, budget) } else { None }
|
||||
}
|
||||
}
|
||||
|
||||
fn scratch(tag: &str) -> (PathBuf, PathBuf) {
|
||||
let root = std::env::temp_dir().join(format!("lc-listed-sources-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
let (from, to) = (root.join("from"), root.join("to"));
|
||||
std::fs::create_dir_all(&from).unwrap();
|
||||
std::fs::create_dir_all(&to).unwrap();
|
||||
(from, to)
|
||||
}
|
||||
|
||||
/// `n` photos `p00.jpg`… in `from`, moved to `to` under the same names.
|
||||
fn moves(from: &Path, to: &Path, n: usize) -> Vec<(String, String)> {
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let name = format!("p{i:02}.jpg");
|
||||
(from.join(&name).to_string_lossy().to_string(), to.join(name).to_string_lossy().to_string())
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn names_lower(dir: &Path) -> Vec<String> {
|
||||
let mut v: Vec<String> = std::fs::read_dir(dir).unwrap().map(|e| e.unwrap().file_name().to_string_lossy().to_lowercase()).collect();
|
||||
v.sort();
|
||||
v
|
||||
}
|
||||
|
||||
/// Given 50 photos in a folder without sidecars, when they are moved, then no sidecar name is
|
||||
/// asked of the disk (it was eight questions for each photo), and the folder is listed once.
|
||||
#[test]
|
||||
fn photos_leaving_a_listed_folder_without_sidecars_ask_the_disk_nothing() {
|
||||
let (from, to) = scratch("none");
|
||||
for (src, _) in moves(&from, &to, 50) {
|
||||
std::fs::write(src, b"x").unwrap();
|
||||
}
|
||||
let fs = Counting::new(true);
|
||||
move_all(&fs, &moves(&from, &to, 50)).unwrap();
|
||||
assert_eq!((fs.xmp_asked.get(), fs.listings.get()), (0, 1));
|
||||
assert_eq!(names_lower(&to).len(), 50);
|
||||
assert!(names_lower(&from).is_empty());
|
||||
let _ = std::fs::remove_dir_all(from.parent().unwrap());
|
||||
}
|
||||
|
||||
/// Given sidecars in every case and naming among the photos, when they are moved and moved back
|
||||
/// (undo), then each goes with its photo each way, and only the photos that have one are asked
|
||||
/// about.
|
||||
#[test]
|
||||
fn sidecars_in_the_listing_move_with_their_photos_and_back() {
|
||||
let (from, to) = scratch("cases");
|
||||
let all = moves(&from, &to, 12);
|
||||
for (src, _) in &all {
|
||||
std::fs::write(src, b"x").unwrap();
|
||||
}
|
||||
// stem and full names, in lower and upper case (the spellings a move looks for)
|
||||
for sc in ["p00.xmp", "p01.XMP", "p02.jpg.xmp", "p03.jpg.XMP"] {
|
||||
std::fs::write(from.join(sc), b"<x/>").unwrap();
|
||||
}
|
||||
let before = names_lower(&from);
|
||||
let fs = Counting::new(true);
|
||||
move_all(&fs, &all).unwrap();
|
||||
assert!(names_lower(&from).is_empty(), "everything left, sidecars with their photos: {:?}", names_lower(&from));
|
||||
assert_eq!(names_lower(&to), before);
|
||||
// (the four photos with a sidecar are asked about; the eight others are not)
|
||||
assert!(fs.xmp_asked.get() > 0 && fs.xmp_asked.get() < 12 * 8, "{}", fs.xmp_asked.get());
|
||||
|
||||
let back: Vec<(String, String)> = all.iter().map(|(a, b)| (b.clone(), a.clone())).collect();
|
||||
move_all(&fs, &back).unwrap();
|
||||
assert_eq!(names_lower(&from), before);
|
||||
assert!(names_lower(&to).is_empty());
|
||||
let _ = std::fs::remove_dir_all(from.parent().unwrap());
|
||||
}
|
||||
|
||||
/// A folder that can't be listed, and one with too few photos to list, keep the probes: a
|
||||
/// sidecar there is still moved with its photo.
|
||||
#[test]
|
||||
fn a_folder_that_cannot_be_listed_or_is_too_small_is_probed_photo_by_photo() {
|
||||
for (can_list, photos) in [(false, 12), (true, LIST_FOLDER_AT - 1)] {
|
||||
let (from, to) = scratch("probed");
|
||||
let all = moves(&from, &to, photos);
|
||||
for (src, _) in &all {
|
||||
std::fs::write(src, b"x").unwrap();
|
||||
}
|
||||
std::fs::write(from.join("p00.XMP"), b"<x/>").unwrap();
|
||||
let fs = Counting::new(can_list);
|
||||
move_all(&fs, &all).unwrap();
|
||||
assert!(names_lower(&to).contains(&"p00.xmp".to_string()), "{can_list} {photos}");
|
||||
assert!(fs.xmp_asked.get() >= photos * 4, "each photo is probed: {}", fs.xmp_asked.get());
|
||||
assert_eq!(fs.listings.get(), usize::from(can_list && photos >= LIST_FOLDER_AT) + usize::from(!can_list), "{can_list} {photos}");
|
||||
let _ = std::fs::remove_dir_all(from.parent().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
/// Given a folder that holds more entries than the listing budget, when its photos are moved,
|
||||
/// then the folder is not collected (the read stops at the budget) and each photo's sidecar is
|
||||
/// still probed and moved with it.
|
||||
#[test]
|
||||
fn a_folder_past_the_listing_budget_is_not_listed_and_is_probed_photo_by_photo() {
|
||||
let (from, to) = scratch("budget");
|
||||
let all = moves(&from, &to, 12);
|
||||
for (src, _) in &all {
|
||||
std::fs::write(src, b"x").unwrap();
|
||||
}
|
||||
std::fs::write(from.join("p00.XMP"), b"<x/>").unwrap();
|
||||
// 13 entries: 12 photos and a sidecar
|
||||
assert!(RealFs.list_dir(&from, 12).is_none(), "one entry past the budget");
|
||||
assert_eq!(RealFs.list_dir(&from, 13).map(|n| n.len()), Some(13), "a budget of exactly its size lists it");
|
||||
|
||||
let fs = Counting::new(true);
|
||||
let listed = ListedSources::with_budget(&fs, &all, 12);
|
||||
assert!(listed.folders.borrow().is_empty(), "the folder is past the budget");
|
||||
let listed = ListedSources::with_budget(&fs, &all, 13);
|
||||
assert_eq!(listed.folders.borrow().len(), 1, "and within it, listed");
|
||||
|
||||
// the move itself goes photo by photo: every photo asks the disk, the sidecar still follows
|
||||
let probing = Counting::new(true);
|
||||
let listed = ListedSources::with_budget(&probing, &all, 12);
|
||||
for (a, b) in &all {
|
||||
move_file_with(&listed, a, b).unwrap();
|
||||
}
|
||||
assert!(probing.xmp_asked.get() >= 12 * 4, "each photo is probed: {}", probing.xmp_asked.get());
|
||||
assert!(names_lower(&to).contains(&"p00.xmp".to_string()));
|
||||
let _ = std::fs::remove_dir_all(from.parent().unwrap());
|
||||
}
|
||||
|
||||
/// Given a `list_dir` override that returns more names than the budget it was given (the trait
|
||||
/// documents `None` then), when the listing is collected, then the folder is skipped: the budget
|
||||
/// neither underflows nor wraps, and the photos' sidecars are probed one by one as before.
|
||||
#[test]
|
||||
fn a_listing_larger_than_its_budget_is_skipped_not_counted_below_zero() {
|
||||
let (from, to) = scratch("overlist");
|
||||
let all = moves(&from, &to, 12);
|
||||
for (src, _) in &all {
|
||||
std::fs::write(src, b"x").unwrap();
|
||||
}
|
||||
std::fs::write(from.join("p00.XMP"), b"<x/>").unwrap();
|
||||
|
||||
let fs = Counting::ignoring_the_budget();
|
||||
let listed = ListedSources::with_budget(&fs, &all, 5);
|
||||
assert_eq!(fs.listings.get(), 1, "the folder was asked for");
|
||||
assert!(listed.folders.borrow().is_empty(), "13 names against a budget of 5: not trusted");
|
||||
|
||||
for (a, b) in &all {
|
||||
move_file_with(&listed, a, b).unwrap();
|
||||
}
|
||||
assert!(names_lower(&to).contains(&"p00.xmp".to_string()), "the sidecar still follows its photo");
|
||||
let _ = std::fs::remove_dir_all(from.parent().unwrap());
|
||||
}
|
||||
@@ -231,7 +231,7 @@ pub fn scan_with(input: SyncInput, progress: &SyncProgress) -> FolderChanges {
|
||||
std::slice::from_ref(&folder),
|
||||
scan.skip(),
|
||||
crate::walk::Limits::default(),
|
||||
Some(&mut |dir, names, complete| {
|
||||
Some(&mut |dir, names, complete, _| {
|
||||
use std::sync::atomic::Ordering::Relaxed;
|
||||
progress.folders_listed.fetch_add(1, Relaxed);
|
||||
let files = names.iter().filter(|(_, kind)| *kind == crate::walk::EntryKind::File).count();
|
||||
@@ -426,7 +426,7 @@ struct Listed {
|
||||
|
||||
/// Whether the disk is asked about `name` whatever the listing holds: a name Windows takes for
|
||||
/// a device (`NUL`, `aux.jpg`: there in every folder, or not openable where it is listed).
|
||||
fn asks_the_disk(name: &str) -> bool {
|
||||
pub(crate) fn asks_the_disk(name: &str) -> bool {
|
||||
let stem = name.split('.').next().unwrap_or_default().trim_end_matches(' ').to_ascii_lowercase();
|
||||
// (`COM` and `LPT` with any one digit, the superscript ones Windows also takes among them)
|
||||
let numbered = ["com", "lpt"].iter().any(|port| {
|
||||
@@ -439,7 +439,7 @@ fn asks_the_disk(name: &str) -> bool {
|
||||
/// Whether `name` can only be found under itself in some case: ASCII, and nothing in it that a
|
||||
/// file system resolves another way (a short name with `~`, a stream after `:`, dots or spaces
|
||||
/// at its end, which Windows drops).
|
||||
fn plain_name(name: &str) -> bool {
|
||||
pub(crate) fn plain_name(name: &str) -> bool {
|
||||
name.is_ascii() && !name.contains(['~', ':']) && !name.ends_with(['.', ' ']) && !name.is_empty()
|
||||
}
|
||||
|
||||
|
||||
@@ -151,7 +151,7 @@ fn a_check_from_the_listing_is_the_check_from_the_disk() {
|
||||
.collect();
|
||||
// (`dir.jpg` is gone, though a sidecar of its name is there)
|
||||
let mut l = Listing::default();
|
||||
let walked = crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete| {
|
||||
let walked = crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete, _| {
|
||||
l.note(d, names, complete);
|
||||
true
|
||||
});
|
||||
@@ -174,7 +174,7 @@ fn a_check_from_the_listing_is_the_check_from_the_disk() {
|
||||
l.asked.load(std::sync::atomic::Ordering::Relaxed)
|
||||
};
|
||||
let mut with = Listing::default();
|
||||
crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete| {
|
||||
crate::walk::files_in_noting(&dir, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete, _| {
|
||||
with.note(d, names, complete);
|
||||
true
|
||||
});
|
||||
@@ -191,7 +191,7 @@ fn a_check_from_the_listing_is_the_check_from_the_disk() {
|
||||
// a folder of plain names only: the disk is asked nothing at all
|
||||
let sub = dir.join("sub");
|
||||
let mut only_plain = Listing::default();
|
||||
crate::walk::files_in_noting(&sub, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete| {
|
||||
crate::walk::files_in_noting(&sub, None, crate::walk::Limits::default(), |_| true, &mut |d, names, complete, _| {
|
||||
only_plain.note(d, names, complete);
|
||||
true
|
||||
});
|
||||
|
||||
@@ -94,9 +94,24 @@ pub enum EntryKind {
|
||||
|
||||
/// What [`files_in_noting`] hands over for each folder it lists: the folder, the name and kind
|
||||
/// of every entry in it (hidden ones too), and whether that is all of them (not when the walk
|
||||
/// stopped inside the folder, or an entry could not be read). It answers whether to go on: `false`
|
||||
/// ends the walk there (a scan cancelled; [`Walked::truncated`] is left alone: who stopped it knows).
|
||||
pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, EntryKind)>, bool) -> bool;
|
||||
/// stopped inside the folder, or an entry could not be read), and the folder's modification time when the walk read
|
||||
/// it and it was old enough to show a later change ([`files_in_noting_timed`]; else `None`). It answers whether to go
|
||||
/// on: `false` ends the walk there (a scan cancelled; [`Walked::truncated`] is left alone: who stopped it knows).
|
||||
pub type NoteFolder<'a> = &'a mut dyn FnMut(&Path, Vec<(std::ffi::OsString, EntryKind)>, bool, Option<std::time::SystemTime>) -> bool;
|
||||
|
||||
/// How old a folder's modification time must be, when the folder is read, for a change after the
|
||||
/// listing to show in it. File systems keep folder times in whole seconds (HFS+, ext3) or two
|
||||
/// (FAT, and SMB1's DOS times): a file added in the same tick as the listing would leave the
|
||||
/// time as it was. Two seconds is the coarsest of them (git's "racily clean" rule, for the same reason).
|
||||
const TIME_GRAIN: std::time::Duration = std::time::Duration::from_secs(2);
|
||||
|
||||
/// `dir`'s modification time, when it is old enough ([`TIME_GRAIN`]) that a change after now
|
||||
/// would move it: read before the folder is listed, so nothing added during the listing hides.
|
||||
fn settled_time(dir: &Path) -> Option<std::time::SystemTime> {
|
||||
let modified = std::fs::metadata(dir).and_then(|m| m.modified()).ok()?;
|
||||
let now = std::time::SystemTime::now();
|
||||
modified.checked_add(TIME_GRAIN).filter(|t| *t <= now).map(|_| modified)
|
||||
}
|
||||
|
||||
/// The files below folder `root` that `keep` accepts. Hidden entries (names starting with `.`)
|
||||
/// are left out, the folder `skip` (e.g. the library's own) is never entered, and the walk stops
|
||||
@@ -123,7 +138,13 @@ pub fn files_in_entering(
|
||||
/// find its files has, with that, the answer to "is this name there" for everything in it, and
|
||||
/// need not ask the disk again (a round trip for each name on a network share).
|
||||
pub fn files_in_noting(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool, note: NoteFolder) -> Walked {
|
||||
walk(root, skip, limits, keep, |_| true, Some(note))
|
||||
walk(root, skip, limits, keep, |_| true, Some((note, false)))
|
||||
}
|
||||
|
||||
/// [`files_in_noting`], also reading each folder's modification time (before it is listed; a round
|
||||
/// trip on a network share) and handing it over when it is old enough to show a later change.
|
||||
pub fn files_in_noting_timed(root: &Path, skip: Option<&Path>, limits: Limits, keep: impl FnMut(&Path) -> bool, note: NoteFolder) -> Walked {
|
||||
walk(root, skip, limits, keep, |_| true, Some((note, true)))
|
||||
}
|
||||
|
||||
fn walk(
|
||||
@@ -132,7 +153,7 @@ fn walk(
|
||||
limits: Limits,
|
||||
mut keep: impl FnMut(&Path) -> bool,
|
||||
mut enter: impl FnMut(&Path) -> bool,
|
||||
mut note: Option<NoteFolder>,
|
||||
mut note: Option<(NoteFolder, bool)>,
|
||||
) -> Walked {
|
||||
let mut out = Walked::default();
|
||||
// canonical folders reached through a link, so a link loop is walked at most once
|
||||
@@ -160,6 +181,7 @@ fn walk(
|
||||
out.truncated = true;
|
||||
continue;
|
||||
}
|
||||
let modified = if note.as_ref().is_some_and(|n| n.1) { settled_time(&path) } else { None };
|
||||
let Ok(rd) = std::fs::read_dir(&path) else {
|
||||
out.unreadable = out.unreadable.saturating_add(1);
|
||||
continue;
|
||||
@@ -227,8 +249,8 @@ fn walk(
|
||||
};
|
||||
children.push((p, dir));
|
||||
}
|
||||
if let (Some(note), Some(listed)) = (note.as_mut(), listed)
|
||||
&& !note(&path, listed, complete)
|
||||
if let (Some((note, _)), Some(listed)) = (note.as_mut(), listed)
|
||||
&& !note(&path, listed, complete, modified)
|
||||
{
|
||||
break;
|
||||
}
|
||||
@@ -292,7 +314,7 @@ mod tests {
|
||||
#[cfg(unix)]
|
||||
std::os::unix::fs::symlink(root.join("a.jpg"), root.join("link.jpg")).unwrap();
|
||||
let mut noted: Vec<(PathBuf, Vec<(String, EntryKind)>, bool)> = Vec::new();
|
||||
let walked = files_in_noting(&root, None, Limits::default(), |_| true, &mut |dir, entries, complete| {
|
||||
let walked = files_in_noting(&root, None, Limits::default(), |_| true, &mut |dir, entries, complete, _| {
|
||||
let mut entries: Vec<(String, EntryKind)> = entries.into_iter().map(|(n, k)| (n.to_string_lossy().to_string(), k)).collect();
|
||||
entries.sort_by(|a, b| a.0.cmp(&b.0));
|
||||
noted.push((dir.to_path_buf(), entries, complete));
|
||||
@@ -308,7 +330,7 @@ mod tests {
|
||||
|
||||
// stopped inside the first folder: its listing is not all of it
|
||||
let mut cut = Vec::new();
|
||||
let walked = files_in_noting(&root, None, Limits { max_depth: 8, max_entries: 2 }, |_| true, &mut |dir, entries, complete| {
|
||||
let walked = files_in_noting(&root, None, Limits { max_depth: 8, max_entries: 2 }, |_| true, &mut |dir, entries, complete, _| {
|
||||
cut.push((dir.to_path_buf(), entries.len(), complete));
|
||||
true
|
||||
});
|
||||
|
||||
@@ -115,6 +115,7 @@ impl LightcraftApp {
|
||||
scan: None,
|
||||
scans_stopping: Default::default(),
|
||||
waiting_import: Default::default(),
|
||||
review_listed: None,
|
||||
sync: None,
|
||||
sync_owns_changes: false,
|
||||
sync_run: None,
|
||||
@@ -122,6 +123,7 @@ impl LightcraftApp {
|
||||
lightroom_last: None,
|
||||
lightroom_result: None,
|
||||
review_pending: None,
|
||||
review_pending_listed: None,
|
||||
shown_library: None,
|
||||
export: None,
|
||||
tasks: Default::default(),
|
||||
|
||||
@@ -466,6 +466,7 @@ pub fn handle(app: &mut LightcraftApp, ctx: &egui::Context, req: &ControlRequest
|
||||
"ui.dialog.cancel" => {
|
||||
if matches!(app.ui.dialog, Some(crate::state::Dialog::Import { .. })) {
|
||||
app.renderer.forget_imports();
|
||||
app.review_listed = None;
|
||||
}
|
||||
app.ui.dialog = None;
|
||||
ok(Value::Null)
|
||||
|
||||
@@ -397,8 +397,10 @@ pub fn show(app: &mut LightcraftApp, ctx: &egui::Context, blocked: bool) {
|
||||
let frame = ctx.cumulative_frame_nr();
|
||||
ctx.data_mut(|d| d.insert_temp(egui::Id::unique(BACKDROP_SHOWN), frame));
|
||||
}
|
||||
// a review closed without importing (Cancel, Esc) leaves no listing behind (OK took it already)
|
||||
if close && matches!(dlg, Dialog::Import { .. }) {
|
||||
app.renderer.forget_imports();
|
||||
app.review_listed = None;
|
||||
}
|
||||
app.ui.dialog = if close { None } else { Some(dlg) };
|
||||
}
|
||||
|
||||
@@ -239,12 +239,15 @@ pub fn browse(app: &mut LightcraftApp, path: &str, subfolders: Option<bool>) ->
|
||||
let candidates =
|
||||
queue.iter().cloned().map(|path| lightcraft_engine::import::ImportCandidate { path, ..Default::default() }).chain(known).collect();
|
||||
// the probes of earlier scans go back to the session with the result, for the import that follows
|
||||
// (a browse imports nothing from a review, so no folder listing goes with it)
|
||||
let listed = lightcraft_engine::import::ListedFolders::default();
|
||||
let _ = tx.send(ScanEnd::Done(lightcraft_engine::import::ScanOutput {
|
||||
candidates,
|
||||
probes: input.take_probes(),
|
||||
truncated: false,
|
||||
unreadable: 0,
|
||||
unsupported: 0,
|
||||
listed,
|
||||
}));
|
||||
};
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
@@ -393,6 +396,7 @@ pub fn poll_scan(app: &mut LightcraftApp, ctx: &egui::Context) {
|
||||
d.album = task.album.filter(|id| app.session.catalog.album(lightcraft_catalog::AlbumId(*id)).is_some_and(|a| !a.folder && !a.is_smart()));
|
||||
d.sources = task.sources;
|
||||
d.library = Some(app.session.library_generation());
|
||||
app.review_pending_listed = Some(out.listed);
|
||||
app.review_pending = Some(crate::state::Dialog::Import { opts: Box::new(d) });
|
||||
show_pending_review(app, ctx);
|
||||
}
|
||||
@@ -408,10 +412,12 @@ fn show_pending_review(app: &mut LightcraftApp, ctx: &egui::Context) {
|
||||
&& !opts.in_library(app)
|
||||
{
|
||||
app.review_pending = None;
|
||||
app.review_pending_listed = None;
|
||||
return;
|
||||
}
|
||||
if app.ui.dialog.is_none() {
|
||||
app.ui.dialog = app.review_pending.take();
|
||||
app.review_listed = app.review_pending_listed.take();
|
||||
} else {
|
||||
ctx.request_repaint_after(std::time::Duration::from_millis(100));
|
||||
}
|
||||
|
||||
@@ -17,6 +17,8 @@ pub struct ImportTask {
|
||||
pub total: usize,
|
||||
pub done: usize,
|
||||
pub(super) params: Value,
|
||||
/// What the review that started this import listed, for its job.
|
||||
listed: Option<lightcraft_engine::import::ListedFolders>,
|
||||
pub imported: usize,
|
||||
/// Brought back from Recently Deleted (`onDeleted: restore`).
|
||||
pub restored: usize,
|
||||
@@ -261,7 +263,9 @@ pub fn start(app: &mut LightcraftApp, d: &ImportDialog) -> Result<Value, String>
|
||||
}
|
||||
}
|
||||
let total = queue.len();
|
||||
app.import = Some(ImportTask::new(queue, params, undo0, false));
|
||||
let mut task = ImportTask::new(queue, params, undo0, false);
|
||||
task.listed = app.review_listed.take();
|
||||
app.import = Some(task);
|
||||
app.renderer.forget_imports();
|
||||
Ok(json!({"importing": total}))
|
||||
}
|
||||
@@ -287,6 +291,16 @@ pub fn tick(app: &mut LightcraftApp, ctx: &egui::Context) {
|
||||
p["paths"] = json!(task.queue);
|
||||
let started = lightcraft_engine::cmd::library::import_params(&app.session, &p)
|
||||
.and_then(|req| Ok((lightcraft_engine::import::ImportJob::new(&mut app.session, req.opts)?, req.album, req.album_name)))
|
||||
.map(|(job, album, name)| {
|
||||
(
|
||||
match task.listed.take() {
|
||||
Some(l) => job.with_listed(l),
|
||||
None => job,
|
||||
},
|
||||
album,
|
||||
name,
|
||||
)
|
||||
})
|
||||
.map_err(|e| e.to_string())
|
||||
.and_then(|(job, album, name)| ImportRun::start(job, std::mem::take(&mut task.queue), album, name, ctx));
|
||||
if task.auto {
|
||||
|
||||
@@ -3695,6 +3695,98 @@ fn import_review_dialog() {
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// Set a folder's modification time (Windows opens a folder for attributes, with backup semantics).
|
||||
fn set_folder_time(dir: &std::path::Path, at: std::time::SystemTime) {
|
||||
#[cfg(windows)]
|
||||
let handle = {
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
std::fs::OpenOptions::new().write(true).access_mode(0x100).custom_flags(0x0200_0000).open(dir)
|
||||
};
|
||||
#[cfg(not(windows))]
|
||||
let handle = std::fs::File::open(dir);
|
||||
handle.unwrap().set_modified(at).unwrap();
|
||||
}
|
||||
|
||||
/// A review's listing belongs to the import that review starts. Given a review that was
|
||||
/// cancelled, when a sidecar appears in its folder (the folder's time put back as it was, as a
|
||||
/// volume with coarse folder times would show it) and its file is imported another way (a folder
|
||||
/// given by name is walked afresh, so only a named file could meet the old listing),
|
||||
/// then the sidecar is read.
|
||||
#[test]
|
||||
fn a_cancelled_reviews_listing_is_not_used_by_another_import() {
|
||||
let dir = std::env::temp_dir().join(format!("lc-ui-import-cancelled-review-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[9, 9, 9, 255]; 64] };
|
||||
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();
|
||||
std::fs::write(dir.join("a.png"), png).unwrap();
|
||||
// (old enough for the scan to vouch for the folder's time)
|
||||
set_folder_time(&dir, std::time::SystemTime::now() - Duration::from_secs(3600));
|
||||
let services = crate::Services { png: None, ..Default::default() };
|
||||
let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), services), [1300.0, 900.0], 1.0);
|
||||
let t = Duration::from_secs(10);
|
||||
let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [dir.to_string_lossy()]}}), t);
|
||||
assert_eq!(r["result"]["scanning"], true, "{r}");
|
||||
h.settle(SETTLE);
|
||||
h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. })));
|
||||
assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. })), "the review is open");
|
||||
assert!(h.app.review_listed.is_some(), "the review holds its listing");
|
||||
h.request("ui.dialog.cancel", json!({}), t);
|
||||
assert!(h.app.review_listed.is_none(), "cancelling the review drops the listing");
|
||||
let was = std::fs::metadata(&dir).unwrap().modified().unwrap();
|
||||
std::fs::write(
|
||||
dir.join("a.xmp"),
|
||||
r#"<x:xmpmeta xmlns:x="adobe:ns:meta/"><rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"><rdf:Description rdf:about="" xmlns:xmp="http://ns.adobe.com/xap/1.0/" xmp:Rating="4"/></rdf:RDF></x:xmpmeta>"#,
|
||||
)
|
||||
.unwrap();
|
||||
set_folder_time(&dir, was);
|
||||
let r = h.request("engine.execute", json!({"command": "library.import", "params": {"paths": [dir.join("a.png").to_string_lossy()]}}), t);
|
||||
assert_eq!(r["ok"], true, "{r}");
|
||||
h.settle(SETTLE);
|
||||
let p = h.app.session.catalog.photos().find(|p| p.file_name == "a.png").expect("imported");
|
||||
assert_eq!(p.rating, 4, "the sidecar that appeared after the review is read");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
/// A review waiting behind the open one keeps its own listing. Given a review that is open, when
|
||||
/// another scan finishes (it waits for the dialog to close), then the open review still holds the
|
||||
/// folders its own scan listed, and the waiting one's are kept for when it opens.
|
||||
#[test]
|
||||
fn a_waiting_reviews_listing_does_not_replace_the_open_ones() {
|
||||
let make = |tag: &str| {
|
||||
let dir = std::env::temp_dir().join(format!("lc-ui-import-waiting-{tag}-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let img = lightcraft_raster::Rgba8 { width: 8, height: 8, data: vec![[9, 9, 9, 255]; 64] };
|
||||
let png = lightcraft_codecs::encode_png(&lightcraft_codecs::EncodeImage::rgba8(&img), &lightcraft_codecs::EncodeMeta::default()).unwrap();
|
||||
std::fs::write(dir.join("a.png"), png).unwrap();
|
||||
set_folder_time(&dir, std::time::SystemTime::now() - Duration::from_secs(3600));
|
||||
dir
|
||||
};
|
||||
let (first, second) = (make("first"), make("second"));
|
||||
let services = crate::Services { png: None, ..Default::default() };
|
||||
let mut h = Headless::new(LightcraftApp::new(lightcraft_engine::Session::with_demo().with_fs(), services), [1300.0, 900.0], 1.0);
|
||||
let t = Duration::from_secs(10);
|
||||
let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [first.to_string_lossy()]}}), t);
|
||||
assert_eq!(r["result"]["scanning"], true, "{r}");
|
||||
h.step_until(SETTLE, |h| matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. })));
|
||||
let listed = |h: &Headless| format!("{:?}", h.app.review_listed);
|
||||
assert!(listed(&h).contains("-first-"), "the open review holds its own listing: {}", listed(&h));
|
||||
let r = h.request("engine.execute", json!({"command": "file.addPhotos", "params": {"paths": [second.to_string_lossy()]}}), t);
|
||||
assert_eq!(r["result"]["scanning"], true, "{r}");
|
||||
h.step_until(SETTLE, |h| h.app.scan.is_none());
|
||||
h.settle(SETTLE);
|
||||
assert!(h.app.review_pending.is_some(), "the second review waits behind the open one");
|
||||
assert!(listed(&h).contains("-first-") && !listed(&h).contains("-second-"), "the open review keeps its listing: {}", listed(&h));
|
||||
// cancelled, the first review makes room for the waiting one, which brings its own listing
|
||||
h.request("ui.dialog.cancel", json!({}), t);
|
||||
h.step_until(SETTLE, |h| h.app.review_pending.is_none());
|
||||
assert!(matches!(h.app.ui.dialog, Some(crate::state::Dialog::Import { .. })), "the waiting review opens");
|
||||
assert!(listed(&h).contains("-second-") && !listed(&h).contains("-first-"), "it holds its own listing: {}", listed(&h));
|
||||
let _ = std::fs::remove_dir_all(&first);
|
||||
let _ = std::fs::remove_dir_all(&second);
|
||||
}
|
||||
|
||||
/// The import review offers what to do with files that are in Recently Deleted (issues #298,
|
||||
/// #706): they are checked, to be restored, by default; Leave them unchecks them; confirming
|
||||
/// restores the photo (with its edits) or, with Import as new, imports the file afresh.
|
||||
|
||||
@@ -339,6 +339,8 @@ pub struct LightcraftApp {
|
||||
pub(crate) scans_stopping: import::StoppingScans,
|
||||
/// Files that waited for a library and wait for the running import or Synchronize Folder too.
|
||||
pub waiting_import: panels::library_problem::WaitingImport,
|
||||
/// The folders the scan of the review on screen listed, for the import that review starts (and no other).
|
||||
pub review_listed: Option<lightcraft_engine::import::ListedFolders>,
|
||||
/// A Synchronize Folder scan in progress (feeds its dialog).
|
||||
pub sync: Option<sync::SyncTask>,
|
||||
/// `session.folder_changes` came from the Synchronize Folder dialog (and goes with it).
|
||||
@@ -353,6 +355,8 @@ pub struct LightcraftApp {
|
||||
pub(crate) lightroom_result: Option<state::Dialog>,
|
||||
/// The import review of a finished scan, waiting for another dialog to close.
|
||||
pub(crate) review_pending: Option<state::Dialog>,
|
||||
/// The folders that review's scan listed; they become [`Self::review_listed`] when the review opens.
|
||||
pub(crate) review_pending_listed: Option<lightcraft_engine::import::ListedFolders>,
|
||||
/// The library generation the window title and the recent list were last updated for.
|
||||
pub shown_library: Option<u64>,
|
||||
/// A background export in progress.
|
||||
|
||||
@@ -1230,6 +1230,7 @@ fn auto_import_waits_for_a_browse_that_starts_during_its_listing() {
|
||||
truncated: false,
|
||||
unreadable: 0,
|
||||
unsupported: 0,
|
||||
listed: Default::default(),
|
||||
}))
|
||||
.unwrap();
|
||||
drop(tx);
|
||||
|
||||
@@ -74,6 +74,7 @@ fn a_scan_closed_with_its_cross_hands_back_its_probes_when_the_worker_ends() {
|
||||
truncated: false,
|
||||
unreadable: 0,
|
||||
unsupported: 0,
|
||||
listed: Default::default(),
|
||||
}))
|
||||
.unwrap();
|
||||
assert!(h.step_until(T, kept), "the probes came back");
|
||||
|
||||
@@ -472,6 +472,19 @@
|
||||
Denoise ▸ Run on chooses; Automatic times both). Photos
|
||||
denoised before are denoised again the next time they are needed. See [AI Denoise](denoise.md).
|
||||
|
||||
### Imports and moves on a network share ask it less
|
||||
- Import no longer asks a network share about each photo's `.xmp` sidecar (up to nine names, each a round trip) when
|
||||
the folder's listing, which the import or the Add Photos review has already read, shows there is none. A sidecar in
|
||||
any letter case (`.xmp`, `.XMP`, `.Xmp`, or `<file name>.xmp`) is still found and read. A folder that changed since
|
||||
it was listed, or was too recently changed to tell, is asked about photo by photo. For the folders that have not
|
||||
changed since the review listed them, importing the photos picked in the review also stops asking the share
|
||||
whether each one is a file or a folder before the first one is handled.
|
||||
- Renaming photos, moving them to another folder, and undoing either look for their sidecars in one listing of each
|
||||
folder that eight or more photos leave, instead of asking for four names per photo. Sidecars the listing shows
|
||||
still move with their photos (`.xmp` or `.XMP`, as before).
|
||||
- Folders that could not be listed completely or whose time can't be read, and files you add one by one, are checked
|
||||
as before.
|
||||
|
||||
### A right-click on a text field while you carry photos opens no menu
|
||||
- While you drag photos from the grid, a right-click on a text field, such as the search box, opens no Cut, Copy and
|
||||
Paste menu. Before, the menu opened over the field the photos were on. Right-clicking a field without a drag works
|
||||
|
||||
Reference in new issue
Block a user