diff options
| author | Martin Fischer <martin@push-f.com> | 2026-12-03 08:11:11 +0100 |
|---|---|---|
| committer | Martin Fischer <martin@push-f.com> | 2026-12-04 09:11:05 +0100 |
| commit | a7c41f1de23ba951da838ca24009a8399a1e1c46 (patch) | |
| tree | 64c8ff38ce80317d762e4239533c2283015bac48 /src | |
Diffstat (limited to 'src')
| -rw-r--r-- | src/main.rs | 441 |
1 files changed, 441 insertions, 0 deletions
diff --git a/src/main.rs b/src/main.rs new file mode 100644 index 0000000..b4d003e --- /dev/null +++ b/src/main.rs @@ -0,0 +1,441 @@ +use std::collections::BTreeMap; +use std::env; +use std::fs::{self, OpenOptions}; +use std::io::Write; +use std::os::unix::fs::{PermissionsExt, symlink}; +use std::path::{Component, Path, PathBuf}; +use std::process::{self, Output}; + +use anyhow::{Context, Result, anyhow, bail}; +use clap::{CommandFactory, Parser, Subcommand}; +use clap_complete::{Shell, generate}; +use serde::{Deserialize, Serialize}; +use tempfile::TempDir; + +const CONFIG_FILE: &str = "treeimp.nix"; +const LOCK_FILE: &str = "treeimp.lock"; + +#[derive(Parser, Debug)] +#[command(about = "Vendor directories from remote Git repositories")] +struct Args { + #[command(subcommand)] + command: Command, +} + +#[derive(Subcommand, Debug)] +enum Command { + /// Write an example treeimp.nix. + Init, + /// Import configured sources. + Sync, + /// Generate shell completions. + #[command(hide = true)] + Completions { shell: Shell }, +} + +#[derive(Deserialize, Debug)] +struct Source { + url: String, + #[serde(rename = "ref")] + git_ref: String, + source: PathBuf, + destination: PathBuf, +} + +#[derive(Clone, Deserialize, Serialize, Debug)] +struct LockedSource { + commit: String, + date: String, +} + +type Lock = BTreeMap<String, LockedSource>; + +struct PreparedSource { + name: String, + destination: PathBuf, + output: PathBuf, + nar_hash: String, + lock: LockedSource, + _temporary_directory: TempDir, +} + +fn main() { + if let Err(error) = run(Args::parse().command) { + eprintln!("treeimp: {error:#}"); + std::process::exit(1); + } +} + +fn run(command: Command) -> Result<()> { + match command { + Command::Init => init(), + Command::Sync => sync(), + Command::Completions { shell } => { + generate( + shell, + &mut Args::command(), + "treeimp", + &mut std::io::stdout(), + ); + Ok(()) + } + } +} + +fn init() -> Result<()> { + let path = env::current_dir() + .context("getting the current directory")? + .join(CONFIG_FILE); + let mut file = OpenOptions::new() + .write(true) + .create_new(true) + .open(&path) + .with_context(|| format!("creating {CONFIG_FILE}"))?; + file.write_all( + br#"{ + example = { + url = "https://git.example.com/example.git"; + ref = "main"; + source = "path/to/directory"; + destination = "vendor/example"; + transform = source: source; + }; +} +"#, + )?; + println!("created {CONFIG_FILE}"); + Ok(()) +} + +fn sync() -> Result<()> { + let root = env::current_dir().context("getting the current directory")?; + let config = root.join(CONFIG_FILE); + if !config.is_file() { + bail!("{} does not exist", config.display()); + } + + let sources = evaluate_sources(&config)?; + let lock_path = root.join(LOCK_FILE); + let mut lock = Lock::new(); + let temporary_root = tempfile::tempdir().context("creating temporary directory")?; + let mut updates = Vec::new(); + + for (name, source) in sources { + validate_source_path(&source.source) + .with_context(|| format!("invalid source path for {name:?}"))?; + let destination = if source.destination.is_absolute() { + source.destination.clone() + } else { + root.join(&source.destination) + }; + let prepared = prepare_source(&name, &source, &config, temporary_root.path())?; + + let current_hash = hash_if_present(&destination)?; + lock.insert(name.clone(), prepared.lock.clone()); + if current_hash.as_deref() == Some(&prepared.nar_hash) { + println!("{name}: unchanged"); + continue; + } + + updates.push(PreparedSource { + name, + destination, + output: prepared.output, + nar_hash: prepared.nar_hash, + lock: prepared.lock, + _temporary_directory: prepared._temporary_directory, + }); + } + + for update in &updates { + replace_tree(&update.output, &update.destination) + .with_context(|| format!("replacing {}", update.destination.display()))?; + println!("{}: updated", update.name); + } + write_lock(&lock_path, &lock)?; + Ok(()) +} + +fn evaluate_sources(config: &Path) -> Result<BTreeMap<String, Source>> { + let config = nix_string(config.as_os_str().to_string_lossy().as_ref())?; + let expression = format!( + "let sources = import (builtins.toPath {config}); in builtins.mapAttrs (_: source: {{ inherit (source) url ref source destination; }}) sources" + ); + let output = nix(&["eval", "--impure", "--json", "--expr", &expression])?; + serde_json::from_slice(&output.stdout).context("decoding source settings returned by Nix") +} + +fn prepare_source( + name: &str, + source: &Source, + config: &Path, + temporary_root: &Path, +) -> Result<PreparedSource> { + let checkout = tempfile::Builder::new() + .prefix("checkout-") + .tempdir_in(temporary_root) + .context("creating Git checkout")?; + git(checkout.path(), &["init", "--quiet"])?; + git( + checkout.path(), + &[ + "fetch", + "--quiet", + "--no-tags", + &source.url, + &source.git_ref, + ], + )?; + let tip = git_stdout(checkout.path(), &["rev-parse", "FETCH_HEAD^{commit}"])?; + let source_path = path_for_git(&source.source); + let commit = git_stdout( + checkout.path(), + &["rev-list", "-1", &tip, "--", &source_path], + )?; + if commit.is_empty() { + bail!("source {name:?}: no commit affecting {source_path:?}"); + } + let date = git_stdout( + checkout.path(), + &[ + "show", + "-s", + "--date=format-local:%Y-%m-%dT%H:%M:%SZ", + "--format=%cd", + &commit, + ], + )?; + git( + checkout.path(), + &[ + "-c", + "advice.detachedHead=false", + "checkout", + "--quiet", + "--detach", + &commit, + ], + )?; + + let input = checkout.path().join(&source.source); + if !input.is_dir() { + bail!( + "source {name:?}: {} is not a directory at commit {commit}", + source.source.display() + ); + } + let output = transform_source(config, name, &input)?; + if !output.is_dir() { + bail!("source {name:?}: transform output is not a directory"); + } + let nar_hash = hash_path(&output)?; + + Ok(PreparedSource { + name: name.to_owned(), + destination: source.destination.clone(), + output, + nar_hash, + lock: LockedSource { commit, date }, + _temporary_directory: checkout, + }) +} + +fn transform_source(config: &Path, name: &str, input: &Path) -> Result<PathBuf> { + let config = nix_string(config.as_os_str().to_string_lossy().as_ref())?; + let name = nix_string(name)?; + let input = nix_string(input.as_os_str().to_string_lossy().as_ref())?; + let expression = format!( + "let sources = import (builtins.toPath {config}); source = builtins.path {{ path = builtins.toPath {input}; name = \"treeimp-source\"; }}; transform = (builtins.getAttr {name} sources).transform; in transform source" + ); + let output = nix(&[ + "build", + "--impure", + "--no-link", + "--print-out-paths", + "--expr", + &expression, + ])?; + let paths: Vec<_> = String::from_utf8(output.stdout) + .context("Nix returned a non-UTF-8 output path")? + .lines() + .filter(|line| !line.is_empty()) + .map(PathBuf::from) + .collect(); + match paths.as_slice() { + [path] => Ok(path.clone()), + _ => bail!( + "Nix build returned {} output paths, expected one", + paths.len() + ), + } +} + +fn hash_if_present(path: &Path) -> Result<Option<String>> { + match fs::symlink_metadata(path) { + Ok(_) => hash_path(path).map(Some), + Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None), + Err(error) => Err(error).with_context(|| format!("examining {}", path.display())), + } +} + +fn hash_path(path: &Path) -> Result<String> { + let path = path + .to_str() + .ok_or_else(|| anyhow!("path is not valid UTF-8: {}", path.display()))?; + let output = nix(&["hash", "path", "--type", "sha256", path])?; + String::from_utf8(output.stdout) + .context("Nix returned a non-UTF-8 hash") + .map(|hash| hash.trim().to_owned()) +} + +fn replace_tree(source: &Path, destination: &Path) -> Result<()> { + let parent = destination + .parent() + .ok_or_else(|| anyhow!("destination has no parent: {}", destination.display()))?; + fs::create_dir_all(parent) + .with_context(|| format!("creating destination parent {}", parent.display()))?; + let staging = tempfile::Builder::new() + .prefix(".treeimp-") + .tempdir_in(parent)?; + let staged_tree = staging.path().join("tree"); + copy_tree(source, &staged_tree)?; + + if fs::symlink_metadata(destination).is_ok() { + remove_tree(destination)?; + } + fs::rename(&staged_tree, destination)?; + Ok(()) +} + +fn copy_tree(source: &Path, destination: &Path) -> Result<()> { + let metadata = fs::symlink_metadata(source)?; + let file_type = metadata.file_type(); + if file_type.is_symlink() { + symlink(fs::read_link(source)?, destination)?; + } else if file_type.is_dir() { + fs::create_dir(destination)?; + fs::set_permissions(destination, fs::Permissions::from_mode(0o755))?; + for entry in fs::read_dir(source)? { + let entry = entry?; + copy_tree(&entry.path(), &destination.join(entry.file_name()))?; + } + } else if file_type.is_file() { + fs::copy(source, destination)?; + let mode = if metadata.permissions().mode() & 0o111 != 0 { + 0o755 + } else { + 0o644 + }; + fs::set_permissions(destination, fs::Permissions::from_mode(mode))?; + } else { + bail!("unsupported file type: {}", source.display()); + } + Ok(()) +} + +fn remove_tree(path: &Path) -> Result<()> { + let metadata = fs::symlink_metadata(path)?; + if metadata.is_dir() && !metadata.file_type().is_symlink() { + fs::remove_dir_all(path)?; + } else { + fs::remove_file(path)?; + } + Ok(()) +} + +fn write_lock(path: &Path, lock: &Lock) -> Result<()> { + let parent = path.parent().unwrap_or_else(|| Path::new(".")); + let mut temporary = tempfile::NamedTempFile::new_in(parent)?; + serde_json::to_writer_pretty(temporary.as_file_mut(), lock)?; + temporary.as_file_mut().write_all(b"\n")?; + temporary.as_file_mut().sync_all()?; + temporary + .as_file_mut() + .set_permissions(fs::Permissions::from_mode(0o644))?; + temporary.persist(path).map_err(|error| error.error)?; + Ok(()) +} + +fn validate_source_path(path: &Path) -> Result<()> { + if path.as_os_str().is_empty() || path.is_absolute() { + bail!("source must be a non-empty repository-relative path"); + } + for component in path.components() { + if matches!( + component, + Component::ParentDir | Component::RootDir | Component::Prefix(_) + ) { + bail!("source must not escape the repository"); + } + } + Ok(()) +} + +fn path_for_git(path: &Path) -> String { + if path == Path::new(".") { + ".".to_owned() + } else { + path.to_string_lossy().trim_start_matches("./").to_owned() + } +} + +fn nix_string(value: &str) -> Result<String> { + serde_json::to_string(value).context("encoding a Nix string") +} + +fn nix(arguments: &[&str]) -> Result<Output> { + command( + "nix", + &["--extra-experimental-features", "nix-command"], + arguments, + None, + ) +} + +fn git(directory: &Path, arguments: &[&str]) -> Result<Output> { + let mut command = process::Command::new("git"); + let output = command + .args(arguments) + .current_dir(directory) + .env("TZ", "UTC") + .output() + .context("running git")?; + if output.status.success() { + return Ok(output); + } + let stderr = String::from_utf8_lossy(&output.stderr); + bail!("git {} failed: {}", arguments.join(" "), stderr.trim()) +} + +fn git_stdout(directory: &Path, arguments: &[&str]) -> Result<String> { + let output = git(directory, arguments)?; + String::from_utf8(output.stdout) + .context("Git returned non-UTF-8 output") + .map(|value| value.trim().to_owned()) +} + +fn command( + program: &str, + prefix: &[&str], + arguments: &[&str], + directory: Option<&Path>, +) -> Result<Output> { + let mut command = process::Command::new(program); + command.args(prefix).args(arguments); + if let Some(directory) = directory { + command.current_dir(directory); + } + let output = command + .output() + .with_context(|| format!("running {program}"))?; + if output.status.success() { + return Ok(output); + } + let stderr = String::from_utf8_lossy(&output.stderr); + bail!( + "{} {} failed: {}", + program, + arguments.join(" "), + stderr.trim() + ) +} |
