vivacity 0.12.0

Fast, Composer-compatible installer for PHP projects: install, update, require, remove, dump-autoload
Documentation
//! Emulation of `phpstan/extension-installer` (1.4.3) and its fork
//! `rector/extension-installer` (0.11.2) — docs/reference/plugins/, MIT.
//! Each writes `src/GeneratedConfig.php` inside its own package: a
//! `var_export` of the installed extensions (`phpstan-extension` /
//! `rector-extension` packages, or any package with `extra.phpstan` /
//! `extra.rector`), keyed by name (`ksort`), with the absolute install path
//! (Composer's `getInstallPath`: the physical project directory + the
//! vendor path), the path relative to the generated file's directory
//! (`findShortestPath(..., directories: true)`), the `extra` block and
//! `getFullPrettyVersion()`. phpstan's adds the packages named `*phpstan*`
//! that are not extensions (`NOT_INSTALLED`) and the compacted
//! `phpstan/phpstan` constraint of the extensions
//! (`Intervals::compactConstraint`, printed `>=a, <b`). phpstan's plugin
//! listens to `post-autoload-dump`, rector's to `post-install-cmd`.

use anyhow::Result;
use serde_json::Value;
use std::collections::BTreeMap;
use std::path::Path;
use vivacity_core::layout::{plugin_allowed, Layout, PluginVerdict};
use vivacity_core::lock::{Lock, LockPackage};
use vivacity_core::pathutil::{find_shortest_path, normalize_path};
use vivacity_core::runtime_stub::php_var_export;
use vivacity_resolver::constraint::{parse_constraints, Bound, Constraint};

pub const PHPSTAN: &str = "phpstan/extension-installer";
pub const RECTOR: &str = "rector/extension-installer";

const PHPSTAN_TEMPLATE: &str = "<?php declare(strict_types = 1);\n\nnamespace PHPStan\\ExtensionInstaller;\n\n/**\n * This class is generated by phpstan/extension-installer.\n * @internal\n */\nfinal class GeneratedConfig\n{\n\n\tpublic const EXTENSIONS = %s;\n\n\tpublic const NOT_INSTALLED = %s;\n\n\t/** @var string|null */\n\tpublic const PHPSTAN_VERSION_CONSTRAINT = %s;\n\n\tprivate function __construct()\n\t{\n\t}\n\n}\n";

const RECTOR_TEMPLATE: &str = "<?php\n\ndeclare(strict_types = 1);\n\nnamespace Rector\\RectorInstaller;\n\n/**\n * This class is generated by rector/extension-installer.\n * @internal\n */\nfinal class GeneratedConfig\n{\n    public const EXTENSIONS = %s;\n\n    private function __construct()\n    {\n    }\n}\n";

/// `BasePackage::getFullPrettyVersion()` on a lock entry: a dev version
/// shows its source reference (git/hg) or, without a source, its dist
/// reference, truncated to 7 characters when 40 long.
fn full_pretty_version(p: &LockPackage) -> String {
    let pretty = p.version().to_owned();
    let normalized = vivacity_core::version::normalize_pretty(&pretty).unwrap_or_default();
    let is_dev = normalized.starts_with("dev-") || normalized.ends_with("-dev");
    let source_type = p
        .raw
        .get("source")
        .and_then(|s| s.get("type"))
        .and_then(Value::as_str)
        .unwrap_or("");
    let source_ref = p
        .raw
        .get("source")
        .and_then(|s| s.get("reference"))
        .and_then(Value::as_str)
        .unwrap_or("");
    let dist_ref = p.dist_reference().unwrap_or("");
    if !is_dev
        || (!matches!(source_type, "git" | "hg")
            && (!source_type.is_empty() || dist_ref.is_empty()))
    {
        return pretty;
    }
    let reference = if !source_ref.is_empty() {
        source_ref
    } else {
        dist_ref
    };
    if reference.is_empty() {
        return pretty;
    }
    if reference.len() == 40 && source_type != "svn" {
        return format!("{pretty} {}", &reference[..7]);
    }
    format!("{pretty} {reference}")
}

/// `getInstallPath($package)` as an absolute path: `LibraryInstaller`
/// holds `realpath(vendor-dir)` as the OS spells it (`/private/tmp/…` on
/// macOS, `C:\\…\\vendor` on Windows, no `\\?\\` prefix) and appends
/// `/<name>` with forward slashes — joined verbatim, never normalised as a
/// whole.
fn absolute_install_path(layout: &Layout, name: &str) -> Option<String> {
    let abs = layout.abs(name)?;
    let vendor = layout.vendor_dir();
    let rel = abs.strip_prefix(&vendor).ok()?;
    let real = std::fs::canonicalize(&vendor).unwrap_or(vendor);
    let real = real.to_string_lossy();
    let real = real.strip_prefix("\\\\?\\").unwrap_or(&real);
    let rel = rel.to_string_lossy().replace('\\', "/");
    Some(format!("{}/{}", real.trim_end_matches(['/', '\\']), rel))
}

fn constraint_into_string(c: &Constraint) -> String {
    let (lo, hi) = (c.lower_bound(), c.upper_bound());
    format!(
        "{}{}, {}{}",
        if lo.inclusive { ">=" } else { ">" },
        lo.version,
        if hi.inclusive { "<=" } else { "<" },
        hi.version
    )
}

/// The file lives inside a package cloned from the store — on Linux a
/// hardlink: written through a temporary file and a rename (a new inode),
/// never in place, or the store entry would carry one project's paths
/// into the next (the rector fixture's file surfaced in sylius's warm run).
fn write_if_changed(path: &Path, contents: &str) -> Result<()> {
    if std::fs::read_to_string(path).ok().as_deref() == Some(contents) {
        return Ok(());
    }
    let tmp = path.with_extension("php.vivacity-tmp");
    std::fs::write(&tmp, contents)?;
    std::fs::rename(&tmp, path)?;
    Ok(())
}

/// `sprintf($template, ...)` with `%s` only.
fn fill(template: &str, args: &[String]) -> String {
    let mut out = String::new();
    let mut parts = template.split("%s");
    if let Some(first) = parts.next() {
        out.push_str(first);
    }
    for (part, arg) in parts.zip(args) {
        out.push_str(arg);
        out.push_str(part);
    }
    out
}

/// phpstan's `Plugin::process` (post-autoload-dump).
pub fn phpstan(
    layout: &Layout,
    local: &Lock,
    manifest: &Value,
    with_dev: bool,
    plugins_enabled: bool,
) -> Result<()> {
    let packages: Vec<&LockPackage> = local.wanted_packages(with_dev).collect();
    if !plugins_enabled
        || !packages.iter().any(|p| p.name() == PHPSTAN)
        || !matches!(plugin_allowed(manifest, PHPSTAN), PluginVerdict::Allowed)
    {
        return Ok(());
    }
    let Some(own) = layout.abs(PHPSTAN) else {
        return Ok(());
    };
    let src_dir = own.join("src");
    if !src_dir.is_dir() {
        return Ok(());
    }
    let generated_dir = normalize_path(
        &absolute_install_path(layout, PHPSTAN)
            .map(|p| format!("{p}/src"))
            .unwrap_or_default(),
    );
    let ignore: Vec<&str> = manifest
        .get("extra")
        .and_then(|e| e.get(PHPSTAN))
        .and_then(|e| e.get("ignore"))
        .and_then(Value::as_array)
        .map(|a| a.iter().filter_map(Value::as_str).collect())
        .unwrap_or_default();
    let mut data: BTreeMap<String, Value> = BTreeMap::new();
    let mut not_installed: BTreeMap<String, Value> = BTreeMap::new();
    let mut constraints: Vec<Constraint> = Vec::new();
    for p in &packages {
        let extra_phpstan = p.raw.get("extra").and_then(|e| e.get("phpstan"));
        if p.package_type() != "phpstan-extension" && extra_phpstan.is_none() {
            if p.name().contains("phpstan")
                && ![
                    "phpstan/phpstan",
                    "phpstan/phpstan-shim",
                    "phpstan/phpdoc-parser",
                    PHPSTAN,
                ]
                .contains(&p.name())
            {
                not_installed.insert(p.name().to_owned(), Value::String(full_pretty_version(p)));
            }
            continue;
        }
        if ignore.contains(&p.name()) {
            continue;
        }
        let Some(install_path) = absolute_install_path(layout, p.name()) else {
            continue;
        };
        let mut phpstan_constraint: Option<Constraint> = None;
        if let Some(text) = p
            .raw
            .get("require")
            .and_then(|r| r.get("phpstan/phpstan"))
            .and_then(Value::as_str)
        {
            if let Ok(parsed) = parse_constraints(text) {
                let c = parsed.constraint;
                if c.lower_bound() == Bound::zero() || c.upper_bound() == Bound::positive_infinity()
                {
                    continue;
                }
                constraints.push(c.clone());
                phpstan_constraint = Some(c);
            }
        }
        let mut entry = serde_json::Map::new();
        entry.insert("install_path".into(), Value::String(install_path.clone()));
        entry.insert(
            "relative_install_path".into(),
            Value::String(find_shortest_path(&generated_dir, &install_path, true)),
        );
        entry.insert(
            "extra".into(),
            extra_phpstan.cloned().unwrap_or(Value::Null),
        );
        entry.insert("version".into(), Value::String(full_pretty_version(p)));
        entry.insert(
            "phpstanVersionConstraint".into(),
            phpstan_constraint
                .as_ref()
                .map(|c| Value::String(constraint_into_string(c)))
                .unwrap_or(Value::Null),
        );
        data.insert(p.name().to_owned(), Value::Object(entry));
    }
    let overall = if constraints.is_empty() {
        Value::Null
    } else {
        let multi = if constraints.len() == 1 {
            constraints.remove(0)
        } else {
            Constraint::Multi {
                constraints,
                conjunctive: true,
            }
        };
        Value::String(constraint_into_string(
            &vivacity_resolver::intervals::compact_constraint(&multi),
        ))
    };
    let as_object = |m: BTreeMap<String, Value>| {
        let mut o = serde_json::Map::new();
        for (k, v) in m {
            o.insert(k, v);
        }
        Value::Object(o)
    };
    let contents = fill(
        PHPSTAN_TEMPLATE,
        &[
            php_var_export(&as_object(data), 0),
            php_var_export(&as_object(not_installed), 0),
            php_var_export(&overall, 0),
        ],
    );
    write_if_changed(&src_dir.join("GeneratedConfig.php"), &contents)
}

/// rector's `PluginInstaller::install` (post-install-cmd).
pub fn rector(
    layout: &Layout,
    local: &Lock,
    manifest: &Value,
    with_dev: bool,
    plugins_enabled: bool,
) -> Result<()> {
    let packages: Vec<&LockPackage> = local.wanted_packages(with_dev).collect();
    if !plugins_enabled
        || !packages.iter().any(|p| p.name() == RECTOR)
        || !matches!(plugin_allowed(manifest, RECTOR), PluginVerdict::Allowed)
    {
        return Ok(());
    }
    let Some(own) = layout.abs(RECTOR) else {
        return Ok(());
    };
    let src_dir = own.join("src");
    if !src_dir.is_dir() {
        return Ok(());
    }
    let generated_dir = normalize_path(
        &absolute_install_path(layout, RECTOR)
            .map(|p| format!("{p}/src"))
            .unwrap_or_default(),
    );
    let mut data: BTreeMap<String, Value> = BTreeMap::new();
    for p in &packages {
        let extra_rector = p.raw.get("extra").and_then(|e| e.get("rector"));
        if p.package_type() != "rector-extension" && extra_rector.is_none() {
            continue;
        }
        let Some(install_path) = absolute_install_path(layout, p.name()) else {
            continue;
        };
        let mut entry = serde_json::Map::new();
        entry.insert("install_path".into(), Value::String(install_path.clone()));
        entry.insert(
            "relative_install_path".into(),
            Value::String(find_shortest_path(&generated_dir, &install_path, true)),
        );
        entry.insert("extra".into(), extra_rector.cloned().unwrap_or(Value::Null));
        entry.insert("version".into(), Value::String(full_pretty_version(p)));
        data.insert(p.name().to_owned(), Value::Object(entry));
    }
    let mut o = serde_json::Map::new();
    for (k, v) in data {
        o.insert(k, v);
    }
    let contents = fill(RECTOR_TEMPLATE, &[php_var_export(&Value::Object(o), 0)]);
    write_if_changed(&src_dir.join("GeneratedConfig.php"), &contents)
}

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

    #[test]
    fn constraint_string_like_the_plugin() {
        let c = parse_constraints("^1.10").unwrap().constraint;
        assert_eq!(constraint_into_string(&c), ">=1.10.0.0-dev, <2.0.0.0-dev");
        let multi = Constraint::Multi {
            constraints: vec![
                parse_constraints("^1.10").unwrap().constraint,
                parse_constraints("^1.11.5").unwrap().constraint,
            ],
            conjunctive: true,
        };
        assert_eq!(
            constraint_into_string(&vivacity_resolver::intervals::compact_constraint(&multi)),
            ">=1.11.5.0-dev, <2.0.0.0-dev"
        );
    }

    #[test]
    fn sprintf_fill() {
        assert_eq!(fill("a %s b %s c", &["1".into(), "2".into()]), "a 1 b 2 c");
    }
}