use std::fs;
use std::path::{Component, Path, PathBuf};
use anyhow::{Context, Result, bail};
use regex::{NoExpand, Regex, escape};
use toml_edit::{DocumentMut, Formatted, Item, Value};
use crate::config::{Config, PLACEHOLDER, Pin, PinPattern};
const VERSION: &str = r"[0-9]+(?:\.[0-9]+)*(?:-[a-z]+\.[0-9]+)?";
pub fn current_versions(root: &Path, config: &Config) -> Result<Vec<(String, String)>> {
let mut versions = Vec::new();
for spec in &config.packages {
versions.push((spec.name.clone(), spec.current(config, root)?.version));
}
Ok(versions)
}
pub fn write(root: &Path, pins: &[Pin], versions: &[(String, String)]) -> Result<Vec<PathBuf>> {
let mut written = Vec::new();
for pin in pins {
let Some((_, version)) = versions.iter().find(|(name, _)| name == &pin.package) else {
continue;
};
let (path, _, body) = rewritten(root, pin, version)?;
fs::write(&path, body).with_context(|| format!("write pin {}", path.display()))?;
written.push(path);
}
Ok(written)
}
pub fn plan(root: &Path, pins: &[Pin], versions: &[(String, String)]) -> Result<Vec<PathBuf>> {
let mut planned = Vec::new();
for pin in pins {
let Some((_, version)) = versions.iter().find(|(name, _)| name == &pin.package) else {
continue;
};
let (path, _, _) = rewritten(root, pin, version)?;
planned.push(path);
}
Ok(planned)
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Stale {
pub file: PathBuf,
pub problem: String,
}
#[must_use]
pub fn stale(root: &Path, pins: &[Pin], versions: &[(String, String)]) -> Vec<Stale> {
pins.iter()
.filter_map(|pin| {
let (_, version) = versions.iter().find(|(name, _)| name == &pin.package)?;
let problem = match rewritten(root, pin, version) {
Ok((_, raw, body)) if raw == body => return None,
Ok(_) => format!("names a version other than {} {version}", pin.package),
Err(error) => format!("{error:#}"),
};
Some(Stale {
file: pin.file.clone(),
problem,
})
})
.collect()
}
fn rewritten(root: &Path, pin: &Pin, version: &str) -> Result<(PathBuf, String, String)> {
ensure_inside(root, &pin.file)?;
let path = root.join(&pin.file);
let raw = fs::read_to_string(&path).with_context(|| format!("read pin {}", path.display()))?;
let mut body = raw.clone();
if let Some(tool) = &pin.tool {
body = rewrite_tool(&body, tool, version, &path)?;
}
for pattern in &pin.patterns {
body = rewrite_pattern(&body, pattern, version)
.with_context(|| format!("pin {}", path.display()))?;
}
Ok((path, raw, body))
}
pub fn ensure_inside_repo(root: &Path, file: &Path, label: &str) -> Result<()> {
if file.is_absolute()
|| file
.components()
.any(|part| matches!(part, Component::ParentDir))
{
bail!("{label} must stay inside the repo: {}", file.display());
}
let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
let path = root.join(file);
if let Ok(meta) = fs::symlink_metadata(&path)
&& meta.file_type().is_symlink()
{
bail!("{label} must not be a symlink: {}", path.display());
}
let resolved = path.canonicalize().unwrap_or(path);
if !resolved.starts_with(&root) {
bail!("{label} must stay inside the repo: {}", file.display());
}
Ok(())
}
fn ensure_inside(root: &Path, file: &Path) -> Result<()> {
ensure_inside_repo(root, file, "pin file")
}
fn rewrite_tool(body: &str, tool: &str, version: &str, path: &Path) -> Result<String> {
let mut doc: DocumentMut = body
.parse()
.with_context(|| format!("parse pin {}", path.display()))?;
let tools = doc
.get_mut("tools")
.and_then(Item::as_table_like_mut)
.with_context(|| format!("{} has no [tools]", path.display()))?;
let Some(entry) = tools.get_mut(tool) else {
bail!("{} has no tools.{tool}", path.display());
};
set_tool_version(entry, version).with_context(|| format!("{} tools.{tool}", path.display()))?;
rewrite_own_refs(&doc.to_string(), tool, version)
.with_context(|| format!("pin {}", path.display()))
}
fn set_tool_version(entry: &mut Item, version: &str) -> Result<()> {
match entry {
Item::Value(Value::InlineTable(table)) => {
set_string(table.get_mut("version").context(NO_VERSION)?, version)
}
Item::Table(table) => {
let Some(Item::Value(existing)) = table.get_mut("version") else {
bail!(NO_VERSION);
};
set_string(existing, version)
}
Item::Value(existing) => set_string(existing, version),
Item::None | Item::ArrayOfTables(_) => bail!("is not a version or a table"),
}
}
const NO_VERSION: &str = "has no version string to rewrite";
fn set_string(existing: &mut Value, version: &str) -> Result<()> {
let Value::String(old) = existing else {
bail!(NO_VERSION);
};
let mut new = Formatted::new(version.to_owned());
*new.decor_mut() = old.decor().clone();
*old = new;
Ok(())
}
fn rewrite_pattern(body: &str, pattern: &PinPattern, version: &str) -> Result<String> {
let text = &pattern.r#match;
let (before, after) = text
.split_once(PLACEHOLDER)
.with_context(|| format!("pattern {text:?} has no {PLACEHOLDER}"))?;
if after.contains(PLACEHOLDER) {
bail!("pattern {text:?} has more than one {PLACEHOLDER}");
}
let (open, close) = if pattern.whole_line {
("(?mR)^", "$")
} else {
("", "")
};
let finder = Regex::new(&format!(
"{open}{}{VERSION}{}{close}",
escape(before),
escape(after)
))
.with_context(|| format!("pattern {text:?}"))?;
let found = finder.find_iter(body).count();
if !pattern.occurrences.allows(found) {
bail!(
"pattern {text:?} matches {found} times, expected {}",
pattern.occurrences
);
}
let pinned = format!("{before}{version}{after}");
Ok(finder.replace_all(body, NoExpand(&pinned)).into_owned())
}
fn rewrite_own_refs(body: &str, tool: &str, version: &str) -> Result<String> {
let name = escape(tool.rsplit(['/', ':']).next().unwrap_or(tool));
let finder = Regex::new(&format!(
r#"(?<include>/{name}(?:\.git)?//[^\s"',\]]*\?ref=v)(?<reference>[0-9][^\s"',\]&#;]*)"#
))
.with_context(|| format!("tool {tool:?}"))?;
let whole = Regex::new(&format!("^{VERSION}$")).context("the version pattern")?;
if let Some(found) = finder
.captures_iter(body)
.find(|found| !whole.is_match(&found["reference"]))
{
bail!(
"{:?} pins v{}, which is not a version this rewrites",
&found[0],
&found["reference"]
);
}
Ok(finder
.replace_all(body, format!("${{include}}{version}"))
.into_owned())
}
#[cfg(test)]
mod tests;