sift-music 0.4.0

Music tagger and library organiser: MusicBrainz matching, tag writing, cover art, fb2k-style paths
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
//! Changing what is already in the library: re-filing albums where the
//! current rules say they belong, and finding albums held twice.
//!
//! Every operation plans each destination before any file moves and refuses
//! an album whose plan collides with anything, the same guarantees import
//! gives. Albums are the unit: half an album moved is worse than none.

use std::collections::HashMap;
use std::path::{Path, PathBuf};

use crate::config::Config;
use crate::library::{Album, Item, Library, LibraryError};
use crate::matching;
use crate::meta::{self, Tags, Track};
use crate::paths;

/// One file's move.
#[derive(Debug, Clone, PartialEq)]
pub struct Move {
    pub from: PathBuf,
    pub to: PathBuf,
}

/// What re-filing an album would do.
#[derive(Debug)]
pub enum Plan {
    /// Already where the rules put it.
    InPlace,
    /// Every audio file's move, then the album's other files (cover, cue,
    /// log) when the whole album changes directory.
    Moves(Vec<Move>),
    /// Left alone, and why.
    Refused(String),
}

/// The tags an indexed file was written with, as far as the path template
/// can see them. Import wrote these fields; rendering them again gives the
/// path import chose, so an album filed under the current rules plans no
/// moves.
fn tags_of(t: &Track) -> Tags {
    Tags {
        title: t.title.clone().unwrap_or_default(),
        artist: t.artist.clone().unwrap_or_default(),
        album: t.album.clone().unwrap_or_default(),
        album_artist: t
            .album_artist
            .clone()
            .or_else(|| t.artist.clone())
            .unwrap_or_default(),
        track: t.track.unwrap_or_default(),
        track_total: t.track_total.unwrap_or_default(),
        disc: t.disc.unwrap_or(1),
        disc_total: t.disc_total.unwrap_or(1),
        date: t.date.clone(),
        original_date: t.original_date.clone(),
        compilation: t.compilation,
        mb_album_id: t.mb_album_id.clone(),
        ..Default::default()
    }
}

fn destination(cfg: &Config, t: &Track) -> Result<PathBuf, String> {
    let rel = paths::render(cfg, &tags_of(t), t, None).map_err(|e| e.to_string())?;
    let ext = t
        .path
        .extension()
        .map(|e| e.to_string_lossy().to_lowercase())
        .unwrap_or_default();
    paths::under(&cfg.directory, &format!("{rel}.{ext}")).map_err(|e| e.to_string())
}

/// Where the current rules put `album`.
pub fn plan_move(cfg: &Config, album: &Album) -> Plan {
    let mut moves = Vec::new();
    let mut claimed: HashMap<String, &Path> = HashMap::new();
    for item in &album.items {
        let from = &item.track.path;
        let to = match destination(cfg, &item.track) {
            Ok(to) => to,
            Err(e) => return Plan::Refused(format!("{}: {e}", from.display())),
        };
        let key = paths::collision_key(&to);
        if let Some(other) = claimed.insert(key.clone(), from) {
            return Plan::Refused(format!(
                "{} and {} would both be filed as {}",
                other.display(),
                from.display(),
                to.display()
            ));
        }
        // A change of case alone is the same file on a case-insensitive
        // disk; it is left as it is rather than renamed through a temporary.
        if key == paths::collision_key(from) {
            continue;
        }
        if to.exists() {
            return Plan::Refused(format!("{} already exists", to.display()));
        }
        moves.push(Move {
            from: from.clone(),
            to,
        });
    }
    if moves.is_empty() {
        return Plan::InPlace;
    }

    // The album's other files follow it only when all of it moves to one
    // new directory; otherwise nothing says which part a cover belongs to.
    let dirs: std::collections::HashSet<PathBuf> = moves
        .iter()
        .filter_map(|m| m.to.parent().map(Path::to_path_buf))
        .collect();
    if moves.len() == album.items.len()
        && dirs.len() == 1
        && let Some(new_dir) = dirs.into_iter().next()
        && new_dir != album.dir
        && let Ok(entries) = std::fs::read_dir(&album.dir)
    {
        for entry in entries.flatten() {
            let path = entry.path();
            if !entry.file_type().is_ok_and(|t| t.is_file()) || meta::is_audio(&path) {
                continue;
            }
            let to = new_dir.join(entry.file_name());
            if to.exists() {
                return Plan::Refused(format!("{} already exists", to.display()));
            }
            moves.push(Move { from: path, to });
        }
    }
    Plan::Moves(moves)
}

/// Carry out a plan from [`plan_move`], keeping the index in step, then
/// remove the directories it emptied (the album's, then its artist's). A
/// directory is only ever removed empty.
pub async fn execute(lib: &mut Library, album: &Album, moves: &[Move]) -> Result<(), LibraryError> {
    for m in moves {
        paths::transfer(&m.from, &m.to, true)
            .await
            .map_err(|e| LibraryError::Io(m.from.clone(), e))?;
        lib.rename(&m.from, &m.to)?;
    }
    if std::fs::remove_dir(&album.dir).is_ok()
        && let Some(parent) = album.dir.parent()
    {
        let _ = std::fs::remove_dir(parent);
    }
    Ok(())
}

/// Move an album into `bin`, at its path relative to the library root, and
/// drop it from the index. Nothing is deleted: putting it back is a move.
pub async fn bin(
    lib: &mut Library,
    library_root: &Path,
    bin: &Path,
    album: &Album,
) -> Result<PathBuf, LibraryError> {
    let rel = album
        .dir
        .strip_prefix(library_root)
        .map_err(|_| {
            LibraryError::Io(
                album.dir.clone(),
                std::io::Error::other("not under the library root"),
            )
        })?
        .to_path_buf();
    let dest = bin.join(rel);
    if dest.exists() {
        return Err(LibraryError::Io(
            dest,
            std::io::Error::from(std::io::ErrorKind::AlreadyExists),
        ));
    }
    let entries =
        std::fs::read_dir(&album.dir).map_err(|e| LibraryError::Io(album.dir.clone(), e))?;
    for entry in entries.flatten() {
        if !entry.file_type().is_ok_and(|t| t.is_file()) {
            continue;
        }
        let from = entry.path();
        paths::transfer(&from, &dest.join(entry.file_name()), true)
            .await
            .map_err(|e| LibraryError::Io(from.clone(), e))?;
        lib.forget(&from)?;
    }
    if std::fs::remove_dir(&album.dir).is_ok()
        && let Some(parent) = album.dir.parent()
    {
        let _ = std::fs::remove_dir(parent);
    }
    Ok(dest)
}

/// Split beets' `modify` arguments into query terms and changes:
/// `field=value` sets, `field!` clears, anything else is part of the query.
pub fn split_modify_args(args: &[String]) -> Result<(Vec<String>, Vec<meta::Change>), String> {
    let (mut query, mut changes) = (Vec::new(), Vec::new());
    for a in args {
        if let Some((f, v)) = a.split_once('=')
            && !f.is_empty()
            && f.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')
        {
            if !meta::EDITABLE.contains(&f) {
                return Err(format!(
                    "{f} cannot be modified; editable: {}",
                    meta::EDITABLE.join(", ")
                ));
            }
            if matches!(f, "track" | "tracktotal" | "disc" | "disctotal")
                && v.parse::<u32>().is_err()
            {
                return Err(format!("{f} takes a number, not {v:?}"));
            }
            changes.push((f.to_string(), Some(v.to_string())));
        } else if let Some(f) = a.strip_suffix('!')
            && meta::EDITABLE.contains(&f)
        {
            changes.push((f.to_string(), None));
        } else {
            query.push(a.clone());
        }
    }
    Ok((query, changes))
}

/// What `modify` did.
#[derive(Debug, Default)]
pub struct ModifyReport {
    pub files: Vec<PathBuf>,
    pub moved: Vec<(PathBuf, PathBuf)>,
    /// Albums whose tags changed but whose new place was refused, and why.
    pub left: Vec<(PathBuf, String)>,
}

/// Change fields on the files `query` matches (every file of each matching
/// album with `albums`), then re-file the albums whose path that changes.
/// With `pretend`, only report which files would change.
pub async fn modify(
    cfg: &Config,
    lib: &mut Library,
    query: &crate::library::Query,
    albums: bool,
    changes: &[meta::Change],
    pretend: bool,
) -> Result<ModifyReport, LibraryError> {
    let files: Vec<PathBuf> = if albums {
        lib.albums(query)?
            .into_iter()
            .flat_map(|a| a.items.into_iter().map(|i| i.track.path))
            .collect()
    } else {
        lib.items(query)?
            .into_iter()
            .map(|i| i.track.path)
            .collect()
    };
    let mut report = ModifyReport {
        files: files.clone(),
        ..Default::default()
    };
    if pretend || changes.is_empty() {
        return Ok(report);
    }
    for f in &files {
        meta::set(f, changes).map_err(|e| LibraryError::Io(f.clone(), std::io::Error::other(e)))?;
    }
    lib.update(&cfg.directory)?;
    let dirs: std::collections::HashSet<PathBuf> = files
        .iter()
        .filter_map(|f| f.parent().map(Path::to_path_buf))
        .collect();
    for album in lib.albums(&crate::library::Query::default())? {
        if !dirs.contains(&album.dir) {
            continue;
        }
        match plan_move(cfg, &album) {
            Plan::InPlace => {}
            Plan::Refused(why) => report.left.push((album.dir.clone(), why)),
            Plan::Moves(moves) => {
                let to = moves
                    .first()
                    .and_then(|m| m.to.parent())
                    .map(Path::to_path_buf)
                    .unwrap_or_default();
                execute(lib, &album, &moves).await?;
                report.moved.push((album.dir.clone(), to));
            }
        }
    }
    Ok(report)
}

/// Tracks an album's own tags say it should have and it does not: numbers
/// absent below each disc's track total, and discs absent below the disc
/// total. Judged from the files alone, so an album with no totals has
/// nothing missing.
pub fn missing(album: &Album) -> Vec<String> {
    let mut discs: std::collections::BTreeMap<u32, (u32, std::collections::BTreeSet<u32>)> =
        Default::default();
    let mut disc_total = 0;
    for i in &album.items {
        let d = i.track.disc.unwrap_or(1);
        let entry = discs.entry(d).or_default();
        entry.0 = entry.0.max(i.track.track_total.unwrap_or(0));
        if let Some(n) = i.track.track {
            entry.1.insert(n);
        }
        disc_total = disc_total.max(i.track.disc_total.unwrap_or(0));
    }
    let mut out = Vec::new();
    for d in 1..=disc_total {
        if !discs.contains_key(&d) {
            out.push(format!("disc {d}"));
        }
    }
    // A later disc not starting at 1 means the album is numbered straight
    // through: judge it as one sequence.
    let continuous = discs
        .iter()
        .skip(1)
        .any(|(_, (_, have))| have.first().is_some_and(|&n| n > 1));
    if continuous {
        let total = discs.values().map(|(t, _)| *t).max().unwrap_or(0);
        let have: std::collections::BTreeSet<u32> = discs
            .values()
            .flat_map(|(_, h)| h.iter().copied())
            .collect();
        out.extend(
            (1..=total)
                .filter(|n| !have.contains(n))
                .map(|n| format!("track {n}")),
        );
        return out;
    }
    let many = discs.len() > 1 || disc_total > 1;
    for (d, (total, have)) in &discs {
        for n in 1..=*total {
            if !have.contains(&n) {
                out.push(if many {
                    format!("{d}-{n}")
                } else {
                    format!("track {n}")
                });
            }
        }
    }
    out
}

/// Albums held more than once, and which copy to keep.
#[derive(Debug)]
pub struct Duplicate<'a> {
    pub keep: &'a Album,
    pub others: Vec<(&'a Album, &'static str)>,
}

/// Why one copy of an album is better than another, first difference wins:
/// lossless over lossy, then more of its tracks present, then higher
/// resolution. Equal copies keep the one filed under the current rules.
fn rank(cfg: &Config, a: &Album) -> (bool, usize, u32, u8, bool) {
    let lossless = a.items.iter().all(|i| {
        matches!(
            i.track.format.as_str(),
            "FLAC" | "ALAC" | "WAV" | "AIFF" | "APE" | "WavPack"
        )
    });
    let rate = a
        .items
        .iter()
        .filter_map(|i| i.track.sample_rate)
        .min()
        .unwrap_or(0);
    let depth = a
        .items
        .iter()
        .filter_map(|i| i.track.bit_depth)
        .min()
        .unwrap_or(0);
    let placed = matches!(plan_move(cfg, a), Plan::InPlace);
    (lossless, a.items.len(), rate, depth, placed)
}

fn why(keep: (bool, usize, u32, u8, bool), other: (bool, usize, u32, u8, bool)) -> &'static str {
    if keep.0 != other.0 {
        "lossy copy of a lossless album"
    } else if keep.1 != other.1 {
        "fewer tracks than the other copy"
    } else if keep.2 != other.2 || keep.3 != other.3 {
        "lower resolution than the other copy"
    } else if keep.4 != other.4 {
        "the same album filed under old naming rules"
    } else {
        "identical copy"
    }
}

/// Whether `album` has the recording `item` is: by MusicBrainz recording id
/// when both have one, by a close title otherwise.
fn contains(album: &Album, item: &Item) -> bool {
    album.items.iter().any(
        |k| match (&k.track.mb_recording_id, &item.track.mb_recording_id) {
            (Some(a), Some(b)) => a == b,
            _ => close_titles(&k.track.title, &item.track.title),
        },
    )
}

/// How far apart two track titles may be and still name one recording:
/// "Dark Thing" and "Dark Ting", "VIP" and "V.I.P".
const TITLE_DISTANCE: f64 = 0.3;

/// How far apart two copies of one track may be in length.
const LENGTH_SLACK: std::time::Duration = std::time::Duration::from_secs(3);

fn close_titles(a: &Option<String>, b: &Option<String>) -> bool {
    let (a, b) = (a.as_deref().unwrap_or(""), b.as_deref().unwrap_or(""));
    a.trim().eq_ignore_ascii_case(b.trim()) || matching::string_distance(a, b) <= TITLE_DISTANCE
}

fn in_order(a: &Album) -> Vec<&Item> {
    let mut items: Vec<&Item> = a.items.iter().collect();
    items.sort_by_key(|i| (i.track.disc.unwrap_or(1), i.track.track.unwrap_or(0)));
    items
}

/// The same music tagged differently: the same album title and number of
/// tracks, each track the same length and closely titled, in order. What
/// pairs two copies whose album artist is spelled differently, or whose
/// track titles are, which the exact key cannot.
fn same_music(a: &Album, b: &Album) -> bool {
    let (a, b) = (in_order(a), in_order(b));
    a.len() == b.len()
        && a.iter().zip(&b).all(|(x, y)| {
            x.track.duration.abs_diff(y.track.duration) <= LENGTH_SLACK
                && close_titles(&x.track.title, &y.track.title)
        })
}

/// Albums that are the same release. With MusicBrainz ids, the same release
/// id; without, the same album artist, album and track titles, compared
/// case-insensitively, so two editions with different track lists are not
/// called duplicates. Beyond those exact matches, albums with the same title
/// that are [`same_music`] are one album under two spellings.
pub fn duplicates<'a>(cfg: &Config, albums: &'a [Album]) -> Vec<Duplicate<'a>> {
    let key = |a: &Album| -> Option<String> {
        let first: &Item = a.items.first()?;
        if let Some(id) = &first.track.mb_album_id {
            return Some(format!("mb:{id}"));
        }
        let norm = |s: &Option<String>| s.as_deref().unwrap_or("").trim().to_lowercase();
        let titles: Vec<String> = a.items.iter().map(|i| norm(&i.track.title)).collect();
        Some(format!(
            "tags:{}\u{1f}{}\u{1f}{}",
            norm(
                &first
                    .track
                    .album_artist
                    .clone()
                    .or(first.track.artist.clone())
            ),
            norm(&first.track.album),
            titles.join("\u{1f}")
        ))
    };
    // Groups are joined by index: first by the exact key, then pairwise
    // within albums sharing a title and a track count.
    let mut parent: Vec<usize> = (0..albums.len()).collect();
    fn root(parent: &mut [usize], mut i: usize) -> usize {
        while parent[i] != i {
            parent[i] = parent[parent[i]];
            i = parent[i];
        }
        i
    }
    fn join(parent: &mut [usize], a: usize, b: usize) {
        let (a, b) = (root(parent, a), root(parent, b));
        parent[a] = b;
    }
    let mut exact: HashMap<String, usize> = HashMap::new();
    let mut titled: HashMap<(String, usize), Vec<usize>> = HashMap::new();
    for (i, a) in albums.iter().enumerate() {
        let Some(k) = key(a) else { continue };
        if let Some(&j) = exact.get(&k) {
            join(&mut parent, i, j);
        } else {
            exact.insert(k, i);
        }
        let title = a.items[0].track.album.as_deref().unwrap_or("");
        titled
            .entry((
                matching::normalise(&matching::base_title(title)),
                a.items.len(),
            ))
            .or_default()
            .push(i);
    }
    for ((title, _), members) in &titled {
        if title.is_empty() {
            continue;
        }
        for (n, &i) in members.iter().enumerate() {
            for &j in &members[n + 1..] {
                if root(&mut parent, i) != root(&mut parent, j)
                    && same_music(&albums[i], &albums[j])
                {
                    join(&mut parent, i, j);
                }
            }
        }
    }
    let mut groups: HashMap<usize, Vec<&Album>> = HashMap::new();
    for (i, a) in albums.iter().enumerate() {
        groups.entry(root(&mut parent, i)).or_default().push(a);
    }
    let mut out: Vec<Duplicate> = groups
        .into_values()
        .filter(|g| g.len() > 1)
        .filter_map(|mut g| {
            g.sort_by_key(|a| std::cmp::Reverse(rank(cfg, a)));
            let keep = g[0];
            let k = rank(cfg, keep);
            // A copy is spare only if the kept one has every track it has.
            // One release in several directories (a folder per disc) is an
            // album in pieces, which `move` puts back together; binning a
            // piece would lose music.
            let others: Vec<_> = g[1..]
                .iter()
                .filter(|a| a.items.iter().all(|i| contains(keep, i)))
                .map(|a| {
                    let reason = match why(k, rank(cfg, a)) {
                        "identical copy" if key(a) != key(keep) => {
                            "the same album, tagged differently"
                        }
                        reason => reason,
                    };
                    (*a, reason)
                })
                .collect();
            (!others.is_empty()).then_some(Duplicate { keep, others })
        })
        .collect();
    out.sort_by(|a, b| a.keep.dir.cmp(&b.keep.dir));
    out
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::library::Query;

    fn config(root: &Path) -> Config {
        let yaml = root.join("config.yaml");
        std::fs::write(
            &yaml,
            format!(
                r#"directory: {}
original_date: true
per_disc_numbering: true
paths:
  default: $albumartist/%if{{$year,($year) }}$album [$format]/$disc$track. $artist - $title
replace:
  '[\\/]': "-"
  '\.$': "-"
  '[<>:"\?\*\|]': "-"
"#,
                root.join("lib").display()
            ),
        )
        .unwrap();
        Config::load(&yaml).unwrap()
    }

    fn file(path: &Path, artist: &str, album: &str, title: &str, n: u32) {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        crate::library::tests::wav(path, 44_100);
        meta::write(
            path,
            &Tags {
                title: title.into(),
                artist: artist.into(),
                album: album.into(),
                album_artist: artist.into(),
                track: n,
                track_total: 2,
                disc: 1,
                disc_total: 1,
                date: Some("2011-09-26".into()),
                original_date: Some("1994-09-27".into()),
                ..Default::default()
            },
            None,
            false,
        )
        .unwrap();
    }

    fn album_of(lib: &Library, dir: &Path) -> Album {
        lib.albums(&Query::default())
            .unwrap()
            .into_iter()
            .find(|a| a.dir == dir)
            .unwrap()
    }

    #[tokio::test]
    async fn an_album_under_old_naming_rules_moves_with_its_cover_and_leaves_nothing_behind() {
        let root = tempfile::tempdir().unwrap();
        let cfg = config(root.path());
        let lib_root = root.path().join("lib");
        let old = lib_root.join("R.E.M_").join("Monster");
        file(
            &old.join("a.wav"),
            "R.E.M.",
            "Monster",
            "What's the Frequency, Kenneth?",
            1,
        );
        file(
            &old.join("b.wav"),
            "R.E.M.",
            "Monster",
            "Crush With Eyeliner",
            2,
        );
        std::fs::write(old.join("cover.jpg"), b"jpg").unwrap();

        let mut lib = Library::in_memory().unwrap();
        lib.update(&lib_root).unwrap();
        let album = album_of(&lib, &old);
        let Plan::Moves(moves) = plan_move(&cfg, &album) else {
            panic!("expected moves");
        };
        let new = lib_root.join("R.E.M-").join("(1994) Monster [WAV]");
        assert_eq!(
            moves.iter().map(|m| m.to.clone()).collect::<Vec<_>>(),
            [
                new.join("0101. R.E.M. - What's the Frequency, Kenneth-.wav"),
                new.join("0102. R.E.M. - Crush With Eyeliner.wav"),
                new.join("cover.jpg"),
            ]
        );
        execute(&mut lib, &album, &moves).await.unwrap();
        assert!(new.join("cover.jpg").exists());
        assert!(!lib_root.join("R.E.M_").exists(), "emptied directories go");
        let moved = album_of(&lib, &new);
        assert!(matches!(plan_move(&cfg, &moved), Plan::InPlace));
        let r = lib.update(&lib_root).unwrap();
        assert_eq!(
            (r.added, r.removed, r.changed),
            (0, 0, 0),
            "the index followed the moves"
        );
    }

    #[tokio::test]
    async fn an_album_whose_destination_is_taken_is_left_alone() {
        let root = tempfile::tempdir().unwrap();
        let cfg = config(root.path());
        let lib_root = root.path().join("lib");
        let old = lib_root.join("R.E.M_").join("Monster");
        let new = lib_root.join("R.E.M-").join("(1994) Monster [WAV]");
        for dir in [&old, &new] {
            file(
                &dir.join("0101. R.E.M. - Crush.wav"),
                "R.E.M.",
                "Monster",
                "Crush",
                1,
            );
        }
        let mut lib = Library::in_memory().unwrap();
        lib.update(&lib_root).unwrap();
        let album = album_of(&lib, &old);
        assert!(
            matches!(plan_move(&cfg, &album), Plan::Refused(r) if r.contains("already exists"))
        );

        let albums = lib.albums(&Query::default()).unwrap();
        let dupes = duplicates(&cfg, &albums);
        assert_eq!(dupes.len(), 1);
        assert_eq!(
            dupes[0].keep.dir, new,
            "the copy under the current rules is kept"
        );
        assert_eq!(dupes[0].others[0].0.dir, old);
        assert_eq!(
            dupes[0].others[0].1,
            "the same album filed under old naming rules"
        );
    }

    #[test]
    fn a_release_split_across_folders_is_not_a_duplicate_of_itself() {
        let root = tempfile::tempdir().unwrap();
        let cfg = config(root.path());
        let lib_root = root.path().join("lib");
        let tag = |path: &Path, title: &str, n: u32, disc: u32| {
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            crate::library::tests::wav(path, 44_100);
            meta::write(
                path,
                &Tags {
                    title: title.into(),
                    artist: "A".into(),
                    album: "B".into(),
                    album_artist: "A".into(),
                    track: n,
                    disc,
                    mb_album_id: Some("release".into()),
                    ..Default::default()
                },
                None,
                false,
            )
            .unwrap();
        };
        tag(&lib_root.join("B/CD1/1.wav"), "One", 1, 1);
        tag(&lib_root.join("B/CD1/2.wav"), "Two", 2, 1);
        tag(&lib_root.join("B/CD2/1.wav"), "Three", 1, 2);
        let mut lib = Library::in_memory().unwrap();
        lib.update(&lib_root).unwrap();
        let albums = lib.albums(&Query::default()).unwrap();
        assert!(duplicates(&cfg, &albums).is_empty());
    }

    #[test]
    fn missing_reads_gaps_from_the_totals() {
        let item = |disc, track, dt, tt| Item {
            track: Track {
                disc: Some(disc),
                track: Some(track),
                disc_total: Some(dt),
                track_total: Some(tt),
                ..Default::default()
            },
            size: 0,
            mtime: 0,
            added: 0,
        };
        let album = Album {
            dir: PathBuf::from("/m/a"),
            items: vec![item(1, 1, 3, 3), item(1, 3, 3, 3), item(3, 1, 3, 1)],
        };
        assert_eq!(missing(&album), ["disc 2", "1-2"]);
        let whole = Album {
            dir: PathBuf::from("/m/b"),
            items: vec![item(1, 1, 1, 2), item(1, 2, 1, 2)],
        };
        assert!(missing(&whole).is_empty());
        let straight_through = Album {
            dir: PathBuf::from("/m/c"),
            items: vec![item(1, 1, 2, 3), item(1, 2, 2, 3), item(2, 3, 2, 3)],
        };
        assert!(missing(&straight_through).is_empty());
    }

    #[test]
    fn modify_arguments_split_into_query_and_changes() {
        let args: Vec<String> = ["artist:burial", "album=Untrue", "genre!", "year:2007"]
            .map(String::from)
            .into();
        let (query, changes) = split_modify_args(&args).unwrap();
        assert_eq!(query, ["artist:burial", "year:2007"]);
        assert_eq!(
            changes,
            [
                ("album".to_string(), Some("Untrue".to_string())),
                ("genre".to_string(), None)
            ]
        );
        assert!(split_modify_args(&["path=/etc".to_string()]).is_err());
        assert!(split_modify_args(&["track=two".to_string()]).is_err());
    }

    #[tokio::test]
    async fn modify_changes_only_the_named_field_and_refiles_the_album() {
        let root = tempfile::tempdir().unwrap();
        let cfg = config(root.path());
        let lib_root = root.path().join("lib");
        let old = lib_root.join("Burial").join("(1994) Untru [WAV]");
        for (n, title) in [(1, "Archangel"), (2, "Near Dark")] {
            let path = old.join(format!("010{n}. Burial - {title}.wav"));
            file(&path, "Burial", "Untru", title, n);
            meta::set(&path, &[("genre".into(), Some("Garage".into()))]).unwrap();
        }
        let mut lib = Library::in_memory().unwrap();
        lib.update(&lib_root).unwrap();
        let query = crate::library::Query::parse(&["album:untru"]).unwrap();
        let changes = [("album".to_string(), Some("Untrue".to_string()))];
        let r = modify(&cfg, &mut lib, &query, true, &changes, false)
            .await
            .unwrap();
        assert_eq!(r.files.len(), 2);
        let new = lib_root.join("Burial").join("(1994) Untrue [WAV]");
        assert_eq!(r.moved, [(old.clone(), new.clone())]);
        let moved = new.join("0101. Burial - Archangel.wav");
        let after = meta::read(&moved).unwrap();
        assert_eq!(after.album.as_deref(), Some("Untrue"));
        assert_eq!(
            after.genre.as_deref(),
            Some("Garage"),
            "untouched fields survive"
        );
    }

    #[tokio::test]
    async fn different_track_lists_are_different_editions_not_duplicates() {
        let root = tempfile::tempdir().unwrap();
        let cfg = config(root.path());
        let lib_root = root.path().join("lib");
        file(&lib_root.join("x/1.wav"), "A", "B", "One", 1);
        file(&lib_root.join("y/1.wav"), "A", "B", "One", 1);
        file(&lib_root.join("y/2.wav"), "A", "B", "Bonus", 2);
        let mut lib = Library::in_memory().unwrap();
        lib.update(&lib_root).unwrap();
        let albums = lib.albums(&Query::default()).unwrap();
        assert!(duplicates(&cfg, &albums).is_empty());
    }

    fn dupes_of(files: &[(&str, &str, &str, &str, u32)]) -> usize {
        let root = tempfile::tempdir().unwrap();
        let cfg = config(root.path());
        let lib_root = root.path().join("lib");
        for (path, artist, album, title, n) in files {
            file(&lib_root.join(path), artist, album, title, *n);
        }
        let mut lib = Library::in_memory().unwrap();
        lib.update(&lib_root).unwrap();
        let albums = lib.albums(&Query::default()).unwrap();
        duplicates(&cfg, &albums).len()
    }

    #[tokio::test]
    async fn one_album_under_two_artist_spellings_is_a_duplicate() {
        let group = "Black Sun Empire, State Of Mind";
        assert_eq!(
            dupes_of(&[
                (
                    "x/1.wav",
                    "Black Sun Empire",
                    "Consume The Power",
                    "Arrakis",
                    1
                ),
                (
                    "x/2.wav",
                    "Black Sun Empire",
                    "Consume The Power",
                    "Dawn",
                    2
                ),
                ("y/1.wav", group, "Consume The Power", "Arrakis", 1),
                ("y/2.wav", group, "Consume The Power", "Dawn", 2),
            ]),
            1
        );
    }

    #[tokio::test]
    async fn track_titles_spelled_differently_are_a_duplicate() {
        assert_eq!(
            dupes_of(&[
                ("x/1.wav", "A", "We Do Scorpion Things", "Dark Thing", 1),
                ("x/2.wav", "A", "We Do Scorpion Things", "Til da Mornin", 2),
                ("y/1.wav", "A", "We Do Scorpion Things", "Dark Ting", 1),
                ("y/2.wav", "A", "We Do Scorpion Things", "Til Da Morning", 2),
            ]),
            1
        );
    }

    #[tokio::test]
    async fn same_title_and_length_with_other_tracks_is_not_a_duplicate() {
        assert_eq!(
            dupes_of(&[
                ("x/1.wav", "A", "B", "One", 1),
                ("x/2.wav", "A", "B", "Two", 2),
                ("y/1.wav", "C", "B", "Something Else", 1),
                ("y/2.wav", "C", "B", "Entirely", 2),
            ]),
            0
        );
    }
}