Skip to main content

koan_core/
organize.rs

1use std::collections::{HashMap, HashSet};
2use std::io::ErrorKind;
3use std::path::{Path, PathBuf};
4use std::time::{SystemTime, UNIX_EPOCH};
5
6use rusqlite::{Connection, params};
7
8use crate::db::connection::{Database, DbError};
9use crate::db::queries::{self, PersistedQueueItem, TrackRow};
10use crate::format::{self, FormatError, MetadataProvider};
11use crate::helpers::{sanitise_filename, truncate_bytes};
12
13/// Ancillary file patterns we move alongside audio files.
14const ANCILLARY_PATTERNS: &[&str] = &[
15    "cover.jpg",
16    "cover.png",
17    "cover.webp",
18    "folder.jpg",
19    "folder.png",
20    "front.jpg",
21    "front.png",
22];
23
24const ANCILLARY_EXTENSIONS: &[&str] = &["cue", "log", "m3u", "m3u8"];
25
26/// Byte ceiling for a destination file name, extension included. Filesystems we
27/// target cap a single name at 255 bytes.
28const MAX_FILE_NAME_BYTES: usize = 250;
29
30#[derive(Debug, thiserror::Error)]
31pub enum OrganizeError {
32    #[error("database error: {0}")]
33    Db(#[from] DbError),
34    #[error("sqlite error: {0}")]
35    Sqlite(#[from] rusqlite::Error),
36    #[error("format error: {0}")]
37    Format(#[from] FormatError),
38    #[error("io error: {0}")]
39    Io(#[from] std::io::Error),
40    #[error("no destination folder: add a library folder, or pass --base-dir")]
41    NoDestination,
42    #[error("no organize batches to undo")]
43    NothingToUndo,
44    #[error("destination already exists: {0}")]
45    DestinationExists(PathBuf),
46    #[error("copied {copied} of {expected} bytes from {path}")]
47    ShortCopy {
48        path: PathBuf,
49        expected: u64,
50        copied: u64,
51    },
52    #[error("not enough free space: {needed} bytes needed, {available} available")]
53    NotEnoughSpace { needed: u64, available: u64 },
54}
55
56/// What the pattern means for one file.
57///
58/// Conflicts are an outcome rather than an error off to one side: "this would
59/// overwrite something" is the single most important thing a preview can tell
60/// you, and it belongs on the row it concerns, next to the destination it would
61/// have landed on.
62#[derive(Debug, Clone, PartialEq, Eq)]
63pub enum PlanOutcome {
64    /// The file will be moved, or was.
65    Move,
66    /// Already exactly where the pattern puts it. Nothing to do.
67    Unchanged,
68    /// Something holds the destination — a file already there, or another file
69    /// in the same run that claimed it first. Nothing is ever overwritten, so
70    /// this file stays where it is.
71    Conflict(String),
72    /// The pattern produced nothing usable for this file, or the move failed.
73    Error(String),
74}
75
76impl PlanOutcome {
77    /// The reason a file isn't moving, for anything rendering it as text.
78    pub fn reason(&self) -> Option<&str> {
79        match self {
80            Self::Conflict(reason) | Self::Error(reason) => Some(reason),
81            _ => None,
82        }
83    }
84}
85
86/// One file's place in a plan: where it is, where the pattern puts it, and
87/// whether that can happen.
88#[derive(Debug, Clone)]
89pub struct PlanEntry {
90    /// The library track this file belongs to, or `None` for a file the library
91    /// doesn't know about. Either way the move is logged and can be undone.
92    pub track_id: Option<i64>,
93    pub from: PathBuf,
94    /// Where the pattern puts it. `None` only when the pattern failed before it
95    /// produced a path at all.
96    pub to: Option<PathBuf>,
97    pub ancillary: Vec<(PathBuf, PathBuf)>,
98    pub outcome: PlanOutcome,
99}
100
101impl PlanEntry {
102    /// Where this file is headed. Only call it on an entry that has a
103    /// destination — a plan that failed before producing one has none.
104    #[cfg(test)]
105    fn dest(&self) -> &Path {
106        self.to.as_deref().expect("plan entry has no destination")
107    }
108
109    /// The executable move this entry stands for, if it is one.
110    fn as_move(&self) -> Option<FileMove> {
111        match (&self.outcome, &self.to) {
112            (PlanOutcome::Move, Some(to)) => Some(FileMove {
113                track_id: self.track_id,
114                from: self.from.clone(),
115                to: to.clone(),
116                ancillary: self.ancillary.clone(),
117            }),
118            _ => None,
119        }
120    }
121}
122
123/// Every selected file and what happens to it, in the order it was planned.
124///
125/// One ordered list rather than separate buckets: a preview is a table with a
126/// row per file, and splitting the failures out of it loses both their place in
127/// the run and the destination they were headed for.
128#[derive(Debug, Default)]
129pub struct OrganizeResult {
130    pub entries: Vec<PlanEntry>,
131}
132
133impl OrganizeResult {
134    pub fn moves(&self) -> impl Iterator<Item = &PlanEntry> {
135        self.entries
136            .iter()
137            .filter(|e| e.outcome == PlanOutcome::Move)
138    }
139
140    pub fn moved_count(&self) -> usize {
141        self.moves().count()
142    }
143
144    /// Files already where the pattern puts them.
145    pub fn unchanged_count(&self) -> usize {
146        self.entries
147            .iter()
148            .filter(|e| e.outcome == PlanOutcome::Unchanged)
149            .count()
150    }
151
152    pub fn conflicts(&self) -> impl Iterator<Item = &PlanEntry> {
153        self.entries
154            .iter()
155            .filter(|e| matches!(e.outcome, PlanOutcome::Conflict(_)))
156    }
157
158    /// Everything that isn't happening and isn't already right — conflicts and
159    /// errors together, since a caller reporting failures wants both.
160    pub fn failures(&self) -> impl Iterator<Item = &PlanEntry> {
161        self.entries
162            .iter()
163            .filter(|e| matches!(e.outcome, PlanOutcome::Conflict(_) | PlanOutcome::Error(_)))
164    }
165
166    /// One line per failure, for callers that render a flat list. Includes the
167    /// destination where there was one — for a conflict that is the whole point.
168    pub fn failure_messages(&self) -> Vec<String> {
169        self.failures()
170            .map(|e| {
171                let reason = e.outcome.reason().unwrap_or("unknown");
172                match &e.to {
173                    Some(to) => format!("{}: {reason} ({})", e.from.display(), to.display()),
174                    None => format!("{}: {reason}", e.from.display()),
175                }
176            })
177            .collect()
178    }
179}
180
181/// An executable move, extracted from a plan entry that can proceed.
182#[derive(Debug)]
183pub struct FileMove {
184    pub track_id: Option<i64>,
185    pub from: PathBuf,
186    pub to: PathBuf,
187    pub ancillary: Vec<(PathBuf, PathBuf)>,
188}
189
190/// One `organize_log` row: id, original path, moved-to path, and the size and
191/// modification time the file had when it was moved.
192type UndoEntry = (i64, String, String, Option<i64>, Option<i64>);
193
194#[derive(Debug, Default)]
195pub struct UndoResult {
196    pub restored: usize,
197    pub errors: Vec<(PathBuf, String)>,
198}
199
200/// Which files an organize run covers.
201enum Selection<'a> {
202    All,
203    TrackIds(&'a [i64]),
204    Paths(&'a [PathBuf]),
205}
206
207/// Album fields a track inherits: both come from the album row, not the track row.
208#[derive(Default, Clone)]
209struct AlbumFacts {
210    date: Option<String>,
211    label: Option<String>,
212}
213
214/// A source file with the metadata its destination will be built from.
215struct ResolvedTrack {
216    source: PathBuf,
217    track_id: Option<i64>,
218    metadata: Result<TrackMetadata, String>,
219}
220
221/// Metadata provider backed by a HashMap, for evaluating format strings against track data.
222struct TrackMetadata {
223    fields: HashMap<String, String>,
224}
225
226impl TrackMetadata {
227    fn from_track_row(track: &TrackRow, album: &AlbumFacts) -> Self {
228        let mut fields = HashMap::new();
229        // Sanitize all field values so they can't inject path separators or illegal chars.
230        let s = sanitise_filename;
231        fields.insert("title".into(), s(&track.title));
232        fields.insert("artist".into(), s(&track.artist_name));
233        fields.insert("album artist".into(), s(&track.album_artist_name));
234        fields.insert("album".into(), s(&track.album_title));
235        if let Some(n) = track.track_number {
236            fields.insert("tracknumber".into(), format!("{n:02}"));
237        }
238        if let Some(d) = track.disc {
239            fields.insert("discnumber".into(), d.to_string());
240        }
241        if let Some(ref date) = album.date {
242            fields.insert("date".into(), s(date));
243        }
244        if let Some(ref label) = album.label {
245            fields.insert("label".into(), s(label));
246        }
247        if let Some(ref codec) = track.codec {
248            fields.insert("codec".into(), s(codec));
249        }
250        if let Some(ref genre) = track.genre {
251            fields.insert("genre".into(), s(genre));
252        }
253        Self { fields }
254    }
255
256    /// Build metadata directly from file tags, for files the library doesn't know about.
257    /// Populates exactly the same field set as `from_track_row` so a preview and the
258    /// move it authorises can never resolve to different paths.
259    fn from_file_meta(meta: &queries::TrackMeta) -> Self {
260        let mut fields = HashMap::new();
261        let s = sanitise_filename;
262        fields.insert("title".into(), s(&meta.title));
263        fields.insert("artist".into(), s(&meta.artist));
264        fields.insert(
265            "album artist".into(),
266            s(meta.album_artist.as_deref().unwrap_or(&meta.artist)),
267        );
268        fields.insert("album".into(), s(&meta.album));
269        if let Some(n) = meta.track_number {
270            fields.insert("tracknumber".into(), format!("{n:02}"));
271        }
272        if let Some(d) = meta.disc {
273            fields.insert("discnumber".into(), d.to_string());
274        }
275        if let Some(ref date) = meta.date {
276            fields.insert("date".into(), s(date));
277        }
278        if let Some(ref label) = meta.label {
279            fields.insert("label".into(), s(label));
280        }
281        if let Some(ref codec) = meta.codec {
282            fields.insert("codec".into(), s(codec));
283        }
284        if let Some(ref genre) = meta.genre {
285            fields.insert("genre".into(), s(genre));
286        }
287        Self { fields }
288    }
289}
290
291impl MetadataProvider for TrackMetadata {
292    fn get_field(&self, name: &str) -> Option<String> {
293        self.fields.get(name).cloned()
294    }
295}
296
297/// Sanitize each component of a relative path independently.
298///
299/// An empty, `.` or `..` component is an error, not something to skip: dropping one
300/// silently collapses a whole album onto a single filename, and the tracks that land
301/// there overwrite each other.
302fn sanitize_relative_path(rel: &str) -> Result<PathBuf, String> {
303    let mut result = PathBuf::new();
304    for part in rel.split(['/', std::path::MAIN_SEPARATOR]) {
305        // Checked before sanitising, which would turn these into `_`.
306        if matches!(part.trim(), "." | "..") {
307            return Err(format!(
308                "format string produced a relative path component: {rel:?}"
309            ));
310        }
311        let sanitized = sanitise_filename(part);
312        if sanitized.is_empty() {
313            return Err(format!(
314                "format string produced an empty path component: {rel:?}"
315            ));
316        }
317        result.push(sanitized);
318    }
319    if result.as_os_str().is_empty() {
320        return Err("format string produced an empty path".into());
321    }
322    Ok(result)
323}
324
325/// Load every album's date and label in one query — both are fields a format string
326/// can reference, and both live on the album row.
327fn load_album_facts(conn: &Connection) -> Result<HashMap<i64, AlbumFacts>, OrganizeError> {
328    let mut stmt = conn.prepare("SELECT id, date, label FROM albums")?;
329    let rows = stmt.query_map([], |row| {
330        Ok((
331            row.get::<_, i64>(0)?,
332            AlbumFacts {
333                date: row.get(1)?,
334                label: row.get(2)?,
335            },
336        ))
337    })?;
338    let mut map = HashMap::new();
339    for row in rows {
340        let (id, facts) = row?;
341        map.insert(id, facts);
342    }
343    Ok(map)
344}
345
346/// Find ancillary files in the same directory as a track.
347fn find_ancillary_files(track_dir: &Path) -> Vec<PathBuf> {
348    let mut files = Vec::new();
349    let Ok(entries) = std::fs::read_dir(track_dir) else {
350        return files;
351    };
352
353    for entry in entries.flatten() {
354        let path = entry.path();
355        if !path.is_file() {
356            continue;
357        }
358        let name = path
359            .file_name()
360            .and_then(|n| n.to_str())
361            .unwrap_or_default()
362            .to_lowercase();
363
364        // Check exact name matches.
365        if ANCILLARY_PATTERNS.iter().any(|p| name == *p) {
366            files.push(path);
367            continue;
368        }
369        // Check extension matches.
370        if let Some(ext) = path.extension().and_then(|e| e.to_str())
371            && ANCILLARY_EXTENSIONS
372                .iter()
373                .any(|e| ext.eq_ignore_ascii_case(e))
374        {
375            files.push(path);
376        }
377    }
378    files.sort();
379    files
380}
381
382/// The destination names a run has already committed to, so two files can never be
383/// planned onto the same path.
384#[derive(Default)]
385struct DestinationLedger {
386    taken: HashSet<String>,
387}
388
389impl DestinationLedger {
390    /// macOS, iOS and Windows filesystems are case-insensitive by default, so
391    /// `Rain.flac` and `RAIN.flac` are one file there and must collide here too.
392    fn key(path: &Path) -> String {
393        let key = path.to_string_lossy().into_owned();
394        if cfg!(any(
395            target_os = "macos",
396            target_os = "ios",
397            target_os = "windows"
398        )) {
399            key.to_lowercase()
400        } else {
401            key
402        }
403    }
404
405    /// Returns false if this destination is already spoken for.
406    fn claim(&mut self, path: &Path) -> bool {
407        self.taken.insert(Self::key(path))
408    }
409}
410
411/// Plan one file: format the pattern, sanitize it into a path, and decide
412/// whether the file can actually go there.
413///
414/// Always yields an entry. A file that can't move is still a row in the plan,
415/// carrying the destination it was headed for and why it isn't going.
416fn plan_single_move(
417    source: &Path,
418    track_id: Option<i64>,
419    metadata: &TrackMetadata,
420    pattern: &str,
421    base_dir: &Path,
422    dests: &mut DestinationLedger,
423) -> PlanEntry {
424    let entry = |to: Option<PathBuf>, outcome: PlanOutcome| PlanEntry {
425        track_id,
426        from: source.to_path_buf(),
427        to,
428        ancillary: Vec::new(),
429        outcome,
430    };
431    // Everything before a destination exists is an error with nothing to point at.
432    macro_rules! bail {
433        ($reason:expr) => {
434            return entry(None, PlanOutcome::Error($reason))
435        };
436    }
437
438    let relative = match format::format(pattern, metadata) {
439        Ok(r) => r,
440        Err(e) => bail!(format!("format error: {e}")),
441    };
442
443    if relative.is_empty() {
444        bail!("format string produced empty path".to_string());
445    }
446
447    let sanitized = match sanitize_relative_path(&relative) {
448        Ok(p) => p,
449        Err(e) => bail!(e),
450    };
451
452    // Preserve the original file extension.
453    // Don't use with_extension() — it replaces after the LAST dot, which
454    // destroys titles containing dots (e.g. "0111. Bicep - TANGZ II" → "0111.flac").
455    let ext = source
456        .extension()
457        .and_then(|e| e.to_str())
458        .unwrap_or("flac");
459    let Some(stem) = sanitized.file_name().and_then(|n| n.to_str()) else {
460        bail!("format string produced an unusable file name".to_string());
461    };
462    // Leave room for the extension, so a long title is shortened rather than
463    // previewing cleanly and failing with ENAMETOOLONG at move time.
464    let stem = truncate_bytes(stem, MAX_FILE_NAME_BYTES.saturating_sub(ext.len() + 1)).trim_end();
465    if stem.is_empty() {
466        bail!("format string produced an empty file name".to_string());
467    }
468    let mut dest = base_dir.to_path_buf();
469    if let Some(parent) = sanitized.parent() {
470        dest.push(parent);
471    }
472    dest.push(format!("{stem}.{ext}"));
473
474    // Safety: verify dest stays under base_dir (defense-in-depth against path traversal).
475    if !dest.starts_with(base_dir) {
476        let reason = format!(
477            "path traversal blocked: destination {} escapes base dir {}",
478            dest.display(),
479            base_dir.display()
480        );
481        return entry(Some(dest), PlanOutcome::Error(reason));
482    }
483
484    if source == dest {
485        // Already in place — claim the name anyway so nothing else targets it.
486        dests.claim(&dest);
487        return entry(Some(dest), PlanOutcome::Unchanged);
488    }
489
490    if !dests.claim(&dest) {
491        return entry(
492            Some(dest),
493            PlanOutcome::Conflict("another file in this run is already going here".into()),
494        );
495    }
496
497    // Whether something is *already* sitting at the destination is a question
498    // for the filesystem, and this function deliberately does not ask one —
499    // see `check_against_disk`.
500    PlanEntry {
501        track_id,
502        from: source.to_path_buf(),
503        to: Some(dest),
504        ancillary: Vec::new(),
505        outcome: PlanOutcome::Move,
506    }
507}
508
509/// Ask the filesystem the two questions formatting cannot answer: whether a
510/// destination is already occupied, and what ancillary files travel with each
511/// move.
512///
513/// Separate from planning because it is the only part that touches the disk. A
514/// preview that reruns on every keystroke wants the pure half immediately and
515/// this afterwards; an execute wants both before it moves anything.
516pub fn check_against_disk(result: &mut OrganizeResult, move_ancillary: bool) {
517    let mut dests = DestinationLedger::default();
518    let mut planned_ancillary: HashSet<PathBuf> = HashSet::new();
519    // One directory read per source folder. An album is one folder and a dozen
520    // tracks, so doing this per file would repeat the same readdir a dozen times.
521    let mut ancillary_by_dir: HashMap<PathBuf, Vec<PathBuf>> = HashMap::new();
522
523    for entry in &mut result.entries {
524        let (PlanOutcome::Move, Some(dest)) = (&entry.outcome, entry.to.clone()) else {
525            continue;
526        };
527
528        // A destination that resolves to the source itself is a case-only
529        // rename, which is a real move; anything else already there would be
530        // overwritten.
531        if dest.exists() && !paths_equal(&entry.from, &dest) {
532            entry.outcome =
533                PlanOutcome::Conflict("a file is already here — it would be overwritten".into());
534            continue;
535        }
536        dests.claim(&dest);
537
538        if !move_ancillary {
539            continue;
540        }
541        let source_dir = entry.from.parent().unwrap_or(Path::new("."));
542        let dest_dir = dest.parent().unwrap_or(Path::new("."));
543        if source_dir == dest_dir {
544            continue;
545        }
546        let candidates = ancillary_by_dir
547            .entry(source_dir.to_path_buf())
548            .or_insert_with(|| find_ancillary_files(source_dir))
549            .clone();
550        for anc_path in candidates {
551            if planned_ancillary.contains(&anc_path) {
552                continue;
553            }
554            let Some(anc_name) = anc_path.file_name() else {
555                continue;
556            };
557            let anc_dest = dest_dir.join(anc_name);
558            // Artwork already at the destination is left alone rather than
559            // overwritten; the audio file is what matters here.
560            if anc_dest.exists() || !dests.claim(&anc_dest) {
561                continue;
562            }
563            planned_ancillary.insert(anc_path.clone());
564            entry.ancillary.push((anc_path, anc_dest));
565        }
566    }
567}
568
569fn resolve_from_rows(rows: Vec<TrackRow>, albums: &HashMap<i64, AlbumFacts>) -> Vec<ResolvedTrack> {
570    let fallback = AlbumFacts::default();
571    rows.into_iter()
572        .filter_map(|track| {
573            let source = PathBuf::from(track.path.as_ref()?);
574            if !source.exists() {
575                return None; // file gone, skip
576            }
577            let facts = track
578                .album_id
579                .and_then(|id| albums.get(&id))
580                .unwrap_or(&fallback);
581            Some(ResolvedTrack {
582                source,
583                track_id: Some(track.id),
584                metadata: Ok(TrackMetadata::from_track_row(&track, facts)),
585            })
586        })
587        .collect()
588}
589
590fn read_tag_metadata(source: &Path) -> Result<TrackMetadata, String> {
591    if !source.exists() {
592        return Err("file not found".to_string());
593    }
594    crate::index::metadata::read_metadata(source)
595        .map(|m| TrackMetadata::from_file_meta(&m))
596        .map_err(|e| format!("metadata error: {e}"))
597}
598
599/// Resolve arbitrary paths: library rows where we have them, file tags otherwise.
600/// Preview and execute both come through here, so both see the same metadata.
601fn resolve_from_paths(
602    db: &Database,
603    paths: &[PathBuf],
604    albums: &HashMap<i64, AlbumFacts>,
605) -> Result<Vec<ResolvedTrack>, OrganizeError> {
606    use rayon::prelude::*;
607
608    let path_strings: Vec<String> = paths
609        .iter()
610        .map(|p| p.to_string_lossy().into_owned())
611        .collect();
612    let known = queries::tracks_by_paths(&db.conn, &path_strings)?;
613
614    // Tag reads are the expensive part, so only the unknown files pay for them.
615    let mut tagged: HashMap<PathBuf, Result<TrackMetadata, String>> = paths
616        .par_iter()
617        .filter(|p| !known.contains_key(p.to_string_lossy().as_ref()))
618        .map(|p| (p.clone(), read_tag_metadata(p)))
619        .collect();
620
621    let fallback = AlbumFacts::default();
622    let mut resolved = Vec::with_capacity(paths.len());
623    for (path, path_str) in paths.iter().zip(&path_strings) {
624        let entry = match known.get(path_str) {
625            Some(track) => {
626                let facts = track
627                    .album_id
628                    .and_then(|id| albums.get(&id))
629                    .unwrap_or(&fallback);
630                ResolvedTrack {
631                    source: path.clone(),
632                    track_id: Some(track.id),
633                    metadata: Ok(TrackMetadata::from_track_row(track, facts)),
634                }
635            }
636            None => ResolvedTrack {
637                source: path.clone(),
638                track_id: None,
639                metadata: tagged
640                    .remove(path)
641                    .unwrap_or_else(|| Err("duplicate path in selection".to_string())),
642            },
643        };
644        resolved.push(entry);
645    }
646    Ok(resolved)
647}
648
649/// A selection with every read already done: library rows, album facts, and
650/// tags for files the library has never seen.
651///
652/// This is the half that costs something. Generating destinations from it is
653/// pure string work, so a preview that reruns as a pattern is typed resolves
654/// once here and formats many times against the result.
655pub struct ResolvedSelection {
656    tracks: Vec<ResolvedTrack>,
657}
658
659impl ResolvedSelection {
660    /// How many files resolved to something with a local path. Fewer than were
661    /// asked for means the rest are remote-only or gone from disk.
662    pub fn len(&self) -> usize {
663        self.tracks.len()
664    }
665
666    pub fn is_empty(&self) -> bool {
667        self.tracks.is_empty()
668    }
669}
670
671/// Read a selection out of the library. `track_ids` of `None` means all of it.
672///
673/// Database reads and a `stat` per file, so it belongs off whatever thread is
674/// drawing — but it only has to happen once per selection.
675pub fn resolve(
676    db: &Database,
677    track_ids: Option<&[i64]>,
678) -> Result<ResolvedSelection, OrganizeError> {
679    let selection = match track_ids {
680        Some(ids) => Selection::TrackIds(ids),
681        None => Selection::All,
682    };
683    resolve_selection(db, selection)
684}
685
686fn resolve_selection(
687    db: &Database,
688    selection: Selection<'_>,
689) -> Result<ResolvedSelection, OrganizeError> {
690    let albums = load_album_facts(&db.conn)?;
691    let tracks = match selection {
692        Selection::All => resolve_from_rows(queries::all_tracks(&db.conn)?, &albums),
693        Selection::TrackIds(ids) => {
694            let mut rows = Vec::with_capacity(ids.len());
695            for &id in ids {
696                if let Some(row) = queries::get_track_row(&db.conn, id)? {
697                    rows.push(row);
698                }
699            }
700            resolve_from_rows(rows, &albums)
701        }
702        Selection::Paths(paths) => resolve_from_paths(db, paths, &albums)?,
703    };
704    Ok(ResolvedSelection { tracks })
705}
706
707/// Turn a pattern into destinations. **Touches no files at all.**
708///
709/// Everything here is formatting the pattern, sanitising what it produced, and
710/// checking the result against the destinations this same run has already
711/// claimed. That is fast enough to run on every keystroke, which is the whole
712/// reason it is separate from `check_against_disk`.
713pub fn generate(selection: &ResolvedSelection, pattern: &str, base_dir: &Path) -> OrganizeResult {
714    let mut entries = Vec::with_capacity(selection.tracks.len());
715    let mut dests = DestinationLedger::default();
716
717    for track in &selection.tracks {
718        let metadata = match &track.metadata {
719            Ok(m) => m,
720            Err(msg) => {
721                entries.push(PlanEntry {
722                    track_id: track.track_id,
723                    from: track.source.clone(),
724                    to: None,
725                    ancillary: Vec::new(),
726                    outcome: PlanOutcome::Error(msg.clone()),
727                });
728                continue;
729            }
730        };
731        entries.push(plan_single_move(
732            &track.source,
733            track.track_id,
734            metadata,
735            pattern,
736            base_dir,
737            &mut dests,
738        ));
739    }
740
741    OrganizeResult { entries }
742}
743
744/// Resolve, generate, and optionally ask the disk. Every entry point plans
745/// through here, so a preview and the execute that follows it produce the same
746/// destinations from the same metadata.
747fn plan(
748    db: &Database,
749    selection: Selection<'_>,
750    pattern: &str,
751    base_dir: &Path,
752    check_disk: bool,
753) -> Result<OrganizeResult, OrganizeError> {
754    let resolved = resolve_selection(db, selection)?;
755    let mut result = generate(&resolved, pattern, base_dir);
756    if check_disk {
757        check_against_disk(&mut result, move_ancillary());
758    }
759    Ok(result)
760}
761
762/// Plan, then carry out the moves: each file's database rows and its rename land
763/// together or not at all.
764fn run(
765    db: &Database,
766    selection: Selection<'_>,
767    pattern: &str,
768    base_dir: &Path,
769) -> Result<OrganizeResult, OrganizeError> {
770    let mut result = plan(db, selection, pattern, base_dir, true)?;
771
772    let pending: Vec<FileMove> = result
773        .entries
774        .iter()
775        .filter_map(PlanEntry::as_move)
776        .collect();
777    if pending.is_empty() {
778        return Ok(result);
779    }
780
781    check_free_space(&pending, base_dir)?;
782
783    let batch_id = batch_id();
784    let floors = cleanup_floors(Some(base_dir));
785
786    // The plan is the report: a move that fails has its own row demoted to an
787    // error, so the caller sees the same table it confirmed, now saying what
788    // actually happened to each file.
789    for file_move in pending {
790        let failure = match execute_single_move(db, &file_move, &batch_id, &floors) {
791            Ok(()) => verify_move(&file_move).err(),
792            Err(e) => Some(e.to_string()),
793        };
794        let Some(reason) = failure else { continue };
795        log::warn!(
796            "organize: {} → {} failed: {reason}",
797            file_move.from.display(),
798            file_move.to.display()
799        );
800        if let Some(entry) = result.entries.iter_mut().find(|e| e.from == file_move.from) {
801            entry.outcome = PlanOutcome::Error(reason);
802        }
803    }
804
805    Ok(result)
806}
807
808/// Preview what would happen without moving files.
809///
810/// `check_disk` is what finds destinations that are already occupied and the
811/// ancillary files travelling with each move. It is a `stat` per file and a
812/// directory read per source folder, and it changes none of the destinations —
813/// so a preview that reruns as a pattern is typed leaves it off and fills it in
814/// afterwards.
815pub fn preview(
816    db: &Database,
817    pattern: &str,
818    base_dir: Option<&Path>,
819    check_disk: bool,
820) -> Result<OrganizeResult, OrganizeError> {
821    let base = resolve_base_dir(base_dir)?;
822    plan(db, Selection::All, pattern, &base, check_disk)
823}
824
825/// Execute the moves: rename files, update DB, log for undo.
826pub fn execute(
827    db: &Database,
828    pattern: &str,
829    base_dir: Option<&Path>,
830) -> Result<OrganizeResult, OrganizeError> {
831    let base = resolve_base_dir(base_dir)?;
832    run(db, Selection::All, pattern, &base)
833}
834
835/// Preview organize for a specific set of tracks.
836pub fn preview_for_tracks(
837    db: &Database,
838    track_ids: &[i64],
839    pattern: &str,
840    base_dir: Option<&Path>,
841    check_disk: bool,
842) -> Result<OrganizeResult, OrganizeError> {
843    let base = resolve_base_dir(base_dir)?;
844    plan(
845        db,
846        Selection::TrackIds(track_ids),
847        pattern,
848        &base,
849        check_disk,
850    )
851}
852
853/// Execute organize for a specific set of tracks.
854pub fn execute_for_tracks(
855    db: &Database,
856    track_ids: &[i64],
857    pattern: &str,
858    base_dir: Option<&Path>,
859) -> Result<OrganizeResult, OrganizeError> {
860    let base = resolve_base_dir(base_dir)?;
861    run(db, Selection::TrackIds(track_ids), pattern, &base)
862}
863
864/// Preview organize for file paths, which may or may not be in the library.
865pub fn preview_for_paths(
866    paths: &[PathBuf],
867    pattern: &str,
868    base_dir: Option<&Path>,
869    check_disk: bool,
870) -> Result<OrganizeResult, OrganizeError> {
871    let db = crate::db::pool::shared().get()?;
872    let base = resolve_base_dir(base_dir)?;
873    plan(&db, Selection::Paths(paths), pattern, &base, check_disk)
874}
875
876/// Execute organize for file paths. Requires the library database: without it there is
877/// nowhere to record the moves, and an organize that can't be undone isn't offered.
878pub fn execute_for_paths(
879    paths: &[PathBuf],
880    pattern: &str,
881    base_dir: Option<&Path>,
882) -> Result<OrganizeResult, OrganizeError> {
883    let db = crate::db::pool::shared().get()?;
884    let base = resolve_base_dir(base_dir)?;
885    run(&db, Selection::Paths(paths), pattern, &base)
886}
887
888/// Verify a move actually happened — dest exists and source is gone.
889fn verify_move(file_move: &FileMove) -> Result<(), String> {
890    if !file_move.to.exists() {
891        return Err(format!(
892            "destination not found after move: {}",
893            file_move.to.display()
894        ));
895    }
896    if file_move.from.exists() && !paths_equal(&file_move.from, &file_move.to) {
897        return Err(format!(
898            "source still exists after move: {}",
899            file_move.from.display()
900        ));
901    }
902    Ok(())
903}
904
905fn log_move(
906    conn: &Connection,
907    batch_id: &str,
908    track_id: Option<i64>,
909    from: &Path,
910    to: &Path,
911    size: Option<u64>,
912    mtime: Option<i64>,
913) -> Result<(), OrganizeError> {
914    conn.execute(
915        "INSERT INTO organize_log (batch_id, track_id, from_path, to_path, size_bytes, mtime)
916         VALUES (?1, ?2, ?3, ?4, ?5, ?6)",
917        params![
918            batch_id,
919            track_id,
920            from.to_string_lossy().as_ref(),
921            to.to_string_lossy().as_ref(),
922            size.map(|s| s as i64),
923            mtime,
924        ],
925    )?;
926    Ok(())
927}
928
929/// Point every path-keyed row at the file's new location.
930///
931/// `tracks.path` and `scan_cache.path` are UNIQUE, so a move onto a path another row
932/// already claims fails here — inside the caller's transaction, before the file itself
933/// is touched.
934fn rewrite_path_references(conn: &Connection, old: &Path, new: &Path) -> Result<(), OrganizeError> {
935    let old_lossy = old.to_string_lossy();
936    let new_lossy = new.to_string_lossy();
937    let old_path = old_lossy.as_ref();
938    let new_path = new_lossy.as_ref();
939
940    conn.execute(
941        "UPDATE tracks SET path = ?1 WHERE path = ?2",
942        params![new_path, old_path],
943    )?;
944    conn.execute(
945        "UPDATE tracks SET cached_path = ?1 WHERE cached_path = ?2",
946        params![new_path, old_path],
947    )?;
948    conn.execute(
949        "UPDATE scan_cache SET path = ?1 WHERE path = ?2",
950        params![new_path, old_path],
951    )?;
952    // The destination may already be starred from an earlier move; OR REPLACE
953    // leaves exactly one favourite row rather than failing on the primary key.
954    conn.execute(
955        "UPDATE OR REPLACE favourites SET track_path = ?1 WHERE track_path = ?2",
956        params![new_path, old_path],
957    )?;
958    conn.execute(
959        "UPDATE playback_state SET cursor_id = ?1 WHERE cursor_id = ?2",
960        params![new_path, old_path],
961    )?;
962    rewrite_queue_json(conn, old_path, new_path)?;
963    Ok(())
964}
965
966/// Rewrite paths inside the saved session's serialized queue.
967///
968/// Playlists need no equivalent: they point at library rows, and a row's path
969/// changing is a column this function has already updated.
970fn rewrite_queue_json(
971    conn: &Connection,
972    old_path: &str,
973    new_path: &str,
974) -> Result<(), OrganizeError> {
975    let mut stmt =
976        conn.prepare("SELECT id, queue_json FROM playback_state WHERE instr(queue_json, ?1) > 0")?;
977    let rows: Vec<(i64, String)> = stmt
978        .query_map(params![old_path], |row| Ok((row.get(0)?, row.get(1)?)))?
979        .collect::<Result<Vec<_>, _>>()?;
980    drop(stmt);
981
982    for (id, json) in rows {
983        let Ok(mut items) = serde_json::from_str::<Vec<PersistedQueueItem>>(&json) else {
984            continue;
985        };
986        let mut changed = false;
987        for item in &mut items {
988            if item.path == old_path {
989                item.path = new_path.to_string();
990                changed = true;
991            }
992        }
993        if !changed {
994            continue;
995        }
996        let Ok(updated) = serde_json::to_string(&items) else {
997            continue;
998        };
999        conn.execute(
1000            "UPDATE playback_state SET queue_json = ?1 WHERE id = ?2",
1001            params![updated, id],
1002        )?;
1003    }
1004    Ok(())
1005}
1006
1007/// Execute a single file move: write the database rows first, then move the file.
1008/// A constraint violation therefore aborts before anything on disk changes, and a
1009/// failed rename rolls the rows back.
1010fn execute_single_move(
1011    db: &Database,
1012    file_move: &FileMove,
1013    batch_id: &str,
1014    floors: &[PathBuf],
1015) -> Result<(), OrganizeError> {
1016    if let Some(parent) = file_move.to.parent() {
1017        std::fs::create_dir_all(parent)?;
1018    }
1019
1020    let source_meta = std::fs::metadata(&file_move.from)?;
1021    let size = source_meta.len();
1022    let mtime = mtime_secs(&source_meta);
1023
1024    let tx = db.conn.unchecked_transaction()?;
1025    log_move(
1026        &tx,
1027        batch_id,
1028        file_move.track_id,
1029        &file_move.from,
1030        &file_move.to,
1031        Some(size),
1032        mtime,
1033    )?;
1034    rewrite_path_references(&tx, &file_move.from, &file_move.to)?;
1035
1036    // Dropping `tx` on the way out of this `?` rolls the rows back.
1037    move_file(&file_move.from, &file_move.to)?;
1038
1039    let mut moved_ancillary: Vec<(&PathBuf, &PathBuf)> = Vec::new();
1040    let mut failure = None;
1041    for (anc_from, anc_to) in &file_move.ancillary {
1042        if let Some(parent) = anc_to.parent()
1043            && std::fs::create_dir_all(parent).is_err()
1044        {
1045            continue;
1046        }
1047        // Best-effort — artwork that won't move doesn't hold up the audio file.
1048        match move_file(anc_from, anc_to) {
1049            Ok(()) => {
1050                moved_ancillary.push((anc_from, anc_to));
1051                let meta = std::fs::metadata(anc_to).ok();
1052                if let Err(e) = log_move(
1053                    &tx,
1054                    batch_id,
1055                    None,
1056                    anc_from,
1057                    anc_to,
1058                    meta.as_ref().map(|m| m.len()),
1059                    meta.as_ref().and_then(mtime_secs),
1060                ) {
1061                    failure = Some(e);
1062                    break;
1063                }
1064            }
1065            Err(e) => log::warn!(
1066                "failed to move ancillary file {}: {}",
1067                anc_from.display(),
1068                e
1069            ),
1070        }
1071    }
1072
1073    let outcome = match failure {
1074        Some(e) => Err(e),
1075        None => tx.commit().map_err(OrganizeError::from),
1076    };
1077
1078    if let Err(e) = outcome {
1079        // The rows rolled back, so nothing records these files as moved and nothing
1080        // could undo them. Put them back.
1081        for (anc_from, anc_to) in moved_ancillary {
1082            let _ = move_file(anc_to, anc_from);
1083        }
1084        let _ = move_file(&file_move.to, &file_move.from);
1085        return Err(e);
1086    }
1087
1088    if let Some(source_dir) = file_move.from.parent() {
1089        remove_empty_dirs(source_dir, floors);
1090    }
1091
1092    Ok(())
1093}
1094
1095/// Undo the most recent organize batch.
1096///
1097/// Each entry is restored only when the original path is still free and the moved file
1098/// is still the one that was logged. Anything else is reported and left in the log, so
1099/// a single blocked file doesn't strand the rest of the batch.
1100pub fn undo(db: &Database) -> Result<UndoResult, OrganizeError> {
1101    // Newest batch by primary key: created_at only has one-second resolution, so two
1102    // batches in the same second would tie.
1103    let batch_id: String = db
1104        .conn
1105        .query_row(
1106            "SELECT batch_id FROM organize_log ORDER BY id DESC LIMIT 1",
1107            [],
1108            |row| row.get(0),
1109        )
1110        .map_err(|_| OrganizeError::NothingToUndo)?;
1111
1112    let mut stmt = db.conn.prepare(
1113        "SELECT id, from_path, to_path, size_bytes, mtime FROM organize_log
1114         WHERE batch_id = ?1 ORDER BY id DESC",
1115    )?;
1116
1117    let entries: Vec<UndoEntry> = stmt
1118        .query_map(params![batch_id], |row| {
1119            Ok((
1120                row.get(0)?,
1121                row.get(1)?,
1122                row.get(2)?,
1123                row.get(3)?,
1124                row.get(4)?,
1125            ))
1126        })?
1127        .collect::<Result<Vec<_>, _>>()?;
1128    drop(stmt);
1129
1130    let floors = cleanup_floors(None);
1131    let mut result = UndoResult::default();
1132
1133    for (log_id, from_path, to_path, size, mtime) in &entries {
1134        let to = Path::new(to_path);
1135        let from = Path::new(from_path);
1136
1137        if !to.exists() {
1138            // Already moved back or deleted — drop the log row.
1139            db.conn
1140                .execute("DELETE FROM organize_log WHERE id = ?1", params![log_id])?;
1141            continue;
1142        }
1143
1144        if from.exists() && !paths_equal(from, to) {
1145            result.errors.push((
1146                from.to_path_buf(),
1147                format!(
1148                    "another file now occupies the original path; {} left in place",
1149                    to.display()
1150                ),
1151            ));
1152            continue;
1153        }
1154
1155        if let Err(msg) = matches_logged_file(to, *size, *mtime) {
1156            result.errors.push((to.to_path_buf(), msg));
1157            continue;
1158        }
1159
1160        if let Some(parent) = from.parent()
1161            && let Err(e) = std::fs::create_dir_all(parent)
1162        {
1163            result.errors.push((from.to_path_buf(), e.to_string()));
1164            continue;
1165        }
1166
1167        let tx = db.conn.unchecked_transaction()?;
1168        if let Err(e) = rewrite_path_references(&tx, to, from) {
1169            result.errors.push((to.to_path_buf(), e.to_string()));
1170            continue;
1171        }
1172        if let Err(e) = move_file(to, from) {
1173            result.errors.push((to.to_path_buf(), e.to_string()));
1174            continue;
1175        }
1176        if let Err(e) = tx.execute("DELETE FROM organize_log WHERE id = ?1", params![log_id]) {
1177            let _ = move_file(from, to);
1178            result.errors.push((to.to_path_buf(), e.to_string()));
1179            continue;
1180        }
1181        if let Err(e) = tx.commit() {
1182            let _ = move_file(from, to);
1183            result.errors.push((to.to_path_buf(), e.to_string()));
1184            continue;
1185        }
1186
1187        if let Some(parent) = to.parent() {
1188            remove_empty_dirs(parent, &floors);
1189        }
1190
1191        result.restored += 1;
1192    }
1193
1194    Ok(result)
1195}
1196
1197/// Confirm the file at a logged destination is still the file that was moved there.
1198/// Rows written before size/mtime were recorded carry neither and are accepted.
1199fn matches_logged_file(path: &Path, size: Option<i64>, mtime: Option<i64>) -> Result<(), String> {
1200    let (Some(size), Some(mtime)) = (size, mtime) else {
1201        return Ok(());
1202    };
1203    let meta = std::fs::metadata(path).map_err(|e| e.to_string())?;
1204    if meta.len() != size as u64 {
1205        return Err(format!(
1206            "{} has changed since it was moved (size differs); left in place",
1207            path.display()
1208        ));
1209    }
1210    if mtime_secs(&meta).is_some_and(|current| current != mtime) {
1211        return Err(format!(
1212            "{} has changed since it was moved (modification time differs); left in place",
1213            path.display()
1214        ));
1215    }
1216    Ok(())
1217}
1218
1219fn mtime_secs(meta: &std::fs::Metadata) -> Option<i64> {
1220    meta.modified()
1221        .ok()?
1222        .duration_since(UNIX_EPOCH)
1223        .ok()
1224        .map(|d| d.as_secs() as i64)
1225}
1226
1227/// Directories an empty-directory sweep must never remove or climb past.
1228fn cleanup_floors(base: Option<&Path>) -> Vec<PathBuf> {
1229    let mut floors: Vec<PathBuf> = base.map(Path::to_path_buf).into_iter().collect();
1230    if let Ok(config) = crate::config::Config::load() {
1231        floors.extend(config.library.folders);
1232    }
1233    floors
1234}
1235
1236/// Remove the directory a file just left, and its now-empty parents — but never a
1237/// configured library root, and never anything above one.
1238fn remove_empty_dirs(start: &Path, floors: &[PathBuf]) {
1239    let mut current = start.to_path_buf();
1240    loop {
1241        if floors.iter().any(|floor| floor == &current) {
1242            break;
1243        }
1244        let empty = std::fs::read_dir(&current)
1245            .map(|mut d| d.next().is_none())
1246            .unwrap_or(false);
1247        if !empty || std::fs::remove_dir(&current).is_err() {
1248            break;
1249        }
1250        let Some(parent) = current.parent() else {
1251            break;
1252        };
1253        // Only keep climbing inside a directory the run was told about.
1254        if !floors
1255            .iter()
1256            .any(|floor| parent.starts_with(floor) && parent != floor.as_path())
1257        {
1258            break;
1259        }
1260        current = parent.to_path_buf();
1261    }
1262}
1263
1264/// Move a file, never overwriting whatever is already at the destination.
1265fn move_file(from: &Path, to: &Path) -> Result<(), OrganizeError> {
1266    if from == to {
1267        return Ok(());
1268    }
1269    if paths_equal(from, to) {
1270        // Same file under a different spelling — a case-only rename on a
1271        // case-insensitive filesystem. Reserving the destination would land on
1272        // the source itself, so it goes via a temporary name.
1273        return rename_via_temp(from, to);
1274    }
1275
1276    // Claim the name atomically: nothing can slip into the destination between
1277    // this check and the rename below.
1278    match std::fs::OpenOptions::new()
1279        .write(true)
1280        .create_new(true)
1281        .open(to)
1282    {
1283        Ok(_) => {}
1284        Err(e) if e.kind() == ErrorKind::AlreadyExists => {
1285            return Err(OrganizeError::DestinationExists(to.to_path_buf()));
1286        }
1287        Err(e) => return Err(e.into()),
1288    }
1289
1290    match transfer(from, to) {
1291        Ok(()) => Ok(()),
1292        Err(e) => {
1293            // Don't leave the empty placeholder behind.
1294            let _ = std::fs::remove_file(to);
1295            Err(e)
1296        }
1297    }
1298}
1299
1300fn rename_via_temp(from: &Path, to: &Path) -> Result<(), OrganizeError> {
1301    let temp = temp_sibling(to);
1302    std::fs::rename(from, &temp)?;
1303    match std::fs::rename(&temp, to) {
1304        Ok(()) => Ok(()),
1305        Err(e) => {
1306            let _ = std::fs::rename(&temp, from);
1307            Err(e.into())
1308        }
1309    }
1310}
1311
1312/// Rename, falling back to a verified copy when the destination is on another filesystem.
1313fn transfer(from: &Path, to: &Path) -> Result<(), OrganizeError> {
1314    match std::fs::rename(from, to) {
1315        Ok(()) => Ok(()),
1316        // EXDEV (18): cross-device link.
1317        Err(e) if e.raw_os_error() == Some(18) => copy_across_devices(from, to),
1318        Err(e) => Err(e.into()),
1319    }
1320}
1321
1322/// Copy to a temporary file, flush it to disk, verify its length, and only then
1323/// drop the original. A crash at any point leaves the source intact.
1324fn copy_across_devices(from: &Path, to: &Path) -> Result<(), OrganizeError> {
1325    let source_meta = std::fs::metadata(from)?;
1326    let expected = source_meta.len();
1327    let temp = temp_sibling(to);
1328
1329    let copied = {
1330        let mut reader = std::fs::File::open(from)?;
1331        let mut writer = std::fs::OpenOptions::new()
1332            .write(true)
1333            .create_new(true)
1334            .open(&temp)?;
1335        let copied = std::io::copy(&mut reader, &mut writer)?;
1336        // std::io::copy returning Ok only means the bytes reached the page cache.
1337        writer.sync_all()?;
1338        if let Ok(modified) = source_meta.modified() {
1339            let _ = writer.set_modified(modified);
1340        }
1341        copied
1342    };
1343
1344    let written = std::fs::metadata(&temp).map(|m| m.len()).unwrap_or(0);
1345    if copied != expected || written != expected {
1346        let _ = std::fs::remove_file(&temp);
1347        return Err(OrganizeError::ShortCopy {
1348            path: from.to_path_buf(),
1349            expected,
1350            copied: copied.min(written),
1351        });
1352    }
1353
1354    if let Err(e) = std::fs::rename(&temp, to) {
1355        let _ = std::fs::remove_file(&temp);
1356        return Err(e.into());
1357    }
1358    std::fs::remove_file(from)?;
1359    Ok(())
1360}
1361
1362fn temp_sibling(path: &Path) -> PathBuf {
1363    let nanos = SystemTime::now()
1364        .duration_since(UNIX_EPOCH)
1365        .unwrap_or_default()
1366        .as_nanos();
1367    path.with_file_name(format!(".koan-{}-{}.tmp", std::process::id(), nanos))
1368}
1369
1370/// Compare paths for equality, including two spellings of one file on a
1371/// case-insensitive filesystem.
1372fn paths_equal(a: &Path, b: &Path) -> bool {
1373    if a == b {
1374        return true;
1375    }
1376    #[cfg(unix)]
1377    {
1378        use std::os::unix::fs::MetadataExt;
1379        if let (Ok(ma), Ok(mb)) = (std::fs::metadata(a), std::fs::metadata(b)) {
1380            return ma.dev() == mb.dev() && ma.ino() == mb.ino();
1381        }
1382    }
1383    false
1384}
1385
1386/// Refuse a run that can't fit, rather than discovering it partway through.
1387/// Only files landing on a different filesystem need space.
1388fn check_free_space(moves: &[FileMove], base_dir: &Path) -> Result<(), OrganizeError> {
1389    let Some(target) = existing_ancestor(base_dir) else {
1390        return Ok(());
1391    };
1392    let Some(target_device) = device_id(&target) else {
1393        return Ok(());
1394    };
1395
1396    let mut needed = 0u64;
1397    for file_move in moves {
1398        if device_id(&file_move.from).is_some_and(|d| d == target_device) {
1399            continue;
1400        }
1401        if let Ok(meta) = std::fs::metadata(&file_move.from) {
1402            needed = needed.saturating_add(meta.len());
1403        }
1404    }
1405    if needed == 0 {
1406        return Ok(());
1407    }
1408
1409    match available_bytes(&target) {
1410        Some(available) if available < needed => {
1411            Err(OrganizeError::NotEnoughSpace { needed, available })
1412        }
1413        _ => Ok(()),
1414    }
1415}
1416
1417fn existing_ancestor(path: &Path) -> Option<PathBuf> {
1418    path.ancestors().find(|p| p.exists()).map(Path::to_path_buf)
1419}
1420
1421#[cfg(unix)]
1422fn device_id(path: &Path) -> Option<u64> {
1423    use std::os::unix::fs::MetadataExt;
1424    std::fs::metadata(path).ok().map(|m| m.dev())
1425}
1426
1427#[cfg(not(unix))]
1428fn device_id(_path: &Path) -> Option<u64> {
1429    None
1430}
1431
1432#[cfg(unix)]
1433fn available_bytes(path: &Path) -> Option<u64> {
1434    use std::os::unix::ffi::OsStrExt;
1435    let c_path = std::ffi::CString::new(path.as_os_str().as_bytes()).ok()?;
1436    let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
1437    if unsafe { libc::statvfs(c_path.as_ptr(), &mut stat) } != 0 {
1438        return None;
1439    }
1440    // Widths of these fields differ between macOS and Linux.
1441    (stat.f_bavail as u64).checked_mul(stat.f_frsize as u64)
1442}
1443
1444#[cfg(not(unix))]
1445fn available_bytes(_path: &Path) -> Option<u64> {
1446    None
1447}
1448
1449/// Where the pattern's relative paths hang off. `None` uses the first
1450/// configured library folder.
1451///
1452/// An empty path is refused rather than accepted as "here". It makes every
1453/// destination relative to the process's working directory — `/` for an app
1454/// bundle — so the plan formats and previews perfectly and every single move
1455/// then fails at `create_dir_all`.
1456fn resolve_base_dir(base_dir: Option<&Path>) -> Result<PathBuf, OrganizeError> {
1457    let dir = match base_dir {
1458        Some(dir) => dir.to_path_buf(),
1459        None => crate::config::Config::load()
1460            .map_err(|e| OrganizeError::Io(std::io::Error::other(e.to_string())))?
1461            .library
1462            .folders
1463            .into_iter()
1464            .find(|folder| !folder.as_os_str().is_empty())
1465            .ok_or(OrganizeError::NoDestination)?,
1466    };
1467
1468    if dir.as_os_str().is_empty() {
1469        return Err(OrganizeError::NoDestination);
1470    }
1471    Ok(dir)
1472}
1473
1474/// Whether cover art and cue sheets travel with the music. A preference, so it
1475/// is read where it is used rather than threaded through every signature.
1476fn move_ancillary() -> bool {
1477    crate::config::Config::load()
1478        .map(|c| c.organize.move_ancillary)
1479        .unwrap_or(true)
1480}
1481
1482fn batch_id() -> String {
1483    let now = SystemTime::now()
1484        .duration_since(UNIX_EPOCH)
1485        .unwrap_or_default();
1486    format!("batch-{}", now.as_nanos())
1487}
1488
1489#[cfg(test)]
1490mod tests {
1491    use super::*;
1492    use crate::db::queries::TrackMeta;
1493    use crate::db::schema;
1494    use tempfile::TempDir;
1495
1496    fn test_db() -> Database {
1497        let conn = rusqlite::Connection::open_in_memory().unwrap();
1498        conn.pragma_update(None, "foreign_keys", "on").unwrap();
1499        schema::create_tables(&conn).unwrap();
1500        Database { conn }
1501    }
1502
1503    fn sample_meta(title: &str, artist: &str, album: &str) -> TrackMeta {
1504        TrackMeta {
1505            title: title.into(),
1506            artist: artist.into(),
1507            album_artist: Some(artist.into()),
1508            album: album.into(),
1509            date: Some("1997-06-16".into()),
1510            disc: Some(1),
1511            track_number: Some(1),
1512            genre: Some("Rock".into()),
1513            label: None,
1514            duration_ms: Some(240_000),
1515            codec: Some("FLAC".into()),
1516            sample_rate: Some(44100),
1517            bit_depth: Some(16),
1518            channels: Some(2),
1519            bitrate: Some(1000),
1520            size_bytes: Some(30_000_000),
1521            mtime: Some(1700000000),
1522            path: None,
1523            source: "local".into(),
1524            remote_id: None,
1525            remote_url: None,
1526            album_remote_id: None,
1527            artist_remote_id: None,
1528            mbid: None,
1529            album_mbid: None,
1530            album_added_at: None,
1531        }
1532    }
1533
1534    fn sample_track_row(title: &str, artist: &str, album: &str) -> TrackRow {
1535        TrackRow {
1536            id: 1,
1537            album_id: Some(1),
1538            artist_id: Some(1),
1539            artist_name: artist.into(),
1540            album_artist_name: artist.into(),
1541            album_title: album.into(),
1542            disc: Some(1),
1543            track_number: Some(1),
1544            title: title.into(),
1545            duration_ms: Some(240_000),
1546            path: Some("/music/test.flac".into()),
1547            codec: Some("FLAC".into()),
1548            sample_rate: Some(44100),
1549            bit_depth: Some(16),
1550            channels: Some(2),
1551            bitrate: Some(1000),
1552            genre: None,
1553            source: "local".into(),
1554            remote_id: None,
1555            cached_path: None,
1556        }
1557    }
1558
1559    /// Write a file with recognisable contents and register it in the library.
1560    fn add_track(db: &Database, path: &Path, title: &str, track_number: i32) -> i64 {
1561        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
1562        std::fs::write(path, format!("audio bytes for {title}")).unwrap();
1563        let mut meta = sample_meta(title, "Radiohead", "OK Computer");
1564        meta.track_number = Some(track_number);
1565        meta.path = Some(path.to_string_lossy().into_owned());
1566        queries::upsert_track(&db.conn, &meta).unwrap()
1567    }
1568
1569    fn db_path_of(db: &Database, track_id: i64) -> Option<String> {
1570        db.conn
1571            .query_row(
1572                "SELECT path FROM tracks WHERE id = ?1",
1573                params![track_id],
1574                |row| row.get(0),
1575            )
1576            .unwrap()
1577    }
1578
1579    fn log_rows(db: &Database) -> Vec<(Option<i64>, String, String)> {
1580        let mut stmt = db
1581            .conn
1582            .prepare("SELECT track_id, from_path, to_path FROM organize_log ORDER BY id")
1583            .unwrap();
1584        let rows = stmt
1585            .query_map([], |row| Ok((row.get(0)?, row.get(1)?, row.get(2)?)))
1586            .unwrap();
1587        rows.map(|r| r.unwrap()).collect()
1588    }
1589
1590    // ---- Metadata + sanitisation ----
1591
1592    #[test]
1593    fn track_metadata_provider_fields() {
1594        let mut track = sample_track_row("Subterranean Homesick Alien", "Radiohead", "OK Computer");
1595        track.track_number = Some(3);
1596        track.genre = Some("Alternative".into());
1597
1598        let album = AlbumFacts {
1599            date: Some("1997-06-16".into()),
1600            label: Some("Parlophone".into()),
1601        };
1602        let meta = TrackMetadata::from_track_row(&track, &album);
1603        assert_eq!(
1604            meta.get_field("title").as_deref(),
1605            Some("Subterranean Homesick Alien")
1606        );
1607        assert_eq!(meta.get_field("artist").as_deref(), Some("Radiohead"));
1608        assert_eq!(meta.get_field("album artist").as_deref(), Some("Radiohead"));
1609        assert_eq!(meta.get_field("album").as_deref(), Some("OK Computer"));
1610        assert_eq!(meta.get_field("tracknumber").as_deref(), Some("03"));
1611        assert_eq!(meta.get_field("discnumber").as_deref(), Some("1"));
1612        assert_eq!(meta.get_field("date").as_deref(), Some("1997-06-16"));
1613        assert_eq!(meta.get_field("label").as_deref(), Some("Parlophone"));
1614        assert_eq!(meta.get_field("codec").as_deref(), Some("FLAC"));
1615        assert_eq!(meta.get_field("genre").as_deref(), Some("Alternative"));
1616        assert_eq!(meta.get_field("nonexistent"), None);
1617    }
1618
1619    /// Both providers must populate the same field names, or a preview taken from one
1620    /// authorises a move planned by the other.
1621    #[test]
1622    fn both_metadata_sources_expose_the_same_fields() {
1623        let mut track = sample_track_row("Airbag", "Radiohead", "OK Computer");
1624        track.genre = Some("Rock".into());
1625        let album = AlbumFacts {
1626            date: Some("1997-06-16".into()),
1627            label: Some("Parlophone".into()),
1628        };
1629        let from_db = TrackMetadata::from_track_row(&track, &album);
1630
1631        let mut meta = sample_meta("Airbag", "Radiohead", "OK Computer");
1632        meta.label = Some("Parlophone".into());
1633        let from_tags = TrackMetadata::from_file_meta(&meta);
1634
1635        let mut db_fields: Vec<&String> = from_db.fields.keys().collect();
1636        let mut tag_fields: Vec<&String> = from_tags.fields.keys().collect();
1637        db_fields.sort();
1638        tag_fields.sort();
1639        assert_eq!(db_fields, tag_fields);
1640    }
1641
1642    #[test]
1643    fn sanitize_replaces_illegal_chars() {
1644        assert_eq!(sanitise_filename("AC/DC"), "AC_DC");
1645        assert_eq!(sanitise_filename("What?"), "What_");
1646        assert_eq!(sanitise_filename("a:b*c"), "a_b_c");
1647        assert_eq!(sanitise_filename("normal"), "normal");
1648    }
1649
1650    #[test]
1651    fn sanitize_relative_path_splits() {
1652        assert_eq!(
1653            sanitize_relative_path("Artist/Album/Track").unwrap(),
1654            PathBuf::from("Artist/Album/Track")
1655        );
1656        assert_eq!(
1657            sanitize_relative_path("Radiohead/(1997) OK Computer/01. Airbag").unwrap(),
1658            PathBuf::from("Radiohead/(1997) OK Computer/01. Airbag")
1659        );
1660    }
1661
1662    #[test]
1663    fn sanitize_relative_path_refuses_traversal_and_gaps() {
1664        // Reinterpreting these silently is what turns one bad pattern into a
1665        // directory full of overwritten files.
1666        assert!(sanitize_relative_path("../../../../etc/passwd").is_err());
1667        assert!(sanitize_relative_path("Artist/../../../outside").is_err());
1668        assert!(sanitize_relative_path("./Artist/./Album").is_err());
1669        assert!(sanitize_relative_path("Radiohead/OK Computer/").is_err());
1670        assert!(sanitize_relative_path("Radiohead//Airbag").is_err());
1671        assert!(sanitize_relative_path("   /Airbag").is_err());
1672    }
1673
1674    #[test]
1675    fn acdc_artist_name_sanitized() {
1676        let track = sample_track_row("Highway to Hell", "AC/DC", "Highway to Hell");
1677        let meta = TrackMetadata::from_track_row(&track, &AlbumFacts::default());
1678        assert_eq!(meta.get_field("album artist").as_deref(), Some("AC_DC"));
1679        let result = format::format("%album artist%/%album%/%title%", &meta).unwrap();
1680        assert_eq!(result, "AC_DC/Highway to Hell/Highway to Hell");
1681    }
1682
1683    #[test]
1684    fn format_string_evaluation() {
1685        let track = sample_track_row("Airbag", "Radiohead", "OK Computer");
1686        let album = AlbumFacts {
1687            date: Some("1997-06-16".into()),
1688            label: None,
1689        };
1690        let meta = TrackMetadata::from_track_row(&track, &album);
1691        let pattern =
1692            "%album artist%/['('$left(%date%,4)')' ]%album%/$num(%tracknumber%,2). %title%";
1693        assert_eq!(
1694            format::format(pattern, &meta).unwrap(),
1695            "Radiohead/(1997) OK Computer/01. Airbag"
1696        );
1697    }
1698
1699    #[test]
1700    fn ancillary_file_detection() {
1701        let tmp = TempDir::new().unwrap();
1702        let dir = tmp.path();
1703        std::fs::write(dir.join("cover.jpg"), b"img").unwrap();
1704        std::fs::write(dir.join("cover.png"), b"img").unwrap();
1705        std::fs::write(dir.join("album.cue"), b"cue").unwrap();
1706        std::fs::write(dir.join("rip.log"), b"log").unwrap();
1707        std::fs::write(dir.join("track.flac"), b"audio").unwrap();
1708
1709        let found = find_ancillary_files(dir);
1710        assert!(found.iter().any(|p| p.file_name().unwrap() == "cover.jpg"));
1711        assert!(found.iter().any(|p| p.file_name().unwrap() == "cover.png"));
1712        assert!(found.iter().any(|p| p.file_name().unwrap() == "album.cue"));
1713        assert!(found.iter().any(|p| p.file_name().unwrap() == "rip.log"));
1714        assert!(!found.iter().any(|p| p.file_name().unwrap() == "track.flac"));
1715    }
1716
1717    // ---- Preview / execute ----
1718
1719    #[test]
1720    fn preview_does_not_move_files() {
1721        let db = test_db();
1722        let tmp = TempDir::new().unwrap();
1723        let source = tmp.path().join("src/test.flac");
1724        add_track(&db, &source, "Airbag", 1);
1725
1726        let result = preview(
1727            &db,
1728            "%album artist%/%album%/%title%",
1729            Some(tmp.path()),
1730            true,
1731        )
1732        .unwrap();
1733        assert!(source.exists());
1734        assert_eq!(result.moved_count(), 1);
1735    }
1736
1737    #[test]
1738    fn execute_moves_files_and_undo_reverts() {
1739        let db = test_db();
1740        let tmp = TempDir::new().unwrap();
1741        let source = tmp.path().join("src/test.flac");
1742        let id = add_track(&db, &source, "Airbag", 1);
1743
1744        let result = execute(&db, "%album artist%/%album%/%title%", Some(tmp.path())).unwrap();
1745        assert_eq!(result.moved_count(), 1);
1746        assert_eq!(result.failures().count(), 0);
1747        assert!(!source.exists());
1748        let dest = result.moves().next().unwrap().dest().to_path_buf();
1749        assert!(dest.exists());
1750        assert_eq!(db_path_of(&db, id).as_deref(), Some(dest.to_str().unwrap()));
1751
1752        let undone = undo(&db).unwrap();
1753        assert_eq!(undone.restored, 1);
1754        assert!(undone.errors.is_empty());
1755        assert!(source.exists());
1756        assert!(!dest.exists());
1757        assert_eq!(
1758            db_path_of(&db, id).as_deref(),
1759            Some(source.to_str().unwrap())
1760        );
1761    }
1762
1763    /// The preview a user confirms and the moves that follow must agree. They read
1764    /// metadata through the same resolver, so a pattern using an album-level field
1765    /// (here `%label%`) resolves identically in both.
1766    #[test]
1767    fn preview_and_execute_agree_on_destinations() {
1768        let db = test_db();
1769        let tmp = TempDir::new().unwrap();
1770        let pattern = "$if2(%label%,%album artist%)/%album%/[$num(%tracknumber%,2). ]%title%";
1771
1772        let source = tmp.path().join("src/aphex.flac");
1773        std::fs::create_dir_all(source.parent().unwrap()).unwrap();
1774        std::fs::write(&source, b"audio").unwrap();
1775        let mut meta = sample_meta("Xtal", "Aphex Twin", "Selected Ambient Works");
1776        meta.label = Some("Warp Records".into());
1777        meta.path = Some(source.to_string_lossy().into_owned());
1778        queries::upsert_track(&db.conn, &meta).unwrap();
1779
1780        let previewed = preview(&db, pattern, Some(tmp.path()), true).unwrap();
1781        assert_eq!(previewed.moved_count(), 1);
1782        let expected = previewed.moves().next().unwrap().dest().to_path_buf();
1783        assert!(expected.starts_with(tmp.path().join("Warp Records")));
1784
1785        let executed = execute(&db, pattern, Some(tmp.path())).unwrap();
1786        assert_eq!(executed.moved_count(), 1);
1787        assert_eq!(executed.moves().next().unwrap().dest(), expected);
1788        assert!(expected.exists());
1789    }
1790
1791    /// The whole macOS flow, end to end: files land from outside the library,
1792    /// get rows where they lie, and organize is what puts them under the music
1793    /// tree. Nothing about the import knows where they will end up.
1794    #[test]
1795    fn imported_files_organize_into_the_library_folder() {
1796        let db = test_db();
1797        let tmp = TempDir::new().unwrap();
1798        let outside = tmp.path().join("Downloads/rip");
1799        let library = tmp.path().join("Music");
1800        std::fs::create_dir_all(&outside).unwrap();
1801        std::fs::create_dir_all(&library).unwrap();
1802
1803        let dropped = outside.join("track.wav");
1804        crate::test_utils::generate_wav(&dropped, 44100, 1, 0.2, 16);
1805
1806        let imported = crate::index::scanner::import_paths(&db, std::slice::from_ref(&outside));
1807        assert_eq!(imported.track_ids.len(), 1, "errors: {:?}", imported.errors);
1808
1809        let result = execute_for_tracks(
1810            &db,
1811            &imported.track_ids,
1812            "%album artist%/%album%/%title%",
1813            Some(&library),
1814        )
1815        .unwrap();
1816
1817        assert_eq!(result.moved_count(), 1);
1818        let dest = result.moves().next().unwrap().dest();
1819        assert!(dest.starts_with(&library), "landed at {}", dest.display());
1820        assert!(dest.exists());
1821        assert!(
1822            !dropped.exists(),
1823            "the original should have moved, not copied"
1824        );
1825
1826        // The row followed the file, so playing it afterwards still works.
1827        assert_eq!(
1828            db_path_of(&db, imported.track_ids[0]).as_deref(),
1829            dest.to_str()
1830        );
1831    }
1832
1833    /// Generation is pure. It is what reruns on every keystroke, so if it ever
1834    /// starts touching the filesystem this is what says so: the destination is
1835    /// occupied and the source directory is full of cover art, and neither
1836    /// shows up until the disk is actually asked.
1837    #[test]
1838    fn generate_touches_no_files() {
1839        let db = test_db();
1840        let tmp = TempDir::new().unwrap();
1841        let source = tmp.path().join("src/track.flac");
1842        add_track(&db, &source, "Airbag", 1);
1843        std::fs::write(source.parent().unwrap().join("cover.jpg"), b"art").unwrap();
1844
1845        // Something is already sitting where the pattern points.
1846        let occupied = tmp.path().join("Radiohead/OK Computer/Airbag.flac");
1847        std::fs::create_dir_all(occupied.parent().unwrap()).unwrap();
1848        std::fs::write(&occupied, b"the good rip").unwrap();
1849
1850        let selection = resolve(&db, None).unwrap();
1851        let mut result = generate(&selection, "%album artist%/%album%/%title%", tmp.path());
1852
1853        // Pure pass: a move, no conflict, no ancillary — it has not looked.
1854        assert_eq!(result.moved_count(), 1);
1855        assert_eq!(result.conflicts().count(), 0);
1856        assert!(result.entries[0].ancillary.is_empty());
1857
1858        // Asking the disk is what finds both.
1859        check_against_disk(&mut result, true);
1860        assert_eq!(result.moved_count(), 0);
1861        assert_eq!(result.conflicts().count(), 1);
1862        assert_eq!(result.conflicts().next().unwrap().dest(), occupied);
1863    }
1864
1865    /// A caller with no library folder configured passes an empty base dir.
1866    /// Taken literally it means "relative to wherever this process happens to
1867    /// be", which plans and previews cleanly and then fails on every file, so
1868    /// it is refused before a plan exists to confirm.
1869    #[test]
1870    fn an_empty_base_dir_is_not_a_destination() {
1871        let db = test_db();
1872        add_track(&db, Path::new("/tmp/src/a.flac"), "Airbag", 1);
1873
1874        let err = preview(&db, "%title%", Some(Path::new("")), false).unwrap_err();
1875        assert!(matches!(err, OrganizeError::NoDestination));
1876
1877        let err = execute(&db, "%title%", Some(Path::new(""))).unwrap_err();
1878        assert!(matches!(err, OrganizeError::NoDestination));
1879    }
1880
1881    /// Resolving once and generating many times must agree with planning from
1882    /// scratch, or the preview would be lying about what execute will do.
1883    #[test]
1884    fn generate_agrees_with_a_full_plan() {
1885        let db = test_db();
1886        let tmp = TempDir::new().unwrap();
1887        add_track(&db, &tmp.path().join("src/a.flac"), "Airbag", 1);
1888        add_track(&db, &tmp.path().join("src/b.flac"), "Karma Police", 2);
1889        let pattern = "%album artist%/%album%/%tracknumber%. %title%";
1890
1891        let selection = resolve(&db, None).unwrap();
1892        let mut generated = generate(&selection, pattern, tmp.path());
1893        check_against_disk(&mut generated, true);
1894        let planned = preview(&db, pattern, Some(tmp.path()), true).unwrap();
1895
1896        assert_eq!(generated.entries.len(), planned.entries.len());
1897        for (a, b) in generated.entries.iter().zip(&planned.entries) {
1898            assert_eq!(a.from, b.from);
1899            assert_eq!(a.to, b.to);
1900            assert_eq!(a.outcome, b.outcome);
1901            assert_eq!(a.ancillary, b.ancillary);
1902        }
1903    }
1904
1905    /// One readdir per source directory, not one per file — the thing that made
1906    /// a preview over an album on a slow volume cost what it did.
1907    #[test]
1908    fn ancillary_is_scanned_once_per_directory() {
1909        let db = test_db();
1910        let tmp = TempDir::new().unwrap();
1911        for (i, title) in ["Airbag", "Karma Police", "Lucky"].iter().enumerate() {
1912            add_track(
1913                &db,
1914                &tmp.path().join(format!("src/{i}.flac")),
1915                title,
1916                i as i32 + 1,
1917            );
1918        }
1919        std::fs::write(tmp.path().join("src/cover.jpg"), b"art").unwrap();
1920
1921        let result = preview(
1922            &db,
1923            "%album artist%/%album%/%title%",
1924            Some(tmp.path()),
1925            true,
1926        )
1927        .unwrap();
1928
1929        // The cover travels with exactly one of them, not all three.
1930        let carrying: Vec<_> = result.moves().filter(|e| !e.ancillary.is_empty()).collect();
1931        assert_eq!(carrying.len(), 1);
1932        assert_eq!(carrying[0].ancillary.len(), 1);
1933    }
1934
1935    /// The disk pass must not mistake a file for its own obstacle. Nothing
1936    /// stops a caller planning against paths a previous run already moved, and
1937    /// a bare `exists()` on the destination says "occupied" for every one of
1938    /// them.
1939    #[test]
1940    fn a_file_already_at_its_destination_is_unchanged_not_a_conflict() {
1941        let db = test_db();
1942        let tmp = TempDir::new().unwrap();
1943        let pattern = "%album artist%/%album%/%title%";
1944        add_track(&db, &tmp.path().join("src/a.flac"), "Airbag", 1);
1945
1946        let moved = execute(&db, pattern, Some(tmp.path())).unwrap();
1947        assert_eq!(moved.moved_count(), 1);
1948
1949        // Plan again, from the rows as they now stand.
1950        let again = preview(&db, pattern, Some(tmp.path()), true).unwrap();
1951        assert_eq!(again.conflicts().count(), 0);
1952        assert_eq!(again.unchanged_count(), 1);
1953    }
1954
1955    #[test]
1956    fn ancillary_files_stay_put_when_they_are_turned_off() {
1957        let db = test_db();
1958        let tmp = TempDir::new().unwrap();
1959        let source = tmp.path().join("src/a.flac");
1960        add_track(&db, &source, "Airbag", 1);
1961        std::fs::write(source.parent().unwrap().join("cover.jpg"), b"art").unwrap();
1962
1963        let selection = resolve(&db, None).unwrap();
1964        let mut off = generate(&selection, "%album artist%/%album%/%title%", tmp.path());
1965        check_against_disk(&mut off, false);
1966        assert!(off.moves().all(|e| e.ancillary.is_empty()));
1967
1968        let mut on = generate(&selection, "%album artist%/%album%/%title%", tmp.path());
1969        check_against_disk(&mut on, true);
1970        assert_eq!(on.moves().next().unwrap().ancillary.len(), 1);
1971    }
1972
1973    // ---- Collisions ----
1974
1975    #[test]
1976    fn colliding_destinations_leave_both_files_intact() {
1977        let db = test_db();
1978        let tmp = TempDir::new().unwrap();
1979        let first = tmp.path().join("src/a.flac");
1980        let second = tmp.path().join("src/b.flac");
1981        // Same title, different track numbers: two library rows, one destination.
1982        let first_id = add_track(&db, &first, "Airbag", 1);
1983        let second_id = add_track(&db, &second, "Airbag", 2);
1984        let second_bytes = std::fs::read(&second).unwrap();
1985
1986        let result = execute(&db, "%album artist%/%album%/%title%", Some(tmp.path())).unwrap();
1987
1988        assert_eq!(result.moved_count(), 1);
1989
1990        // The loser is a row in the plan, flagged as a conflict and still
1991        // carrying the destination it lost — that is what a preview shows.
1992        let blocked = result.conflicts().next().unwrap();
1993        assert_eq!(result.conflicts().count(), 1);
1994        assert_eq!(blocked.from, second);
1995        assert_eq!(blocked.dest(), result.moves().next().unwrap().dest());
1996
1997        // The loser stays exactly where it was, byte for byte.
1998        assert!(second.exists());
1999        assert_eq!(std::fs::read(&second).unwrap(), second_bytes);
2000        assert_eq!(
2001            db_path_of(&db, second_id).as_deref(),
2002            Some(second.to_str().unwrap())
2003        );
2004
2005        let dest = result.moves().next().unwrap().dest();
2006        assert_eq!(
2007            std::fs::read(dest).unwrap(),
2008            b"audio bytes for Airbag".to_vec()
2009        );
2010        assert_eq!(
2011            db_path_of(&db, first_id).as_deref(),
2012            Some(dest.to_str().unwrap())
2013        );
2014    }
2015
2016    #[test]
2017    fn existing_destination_is_never_overwritten() {
2018        let db = test_db();
2019        let tmp = TempDir::new().unwrap();
2020        let source = tmp.path().join("src/new.flac");
2021        add_track(&db, &source, "Airbag", 1);
2022
2023        // Something unrelated is already sitting at the destination.
2024        let dest = tmp.path().join("Radiohead/OK Computer/Airbag.flac");
2025        std::fs::create_dir_all(dest.parent().unwrap()).unwrap();
2026        std::fs::write(&dest, b"the good rip").unwrap();
2027
2028        let result = execute(&db, "%album artist%/%album%/%title%", Some(tmp.path())).unwrap();
2029        assert_eq!(result.moved_count(), 0);
2030
2031        // Flagged as a conflict against the occupied path, so a preview can say
2032        // what would have been overwritten before anyone presses the button.
2033        let blocked = result.conflicts().next().unwrap();
2034        assert_eq!(result.conflicts().count(), 1);
2035        assert_eq!(blocked.from, source);
2036        assert_eq!(blocked.dest(), dest);
2037        assert!(blocked.outcome.reason().unwrap().contains("overwritten"));
2038
2039        assert_eq!(std::fs::read(&dest).unwrap(), b"the good rip".to_vec());
2040        assert!(source.exists());
2041    }
2042
2043    /// `move_file` is the last line of defence: even handed a destination that exists,
2044    /// it refuses rather than replacing it.
2045    #[test]
2046    fn move_file_refuses_an_occupied_destination() {
2047        let tmp = TempDir::new().unwrap();
2048        let from = tmp.path().join("a.flac");
2049        let to = tmp.path().join("b.flac");
2050        std::fs::write(&from, b"source").unwrap();
2051        std::fs::write(&to, b"keep me").unwrap();
2052
2053        let err = move_file(&from, &to).unwrap_err();
2054        assert!(matches!(err, OrganizeError::DestinationExists(_)));
2055        assert_eq!(std::fs::read(&to).unwrap(), b"keep me".to_vec());
2056        assert_eq!(std::fs::read(&from).unwrap(), b"source".to_vec());
2057    }
2058
2059    #[cfg(any(target_os = "macos", target_os = "ios"))]
2060    #[test]
2061    fn case_only_difference_collides_on_a_case_insensitive_filesystem() {
2062        let db = test_db();
2063        let tmp = TempDir::new().unwrap();
2064        let first = tmp.path().join("src/1.flac");
2065        let second = tmp.path().join("src/2.flac");
2066        std::fs::create_dir_all(first.parent().unwrap()).unwrap();
2067        for (path, title, number) in [(&first, "Rain", 1i32), (&second, "RAIN", 2)] {
2068            std::fs::write(path, format!("audio bytes for {title}")).unwrap();
2069            let mut meta = sample_meta(title, "Radiohead", "OK Computer");
2070            meta.track_number = Some(number);
2071            meta.path = Some(path.to_string_lossy().into_owned());
2072            queries::upsert_track(&db.conn, &meta).unwrap();
2073        }
2074
2075        let result = execute(&db, "%album artist%/%album%/%title%", Some(tmp.path())).unwrap();
2076        assert_eq!(result.moved_count(), 1);
2077        assert_eq!(result.failures().count(), 1);
2078        assert!(second.exists());
2079        assert_eq!(
2080            std::fs::read(&second).unwrap(),
2081            b"audio bytes for RAIN".to_vec()
2082        );
2083    }
2084
2085    /// A rename that only changes case has to go via a temporary name: reserving the
2086    /// destination would otherwise open the source file itself.
2087    /// Not on iOS: the simulator's sandboxed filesystem answers `stat` for
2088    /// `Rain.flac` with ENOENT while `open(O_CREAT|O_EXCL)` on the same name
2089    /// answers EEXIST — measured, both, in one directory. `paths_equal` reads
2090    /// `stat`, so the case-only rename it exists to catch cannot be detected
2091    /// there. Unverified on a device, where the volume is ordinary APFS.
2092    #[cfg(not(target_os = "ios"))]
2093    #[test]
2094    fn case_only_rename_keeps_the_file() {
2095        let tmp = TempDir::new().unwrap();
2096        let from = tmp.path().join("rain.flac");
2097        let to = tmp.path().join("Rain.flac");
2098        std::fs::write(&from, b"audio bytes").unwrap();
2099
2100        move_file(&from, &to).unwrap();
2101
2102        assert_eq!(std::fs::read(&to).unwrap(), b"audio bytes".to_vec());
2103        let names: Vec<String> = std::fs::read_dir(tmp.path())
2104            .unwrap()
2105            .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
2106            .collect();
2107        assert_eq!(names, vec!["Rain.flac".to_string()]);
2108    }
2109
2110    /// The cross-device path copies, flushes and verifies before unlinking the
2111    /// original, so an interrupted move can never leave a truncated file and no source.
2112    #[test]
2113    fn cross_device_copy_verifies_before_dropping_the_source() {
2114        let tmp = TempDir::new().unwrap();
2115        let from = tmp.path().join("a.flac");
2116        let to = tmp.path().join("b.flac");
2117        let bytes: Vec<u8> = (0..64_000u32).map(|i| (i % 251) as u8).collect();
2118        std::fs::write(&from, &bytes).unwrap();
2119        let mtime = std::fs::metadata(&from).unwrap().modified().unwrap();
2120
2121        copy_across_devices(&from, &to).unwrap();
2122
2123        assert!(!from.exists());
2124        assert_eq!(std::fs::read(&to).unwrap(), bytes);
2125        // Preserved, so scan_cache entries stay valid across a cross-device move.
2126        assert_eq!(std::fs::metadata(&to).unwrap().modified().unwrap(), mtime);
2127        // No temporary left behind.
2128        let leftovers: Vec<_> = std::fs::read_dir(tmp.path())
2129            .unwrap()
2130            .filter(|e| {
2131                e.as_ref()
2132                    .unwrap()
2133                    .file_name()
2134                    .to_string_lossy()
2135                    .starts_with(".koan-")
2136            })
2137            .collect();
2138        assert!(leftovers.is_empty());
2139    }
2140
2141    #[test]
2142    fn free_space_check_ignores_same_device_moves() {
2143        let tmp = TempDir::new().unwrap();
2144        let from = tmp.path().join("a.flac");
2145        std::fs::write(&from, b"audio").unwrap();
2146        let moves = vec![FileMove {
2147            track_id: None,
2148            from,
2149            to: tmp.path().join("b.flac"),
2150            ancillary: Vec::new(),
2151        }];
2152        // A rename within one filesystem consumes no space.
2153        assert!(check_free_space(&moves, tmp.path()).is_ok());
2154    }
2155
2156    // ---- Bad patterns ----
2157
2158    #[test]
2159    fn unknown_function_refuses_the_move() {
2160        let db = test_db();
2161        let tmp = TempDir::new().unwrap();
2162        let source = tmp.path().join("src/test.flac");
2163        add_track(&db, &source, "Airbag", 1);
2164
2165        // $nun instead of $num.
2166        let result = execute(
2167            &db,
2168            "%album artist%/%album%/$nun(%tracknumber%,2). %title%",
2169            Some(tmp.path()),
2170        )
2171        .unwrap();
2172        assert_eq!(result.moved_count(), 0);
2173        assert_eq!(result.failures().count(), 1);
2174        assert!(result.failure_messages()[0].contains("unknown function"));
2175        assert!(source.exists());
2176    }
2177
2178    /// An empty last component used to append the extension to the parent directory,
2179    /// pointing every track on an album at one file.
2180    #[test]
2181    fn empty_final_component_refuses_the_move() {
2182        let db = test_db();
2183        let tmp = TempDir::new().unwrap();
2184        let first = tmp.path().join("src/a.flac");
2185        let second = tmp.path().join("src/b.flac");
2186        add_track(&db, &first, "Airbag", 1);
2187        add_track(&db, &second, "Karma Police", 2);
2188
2189        // The conditional resolves to nothing, leaving a trailing separator.
2190        let result = execute(
2191            &db,
2192            "%album artist%/%album%/[%nonexistent field%]",
2193            Some(tmp.path()),
2194        )
2195        .unwrap();
2196
2197        assert_eq!(result.moved_count(), 0);
2198        assert_eq!(result.failures().count(), 2);
2199        assert!(first.exists());
2200        assert!(second.exists());
2201        assert!(!tmp.path().join("Radiohead/OK Computer.flac").exists());
2202    }
2203
2204    #[test]
2205    fn long_title_is_truncated_rather_than_failing() {
2206        let db = test_db();
2207        let tmp = TempDir::new().unwrap();
2208        let source = tmp.path().join("src/test.flac");
2209        let title = "a".repeat(300);
2210        add_track(&db, &source, &title, 1);
2211
2212        let result = execute(&db, "%album artist%/%album%/%title%", Some(tmp.path())).unwrap();
2213        assert_eq!(
2214            result.moved_count(),
2215            1,
2216            "errors: {:?}",
2217            result.failure_messages()
2218        );
2219        let name = result
2220            .moves()
2221            .next()
2222            .unwrap()
2223            .dest()
2224            .file_name()
2225            .unwrap()
2226            .to_string_lossy();
2227        assert!(name.len() <= MAX_FILE_NAME_BYTES);
2228        assert!(name.ends_with(".flac"));
2229        assert!(result.moves().next().unwrap().dest().exists());
2230    }
2231
2232    // ---- Directory cleanup ----
2233
2234    #[test]
2235    fn remove_empty_dirs_never_climbs_past_a_floor() {
2236        let tmp = TempDir::new().unwrap();
2237        let root = tmp.path().join("library");
2238        let nested = root.join("artist/album");
2239        std::fs::create_dir_all(&nested).unwrap();
2240
2241        remove_empty_dirs(&nested, std::slice::from_ref(&root));
2242
2243        assert!(!nested.exists());
2244        assert!(!root.join("artist").exists());
2245        assert!(root.exists(), "the library root must survive");
2246    }
2247
2248    #[test]
2249    fn remove_empty_dirs_stays_put_outside_any_floor() {
2250        let tmp = TempDir::new().unwrap();
2251        let outside = tmp.path().join("incoming/rip");
2252        std::fs::create_dir_all(&outside).unwrap();
2253
2254        remove_empty_dirs(&outside, &[tmp.path().join("library")]);
2255
2256        assert!(!outside.exists());
2257        assert!(
2258            tmp.path().join("incoming").exists(),
2259            "no floor means no climbing"
2260        );
2261    }
2262
2263    #[test]
2264    fn remove_empty_dirs_never_removes_a_floor_itself() {
2265        let tmp = TempDir::new().unwrap();
2266        let root = tmp.path().join("library");
2267        std::fs::create_dir_all(&root).unwrap();
2268
2269        remove_empty_dirs(&root, std::slice::from_ref(&root));
2270
2271        assert!(root.exists());
2272    }
2273
2274    // ---- Undo ----
2275
2276    #[test]
2277    fn undo_refuses_when_the_original_path_is_occupied() {
2278        let db = test_db();
2279        let tmp = TempDir::new().unwrap();
2280        let source = tmp.path().join("src/test.flac");
2281        add_track(&db, &source, "Airbag", 1);
2282
2283        let result = execute(&db, "%album artist%/%album%/%title%", Some(tmp.path())).unwrap();
2284        let dest = result.moves().next().unwrap().dest().to_path_buf();
2285
2286        // A different rip lands at the vacated path before the undo.
2287        std::fs::create_dir_all(source.parent().unwrap()).unwrap();
2288        std::fs::write(&source, b"a completely different rip").unwrap();
2289
2290        let undone = undo(&db).unwrap();
2291        assert_eq!(undone.restored, 0);
2292        assert_eq!(undone.errors.len(), 1);
2293        assert_eq!(
2294            std::fs::read(&source).unwrap(),
2295            b"a completely different rip".to_vec()
2296        );
2297        assert!(dest.exists());
2298        // The entry stays in the log so it can be undone once the path is free.
2299        assert_eq!(log_rows(&db).len(), 1);
2300    }
2301
2302    #[test]
2303    fn undo_refuses_when_the_moved_file_has_been_replaced() {
2304        let db = test_db();
2305        let tmp = TempDir::new().unwrap();
2306        let source = tmp.path().join("src/test.flac");
2307        add_track(&db, &source, "Airbag", 1);
2308
2309        let result = execute(&db, "%album artist%/%album%/%title%", Some(tmp.path())).unwrap();
2310        let dest = result.moves().next().unwrap().dest().to_path_buf();
2311        std::fs::write(&dest, b"replaced with something else entirely").unwrap();
2312
2313        let undone = undo(&db).unwrap();
2314        assert_eq!(undone.restored, 0);
2315        assert_eq!(undone.errors.len(), 1);
2316        assert!(!source.exists());
2317        assert!(dest.exists());
2318    }
2319
2320    /// `created_at` has one-second resolution, so batches are ordered by primary key.
2321    #[test]
2322    fn undo_takes_the_newest_batch_when_timestamps_tie() {
2323        let db = test_db();
2324        let tmp = TempDir::new().unwrap();
2325        let older = tmp.path().join("older.flac");
2326        let newer = tmp.path().join("newer.flac");
2327        std::fs::write(&older, b"older").unwrap();
2328        std::fs::write(&newer, b"newer").unwrap();
2329        let moved_older = tmp.path().join("moved-older.flac");
2330        let moved_newer = tmp.path().join("moved-newer.flac");
2331        std::fs::rename(&older, &moved_older).unwrap();
2332        std::fs::rename(&newer, &moved_newer).unwrap();
2333
2334        for (batch, from, to) in [
2335            ("batch-1", &older, &moved_older),
2336            ("batch-2", &newer, &moved_newer),
2337        ] {
2338            db.conn
2339                .execute(
2340                    "INSERT INTO organize_log (batch_id, track_id, from_path, to_path, created_at)
2341                     VALUES (?1, NULL, ?2, ?3, '2025-01-01 00:00:00')",
2342                    params![
2343                        batch,
2344                        from.to_string_lossy().as_ref(),
2345                        to.to_string_lossy().as_ref()
2346                    ],
2347                )
2348                .unwrap();
2349        }
2350
2351        let undone = undo(&db).unwrap();
2352        assert_eq!(undone.restored, 1);
2353        assert!(newer.exists(), "the newest batch is the one undone");
2354        assert!(!older.exists());
2355    }
2356
2357    // ---- Database consistency ----
2358
2359    #[test]
2360    fn favourites_and_queue_state_follow_the_move() {
2361        let db = test_db();
2362        let tmp = TempDir::new().unwrap();
2363        let source = tmp.path().join("src/test.flac");
2364        add_track(&db, &source, "Airbag", 1);
2365        let source_str = source.to_string_lossy().into_owned();
2366
2367        queries::add_favourite(&db.conn, crate::db::queries::LOCAL_USER, &source).unwrap();
2368        let item = PersistedQueueItem {
2369            path: source_str.clone(),
2370            title: "Airbag".into(),
2371            artist: "Radiohead".into(),
2372            album_artist: "Radiohead".into(),
2373            album: "OK Computer".into(),
2374            year: None,
2375            codec: None,
2376            track_number: Some(1),
2377            disc: Some(1),
2378            duration_ms: None,
2379            db_id: None,
2380        };
2381        queries::save_playback_state(&db.conn, &[item], Some(&source_str), 0, false, false)
2382            .unwrap();
2383
2384        let result = execute(&db, "%album artist%/%album%/%title%", Some(tmp.path())).unwrap();
2385        let dest = result.moves().next().unwrap().dest().to_path_buf();
2386        let dest_str = dest.to_string_lossy().into_owned();
2387
2388        let favourites =
2389            queries::load_favourites(&db.conn, crate::db::queries::LOCAL_USER).unwrap();
2390        assert!(favourites.contains(&dest));
2391        assert!(!favourites.contains(&source));
2392
2393        let state = queries::load_playback_state(&db.conn).unwrap().unwrap();
2394        assert_eq!(state.items[0].path, dest_str);
2395        assert_eq!(state.cursor_path.as_deref(), Some(dest_str.as_str()));
2396
2397        assert_eq!(undo(&db).unwrap().restored, 1);
2398
2399        let favourites =
2400            queries::load_favourites(&db.conn, crate::db::queries::LOCAL_USER).unwrap();
2401        assert!(favourites.contains(&source));
2402        assert!(!favourites.contains(&dest));
2403        let state = queries::load_playback_state(&db.conn).unwrap().unwrap();
2404        assert_eq!(state.items[0].path, source_str);
2405        assert_eq!(state.cursor_path.as_deref(), Some(source_str.as_str()));
2406    }
2407
2408    #[test]
2409    fn scan_cache_follows_the_move() {
2410        let db = test_db();
2411        let tmp = TempDir::new().unwrap();
2412        let source = tmp.path().join("src/test.flac");
2413        let id = add_track(&db, &source, "Airbag", 1);
2414        db.conn
2415            .execute(
2416                "INSERT INTO scan_cache (path, mtime, size, track_id) VALUES (?1, 1, 1, ?2)",
2417                params![source.to_string_lossy().as_ref(), id],
2418            )
2419            .unwrap();
2420
2421        let result = execute(&db, "%album artist%/%album%/%title%", Some(tmp.path())).unwrap();
2422        let dest = result
2423            .moves()
2424            .next()
2425            .unwrap()
2426            .dest()
2427            .to_string_lossy()
2428            .into_owned();
2429
2430        let cached: String = db
2431            .conn
2432            .query_row(
2433                "SELECT path FROM scan_cache WHERE track_id = ?1",
2434                params![id],
2435                |r| r.get(0),
2436            )
2437            .unwrap();
2438        assert_eq!(cached, dest);
2439    }
2440
2441    /// A failure partway through a batch must leave the rest of the run truthful: the
2442    /// files that moved are in the result and the log, the one that didn't is in neither.
2443    #[test]
2444    fn partial_failure_leaves_the_database_and_result_consistent() {
2445        let db = test_db();
2446        let tmp = TempDir::new().unwrap();
2447        let first = tmp.path().join("src/a.flac");
2448        let clash = tmp.path().join("src/b.flac");
2449        let third = tmp.path().join("src/c.flac");
2450        let first_id = add_track(&db, &first, "Airbag", 1);
2451        let clash_id = add_track(&db, &clash, "Airbag", 2);
2452        let third_id = add_track(&db, &third, "Karma Police", 3);
2453
2454        let result = execute(&db, "%album artist%/%album%/%title%", Some(tmp.path())).unwrap();
2455
2456        assert_eq!(result.moved_count(), 2);
2457        assert_eq!(result.failures().count(), 1);
2458
2459        let logged = log_rows(&db);
2460        assert_eq!(logged.len(), 2);
2461        for file_move in result.moves() {
2462            assert!(file_move.dest().exists());
2463            assert!(
2464                logged
2465                    .iter()
2466                    .any(|(_, _, to)| Path::new(to) == file_move.dest())
2467            );
2468        }
2469
2470        // The failed file is untouched, in the filesystem and in the database.
2471        assert!(clash.exists());
2472        assert_eq!(
2473            db_path_of(&db, clash_id).as_deref(),
2474            Some(clash.to_str().unwrap())
2475        );
2476        assert_ne!(db_path_of(&db, first_id).as_deref(), first.to_str());
2477        assert_ne!(db_path_of(&db, third_id).as_deref(), third.to_str());
2478    }
2479
2480    /// The TUI organizes a selection of paths. Files the library doesn't know about
2481    /// still get a log entry, so the whole run can be undone.
2482    #[test]
2483    fn unknown_paths_are_logged_and_undoable() {
2484        let db = test_db();
2485        let tmp = TempDir::new().unwrap();
2486        let known = tmp.path().join("src/known.flac");
2487        add_track(&db, &known, "Airbag", 1);
2488
2489        let result = run(
2490            &db,
2491            Selection::Paths(std::slice::from_ref(&known)),
2492            "%album artist%/%album%/%title%",
2493            tmp.path(),
2494        )
2495        .unwrap();
2496
2497        assert_eq!(result.moved_count(), 1);
2498        let logged = log_rows(&db);
2499        assert_eq!(logged.len(), 1);
2500        assert!(logged[0].0.is_some());
2501
2502        assert_eq!(undo(&db).unwrap().restored, 1);
2503        assert!(known.exists());
2504    }
2505
2506    #[test]
2507    fn ancillary_files_move_with_the_album() {
2508        let db = test_db();
2509        let tmp = TempDir::new().unwrap();
2510        let source = tmp.path().join("src/test.flac");
2511        add_track(&db, &source, "Airbag", 1);
2512        std::fs::write(source.parent().unwrap().join("cover.jpg"), b"art").unwrap();
2513
2514        let result = execute(&db, "%album artist%/%album%/%title%", Some(tmp.path())).unwrap();
2515        assert_eq!(result.moved_count(), 1);
2516        let dest_dir = result.moves().next().unwrap().dest().parent().unwrap();
2517        assert!(dest_dir.join("cover.jpg").exists());
2518
2519        // Both the audio and the artwork are in the log, so undo restores both.
2520        assert_eq!(log_rows(&db).len(), 2);
2521        assert_eq!(undo(&db).unwrap().restored, 2);
2522        assert!(source.parent().unwrap().join("cover.jpg").exists());
2523    }
2524
2525    // ---- Extension handling ----
2526
2527    #[test]
2528    fn extension_not_clobbered_by_dots_in_title() {
2529        // Regression: with_extension() replaces after the LAST dot,
2530        // destroying titles with dots ("0111. Bicep - TANGZ II" → "0111.flac").
2531        let db = test_db();
2532        let tmp = TempDir::new().unwrap();
2533        let source = tmp.path().join("src/CHROMA 011 A.L.O.E II.flac");
2534        std::fs::create_dir_all(source.parent().unwrap()).unwrap();
2535        std::fs::write(&source, b"fake").unwrap();
2536
2537        let mut meta = sample_meta("CHROMA 011 A.L.O.E II", "Bicep", "CHROMA 000");
2538        meta.track_number = Some(10);
2539        meta.date = Some("2025-11-21".into());
2540        meta.path = Some(source.to_string_lossy().into_owned());
2541        queries::upsert_track(&db.conn, &meta).unwrap();
2542
2543        let pattern = "%album artist%/['('$left(%date%,4)')' ]%album% '['%codec%']'/[$num(%discnumber%,2)][%tracknumber%. ][%artist% - ]%title%";
2544        let result = preview(&db, pattern, Some(tmp.path()), true).unwrap();
2545        assert_eq!(result.moved_count(), 1);
2546        assert_eq!(
2547            result
2548                .moves()
2549                .next()
2550                .unwrap()
2551                .dest()
2552                .file_name()
2553                .unwrap()
2554                .to_string_lossy(),
2555            "0110. Bicep - CHROMA 011 A.L.O.E II.flac"
2556        );
2557    }
2558
2559    #[test]
2560    fn extension_preserved_for_tracknumber_dot() {
2561        // "0111. Bicep - TANGZ II" must not become "0111.flac"
2562        let db = test_db();
2563        let tmp = TempDir::new().unwrap();
2564        let source = tmp.path().join("src/CHROMA 012 TANGZ II.flac");
2565        std::fs::create_dir_all(source.parent().unwrap()).unwrap();
2566        std::fs::write(&source, b"fake").unwrap();
2567
2568        let mut meta = sample_meta("CHROMA 012 TANGZ II", "Bicep", "CHROMA 000");
2569        meta.track_number = Some(11);
2570        meta.date = Some("2025-11-21".into());
2571        meta.path = Some(source.to_string_lossy().into_owned());
2572        queries::upsert_track(&db.conn, &meta).unwrap();
2573
2574        let pattern = "%album artist%/['('$left(%date%,4)')' ]%album% '['%codec%']'/[$num(%discnumber%,2)][%tracknumber%. ][%artist% - ]%title%";
2575        let result = preview(&db, pattern, Some(tmp.path()), true).unwrap();
2576        assert_eq!(result.moved_count(), 1);
2577        assert_eq!(
2578            result
2579                .moves()
2580                .next()
2581                .unwrap()
2582                .dest()
2583                .file_name()
2584                .unwrap()
2585                .to_string_lossy(),
2586            "0111. Bicep - CHROMA 012 TANGZ II.flac"
2587        );
2588    }
2589}