use super::*;
#[allow(clippy::too_many_arguments)]
pub(crate) fn resolution_fallback(
project: &std::path::Path,
manifest: &serde_json::Value,
command: vivacity_core::scope::ResolutionCommand,
no_plugins: bool,
no_fallback: bool,
with_install: bool,
post_update_cmd: bool,
with_dev: bool,
start: &PoolStart<'_>,
) -> anyhow::Result<Option<i32>> {
let mut issues = vivacity_core::scope::resolution_issues(
project,
manifest,
command,
!no_plugins,
with_install,
post_update_cmd,
);
if !no_plugins
&& matches!(
command,
vivacity_core::scope::ResolutionCommand::Require
| vivacity_core::scope::ResolutionCommand::Remove
)
&& vivacity_core::scope::active_plugins(project, manifest, true)
.iter()
.any(|p| p == vivacity_core::effect_plugins::LAMINAS_SKELETON)
&& vivacity_core::effect_plugins::laminas_skeleton_configured(manifest) == Ok(true)
{
issues.push(vivacity_core::scope::ScopeIssue::ResolutionPlugin(
vivacity_core::effect_plugins::LAMINAS_SKELETON.to_owned(),
"rewrites composer.json, which the command reads again for the lock's hash (not emulated)".to_owned(),
));
}
if !with_install && post_update_cmd && !no_plugins {
issues.extend(crate::no_install::issues_before_resolution(
project, manifest, with_dev,
));
}
let flex_active = vivacity_core::scope::active_plugins(project, manifest, !no_plugins)
.iter()
.any(|p| p == "symfony/flex");
if flex_active && !issues.iter().any(|i| matches!(i, vivacity_core::scope::ScopeIssue::ResolutionPlugin(n, _) if n == "symfony/flex")) {
if let Some(reason) = flex_write_guard(project, manifest) {
issues.push(vivacity_core::scope::ScopeIssue::ResolutionPlugin(
"symfony/flex".to_owned(),
reason,
));
}
}
let merge_active = vivacity_core::scope::active_plugins(project, manifest, !no_plugins)
.iter()
.any(|p| p == vivacity_resolver::merge_plugin::PLUGIN_NAME);
if merge_active {
if let Ok(Some(merged)) = merge_root_when(project, manifest, true, true) {
if !merged.repositories.is_empty() {
issues.push(vivacity_core::scope::ScopeIssue::ResolutionPlugin(
vivacity_resolver::merge_plugin::PLUGIN_NAME.to_owned(),
format!(
"merges repositories from {} (not emulated at resolution)",
merged.repositories.join(", ")
),
));
}
}
}
issues.extend(insecure_repository_issue(
project,
manifest,
with_install,
with_dev,
!no_plugins,
start,
));
if issues.is_empty() {
return Ok(None);
}
delegate_resolution(&issues, no_fallback).map(Some)
}
pub(crate) fn hold_trigger(manifest: &serde_json::Value) -> bool {
let mut memo = HOLD_TRIGGER
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(decided) = *memo {
return decided;
}
let decided = evaluate_hold_trigger(manifest);
*memo = Some(decided);
decided
}
static HOLD_TRIGGER: std::sync::Mutex<Option<bool>> = std::sync::Mutex::new(None);
pub(crate) fn forget_hold_trigger() {
*HOLD_TRIGGER
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner) = None;
}
fn evaluate_hold_trigger(manifest: &serde_json::Value) -> bool {
if std::env::var("VIVACITY_HOLD_OUTPUT").as_deref() == Ok("force") {
return true;
}
fn remote(repos: Option<&serde_json::Value>) -> bool {
use serde_json::Value;
let entries: Box<dyn Iterator<Item = &Value>> = match repos {
Some(Value::Array(a)) => Box::new(a.iter()),
Some(Value::Object(o)) => Box::new(o.values()),
_ => return false,
};
entries.into_iter().any(|r| {
if r.get("type").and_then(Value::as_str) != Some("composer") {
return false;
}
let Some(url) = r.get("url").and_then(Value::as_str) else {
return false;
};
let lower = url.to_ascii_lowercase();
let Some(rest) = ["https?://", "https://", "http://"]
.iter()
.find_map(|p| lower.strip_prefix(p))
else {
return !lower.contains("://") && !std::path::Path::new(url).exists();
};
let host = rest.split(['/', ':']).next().unwrap_or("");
host != "repo.packagist.org" && host != "packagist.org"
})
}
let configured = remote(manifest.get("repositories"))
|| vivacity_core::fetch::composer_home().is_some_and(|home| {
vivacity_core::fetch::with_global_json(&home, "config.json", |c| {
remote(c.and_then(|c| c.get("repositories")))
})
});
configured && secure_http_refuses()
}
fn secure_http_refuses() -> bool {
use vivacity_core::secure_http::{classify, Verdict};
matches!(
classify("http://localhost/"),
Verdict::Refuse | Verdict::HandOver(_)
)
}
pub(crate) fn start_holding(until: &str) {
if vivacity_core::io::holding_output() {
return;
}
vivacity_core::io::hold_output();
if std::env::var_os("VIVACITY_TRACE").is_some() {
eprintln!("trace: output held until {until} (secure-http)");
}
}
#[derive(Default)]
pub(crate) struct PoolStart<'a> {
pub allow: Vec<String>,
pub mode: Option<vivacity_resolver::pool::UpdateMode>,
pub added: Vec<(String, String)>,
pub removed: Vec<String>,
pub lock: Option<&'a serde_json::Value>,
pub no_resolution: bool,
}
pub(crate) fn local_install_issue(manifest: &serde_json::Value) -> Option<String> {
use serde_json::Value;
let local = |repos: Option<&Value>| -> bool {
let entries: Box<dyn Iterator<Item = &Value>> = match repos {
Some(Value::Array(a)) => Box::new(a.iter()),
Some(Value::Object(o)) => Box::new(o.values()),
_ => return false,
};
entries.into_iter().any(|r| {
r.get("type").and_then(Value::as_str) == Some("composer")
&& r.get("url")
.and_then(Value::as_str)
.is_some_and(|u| u.starts_with("file://") || !u.contains("://"))
})
};
let home = vivacity_core::fetch::composer_home();
let any = local(manifest.get("repositories"))
|| home.as_deref().is_some_and(|h| {
vivacity_core::fetch::with_global_json(h, "config.json", |c| {
local(c.and_then(|c| c.get("repositories")))
})
});
if !any {
return None;
}
let config = vivacity_resolver::session::MergedConfig::load(manifest, home.as_deref()).ok()?;
let policy = vivacity_resolver::policy_config::PolicyConfig::from_raw(&config.policy).ok()?;
let repos: Vec<(String, Option<Value>)> = config
.repositories
.iter()
.filter(|r| r.definition.get("type").and_then(Value::as_str) == Some("composer"))
.filter_map(|r| {
let url = r.definition.get("url").and_then(Value::as_str)?;
vivacity_resolver::repository::repo_urls(url)
.packages_json_url
.starts_with("file://")
.then(|| (url.to_owned(), r.definition.get("filter").cloned()))
})
.collect();
vivacity_resolver::repository::local_unsupported(
&repos,
&policy.custom_lists,
false,
policy.malware_blocks("install"),
)
}
pub(crate) fn repository_construction_issue(
project: Option<&std::path::Path>,
manifest: Option<&serde_json::Value>,
) -> Option<String> {
use serde_json::Value;
let check = |repos: Option<&Value>| -> Option<String> {
let entries: Vec<(String, &Value)> = match repos {
None | Some(Value::Null) => return None,
Some(Value::Array(a)) => a
.iter()
.enumerate()
.map(|(i, r)| (i.to_string(), r))
.collect(),
Some(Value::Object(o)) => o.iter().map(|(k, r)| (k.clone(), r)).collect(),
Some(_) => return Some("\"repositories\" is not a list of definitions".to_owned()),
};
for (name, repo) in entries {
let def = match repo {
Value::Bool(false) => continue,
Value::Object(m) => m,
_ => return Some(format!("repository {name} is not a definition")),
};
if def.len() == 1 && def.values().next() == Some(&Value::Bool(false)) {
continue;
}
let Some(kind) = def.get("type") else {
return Some(format!("repository {name} has no type"));
};
if def.get("packagist") == Some(&Value::Bool(false)) {
return Some(format!(
"repository {name} has a packagist key, which Composer warns about"
));
}
let set = |k: &str| def.get(k).filter(|v| !v.is_null());
let array = |v: &Value| v.is_array() || v.is_object();
if set("only").is_some_and(|v| !array(v))
|| set("exclude").is_some_and(|v| !array(v))
|| (set("only").is_some() && set("exclude").is_some())
|| set("canonical").is_some_and(|v| !v.is_boolean())
{
return Some(format!(
"repository {name} has an only/exclude/canonical Composer refuses"
));
}
if kind.as_str() != Some("composer") {
continue;
}
let refused = match def.get("url") {
Some(Value::String(url)) => composer_url_refused(project, url),
_ => true,
};
if refused {
return Some(format!(
"repository {name} has a url Composer refuses for a composer repository"
));
}
if def.get("filter").is_some_and(user_filter_refused) {
return Some(format!("repository {name} has a filter Composer refuses"));
}
}
None
};
if let Some(why) = check(manifest.and_then(|m| m.get("repositories"))) {
return Some(why);
}
let home = vivacity_core::fetch::composer_home()?;
vivacity_core::fetch::with_global_json(&home, "config.json", |c| {
check(c.and_then(|c| c.get("repositories")))
})
}
fn composer_url_refused(project: Option<&std::path::Path>, url: &str) -> bool {
let bytes = url.as_bytes();
let word = bytes
.iter()
.take_while(|b| b.is_ascii_alphanumeric() || **b == b'_' || **b == b'.')
.count();
let after = if bytes.get(word) == Some(&b'?') {
word + 1
} else {
word
};
let owned;
let url = if word > 0 && url[after..].starts_with("://") {
url
} else {
let path = std::path::Path::new(url);
let exists = if path.is_absolute() {
path.exists()
} else {
project.is_some_and(|p| p.join(path).exists())
};
if exists {
return false;
}
owned = format!("http://{url}");
&owned
};
let url = url.trim_end_matches('/').replace('\\', "/");
let Some((scheme, rest)) = url.split_once("://") else {
return true;
};
if scheme.eq_ignore_ascii_case("file") {
return false;
}
let authority = rest.split(['/', '?', '#']).next().unwrap_or("");
let host_port = authority.rsplit('@').next().unwrap_or("");
if host_port.is_empty() {
return true;
}
let port = if host_port.starts_with('[') && host_port.ends_with(']') {
""
} else {
match host_port.rsplit_once(':') {
Some(("", _)) => return true,
Some((_, port)) => port,
None => "",
}
};
!(port.is_empty() || php_port(port))
}
fn php_port(port: &str) -> bool {
if port.len() > 5 {
return false;
}
let s = port.trim_start_matches([' ', '\t', '\n', '\r', '\x0b', '\x0c']);
let (negative, s) = match s.as_bytes().first() {
Some(b'-') => (true, &s[1..]),
Some(b'+') => (false, &s[1..]),
_ => (false, s),
};
let digits: String = s.chars().take_while(char::is_ascii_digit).collect();
if digits.is_empty() {
return false;
}
let value: i64 = digits.parse().unwrap_or(i64::MAX);
!negative && value <= 65535 || (negative && value == 0)
}
fn user_filter_refused(filter: &serde_json::Value) -> bool {
use serde_json::Value;
let integer_key = |k: &str| {
let digits = k.strip_prefix('-').unwrap_or(k);
k == "0"
|| (!digits.is_empty()
&& !digits.starts_with('0')
&& digits.bytes().all(|b| b.is_ascii_digit())
&& k.parse::<i64>().is_ok())
};
match filter {
Value::Null | Value::Bool(_) => false,
Value::Array(a) => !a.is_empty(),
Value::Object(m) => m
.iter()
.any(|(k, v)| k.is_empty() || integer_key(k) || !v.is_boolean()),
_ => true,
}
}
pub(crate) fn unregistered_repository_issue(
manifest: &serde_json::Value,
) -> Option<vivacity_core::scope::ScopeIssue> {
use serde_json::Value;
let home = vivacity_core::fetch::composer_home();
let issue = |why: String| Some(vivacity_core::scope::ScopeIssue::Layout(why));
let config = match vivacity_resolver::session::MergedConfig::load(manifest, home.as_deref()) {
Ok(c) => c,
Err(e) => return issue(e.message),
};
for repo in &config.repositories {
let def = &repo.definition;
let named = match &repo.key {
vivacity_resolver::session::RepoKey::Named(n) => n.clone(),
vivacity_resolver::session::RepoKey::Indexed(i) => i.to_string(),
};
let Some(kind) = def.get("type").and_then(Value::as_str) else {
return issue(format!("repository {named} has no type"));
};
match kind {
"package" => {
let well_formed = |p: &Value| {
p.get("name").is_some_and(Value::is_string)
&& p.get("version").is_some_and(Value::is_string)
};
let ok = match def.get("package") {
Some(p @ Value::Object(_)) => well_formed(p),
Some(Value::Array(list)) => {
!list.is_empty() && list.iter().all(|p| p.is_object() && well_formed(p))
}
_ => false,
};
if !ok {
return issue(format!(
"repository {named} of type \"package\" without a package definition vivacity can vouch for"
));
}
}
"composer" | "vcs" | "git" | "bitbucket" | "git-bitbucket" | "github" | "gitlab"
| "svn" | "fossil" | "perforce" | "hg" | "artifact" | "path" => {
if !def
.get("url")
.and_then(Value::as_str)
.is_some_and(|u| !u.is_empty())
{
return issue(format!("repository {named} has no url"));
}
}
other => {
return issue(format!(
"repository {named} of type \"{other}\", which Composer does not register"
))
}
}
}
None
}
fn insecure_repository_issue(
project: &std::path::Path,
manifest: &serde_json::Value,
with_install: bool,
with_dev: bool,
plugins_enabled: bool,
start: &PoolStart<'_>,
) -> Option<vivacity_core::scope::ScopeIssue> {
use serde_json::Value;
use vivacity_core::secure_http::{classify, insecure, Verdict};
if start.no_resolution {
return None;
}
let home = vivacity_core::fetch::composer_home();
let config = vivacity_resolver::session::MergedConfig::load(manifest, home.as_deref()).ok()?;
let why = |v: Verdict| match v {
Verdict::Refuse => Some("which secure-http refuses".to_owned()),
Verdict::HandOver(reason) => Some(format!("with {reason}")),
Verdict::Allowed | Verdict::Warn { .. } => None,
};
let mut local: Vec<String> = Vec::new();
let mut local_filters: Vec<(String, Option<Value>)> = Vec::new();
for repo in &config.repositories {
let def = &repo.definition;
let kind = def.get("type").and_then(Value::as_str);
let named = match &repo.key {
vivacity_resolver::session::RepoKey::Named(n) => n.clone(),
vivacity_resolver::session::RepoKey::Indexed(i) => i.to_string(),
};
if !matches!(kind, Some("composer" | "path") | None) {
return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
"repository {named} of type \"{}\" (not supported by vivacity at resolution)",
kind.unwrap_or("")
)));
}
if kind.is_some()
&& ["only", "exclude", "canonical"]
.iter()
.any(|k| def.get(*k).is_some())
{
return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
"repository {named} sets only/exclude/canonical (not supported by vivacity at resolution)"
)));
}
if kind != Some("composer") {
continue;
}
match def.get("url").and_then(Value::as_str) {
None => {
return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
"repository {named} has no url"
)))
}
Some(url) if url.starts_with("https://") => {}
Some(url) => {
let canonical = vivacity_resolver::repository::repo_urls(url).url;
if !["file://", "http://", "https://"]
.iter()
.any(|p| canonical.starts_with(p))
{
return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
"repository {named} has a url scheme vivacity does not read ({url})"
)));
}
}
}
if def.get("allow_ssl_downgrade") == Some(&Value::Bool(true)) {
return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
"repository {} sets allow_ssl_downgrade (not reproduced)",
def.get("url").and_then(Value::as_str).unwrap_or("?")
)));
}
let Some(url) = def.get("url").and_then(Value::as_str) else {
continue;
};
if url.starts_with("https://") {
continue;
}
let urls = vivacity_resolver::repository::repo_urls(url);
if insecure(&urls.packages_json_url).is_some() {
if let Some(why) = why(classify(&urls.packages_json_url)) {
return Some(vivacity_core::scope::ScopeIssue::Layout(format!(
"repository {} is read over an insecure protocol, {why}",
vivacity_resolver::metacache::sanitize_url(&urls.url)
)));
}
continue;
}
if urls.packages_json_url.starts_with("file://") {
local.push(url.to_owned());
local_filters.push((url.to_owned(), def.get("filter").cloned()));
}
}
let partial = !start.allow.is_empty() || !start.added.is_empty();
let read_lock;
let lock = match start.lock {
Some(l) => Some(l),
None if partial && with_install && !local.is_empty() => {
read_lock = vivacity_core::jsonfile::read(&project.join("composer.lock"));
read_lock.as_deref()
}
None => None,
};
if let (true, true, Some(lock)) = (with_install, partial, lock) {
if let Some(reason) =
fixed_insecure_reason(project, manifest, with_dev, plugins_enabled, start, lock)
{
return Some(vivacity_core::scope::ScopeIssue::Layout(reason));
}
}
let fixed = lock
.filter(|_| partial)
.map(|l| fixed_packages(manifest, with_dev, start, l));
if local.is_empty() {
return None;
}
let policy = vivacity_resolver::policy_config::PolicyConfig::from_raw(&config.policy).ok();
let custom_lists = policy
.as_ref()
.map(|p| p.custom_lists.clone())
.unwrap_or_default();
if let Some(why) =
vivacity_resolver::repository::local_unsupported(&local_filters, &custom_lists, true, false)
{
return Some(vivacity_core::scope::ScopeIssue::Layout(why));
}
let filters_fatal = policy
.as_ref()
.is_none_or(|p| !(p.ignore_unreachable.update && p.ignore_unreachable.install));
let scope = pool_scope(
manifest,
with_install,
with_dev,
start,
fixed,
filters_fatal,
);
let (found, verdict) = vivacity_resolver::repository::local_insecure_url(&local, &scope)?;
why(verdict).map(|why| {
vivacity_core::scope::ScopeIssue::Layout(format!(
"a local repository names {} (an insecure protocol), {why}",
vivacity_resolver::metacache::sanitize_url(&found)
))
})
}
fn root_requirements(
manifest: &serde_json::Value,
with_dev: bool,
start: &PoolStart<'_>,
) -> Vec<(String, String)> {
use serde_json::Value;
let removed: Vec<String> = start.removed.iter().map(|n| n.to_lowercase()).collect();
let sections: &[&str] = if with_dev {
&["require", "require-dev"]
} else {
&["require"]
};
let mut root: Vec<(String, String)> = sections
.iter()
.filter_map(|k| manifest.get(*k).and_then(Value::as_object))
.flatten()
.filter_map(|(n, c)| Some((n.to_lowercase(), c.as_str()?.to_owned())))
.filter(|(n, _)| !removed.contains(n))
.collect();
for (name, constraint) in &start.added {
let name = name.to_lowercase();
root.retain(|(n, _)| *n != name);
root.push((name, constraint.clone()));
}
root
}
pub(crate) fn fixed_insecure_reason(
project: &std::path::Path,
manifest: &serde_json::Value,
with_dev: bool,
plugins_enabled: bool,
start: &PoolStart<'_>,
lock: &serde_json::Value,
) -> Option<String> {
use serde_json::Value;
if !crate::install::any_insecure_dist(lock) {
return None;
}
let fixed = fixed_packages(manifest, with_dev, start, lock);
let sections = if with_dev {
&["packages", "packages-dev"][..]
} else {
&["packages"][..]
};
let entries: Vec<Value> = sections
.iter()
.filter_map(|k| lock.get(*k).and_then(Value::as_array))
.flatten()
.filter(|p| {
p.get("name")
.and_then(Value::as_str)
.is_some_and(|n| fixed.names.contains(&n.to_lowercase()))
})
.cloned()
.collect();
let subset = serde_json::json!({"packages": entries, "packages-dev": []});
let parsed = vivacity_core::lock::Lock::from_value(&subset);
crate::install::insecure_dist_reason(project, manifest, &parsed, true, plugins_enabled)
}
struct Fixed {
names: std::collections::BTreeSet<String>,
requires: Vec<(String, String)>,
}
fn fixed_packages(
manifest: &serde_json::Value,
with_dev: bool,
start: &PoolStart<'_>,
lock: &serde_json::Value,
) -> Fixed {
use serde_json::Value;
use vivacity_resolver::pool::UpdateMode;
let root = root_requirements(manifest, with_dev, start);
let mut allow: Vec<String> = start.allow.iter().map(|n| n.to_lowercase()).collect();
allow.extend(start.added.iter().map(|(n, _)| n.to_lowercase()));
let locked: Vec<&Value> = ["packages", "packages-dev"]
.iter()
.filter_map(|k| lock.get(*k).and_then(Value::as_array))
.flatten()
.collect();
let name_of = |p: &Value| {
p.get("name")
.and_then(Value::as_str)
.unwrap_or("")
.to_lowercase()
};
let patterns: Vec<_> = allow
.iter()
.map(|a| vivacity_resolver::pool::package_name_regexp(a))
.collect();
let mut allowed: std::collections::BTreeSet<String> = locked
.iter()
.map(|p| name_of(p))
.filter(|n| {
patterns
.iter()
.any(|re| re.is_match(n.as_bytes()).unwrap_or(false))
})
.collect();
if let Some(mode) = start.mode.filter(|m| *m != UpdateMode::OnlyListed) {
let root_names: Vec<&String> = root.iter().map(|(n, _)| n).collect();
let mut pending: Vec<String> = allowed.iter().cloned().collect();
while let Some(name) = pending.pop() {
let Some(p) = locked.iter().find(|p| name_of(p) == name) else {
continue;
};
for dep in p
.get("require")
.and_then(Value::as_object)
.into_iter()
.flatten()
.map(|(d, _)| d.to_lowercase())
{
if mode == UpdateMode::ListedWithTransitiveDepsNoRootRequire
&& root_names.contains(&&dep)
{
continue;
}
if allowed.insert(dep.clone()) {
pending.push(dep);
}
}
}
}
let mut names = std::collections::BTreeSet::new();
let mut requires = Vec::new();
for p in &locked {
let name = name_of(p);
if allowed.contains(&name) {
continue;
}
names.insert(name);
for (target, _) in p
.get("replace")
.and_then(Value::as_object)
.into_iter()
.flatten()
{
names.insert(target.to_lowercase());
}
for (dep, c) in p
.get("require")
.and_then(Value::as_object)
.into_iter()
.flatten()
{
if let Some(c) = c.as_str() {
requires.push((dep.to_lowercase(), c.to_owned()));
}
}
}
Fixed { names, requires }
}
fn pool_scope(
manifest: &serde_json::Value,
with_install: bool,
with_dev: bool,
start: &PoolStart<'_>,
fixed: Option<Fixed>,
filters_fatal: bool,
) -> vivacity_resolver::repository::LocalScope {
use serde_json::Value;
use vivacity_resolver::pool::UpdateMode;
let root = root_requirements(manifest, with_dev, start);
let flagged = root
.iter()
.filter(|(_, c)| {
c.contains('@')
|| c.split("||").flat_map(|a| a.split('|')).any(|alt| {
let left = alt.split(" as ").next().unwrap_or(alt).trim();
vivacity_resolver::version::parse_stability(left) != "stable"
})
})
.map(|(n, _)| n.clone())
.collect();
let root_aliases = root
.iter()
.filter_map(|(n, c)| {
let (from, to) = c.split_once(" as ")?;
let norm = |v: &str| {
vivacity_resolver::version::normalize(v.trim().trim_start_matches(['=', ' ']), None)
.ok()
};
Some((n.clone(), norm(from)?, norm(to)?))
})
.collect();
let minimum_stability = match manifest
.get("minimum-stability")
.and_then(Value::as_str)
.map(str::to_lowercase)
.as_deref()
{
Some("rc") => "RC".to_owned(),
Some(s @ ("dev" | "alpha" | "beta")) => s.to_owned(),
_ => "stable".to_owned(),
};
let root_names = root.iter().map(|(n, _)| n.clone()).collect();
let (skipped, mut requires) = match fixed {
Some(f) => (f.names, f.requires),
None => (std::collections::BTreeSet::new(), Vec::new()),
};
requires.extend(root);
requires.retain(|(n, _)| !skipped.contains(n));
let unlock = match start.mode {
Some(UpdateMode::ListedWithTransitiveDeps) => Some(false),
Some(UpdateMode::ListedWithTransitiveDepsNoRootRequire) => Some(true),
_ => None,
};
vivacity_resolver::repository::LocalScope {
requires,
skipped,
minimum_stability,
flagged,
root_aliases,
unlock,
root_names,
with_dists: with_install,
filters_fatal,
}
}
static MANIFEST_RESTORED: std::sync::atomic::AtomicU8 = std::sync::atomic::AtomicU8::new(0);
pub(crate) fn manifest_restored(created: bool) {
MANIFEST_RESTORED.store(
if created { 2 } else { 1 },
std::sync::atomic::Ordering::Relaxed,
);
}
pub(crate) fn forget_manifest_restored() {
MANIFEST_RESTORED.store(0, std::sync::atomic::Ordering::Relaxed);
}
pub(crate) fn delegate_resolution(
issues: &[vivacity_core::scope::ScopeIssue],
no_fallback: bool,
) -> anyhow::Result<i32> {
let tokens = command_line();
let command = command_of(&tokens);
let composer = which_composer();
let stops = no_fallback || composer.is_none();
vivacity_core::io::drop_output();
if stops {
vivacity_core::io::release_deferred();
} else {
vivacity_core::io::drop_held();
vivacity_core::io::drop_deferred();
}
let reason_line = |line: &str| {
if stops {
vivacity_core::say_always!("{line}");
} else {
vivacity_core::say!("{line}");
}
};
reason_line(&format!(
"vivacity: `{}` on this project is outside what vivacity handles natively:",
canonical_command(&command)
));
for issue in issues {
reason_line(&format!(" - {issue}"));
}
if no_fallback {
let restored = MANIFEST_RESTORED.swap(0, std::sync::atomic::Ordering::Relaxed);
if restored == 1 {
vivacity_core::say_always!("--no-fallback given: stopping here (composer.json was edited, then put back as it was; nothing else was written to the project).");
} else if restored == 2 {
vivacity_core::say_always!("--no-fallback given: stopping here (composer.json was created, then removed; nothing else was written to the project).");
} else {
vivacity_core::say_always!(
"--no-fallback given: stopping here (nothing was written to the project)."
);
}
return Ok(3);
}
let Some(composer) = composer else {
vivacity_core::say_always!(
"composer not found for the fallback — install Composer or run with --no-plugins."
);
return Ok(3);
};
let forwarded = forwarded_arguments(&tokens, &command);
hand_over(
&composer,
&forwarded,
has_option(&tokens, "--offline"),
None,
)
.context("cannot run composer")
}
pub(crate) fn command_line() -> Vec<std::ffi::OsString> {
let argv = ARGV.lock().map(|a| a.clone()).unwrap_or_default();
argv.into_iter().skip(1).collect()
}
fn command_of(tokens: &[std::ffi::OsString]) -> String {
tokens
.iter()
.map(|t| t.to_string_lossy())
.find(|t| !t.starts_with('-'))
.unwrap_or_default()
.into_owned()
}
fn canonical_command(command: &str) -> &str {
match command {
"r" => "require",
"rm" => "remove",
"upgrade" => "update",
other => other,
}
}
fn has_option(tokens: &[std::ffi::OsString], flag: &str) -> bool {
tokens.iter().take_while(|t| *t != "--").any(|t| t == flag)
}
pub(crate) fn hand_over(
composer: &std::path::Path,
args: &[std::ffi::OsString],
offline: bool,
reason: Option<&str>,
) -> std::io::Result<i32> {
vivacity_core::signals::release();
vivacity_core::io::drop_held();
vivacity_core::io::drop_output();
if let Err(why) = vivacity_core::fetch::take_back_cached_dists() {
vivacity_core::say_always!("Error: {why}");
return Ok(1);
}
let line = args
.iter()
.map(|a| a.to_string_lossy().into_owned())
.collect::<Vec<_>>()
.join(" ");
match reason {
Some(reason) => {
vivacity_core::say!("vivacity: delegating to `composer {line}` ({reason})…")
}
None => vivacity_core::say!("vivacity: delegating to `composer {line}`…"),
}
let mut cmd = std::process::Command::new(composer);
cmd.args(args);
with_verbosity(&mut cmd);
if offline {
cmd.env("COMPOSER_DISABLE_NETWORK", "1");
}
let status = vivacity_core::signals::spawn_forwarding(&mut cmd)?;
Ok(vivacity_core::signals::exit_code_of(status))
}
pub(crate) fn forwarded_arguments(
tokens: &[std::ffi::OsString],
command: &str,
) -> Vec<std::ffi::OsString> {
let has = |flag: &str| has_option(tokens, flag);
let mut dropped = vec![
"--no-fallback",
"--check-scope",
"--offline",
"--run-scripts",
];
if matches!(canonical_command(command), "require" | "remove") {
dropped.push("--no-autoloader");
}
let mut before_dashes = true;
let mut forwarded: Vec<std::ffi::OsString> = Vec::new();
for t in tokens {
if t == "--" {
before_dashes = false;
}
if before_dashes && dropped.iter().any(|f| t == f) {
continue;
}
forwarded.push(t.clone());
}
if !has("--run-scripts") && !has("--no-scripts") {
let at = forwarded
.iter()
.position(|t| t == "--")
.unwrap_or(forwarded.len());
forwarded.insert(at, "--no-scripts".into());
}
forwarded
}
pub(crate) fn with_verbosity(cmd: &mut std::process::Command) {
let level = match vivacity_core::io::level() {
vivacity_core::io::Verbosity::Quiet => "-1",
vivacity_core::io::Verbosity::Normal => "0",
vivacity_core::io::Verbosity::Verbose => "1",
};
cmd.env("SHELL_VERBOSITY", level);
}
pub(crate) fn fallback_or_fail(
args: &InstallArgs,
scope: &vivacity_core::scope::ScopeReport,
) -> anyhow::Result<i32> {
let composer = which_composer();
let stops = args.no_fallback || args.check_scope || composer.is_none();
vivacity_core::io::drop_output();
if !stops {
vivacity_core::io::drop_held();
}
let reason_line = |line: &str| {
if stops {
vivacity_core::say_always!("{line}");
} else {
vivacity_core::say!("{line}");
}
};
reason_line("vivacity: this lock is outside what vivacity handles natively:");
for issue in &scope.issues {
reason_line(&format!(" - {issue}"));
}
if args.no_fallback || args.check_scope {
vivacity_core::say_always!(
"--no-fallback given: stopping here (no partial vendor/ was written)."
);
return Ok(3);
}
let Some(composer) = composer else {
vivacity_core::say_always!(
"composer not found for the fallback — install Composer or remove the unsupported items."
);
return Ok(3);
};
let forwarded = match &args.fallback_line {
Some(line) => line.clone(),
None => forwarded_arguments(&command_line(), "install"),
};
let code =
hand_over(&composer, &forwarded, args.offline, None).context("cannot run composer")?;
if code == 0 {
if let Some(plan) = args
.post_update
.as_ref()
.and_then(|u| u.flex_plan.as_deref())
{
plan.print_and_apply()?;
}
}
Ok(code)
}
pub(crate) fn after_update_line(args: &UpdateArgs) -> Vec<std::ffi::OsString> {
let mut line: Vec<std::ffi::OsString> = vec!["install".into()];
for (on, flag) in [
(args.dry_run, "--dry-run"),
(args.prefer_source, "--prefer-source"),
(args.prefer_dist, "--prefer-dist"),
(args.no_dev, "--no-dev"),
(args.no_progress, "--no-progress"),
(args.no_autoloader, "--no-autoloader"),
(args.optimize_autoloader, "--optimize-autoloader"),
(args.classmap_authoritative, "--classmap-authoritative"),
(args.apcu_autoloader, "--apcu-autoloader"),
(args.ignore_platform_reqs, "--ignore-platform-reqs"),
(args.no_plugins, "--no-plugins"),
(args.no_blocking, "--no-blocking"),
(args.no_security_blocking, "--no-security-blocking"),
(args.compat.no_interaction, "--no-interaction"),
(args.compat.no_ansi, "--no-ansi"),
] {
if on {
line.push(flag.into());
}
}
let valued = |name: &str, value: &std::ffi::OsStr| {
let mut word = std::ffi::OsString::from(format!("--{name}="));
word.push(value);
word
};
if let Some(how) = &args.prefer_install {
line.push(valued("prefer-install", how.as_ref()));
}
if let Some(prefix) = &args.apcu_autoloader_prefix {
line.push(valued("apcu-autoloader-prefix", prefix.as_ref()));
}
for req in &args.ignore_platform_req {
line.push(valued("ignore-platform-req", req.as_ref()));
}
if let Some(dir) = &args.working_dir {
line.push(valued("working-dir", dir.as_os_str()));
}
line.push("--no-scripts".into());
line
}
pub(crate) fn active_plugin(
project: &std::path::Path,
plugins_enabled: bool,
run_scripts: bool,
) -> Option<String> {
crate::verbose_listeners::issue(
project,
crate::plugin_order::global_composer_dir().as_deref(),
plugins_enabled,
run_scripts,
)
}
pub(crate) fn delegate_for_verbosity(
tokens: &[std::ffi::OsString],
reason: &str,
remedy: &str,
) -> i32 {
let command = command_of(tokens);
let stop = if has_option(tokens, "--no-fallback") {
Some("--no-fallback")
} else if has_option(tokens, "--check-scope") {
Some("--check-scope")
} else {
None
};
if let Some(option) = stop {
vivacity_core::say_always!(
"vivacity: `{command}` with {reason} is outside what vivacity reproduces."
);
vivacity_core::say_always!("{option} given: stopping here (nothing was written).");
return 3;
}
let Some(composer) = which_composer() else {
vivacity_core::say_always!(
"composer not found for the fallback — install Composer or {remedy}."
);
return 3;
};
let forwarded = forwarded_arguments(tokens, &command);
match hand_over(
&composer,
&forwarded,
has_option(tokens, "--offline"),
Some(reason),
) {
Ok(code) => code,
Err(e) => {
vivacity_core::say_always!("Error: cannot run composer: {e}");
1
}
}
}
pub(crate) fn which_composer() -> Option<PathBuf> {
let path = std::env::var_os("PATH")?;
let names: &[&str] = if cfg!(windows) {
&["composer.bat", "composer.cmd", "composer.exe", "composer"]
} else {
&["composer"]
};
std::env::split_paths(&path)
.flat_map(|d| names.iter().map(move |n| d.join(n)))
.find(|c| c.is_file())
}
#[cfg(test)]
mod tests {
#[test]
fn composer_urls_the_constructor_refuses() {
let refused = |u: &str| composer_url_refused(None, u);
assert!(refused("https:///x"));
assert!(refused("https://repo.test:99999"));
assert!(refused("https://repo.test:65536"));
assert!(refused("https://repo.test:000443"));
assert!(refused("https://repo.test:123456"));
assert!(refused("https://repo.test:-1"));
assert!(refused("https://repo.test:+"));
assert!(refused("https://user@/x"));
assert!(refused("http://:80/x"));
assert!(refused("http://[::1]:x"));
assert!(!refused("https://repo.test:80a"));
assert!(!refused("https://repo.test:+80"));
assert!(!refused("https://repo.test: 80"));
assert!(!refused("https://repo.test: 8"));
assert!(!refused("https://repo.test:8a/x"));
assert!(!refused("https://repo.test:0"));
assert!(!refused("https://repo.test:"));
assert!(!refused("http://[::1"));
assert!(!refused("http://[::1]x"));
assert!(!refused("http://[::1]:80"));
assert!(!refused("http://[::1]"));
assert!(!refused("http://[::1]:x:80"));
assert!(refused("http://[::1]:80:x"));
assert!(!refused("https://repo.test:8443/"));
assert!(!refused("https://repo.test"));
assert!(!refused("https://[::1]:8080/x"));
assert!(!refused("file:///tmp/x"));
assert!(!refused("repo.test/x"));
assert!(!refused("https?://repo.test"));
}
#[test]
fn user_filters_the_constructor_refuses() {
use serde_json::json;
assert!(!user_filter_refused(&json!(false)));
assert!(!user_filter_refused(&json!(null)));
assert!(!user_filter_refused(&json!([])));
assert!(!user_filter_refused(&json!({"malware": false, "-0": true})));
assert!(user_filter_refused(&json!({"0": false})));
assert!(user_filter_refused(&json!({"12": true})));
assert!(user_filter_refused(&json!({"x": "no"})));
assert!(user_filter_refused(&json!(["x"])));
assert!(user_filter_refused(&json!("x")));
}
use super::*;
fn forward(tokens: &[&str], command: &str) -> Vec<String> {
let tokens: Vec<std::ffi::OsString> = tokens.iter().map(Into::into).collect();
forwarded_arguments(&tokens, command)
.iter()
.map(|t| t.to_string_lossy().into_owned())
.collect()
}
#[test]
fn vivacity_options_are_dropped_and_no_scripts_added_last() {
for flag in ["--no-fallback", "--check-scope", "--offline"] {
assert_eq!(
forward(&["install", flag, "-o", "--working-dir", "p"], "install"),
["install", "-o", "--working-dir", "p", "--no-scripts"],
"{flag}"
);
}
assert_eq!(
forward(
&[
"install",
"--dry-run",
"--prefer-install=source",
"-q",
"--working-dir=p"
],
"install"
),
[
"install",
"--dry-run",
"--prefer-install=source",
"-q",
"--working-dir=p",
"--no-scripts"
]
);
}
#[test]
fn run_scripts_hands_the_scripts_to_composer() {
assert_eq!(
forward(&["install", "--run-scripts"], "install"),
["install"]
);
assert_eq!(
forward(&["install", "--run-scripts", "--no-scripts"], "install"),
["install", "--no-scripts"]
);
assert_eq!(
forward(&["update", "--no-scripts", "-n"], "update"),
["update", "--no-scripts", "-n"]
);
}
#[test]
fn nothing_after_double_dash_is_touched() {
assert_eq!(
forward(
&["require", "--offline", "--", "--no-fallback", "--offline"],
"require"
),
[
"require",
"--no-scripts",
"--",
"--no-fallback",
"--offline"
]
);
assert_eq!(
forward(
&["require", "--", "--run-scripts", "--no-scripts"],
"require"
),
[
"require",
"--no-scripts",
"--",
"--run-scripts",
"--no-scripts"
]
);
}
#[test]
fn no_autoloader_is_dropped_only_where_composer_lacks_it() {
for command in ["require", "r", "remove", "rm"] {
assert_eq!(
forward(&[command, "a/b", "--no-autoloader"], command),
[command, "a/b", "--no-scripts"],
"{command}"
);
}
for command in ["install", "update"] {
assert_eq!(
forward(&[command, "--no-autoloader"], command),
[command, "--no-autoloader", "--no-scripts"],
"{command}"
);
}
}
#[test]
fn the_command_is_the_first_word_and_options_stop_at_double_dash() {
let tokens: Vec<std::ffi::OsString> = ["rm", "a/b", "--", "--offline"]
.iter()
.map(Into::into)
.collect();
assert_eq!(command_of(&tokens), "rm");
assert!(!has_option(&tokens, "--offline"));
assert!(has_option(&tokens[..2], "a/b"));
}
fn update_args(argv: &[&str]) -> UpdateArgs {
let argv = std::iter::once("vivacity").chain(argv.iter().copied());
match Cli::try_parse_from(argv).expect("parses") {
Cli::Update(args) => args,
other => panic!("not an update: {other:?}"),
}
}
fn line(args: &UpdateArgs) -> Vec<String> {
after_update_line(args)
.iter()
.map(|t| t.to_string_lossy().into_owned())
.collect()
}
#[test]
fn the_install_phase_line_carries_what_the_install_reads() {
assert_eq!(line(&update_args(&["update"])), ["install", "--no-scripts"]);
let mut args = update_args(&["update"]);
args.prefer_source = true;
args.prefer_install = Some("auto".to_owned());
assert_eq!(
line(&args),
[
"install",
"--prefer-source",
"--prefer-install=auto",
"--no-scripts"
]
);
let args = update_args(&[
"update",
"a/b",
"--with",
"c/d:1.0",
"-W",
"--prefer-stable",
"--no-audit",
"--offline",
"--no-fallback",
"-v",
"--working-dir",
"proj",
"--no-dev",
"-oa",
"--apcu-autoloader",
"--apcu-autoloader-prefix=pfx",
"--no-progress",
"--no-autoloader",
"--ignore-platform-reqs",
"--ignore-platform-req=ext-a",
"--ignore-platform-req",
"ext-b",
"--no-plugins",
"-n",
"--no-ansi",
"--no-blocking",
"--no-security-blocking",
"--dry-run",
]);
assert_eq!(
line(&args),
[
"install",
"--dry-run",
"--no-dev",
"--no-progress",
"--no-autoloader",
"--optimize-autoloader",
"--classmap-authoritative",
"--apcu-autoloader",
"--ignore-platform-reqs",
"--no-plugins",
"--no-blocking",
"--no-security-blocking",
"--no-interaction",
"--no-ansi",
"--apcu-autoloader-prefix=pfx",
"--ignore-platform-req=ext-a",
"--ignore-platform-req=ext-b",
"--working-dir=proj",
"--no-scripts",
]
);
}
}