composr 1.0.0

Fast Rust install + dump-autoload for Composer projects (vowels not included)
Documentation
use anyhow::{Context, Result};
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

/// One classmap entry: FQCN (raw bytes — see [`crate::parse::Declaration`]) →
/// absolute path. Keys sort lexicographically by byte, matching PHP `ksort`.
pub type ClassMap = BTreeMap<Vec<u8>, PathBuf>;

/// Emit `vendor/composer/autoload_classmap.php` content as raw bytes.
///
/// Composer sorts the map by `ksort` (byte-wise ASCII), uses `array(...)`
/// syntax, single-quoted strings, and prefixes paths with either
/// `$baseDir . '/...'` (project) or `$vendorDir . '/...'` (vendor packages).
pub fn render_classmap_php(map: &ClassMap, root: &Path, vendor_dir: &Path) -> Vec<u8> {
    let mut out = Vec::with_capacity(map.len() * 96);
    out.extend_from_slice(b"<?php\n\n// autoload_classmap.php @generated by Composer\n\n");
    out.extend_from_slice(b"$vendorDir = dirname(__DIR__);\n");
    out.extend_from_slice(b"$baseDir = dirname($vendorDir);\n\n");
    out.extend_from_slice(b"return array(\n");

    for (fqcn, path) in map {
        out.extend_from_slice(b"    '");
        write_escaped_single_quote(&mut out, fqcn);
        out.extend_from_slice(b"' => ");
        write_path_expr(&mut out, path, root, vendor_dir, PathStyle::Var);
        out.extend_from_slice(b",\n");
    }

    out.extend_from_slice(b");\n");
    out
}

/// Render the inner body of `autoload_static.php`'s `$classMap = array(...)`
/// section — just the entry lines, indented as Composer indents them
/// (8 spaces). Caller wraps in the surrounding scaffold.
pub fn render_static_classmap_body(map: &ClassMap, root: &Path, vendor_dir: &Path) -> Vec<u8> {
    let mut out = Vec::with_capacity(map.len() * 96);
    for (fqcn, path) in map {
        out.extend_from_slice(b"        '");
        write_escaped_single_quote(&mut out, fqcn);
        out.extend_from_slice(b"' => ");
        write_path_expr(&mut out, path, root, vendor_dir, PathStyle::DirRelative);
        out.extend_from_slice(b",\n");
    }
    out
}

/// Replace the `$classMap = array (...);` section of an existing
/// `autoload_static.php` with a freshly-rendered body. We only touch the
/// classMap section — everything else (file hashes, PSR-4 prefix maps, the
/// class-name suffix that pairs this file with autoload_real.php, the
/// `getInitializer` block) is preserved byte-for-byte. That's deliberate:
/// our tool's job is to update the classmap, and Composer owns the rest.
///
/// We operate on raw bytes because Composer's `$files` section can legally
/// contain non-UTF-8 bytes as array keys (we've seen `'\xa9' => ...` in real
/// projects). Treating the input as `&str` would refuse to load such a file.
pub fn replace_static_classmap(existing: &[u8], new_body: &[u8]) -> Result<Vec<u8>> {
    let needle: &[u8] = b"public static $classMap = array (";
    let start = memchr_find(existing, needle)
        .context("autoload_static.php has no $classMap section to replace")?;
    // Skip to the line break after the opening.
    let nl_off = memchr::memchr(b'\n', &existing[start..])
        .context("malformed $classMap opening line")?;
    let after_open = start + nl_off + 1;
    // Find the closing `    );` line. Two shapes to accept:
    //   1) `<entries...>\n    );` — the normal case with at least one entry
    //   2) `    );` immediately at after_open — composer-like file with an
    //      empty class map (rare in real projects, but happens with stubbed
    //      or freshly bootstrapped files).
    let close = if existing[after_open..].starts_with(b"    );") {
        after_open
    } else {
        let close_marker: &[u8] = b"\n    );";
        let close_rel = memchr_find(&existing[after_open..], close_marker)
            .context("autoload_static.php $classMap section has no closing `    );`")?;
        after_open + close_rel + 1
    };

    let mut out = Vec::with_capacity(existing.len() - (close - after_open) + new_body.len());
    out.extend_from_slice(&existing[..after_open]);
    out.extend_from_slice(new_body);
    out.extend_from_slice(&existing[close..]);
    Ok(out)
}

fn memchr_find(haystack: &[u8], needle: &[u8]) -> Option<usize> {
    if needle.is_empty() || haystack.len() < needle.len() {
        return None;
    }
    let first = needle[0];
    let mut i = 0;
    while let Some(pos) = memchr::memchr(first, &haystack[i..]) {
        let abs = i + pos;
        if abs + needle.len() > haystack.len() {
            return None;
        }
        if &haystack[abs..abs + needle.len()] == needle {
            return Some(abs);
        }
        i = abs + 1;
    }
    None
}

#[derive(Copy, Clone)]
enum PathStyle {
    /// `$vendorDir . '/foo'` / `$baseDir . '/foo'` — used in autoload_classmap.php.
    Var,
    /// `__DIR__ . '/..' . '/foo'` (vendor) or `__DIR__ . '/../..' . '/foo'` (root) —
    /// used inline inside vendor/composer/autoload_static.php.
    DirRelative,
}

fn write_path_expr(
    out: &mut Vec<u8>,
    path: &Path,
    root: &Path,
    vendor_dir: &Path,
    style: PathStyle,
) {
    if let Ok(rel) = path.strip_prefix(vendor_dir) {
        let rel = rel.to_string_lossy();
        match style {
            PathStyle::Var => {
                out.extend_from_slice(b"$vendorDir . '/");
                out.extend_from_slice(rel.as_bytes());
                out.push(b'\'');
            }
            PathStyle::DirRelative => {
                out.extend_from_slice(b"__DIR__ . '/..' . '/");
                out.extend_from_slice(rel.as_bytes());
                out.push(b'\'');
            }
        }
    } else if let Ok(rel) = path.strip_prefix(root) {
        let rel = rel.to_string_lossy();
        match style {
            PathStyle::Var => {
                out.extend_from_slice(b"$baseDir . '/");
                out.extend_from_slice(rel.as_bytes());
                out.push(b'\'');
            }
            PathStyle::DirRelative => {
                out.extend_from_slice(b"__DIR__ . '/../..' . '/");
                out.extend_from_slice(rel.as_bytes());
                out.push(b'\'');
            }
        }
    } else {
        // File outside both root and vendor — emit an absolute literal.
        // Rare (custom classmap entry pointing outside the project).
        out.push(b'\'');
        write_escaped_single_quote(out, path.to_string_lossy().as_bytes());
        out.push(b'\'');
    }
}

/// Append `s` to `out`, escaping `\` as `\\` and `'` as `\'` — the only
/// PHP single-quoted-string escapes. Operates on raw bytes so non-UTF-8
/// identifier bytes (PHP allows \x80-\xff) round-trip verbatim.
fn write_escaped_single_quote(out: &mut Vec<u8>, s: &[u8]) {
    for &b in s {
        match b {
            b'\\' => out.extend_from_slice(b"\\\\"),
            b'\'' => out.extend_from_slice(b"\\'"),
            _ => out.push(b),
        }
    }
}

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

    fn contains(haystack: &[u8], needle: &[u8]) -> bool {
        haystack.windows(needle.len()).any(|w| w == needle)
    }

    #[test]
    fn renders_simple_classmap() {
        let mut map = ClassMap::new();
        map.insert(b"Foo\\Bar".to_vec(), PathBuf::from("/proj/app/Foo/Bar.php"));
        let s = render_classmap_php(&map, Path::new("/proj"), Path::new("/proj/vendor"));
        assert!(contains(
            &s,
            b"'Foo\\\\Bar' => $baseDir . '/app/Foo/Bar.php',"
        ));
        assert!(s.starts_with(b"<?php\n\n// autoload_classmap.php @generated by Composer\n\n"));
        assert!(s.ends_with(b");\n"));
    }

    #[test]
    fn renders_vendor_path() {
        let mut map = ClassMap::new();
        map.insert(
            b"Vendor\\Cls".to_vec(),
            PathBuf::from("/proj/vendor/acme/lib/src/Cls.php"),
        );
        let s = render_classmap_php(&map, Path::new("/proj"), Path::new("/proj/vendor"));
        assert!(contains(&s, b"$vendorDir . '/acme/lib/src/Cls.php'"));
    }

    #[test]
    fn renders_high_byte_class_key_verbatim() {
        // Symfony declares `class \xa9` — make sure we emit the byte raw
        // (not as a UTF-8 replacement character).
        let mut map = ClassMap::new();
        map.insert(
            vec![0xa9],
            PathBuf::from("/proj/vendor/symfony/cache/Traits/ValueWrapper.php"),
        );
        let s = render_classmap_php(&map, Path::new("/proj"), Path::new("/proj/vendor"));
        // Must contain literal `'<0xa9>' => ...`, not `'\xef\xbf\xbd'`.
        assert!(contains(&s, &[b'\'', 0xa9, b'\'', b' ', b'=', b'>']));
    }

    #[test]
    fn replaces_static_classmap() {
        let existing: &[u8] = b"<?php\n\
            namespace Composer\\Autoload;\n\
            class Foo {\n\
            \x20\x20\x20\x20public static $files = array(\n\
            \x20\x20\x20\x20\x20\x20\x20\x20'a' => 'b',\n\
            \x20\x20\x20\x20);\n\n\
            \x20\x20\x20\x20public static $classMap = array (\n\
            \x20\x20\x20\x20\x20\x20\x20\x20'Old\\\\Class' => 'old.php',\n\
            \x20\x20\x20\x20);\n\n\
            \x20\x20\x20\x20public static function getInitializer() {}\n\
            }\n";
        let new_body: &[u8] = b"        'New\\\\Class' => 'new.php',\n";
        let out = replace_static_classmap(existing, new_body).unwrap();
        let out_str = std::str::from_utf8(&out).unwrap();
        assert!(out_str.contains("'New\\\\Class' => 'new.php',"));
        assert!(!out_str.contains("'Old\\\\Class'"));
        assert!(out_str.contains("public static $files"));
        assert!(out_str.contains("getInitializer"));
    }

    #[test]
    fn replaces_static_classmap_preserves_non_utf8_bytes() {
        // `$files` array keys in real Composer output have been seen to
        // contain raw Latin-1 bytes (e.g. 0xa9 ©). Verify we round-trip
        // those bytes verbatim rather than mangling them.
        let mut existing: Vec<u8> = b"<?php\n\
            class Foo {\n\
            \x20\x20\x20\x20public static $files = array(\n\
            \x20\x20\x20\x20\x20\x20\x20\x20'".to_vec();
        existing.push(0xa9);
        existing.extend_from_slice(b"' => 'val',\n\
            \x20\x20\x20\x20);\n\n\
            \x20\x20\x20\x20public static $classMap = array (\n\
            \x20\x20\x20\x20\x20\x20\x20\x20'X' => 'x.php',\n\
            \x20\x20\x20\x20);\n\
            }\n");
        let new_body: &[u8] = b"        'Y' => 'y.php',\n";
        let out = replace_static_classmap(&existing, new_body).unwrap();
        assert!(out.contains(&0xa9));
        assert!(out
            .windows(b"'Y' => 'y.php',".len())
            .any(|w| w == b"'Y' => 'y.php',"));
    }

    #[test]
    fn escapes_backslash_and_quote() {
        let mut out = Vec::new();
        write_escaped_single_quote(&mut out, b"Foo\\Bar");
        assert_eq!(out, b"Foo\\\\Bar");
        let mut out = Vec::new();
        write_escaped_single_quote(&mut out, b"it's");
        assert_eq!(out, b"it\\'s");
    }
}