pub mod bun;
pub mod cargo_adapter;
pub mod go;
pub mod gradle;
pub mod maven;
pub mod npm;
pub mod pnpm;
pub mod poetry;
pub mod uv;
pub mod venv;
pub mod yarn;
use std::collections::HashMap;
use std::fmt;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, OnceLock};
use anyhow::{Context as _, Result};
use walkdir::WalkDir;
#[derive(Debug, Clone)]
pub struct BloatDir {
pub name: String,
pub path: PathBuf,
pub size_bytes: u64,
pub shared_bytes: u64,
}
impl fmt::Display for BloatDir {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{} ({})", self.name, self.path.display())
}
}
#[derive(Debug, Clone)]
pub struct DriftReport {
pub directory: String,
pub unrecorded: Vec<String>,
pub record_command: &'static str,
}
pub trait PackageManager: Send + Sync {
fn name(&self) -> &'static str;
fn detect(&self, project_path: &Path) -> bool;
fn bloat_dirs(&self, project_path: &Path) -> Vec<BloatDir>;
fn enforce_lockfile(&self, project_path: &Path, policy: EnforcePolicy) -> Result<()>;
fn restore(&self, project_path: &Path, timeout: std::time::Duration) -> Result<()>;
fn restore_named(
&self,
project_path: &Path,
dir_name: &str,
timeout: std::time::Duration,
) -> Result<()> {
let _ = dir_name;
self.restore(project_path, timeout)
}
fn lockfiles(&self) -> &'static [&'static str] {
&[]
}
fn drift(&self, project_path: &Path) -> Vec<DriftReport> {
let _ = project_path;
Vec::new()
}
fn opt_in(&self) -> bool {
false
}
}
const JS_MANAGERS: [&str; 4] = ["npm", "pnpm", "yarn", "bun"];
const JS_INSTALL_MARKERS: [(&str, &[&str]); 3] = [
("pnpm", &[".pnpm", ".modules.yaml"]),
("yarn", &[".yarn-state.yml", ".yarn-integrity"]),
("npm", &[".package-lock.json"]),
];
pub fn get_all_adapters() -> Vec<Box<dyn PackageManager>> {
vec![
Box::new(npm::Npm),
Box::new(pnpm::Pnpm),
Box::new(yarn::Yarn),
Box::new(bun::Bun),
Box::new(uv::Uv),
Box::new(poetry::Poetry),
Box::new(venv::Venv),
Box::new(cargo_adapter::Cargo),
Box::new(go::Go),
Box::new(gradle::Gradle),
Box::new(maven::Maven),
]
}
fn opt_in_enabled() -> &'static [String] {
static ENABLED: OnceLock<Vec<String>> = OnceLock::new();
ENABLED.get_or_init(|| {
crate::config::Registry::load()
.map(|r| {
let mut names = Vec::new();
if r.settings.enable_gradle {
names.push("gradle".to_string());
}
if r.settings.enable_maven {
names.push("maven".to_string());
}
names
})
.unwrap_or_default()
})
}
pub fn detect_adapters(project_path: &Path) -> Vec<Box<dyn PackageManager>> {
let mut detected: Vec<Box<dyn PackageManager>> = get_all_adapters()
.into_iter()
.filter(|adapter| !adapter.opt_in() || opt_in_enabled().iter().any(|n| n == adapter.name()))
.filter(|adapter| adapter.detect(project_path))
.collect();
resolve_conflicts(project_path, &mut detected);
detected
}
fn resolve_conflicts(project_path: &Path, detected: &mut Vec<Box<dyn PackageManager>>) {
resolve_js_conflict(project_path, detected);
resolve_python_conflict(project_path, detected);
}
fn resolve_js_conflict(project_path: &Path, detected: &mut Vec<Box<dyn PackageManager>>) {
if detected
.iter()
.filter(|a| JS_MANAGERS.contains(&a.name()))
.count()
< 2
{
return;
}
let winner = declared_package_manager(project_path)
.filter(|name| detected.iter().any(|a| a.name() == name))
.or_else(|| installed_manager(project_path, detected))
.or_else(|| newest_lockfile_owner(project_path, detected));
let Some(winner) = winner else { return };
detected.retain(|a| !JS_MANAGERS.contains(&a.name()) || a.name() == winner);
}
fn resolve_python_conflict(project_path: &Path, detected: &mut Vec<Box<dyn PackageManager>>) {
if detected.iter().any(|a| a.name() == "uv") {
detected.retain(|a| a.name() != "venv");
}
let uv_detected = detected.iter().any(|a| a.name() == "uv");
let poetry_detected = detected.iter().any(|a| a.name() == "poetry");
if uv_detected && poetry_detected {
let loser = if !project_path.join("uv.lock").exists()
&& project_path.join("poetry.lock").exists()
{
"uv"
} else {
"poetry"
};
detected.retain(|a| a.name() != loser);
}
}
fn installed_manager(project_path: &Path, detected: &[Box<dyn PackageManager>]) -> Option<String> {
let node_modules = project_path.join("node_modules");
if !node_modules.is_dir() {
return None;
}
JS_INSTALL_MARKERS
.iter()
.find(|(name, markers)| {
detected.iter().any(|a| a.name() == *name)
&& markers.iter().any(|m| node_modules.join(m).exists())
})
.map(|(name, _)| (*name).to_string())
}
fn declared_package_manager(project_path: &Path) -> Option<String> {
let raw = std::fs::read_to_string(project_path.join("package.json")).ok()?;
let json: serde_json::Value = serde_json::from_str(&raw).ok()?;
let declared = json.get("packageManager")?.as_str()?;
let name = declared.split('@').next().unwrap_or_default();
JS_MANAGERS
.iter()
.find(|m| **m == name)
.map(|m| (*m).to_string())
}
fn newest_lockfile_owner(
project_path: &Path,
detected: &[Box<dyn PackageManager>],
) -> Option<String> {
detected
.iter()
.filter(|a| JS_MANAGERS.contains(&a.name()))
.filter_map(|a| {
let newest = a
.lockfiles()
.iter()
.filter_map(|f| std::fs::metadata(project_path.join(f)).ok()?.modified().ok())
.max()?;
Some((newest, a.name().to_string()))
})
.fold(None::<(std::time::SystemTime, String)>, |best, cur| {
match best {
Some(b) if b.0 >= cur.0 => Some(b),
_ => Some(cur),
}
})
.map(|(_, name)| name)
}
pub fn dir_size(path: &Path) -> u64 {
if !path.exists() {
return 0;
}
WalkDir::new(path)
.follow_links(false)
.into_iter()
.flatten()
.filter_map(|entry| entry.metadata().ok())
.filter(|meta| meta.is_file())
.map(|meta| meta.len())
.sum()
}
#[derive(Debug, Clone, Copy, Default)]
pub struct DirSizeBreakdown {
pub freed_bytes: u64,
pub shared_bytes: u64,
}
pub fn dir_size_with_hardlinks(path: &Path) -> DirSizeBreakdown {
let mut out = DirSizeBreakdown::default();
if !path.exists() {
return out;
}
let mut linked: HashMap<(u64, u64), (u64, u64, u64)> = HashMap::new();
for entry in WalkDir::new(path).follow_links(false).into_iter().flatten() {
let Ok(meta) = entry.metadata() else { continue };
if !meta.is_file() {
continue;
}
match file_link_identity(entry.path(), &meta) {
Some((dev, ino, nlink)) if nlink > 1 => {
linked.entry((dev, ino)).or_insert((meta.len(), nlink, 0)).2 += 1;
}
_ => out.freed_bytes += meta.len(),
}
}
for (bytes, nlink, seen) in linked.into_values() {
if seen >= nlink {
out.freed_bytes += bytes;
} else {
out.shared_bytes += bytes;
}
}
out
}
#[cfg(unix)]
fn file_link_identity(_path: &Path, meta: &std::fs::Metadata) -> Option<(u64, u64, u64)> {
use std::os::unix::fs::MetadataExt as _;
Some((meta.dev(), meta.ino(), meta.nlink()))
}
#[cfg(windows)]
fn file_link_identity(path: &Path, _meta: &std::fs::Metadata) -> Option<(u64, u64, u64)> {
use std::os::windows::fs::OpenOptionsExt as _;
use std::os::windows::io::AsRawHandle as _;
use windows_sys::Win32::Storage::FileSystem::{
BY_HANDLE_FILE_INFORMATION, GetFileInformationByHandle,
};
let file = std::fs::OpenOptions::new().access_mode(0).open(path).ok()?;
let mut info: BY_HANDLE_FILE_INFORMATION = unsafe { std::mem::zeroed() };
if unsafe { GetFileInformationByHandle(file.as_raw_handle(), &mut info) } == 0 {
return None;
}
Some((
u64::from(info.dwVolumeSerialNumber),
(u64::from(info.nFileIndexHigh) << 32) | u64::from(info.nFileIndexLow),
u64::from(info.nNumberOfLinks),
))
}
#[cfg(not(any(unix, windows)))]
fn file_link_identity(_path: &Path, _meta: &std::fs::Metadata) -> Option<(u64, u64, u64)> {
None
}
pub fn resolve_program(program: &str) -> String {
#[cfg(windows)]
{
if Path::new(program).components().count() > 1 {
return program.to_string();
}
let Some(path_var) = std::env::var_os("PATH") else {
return program.to_string();
};
for dir in std::env::split_paths(&path_var) {
for ext in ["exe", "cmd", "bat"] {
let candidate = dir.join(format!("{program}.{ext}"));
if candidate.is_file() {
return candidate.to_string_lossy().into_owned();
}
}
}
}
program.to_string()
}
pub fn binary_available(program: &str) -> bool {
static CACHE: OnceLock<Mutex<HashMap<String, bool>>> = OnceLock::new();
let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));
let mut guard = match cache.lock() {
Ok(g) => g,
Err(_) => return probe_binary(program),
};
if let Some(known) = guard.get(program) {
return *known;
}
let available = probe_binary(program);
guard.insert(program.to_string(), available);
available
}
fn probe_binary(program: &str) -> bool {
crate::spawn::command(resolve_program(program))
.arg("--version")
.stdin(std::process::Stdio::null())
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
struct CommandOutput {
status: std::process::ExitStatus,
stdout: String,
stderr: String,
}
fn spawn_capture(
program: &str,
args: &[&str],
cwd: &Path,
timeout: std::time::Duration,
) -> Result<CommandOutput> {
use std::io::Read;
use std::process::Stdio;
use std::thread;
use std::time::Instant;
let resolved = resolve_program(program);
let mut child = crate::spawn::command(&resolved)
.args(args)
.current_dir(cwd)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.with_context(|| format!("Failed to execute: {program} {}", args.join(" ")))?;
let mut stdout_pipe = child.stdout.take();
let mut stderr_pipe = child.stderr.take();
let stdout_reader = thread::spawn(move || {
let mut buf = Vec::new();
if let Some(pipe) = stdout_pipe.as_mut() {
let _ = pipe.read_to_end(&mut buf);
}
buf
});
let stderr_reader = thread::spawn(move || {
let mut buf = Vec::new();
if let Some(pipe) = stderr_pipe.as_mut() {
let _ = pipe.read_to_end(&mut buf);
}
buf
});
let start = Instant::now();
let status = loop {
match child.try_wait()? {
Some(status) => break status,
None => {
if start.elapsed() >= timeout {
let _ = child.kill();
let _ = child.wait();
anyhow::bail!(
"Command timed out after {}s: {} {}\n\
To increase the timeout, run: `devp config set command_timeout_secs <seconds>`",
timeout.as_secs(),
program,
args.join(" ")
);
}
thread::sleep(std::time::Duration::from_millis(100));
}
}
};
let stderr = stderr_reader
.join()
.map(|b| String::from_utf8_lossy(&b).into_owned())
.unwrap_or_default();
let stdout = stdout_reader
.join()
.map(|b| String::from_utf8_lossy(&b).into_owned())
.unwrap_or_default();
Ok(CommandOutput {
status,
stdout,
stderr,
})
}
pub fn run_command_with_timeout(
program: &str,
args: &[&str],
cwd: &Path,
timeout: std::time::Duration,
) -> Result<()> {
let out = spawn_capture(program, args, cwd, timeout)?;
if out.status.success() {
Ok(())
} else {
anyhow::bail!(
"{} {} failed (exit code {:?}):\n{}",
program,
args.join(" "),
out.status.code(),
out.stderr.trim()
)
}
}
pub fn capture_command_with_timeout(
program: &str,
args: &[&str],
cwd: &Path,
timeout: std::time::Duration,
) -> Result<String> {
let out = spawn_capture(program, args, cwd, timeout)?;
if out.status.success() {
Ok(out.stdout)
} else {
anyhow::bail!(
"{} {} failed (exit code {:?}):\n{}",
program,
args.join(" "),
out.status.code(),
out.stderr.trim()
)
}
}
pub fn try_run_command(program: &str, args: &[&str], cwd: &Path) -> bool {
crate::spawn::command(resolve_program(program))
.args(args)
.current_dir(cwd)
.stdin(std::process::Stdio::null())
.output()
.map(|o| o.status.success())
.unwrap_or(false)
}
const MANIFEST_MTIME_TOLERANCE: std::time::Duration = std::time::Duration::from_secs(60);
fn refuse_if_manifest_newer(lockfile: &Path, program: &str, cwd: &Path) -> Result<()> {
let manifest_name = match lockfile.file_name().and_then(|n| n.to_str()) {
Some("Cargo.lock") => "Cargo.toml",
Some("package-lock.json")
| Some("yarn.lock")
| Some("pnpm-lock.yaml")
| Some("bun.lockb")
| Some("bun.lock") => "package.json",
Some("uv.lock") | Some("poetry.lock") | Some("pdm.lock") => "pyproject.toml",
Some("go.sum") => "go.mod",
Some("composer.lock") => "composer.json",
_ => return Ok(()),
};
let manifest = cwd.join(manifest_name);
let (Ok(manifest_meta), Ok(lock_meta)) =
(std::fs::metadata(&manifest), std::fs::metadata(lockfile))
else {
return Ok(());
};
if let (Ok(manifest_mtime), Ok(lock_mtime)) = (manifest_meta.modified(), lock_meta.modified())
&& manifest_mtime > lock_mtime + MANIFEST_MTIME_TOLERANCE
{
anyhow::bail!(
"`{program}` is not available, and `{manifest_name}` has been edited more \
recently than `{}` — the lockfile may no longer record the current \
dependencies, and without `{program}` that cannot be verified. Install \
{program} and run its lockfile sync, then prune again.",
lockfile.display()
);
}
Ok(())
}
pub fn lock_sync_or_verify_with_timeout(
lockfile: &Path,
program: &str,
sync_args: &[&str],
cwd: &Path,
timeout: std::time::Duration,
) -> Result<()> {
let lockfile_exists = lockfile.exists();
if !binary_available(program) {
if lockfile_exists {
refuse_if_manifest_newer(lockfile, program, cwd)?;
return Ok(());
} else {
anyhow::bail!(
"`{program}` is not available and no lockfile was found at `{}`. \
Cannot safely delete dependencies — install {program} first, \
or commit a lockfile.",
lockfile.display()
);
}
}
run_command_with_timeout(program, sync_args, cwd, timeout)
}
#[derive(Debug, Clone, Copy)]
pub struct EnforcePolicy {
pub allow_rewrite: bool,
pub timeout: std::time::Duration,
}
impl Default for EnforcePolicy {
fn default() -> Self {
Self {
allow_rewrite: crate::constants::DEFAULT_ALLOW_MANIFEST_REWRITE,
timeout: std::time::Duration::from_secs(crate::constants::DEFAULT_COMMAND_TIMEOUT_SECS),
}
}
}
impl EnforcePolicy {
pub fn from_settings(settings: &crate::config::Settings) -> Self {
Self {
allow_rewrite: settings.allow_manifest_rewrite,
timeout: std::time::Duration::from_secs(settings.command_timeout_secs),
}
}
}
pub fn enforce_two_tier(
lockfile: &Path,
program: &str,
verify_args: &[&str],
write_args: &[&str],
cwd: &Path,
policy: EnforcePolicy,
) -> Result<()> {
if policy.allow_rewrite {
return lock_sync_or_verify_with_timeout(
lockfile,
program,
write_args,
cwd,
policy.timeout,
);
}
lock_verify_or_generate(
lockfile,
program,
verify_args,
write_args,
cwd,
policy.timeout,
)
}
pub fn lock_verify_or_generate(
lockfile: &Path,
program: &str,
verify_args: &[&str],
generate_args: &[&str],
cwd: &Path,
timeout: std::time::Duration,
) -> Result<()> {
let lockfile_exists = lockfile.exists();
if !binary_available(program) {
if lockfile_exists {
refuse_if_manifest_newer(lockfile, program, cwd)?;
return Ok(());
}
anyhow::bail!(
"`{program}` is not available and no lockfile was found at `{}`. \
Cannot safely delete dependencies — install {program} first, \
or commit a lockfile.",
lockfile.display()
);
}
if lockfile_exists {
run_command_with_timeout(program, verify_args, cwd, timeout)
} else {
run_command_with_timeout(program, generate_args, cwd, timeout)
}
}
pub fn lock_sync_or_verify(
lockfile: &Path,
program: &str,
sync_args: &[&str],
cwd: &Path,
) -> Result<()> {
lock_sync_or_verify_with_timeout(
lockfile,
program,
sync_args,
cwd,
std::time::Duration::from_secs(crate::constants::DEFAULT_COMMAND_TIMEOUT_SECS),
)
}
#[derive(Debug, Clone)]
pub struct BinaryCheckStatus {
pub name: String,
pub available: bool,
pub version: Option<String>,
}
pub fn scan_required_binaries(adapter_names: &[String]) -> Vec<BinaryCheckStatus> {
let mut unique: Vec<String> = adapter_names
.iter()
.filter(|&n| n != "-" && n != "venv" && n != "gradle" && n != "maven")
.cloned()
.collect();
unique.sort();
unique.dedup();
unique
.into_iter()
.map(|name| {
let output = crate::spawn::command(resolve_program(&name))
.arg("--version")
.stdin(std::process::Stdio::null())
.output();
match output {
Ok(out) if out.status.success() => {
let ver = String::from_utf8_lossy(&out.stdout).trim().to_string();
let first_line = ver.lines().next().unwrap_or(&ver).to_string();
BinaryCheckStatus {
name,
available: true,
version: if first_line.is_empty() {
None
} else {
Some(first_line)
},
}
}
_ => BinaryCheckStatus {
name,
available: false,
version: None,
},
}
})
.collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
use tempfile::TempDir;
#[test]
fn test_bloat_dir_display() {
let bd = BloatDir {
name: "node_modules".to_string(),
path: PathBuf::from("/test/node_modules"),
size_bytes: 1024,
shared_bytes: 0,
};
assert!(bd.to_string().contains("node_modules"));
}
#[test]
fn test_hardlink_size_counts_a_plain_file_in_full() {
let tmp = TempDir::new().unwrap();
let tree = tmp.path().join("tree");
fs::create_dir(&tree).unwrap();
fs::write(tree.join("copied.txt"), "12345").unwrap();
let size = dir_size_with_hardlinks(&tree);
assert_eq!(size.freed_bytes, 5);
assert_eq!(size.shared_bytes, 0);
}
#[test]
fn test_hardlink_size_excludes_a_file_the_store_keeps() {
let tmp = TempDir::new().unwrap();
let store = tmp.path().join("store");
let tree = tmp.path().join("tree");
fs::create_dir(&store).unwrap();
fs::create_dir(&tree).unwrap();
fs::write(store.join("pkg.js"), "0123456789").unwrap();
fs::hard_link(store.join("pkg.js"), tree.join("pkg.js")).unwrap();
let size = dir_size_with_hardlinks(&tree);
assert_eq!(size.freed_bytes, 0);
assert_eq!(size.shared_bytes, 10);
}
#[test]
fn test_hardlink_size_counts_an_internal_pair_once() {
let tmp = TempDir::new().unwrap();
let tree = tmp.path().join("tree");
fs::create_dir(&tree).unwrap();
fs::write(tree.join("a.js"), "abcdefg").unwrap();
fs::hard_link(tree.join("a.js"), tree.join("b.js")).unwrap();
let size = dir_size_with_hardlinks(&tree);
assert_eq!(size.freed_bytes, 7);
assert_eq!(size.shared_bytes, 0);
}
#[test]
fn test_dir_size_empty() {
let tmp = TempDir::new().unwrap();
assert_eq!(dir_size(tmp.path()), 0);
}
#[test]
fn test_dir_size_with_files() {
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join("file1.txt"), "hello").unwrap();
fs::write(tmp.path().join("file2.txt"), "world!").unwrap();
assert_eq!(dir_size(tmp.path()), 11); }
#[test]
fn test_dir_size_nonexistent() {
assert_eq!(dir_size(Path::new("/nonexistent/path")), 0);
}
#[test]
fn test_get_all_adapters_not_empty() {
let adapters = get_all_adapters();
assert!(adapters.len() >= 6);
}
#[test]
fn test_detect_adapters_npm() {
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join("package.json"), "{}").unwrap();
fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
let adapters = detect_adapters(tmp.path());
let names: Vec<&str> = adapters.iter().map(|a| a.name()).collect();
assert!(names.contains(&"npm"));
}
#[test]
fn test_detect_adapters_empty_dir() {
let tmp = TempDir::new().unwrap();
let adapters = detect_adapters(tmp.path());
assert!(adapters.is_empty());
}
fn detected_names(dir: &Path) -> Vec<&'static str> {
let mut names: Vec<&'static str> = detect_adapters(dir).iter().map(|a| a.name()).collect();
names.sort_unstable();
names
}
#[test]
fn test_detect_adapters_multiple_ecosystems_coexist() {
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join("package.json"), "{}").unwrap();
fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
fs::write(tmp.path().join("uv.lock"), "").unwrap();
fs::write(tmp.path().join("Cargo.toml"), "[package]").unwrap();
fs::write(tmp.path().join("go.mod"), "module x").unwrap();
assert_eq!(detected_names(tmp.path()), vec!["cargo", "go", "npm", "uv"]);
}
#[test]
fn test_js_conflict_resolved_by_package_manager_field() {
let tmp = TempDir::new().unwrap();
fs::write(
tmp.path().join("package.json"),
r#"{"packageManager":"yarn@4.1.0"}"#,
)
.unwrap();
fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
fs::write(tmp.path().join("pnpm-lock.yaml"), "").unwrap();
fs::write(tmp.path().join("yarn.lock"), "").unwrap();
assert_eq!(detected_names(tmp.path()), vec!["yarn"]);
}
#[test]
fn test_js_conflict_resolved_by_what_installed_node_modules() {
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join("package.json"), "{}").unwrap();
fs::write(tmp.path().join("pnpm-lock.yaml"), "").unwrap();
fs::create_dir_all(tmp.path().join("node_modules/.pnpm")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
assert_eq!(detected_names(tmp.path()), vec!["pnpm"]);
}
#[test]
fn test_js_conflict_prefers_yarn_state_over_leftover_npm_bookkeeping() {
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join("package.json"), "{}").unwrap();
fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
fs::write(tmp.path().join("yarn.lock"), "").unwrap();
let nm = tmp.path().join("node_modules");
fs::create_dir_all(&nm).unwrap();
fs::write(nm.join(".package-lock.json"), "{}").unwrap();
fs::write(nm.join(".yarn-state.yml"), "").unwrap();
assert_eq!(detected_names(tmp.path()), vec!["yarn"]);
}
#[test]
fn test_declared_package_manager_outranks_what_is_installed() {
let tmp = TempDir::new().unwrap();
fs::write(
tmp.path().join("package.json"),
r#"{"packageManager":"pnpm@9.1.0"}"#,
)
.unwrap();
fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
fs::write(tmp.path().join("pnpm-lock.yaml"), "").unwrap();
let nm = tmp.path().join("node_modules");
fs::create_dir_all(&nm).unwrap();
fs::write(nm.join(".package-lock.json"), "{}").unwrap();
assert_eq!(detected_names(tmp.path()), vec!["pnpm"]);
}
#[test]
fn test_uv_takes_precedence_over_plain_venv() {
let tmp = TempDir::new().unwrap();
fs::write(
tmp.path().join("pyproject.toml"),
"[project]\nname = \"x\"\n\n[tool.uv]\n",
)
.unwrap();
fs::write(tmp.path().join("requirements.txt"), "requests\n").unwrap();
let venv = tmp.path().join(".venv");
fs::create_dir_all(&venv).unwrap();
fs::write(venv.join("pyvenv.cfg"), "home = /usr\n").unwrap();
assert_eq!(detected_names(tmp.path()), vec!["uv"]);
}
#[test]
fn test_plain_venv_handles_projects_uv_does_not_claim() {
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join("requirements.txt"), "requests\n").unwrap();
let venv = tmp.path().join("venv");
fs::create_dir_all(&venv).unwrap();
fs::write(venv.join("pyvenv.cfg"), "home = /usr\n").unwrap();
assert_eq!(detected_names(tmp.path()), vec!["venv"]);
}
#[test]
fn test_js_conflict_falls_back_to_newest_lockfile() {
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join("package.json"), "{}").unwrap();
fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(tmp.path().join("pnpm-lock.yaml"), "").unwrap();
assert_eq!(detected_names(tmp.path()), vec!["pnpm"]);
}
#[test]
fn test_js_conflict_ignores_an_unrecognised_package_manager_field() {
let tmp = TempDir::new().unwrap();
fs::write(
tmp.path().join("package.json"),
r#"{"packageManager":"deno@2.0.0"}"#,
)
.unwrap();
fs::write(tmp.path().join("package-lock.json"), "{}").unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
fs::write(tmp.path().join("yarn.lock"), "").unwrap();
assert_eq!(detected_names(tmp.path()), vec!["yarn"]);
}
#[test]
fn test_js_conflict_does_not_disturb_a_single_manager() {
let tmp = TempDir::new().unwrap();
fs::write(tmp.path().join("package.json"), "{}").unwrap();
fs::write(tmp.path().join("pnpm-lock.yaml"), "").unwrap();
assert_eq!(detected_names(tmp.path()), vec!["pnpm"]);
}
#[test]
fn test_js_adapters_declare_their_lockfiles() {
for adapter in get_all_adapters() {
if JS_MANAGERS.contains(&adapter.name()) {
assert!(
!adapter.lockfiles().is_empty(),
"{} shares node_modules and must declare its lockfiles for \
conflict resolution",
adapter.name()
);
}
}
}
#[test]
fn test_adapter_names_unique() {
let adapters = get_all_adapters();
let names: Vec<&str> = adapters.iter().map(|a| a.name()).collect();
let mut unique = names.clone();
unique.sort();
unique.dedup();
assert_eq!(names.len(), unique.len(), "Adapter names must be unique");
}
}