Skip to content
Closed
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
93 changes: 91 additions & 2 deletions crates/engine/src/cmd/browse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -197,6 +197,15 @@ pub fn specs() -> Vec<CommandSpec> {
Ok(json!({"path": to, "relinked": n}))
}
),
cmd!(
"folder.updateLocation",
"Update Folder Location",
[],
None,
"{path, to} — folder (or disk) `path` of the library is now at folder `to`: it was moved or renamed outside LightCraft, or its disk came back at another drive letter or mount point. The photos in it and in the folders inside it are relinked to the same places under `to`, and their colour labels and a chosen folder go along; no file is touched and `path` need not exist. Refused when one folder is inside the other or a photo would land on one the library already has. One undo step → {path, to, relinked}",
always,
update_location
),
cmd!(
"folder.create",
"New Folder on Disk",
Expand Down Expand Up @@ -303,6 +312,86 @@ fn folder_param<'a>(p: &'a Value, key: &str) -> Option<&'a str> {
str_param(p, key).map(|x| x.trim_end_matches(['/', '\\'])).filter(|x| !x.is_empty())
}

/// `folder.updateLocation`: the library's folder `path` is now at `to` (Lightroom Classic's Update
/// Folder Location). Like Rename / Move Folder without touching the disk: the photos at or below
/// `path` are relinked to the same names below `to`, the folder records follow, and undo and redo
/// take the chosen folder along. Folders are compared by identity ([`folder_key`]), so `path` may
/// be spelled with either separator, and a folder whose name only changed case
/// (`/Volumes/tokyo` → `/Volumes/TOKYO`) can be pointed at its new spelling.
///
/// [`folder_key`]: lightcraft_catalog::query::folder_key
fn update_location(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "folder.updateLocation";
use lightcraft_catalog::query::{folder_key, folder_rest, folder_within};
let from = folder_param(p, "path").ok_or_else(|| bad(C, "missing path"))?.to_string();
let to_param = str_param(p, "to").map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| bad(C, "missing to"))?;
// joined onto as given (absolute): trimming `E:\` to `E:` would make `E:Photos` on Windows
let dest = std::path::absolute(to_param).map_err(|e| bad(C, format!("{to_param}: {e}")))?;
if !dest.is_dir() {
return Err(bad(C, format!("{to_param} is not a folder")));
}
let to = dest.to_string_lossy().trim_end_matches(['/', '\\']).to_string();
let to = if to.is_empty() { dest.to_string_lossy().to_string() } else { to };
if from == to {
return Ok(json!({"path": from, "to": to, "relinked": 0}));
}
// a case-only change (`tokyo` → `TOKYO`) is one folder on Windows and still worth spelling anew
if folder_key(&from) != folder_key(&to) && (folder_within(&to, &from) || folder_within(&from, &to)) {
return Err(bad(C, format!("{to} and {from} are inside one another: choose the folder's new place itself")));
}
if s.library.as_ref().is_some_and(|l| {
let dir = l.dir.to_string_lossy();
folder_within(&dir, &from) || folder_within(&from, &dir)
}) {
return Err(bad(C, "the library's own folders can't be relinked"));
}
let moved: Vec<(PhotoId, String, String)> = s
.catalog
.photos()
.filter_map(|ph| match &ph.source {
lightcraft_catalog::Source::File { path } => folder_rest(path, &from).map(|rest| {
let np = rest.iter().fold(dest.clone(), |d, name| d.join(name));
(ph.id, ph.file_name.clone(), np.to_string_lossy().to_string())
}),
_ => None,
})
.collect();
let records = s.catalog.folder_records_follow(&from, &to);
if moved.is_empty() && records.is_empty() {
return Err(bad(C, format!("the library has no photos in {from}")));
}
// never two photos of the library for one file: one already at a new place refuses the step
let moving: std::collections::HashSet<PhotoId> = moved.iter().map(|m| m.0).collect();
let mut taken: std::collections::HashMap<String, &str> = std::collections::HashMap::new();
for ph in s.catalog.photos().filter(|ph| !moving.contains(&ph.id)) {
if let lightcraft_catalog::Source::File { path } = &ph.source
&& folder_within(path, &to)
{
taken.insert(folder_key(path), ph.file_name.as_str());
}
}
let clashes: Vec<&str> = moved.iter().filter_map(|(_, _, np)| taken.get(&folder_key(np)).copied()).take(5).collect();
if !clashes.is_empty() {
return Err(bad(
C,
format!(
"{} already in the library at {to}: nothing was relinked. Remove the copies there first (or use Find Missing Photos)",
clashes.join(", ")
),
));
}
let n = moved.len();
let mut ops: Vec<Op> = moved
.into_iter()
.map(|(id, file_name, path)| Op::Relink { id, file_name, source: lightcraft_catalog::Source::File { path }, format: None })
.collect();
ops.extend(records);
let undo = crate::FolderMove { from: to.clone(), to: from.clone(), on_disk: false };
s.commit_with_folder("Update Folder Location", Op::Batch { ops }, undo)?;
follow_folder(s, &from, &to);
Ok(json!({"path": from, "to": to, "relinked": n}))
}

/// `folder.create`: a new folder on disk inside `parent`; undo removes it while it is empty.
fn create_folder(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "folder.create";
Expand All @@ -319,7 +408,7 @@ fn create_folder(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(C, format!("{path} already exists: choose another name")));
}
folder_on_disk("", &path).map_err(|e| bad(C, e))?;
let undo = crate::FolderMove { from: path.clone(), to: String::new() };
let undo = crate::FolderMove { from: path.clone(), to: String::new(), on_disk: true };
if let Err(e) = s.commit_with_folder(&format!("Create Folder “{name}”"), Op::Batch { ops: vec![] }, undo) {
let _ = remove_empty_folder(&path);
return Err(e);
Expand Down Expand Up @@ -450,7 +539,7 @@ pub(crate) fn move_folder(s: &mut Session, from: &str, to: &str) -> std::result:
let name = Path::new(to).file_name().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
let renamed = src.parent() == dst.parent();
let label = if renamed { format!("Rename Folder to “{name}”") } else { format!("Move Folder “{name}”") };
let folder = crate::FolderMove { from: to.to_string(), to: from.to_string() };
let folder = crate::FolderMove { from: to.to_string(), to: from.to_string(), on_disk: true };
if let Err(e) = s.commit_with_folder(&label, Op::Batch { ops }, folder) {
// the catalog didn't take it: put the folder back where the photos still point
let back = rename_folder_on_disk(to, from).err().map(|b| format!("; moving it back failed too: {b}")).unwrap_or_default();
Expand Down
10 changes: 6 additions & 4 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -140,16 +140,18 @@ fn single_photo(op: &Op, depth: usize) -> Option<PhotoId> {
}
}

/// A folder renamed or moved on disk as part of an undo step.
/// A folder renamed or moved as part of an undo step: on disk, or (`on_disk: false`, Update Folder
/// Location) only in the library, whose chosen folder still follows it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FolderMove {
pub from: String,
pub to: String,
pub on_disk: bool,
}

impl FolderMove {
fn reversed(&self) -> Self {
Self { from: self.to.clone(), to: self.from.clone() }
Self { from: self.to.clone(), to: self.from.clone(), on_disk: self.on_disk }
}
}

Expand Down Expand Up @@ -680,11 +682,11 @@ impl Session {
rename::retry_sidecars(fs, &mut entry.retry_sidecars).map_err(|e| EngineError::Other(format!("can't move the files back: {e}")))?;
let op = &entry.op;
let folder = entry.folder.as_ref();
if let Some(f) = folder {
if let Some(f) = folder.filter(|f| f.on_disk) {
cmd::browse::folder_on_disk(&f.from, &f.to).map_err(|e| EngineError::Other(format!("can't move the folder back: {e}")))?;
}
let undo_folder = || {
if let Some(f) = folder {
if let Some(f) = folder.filter(|f| f.on_disk) {
let _ = cmd::browse::folder_on_disk(&f.to, &f.from);
}
};
Expand Down
111 changes: 111 additions & 0 deletions crates/engine/src/tests_folders.rs
Original file line number Diff line number Diff line change
Expand Up @@ -685,3 +685,114 @@ fn a_destination_without_write_permission_reports_an_error_and_keeps_everything(
}
std::fs::set_permissions(dir.0.join("ro"), std::fs::Permissions::from_mode(0o755)).unwrap();
}

// ---- folder.updateLocation: a folder or disk now somewhere else (moved outside LightCraft)

fn add_at(s: &mut Session, path: &str) -> lightcraft_catalog::PhotoId {
let id = s.catalog.alloc_photo_id();
let name = path.rsplit(['/', '\\']).next().unwrap_or(path).to_string();
let p = Photo::new(id, Source::File { path: path.into() }, &name, "JPEG", 60, 40, "2026-01-01T10:00:00");
s.catalog.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
id
}

/// `rel` (with `/`) inside the scratch folder, spelled as the platform joins it.
fn native(dir: &Scratch, rel: &str) -> String {
rel.split('/').fold(dir.0.clone(), |p, n| p.join(n)).to_string_lossy().to_string()
}

#[test]
fn a_disk_that_came_back_elsewhere_is_one_step_and_its_labels_and_choice_follow() {
let dir = Scratch::new("relocate");
std::fs::create_dir_all(dir.0.join("new/day1")).unwrap();
// the old place is gone (an unplugged disk now mounted elsewhere): it is never looked at
let old = dir.path("old");
let mut s = Session::new();
let a = add_at(&mut s, &format!("{old}/a.jpg"));
let b = add_at(&mut s, &format!("{old}/day1/b.jpg"));
let other = add_at(&mut s, "/elsewhere/c.jpg");
s.execute("folder.label", &json!({"path": old, "label": "red"})).unwrap();
s.execute("folder.label", &json!({"path": format!("{old}/day1"), "label": "blue"})).unwrap();
s.execute("library.filter", &json!({"libraryFolder": format!("{old}/day1")})).unwrap();
let undo_before = s.undo.len();

let r = s.execute("folder.updateLocation", &json!({"path": old, "to": dir.path("new")})).unwrap();
assert_eq!(r["relinked"], 2, "{r}");
assert_eq!(s.undo.len(), undo_before + 1, "one undo step");
assert_eq!(s.undo.last().unwrap().label, "Update Folder Location");
assert_eq!(file_of(&s, a), native(&dir, "new/a.jpg"));
assert_eq!(file_of(&s, b), native(&dir, "new/day1/b.jpg"));
assert_eq!(file_of(&s, other), "/elsewhere/c.jpg", "photos elsewhere stay");
assert_eq!(listed_label(&mut s, &dir.path("new")).as_deref(), Some("red"));
assert_eq!(listed_label(&mut s, &dir.path("new/day1")).as_deref(), Some("blue"), "the folders inside go along");
assert_eq!(s.catalog.folder_record(&old), None, "nothing stays behind");
same_folder(s.filter.library_folder.as_deref(), &dir.path("new/day1"), "the chosen folder follows");
assert_eq!(s.visible().len(), 1);
assert!(!dir.0.join("old").exists() && dir.0.join("new/day1").is_dir(), "no folder made, moved or removed");

s.execute("edit.undo", &json!({})).unwrap();
assert_eq!((file_of(&s, a), file_of(&s, b)), (format!("{old}/a.jpg"), format!("{old}/day1/b.jpg")));
assert_eq!(listed_label(&mut s, &old).as_deref(), Some("red"));
same_folder(s.filter.library_folder.as_deref(), &format!("{old}/day1"), "undo takes the choice back");
assert!(!dir.0.join("old").exists() && dir.0.join("new/day1").is_dir(), "undo touches no folder either");

s.execute("edit.redo", &json!({})).unwrap();
assert_eq!(file_of(&s, b), native(&dir, "new/day1/b.jpg"));
assert_eq!(listed_label(&mut s, &dir.path("new/day1")).as_deref(), Some("blue"), "redo carries them again");
}

#[test]
fn a_folder_whose_name_only_changed_case_takes_its_new_spelling() {
// macOS: `/Volumes/tokyo` came back as `/Volumes/TOKYO` and listed as a second disk
let dir = Scratch::new("relocate-case");
std::fs::create_dir_all(dir.0.join("TOKYO")).unwrap();
let mut s = Session::new();
let a = add_at(&mut s, &format!("{}/2024/a.jpg", dir.path("tokyo")));
s.execute("folder.label", &json!({"path": dir.path("tokyo"), "label": "green"})).unwrap();
let r = s.execute("folder.updateLocation", &json!({"path": dir.path("tokyo"), "to": dir.path("TOKYO")})).unwrap();
assert_eq!(r["relinked"], 1);
assert_eq!(file_of(&s, a), native(&dir, "TOKYO/2024/a.jpg"));
assert_eq!(listed_label(&mut s, &dir.path("TOKYO")).as_deref(), Some("green"));
}

#[test]
fn a_library_written_on_windows_follows_a_folder_here() {
// the photos were stored as `D:\Photos\…` (another machine, either separator); their folder is here now
let dir = Scratch::new("relocate-drive");
std::fs::create_dir_all(dir.0.join("Photos/2026")).unwrap();
let mut s = Session::new();
let a = add_at(&mut s, r"D:\Photos\2026\IMG_1.CR3");
let b = add_at(&mut s, "D:/Photos/IMG_2.CR3");
let r = s.execute("folder.updateLocation", &json!({"path": r"D:\Photos", "to": dir.path("Photos")})).unwrap();
assert_eq!(r["relinked"], 2, "{r}");
assert_eq!(file_of(&s, a), native(&dir, "Photos/2026/IMG_1.CR3"));
assert_eq!(file_of(&s, b), native(&dir, "Photos/IMG_2.CR3"));
}

#[test]
fn update_folder_location_refuses_and_changes_nothing() {
let dir = Scratch::new("relocate-refuse");
std::fs::create_dir_all(dir.0.join("new/inner")).unwrap();
let mut s = Session::new();
add_at(&mut s, &format!("{}/a.jpg", dir.path("old")));
add_at(&mut s, &format!("{}/b.jpg", dir.path("new")));
add_at(&mut s, &format!("{}/b.jpg", dir.path("old")));
let before = s.catalog.to_snapshot();
let undo = s.undo.len();
for (p, why, says) in [
(json!({"to": dir.path("new")}), "no path", "missing path"),
(json!({"path": dir.path("old")}), "no destination", "missing to"),
(json!({"path": dir.path("old"), "to": dir.path("nope")}), "a destination that isn't a folder", "not a folder"),
(json!({"path": dir.path("old"), "to": dir.path("new")}), "a photo already there", "already in the library"),
(json!({"path": dir.path("new"), "to": dir.path("new/inner")}), "into itself", "inside one another"),
(json!({"path": dir.path("gone"), "to": dir.path("new")}), "a folder with no photos", "no photos"),
] {
let e = s.execute("folder.updateLocation", &p).unwrap_err().to_string();
assert!(e.contains(says), "{why}: {e}");
assert_eq!(s.catalog.to_snapshot(), before, "{why}: the library is unchanged");
assert_eq!(s.undo.len(), undo, "{why}: no undo step");
}
let same = s.execute("folder.updateLocation", &json!({"path": dir.path("new"), "to": dir.path("new")})).unwrap();
assert_eq!(same["relinked"], 0, "the same place is nothing to do");
assert_eq!(s.undo.len(), undo);
}
Loading