use std::collections::{BTreeMap, BTreeSet};
use std::path::{Path, PathBuf};
#[derive(Debug, Clone)]
pub struct Committed {
command: String,
files: BTreeMap<PathBuf, String>,
owned: BTreeSet<PathBuf>,
}
impl Committed {
#[must_use]
pub fn by(command: impl Into<String>) -> Self {
Self { command: command.into(), files: BTreeMap::new(), owned: BTreeSet::new() }
}
#[must_use]
pub fn file(mut self, path: impl Into<PathBuf>, contents: impl Into<String>) -> Self {
self.files.insert(path.into(), contents.into());
self
}
#[must_use]
pub fn dir<N, C>(
mut self,
dir: impl Into<PathBuf>,
files: impl IntoIterator<Item = (N, C)>,
) -> Self
where
N: AsRef<Path>,
C: Into<String>,
{
let dir = dir.into();
for (name, contents) in files {
self.files.insert(dir.join(name), contents.into());
}
self.owned.insert(dir);
self
}
pub fn update(&self) -> std::io::Result<Vec<Change>> {
let mut changes = Vec::new();
for (path, contents) in &self.files {
let want = normalize_newlines(contents);
if reads_as(path, &want) {
continue;
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent)?;
}
std::fs::write(path, &want)?;
changes.push(Change::Wrote(path.clone()));
}
for extra in self.extra()? {
std::fs::remove_file(&extra)?;
changes.push(Change::Removed(extra));
}
Ok(changes)
}
pub fn check(&self) -> Result<(), Drifted> {
let mut paths = Vec::new();
for (path, contents) in &self.files {
match std::fs::read_to_string(path) {
Ok(have) if normalize_newlines(&have) == normalize_newlines(contents) => {}
Ok(_) => paths.push((path.clone(), Drift::Stale)),
Err(_) => paths.push((path.clone(), Drift::Missing)),
}
}
for extra in self.extra().unwrap_or_default() {
paths.push((extra, Drift::Extra));
}
if paths.is_empty() {
return Ok(());
}
Err(Drifted { command: self.command.clone(), ci: std::env::var_os("CI").is_some(), paths })
}
fn extra(&self) -> std::io::Result<Vec<PathBuf>> {
let mut extra = Vec::new();
for dir in &self.owned {
for entry in std::fs::read_dir(dir)? {
let path = entry?.path();
if path.extension().is_some_and(|e| e == "rs")
&& path.is_file()
&& !self.files.contains_key(&path)
{
extra.push(path);
}
}
}
extra.sort();
Ok(extra)
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum Change {
Wrote(PathBuf),
Removed(PathBuf),
}
impl std::fmt::Display for Change {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Wrote(p) => write!(f, "wrote {}", p.display()),
Self::Removed(p) => write!(f, "removed {} (no longer generated)", p.display()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Drift {
Stale,
Missing,
Extra,
}
impl Drift {
const fn label(self) -> &'static str {
match self {
Self::Stale => "stale ",
Self::Missing => "missing",
Self::Extra => "extra ",
}
}
}
#[derive(Clone)]
pub struct Drifted {
command: String,
ci: bool,
paths: Vec<(PathBuf, Drift)>,
}
impl Drifted {
#[must_use]
pub fn paths(&self) -> &[(PathBuf, Drift)] {
&self.paths
}
#[must_use]
pub fn command(&self) -> &str {
&self.command
}
}
impl std::fmt::Display for Drifted {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let n = self.paths.len();
let s = if n == 1 { "" } else { "s" };
writeln!(f, "{n} path{s} out of date:")?;
for (path, how) in &self.paths {
writeln!(f, " {} {}", how.label(), path.display())?;
}
write!(f, "\nRun `{}` and review the diff. It changes the wire format.", self.command)?;
if self.ci {
write!(f, "\n NOTE: run `{}` locally and commit the updated files.", self.command)?;
}
Ok(())
}
}
impl std::fmt::Debug for Drifted {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
std::fmt::Display::fmt(self, f)
}
}
impl core::error::Error for Drifted {}
fn normalize_newlines(s: &str) -> String {
s.replace("\r\n", "\n")
}
fn reads_as(path: &Path, contents: &str) -> bool {
std::fs::read_to_string(path).is_ok_and(|old| normalize_newlines(&old) == contents)
}