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