Cotton code
186 lines · 7.6 KB · RustRaw
//! A playlist file found in a folder of songs (`.m3u`, `.m3u8`) as a list of//! songs: one rule for the Mac's `music:import` and the phone's Add a folder//! (open standards, 7 Nov 2026), and the shape the open bundle writes//! (`Music/playlists/<List>.m3u8`, paths relative to the list).//!//! - The list is named after its file ([`list_name`]).//! - Each entry is a song found by its path relative to the list, then by its//!   file name; an entry neither finds is skipped and counted ([`resolve`]).//!   `#EXTINF` and every other `#` line are ignored: the song's own tags name//!   it.//! - A list already held by that name only grows: the songs it lacks are//!   appended in the file's order, nothing removed ([`to_append`]); a song is//!   at most once in a list./// The extensions a playlist file ends in.pub const LIST_EXTENSIONS: [&str; 2] = ["m3u", "m3u8"];/// Whether a file's name is a playlist's.pub fn is_list_file(path: &str) -> bool {    path.rsplit_once('.').is_some_and(|(_, ext)| LIST_EXTENSIONS.contains(&ext.to_ascii_lowercase().as_str()))}/// A playlist file's text: UTF-8 (a BOM dropped), else Latin-1, as an `.m3u`/// written by an older player often is.pub fn text_of(bytes: &[u8]) -> String {    let bytes = bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes);    match std::str::from_utf8(bytes) {        Ok(text) => text.to_string(),        Err(_) => bytes.iter().map(|&b| b as char).collect(),    }}/// The list's name: its file's name without the extension.pub fn list_name(source_path: &str) -> String {    let file = source_path.rsplit('/').next().unwrap_or(source_path);    match file.rsplit_once('.') {        Some((stem, _)) if !stem.trim().is_empty() => stem.trim().to_string(),        _ => file.trim().to_string(),    }}/// `%20` and the rest of a `file://` URL's escapes, decoded.fn unescaped(text: &str) -> String {    let bytes = text.as_bytes();    let mut out = Vec::with_capacity(bytes.len());    let mut at = 0;    while at < bytes.len() {        let hex = |b: u8| (b as char).to_digit(16);        if bytes[at] == b'%' && at + 2 < bytes.len() {            if let (Some(high), Some(low)) = (hex(bytes[at + 1]), hex(bytes[at + 2])) {                out.push((high * 16 + low) as u8);                at += 3;                continue;            }        }        out.push(bytes[at]);        at += 1;    }    String::from_utf8_lossy(&out).to_string()}/// The entries of a playlist, in order: every line that is not blank and not/// a `#` line, a `file://` URL as its path, Windows' `\` as `/`.pub fn entries(text: &str) -> Vec<String> {    text.lines()        .map(str::trim)        .filter(|line| !line.is_empty() && !line.starts_with('#'))        .map(|line| match line.strip_prefix("file://") {            Some(url) => unescaped(url.strip_prefix("localhost").unwrap_or(url)),            None => line.to_string(),        })        .map(|line| line.replace('\\', "/"))        .collect()}/// `a/b/../c/./d` as `a/c/d`; `None` when a `..` climbs above the start.fn normalized(path: &str) -> Option<String> {    let mut parts: Vec<&str> = Vec::new();    for part in path.split('/') {        match part {            "" | "." => {}            ".." => {                parts.pop()?;            }            part => parts.push(part),        }    }    Some(parts.join("/"))}fn folded(path: &str) -> String {    path.to_lowercase()}fn file_name(path: &str) -> &str {    path.rsplit('/').next().unwrap_or(path)}/// What a playlist's entries came to.#[derive(Debug, Clone, Default, PartialEq, Eq)]pub struct Resolved {    /// The songs found, in the file's order, each once.    pub songs: Vec<String>,    /// The entries no song was found for.    pub skipped: usize,}/// Each entry of the list at `list_path` (its path as it came in, beside the/// songs' own) found among `songs` (`(path, id)`, the paths as they came in):/// by its path relative to the list's folder, case aside, else by its file/// name (the first song of that name), else skipped and counted. An absolute/// entry is found by its file name alone.pub fn resolve(list_path: &str, entries: &[String], songs: &[(String, String)]) -> Resolved {    let folder = list_path.rsplit_once('/').map_or("", |(folder, _)| folder);    let by_path: std::collections::HashMap<String, &str> =        songs.iter().rev().filter_map(|(path, id)| Some((folded(&normalized(path)?), id.as_str()))).collect();    let mut by_name: std::collections::HashMap<String, &str> = std::collections::HashMap::new();    for (path, id) in songs {        by_name.entry(folded(file_name(path))).or_insert(id.as_str());    }    let mut out = Resolved::default();    for entry in entries {        let absolute = entry.starts_with('/') || entry.get(1..3) == Some(":/");        let relative = (!absolute).then(|| normalized(&format!("{folder}/{entry}"))).flatten();        let found = relative            .and_then(|path| by_path.get(&folded(&path)).copied())            .or_else(|| by_name.get(&folded(file_name(entry))).copied());        match found {            Some(id) if !out.songs.iter().any(|held| held == id) => out.songs.push(id.to_string()),            Some(_) => {}            None => out.skipped += 1,        }    }    out}/// The songs a list holding `held` takes from `found`: those it lacks, in/// `found`'s order. Nothing it holds is removed or moved.pub fn to_append(held: &[String], found: &[String]) -> Vec<String> {    found.iter().filter(|id| !held.contains(id)).cloned().collect()}#[cfg(test)]mod tests {    use super::*;    fn songs(paths: &[(&str, &str)]) -> Vec<(String, String)> {        paths.iter().map(|(path, id)| (path.to_string(), id.to_string())).collect()    }    /// RULE (open standards, 7 Nov 2026): a playlist's entries are its non-# lines; #EXTINF names nothing, the song's own tags do.    #[test]    fn entries_are_the_lines_that_are_not_comments() {        let text = "\u{feff}#EXTM3U\n#PLAYLIST:Night\n#EXTINF:201,Ana Vell - Low Tide\n../Ana Vell/Two Rooms/01 Low Tide.flac\n\r\n  \nC:\\Music\\x.mp3\nfile:///Users/a/Music/My%20Song.mp3\n";        assert_eq!(entries(&text_of(text.as_bytes())), vec!["../Ana Vell/Two Rooms/01 Low Tide.flac", "C:/Music/x.mp3", "/Users/a/Music/My Song.mp3"]);        assert_eq!(text_of(&[b'a', 0xE9]), "aé", "Latin-1 when it is no UTF-8");        assert_eq!(list_name("Lib/Music/playlists/Night Drive.m3u8"), "Night Drive");        assert!(is_list_file("x/Night.M3U") && is_list_file("Night.m3u8") && !is_list_file("Night.pls"));    }    /// RULE (open standards, 7 Nov 2026): a song is found by its path relative to the list, then by its file name, else skipped and counted; each once.    #[test]    fn songs_are_found_by_relative_path_then_by_name_and_the_rest_counted() {        let held = songs(&[            ("Lib/Music/Ana Vell/Two Rooms/01 Low Tide.flac", "a"),            ("Lib/Music/Oru/Night/01 Low Tide.flac", "b"),            ("Elsewhere/02 Morning.mp3", "c"),        ]);        let list = "Lib/Music/playlists/Mix.m3u8";        let found = resolve(            list,            &[                "../Oru/Night/01 low tide.FLAC".into(),                "../Ana Vell/Two Rooms/01 Low Tide.flac".into(),                "somewhere/02 Morning.mp3".into(),                "/abs/path/02 Morning.mp3".into(),                "../Gone/03 Missing.mp3".into(),                "../../../../../x.mp3".into(),            ],            &held,        );        assert_eq!(found.songs, vec!["b", "a", "c"], "the path finds the right one of two names alike; a song is once");        assert_eq!(found.skipped, 2);        assert_eq!(to_append(&["a".into()], &found.songs), vec!["b", "c"]);    }}