Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
abb70f6
Issue #3114: Lightroom import archive works on volumes without hard l…
THEtheChad Oct 27, 2026
0c71ab7
Issue #3114: the archive warning comes first; the no-hard-links test …
THEtheChad Oct 27, 2026
d0b5434
fix(lightroom): the import index refuses a linked Interop folder (#3114)
THEtheChad Oct 27, 2026
0a1b05b
fix(lightroom): refuse a linked Interop folder before importing (#3114)
THEtheChad Oct 27, 2026
54a3712
fix(lightroom): refuse an unwritable Interop folder before importing …
THEtheChad Oct 27, 2026
e148eff
fix(lightroom): a saved archive is reported even when its cleanup fai…
THEtheChad Oct 27, 2026
e0197b6
fix(lightroom): reusing an archive tries to retire every old one (#3114)
THEtheChad Oct 30, 2026
f84818d
fix(lightroom): sync the archive folder once the archive is saved (#3…
THEtheChad Oct 30, 2026
51a7820
docs(lightroom): a failed index write can let a retry duplicate virtu…
THEtheChad Oct 30, 2026
4245e7f
test(lightroom): the archive folder-sync test runs on Unix only (#3114)
THEtheChad Oct 30, 2026
efb2fe2
docs(lightroom): say which archive failures only warn, and what the n…
THEtheChad Oct 30, 2026
b1c1767
Issue #1588: one bad Lightroom record costs that record, not the import
THEtheChad Oct 27, 2026
db1ab69
Issue #1588: duplicate ids and bad capture times cost only that record
THEtheChad Oct 27, 2026
379c963
docs(lightroom): a virtual copy whose master is gone is an incomplete…
THEtheChad Oct 27, 2026
f7a76f9
fix(lightroom): check capture dates strictly and keep a bad stored on…
THEtheChad Oct 30, 2026
852e3b6
#3501: keep a capture date of just a year or a month as stated
clydecbrown Oct 31, 2026
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
181 changes: 179 additions & 2 deletions crates/catalog/src/dates.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,6 +100,37 @@ fn tail_start(iso: &str) -> Option<usize> {
ok.then_some(start)
}

/// A capture time stated only to the year (`1983`) or the month (`1983-04`): the reduced ISO 8601
/// dates XMP allows, as for a scanned print whose day isn't known. `Some((year, month))` for exactly
/// those two forms, a year 0001–9999 and a month 01–12; `None` for anything else, a full date included.
pub fn partial_capture(s: &str) -> Option<(u16, Option<u8>)> {
let digits = |x: &str| x.bytes().all(|c| c.is_ascii_digit());
let year = s.get(..4).filter(|y| digits(y)).and_then(|y| y.parse::<u16>().ok()).filter(|y| *y > 0)?;
match s.get(4..)? {
"" => Some((year, None)),
rest => {
let month = rest.strip_prefix('-').filter(|m| m.len() == 2 && digits(m))?.parse::<u8>().ok()?;
(1..=12).contains(&month).then_some((year, Some(month)))
}
}
}

/// What a capture time stands for when the library sorts, groups, filters or compares it: a
/// [`partial_capture`] is the start of its period (`1983` → `1983-01-01T00:00:00`, `1983-04` →
/// `1983-04-01T00:00:00`); any other time is itself.
pub fn capture_start(c: &str) -> std::borrow::Cow<'_, str> {
match partial_capture(c) {
Some((y, m)) => format!("{y:04}-{:02}-01T00:00:00", m.unwrap_or(1)).into(),
None => c.into(),
}
}

/// Whether the library can hold `c` as a capture time: a time [`iso_seconds`] reads, or a
/// [`partial_capture`]. (`Op::SetCaptured` refuses anything else.)
pub fn is_capture_time(c: &str) -> bool {
iso_seconds(&capture_start(c)).is_some()
}

/// Normalize user input to `YYYY-MM-DDTHH:MM:SS` (accepts a space instead of `T`, missing
/// seconds or time). `None` if it isn't a valid date.
pub fn normalize_iso(s: &str) -> Option<String> {
Expand Down Expand Up @@ -159,8 +190,13 @@ pub struct DateRun {
}

/// A capture time for display: `2022-03-30T22:11:11` → "March 30, 2022 at 10:11:11 PM" (the
/// date alone when there is no time; the input unchanged when it doesn't parse).
/// date alone when there is no time, "April 1983" / "1983" for a [`partial_capture`]; the input
/// unchanged when it doesn't parse).
pub fn display_time(iso: &str) -> String {
// a year or a month alone shows as such: "1983", "April 1983"
if partial_capture(iso).is_some() {
return group_label(iso);
}
let num = |r: std::ops::Range<usize>| iso.get(r).and_then(|v| v.parse::<u32>().ok());
let (Some(y), Some(mo), Some(d)) = (num(0..4), num(5..7), num(8..10)) else { return iso.to_string() };
let Some(month) = MONTHS.get((mo as usize).wrapping_sub(1)) else { return iso.to_string() };
Expand Down Expand Up @@ -218,7 +254,9 @@ impl Catalog {
SortKey::EditDate => p.edited.as_deref(),
_ => None,
};
d.filter(|d| iso_seconds(d.get(..10).unwrap_or("")).is_some()).and_then(|d| d.get(..by.prefix())).unwrap_or("").to_string()
// a partial capture time (`1983-04`) groups at the start of its period
let d = d.map(capture_start);
d.as_deref().filter(|d| iso_seconds(d.get(..10).unwrap_or("")).is_some()).and_then(|d| d.get(..by.prefix())).unwrap_or("").to_string()
}
}

Expand Down Expand Up @@ -423,4 +461,143 @@ mod tests {
[("2026-09-30".into(), 0, 3), ("2026-08-01".into(), 3, 1)]
);
}

/// A year or a month alone (`1983`, `1983-04`: a scanned print's date) and nothing else.
#[test]
fn a_partial_capture_time_is_a_year_or_a_month_alone() {
assert_eq!(partial_capture("1983"), Some((1983, None)));
assert_eq!(partial_capture("1983-04"), Some((1983, Some(4))));
for not in [
"",
"0000",
"0000-00",
"1983-00",
"1983-13",
"1983-4",
"1983-04-",
"198",
"19830",
" 1983",
"1983 ",
"1983-04-12",
"1983",
"1983-04",
"1980",
"garbage",
] {
assert_eq!(partial_capture(not), None, "{not}");
}
assert_eq!(capture_start("1983"), "1983-01-01T00:00:00");
assert_eq!(capture_start("1983-04"), "1983-04-01T00:00:00");
assert_eq!(capture_start("2024-01-16T12:34:56Z"), "2024-01-16T12:34:56Z");
assert_eq!(display_time("1983"), "1983");
assert_eq!(display_time("1983-04"), "April 1983");
}

/// A catalog with one photo per `(capture time, import time)`, each stored through `SetCaptured`.
fn dated(times: &[(&str, &str)]) -> (Catalog, Vec<PhotoId>) {
let mut c = Catalog::new();
let mut ids = Vec::new();
for (captured, imported) in times {
let id = c.alloc_photo_id();
let p = Photo::new(id, Source::Demo { scene: 1 }, "a.jpg", "JPEG", 3, 2, imported);
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
c.apply(Op::SetCaptured { id, captured: Some((*captured).into()) }).unwrap();
ids.push(id);
}
(c, ids)
}

const PERIODS: [(&str, &str); 6] = [
("1983-04-01T00:00:01", "2026-10-01T00:00:00"),
("1983-04", "2026-10-01T00:00:00"),
("1983-03-31T23:59:59", "2026-10-01T00:00:00"),
("1983", "2026-10-01T00:00:00"),
("1982-12-31T23:59:59", "2026-10-01T00:00:00"),
("1984-01", "2026-10-01T00:00:00"),
];

/// The library holds a partial capture time as stated, and still refuses what isn't a date.
#[test]
fn a_partial_capture_time_is_held_as_stated() {
let (mut c, ids) = dated(&PERIODS);
assert_eq!(c.photo(ids[1]).unwrap().captured.as_deref(), Some("1983-04"));
for bad in ["1983-13", "0000-00", "0000", "text", "1983"] {
assert!(c.apply(Op::SetCaptured { id: ids[0], captured: Some(bad.into()) }).is_err(), "{bad}");
}
}

/// Sorted by capture date, a partial time is the start of its period: `1983-04` ties with
/// `1983-04-01T00:00:00`, and the import time decides, as for any two photos taken at once.
#[test]
fn a_partial_capture_time_sorts_as_the_start_of_its_period() {
let mut times = PERIODS.to_vec();
times[1].1 = "2026-10-02T00:00:00";
times.push(("1983-04-01T00:00:00", "2026-10-01T00:00:00"));
let (c, _) = dated(&times);
let sort = crate::Sort { key: SortKey::CaptureDate, ascending: true, ..Default::default() };
let order: Vec<_> = c.query(&crate::Filter::default(), &sort).iter().map(|id| c.photo(*id).unwrap().captured.clone().unwrap()).collect();
assert_eq!(order, ["1982-12-31T23:59:59", "1983", "1983-03-31T23:59:59", "1983-04-01T00:00:00", "1983-04", "1983-04-01T00:00:01", "1984-01"]);
}

/// Date headers and the By Date section put a partial time at the start of its period.
#[test]
fn a_partial_capture_time_groups_at_the_start_of_its_period() {
let (c, ids) = dated(&PERIODS);
let group = |id, by| c.date_group(id, SortKey::CaptureDate, by);
assert_eq!(
(group(ids[1], GroupBy::Year), group(ids[1], GroupBy::Month), group(ids[1], GroupBy::Day)),
("1983".into(), "1983-04".into(), "1983-04-01".into())
);
assert_eq!((group(ids[3], GroupBy::Month), group(ids[3], GroupBy::Day)), ("1983-01".into(), "1983-01-01".into()));
let by_date = c.date_groups();
let y1983 = by_date.iter().find(|g| g.year == "1983").unwrap();
assert_eq!(y1983.count, 4, "{by_date:?}");
assert!(y1983.months.contains(&("1983-04".into(), 2)), "{by_date:?}");
assert!(y1983.months.contains(&("1983-01".into(), 1)), "{by_date:?}");
}

/// Date filters and smart-collection rules read a partial time as the start of its period.
#[test]
fn a_partial_capture_time_meets_filters_and_rules_as_the_start_of_its_period() {
let (c, ids) = dated(&PERIODS);
let sort = crate::Sort { key: SortKey::CaptureDate, ascending: true, ..Default::default() };
let matching = |f: crate::Filter| {
let mut found: Vec<_> = c.query(&f, &sort).iter().map(|id| c.photo(*id).unwrap().captured.clone().unwrap()).collect();
found.sort();
found
};
assert_eq!(matching(crate::Filter { date: Some("1983-04-01".into()), ..Default::default() }), ["1983-04", "1983-04-01T00:00:01"]);
assert_eq!(
matching(crate::Filter { date_from: Some("1983-04-01".into()), date_to: Some("1983-04-30".into()), ..Default::default() }),
["1983-04", "1983-04-01T00:00:01"]
);
assert_eq!(matching(crate::Filter { text: "date:1983-01".into(), ..Default::default() }), ["1983"]);
let rule = |op: &str, value: serde_json::Value| {
let set: crate::RuleSet =
serde_json::from_value(serde_json::json!({"match": "all", "rules": [{"field": "captureDate", "op": op, "value": value}]})).unwrap();
set.matches(c.photo(ids[1]).unwrap(), &c)
};
assert!(rule("is", "1983-04".into()));
assert!(rule("is", "1983".into()));
assert!(rule("is", "1983-04-01".into()));
assert!(!rule("is", "1983-03".into()));
assert!(rule("between", serde_json::json!(["1983-04-01", "1983-04-30"])));
assert!(!rule("after", "1983-04-01T00:00:01".into()));
}

/// A year or a month alone has no time of day, so photos dated to the same one are not a burst.
#[test]
fn partial_capture_times_are_not_stacked_by_time() {
let mut c = Catalog::new();
let mut ids = Vec::new();
for (i, t) in ["1983", "1983", "1983-04", "1983-04"].iter().enumerate() {
let id = c.alloc_photo_id();
let mut p = Photo::new(id, Source::Demo { scene: 1 }, &format!("{i}.jpg"), "JPEG", 3, 2, "2026-10-01T00:00:00");
p.captured = Some((*t).into());
c.apply(Op::AddPhoto { photo: Box::new(p) }).unwrap();
ids.push(id);
}
assert!(c.auto_stack_groups(&ids, 60.0).is_empty());
}
}
2 changes: 1 addition & 1 deletion crates/catalog/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -901,7 +901,7 @@ impl Catalog {
}
Op::SetCaptured { id, captured } => {
if let Some(c) = &captured
&& stacks::iso_seconds(c).is_none()
&& !dates::is_capture_time(c)
{
return Err(CatalogError::Invalid(format!("not a date: {c}")));
}
Expand Down
35 changes: 23 additions & 12 deletions crates/catalog/src/query.rs
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,11 @@ impl Sort {
/// Which of two photos comes first in this order (never `Equal` for two photos: the id decides last).
pub fn order(&self, a: &Photo, b: &Photo) -> std::cmp::Ordering {
let o = match self.key {
SortKey::CaptureDate => a.captured.cmp(&b.captured).then_with(|| a.imported.cmp(&b.imported)),
// a partial capture time (`1983-04`) sorts at the start of its period
SortKey::CaptureDate => {
let (at_a, at_b) = (a.captured.as_deref().map(crate::dates::capture_start), b.captured.as_deref().map(crate::dates::capture_start));
at_a.cmp(&at_b).then_with(|| a.imported.cmp(&b.imported))
}
SortKey::ImportDate => a.imported.cmp(&b.imported),
SortKey::EditDate => a.edited.cmp(&b.edited),
SortKey::FileName => cmp_name(&a.file_name, &b.file_name),
Expand Down Expand Up @@ -214,7 +218,7 @@ fn token_matches(p: &Photo, tok: &str) -> bool {
"person" | "who" => has_person(p, val),
"type" | "kind" => format!("{:?}", p.kind).eq_ignore_ascii_case(val),
"edited" => (val == "true" || val == "yes") == p.is_edited(),
"date" => p.captured.as_deref().is_some_and(|c| c.starts_with(val)),
"date" => p.captured.as_deref().is_some_and(|c| crate::dates::capture_start(c).starts_with(val)),
"copy" | "virtual" => (val == "true" || val == "yes") == p.copy_of.is_some(),
"name" | "file" => p.file_name.to_lowercase().contains(val),
// Not a known field: the colon is part of a plain word ("10:30", "Re:"), its value unquoted
Expand Down Expand Up @@ -408,17 +412,18 @@ impl Filter {
{
return false;
}
// a partial capture time (`1983-04`) stands for the start of its period
if let Some(from) = &self.date_from
&& match p.captured.as_deref() {
Some(c) => c < from.as_str(),
&& match p.captured.as_deref().map(crate::dates::capture_start) {
Some(c) => *c < *from.as_str(),
None => true,
}
{
return false;
}
if let Some(to) = &self.date_to
&& match p.captured.as_deref() {
Some(c) => c.get(..to.len()).unwrap_or(c) > to.as_str(),
&& match p.captured.as_deref().map(crate::dates::capture_start) {
Some(c) => c.get(..to.len()).unwrap_or(&c) > to.as_str(),
None => true,
}
{
Expand All @@ -430,7 +435,7 @@ impl Filter {
return false;
}
if let Some(d) = &self.date
&& !p.captured.as_deref().is_some_and(|c| c.starts_with(d.as_str()))
&& !p.captured.as_deref().is_some_and(|c| crate::dates::capture_start(c).starts_with(d.as_str()))
{
return false;
}
Expand Down Expand Up @@ -525,20 +530,26 @@ impl Catalog {

/// Year → month → day counts for the "By Date" section (newest first).
pub fn date_groups(&self) -> Vec<DateGroup> {
use std::borrow::Cow;
use std::collections::BTreeMap;
let mut years: BTreeMap<&str, (BTreeMap<&str, usize>, BTreeMap<&str, usize>)> = BTreeMap::new();
let mut years: BTreeMap<Cow<str>, (BTreeMap<Cow<str>, usize>, BTreeMap<Cow<str>, usize>)> = BTreeMap::new();
for p in self.photos().filter(|p| p.in_library()) {
let Some(d) = p.captured.as_deref() else { continue };
let Some(d) = p.captured.as_deref().map(crate::dates::capture_start) else { continue };
// `get`, not `[..]`: a corrupt or foreign `captured` (a Lightroom catalog's
// captureTime is copied verbatim) may not be ASCII, and slicing it on a byte index
// would panic — the same rule as `dates::group_label`.
if let (Some(year), Some(month), Some(day)) = (d.get(..4), d.get(..7), d.get(..10)) {
// would panic — the same rule as `dates::group_label`. A partial time (`1983-04`) counts
// at the start of its period, so only it owns its keys.
let part = |n: usize| match &d {
Cow::Borrowed(d) => d.get(..n).map(Cow::Borrowed),
Cow::Owned(d) => d.get(..n).map(|k| Cow::Owned(k.to_string())),
};
if let (Some(year), Some(month), Some(day)) = (part(4), part(7), part(10)) {
let (months, days) = years.entry(year).or_default();
*months.entry(month).or_default() += 1;
*days.entry(day).or_default() += 1;
}
}
let newest_first = |m: BTreeMap<&str, usize>| m.into_iter().rev().map(|(k, n)| (k.to_string(), n)).collect::<Vec<_>>();
let newest_first = |m: BTreeMap<Cow<str>, usize>| m.into_iter().rev().map(|(k, n)| (k.to_string(), n)).collect::<Vec<_>>();
years
.into_iter()
.rev()
Expand Down
3 changes: 2 additions & 1 deletion crates/catalog/src/rules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1020,7 +1020,8 @@ impl Rule {
let want = crate::CopyrightStatus::parse(&want);
(want == Some(m.copyright_status)) == (op == "is")
}
"captureDate" => date_op(op, p.captured.as_deref(), value),
// a partial capture time (`1983-04`) stands for the start of its period
"captureDate" => date_op(op, p.captured.as_deref().map(crate::dates::capture_start).as_deref(), value),
"importDate" => date_op(op, Some(&p.imported), value),
"editDate" => date_op(op, p.edited.as_deref(), value),
"shutterSpeed" => num_op(op, crate::parse_shutter_seconds(&m.shutter), &shutter_value(value)),
Expand Down
38 changes: 35 additions & 3 deletions crates/catalog/src/safe_file.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
//! and sync, plus a read-back check, and the file then appears under its final name **without
//! replacing anything** (a hard link, which fails on a taken name; where the volume has no hard
//! links, an exclusive create that claims the name, then a rename over that placeholder).
//! [`publish_new`] is that last step on its own, for a writer with its own temp file (the
//! Lightroom recovery archive).
//! - [`same_file`] tells whether two paths name the same file on disk (device + inode on Unix,
//! volume serial number + file index on Windows,
//! resolved paths elsewhere), for "is this target an original?" checks.
Expand All @@ -35,6 +37,7 @@ use std::sync::atomic::{AtomicU64, Ordering};
thread_local! {
static FAIL_AFTER: Cell<Option<u64>> = const { Cell::new(None) };
static SYNCS: Cell<u64> = const { Cell::new(0) };
static NO_HARD_LINKS: Cell<bool> = const { Cell::new(false) };
}

/// How many file and folder syncs this module made **on the calling thread** (for tests: a
Expand Down Expand Up @@ -68,6 +71,28 @@ impl Drop for FaultGuard {
}
}

/// Fault injection for tests (in any crate): while the returned guard lives, [`publish_new`]
/// **on the calling thread** acts as on a volume without hard links (FAT/exFAT, some shares), so
/// it takes the exclusive-create + rename fallback. Product code never calls it.
#[doc(hidden)]
pub fn without_hard_links() -> NoHardLinksGuard {
NoHardLinksGuard { previous: NO_HARD_LINKS.with(|c| c.replace(true)), _same_thread: std::marker::PhantomData }
}

/// Ends a [`without_hard_links`] when dropped, putting back what was set before (so nested guards
/// work). It stays on the thread whose flag it set (not `Send`).
#[doc(hidden)]
pub struct NoHardLinksGuard {
previous: bool,
_same_thread: std::marker::PhantomData<*const ()>,
}

impl Drop for NoHardLinksGuard {
fn drop(&mut self) {
NO_HARD_LINKS.with(|c| c.set(self.previous));
}
}

/// Counts what is written; fails past an injected limit.
struct Limited<W> {
inner: W,
Expand Down Expand Up @@ -222,9 +247,12 @@ pub fn write_new_unique(candidates: &mut dyn Iterator<Item = PathBuf>, data: &[u
r
}

/// Give the complete temp file `tmp` the name `path`, unless that is taken.
fn publish_new(tmp: &Path, path: &Path) -> io::Result<()> {
match fs::hard_link(tmp, path) {
/// Give the complete temp file `tmp` (in the same folder) the name `path`, unless that is taken
/// (`AlreadyExists`): a hard link, or where the volume has none, [`publish_new_by_rename`]. After
/// a hard link `tmp` is a second name of the file; after the fallback it is gone.
pub fn publish_new(tmp: &Path, path: &Path) -> io::Result<()> {
let linked = if NO_HARD_LINKS.with(Cell::get) { Err(io::Error::from(io::ErrorKind::Unsupported)) } else { fs::hard_link(tmp, path) };
match linked {
Ok(()) => Ok(()),
Err(e) if e.kind() == io::ErrorKind::AlreadyExists => Err(e),
// no hard links on this volume (FAT/exFAT, some shares)
Expand All @@ -235,6 +263,10 @@ fn publish_new(tmp: &Path, path: &Path) -> io::Result<()> {
/// Fallback of [`publish_new`]: reserve the name with an exclusive create (atomic, so a file that
/// appears at the same time is never replaced), then rename the complete temp file over our own
/// empty placeholder. `before_claim` runs just before the name is claimed (a test hook).
///
/// That guarantee holds against other writers that also create names exclusively (as everything in
/// a library folder does). A process that deletes or replaces our placeholder between the claim and
/// the rename would have its file replaced, and a failed rename removes whatever then has the name.
fn publish_new_by_rename(tmp: &Path, path: &Path, before_claim: &dyn Fn()) -> io::Result<()> {
before_claim();
OpenOptions::new().write(true).create_new(true).open(path)?;
Expand Down
Loading