Skip to content

LightCraft: An open-source non-destructive photo editor written by scratch in pure Rust

Synchronize Folder: one undo step with a full history; partial failures reported (review fixes)

Nathaniel Ledfordf9d4892c2315
diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs
index 02c3cd9c1..5607bda49 100644
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@ -167,6 +167,9 @@ pub struct Session {
/// Photos in the current source with no filter on (cached like `visible`).
total: Option<((u64, String), usize)>,
pub undo: Vec<UndoEntry>,
+ /// Undo steps committed in this session, ever (the history drops its oldest past 1000, so
+ /// its length can't tell how many steps a command just made; see [`Session::commits`]).
+ commits: u64,
pub redo: Vec<UndoEntry>,
pub interaction: Option<Interaction>,
/// Set by a command whose change must not rewrite the photo's XMP sidecar even with auto-write on
@@ -294,6 +297,7 @@ impl Session {
visible_gen: 0,
total: None,
undo: Vec::new(),
+ commits: 0,
redo: Vec::new(),
interaction: None,
skip_auto_write: false,
@@ -427,6 +431,7 @@ impl Session {
let inv = self.catalog.apply(op)?;
self.pending_log.push(fwd);
self.undo.push(UndoEntry { label: label.to_string(), op: inv, folder: None });
+ self.commits = self.commits.wrapping_add(1);
if self.undo.len() > 1000 {
self.undo.remove(0);
}
@@ -491,6 +496,12 @@ impl Session {
/// Fold the last `n` undo steps into one (commands that commit step by step because each op
/// depends on the state the previous one left).
+ /// How many undo steps were committed in this session so far: what a command that commits
+ /// several steps compares before and after to merge them ([`Session::merge_undo`]).
+ pub fn commits(&self) -> u64 {
+ self.commits
+ }
+
pub fn merge_undo(&mut self, n: usize, label: &str) {
if n < 2 || n > self.undo.len() {
return;
diff --git a/crates/engine/src/sync.rs b/crates/engine/src/sync.rs
index 602296049..0b5cc73db 100644
--- a/crates/engine/src/sync.rs
+++ b/crates/engine/src/sync.rs
@@ -323,12 +323,13 @@ fn sidecar_has_news(labels: &Catalog, p: &Photo, naming: SidecarNaming) -> bool
}
/// Act on `changes` as `choice` says, as one undo step ("Synchronize Folder"). A missing photo
-/// whose file is back by now is left alone.
+/// whose file is back by now is left alone. Once the import is in, a part that fails is
+/// reported in `failed` and the rest is still done (and still one step).
pub fn synchronize(s: &mut Session, changes: FolderChanges, choice: SyncChoice) -> Result<SyncReport> {
if changes.offline {
return Err(not_there(&changes.path));
}
- let mark = s.undo.len();
+ let mark = s.commits();
let mut report = SyncReport::default();
let FolderChanges { new, missing, metadata, moved, probes, .. } = changes;
if choice.import_new && !new.is_empty() {
@@ -346,8 +347,11 @@ pub fn synchronize(s: &mut Session, changes: FolderChanges, choice: SyncChoice)
.map(|m| crate::cmd::missing::relink_op(PhotoId(m.id), &m.to))
.collect();
if !ops.is_empty() {
- report.relinked = ops.len();
- s.commit("Relink Moved Photos", Op::Batch { ops })?;
+ let n = ops.len();
+ match s.commit("Relink Moved Photos", Op::Batch { ops }) {
+ Ok(()) => report.relinked = n,
+ Err(e) => report.failed.push((String::new(), e.to_string())),
+ }
}
}
if choice.remove_missing {
@@ -358,8 +362,11 @@ pub fn synchronize(s: &mut Session, changes: FolderChanges, choice: SyncChoice)
.map(|id| Op::SetDeleted { id: *id, deleted: true })
.collect();
if !ops.is_empty() {
- report.removed = ops.len();
- s.commit("Remove Missing Photos", Op::Batch { ops })?;
+ let n = ops.len();
+ match s.commit("Remove Missing Photos", Op::Batch { ops }) {
+ Ok(()) => report.removed = n,
+ Err(e) => report.failed.push((String::new(), e.to_string())),
+ }
}
}
if choice.read_metadata {
@@ -374,11 +381,15 @@ pub fn synchronize(s: &mut Session, changes: FolderChanges, choice: SyncChoice)
Err(e) => report.failed.push((m.path.clone(), e.to_string())),
}
}
- if !ops.is_empty() {
- s.commit("Read Metadata from File", Op::Batch { ops })?;
+ if !ops.is_empty()
+ && let Err(e) = s.commit("Read Metadata from File", Op::Batch { ops })
+ {
+ report.read = 0;
+ report.failed.push((String::new(), e.to_string()));
}
}
- let steps = s.undo.len().saturating_sub(mark);
+ // (what was done stays one step even when a later part failed: the report says which)
+ let steps = usize::try_from(s.commits().wrapping_sub(mark)).unwrap_or(usize::MAX).min(s.undo.len());
s.merge_undo(steps, "Synchronize Folder");
if let Some(last) = s.undo.last_mut().filter(|_| steps == 1) {
last.label = "Synchronize Folder".into();
diff --git a/crates/engine/src/tests_sync.rs b/crates/engine/src/tests_sync.rs
index daebda739..411ded3ab 100644
--- a/crates/engine/src/tests_sync.rs
+++ b/crates/engine/src/tests_sync.rs
@@ -342,3 +342,22 @@ fn a_file_renamed_or_moved_inside_the_folder_is_relinked_not_lost() {
s.execute("edit.undo", &json!({})).unwrap();
assert_eq!(s.catalog.photo(a).unwrap().source, lightcraft_catalog::Source::File { path: dir.path("trip/a.png") });
}
+
+#[test]
+fn synchronizing_is_one_undo_step_even_with_a_full_undo_history() {
+ let dir = Scratch::new("full-undo");
+ let mut s = library(&dir);
+ let a = s.catalog.photos().find(|p| p.file_name == "a.png").unwrap().id;
+ // a long session: the history is at its limit and drops its oldest steps
+ for i in 0..1005u32 {
+ s.execute("photo.rate", &json!({"ids": [a.0], "rating": i % 5})).unwrap();
+ }
+ let before = holdings(&s);
+ write_png(&dir.path("trip/c.png"), 3);
+ std::fs::remove_file(dir.path("trip/day1/b.png")).unwrap();
+ let r = s.execute("folder.synchronize", &json!({"path": dir.path("trip"), "removeMissing": true})).unwrap();
+ assert_eq!((r["imported"].as_u64(), r["removed"].as_u64()), (Some(1), Some(1)), "{r}");
+ let undo = s.execute("edit.undo", &json!({})).unwrap();
+ assert_eq!(undo["undone"], "Synchronize Folder");
+ assert_eq!(holdings(&s), before, "one step undoes the import and the removal");
+}