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::archive::ArchiveKind;
use crate::auth::{AuthCredentials, read_all_auth_with};
use crate::downloader::{DistCandidate, DistOutcome, DistRequest, fetch_and_extract_dists};
use crate::error::InstallError;
use crate::fetch::Fetcher;
use crate::progress::Progress;
use crate::source::{SourceFetcher, SourceSpec, materialize_sources};
use crate::stale::{InstallRecord, remove_stale_packages};
#[derive(Clone, Copy)]
#[non_exhaustive]
pub struct InstallEnv<'a> {
pub fetcher: &'a dyn Fetcher,
pub progress: &'a dyn Progress,
pub cache_root: &'a Path,
pub source_fetcher: Option<&'a dyn SourceFetcher>,
pub machine_auth: Option<&'a HashMap<String, AuthCredentials>>,
pub autoload_marker: &'a str,
pub wording: Wording<'a>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub struct Wording<'a> {
pub tool: &'a str,
pub update_command: &'a str,
pub install_command: &'a str,
pub scripts_hint: &'a str,
}
impl Default for Wording<'_> {
fn default() -> Self {
Self {
tool: "this installer",
update_command: "composer update",
install_command: "composer install",
scripts_hint: "Supply a `ScriptHooks` implementation to run them.",
}
}
}
impl<'a> InstallEnv<'a> {
pub fn new(fetcher: &'a dyn Fetcher, progress: &'a dyn Progress, cache_root: &'a Path) -> Self {
Self {
fetcher,
progress,
cache_root,
source_fetcher: None,
machine_auth: None,
autoload_marker: AUTOLOAD_FRESH_MARKER,
wording: Wording::default(),
}
}
#[must_use]
pub fn with_wording(mut self, wording: Wording<'a>) -> Self {
self.wording = wording;
self
}
#[must_use]
pub fn with_machine_auth(mut self, auth: &'a HashMap<String, AuthCredentials>) -> Self {
self.machine_auth = Some(auth);
self
}
#[must_use]
pub fn with_autoload_marker(mut self, name: &'a str) -> Self {
self.autoload_marker = name;
self
}
#[must_use]
pub fn with_source_fetcher(mut self, source_fetcher: &'a dyn SourceFetcher) -> Self {
self.source_fetcher = Some(source_fetcher);
self
}
}
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)
.field("source_fetcher", &self.source_fetcher.is_some())
.field("machine_auth", &self.machine_auth.map(HashMap::len))
.field("autoload_marker", &self.autoload_marker)
.field("wording", &self.wording)
.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 = match std::fs::read(&composer_json_path) {
Ok(bytes) => bytes,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
return Err(InstallError::MissingManifest {
path: composer_json_path,
}
.into());
}
Err(e) => {
return Err(
eyre::Report::new(e).wrap_err(format!("reading {}", composer_json_path.display()))
);
}
};
let lock = if composer_lock_path.exists() {
Lock::read(&composer_lock_path)?
} else {
return Err(InstallError::MissingLock {
path: composer_lock_path,
}
.into());
};
let mut warnings = Vec::new();
let wording = &env.wording;
warnings.extend(content_hash_warning(&composer_json_bytes, &lock, wording)?);
warnings.extend(preflight(
&composer_json_bytes,
&lock,
opts.no_dev,
hooks.is_some(),
env.source_fetcher.is_some(),
wording,
)?);
let composer_json_value: Value = serde_json::from_slice(&composer_json_bytes).map_err(|e| {
InstallError::InvalidManifest {
path: composer_json_path.clone(),
detail: e.to_string(),
}
})?;
let auth: HashMap<String, AuthCredentials> =
read_all_auth_with(&composer_json_value, project_root, env.machine_auth)?;
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 {tool} does not reproduce:\n {}\n\n\
`artisan package:discover` and `ComposerScripts::postAutoloadDump` are reproduced 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 "),
tool = wording.tool,
));
}
}
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 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) = diff_install_set_with_force(
&installable,
installed_state.as_ref(),
project_root,
&force_patch,
);
let new_record = InstallRecord::for_packages(&candidates, &installer_paths);
let packages_removed = remove_stale_packages(project_root, &new_record);
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 {tool} \
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,
tool = wording.tool,
));
}
project_root.join(rel)
})
.collect();
let dist_indices: Vec<usize> = (0..install_set.len())
.filter(|&i| install_set[i].dist.is_some())
.collect();
let source_indices: Vec<usize> = (0..install_set.len())
.filter(|&i| install_set[i].is_source_install())
.collect();
let candidate_sets: Vec<Vec<DistCandidate>> = dist_indices
.iter()
.map(|&i| {
install_set[i]
.dist_urls()
.into_iter()
.map(|url| {
let auth_entry = composer_auth::auth_key(&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<'_>> = dist_indices
.iter()
.zip(candidate_sets.iter())
.filter_map(|(&i, candidates)| {
let p = install_set[i];
let dist = p.dist.as_ref()?;
let (primary, fallbacks) = candidates
.split_first()
.expect("non-empty dist_urls for a dist package");
Some(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,
archive: ArchiveKind::from_dist_type(&dist.kind).unwrap_or(ArchiveKind::Zip),
vendor_dest: &vendor_dirs[i],
auth_header: primary.auth_header.as_deref(),
auth_header_name: primary.auth_header_name,
project_root,
fallbacks,
})
})
.collect();
let source_url_sets: Vec<Vec<String>> = source_indices
.iter()
.map(|&i| install_set[i].source_urls())
.collect();
let source_specs: Vec<SourceSpec<'_>> = source_indices
.iter()
.zip(source_url_sets.iter())
.map(|(&i, urls)| {
let p = install_set[i];
SourceSpec {
package_name: &p.name,
urls,
reference: p.source.as_ref().map_or("", |s| s.reference.as_str()),
dest: &vendor_dirs[i],
}
})
.collect();
let outcomes = fetch_and_extract_dists(
env.fetcher,
env.cache_root,
&dists,
env.progress,
opts.link_mode,
)?;
let sources_installed = match env.source_fetcher {
Some(fetcher) if !source_specs.is_empty() => materialize_sources(fetcher, &source_specs)?,
_ => 0,
};
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 {
let resolved;
let plan = if plan.deferred.is_empty() {
plan
} else {
let mut p = plan.clone();
p.resolve_deferred()
.wrap_err("materializing vendor-shipped patches after install")?;
resolved = p;
&resolved
};
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(env.autoload_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)
.saturating_add(u32::try_from(sources_installed).unwrap_or(u32::MAX));
let packages_up_to_date = packages_up_to_date.saturating_add(path_summary.up_to_date);
if let Err(e) = new_record.write(project_root) {
warnings.push(format!(
"could not record the installed packages ({e}); the next install may not \
remove packages that leave the lock"
));
}
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();
for target in plan.deferred_targets() {
if let Some(p) = installable.iter().find(|p| p.name == target) {
force.insert(p.name.as_str());
}
}
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;
warnings.extend(
stats
.warnings
.into_iter()
.map(|w| format!("deploy of {}: {w}", pkg.name)),
);
}
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())
.or_else(|| {
pkg.get("source")
.and_then(|s| s.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,
) -> (Vec<&'a LockPackage>, u32) {
diff_install_set_with_force(installable, installed_state, project_root, &HashSet::new())
}
pub(crate) fn diff_install_set_with_force<'a>(
installable: &[&'a LockPackage],
installed_state: Option<&InstalledState>,
project_root: &Path,
force: &HashSet<&str>,
) -> (Vec<&'a LockPackage>, u32) {
let Some(state) = installed_state else {
return (installable.to_vec(), 0);
};
let mut need_install: Vec<&'a LockPackage> = Vec::new();
let mut up_to_date: u32 = 0;
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);
}
(need_install, up_to_date)
}
fn dist_up_to_date(p: &LockPackage, state: &InstalledState, project_root: &Path) -> bool {
let lock_ref = p.install_reference();
state.packages.get(&p.name).is_some_and(|installed_ref| {
installed_ref == lock_ref && project_root.join("vendor").join(&p.name).is_dir()
})
}
pub(crate) 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,
wording: &Wording<'_>,
) -> 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 `{}` to regenerate the lock.",
wording.update_command,
)))
}
fn preflight(
composer_json_bytes: &[u8],
lock: &Lock,
no_dev: bool,
scripts_on: bool,
sources_on: bool,
wording: &Wording<'_>,
) -> Result<Vec<String>> {
let Wording {
tool,
install_command,
scripts_hint,
..
} = *wording;
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(format!(
"composer.json declares `scripts`; they are not run by default. {scripts_hint}"
));
}
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());
}
let Some(dist) = &p.dist else {
match &p.source {
Some(src) if src.kind == "git" && sources_on => {}
Some(src) if src.kind == "git" => reasons.push(format!(
"package `{}` has no `dist` block, only a git source, and git source \
installs are not enabled — configure a source fetcher, or install it \
with `{install_command}`.",
p.name,
)),
Some(src) => reasons.push(format!(
"package `{}` has a `{}` source; {tool} can only install git \
sources — install it with `{install_command}`.",
p.name, src.kind,
)),
None => reasons.push(format!(
"package `{}` has no `dist` block and no git `source` to clone — install \
it with `{install_command}`.",
p.name,
)),
}
continue;
};
if ArchiveKind::from_dist_type(&dist.kind).is_none() {
reasons.push(format!(
"package `{}` uses dist type `{}`; {tool} handles only `zip` and \
`tar` dists — install it with `{install_command}`.",
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`); \
{pronoun} files install like any other package's, but {tool} \
does not run plugin install-time hooks. Run `{install_command}` \
if the hook behavior is required.",
verb = if plugin_packages.len() == 1 {
"is a"
} else {
"are"
},
pronoun = if plugin_packages.len() == 1 {
"its"
} else {
"their"
},
));
}
if reasons.is_empty() {
Ok(warnings)
} else {
Err(InstallError::Unsupported { reasons }.into())
}
}
#[cfg(test)]
mod tests;