use std::collections::{BTreeMap, HashMap};
use std::path::{Component, Path, PathBuf};
use composer_installers::InstallerPaths;
use composer_manifest::lockfile::LockPackage;
use serde::{Deserialize, Serialize};
use serde_json::Value;
const RECORD_VERSION: u32 = 1;
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub(crate) struct InstallRecord {
version: u32,
packages: BTreeMap<String, String>,
}
impl InstallRecord {
pub(crate) fn for_packages(
packages: &[&LockPackage],
installer_paths: &InstallerPaths,
) -> Self {
let packages = packages
.iter()
.filter(|p| !p.is_metapackage())
.map(|p| {
let rel = composer_installers::install_path(
&p.name,
p.package_type.as_deref(),
installer_paths,
);
(p.name.clone(), rel)
})
.collect();
Self {
version: RECORD_VERSION,
packages,
}
}
pub(crate) fn read(project_root: &Path) -> Option<Self> {
let bytes = std::fs::read(record_path(project_root)).ok()?;
let record: Self = serde_json::from_slice(&bytes).ok()?;
(record.version == RECORD_VERSION).then_some(record)
}
pub(crate) fn write(&self, project_root: &Path) -> std::io::Result<()> {
let path = record_path(project_root);
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("json.tmp");
let body = serde_json::to_vec_pretty(self).map_err(std::io::Error::other)?;
std::fs::write(&tmp, body)?;
std::fs::rename(&tmp, &path)
}
}
pub(crate) fn record_path(project_root: &Path) -> PathBuf {
project_root.join("vendor/bougie/state/installed-packages.json")
}
fn installed_json_paths(project_root: &Path) -> HashMap<String, Option<String>> {
let Some(packages) = std::fs::read(project_root.join("vendor/composer/installed.json"))
.ok()
.and_then(|b| serde_json::from_slice::<Value>(&b).ok())
.and_then(|v| v.get("packages")?.as_array().cloned())
else {
return HashMap::new();
};
packages
.iter()
.filter_map(|p| {
let name = p.get("name")?.as_str()?;
if name.is_empty() {
return None;
}
let path = p
.get("install-path")
.and_then(Value::as_str)
.and_then(|ip| normalize_relative(&format!("vendor/composer/{ip}")));
Some((name.to_string(), path))
})
.collect()
}
fn normalize_relative(path: &str) -> Option<String> {
let mut out: Vec<&str> = Vec::new();
for c in Path::new(path).components() {
match c {
Component::Normal(s) => out.push(s.to_str()?),
Component::CurDir => {}
Component::ParentDir => {
out.pop()?;
}
Component::RootDir | Component::Prefix(_) => return None,
}
}
Some(out.join("/"))
}
const PROTECTED: &[&str] = &[
"",
"vendor",
"vendor/composer",
"vendor/bin",
"vendor/bougie",
];
fn is_same_or_ancestor(a: &str, b: &str) -> bool {
a == b || a.is_empty() || b.strip_prefix(a).is_some_and(|rest| rest.starts_with('/'))
}
pub(crate) fn remove_stale_packages(project_root: &Path, wanted: &InstallRecord) -> u32 {
let previous = previous_install(project_root);
let wanted_paths: Vec<&str> = wanted.packages.values().map(String::as_str).collect();
let mut removed: u32 = 0;
for (name, rel) in &previous {
if wanted.packages.contains_key(name) || PROTECTED.contains(&rel.as_str()) {
continue;
}
if wanted_paths
.iter()
.any(|w| is_same_or_ancestor(rel, w) || is_same_or_ancestor(w, rel))
{
continue;
}
if remove_package_dir(project_root, rel) {
removed = removed.saturating_add(1);
}
}
removed
}
fn previous_install(project_root: &Path) -> BTreeMap<String, String> {
let mut previous: BTreeMap<String, String> = BTreeMap::new();
if let Some(record) = InstallRecord::read(project_root) {
for (name, rel) in record.packages {
if let Some(rel) = normalize_relative(&rel) {
previous.insert(name, rel);
}
}
}
for (name, rel) in installed_json_paths(project_root) {
let rel = rel.or_else(|| normalize_relative(&format!("vendor/{name}")));
if let Some(rel) = rel {
previous.entry(name).or_insert(rel);
}
}
previous
}
fn remove_package_dir(project_root: &Path, rel: &str) -> bool {
let dir = project_root.join(rel);
let Ok(meta) = std::fs::symlink_metadata(&dir) else {
return false;
};
let ok = if meta.file_type().is_symlink() {
std::fs::remove_file(&dir)
.or_else(|_| std::fs::remove_dir(&dir))
.is_ok()
} else if meta.is_dir() {
std::fs::remove_dir_all(&dir).is_ok()
} else {
false
};
if ok
&& let Some(parent) = dir.parent()
&& parent != project_root.join("vendor")
&& parent.starts_with(project_root.join("vendor"))
{
let _ = std::fs::remove_dir(parent);
}
ok
}
#[cfg(test)]
mod tests;