Skip to content

A fast file manager for Windows and macOS that never freezes: tabs, dual panes, archives as folders, Quick Look-style previews. A File Explorer and Finder alternative written in Rust.

25.3 KB
Raw Blame
//! Bulk rename: pure name computation + validation (no I/O).
//!
//! [`compute`] maps every input name to its new name (or a [`RenameError`]); duplicates between
//! the new names, collisions with sibling files that are not part of the batch, Windows-invalid
//! characters, reserved device names and empty names are all reported per item.
//! [`plan`] turns the result into a swap-safe sequence of renames.

use std::collections::{HashMap, HashSet};

use regex::RegexBuilder;

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenameItem {
    pub name: String,
    pub is_dir: bool,
    /// Modified time, ms since the Unix epoch (used by `{date}`).
    pub modified_ms: i64,
    /// Created time, ms since the Unix epoch (used by `{created}`; 0 when unknown).
    pub created_ms: i64,
}

impl RenameItem {
    pub fn new(name: impl Into<String>, is_dir: bool, modified_ms: i64) -> Self {
        Self { name: name.into(), is_dir, modified_ms, created_ms: 0 }
    }

    /// The item with its creation time (for `{created}`).
    pub fn with_created(mut self, created_ms: i64) -> Self {
        self.created_ms = created_ms;
        self
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum CaseKind {
    Lower,
    Upper,
    Title,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Mode {
    FindReplace { find: String, replace: String, case_insensitive: bool, regex: bool },
    /// `{n}` / `{n:03}` counter, `{name}` stem, `{ext}` (no dot), `{date}` modified, `{created}` created, `{today}` (YYYY-MM-DD).
    Pattern { pattern: String, start: i64, step: i64 },
    Case(CaseKind),
    PrefixSuffix { prefix: String, suffix: String },
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RenameSpec {
    pub mode: Mode,
    /// Apply the mode to the whole name (including the extension) instead of the stem only.
    pub include_ext: bool,
    /// Names of sibling entries that are NOT part of the batch (collision check, case-insensitive).
    pub existing: Vec<String>,
}

impl RenameSpec {
    pub fn new(mode: Mode) -> Self {
        Self { mode, include_ext: false, existing: Vec::new() }
    }
}

#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
pub enum RenameError {
    #[error("Ad boş olamaz")]
    Empty,
    #[error("Geçersiz karakter: < > : \" / \\ | ? * veya denetim karakteri")]
    InvalidChars,
    #[error("Ad nokta veya boşlukla bitemez")]
    TrailingDotSpace,
    #[error("Ayrılmış Windows adı")]
    Reserved,
    #[error("Ad çok uzun")]
    TooLong,
    #[error("Aynı ada çıkan başka bir öğe var")]
    Duplicate,
    #[error("Klasörde bu ada sahip başka bir öğe var")]
    Exists,
    #[error("Geçersiz düzenli ifade: {0}")]
    BadRegex(String),
}

/// (stem, ext-with-dot). A leading dot alone (".gitignore") is not an extension.
pub fn split_ext(name: &str, is_dir: bool) -> (&str, &str) {
    if is_dir {
        return (name, "");
    }
    match name.rfind('.') {
        Some(i) if i > 0 => (&name[..i], &name[i..]),
        _ => (name, ""),
    }
}

fn title_case(s: &str) -> String {
    crate::sort::title(s)
}

fn format_date(ms: i64) -> String {
    use chrono::{DateTime, Local};
    DateTime::from_timestamp_millis(ms)
        .map(|d| d.with_timezone(&Local).format("%Y-%m-%d").to_string())
        .unwrap_or_default()
}

/// Expands `{token}` placeholders in `pattern`: `lookup` gives the text for a token, or `None`
/// to keep `{token}` as it is (a typo then shows in the result instead of vanishing). A brace
/// that is never closed is kept too. The bulk rename and the folder organizer both expand
/// their templates with this, each with its own set of tokens.
pub fn expand_template(pattern: &str, mut lookup: impl FnMut(&str) -> Option<String>) -> String {
    let mut out = String::new();
    let mut rest = pattern;
    while let Some(open) = rest.find('{') {
        out.push_str(&rest[..open]);
        let after = &rest[open + 1..];
        let Some(close) = after.find('}') else {
            out.push_str(&rest[open..]);
            return out;
        };
        let tok = &after[..close];
        match lookup(tok) {
            Some(text) => out.push_str(&text),
            None => {
                out.push('{');
                out.push_str(tok);
                out.push('}');
            }
        }
        rest = &after[close + 1..];
    }
    out.push_str(rest);
    out
}

/// The dates a pattern can take (YYYY-MM-DD): modified, created and today (issue 435).
struct Dates {
    modified: String,
    created: String,
    today: String,
}

/// Expands `{n}`, `{n:03}`, `{name}`, `{ext}`, `{date}`, `{created}`, `{today}`; unknown braces are kept literally.
fn expand_pattern(pattern: &str, n: i64, stem: &str, ext: &str, dates: &Dates) -> String {
    expand_template(pattern, |tok| match tok {
        "name" => Some(stem.to_string()),
        "ext" => Some(ext.trim_start_matches('.').to_string()),
        "date" => Some(dates.modified.clone()),
        "created" => Some(dates.created.clone()),
        "today" => Some(dates.today.clone()),
        "n" => Some(n.to_string()),
        t if t.starts_with("n:") => t[2..].parse::<usize>().ok().map(|w| format!("{n:0w$}", w = w.min(32))),
        _ => None,
    })
}

const RESERVED: [&str; 22] = [
    "CON", "PRN", "AUX", "NUL", "COM1", "COM2", "COM3", "COM4", "COM5", "COM6", "COM7", "COM8", "COM9", "LPT1",
    "LPT2", "LPT3", "LPT4", "LPT5", "LPT6", "LPT7", "LPT8", "LPT9",
];

/// Validates a single file name against Windows rules.
pub fn validate(name: &str) -> Result<(), RenameError> {
    if name.trim().is_empty() {
        return Err(RenameError::Empty);
    }
    if name.chars().any(|c| matches!(c, '<' | '>' | ':' | '"' | '/' | '\\' | '|' | '?' | '*') || (c as u32) < 32) {
        return Err(RenameError::InvalidChars);
    }
    if name.ends_with('.') || name.ends_with(' ') {
        return Err(RenameError::TrailingDotSpace);
    }
    let base = name.split('.').next().unwrap_or("").trim_end().to_uppercase();
    if RESERVED.contains(&base.as_str()) {
        return Err(RenameError::Reserved);
    }
    if name.chars().count() > 255 {
        return Err(RenameError::TooLong);
    }
    Ok(())
}

/// The Find/Replace pattern, built once for all the items (not per item: with thousands of
/// files selected that was a regex build per file per keystroke).
fn find_regex(spec: &RenameSpec) -> Option<Result<regex::Regex, RenameError>> {
    let Mode::FindReplace { find, case_insensitive, regex, .. } = &spec.mode else { return None };
    if find.is_empty() {
        return None;
    }
    let pat = if *regex { find.clone() } else { regex::escape(find) };
    Some(RegexBuilder::new(&pat).case_insensitive(*case_insensitive).build().map_err(|e| RenameError::BadRegex(e.to_string().lines().last().unwrap_or("").trim().to_string())))
}

fn transform(item: &RenameItem, idx: usize, spec: &RenameSpec, re: Option<&Result<regex::Regex, RenameError>>) -> Result<String, RenameError> {
    let (stem, ext) = split_ext(&item.name, item.is_dir);
    let (target, tail): (&str, &str) = if spec.include_ext { (&item.name, "") } else { (stem, ext) };
    let body = match &spec.mode {
        Mode::FindReplace { replace, regex, .. } => {
            if let Some(re) = re {
                let re = re.as_ref().map_err(Clone::clone)?;
                if *regex {
                    re.replace_all(target, replace.as_str()).into_owned()
                } else {
                    re.replace_all(target, regex::NoExpand(replace.as_str())).into_owned()
                }
            } else {
                target.to_string()
            }
        }
        Mode::Pattern { pattern, start, step } => {
            let n = start.saturating_add(step.saturating_mul(idx as i64));
            let name_tok = if spec.include_ext { item.name.as_str() } else { stem };
            // (a date is formatted only when the pattern uses it)
            let when = |tok: &str, ms: i64| if pattern.contains(tok) { format_date(ms) } else { String::new() };
            let dates = Dates {
                modified: when("{date", item.modified_ms),
                created: when("{created", item.created_ms),
                today: when("{today", chrono::Local::now().timestamp_millis()),
            };
            expand_pattern(pattern, n, name_tok, ext, &dates)
        }
        Mode::Case(k) => {
            // The extension (when included) is never cased with locale rules: ".AVI" must
            // become ".avi", not ".avı".
            let (words, ext_part) = if spec.include_ext { split_ext(target, item.is_dir) } else { (target, "") };
            let words = match k {
                CaseKind::Lower => crate::sort::lower(words),
                CaseKind::Upper => crate::sort::upper(words),
                CaseKind::Title => title_case(words),
            };
            let ext_part = match k {
                CaseKind::Upper => ext_part.to_ascii_uppercase(),
                _ => ext_part.to_ascii_lowercase(),
            };
            format!("{words}{ext_part}")
        }
        Mode::PrefixSuffix { prefix, suffix } => format!("{prefix}{target}{suffix}"),
    };
    Ok(format!("{body}{tail}"))
}

/// Computes new names. The result has the same length/order as `items`; an unchanged name is `Ok(old)`.
pub fn compute(items: &[RenameItem], spec: &RenameSpec) -> Vec<Result<String, RenameError>> {
    let re = find_regex(spec);
    let mut out: Vec<Result<String, RenameError>> = items
        .iter()
        .enumerate()
        .map(|(i, it)| {
            let n = transform(it, i, spec, re.as_ref())?;
            validate(&n)?;
            Ok(n)
        })
        .collect();

    let mut count: HashMap<String, usize> = HashMap::new();
    for n in out.iter().flatten() {
        *count.entry(n.to_lowercase()).or_default() += 1;
    }
    let existing: HashSet<String> = spec.existing.iter().map(|s| s.to_lowercase()).collect();
    for r in out.iter_mut() {
        if let Ok(n) = r {
            let k = n.to_lowercase();
            if count.get(&k).copied().unwrap_or(0) > 1 {
                *r = Err(RenameError::Duplicate);
            } else if existing.contains(&k) {
                *r = Err(RenameError::Exists);
            }
        }
    }
    out
}

/// One rename inside a single folder (names only).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Step {
    pub from: String,
    pub to: String,
}

/// Turns `(old, new)` pairs into an ordered, swap-safe list of renames. Every pair whose target
/// equals another batch member's current name goes through a temporary name (`tmp(i)`, which must
/// not exist in the folder): first all moves-out, then the plain moves, then all moves-in.
/// Unchanged pairs are skipped; case-only renames go direct.
pub fn plan(pairs: &[(String, String)], tmp: impl Fn(usize) -> String) -> Vec<Step> {
    let changed: Vec<(usize, &(String, String))> = pairs.iter().enumerate().filter(|(_, (a, b))| a != b).collect();
    let olds: HashSet<String> = changed.iter().map(|(_, (a, _))| a.to_lowercase()).collect();
    let (mut out, mut direct, mut back) = (Vec::new(), Vec::new(), Vec::new());
    for (i, (old, new)) in changed {
        let case_only = old.to_lowercase() == new.to_lowercase();
        if !case_only && olds.contains(&new.to_lowercase()) {
            let t = tmp(i);
            out.push(Step { from: old.clone(), to: t.clone() });
            back.push(Step { from: t, to: new.clone() });
        } else {
            direct.push(Step { from: old.clone(), to: new.clone() });
        }
    }
    out.extend(direct);
    out.extend(back);
    out
}

/// A name typed or pasted with characters Windows does not allow, made into one it does, the way a person would have written it:
/// a colon becomes " - " ("Episode 1: The Beginning" is "Episode 1 - The Beginning"), a slash, a backslash and a bar become "-" (so
/// "1/2" stays readable as "1-2" instead of turning into "12"), a double quote becomes a single one, and `* ? < >` and control
/// characters go. Runs of spaces are made one, and the spaces and dots Windows takes off a name's end go too. A name that is fine is
/// given back as it is.
///
/// Issue 370: a single such character made the rename fail, and what had been typed was lost. Explorer only says the name is wrong.
pub fn tidy_name(name: &str) -> String {
    let mut out = String::with_capacity(name.len() + 8);
    for c in name.chars() {
        match c {
            ':' => out.push_str(if out.ends_with(' ') { "- " } else { " - " }),
            '/' | '\\' | '|' => out.push('-'),
            '"' => out.push('\''),
            '*' | '?' | '<' | '>' => {}
            c if (c as u32) < 0x20 => {}
            c => out.push(c),
        }
    }
    let mut single = String::with_capacity(out.len());
    for c in out.chars() {
        if !(c == ' ' && single.ends_with(' ')) {
            single.push(c);
        }
    }
    single.trim_start().trim_end_matches([' ', '.']).to_string()
}

// ------------------------------------------------------------------ several names edited in place at once (issue 435)

/// One edit of the leading name box while several items are renamed in place: of the text before it, `front` characters at the start
/// and `back` at the end stayed, the `removed` characters between them were replaced by `inserted`. Counted in characters, not bytes.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Edit {
    pub front: usize,
    pub back: usize,
    pub removed: usize,
    pub inserted: String,
    /// The text of the `front` and `back` characters (what stayed of the leading name on each side).
    pub head: String,
    pub tail: String,
}

/// The edit that turns `before` into `after` (each keystroke is one: a typed or deleted character, a paste, a selection replaced).
pub fn edit_between(before: &str, after: &str) -> Edit {
    let a: Vec<char> = before.chars().collect();
    let b: Vec<char> = after.chars().collect();
    let front = a.iter().zip(&b).take_while(|(x, y)| x == y).count();
    let back = a[front..].iter().rev().zip(b[front..].iter().rev()).take_while(|(x, y)| x == y).count();
    Edit {
        front,
        back,
        removed: a.len() - front - back,
        inserted: b[front..b.len() - back].iter().collect(),
        head: a[..front].iter().collect(),
        tail: a[a.len() - back..].iter().collect(),
    }
}

/// `edit` (made in another name) done to `name`. It is placed from the START of the name or from its END: from the side whose kept
/// text this name shares (a name that ends in the leading name's ".txt" but starts otherwise is edited from the end), and where both
/// or neither match, from the side the edit was nearer to in the leading name (typing at the beginning, Home then Delete: the start;
/// typing at the end, End then Backspace: the end). So names of different lengths change alike: "File1", "File22" with Home, Delete
/// give "ile1", "ile22". When the whole leading name was replaced (`front` and `back` both 0) every name becomes the new text.
pub fn apply_edit(name: &str, edit: &Edit) -> String {
    let c: Vec<char> = name.chars().collect();
    if edit.front == 0 && edit.back == 0 {
        return edit.inserted.clone();
    }
    let len = c.len();
    let (head_ok, tail_ok) = (name.starts_with(&edit.head), name.ends_with(&edit.tail));
    let from_start = match (head_ok, tail_ok) {
        (true, false) => true,
        (false, true) => false,
        _ => edit.front <= edit.back,
    };
    let (start, end) = if from_start {
        let start = edit.front.min(len);
        (start, (start + edit.removed).min(len))
    } else {
        let end = len.saturating_sub(edit.back);
        (end.saturating_sub(edit.removed), end)
    };
    let mut out: String = c[..start].iter().collect();
    out.push_str(&edit.inserted);
    out.extend(&c[end..]);
    out
}

/// The tokens the in-place rename can insert ({n:02}, {today}, {created}, {date}), filled in for one item: `n` is its place in the
/// view (from 1), the dates are the item's own. Other braces stay as they are.
pub fn fill_tokens(text: &str, n: i64, modified_ms: i64, created_ms: i64) -> String {
    let dates = Dates { modified: format_date(modified_ms), created: format_date(created_ms), today: chrono::Local::now().format("%Y-%m-%d").to_string() };
    expand_template(text, |tok| match tok {
        "date" => Some(dates.modified.clone()),
        "created" => Some(dates.created.clone()),
        "today" => Some(dates.today.clone()),
        "n" => Some(n.to_string()),
        t if t.starts_with("n:") => t[2..].parse::<usize>().ok().map(|w| format!("{n:0w$}", w = w.min(32))),
        _ => None,
    })
}

#[cfg(test)]
mod tests {
    /// Issue 370's own examples, and the rest of the characters.
    #[test]
    fn a_name_with_characters_windows_refuses_is_tidied_as_written() {
        use super::tidy_name;
        assert_eq!(tidy_name("Report: draft 2026?.txt"), "Report - draft 2026.txt");
        assert_eq!(tidy_name("Notes: Q4 \"final\""), "Notes - Q4 'final'");
        assert_eq!(tidy_name("Episode 1: The Beginning"), "Episode 1 - The Beginning");
        assert_eq!(tidy_name("Episode 1 : The Beginning"), "Episode 1 - The Beginning", "no double spaces around the dash");
        assert_eq!(tidy_name("AC/DC 1\\2 | live"), "AC-DC 1-2 - live");
        assert_eq!(tidy_name("what? <why>*"), "what why");
        assert_eq!(tidy_name("trailing dots..  "), "trailing dots");
        assert_eq!(tidy_name("a\tb"), "ab", "control characters go");
        assert_eq!(tidy_name("fine name.txt"), "fine name.txt", "a good name is left as it is");
        assert_eq!(tidy_name("???"), "", "nothing left: the caller says so");
    }

    use super::*;

    #[test]
    fn an_edit_in_one_name_happens_in_all_of_them() {
        let all = |names: &[&str], before: &str, after: &str| -> Vec<String> {
            let e = edit_between(before, after);
            names.iter().map(|n| apply_edit(n, &e)).collect()
        };
        // the issue's own example: Home, Delete
        assert_eq!(all(&["File1", "File2", "File33"], "File1", "ile1"), ["ile1", "ile2", "ile33"]);
        // typed at the start and at the end
        assert_eq!(all(&["a", "bbb"], "a", "Xa"), ["Xa", "Xbbb"]);
        assert_eq!(all(&["a", "bbb"], "a", "a_x"), ["a_x", "bbb_x"]);
        // End, Backspace
        assert_eq!(all(&["File1", "File22"], "File1", "File"), ["File", "File2"]);
        // before the extension, when it is shown
        assert_eq!(all(&["a.txt", "long name.txt"], "a.txt", "a 2.txt"), ["a 2.txt", "long name 2.txt"]);
        // the whole name replaced
        assert_eq!(all(&["one", "three"], "one", "P"), ["P", "P"]);
        // a name too short to reach the edited part stays as it is
        assert_eq!(all(&["abcdef", "ab"], "abcdef", "abf"), ["abf", "ab"]);
        // characters, not bytes
        assert_eq!(all(&["Özet", "Çiçek"], "Özet", "zet"), ["zet", "içek"]);
    }

    #[test]
    fn the_inserted_tokens_are_filled_for_each_item() {
        assert_eq!(fill_tokens("Trip_{n:02}", 7, 0, 0), "Trip_07");
        assert_eq!(fill_tokens("{n}-{weird}", 3, 0, 0), "3-{weird}");
        let day = 1_700_000_000_000; // 2023-11-14/15 depending on the zone
        assert!(fill_tokens("{date}", 1, day, 0).starts_with("2023-11-1"));
        assert_eq!(fill_tokens("{today}", 1, 0, 0), chrono::Local::now().format("%Y-%m-%d").to_string());
    }

    fn items(n: &[&str]) -> Vec<RenameItem> {
        n.iter().map(|s| RenameItem::new(*s, false, 0)).collect()
    }
    fn ok(v: Vec<Result<String, RenameError>>) -> Vec<String> {
        v.into_iter().map(|r| r.unwrap()).collect()
    }
    fn pat(p: &str, start: i64, step: i64) -> RenameSpec {
        RenameSpec::new(Mode::Pattern { pattern: p.into(), start, step })
    }
    fn fr(f: &str, r: &str, ci: bool, regex: bool) -> RenameSpec {
        RenameSpec::new(Mode::FindReplace { find: f.into(), replace: r.into(), case_insensitive: ci, regex })
    }
    fn st(a: &str, b: &str) -> Step {
        Step { from: a.into(), to: b.into() }
    }

    #[test]
    fn counter_padding_and_step() {
        let r = ok(compute(&items(&["a.jpg", "b.jpg", "c.png"]), &pat("Tatil_{n:03}", 1, 1)));
        assert_eq!(r, ["Tatil_001.jpg", "Tatil_002.jpg", "Tatil_003.png"]);
        let r = ok(compute(&items(&["a.txt", "b.txt"]), &pat("{n:02}-{name}", 10, 5)));
        assert_eq!(r, ["10-a.txt", "15-b.txt"]);
        let r = ok(compute(&items(&["x.txt", "y.txt"]), &pat("f{n}", 99, 1)));
        assert_eq!(r, ["f99.txt", "f100.txt"]);
    }

    #[test]
    fn pattern_ext_and_unknown_tokens() {
        assert_eq!(ok(compute(&items(&["a.b"]), &pat("{ext}{foo}", 1, 1))), ["b{foo}.b"]);
        let mut s = pat("{name}.{ext}", 1, 1);
        s.include_ext = true;
        assert_eq!(ok(compute(&items(&["a.b"]), &s)), ["a.b.b"]);
    }

    #[test]
    fn created_and_today_tokens() {
        let it = vec![RenameItem::new("a.txt", false, 1_700_000_000_000).with_created(1_600_000_000_000)];
        let r = ok(compute(&it, &pat("{created}_{today}", 1, 1)));
        let today = chrono::Local::now().format("%Y-%m-%d").to_string();
        assert!(r[0].starts_with("2020-09-1"), "{r:?}");
        assert!(r[0].contains(&format!("_{today}")), "{r:?}");
    }

    #[test]
    fn date_token() {
        let it = vec![RenameItem::new("a.txt", false, 1_700_000_000_000)];
        let r = ok(compute(&it, &pat("{date}", 1, 1)));
        assert!(r[0].ends_with(".txt") && r[0].len() == "2023-11-14.txt".len(), "{r:?}");
    }

    #[test]
    fn find_replace_plain_and_case() {
        assert_eq!(ok(compute(&items(&["IMG_1.jpg", "img_2.jpg"]), &fr("img", "Foto", true, false))), ["Foto_1.jpg", "Foto_2.jpg"]);
        assert_eq!(ok(compute(&items(&["IMG_1.jpg", "img_2.jpg"]), &fr("img", "Foto", false, false))), ["IMG_1.jpg", "Foto_2.jpg"]);
        // '$' is literal in plain mode
        assert_eq!(ok(compute(&items(&["a.txt"]), &fr("a", "$1", false, false))), ["$1.txt"]);
        // extension untouched by default
        assert_eq!(ok(compute(&items(&["txt.txt"]), &fr("txt", "doc", false, false))), ["doc.txt"]);
        let mut s = fr("txt", "md", false, false);
        s.include_ext = true;
        assert_eq!(ok(compute(&items(&["txt.txt"]), &s)), ["md.md"]);
    }

    #[test]
    fn regex_groups() {
        let s = fr(r"(\d{4})-(\d{2})-(\d{2})", "$3.$2.$1", false, true);
        assert_eq!(ok(compute(&items(&["rapor 2024-03-15.pdf"]), &s)), ["rapor 15.03.2024.pdf"]);
        assert!(matches!(compute(&items(&["a"]), &fr("(", "", false, true))[0], Err(RenameError::BadRegex(_))));
    }

    #[test]
    fn case_modes() {
        let c = |k| RenameSpec::new(Mode::Case(k));
        assert_eq!(ok(compute(&items(&["Hello World.TXT"]), &c(CaseKind::Upper))), ["HELLO WORLD.TXT"]);
        assert_eq!(ok(compute(&items(&["Hello World.TXT"]), &c(CaseKind::Lower))), ["hello world.TXT"]);
        assert_eq!(ok(compute(&items(&["hELLO wORLD-foo_bar.txt"]), &c(CaseKind::Title))), ["Hello World-Foo_Bar.txt"]);
        let mut s = c(CaseKind::Lower);
        s.include_ext = true;
        assert_eq!(ok(compute(&items(&["A.TXT"]), &s)), ["a.txt"]);
    }

    #[test]
    fn prefix_suffix() {
        let s = RenameSpec::new(Mode::PrefixSuffix { prefix: "yeni_".into(), suffix: "_v2".into() });
        assert_eq!(ok(compute(&items(&["a.txt", ".env"]), &s)), ["yeni_a_v2.txt", "yeni_.env_v2"]);
    }

    #[test]
    fn conflicts() {
        let r = compute(&items(&["a.txt", "b.txt"]), &pat("same", 1, 1));
        assert_eq!(r, vec![Err(RenameError::Duplicate), Err(RenameError::Duplicate)]);
        // case-insensitive duplicate: "a" -> "B" collides with existing batch target "b"
        let r = compute(&items(&["a", "b"]), &fr("a", "B", false, false));
        assert_eq!(r[0], Err(RenameError::Duplicate));
        assert_eq!(compute(&items(&["a.txt"]), &pat("x:y", 1, 1))[0], Err(RenameError::InvalidChars));
        assert_eq!(compute(&items(&["a"]), &pat("con", 1, 1))[0], Err(RenameError::Reserved));
        assert_eq!(validate("NUL.txt"), Err(RenameError::Reserved));
        assert_eq!(validate("console"), Ok(()));
        assert_eq!(compute(&items(&["a"]), &pat("", 1, 1))[0], Err(RenameError::Empty));
        assert_eq!(validate("a."), Err(RenameError::TrailingDotSpace));
        let mut s = pat("keep", 1, 1);
        s.existing = vec!["KEEP".into()];
        assert_eq!(compute(&items(&["a"]), &s)[0], Err(RenameError::Exists));
    }

    #[test]
    fn swap_names_are_valid() {
        // Reversing a<->b: targets equal each other's old names but are distinct, so no conflict.
        let r = compute(&items(&["a", "b"]), &pat("{n}", 2, -1));
        assert_eq!(ok(r), ["2", "1"]);
        let pairs = vec![("a".to_string(), "b".to_string()), ("b".to_string(), "a".to_string())];
        let steps = plan(&pairs, |i| format!("~tmp{i}"));
        assert_eq!(steps, vec![st("a", "~tmp0"), st("b", "~tmp1"), st("~tmp0", "b"), st("~tmp1", "a")]);
    }

    #[test]
    fn plan_chain_and_simple() {
        let pairs = vec![
            ("a".to_string(), "b".to_string()),
            ("b".to_string(), "c".to_string()),
            ("x".into(), "y".into()),
            ("same".into(), "same".into()),
        ];
        let steps = plan(&pairs, |i| format!("~t{i}"));
        let mut fs: HashSet<String> = ["a", "b", "x", "same"].iter().map(|s| s.to_string()).collect();
        for Step { from, to } in steps {
            assert!(fs.remove(&from), "missing {from}");
            assert!(fs.insert(to.clone()), "overwrite {to}");
        }
        let want: HashSet<String> = ["b", "c", "y", "same"].iter().map(|s| s.to_string()).collect();
        assert_eq!(fs, want);
        assert_eq!(plan(&[("a.txt".into(), "A.txt".into())], |i| format!("~t{i}")), vec![st("a.txt", "A.txt")]);
    }
}