capy-cli 0.10.0

The command-line interface for the Capy web framework.
Documentation
//! Conservative multi-file edits shared by workflow generators.
use anyhow::{bail, Context, Result};
use fs2::FileExt;
use std::{
    collections::BTreeMap,
    fs::{self, File, OpenOptions},
    io::Write,
    path::{Path, PathBuf},
};

struct Change {
    before: Option<Vec<u8>>,
    after: Vec<u8>,
}

pub(crate) struct EditPlan<'a> {
    root: &'a Path,
    _lock: File,
    changes: BTreeMap<PathBuf, Change>,
}

impl<'a> EditPlan<'a> {
    pub fn new(root: &'a Path) -> Result<Self> {
        reject_symlinks(root, &root.join(".capy-generator.lock"))?;
        let lock = OpenOptions::new()
            .create(true)
            .truncate(false)
            .read(true)
            .write(true)
            .open(root.join(".capy-generator.lock"))?;
        lock.lock_exclusive()
            .context("Cannot lock the Capy generator registry")?;
        Ok(Self {
            root,
            _lock: lock,
            changes: BTreeMap::new(),
        })
    }

    pub fn read(&self, relative: &str) -> Result<String> {
        let path = self.root.join(relative);
        reject_symlinks(self.root, &path)?;
        if let Some(change) = self.changes.get(&path) {
            return String::from_utf8(change.after.clone())
                .context("Generator source must be UTF-8");
        }
        fs::read_to_string(&path).with_context(|| format!("Cannot read {}", path.display()))
    }

    pub fn exists(&self, relative: &str) -> bool {
        let path = self.root.join(relative);
        self.changes.contains_key(&path) || path.exists()
    }

    pub fn create(&mut self, relative: &str, source: String) -> Result<()> {
        self.put(relative, source, false)
    }
    pub fn replace(&mut self, relative: &str, source: String) -> Result<()> {
        self.put(relative, source, true)
    }

    fn put(&mut self, relative: &str, source: String, existing: bool) -> Result<()> {
        let relative_path = Path::new(relative);
        if relative_path.is_absolute()
            || relative_path
                .components()
                .any(|part| !matches!(part, std::path::Component::Normal(_)))
        {
            bail!("Invalid generator output path.");
        }
        let path = self.root.join(relative_path);
        reject_symlinks(self.root, &path)?;
        let after = if relative.ends_with(".rs") {
            crate::generate::format_rust(&source)?
        } else {
            source
        }
        .into_bytes();
        if let Some(change) = self.changes.get_mut(&path) {
            if !existing {
                bail!(
                    "Duplicate generated output {}; no files changed.",
                    path.display()
                );
            }
            change.after = after;
            return Ok(());
        }
        let before = match fs::read(&path) {
            Ok(bytes) => Some(bytes),
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
            Err(error) => return Err(error.into()),
        };
        if before.is_some() != existing {
            bail!(
                "{} {}. Capy never silently overwrites generated files; no files changed.",
                path.display(),
                if existing {
                    "is missing"
                } else {
                    "already exists"
                }
            );
        }
        self.changes.insert(path, Change { before, after });
        Ok(())
    }

    pub fn anchor(&mut self, relative: &str, marker: &str, addition: &str) -> Result<()> {
        let source = self.read(relative)?;
        if source.matches(marker).count() != 1 || !source.lines().any(|line| line.trim() == marker)
        {
            bail!("Cannot safely update {relative}: expected one `{marker}` line. Restore the marker or add this exact snippet manually:\n{addition}\nNo files changed.");
        }
        self.replace(
            relative,
            source.replace(marker, &format!("{addition}\n{marker}")),
        )
    }

    pub fn commit(self) -> Result<Vec<PathBuf>> {
        self.commit_with(|file, path, existing| {
            if existing {
                file.persist(path)
                    .map(|_| ())
                    .map_err(|error| error.error.into())
            } else {
                file.persist_noclobber(path)
                    .map(|_| ())
                    .map_err(|error| error.error.into())
            }
        })
    }

    fn commit_with(
        self,
        mut persist: impl FnMut(tempfile::NamedTempFile, &Path, bool) -> Result<()>,
    ) -> Result<Vec<PathBuf>> {
        let mut staged = Vec::new();
        // All parsing, collision checks and formatting finish before any source mutation.
        for (path, change) in &self.changes {
            reject_symlinks(self.root, path)?;
            let current = match fs::read(path) {
                Ok(bytes) => Some(bytes),
                Err(error) if error.kind() == std::io::ErrorKind::NotFound => None,
                Err(error) => return Err(error.into()),
            };
            if current != change.before {
                bail!(
                    "{} changed during generation; retry after saving. No files changed.",
                    path.display()
                );
            }
            let mut temp = tempfile::NamedTempFile::new_in(self.root)?;
            if change.before.is_some() {
                temp.as_file()
                    .set_permissions(fs::metadata(path)?.permissions())?;
            }
            temp.write_all(&change.after)?;
            temp.as_file().sync_all()?;
            staged.push(temp);
        }
        let mut created = Vec::new();
        let mut committed: Vec<PathBuf> = Vec::new();
        let result: Result<()> = (|| {
            for ((path, change), temp) in self.changes.iter().zip(staged) {
                let mut missing = Vec::new();
                let mut parent = path.parent().context("Missing generator parent")?;
                while !parent.exists() {
                    missing.push(parent.to_path_buf());
                    parent = parent.parent().context("Missing generator root")?;
                }
                for directory in missing.into_iter().rev() {
                    fs::create_dir(&directory)?;
                    created.push(directory);
                }
                reject_symlinks(self.root, path)?;
                persist(temp, path, change.before.is_some())?;
                committed.push(path.clone());
            }
            Ok(())
        })();
        if let Err(error) = result {
            for path in committed.iter().rev() {
                match &self.changes[path].before {
                    Some(bytes) => {
                        let mut restored = tempfile::NamedTempFile::new_in(self.root)?;
                        restored
                            .as_file()
                            .set_permissions(fs::metadata(path)?.permissions())?;
                        restored.write_all(bytes)?;
                        restored.as_file().sync_all()?;
                        restored
                            .persist(path)
                            .map_err(|error| error.error)
                            .context(
                                "Generator rollback failed; inspect partially restored files",
                            )?;
                    }
                    None => fs::remove_file(path)?,
                }
            }
            for directory in created.iter().rev() {
                fs::remove_dir(directory)
                    .context("Generator rollback could not remove a created directory")?;
            }
            return Err(
                error.context("Generation failed; committed source changes were rolled back")
            );
        }
        Ok(committed)
    }
}

fn reject_symlinks(root: &Path, path: &Path) -> Result<()> {
    for ancestor in path.ancestors() {
        if let Ok(metadata) = fs::symlink_metadata(ancestor) {
            if metadata.file_type().is_symlink() {
                bail!(
                    "Generator refuses symlink {}; no files changed.",
                    ancestor.display()
                );
            }
        }
        if ancestor == root {
            break;
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn partial_commit_restores_custom_files_and_removes_only_created_directories() {
        let root = tempfile::tempdir().unwrap();
        fs::write(root.path().join("a.rs"), "// application customization\n").unwrap();
        let mut plan = EditPlan::new(root.path()).unwrap();
        plan.replace("a.rs", "// changed\n".into()).unwrap();
        plan.create("b/nested/file.txt", "new".into()).unwrap();
        plan.create("c/file.txt", "new".into()).unwrap();
        let mut writes = 0;
        assert!(plan
            .commit_with(|file, path, _| {
                writes += 1;
                if writes == 3 {
                    bail!("injected persist failure");
                }
                file.persist(path).map_err(|error| error.error)?;
                Ok(())
            })
            .is_err());
        assert_eq!(
            fs::read_to_string(root.path().join("a.rs")).unwrap(),
            "// application customization\n"
        );
        assert!(!root.path().join("b").exists());
        assert!(!root.path().join("c").exists());
    }
}