Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions crates/engine/src/cmd/convert.rs
Original file line number Diff line number Diff line change
Expand Up @@ -207,17 +207,27 @@ fn edit_copy(s: &mut Session, p: &Value, id: lightcraft_catalog::PhotoId, opts:
/// again (see [`lightcraft_catalog::Photo::preview_checked`]).
pub(crate) fn content_op(id: lightcraft_catalog::PhotoId, ph: &lightcraft_catalog::Photo, info: crate::media::ProbeInfo) -> Option<Op> {
let preview_checked = ph.preview_stamp(&info.preview_only);
let same = info.content_hash == ph.content_hash
// (a Duplicate's hash is its original's plus a suffix: the same content)
let same = info.content_hash.as_deref().map(crate::sync::base_hash) == ph.content_hash.as_deref().map(crate::sync::base_hash)
&& info.file_size == ph.file_size
&& (info.width, info.height) == (ph.width, ph.height)
&& info.preview_only == ph.preview_only
&& preview_checked == ph.preview_checked;
(!same).then_some(Op::SetContent {
if same {
return None;
}
// A fresh byte digest replaces the old digest, not the identity of an independent copy.
let suffix = ph.content_hash.as_deref().and_then(|h| h.split_once(":dup")).map(|(_, suffix)| suffix);
let content_hash = info.content_hash.map(|h| match suffix {
Some(s) => format!("{h}:dup{s}"),
None => h,
});
Some(Op::SetContent {
id,
width: info.width,
height: info.height,
file_size: info.file_size,
content_hash: info.content_hash,
content_hash,
preview_only: info.preview_only,
preview_checked,
})
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/cmd/library/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ pub fn import_params(s: &Session, p: &Value) -> Result<ImportRequest> {
metadata_preset,
convert_dng: bool_or(p, "dng", false),
backup,
import_anyway: strs(p, "importAnyway").into_iter().collect(),
local: bool_or(p, "local", false),
// (only the Lightroom import makes records of duplicates)
read_duplicates: false,
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/library/specs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1525,7 +1525,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Import Photos",
["File"],
Some("Cmd+Shift+I"),
"{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), backup?: folder (copy or move: each file the import copies or moves is also copied here, under the same folders and name as in the destination — a mirror of it — and verified like the main copy; a bad backup copy is removed and reported, a different file already at its place is left alone and reported; must be outside the destination and not contain it; a move keeps the original of a photo with no backup copy), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, recipe?: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}] (a batch-edit recipe: each control is set to its value, clamped to the control's range, on every photo this import adds, after its sidecar, camera default and preset, as one extra History step named Import adjustments; a photo the library already has — a duplicate, one restored from Recently Deleted, one joined from a browsed folder — is not changed; a control a recipe may not name is refused before anything is imported; preset.saveRecipe keeps a recipe for reuse), keywords?: [..], onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, skipped: {unreadable, unsupported} (what the folder walk left out, as library.importPreview counts it; a file named in paths is always tried, so it is never counted here), warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), backups?: [{path, to}] (backup: the copy in the destination and its backup), backupFailed?: [{path, reason}] (backup: imported photos with no backup copy, and why), album?}",
"{paths: [file or folder (recursive)], mode?: add|copy|move (add = reference the files in place; copy = into the library's Originals/YYYY/YYYY-MM-DD/; move = as copy, then each original and its XMP sidecars are removed from the source — only after the copy is verified (a hard link on the same volume, else copied, synced and compared byte for byte) and its catalog record is saved; failed, duplicate and unchecked files keep their sources; a taken name gets -1, -2…; undo removes the photos from the library but leaves the files at the destination), destination?: folder for copies / moves, organize?: date (YYYY/YYYY-MM-DD) | month (YYYY/YYYY-MM) | flat | a folder template, e.g. `{date:%Y}/{date:%Y%m%d}` → 2026/20260114 (the template's `/` make the folders, each level expanded with the rename tokens and made a safe folder name: never outside the destination; must be relative, no `..`; a level with missing metadata is `unknown`) — dated by capture time, else the import time, rename?: file-name template for copies, original extension added (tokens: {name} {num} {seq} {seq:N} {date} {date:%Y%m%d} {folder} {camera} {lens} {iso} {rating} {title} {creator} {ext}; photo.renameTokens explains each; blank = keep names), renameStart?: 1 (must fit this platform; later files are reported failed if the sequence runs out), metadataPreset?: name, dng?: bool (copy raws as DNG; copy only), backup?: folder (copy or move: each file the import copies or moves is also copied here, under the same folders and name as in the destination — a mirror of it — and verified like the main copy; a bad backup copy is removed and reported, a different file already at its place is left alone and reported; must be outside the destination and not contain it; a move keeps the original of a photo with no backup copy), local?: bool (browsing: the photos stay out of the library, like library.browse; not with move), album?: albumId, albumName?: new album, preset?: presetId, recipe?: [{id: a plain develop control (develop.controls; no white balance, geometry or crop), value}] (a batch-edit recipe: each control is set to its value, clamped to the control's range, on every photo this import adds, after its sidecar, camera default and preset, as one extra History step named Import adjustments; a photo the library already has — a duplicate, one restored from Recently Deleted, one joined from a browsed folder — is not changed; a control a recipe may not name is refused before anything is imported; preset.saveRecipe keeps a recipe for reuse), keywords?: [..], importAnyway?: [paths] (files whose content another photo already has, imported as new photos anyway; a file already in the library from the same path never is; they count in `importedAnyway`), onDeleted?: restore|skip|fresh (a file that is in Recently Deleted: restore (default) = bring the photo back with its edits — relinked to the file when its own is gone, skip = leave it there and say so, fresh = delete the trashed record and import the file as new)} → {imported, importedAnyway?, duplicates: [{path, existing, reason, existingDeleted?}], restored?: [photoId], failed, skipped: {unreadable, unsupported} (what the folder walk left out, as library.importPreview counts it; a file named in paths is always tried, so it is never counted here), warnings?: [{path, code: cameraProfile|uprightGeometry|unmappedXmp, profile?, mode?: off|auto|level|vertical|full|guided|unknown, fields?}], moved?: [{from, to, sidecars?}], kept?: [{path, reason}] (move: sources left in place and why), backups?: [{path, to}] (backup: the copy in the destination and its backup), backupFailed?: [{path, reason}] (backup: imported photos with no backup copy, and why), album?}",
always,
|s, p| {
let req = import_params(s, p)?;
Expand Down
4 changes: 2 additions & 2 deletions crates/engine/src/import.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,8 @@ pub use scan::{
#[cfg(test)]
use scan::{library_files, library_hashes};
pub use types::{
BackupCopy, Duplicate, FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, ImportUprightMode, ImportWarning, ImportWarningCode,
Kept, Moved, OnDeleted, Organize, Skipped,
BackupCopy, Duplicate, DuplicateCounts, FileFacts, ImportCandidate, ImportMode, ImportOptions, ImportReport, ImportUprightMode, ImportWarning,
ImportWarningCode, Kept, Moved, OnDeleted, Organize, Skipped,
};

mod listed_folders;
Expand Down
132 changes: 98 additions & 34 deletions crates/engine/src/import/commit.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
use std::collections::HashSet;

use super::defaults::apply_import_defaults;
use super::files::copy_into;
use super::job::{Prepared, PreparedItem, ReadyFile};
use super::job::{Prepared, PreparedItem, ReadyFile, normalize_import_path};
use super::types::{BackupCopy, Duplicate, FileFacts, ImportOptions, ImportReport, Kept, Moved, OnDeleted};
use super::{HashMap, Op, Path, PathBuf, Photo, PhotoId, ProbeInfo, Session, Source};

Expand Down Expand Up @@ -212,6 +214,21 @@ fn back_up(
Ok(copy.to_string_lossy().to_string())
}

/// The library's photos by base content hash (a Duplicate's `:dup<id>` dropped), built once per
/// commit for the files ticked to import anyway (`wanted`) instead of a catalog scan per file.
fn photos_by_base_hash(cat: &lightcraft_catalog::Catalog, wanted: bool) -> HashMap<String, Vec<PhotoId>> {
let mut by_base: HashMap<String, Vec<PhotoId>> = HashMap::new();
if !wanted {
return by_base;
}
for p in cat.photos().filter(|p| !p.local || p.deleted) {
if let Some(h) = &p.content_hash {
by_base.entry(crate::sync::base_hash(h).to_string()).or_default().push(p.id);
}
}
by_base
}

/// A trashed photo's file is not where the library had it (never on the web, where paths are
/// storage keys, not files).
fn trashed_file_is_gone(cat: &lightcraft_catalog::Catalog, id: PhotoId) -> bool {
Expand Down Expand Up @@ -254,33 +271,75 @@ impl Session {
}
}

/// Trashed photos an import set to Fresh replaces, in the order matched, each removed once.
#[derive(Default)]
struct FreshTrash {
by_hash: HashMap<String, Vec<PhotoId>>,
by_path: HashMap<String, PhotoId>,
ids: Vec<PhotoId>,
purged: HashSet<PhotoId>,
}

impl FreshTrash {
fn new(cat: &lightcraft_catalog::Catalog, on_deleted: OnDeleted) -> Self {
let mut trash = Self::default();
if on_deleted == OnDeleted::Fresh {
for p in cat.photos().filter(|p| p.deleted) {
if let Some(h) = &p.content_hash {
trash.by_hash.entry(crate::sync::base_hash(h).to_string()).or_default().push(p.id);
}
if let Source::File { path } = &p.source {
trash.by_path.insert(path.clone(), p.id);
}
}
}
trash
}

fn match_photo(&mut self, hash: Option<&str>, path: Option<&str>) {
let content = hash.and_then(|h| self.by_hash.remove(crate::sync::base_hash(h)));
let file = path.and_then(|p| self.by_path.remove(p));
self.ids.extend(content.into_iter().flatten().chain(file).filter(|old| self.purged.insert(*old)));
}
}

/// A hand-ticked content duplicate gets a distinct hash so it isn't mistaken for the first copy.
fn import_content_hash(
id: PhotoId,
path: &str,
mut hash: Option<String>,
anyway: &HashSet<String>,
new_hash: &HashMap<String, PhotoId>,
by_base: &HashMap<String, Vec<PhotoId>>,
purged: &HashSet<PhotoId>,
) -> (Option<String>, bool) {
if anyway.contains(&normalize_import_path(path))
&& let Some(h) = &mut hash
&& (new_hash.get(h.as_str()).is_some_and(|first| *first != id)
|| by_base.get(h.as_str()).is_some_and(|ids| ids.iter().any(|p| !purged.contains(p))))
{
*h = format!("{h}:dup{}", id.0);
return (hash, true);
}
(hash, false)
}

/// The catalog half of an import: add the photos [`ImportJob::prepare`] readied (one undoable op;
/// a Move's sources are removed once it is saved). On a failed commit a Move's placed files are
/// taken back.
pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepared: Prepared) -> crate::Result<ImportReport> {
let now = now.to_string();
let mut report = ImportReport { scanned: prepared.scanned, skipped: prepared.skipped, ..Default::default() };
let mut default_denoiser = None;
let anyway = prepared.anyway;
let mut ops = Vec::new();
// Move: placed at the destination, sources untouched until the records are committed
// (with its backup: where it was made, or why it wasn't, so the source stays)
let mut placed: Vec<(crate::import_move::Placed, Option<Result<PathBuf, String>>)> = Vec::new();
// photos added by this batch, by content (a duplicate of a file earlier in the import names it)
let mut new_hash: HashMap<String, PhotoId> = HashMap::new();
// Fresh: trashed photos a new import replaces (by content or by file), each removed once
let (mut trash_hash, mut trash_path): (HashMap<String, PhotoId>, HashMap<String, PhotoId>) = Default::default();
if opts.on_deleted == OnDeleted::Fresh {
for p in s.catalog.photos().filter(|p| p.deleted) {
if let Some(h) = &p.content_hash {
trash_hash.insert(h.clone(), p.id);
}
if let Source::File { path } = &p.source {
trash_path.insert(path.clone(), p.id);
}
}
}
let mut purge: Vec<PhotoId> = Vec::new();
let mut purged: std::collections::HashSet<PhotoId> = Default::default();
let mut trash = FreshTrash::new(&s.catalog, opts.on_deleted);
let by_base = photos_by_base_hash(&s.catalog, !anyway.is_empty());
for it in prepared.items {
match it {
PreparedItem::Promote(id, fresh) => {
Expand All @@ -295,20 +354,26 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
// "Import as new": a trashed photo with the same content is replaced, as for a new file
let content =
fresh.as_ref().and_then(|i| i.content_hash.clone()).or_else(|| s.catalog.photo(id).and_then(|p| p.content_hash.clone()));
if let Some(old) = content.as_ref().and_then(|h| trash_hash.get(h))
&& purged.insert(*old)
{
purge.push(*old);
}
trash.match_photo(content.as_deref(), None);
report.imported.push(id.0);
}
PreparedItem::Duplicate { path, existing, reason, hash, file } => {
let existing = existing.or_else(|| {
let h = hash?;
new_hash
.get(&h)
.copied()
.or_else(|| s.catalog.photos().find(|p| !p.local && p.content_hash.as_deref() == Some(h.as_str())).map(|p| p.id))
let hash = hash?;
let h = crate::sync::base_hash(&hash);
new_hash.get(h).copied().or_else(|| {
let mut suffixed = None;
for p in s.catalog.photos().filter(|p| !p.local) {
let Some(stored) = p.content_hash.as_deref() else { continue };
if stored == h {
return Some(p.id);
}
if suffixed.is_none() && crate::sync::base_hash(stored) == h {
suffixed = Some(p.id);
}
}
suffixed
})
});
let trashed = existing.filter(|id| s.catalog.photo(*id).is_some_and(|p| p.deleted));
match trashed {
Expand Down Expand Up @@ -341,20 +406,19 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
placed.extend(pl.map(|p| (p, backed_up)));
let id = s.catalog.alloc_photo_id();
if let Some(h) = &info.content_hash {
new_hash.insert(h.clone(), id);
}
for old in info.content_hash.as_ref().and_then(|h| trash_hash.get(h)).into_iter().chain(trash_path.get(&stored)) {
if purged.insert(*old) {
purge.push(*old);
}
new_hash.entry(h.clone()).or_insert(id);
}
trash.match_photo(info.content_hash.as_deref(), Some(&stored));
let (hash, forced) = import_content_hash(id, &path, info.content_hash, &anyway, &new_hash, &by_base, &trash.purged);
report.imported_anyway += usize::from(forced);

// a copy is catalogued under its new name
let name = Path::new(&stored).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_else(|| path.clone());
let mut p = Photo::new(id, Source::File { path: stored }, &name, &info.format, info.width, info.height, &now);
p.kind = info.kind;
p.file_size = info.file_size;
p.as_shot_wb = info.as_shot_wb;
p.content_hash = info.content_hash;
p.content_hash = hash;
p.embedded_lens = info.embedded_lens.map(Box::new);
p.set_preview_only(info.preview_only.clone());
if let Some(sc) =
Expand Down Expand Up @@ -407,8 +471,8 @@ pub fn commit_prepared(s: &mut Session, opts: &ImportOptions, now: &str, prepare
}
}
// (built against the catalog as it is: one op list for all of them, ahead of the additions)
if !purge.is_empty() {
ops.insert(0, s.catalog.delete_photos_permanently_ops(&purge));
if !trash.ids.is_empty() {
ops.insert(0, s.catalog.delete_photos_permanently_ops(&trash.ids));
}
let log0 = s.pending_log.len();
let (verb, n) = if report.imported.is_empty() && !report.restored.is_empty() {
Expand Down
Loading
Loading