use std::collections::{HashMap, HashSet};
use std::hash::{Hash, Hasher};
use std::path::{Path, PathBuf};
use composer_autoload::{DumpRequest, dump_autoload};
use composer_manifest::lockfile::{self, Lock, LockPackage};
use composer_patches::{ApplyOptions, FailureMode, MaterializedPatch, PatchPlan, apply_patch_text};
use eyre::{Context, Result, eyre};
use serde_json::Value;
use crate::auth::{AuthCredentials, read_all_auth};
use crate::downloader::{DistCandidate, DistOutcome, DistRequest, fetch_and_extract_dists};
use crate::fetch::Fetcher;
use crate::progress::Progress;
#[derive(Clone, Copy)]
pub struct InstallEnv<'a> {
pub fetcher: &'a dyn Fetcher,
pub progress: &'a dyn Progress,
pub cache_root: &'a Path,
}
impl std::fmt::Debug for InstallEnv<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("InstallEnv")
.field("cache_root", &self.cache_root)
.finish_non_exhaustive()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum LinkMode {
#[default]
Extract,
Hardlink,
}
#[derive(Debug, Clone, Copy, Default)]
pub struct InstallOptions {
pub no_dev: bool,
pub link_mode: LinkMode,
}
pub trait ScriptHooks {
fn pre_cmd(&self) -> Result<()>;
fn pre_autoload_dump(&self) -> Result<()>;
fn post_autoload_dump(&self) -> Result<()>;
fn post_cmd(&self) -> Result<()>;
}
#[derive(Debug, Clone)]
pub struct InstallSummary {
pub project_root: PathBuf,
pub packages_installed: u32,
pub packages_already_present: u32,
pub packages_up_to_date: u32,
pub plugin_hooks_skipped: u32,
pub packages_removed: u32,
pub bins_installed: u32,
pub files_deployed: u64,
pub no_dev: bool,
pub download_bytes: u64,
pub autoload_ms: u64,
pub warnings: Vec<String>,
}
pub fn install_from_lock(
env: &InstallEnv<'_>,
project_root: &Path,
opts: InstallOptions,
hooks: Option<&dyn ScriptHooks>,
) -> Result<InstallSummary> {
install_from_lock_with_patches(env, project_root, opts, hooks, None)
}
#[tracing::instrument(skip_all, fields(project_root = %project_root.display()))]
pub fn install_from_lock_with_patches(
env: &InstallEnv<'_>,
project_root: &Path,
opts: InstallOptions,
hooks: Option<&dyn ScriptHooks>,
patches: Option<&PatchPlan>,
) -> Result<InstallSummary> {
let composer_json_path = project_root.join("composer.json");
let composer_lock_path = project_root.join("composer.lock");
let composer_json_bytes = std::fs::read(&composer_json_path).wrap_err_with(|| {
format!(
"{} not found — not a Composer project",
composer_json_path.display()
)
})?;
let lock = if composer_lock_path.exists() {
Lock::read(&composer_lock_path)?
} else {
return Err(eyre!(
"{} not found — run `composer update` first to generate it",
composer_lock_path.display()
));
};
let mut warnings = Vec::new();
warnings.extend(content_hash_warning(&composer_json_bytes, &lock)?);
warnings.extend(preflight(
&composer_json_bytes,
&lock,
opts.no_dev,
hooks.is_some(),
)?);
let composer_json_value: Value = serde_json::from_slice(&composer_json_bytes)
.map_err(|e| eyre!("parsing composer.json: {e}"))?;
let auth: HashMap<String, AuthCredentials> = read_all_auth(&composer_json_value, project_root)?;
if let Some(hooks) = hooks {
hooks.pre_cmd()?;
}
let candidates: Vec<&LockPackage> = if opts.no_dev {
lock.packages.iter().collect()
} else {
lock.all_packages().collect()
};
let plugin_hooks_skipped =
u32::try_from(candidates.iter().filter(|p| p.is_composer_plugin()).count())
.unwrap_or(u32::MAX);
if hooks.is_none() && candidates.iter().any(|p| p.name == "laravel/framework") {
let scripts = composer_json_value
.get("scripts")
.cloned()
.unwrap_or(Value::Null);
let blocking = composer_installers::blocking_post_autoload_dump(&scripts);
if !blocking.is_empty() {
return Err(eyre!(
"Laravel post-autoload-dump runs steps before/among the default Laravel steps \
that this installer does not reproduce:\n {}\n\nIt reproduces \
`artisan package:discover` and `ComposerScripts::postAutoloadDump` natively, \
but only when they run first — a step ahead of or between them may change what \
they see. Steps appended *after* the defaults are fine. Reorder so custom steps \
come last, or run the script yourself (`composer run-script post-autoload-dump`). \
If Laravel changed its default post-autoload-dump, the native discovery is out of \
date — please report it.",
blocking.join("\n "),
));
}
}
let installable: Vec<&LockPackage> = candidates
.iter()
.copied()
.filter(|p| !p.is_path_dist() && !p.is_metapackage())
.collect();
let installer_paths = composer_installers::InstallerPaths::parse(&composer_json_value);
let path_packages: Vec<&LockPackage> = candidates
.iter()
.copied()
.filter(|p| p.is_path_dist())
.collect();
let path_dests: Vec<PathBuf> = path_packages
.iter()
.map(|p| {
let rel = composer_installers::install_path(
&p.name,
p.package_type.as_deref(),
&installer_paths,
);
project_root.join(rel)
})
.collect();
let path_keep_names: HashSet<&str> = path_packages.iter().map(|p| p.name.as_str()).collect();
let installed_state = read_installed_state(project_root);
let force_patch: HashSet<&str> = patches
.map(|plan| compute_force_set(plan, &installable, installed_state.as_ref(), project_root))
.unwrap_or_default();
let (install_set, packages_up_to_date, packages_removed) = diff_install_set_with_force(
&installable,
installed_state.as_ref(),
project_root,
&path_keep_names,
&force_patch,
);
let vendor_dirs: Vec<PathBuf> = install_set
.iter()
.map(|p| {
let rel = composer_installers::install_path(
&p.name,
p.package_type.as_deref(),
&installer_paths,
);
if rel == format!("vendor/{}", p.name)
&& let Some(framework) =
composer_installers::unsupported_framework(p.package_type.as_deref())
{
warnings.push(format!(
"{}: package type '{}' is a composer/installers '{}' type that this installer \
does not relocate — installing to vendor/{} (the framework may expect it \
elsewhere; add an extra.installer-paths entry to override)",
p.name,
p.package_type.as_deref().unwrap_or(""),
framework,
p.name,
));
}
project_root.join(rel)
})
.collect();
let candidate_sets: Vec<Vec<DistCandidate>> = install_set
.iter()
.map(|p| {
p.dist_urls()
.into_iter()
.map(|url| {
let auth_entry = auth_origin_from_url(&url)
.and_then(|origin| auth.get(origin))
.map(|creds| (creds.header_value(), creds.header_name()));
DistCandidate {
url,
auth_header: auth_entry.as_ref().map(|(v, _)| v.clone()),
auth_header_name: auth_entry.as_ref().map(|(_, n)| *n),
}
})
.collect()
})
.collect();
let dists: Vec<DistRequest<'_>> = install_set
.iter()
.zip(vendor_dirs.iter())
.zip(candidate_sets.iter())
.map(|((p, dest), candidates)| {
let dist = p.dist.as_ref().unwrap();
let (primary, fallbacks) = candidates
.split_first()
.expect("non-empty dist_urls for a dist package");
DistRequest {
package_name: &p.name,
url: &primary.url,
sha1: dist.shasum.as_deref().unwrap_or(""),
reference: dist.reference.as_deref().unwrap_or(""),
strip_prefix: None,
vendor_dest: dest,
auth_header: primary.auth_header.as_deref(),
auth_header_name: primary.auth_header_name,
project_root,
fallbacks,
}
})
.collect();
let outcomes = fetch_and_extract_dists(
env.fetcher,
env.cache_root,
&dists,
env.progress,
opts.link_mode,
)?;
let path_summary = crate::path_link::materialize_path_packages(
project_root,
&path_packages,
&path_dests,
installed_state.as_ref(),
);
warnings.extend(path_summary.warnings);
if let Some(plan) = patches {
apply_patch_plan(
plan,
&install_set,
&vendor_dirs,
project_root,
&mut warnings,
)?;
}
let deploy_summary = deploy_components(&install_set, &vendor_dirs, project_root);
warnings.extend(deploy_summary.warnings);
if let Some(hooks) = hooks {
hooks.pre_autoload_dump()?;
}
let autoload_marker = project_root
.join("vendor/composer")
.join(AUTOLOAD_FRESH_MARKER);
let lock_bytes = std::fs::read(&composer_lock_path).unwrap_or_default();
let fingerprint =
autoload_fingerprint(&composer_json_bytes, &lock_bytes, opts.no_dev).to_string();
let autoload_fresh = hooks.is_none()
&& install_set.is_empty()
&& packages_removed == 0
&& path_summary.linked == 0
&& project_root.join("vendor/autoload.php").is_file()
&& std::fs::read_to_string(&autoload_marker)
.ok()
.as_deref()
.map(str::trim)
== Some(fingerprint.as_str());
let autoload_started = std::time::Instant::now();
if !autoload_fresh {
dump_autoload(&DumpRequest {
project_root,
optimize: false,
classmap_authoritative: false,
no_dev: opts.no_dev,
apcu_autoloader: false,
apcu_prefix: None,
autoloader_suffix: None,
})
.map_err(|e| eyre!("autoload dump failed: {e}"))?;
if let Err(e) = std::fs::write(&autoload_marker, &fingerprint) {
warnings.push(format!(
"could not write autoload freshness marker {}: {e}",
autoload_marker.display()
));
}
}
let autoload_ms = u64::try_from(autoload_started.elapsed().as_millis()).unwrap_or(u64::MAX);
match hooks {
Some(hooks) => hooks.post_autoload_dump()?,
None => {
if candidates.iter().any(|p| p.name == "laravel/framework")
&& let Err(e) = run_laravel_discovery(project_root, &composer_json_value)
{
warnings.push(format!("laravel package discovery failed: {e}"));
}
}
}
let bin_summary = crate::bin_proxy::install_bin_proxies(project_root, &candidates);
warnings.extend(bin_summary.warnings);
if let Some(hooks) = hooks {
hooks.post_cmd()?;
}
let packages_installed = u32::try_from(
outcomes
.iter()
.filter(|o| matches!(o, DistOutcome::Downloaded { .. }))
.count(),
)
.unwrap_or(u32::MAX);
let download_bytes: u64 = outcomes
.iter()
.map(|o| match o {
DistOutcome::Downloaded { bytes } => *bytes,
DistOutcome::CacheHit => 0,
})
.sum();
let packages_already_present = u32::try_from(
outcomes
.iter()
.filter(|o| **o == DistOutcome::CacheHit)
.count(),
)
.unwrap_or(u32::MAX);
let packages_installed = packages_installed.saturating_add(path_summary.linked);
let packages_up_to_date = packages_up_to_date.saturating_add(path_summary.up_to_date);
Ok(InstallSummary {
project_root: project_root.to_path_buf(),
packages_installed,
packages_already_present,
packages_up_to_date,
plugin_hooks_skipped,
packages_removed,
bins_installed: bin_summary.bins_installed,
files_deployed: deploy_summary.files_deployed,
no_dev: opts.no_dev,
download_bytes,
autoload_ms,
warnings,
})
}
fn compute_force_set<'a>(
plan: &'a PatchPlan,
installable: &[&'a LockPackage],
installed_state: Option<&InstalledState>,
project_root: &Path,
) -> HashSet<&'a str> {
let mut force: HashSet<&str> = plan
.tracked_packages()
.filter(|name| plan.fingerprint_changed(name))
.collect();
if plan.root_patches.is_empty() {
return force;
}
let by_name: HashMap<&str, &LockPackage> =
installable.iter().map(|p| (p.name.as_str(), *p)).collect();
let needs_reextract = |name: &str| -> bool {
by_name.get(name).is_some_and(|p| {
installed_state.is_none_or(|state| !dist_up_to_date(p, state, project_root))
})
};
loop {
let mut added = false;
for rp in &plan.root_patches {
let any_reextract = rp
.packages
.iter()
.any(|pkg| force.contains(pkg.as_str()) || needs_reextract(pkg));
if any_reextract {
for pkg in &rp.packages {
if let Some(p) = by_name.get(pkg.as_str())
&& force.insert(p.name.as_str())
{
added = true;
}
}
}
}
if !added {
break;
}
}
force
}
fn apply_patch_plan(
plan: &PatchPlan,
install_set: &[&LockPackage],
vendor_dirs: &[PathBuf],
project_root: &Path,
warnings: &mut Vec<String>,
) -> Result<()> {
let mut new_fingerprints = plan.applied.clone();
let install_names: HashSet<&str> = install_set.iter().map(|p| p.name.as_str()).collect();
let mut failed: HashSet<String> = HashSet::new();
for (pkg, vendor_dir) in install_set.iter().zip(vendor_dirs.iter()) {
let Some(pkg_patches) = plan.patches.get(&pkg.name) else {
continue;
};
let res = composer_patches::apply_package_patches(
vendor_dir,
&pkg.name,
pkg_patches,
plan.failure_mode,
plan.skip_report,
)?;
warnings.extend(res.warnings);
if res.fingerprint.is_none() {
failed.insert(pkg.name.clone());
}
}
let vendor_by_name: HashMap<&str, &PathBuf> = install_set
.iter()
.zip(vendor_dirs.iter())
.map(|(p, dir)| (p.name.as_str(), dir))
.collect();
for rp in &plan.root_patches {
let all_pristine = rp
.packages
.iter()
.all(|p| install_names.contains(p.as_str()));
if !all_pristine {
continue;
}
if apply_root_patch(project_root, &rp.patch, plan.failure_mode, warnings)? {
if !plan.skip_report {
for pkg in &rp.packages {
if let Some(dir) = vendor_by_name.get(pkg.as_str())
&& let Err(e) = composer_patches::append_patches_txt(dir, &[&rp.patch])
{
warnings.push(format!(
"could not update PATCHES.txt in `{}`: {e}",
dir.display()
));
}
}
}
} else {
failed.extend(rp.packages.iter().cloned());
}
}
for name in plan.tracked_packages() {
if !install_names.contains(name) {
continue;
}
match (failed.contains(name), plan.desired_fingerprint(name)) {
(false, Some(fp)) => {
new_fingerprints.insert(name.to_string(), fp);
}
_ => {
new_fingerprints.remove(name);
}
}
}
let human = plan.write_lock.then(|| plan.human_view());
if let Err(e) = composer_patches::lock::write_with_human(project_root, &new_fingerprints, human)
{
warnings.push(format!("could not write patches.lock.json: {e}"));
}
Ok(())
}
fn apply_root_patch(
project_root: &Path,
patch: &MaterializedPatch,
failure_mode: FailureMode,
warnings: &mut Vec<String>,
) -> Result<bool> {
let text = std::fs::read_to_string(&patch.local_path)
.with_context(|| format!("reading patch `{}`", patch.local_path.display()))?;
let opts = ApplyOptions {
depth: patch.depth,
..ApplyOptions::default()
};
match apply_patch_text(project_root, &text, &opts) {
Ok(_) => Ok(true),
Err(e) => match failure_mode {
FailureMode::Abort => Err(eyre!(
"patch `{}` failed to apply at the project root: {e:#}",
patch.description
)),
FailureMode::SkipAndWarn => {
warnings.push(format!(
"patch `{}` failed to apply at the project root: {e:#}",
patch.description
));
Ok(false)
}
},
}
}
struct DeploySummary {
files_deployed: u64,
warnings: Vec<String>,
}
fn deploy_components(
install_set: &[&LockPackage],
vendor_dirs: &[PathBuf],
project_root: &Path,
) -> DeploySummary {
let mut files_deployed = 0u64;
let mut warnings = Vec::new();
let mut deployed_component = false;
for (pkg, vendor_dir) in install_set.iter().zip(vendor_dirs.iter()) {
let Some(plan) = composer_installers::plan_deploy(pkg.package_type.as_deref(), &pkg.extra)
else {
continue;
};
if plan.map.is_empty() && plan.chmod.is_empty() {
continue;
}
match composer_installers::apply_deploy(&plan, vendor_dir, project_root) {
Ok(stats) => {
files_deployed += stats.files_copied;
deployed_component |= plan.is_component;
}
Err(e) => {
warnings.push(format!("deploy of {} failed: {e}", pkg.name));
}
}
}
if deployed_component && let Err(e) = write_vendor_path_php(project_root) {
warnings.push(format!("writing app/etc/vendor_path.php failed: {e}"));
}
DeploySummary {
files_deployed,
warnings,
}
}
fn run_laravel_discovery(project_root: &Path, composer_json_value: &Value) -> Result<()> {
let installed_path = project_root.join("vendor/composer/installed.json");
let bytes = std::fs::read(&installed_path)
.wrap_err_with(|| format!("reading {}", installed_path.display()))?;
let installed: Value = serde_json::from_slice(&bytes).wrap_err("parsing installed.json")?;
let root_extra = composer_json_value
.get("extra")
.cloned()
.unwrap_or(Value::Null);
let manifest = composer_installers::build_package_manifest(&installed, &root_extra);
let php = composer_installers::render_packages_php(&manifest);
let cache_path = project_root.join(composer_installers::PACKAGES_CACHE);
if let Some(parent) = cache_path.parent() {
std::fs::create_dir_all(parent)
.wrap_err_with(|| format!("creating {}", parent.display()))?;
}
std::fs::write(&cache_path, php)
.wrap_err_with(|| format!("writing {}", cache_path.display()))?;
for rel in composer_installers::STALE_CACHES {
let path = project_root.join(rel);
if path.exists() {
let _ = std::fs::remove_file(path);
}
}
Ok(())
}
fn write_vendor_path_php(project_root: &Path) -> Result<()> {
let dir = project_root.join("app/etc");
std::fs::create_dir_all(&dir).wrap_err_with(|| format!("creating {}", dir.display()))?;
std::fs::write(
dir.join("vendor_path.php"),
composer_installers::VENDOR_PATH_PHP,
)
.wrap_err("writing vendor_path.php")?;
Ok(())
}
pub(crate) struct InstalledState {
pub(crate) packages: HashMap<String, String>,
}
fn read_installed_state(project_root: &Path) -> Option<InstalledState> {
let path = project_root.join("vendor/composer/installed.json");
let bytes = std::fs::read(&path).ok()?;
let value: Value = serde_json::from_slice(&bytes).ok()?;
let obj = value.as_object()?;
let packages_arr = obj.get("packages")?.as_array()?;
let mut packages = HashMap::with_capacity(packages_arr.len());
for pkg in packages_arr {
let name = pkg.get("name").and_then(|v| v.as_str()).unwrap_or("");
if name.is_empty() {
continue;
}
let reference = pkg
.get("dist")
.and_then(|d| d.get("reference"))
.and_then(|r| r.as_str())
.unwrap_or("");
packages.insert(name.to_string(), reference.to_string());
}
Some(InstalledState { packages })
}
#[cfg(test)]
pub(crate) fn diff_install_set<'a>(
installable: &[&'a LockPackage],
installed_state: Option<&InstalledState>,
project_root: &Path,
keep_names: &HashSet<&str>,
) -> (Vec<&'a LockPackage>, u32, u32) {
diff_install_set_with_force(
installable,
installed_state,
project_root,
keep_names,
&HashSet::new(),
)
}
pub(crate) fn diff_install_set_with_force<'a>(
installable: &[&'a LockPackage],
installed_state: Option<&InstalledState>,
project_root: &Path,
keep_names: &HashSet<&str>,
force: &HashSet<&str>,
) -> (Vec<&'a LockPackage>, u32, u32) {
let Some(state) = installed_state else {
return (installable.to_vec(), 0, 0);
};
let mut need_install: Vec<&'a LockPackage> = Vec::new();
let mut up_to_date: u32 = 0;
let mut wanted_names: HashSet<&str> = installable.iter().map(|p| p.name.as_str()).collect();
wanted_names.extend(keep_names.iter().copied());
for p in installable {
if !force.contains(p.name.as_str()) && dist_up_to_date(p, state, project_root) {
up_to_date = up_to_date.saturating_add(1);
continue;
}
need_install.push(p);
}
let mut removed: u32 = 0;
for old_name in state.packages.keys() {
if !wanted_names.contains(old_name.as_str()) {
let vendor_dir = project_root.join("vendor").join(old_name);
if vendor_dir.is_dir() {
let _ = std::fs::remove_dir_all(&vendor_dir);
removed = removed.saturating_add(1);
}
}
}
(need_install, up_to_date, removed)
}
fn dist_up_to_date(p: &LockPackage, state: &InstalledState, project_root: &Path) -> bool {
let lock_ref = p
.dist
.as_ref()
.and_then(|d| d.reference.as_deref())
.unwrap_or("");
state.packages.get(&p.name).is_some_and(|installed_ref| {
installed_ref == lock_ref && project_root.join("vendor").join(&p.name).is_dir()
})
}
fn auth_origin_from_url(url: &str) -> Option<&str> {
let after_scheme = url.split_once("://")?.1;
let host_and_port = after_scheme.split('/').next()?;
if host_and_port.is_empty() {
None
} else {
Some(host_and_port)
}
}
const AUTOLOAD_FRESH_MARKER: &str = ".composer-install-autoload-fresh";
fn autoload_fingerprint(composer_json_bytes: &[u8], lock_bytes: &[u8], no_dev: bool) -> u64 {
let mut h = std::hash::DefaultHasher::new();
composer_json_bytes.hash(&mut h);
lock_bytes.hash(&mut h);
no_dev.hash(&mut h);
h.finish()
}
fn content_hash_warning(composer_json_bytes: &[u8], lock: &Lock) -> Result<Option<String>> {
let Some(expected) = &lock.content_hash else {
return Ok(None);
};
let actual = lockfile::content_hash(composer_json_bytes)?;
if actual.eq_ignore_ascii_case(expected) {
return Ok(None);
}
Ok(Some(format!(
"composer.lock is out of sync with composer.json (content-hash {expected} → {actual}); \
installing the locked package set anyway — you may be getting outdated dependencies. \
Run `composer update` to regenerate the lock.",
)))
}
fn preflight(
composer_json_bytes: &[u8],
lock: &Lock,
no_dev: bool,
scripts_on: bool,
) -> Result<Vec<String>> {
let mut reasons: Vec<String> = Vec::new();
let mut warnings: Vec<String> = Vec::new();
let mut plugin_packages: Vec<String> = Vec::new();
if !scripts_on
&& let Ok(value) = serde_json::from_slice::<Value>(composer_json_bytes)
&& value
.get("scripts")
.and_then(Value::as_object)
.is_some_and(|s| !s.is_empty())
&& !composer_installers::only_reproduced_scripts(
value.get("scripts").unwrap_or(&Value::Null),
)
{
warnings.push(
"composer.json declares `scripts`; they are not run by default. \
Supply a `ScriptHooks` implementation to run them."
.into(),
);
}
let packages: Vec<&LockPackage> = if no_dev {
lock.packages.iter().collect()
} else {
lock.all_packages().collect()
};
for p in packages {
if p.is_path_dist() {
continue;
}
if p.is_metapackage() {
continue;
}
if p.is_composer_plugin() {
plugin_packages.push(p.name.clone());
continue;
}
let Some(dist) = &p.dist else {
reasons.push(format!(
"package `{}` has no `dist` block (source-only install); \
this installer does not clone VCS sources — run a full `composer install`.",
p.name,
));
continue;
};
if dist.kind != "zip" {
reasons.push(format!(
"package `{}` uses dist type `{}`; this installer currently supports only \
zip dists — run a full `composer install`.",
p.name, dist.kind,
));
}
}
if !plugin_packages.is_empty() {
let names = plugin_packages.join(", ");
let noun = if plugin_packages.len() == 1 {
"package"
} else {
"packages"
};
warnings.push(format!(
"{noun} {names} {verb} Composer plugins (type `composer-plugin`); \
this installer does not run plugin install-time hooks and skips \
{pronoun}. Run a full `composer install` if the plugin behavior is required.",
verb = if plugin_packages.len() == 1 {
"is a"
} else {
"are"
},
pronoun = if plugin_packages.len() == 1 {
"the package itself"
} else {
"them"
},
));
}
if reasons.is_empty() {
Ok(warnings)
} else {
let bullets = reasons
.iter()
.map(|r| format!(" - {r}"))
.collect::<Vec<_>>()
.join("\n");
Err(eyre!(
"this lockfile requires features this installer does not handle:\n{bullets}",
))
}
}
#[cfg(test)]
mod tests;