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