use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
use std::{fmt, fs};
use anyhow::{Result, bail};
use serde_json::Value;
mod parse;
use parse::{parse_bun, parse_cargo, parse_npm, parse_uv};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
Parsed(Format),
Unchanged,
Unreadable,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Format {
Cargo,
Bun,
Npm,
Uv,
}
#[must_use]
pub fn kind(path: &Path) -> Option<Kind> {
match path.file_name()?.to_str()? {
"Cargo.lock" => Some(Kind::Parsed(Format::Cargo)),
"bun.lock" => Some(Kind::Parsed(Format::Bun)),
"package-lock.json" | "npm-shrinkwrap.json" => Some(Kind::Parsed(Format::Npm)),
"uv.lock" => Some(Kind::Parsed(Format::Uv)),
"pnpm-lock.yaml" | "poetry.lock" | "pdm.lock" => Some(Kind::Unchanged),
"yarn.lock" | "bun.lockb" => Some(Kind::Unreadable),
_ => None,
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
pub label: String,
pub name: String,
pub version: Option<String>,
pub member: bool,
rest: String,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Lockfile {
header: String,
pub(super) entries: BTreeMap<String, Entry>,
}
impl Entry {
#[must_use]
pub fn follows_version(&self, format: Format) -> bool {
!(format == Format::Bun && self.member && self.label == "." && self.version.is_none())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Member {
manifest: PathBuf,
names: BTreeSet<String>,
}
impl Member {
#[must_use]
pub fn new(manifest: impl Into<PathBuf>, names: BTreeSet<String>) -> Self {
Self {
manifest: manifest.into(),
names,
}
}
#[must_use]
pub fn manifest(&self) -> &Path {
&self.manifest
}
fn label(&self, lock_dir: &Path) -> Option<String> {
let dir = self.manifest.parent()?;
let label = dir.strip_prefix(lock_dir).ok()?;
Some(if label.as_os_str().is_empty() {
".".to_owned()
} else {
label.display().to_string()
})
}
#[must_use]
pub fn records(&self, format: Format, lock_dir: &Path, name: &str, label: &str) -> bool {
match format {
Format::Cargo => self.names.contains(name),
Format::Uv => {
let name = pep503(name);
self.names.iter().any(|known| pep503(known) == name)
}
Format::Bun | Format::Npm => self.label(lock_dir).as_deref() == Some(label),
}
}
}
pub(super) fn pep503(name: &str) -> String {
let mut normalized = String::with_capacity(name.len());
for character in name.chars() {
if matches!(character, '-' | '_' | '.') {
if !normalized.ends_with('-') {
normalized.push('-');
}
} else {
normalized.extend(character.to_lowercase());
}
}
normalized
}
#[must_use]
pub fn declared_name(manifest: &Path) -> Option<String> {
let text = fs::read_to_string(manifest).ok()?;
match manifest.file_name()?.to_str()? {
"Cargo.toml" => toml_name(&text, "package"),
"pyproject.toml" => toml_name(&text, "project"),
"package.json" => serde_json::from_str::<Value>(&text)
.ok()?
.get("name")?
.as_str()
.map(str::to_owned),
_ => None,
}
}
fn toml_name(text: &str, table: &str) -> Option<String> {
let document = text.parse::<toml_edit::DocumentMut>().ok()?;
document
.get(table)?
.get("name")?
.as_str()
.map(str::to_owned)
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Change {
Header,
Added(String),
Removed(String),
Changed(String),
Member {
label: String,
name: String,
from: Option<String>,
to: Option<String>,
},
}
impl Change {
#[must_use]
pub fn is_member_version(&self) -> bool {
matches!(
self,
Self::Member {
label: _,
name: _,
from: _,
to: _
}
)
}
}
impl fmt::Display for Change {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Header => write!(f, "its header changed"),
Self::Added(label) => write!(f, "`{label}` was added"),
Self::Removed(label) => write!(f, "`{label}` was removed"),
Self::Changed(label) => write!(f, "`{label}` changed"),
Self::Member {
label,
from,
to,
name: _,
} => write!(
f,
"`{label}` moved from {} to {}",
from.as_deref().unwrap_or("no version"),
to.as_deref().unwrap_or("no version")
),
}
}
}
impl Lockfile {
pub fn parse(format: Format, text: &str) -> Result<Self> {
match format {
Format::Cargo => parse_cargo(text),
Format::Bun => parse_bun(text),
Format::Npm => parse_npm(text),
Format::Uv => parse_uv(text),
}
}
pub fn entries(&self) -> impl Iterator<Item = &Entry> {
self.entries.values()
}
pub fn members(&self) -> impl Iterator<Item = &Entry> {
self.entries().filter(|entry| entry.member)
}
#[must_use]
pub fn is_idle_for(&self, format: Format, lock_dir: &Path, member: &Member) -> bool {
let mut recorded = self
.members()
.filter(|entry| member.records(format, lock_dir, &entry.name, &entry.label))
.peekable();
let found = recorded.peek().is_some();
found && recorded.all(|entry| !entry.follows_version(format))
}
#[must_use]
pub fn compare(&self, newer: &Self) -> Vec<Change> {
let mut changes = Vec::new();
if self.header != newer.header {
changes.push(Change::Header);
}
let mut removed = BTreeSet::new();
let mut added = BTreeSet::new();
for (key, old) in &self.entries {
match newer.entries.get(key) {
None => {
removed.insert(old.label.clone());
}
Some(new) if new == old => {}
Some(new)
if new.member && old.member && new.name == old.name && new.rest == old.rest =>
{
changes.push(Change::Member {
label: new.label.clone(),
name: new.name.clone(),
from: old.version.clone(),
to: new.version.clone(),
});
}
Some(new) => changes.push(Change::Changed(new.label.clone())),
}
}
for (key, new) in &newer.entries {
if !self.entries.contains_key(key) {
added.insert(new.label.clone());
}
}
for label in removed.intersection(&added) {
changes.push(Change::Changed(label.clone()));
}
changes.extend(removed.difference(&added).cloned().map(Change::Removed));
changes.extend(added.difference(&removed).cloned().map(Change::Added));
changes
}
fn insert(&mut self, key: String, entry: Entry) -> Result<()> {
let label = entry.label.clone();
if self.entries.insert(key, entry).is_some() {
bail!("`{label}` is locked twice");
}
Ok(())
}
}