roneocratesroneo-coresrcworker.rs
98ff76d5794bbd1480ad719803187d2c40e42403- use std::collections::HashSet;
- use std::fs;
- use std::path::{Path, PathBuf};
- use std::sync::Arc;
- use indexmap::IndexMap;
- use rayon::prelude::*;
- use serde_json::Value as JsonValue;
- use crate::answers::AnswersMap;
- use crate::config::TemplateConfig;
- use crate::error::{Result, RoneoError};
- use crate::filter::PathFilter;
- use crate::fs_util::{
- TempDir, copy_permissions, create_symlink, file_mode_from_metadata, set_executable,
- set_file_mode,
- };
- use crate::plugin::{ExtensionInitContext, ExtensionRegistry};
- use crate::prompt::{
- AnswerCollectionOptions, NonInteractivePrompter, OverwriteChoice, Prompter, collect_answers,
- };
- use crate::renderer::{CopierConf, TemplateRenderer, build_render_context};
- use crate::settings::UserSettings;
- use crate::tasks::{MigrationRun, MigrationStage, run_migrations, run_tasks};
- use crate::template::{ResolvedTemplate, TemplateBacking};
- use crate::vcs::{self, ConflictMode, InMemoryGitTree};
- use crate::version::Pep440Version;
- /// Highest Copier specification version that Ronéo declares compatibility with
- /// when validating `_min_copier_version`.
- pub const COPIER_COMPAT_VERSION: &str = "9.19.1";
- /// Options controlling `copy`, `recopy`, and `update`.
- #[derive(Debug, Clone)]
- pub struct CopyOptions {
- pub vcs_ref: Option<String>,
- pub data: IndexMap<String, JsonValue>,
- pub answers_file: Option<PathBuf>,
- pub exclude: Vec<String>,
- pub skip_if_exists: Vec<String>,
- pub use_default_excludes: bool,
- pub use_prereleases: bool,
- pub overwrite: bool,
- pub pretend: bool,
- pub defaults: bool,
- pub skip_answered: bool,
- pub ask_questions: Vec<String>,
- pub skip_tasks: bool,
- pub trust: bool,
- pub conflict_mode: ConflictMode,
- pub context_lines: usize,
- pub cleanup_on_error: bool,
- pub skip_git_check: bool,
- pub quiet: bool,
- pub user_settings: Option<UserSettings>,
- pub extensions: ExtensionRegistry,
- }
- impl Default for CopyOptions {
- fn default() -> Self {
- Self {
- vcs_ref: None,
- data: IndexMap::new(),
- answers_file: None,
- exclude: Vec::new(),
- skip_if_exists: Vec::new(),
- use_default_excludes: true,
- use_prereleases: false,
- overwrite: false,
- pretend: false,
- defaults: false,
- skip_answered: false,
- ask_questions: Vec::new(),
- skip_tasks: false,
- trust: false,
- conflict_mode: ConflictMode::Inline,
- context_lines: 3,
- cleanup_on_error: true,
- skip_git_check: false,
- quiet: false,
- user_settings: None,
- extensions: ExtensionRegistry::new(),
- }
- }
- }
- /// High-level events emitted during copy/recopy/update for UI/CLI reporting.
- #[derive(Debug, Clone)]
- pub enum ActionEvent {
- Create(PathBuf),
- Overwrite(PathBuf),
- Update(PathBuf),
- Delete(PathBuf),
- Identical(PathBuf),
- Skip(PathBuf),
- Conflict(PathBuf),
- RunTask(String),
- Message(String),
- Warning(String),
- }
- pub trait Reporter {
- fn emit(&self, event: ActionEvent);
- }
- #[derive(Debug, Default)]
- pub struct NoopReporter;
- impl Reporter for NoopReporter {
- fn emit(&self, _event: ActionEvent) {}
- }
- /// Summary returned after `copy`, `recopy`, or `update`.
- #[derive(Debug, Clone)]
- pub struct OperationReport {
- pub src_path: String,
- pub dst_path: PathBuf,
- pub commit: Option<String>,
- pub answers_file: PathBuf,
- pub created: usize,
- pub updated: usize,
- pub skipped: usize,
- pub conflicts: Vec<String>,
- }
- /// Result of previewing a 3-way template update via `diff_update`.
- #[derive(Debug, Clone)]
- pub struct UpdateDiff {
- pub src_path: String,
- pub from_commit: String,
- pub to_commit: Option<String>,
- pub patch: String,
- pub created: Vec<String>,
- pub modified: Vec<String>,
- pub deleted: Vec<String>,
- }
- /// Result of checking whether a newer template version is available (`roneo check-update`).
- #[derive(Debug, Clone, serde::Serialize)]
- pub struct CheckUpdateReport {
- pub src_path: String,
- pub current_version: String,
- pub latest_version: String,
- pub update_available: bool,
- }
- /// Check whether a newer template version is available for an existing project without
- /// modifying any files (matching Copier's `check-update` / `get_update_data`).
- pub fn check_update(dst_path: &Path, options: &CopyOptions) -> Result<CheckUpdateReport> {
- let answers_path = AnswersMap::find_in_dir(dst_path, options.answers_file.as_deref())
- .ok_or_else(|| RoneoError::MissingAnswersFile(dst_path.to_path_buf()))?;
- let previous = AnswersMap::load(&answers_path)?;
- let src = previous
- .src_path()
- .ok_or_else(|| RoneoError::InvalidConfig("Answers file is missing `_src_path`".into()))?
- .to_string();
- let current_commit = previous
- .commit()
- .ok_or_else(|| {
- RoneoError::InvalidConfig(
- "Answers file is missing `_commit`. Cannot check updates for a non-git template."
- .into(),
- )
- })?
- .to_string();
- let current_tpl = ResolvedTemplate::resolve(&src, Some(¤t_commit))?;
- let latest_tpl = current_tpl.resolve_sibling(None, options.use_prereleases)?;
- let latest_commit = latest_tpl
- .commit
- .clone()
- .or_else(|| latest_tpl.commit_hash.clone())
- .unwrap_or_else(|| "HEAD".to_string());
- let update_available = match (
- Pep440Version::parse(¤t_commit),
- Pep440Version::parse(&latest_commit),
- ) {
- (Some(cur_ver), Some(lat_ver)) => lat_ver > cur_ver,
- _ => match (¤t_tpl.commit_hash, &latest_tpl.commit_hash) {
- (Some(c), Some(l)) => c != l,
- _ => current_commit != latest_commit,
- },
- };
- Ok(CheckUpdateReport {
- src_path: src,
- current_version: current_commit,
- latest_version: latest_commit,
- update_available,
- })
- }
- /// Render a new project from `src_path` into `dst_path`.
- ///
- /// If `dst_path` did not exist prior to `copy` and an error occurs, `dst_path` is automatically
- /// removed unless `options.cleanup_on_error` is `false` (Copier's `--no-cleanup`).
- pub fn copy(
- src_path: &str,
- dst_path: &Path,
- options: &CopyOptions,
- prompter: &dyn Prompter,
- reporter: &dyn Reporter,
- ) -> Result<OperationReport> {
- let dst_existed = dst_path.exists();
- let result = copy_inner(src_path, dst_path, options, prompter, reporter);
- if result.is_err()
- && !dst_existed
- && options.cleanup_on_error
- && !options.pretend
- && dst_path.exists()
- {
- let _ = fs::remove_dir_all(dst_path);
- }
- result
- }
- fn copy_inner(
- src_path: &str,
- dst_path: &Path,
- options: &CopyOptions,
- prompter: &dyn Prompter,
- reporter: &dyn Reporter,
- ) -> Result<OperationReport> {
- let resolved = ResolvedTemplate::resolve_with_options(
- src_path,
- options.vcs_ref.as_deref(),
- options.use_prereleases,
- )?;
- check_min_copier_version(&resolved.config, reporter)?;
- let user_settings = resolve_user_settings(options);
- let is_trusted_pre =
- options.trust || user_settings.is_trusted(&resolved.original_src, &resolved.resolved_src);
- let active_exts = build_active_extensions(&resolved, options, is_trusted_pre)?;
- let is_trusted = check_trust(&resolved, options, &user_settings, &active_exts, reporter)?;
- let file_reader = resolved.file_reader();
- let init_ctx = ExtensionInitContext {
- template_root: resolved.local_path.clone(),
- dst_path: dst_path.to_path_buf(),
- file_reader: Arc::clone(&file_reader),
- };
- let renderer = TemplateRenderer::with_extensions(
- &resolved.config.settings.envops,
- Some(file_reader),
- Some(&active_exts),
- Some(&init_ctx),
- )?;
- if let Some(msg) = &resolved.config.settings.message_before_copy {
- let banner = renderer.render_str(msg, &options.data, "_message_before_copy")?;
- if !banner.trim().is_empty() {
- reporter.emit(ActionEvent::Message(banner));
- }
- }
- let prompt_init_ctx =
- build_prompt_initial_context(&resolved, dst_path, &renderer, options, "copy", is_trusted)?;
- let mut answers = collect_answers(
- &resolved.config,
- &renderer,
- prompter,
- &AnswerCollectionOptions {
- data: &options.data,
- previous_answers: None,
- user_defaults: Some(&user_settings.defaults),
- initial_context: Some(&prompt_init_ctx),
- extensions: Some(&active_exts),
- use_defaults: options.defaults,
- skip_answered: options.skip_answered,
- ask_questions: &options.ask_questions,
- },
- )?;
- answers.set_src_path(&resolved.original_src);
- if let Some(commit) = &resolved.commit {
- answers.set_commit(commit);
- }
- let (report, ctx) = render_into_destination(
- &resolved,
- dst_path,
- &answers,
- &renderer,
- &active_exts,
- options,
- "copy",
- is_trusted,
- Some(prompter),
- reporter,
- )?;
- if !options.skip_tasks && !resolved.config.settings.tasks.is_empty() {
- run_tasks(
- &resolved.config.settings.tasks,
- dst_path,
- &renderer,
- &ctx,
- &[],
- options.pretend,
- |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())),
- )?;
- }
- if let Some(msg) = &resolved.config.settings.message_after_copy {
- let banner = renderer.render_str(msg, &ctx, "_message_after_copy")?;
- if !banner.trim().is_empty() {
- reporter.emit(ActionEvent::Message(banner));
- }
- }
- Ok(report)
- }
- /// Re-apply a template onto an existing project using saved answers, without 3-way diffing.
- pub fn recopy(
- dst_path: &Path,
- src_override: Option<&str>,
- options: &CopyOptions,
- prompter: &dyn Prompter,
- reporter: &dyn Reporter,
- ) -> Result<OperationReport> {
- let answers_path = AnswersMap::find_in_dir(dst_path, options.answers_file.as_deref())
- .ok_or_else(|| RoneoError::MissingAnswersFile(dst_path.to_path_buf()))?;
- let previous = AnswersMap::load(&answers_path)?;
- let src = src_override
- .or_else(|| previous.src_path())
- .ok_or_else(|| {
- RoneoError::InvalidConfig(
- "Answers file is missing `_src_path`; pass a template source explicitly".into(),
- )
- })?;
- let resolved = ResolvedTemplate::resolve_with_options(
- src,
- options.vcs_ref.as_deref(),
- options.use_prereleases,
- )?;
- check_min_copier_version(&resolved.config, reporter)?;
- let user_settings = resolve_user_settings(options);
- let is_trusted_pre =
- options.trust || user_settings.is_trusted(&resolved.original_src, &resolved.resolved_src);
- let active_exts = build_active_extensions(&resolved, options, is_trusted_pre)?;
- let is_trusted = check_trust(&resolved, options, &user_settings, &active_exts, reporter)?;
- let file_reader = resolved.file_reader();
- let init_ctx = ExtensionInitContext {
- template_root: resolved.local_path.clone(),
- dst_path: dst_path.to_path_buf(),
- file_reader: Arc::clone(&file_reader),
- };
- let renderer = TemplateRenderer::with_extensions(
- &resolved.config.settings.envops,
- Some(file_reader),
- Some(&active_exts),
- Some(&init_ctx),
- )?;
- let prompt_init_ctx = build_prompt_initial_context(
- &resolved, dst_path, &renderer, options, "recopy", is_trusted,
- )?;
- let mut answers = collect_answers(
- &resolved.config,
- &renderer,
- prompter,
- &AnswerCollectionOptions {
- data: &options.data,
- previous_answers: Some(&previous),
- user_defaults: Some(&user_settings.defaults),
- initial_context: Some(&prompt_init_ctx),
- extensions: Some(&active_exts),
- use_defaults: options.defaults,
- skip_answered: options.skip_answered,
- ask_questions: &options.ask_questions,
- },
- )?;
- answers.set_src_path(&resolved.original_src);
- if let Some(commit) = &resolved.commit {
- answers.set_commit(commit);
- }
- let mut recopy_opts = options.clone();
- recopy_opts.overwrite = true;
- let (report, ctx) = render_into_destination(
- &resolved,
- dst_path,
- &answers,
- &renderer,
- &active_exts,
- &recopy_opts,
- "recopy",
- is_trusted,
- None,
- reporter,
- )?;
- if !options.skip_tasks && !resolved.config.settings.tasks.is_empty() {
- run_tasks(
- &resolved.config.settings.tasks,
- dst_path,
- &renderer,
- &ctx,
- &[],
- options.pretend,
- |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())),
- )?;
- }
- Ok(report)
- }
- /// Update an existing git-tracked project to a newer template version via 3-way merge,
- /// preserving local user edits cleanly (Copier's smart update algorithm).
- ///
- /// Works both when `dst_path` is a Git repository root and when it is a subdirectory inside
- /// a Git monorepo.
- pub fn update(
- dst_path: &Path,
- options: &CopyOptions,
- prompter: &dyn Prompter,
- reporter: &dyn Reporter,
- ) -> Result<OperationReport> {
- let (git_root, subproject_subdir) = resolve_git_destination(dst_path, options)?;
- let wt_status = if options.skip_git_check {
- vcs::WorkingTreeStatus {
- is_clean: true,
- ignored_paths: Vec::new(),
- }
- } else {
- let status = vcs::inspect_working_tree(&git_root)?;
- if !options.pretend && !status.is_clean {
- return Err(RoneoError::DirtyDestination(dst_path.to_path_buf()));
- }
- status
- };
- let prepared = prepare_update_patch(dst_path, options, prompter, reporter, true)?;
- // Reject downgrades on PEP 440 versioned templates (matching Copier's DowngradeError).
- let new_commit_str = prepared.new_template.commit.as_deref().unwrap_or("");
- if let (Some(old_ver), Some(new_ver)) = (
- Pep440Version::parse(&prepared.old_commit),
- Pep440Version::parse(new_commit_str),
- ) && new_ver < old_ver
- {
- return Err(RoneoError::DowngradeNotSupported {
- from: prepared.old_commit,
- to: new_commit_str.to_string(),
- });
- }
- let diff_summary = summarize_patch(&prepared.patch);
- for path in &diff_summary.created {
- reporter.emit(ActionEvent::Create(PathBuf::from(path)));
- }
- for path in &diff_summary.modified {
- reporter.emit(ActionEvent::Update(PathBuf::from(path)));
- }
- for path in &diff_summary.deleted {
- reporter.emit(ActionEvent::Delete(PathBuf::from(path)));
- }
- if !options.skip_tasks && !prepared.new_template.config.settings.migrations.is_empty() {
- run_migrations(
- &prepared.new_template.config.settings.migrations,
- &MigrationRun {
- version_from: &prepared.old_commit,
- version_to: new_commit_str,
- stage: MigrationStage::Before,
- dst_path,
- renderer: &prepared.new_renderer,
- ctx: &prepared.new_ctx,
- pretend: options.pretend,
- },
- |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())),
- )?;
- }
- // Honor `_skip_if_exists` / `-s`, `.gitignore`-ignored files, AND exclude `.copier-answers.yml`
- // from `git apply` (written cleanly afterwards to prevent spurious merge conflicts, matching Copier).
- let mut apply_excludes = collect_update_skip_excludes(
- dst_path,
- subproject_subdir.as_deref(),
- &diff_summary,
- &prepared.new_skip_filter,
- );
- let skipped_count = apply_excludes.len();
- for ignored in &wt_status.ignored_paths {
- apply_excludes.push(ignored.clone());
- }
- let format_repo_rel = |rel: &Path| -> String {
- match subproject_subdir.as_deref() {
- Some(sub) if !sub.as_os_str().is_empty() => {
- sub.join(rel).to_string_lossy().replace('\\', "/")
- }
- _ => rel.to_string_lossy().replace('\\', "/"),
- }
- };
- apply_excludes.push(format_repo_rel(&prepared.new_answers_rel));
- if let Ok(old_rel) = prepared.old_answers_path.strip_prefix(dst_path)
- && old_rel != prepared.new_answers_rel
- {
- apply_excludes.push(format_repo_rel(old_rel));
- }
- let old_snapshot_dir = prepared.diff_root.path().join("a");
- let new_snapshot_dir = prepared.diff_root.path().join("b");
- let mut conflicts = Vec::new();
- if !options.pretend && !prepared.patch.is_empty() {
- let apply_res = vcs::apply_patch(
- &git_root,
- subproject_subdir.as_deref(),
- &prepared.patch,
- options.conflict_mode,
- &apply_excludes,
- Some((&old_snapshot_dir, &new_snapshot_dir)),
- )?;
- if apply_res.has_conflicts {
- for c in &apply_res.conflicted_files {
- reporter.emit(ActionEvent::Conflict(PathBuf::from(c)));
- }
- if apply_res.conflicted_files.is_empty() && !apply_res.stderr.is_empty() {
- reporter.emit(ActionEvent::Warning(apply_res.stderr.clone()));
- }
- conflicts = apply_res.conflicted_files;
- }
- }
- // Write the updated answers file directly (never conflicted by `git apply`), and clean up
- // the previous answers file if `_answers_file` was renamed between template versions.
- let answers_dst = dst_path.join(&prepared.new_answers_rel);
- if !options.pretend
- && let Some(bytes) = &prepared.new_answers_bytes
- {
- if let Some(parent) = answers_dst.parent() {
- fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?;
- }
- fs::write(&answers_dst, bytes).map_err(|e| RoneoError::io(&answers_dst, e))?;
- let old_canon = fs::canonicalize(&prepared.old_answers_path).ok();
- let new_canon = fs::canonicalize(&answers_dst).ok();
- if old_canon != new_canon && prepared.old_answers_path.is_file() {
- let _ = fs::remove_file(&prepared.old_answers_path);
- if let Ok(rel) = prepared.old_answers_path.strip_prefix(dst_path) {
- reporter.emit(ActionEvent::Delete(rel.to_path_buf()));
- }
- }
- }
- if !options.skip_tasks {
- if !prepared.new_template.config.settings.migrations.is_empty() {
- run_migrations(
- &prepared.new_template.config.settings.migrations,
- &MigrationRun {
- version_from: &prepared.old_commit,
- version_to: new_commit_str,
- stage: MigrationStage::After,
- dst_path,
- renderer: &prepared.new_renderer,
- ctx: &prepared.new_ctx,
- pretend: options.pretend,
- },
- |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())),
- )?;
- }
- if !prepared.new_template.config.settings.tasks.is_empty() {
- run_tasks(
- &prepared.new_template.config.settings.tasks,
- dst_path,
- &prepared.new_renderer,
- &prepared.new_ctx,
- &[],
- options.pretend,
- |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())),
- )?;
- }
- }
- if let Some(msg) = &prepared.new_template.config.settings.message_after_update {
- let banner =
- prepared
- .new_renderer
- .render_str(msg, &prepared.new_ctx, "_message_after_update")?;
- if !banner.trim().is_empty() {
- reporter.emit(ActionEvent::Message(banner));
- }
- }
- Ok(OperationReport {
- src_path: prepared.src,
- dst_path: dst_path.to_path_buf(),
- commit: prepared.new_template.commit,
- answers_file: answers_dst,
- created: diff_summary.created.len(),
- updated: diff_summary.modified.len() + diff_summary.deleted.len(),
- skipped: skipped_count,
- conflicts,
- })
- }
- /// Preview the exact unified diff that `update` would apply, without modifying `dst_path`.
- pub fn diff_update(
- dst_path: &Path,
- options: &CopyOptions,
- prompter: &dyn Prompter,
- ) -> Result<UpdateDiff> {
- let noop = NoopReporter;
- let prepared = prepare_update_patch(dst_path, options, prompter, &noop, false)?;
- let summary = summarize_patch(&prepared.patch);
- Ok(UpdateDiff {
- src_path: prepared.src,
- from_commit: prepared.old_commit,
- to_commit: prepared.new_template.commit,
- patch: String::from_utf8_lossy(&prepared.patch).into_owned(),
- created: summary.created,
- modified: summary.modified,
- deleted: summary.deleted,
- })
- }
- struct PreparedUpdate {
- src: String,
- old_commit: String,
- old_answers_path: PathBuf,
- new_template: ResolvedTemplate,
- new_renderer: TemplateRenderer,
- new_answers_rel: PathBuf,
- new_answers_bytes: Option<Vec<u8>>,
- new_ctx: IndexMap<String, JsonValue>,
- new_skip_filter: PathFilter,
- diff_root: TempDir,
- patch: Vec<u8>,
- }
- fn resolve_git_destination(
- dst_path: &Path,
- options: &CopyOptions,
- ) -> Result<(PathBuf, Option<PathBuf>)> {
- if let Some(root) = vcs::find_git_worktree_root(dst_path) {
- let canon_root = fs::canonicalize(&root).unwrap_or(root);
- let canon_dst = fs::canonicalize(dst_path).unwrap_or_else(|_| dst_path.to_path_buf());
- let subdir = canon_dst
- .strip_prefix(&canon_root)
- .ok()
- .filter(|p| !p.as_os_str().is_empty())
- .map(Path::to_path_buf);
- return Ok((canon_root, subdir));
- }
- if options.skip_git_check {
- return Ok((dst_path.to_path_buf(), None));
- }
- Err(RoneoError::NotAGitRepo(dst_path.to_path_buf()))
- }
- fn collect_update_skip_excludes(
- dst_path: &Path,
- subproject_subdir: Option<&Path>,
- summary: &PatchSummary,
- skip_filter: &PathFilter,
- ) -> Vec<String> {
- let mut out = Vec::new();
- for rel in summary.modified.iter().chain(summary.deleted.iter()) {
- let rel_path = Path::new(rel);
- if dst_path.join(rel_path).exists() && skip_filter.should_skip_if_exists(rel_path, false) {
- let full = match subproject_subdir {
- Some(sub) if !sub.as_os_str().is_empty() => {
- sub.join(rel_path).to_string_lossy().replace('\\', "/")
- }
- _ => rel.clone(),
- };
- out.push(full);
- }
- }
- out
- }
- /// Shared fast-path engine for both `update` and `diff_update`:
- /// - Reuses one `gix::ThreadSafeRepository` for both old & new commits (`resolve_sibling`).
- /// - Renders `old_template` into `tmp/a` and `new_template` into `tmp/b` in parallel via `rayon::join`.
- /// - Produces the binary unified patch in ONE `git diff --no-index --no-prefix` call (zero `git init/add/commit`
- /// and zero working-tree copy/delete).
- fn prepare_update_patch(
- dst_path: &Path,
- options: &CopyOptions,
- prompter: &dyn Prompter,
- reporter: &dyn Reporter,
- enforce_trust: bool,
- ) -> Result<PreparedUpdate> {
- let answers_path = AnswersMap::find_in_dir(dst_path, options.answers_file.as_deref())
- .ok_or_else(|| RoneoError::MissingAnswersFile(dst_path.to_path_buf()))?;
- let previous = AnswersMap::load(&answers_path)?;
- let src = previous
- .src_path()
- .ok_or_else(|| RoneoError::InvalidConfig("Answers file is missing `_src_path`".into()))?
- .to_string();
- let old_commit = previous
- .commit()
- .ok_or_else(|| {
- RoneoError::InvalidConfig(
- "Answers file is missing `_commit`. Cannot smart-update a non-git template; use `recopy`."
- .into(),
- )
- })?
- .to_string();
- let old_template = ResolvedTemplate::resolve(&src, Some(&old_commit))?;
- let target_ref = if options.vcs_ref.as_deref() == Some(":current:") {
- Some(old_commit.as_str())
- } else {
- options.vcs_ref.as_deref()
- };
- let new_template = old_template.resolve_sibling(target_ref, options.use_prereleases)?;
- check_min_copier_version(&new_template.config, reporter)?;
- let user_settings = resolve_user_settings(options);
- let is_trusted_pre = options.trust
- || user_settings.is_trusted(&new_template.original_src, &new_template.resolved_src);
- let old_exts = build_active_extensions(&old_template, options, is_trusted_pre)?;
- let new_exts = build_active_extensions(&new_template, options, is_trusted_pre)?;
- let is_trusted = if enforce_trust {
- check_trust(&new_template, options, &user_settings, &new_exts, reporter)?
- } else {
- is_trusted_pre
- };
- let old_reader = old_template.file_reader();
- let new_reader = new_template.file_reader();
- let old_init = ExtensionInitContext {
- template_root: old_template.local_path.clone(),
- dst_path: dst_path.to_path_buf(),
- file_reader: Arc::clone(&old_reader),
- };
- let new_init = ExtensionInitContext {
- template_root: new_template.local_path.clone(),
- dst_path: dst_path.to_path_buf(),
- file_reader: Arc::clone(&new_reader),
- };
- let old_renderer = TemplateRenderer::with_extensions(
- &old_template.config.settings.envops,
- Some(old_reader),
- Some(&old_exts),
- Some(&old_init),
- )?;
- let new_renderer = TemplateRenderer::with_extensions(
- &new_template.config.settings.envops,
- Some(new_reader),
- Some(&new_exts),
- Some(&new_init),
- )?;
- if enforce_trust && let Some(msg) = &new_template.config.settings.message_before_update {
- let banner =
- new_renderer.render_str(msg, &previous.combined(), "_message_before_update")?;
- if !banner.trim().is_empty() {
- reporter.emit(ActionEvent::Message(banner));
- }
- }
- let prompt_init_ctx = build_prompt_initial_context(
- &new_template,
- dst_path,
- &new_renderer,
- options,
- "update",
- is_trusted,
- )?;
- let mut new_answers = collect_answers(
- &new_template.config,
- &new_renderer,
- prompter,
- &AnswerCollectionOptions {
- data: &options.data,
- previous_answers: Some(&previous),
- user_defaults: Some(&user_settings.defaults),
- initial_context: Some(&prompt_init_ctx),
- extensions: Some(&new_exts),
- use_defaults: options.defaults,
- skip_answered: options.skip_answered,
- ask_questions: &options.ask_questions,
- },
- )?;
- new_answers.set_src_path(&src);
- if let Some(commit) = &new_template.commit {
- new_answers.set_commit(commit);
- }
- // One TempDir with sibling `a/` (old snapshot) and `b/` (new snapshot) rendered in parallel.
- let diff_root = TempDir::with_prefix("roneo-diff")?;
- let old_dir = diff_root.path().join("a");
- let new_dir = diff_root.path().join("b");
- fs::create_dir(&old_dir).map_err(|e| RoneoError::io(&old_dir, e))?;
- fs::create_dir(&new_dir).map_err(|e| RoneoError::io(&new_dir, e))?;
- let mut new_temp_opts = options.clone();
- new_temp_opts.overwrite = true;
- new_temp_opts.pretend = false;
- new_temp_opts.skip_tasks = true;
- // Copier discussion #2345: also apply the new template's `_exclude` patterns when rendering
- // the old snapshot so newly excluded files are not treated as deleted in the diff.
- let mut old_temp_opts = new_temp_opts.clone();
- for pat in &new_template.config.settings.exclude {
- if !pat.contains("{{") && !pat.contains("{%") {
- for line in pat.lines() {
- let trimmed = line.trim();
- if !trimmed.is_empty() {
- old_temp_opts.exclude.push(trimmed.to_string());
- }
- }
- }
- }
- // Reconstruct full `old_answers` (including `when: false` defaults for strict-undefined
- // templates) AND render `old_template` IN PARALLEL with rendering `new_template`!
- let noop = NoopReporter;
- let (old_res, new_res) = rayon::join(
- || -> Result<()> {
- let old_prompt_init_ctx = build_prompt_initial_context(
- &old_template,
- dst_path,
- &old_renderer,
- options,
- "update",
- is_trusted,
- )?;
- let mut old_answers = collect_answers(
- &old_template.config,
- &old_renderer,
- &NonInteractivePrompter,
- &AnswerCollectionOptions {
- data: &previous.user,
- previous_answers: Some(&previous),
- user_defaults: Some(&user_settings.defaults),
- initial_context: Some(&old_prompt_init_ctx),
- extensions: Some(&old_exts),
- use_defaults: true,
- skip_answered: true,
- ask_questions: &[],
- },
- )?;
- old_answers.metadata.clone_from(&previous.metadata);
- render_into_destination(
- &old_template,
- &old_dir,
- &old_answers,
- &old_renderer,
- &old_exts,
- &old_temp_opts,
- "update",
- is_trusted,
- None,
- &noop,
- )?;
- Ok(())
- },
- || {
- render_into_destination(
- &new_template,
- &new_dir,
- &new_answers,
- &new_renderer,
- &new_exts,
- &new_temp_opts,
- "update",
- is_trusted,
- None,
- &noop,
- )
- },
- );
- old_res?;
- let (new_render_report, new_ctx) = new_res?;
- let new_answers_rel = new_render_report
- .answers_file
- .strip_prefix(&new_dir)
- .map_or_else(
- |_| {
- PathBuf::from(
- new_render_report
- .answers_file
- .file_name()
- .unwrap_or_default(),
- )
- },
- Path::to_path_buf,
- );
- let new_answers_bytes = fs::read(&new_render_report.answers_file).ok();
- let mut all_skip = Vec::with_capacity(
- new_template.config.settings.skip_if_exists.len() + options.skip_if_exists.len(),
- );
- for pat in &new_template.config.settings.skip_if_exists {
- let expanded = new_renderer.render_str(pat, &new_ctx, "_skip_if_exists")?;
- for line in expanded.lines() {
- let trimmed = line.trim();
- if !trimmed.is_empty() {
- all_skip.push(trimmed.to_string());
- }
- }
- }
- all_skip.extend(options.skip_if_exists.iter().cloned());
- let new_skip_filter = PathFilter::new(Path::new(""), &[], &all_skip, false)?;
- let patch = vcs::diff_directories(diff_root.path(), "a", "b", options.context_lines)?;
- Ok(PreparedUpdate {
- src,
- old_commit,
- old_answers_path: answers_path,
- new_template,
- new_renderer,
- new_answers_rel,
- new_answers_bytes,
- new_ctx,
- new_skip_filter,
- diff_root,
- patch,
- })
- }
- fn resolve_user_settings(options: &CopyOptions) -> UserSettings {
- options
- .user_settings
- .clone()
- .unwrap_or_else(UserSettings::load_default)
- }
- fn check_min_copier_version(config: &TemplateConfig, reporter: &dyn Reporter) -> Result<()> {
- let Some(required_raw) = config.settings.min_copier_version.as_deref() else {
- return Ok(());
- };
- let trimmed = required_raw.trim();
- if trimmed.is_empty() {
- return Ok(());
- }
- if let (Some(required), Some(supported)) = (
- Pep440Version::parse(trimmed),
- Pep440Version::parse(COPIER_COMPAT_VERSION),
- ) {
- if required > supported {
- return Err(RoneoError::IncompatibleCopierVersion {
- required: trimmed.to_string(),
- supported: COPIER_COMPAT_VERSION.to_string(),
- });
- }
- if required.release.first() < supported.release.first() {
- reporter.emit(ActionEvent::Warning(format!(
- "Template targets older Copier {trimmed} (Roneo targets Copier {COPIER_COMPAT_VERSION})."
- )));
- }
- }
- Ok(())
- }
- fn folder_name_for(dst_path: &Path) -> String {
- dst_path
- .file_name()
- .map(|s| s.to_string_lossy().into_owned())
- .or_else(|| {
- fs::canonicalize(dst_path)
- .or_else(|_| std::env::current_dir())
- .ok()
- .and_then(|p| p.file_name().map(|s| s.to_string_lossy().into_owned()))
- })
- .unwrap_or_default()
- }
- fn build_active_extensions(
- resolved: &ResolvedTemplate,
- options: &CopyOptions,
- is_trusted: bool,
- ) -> Result<ExtensionRegistry> {
- let mut reg = options.extensions.clone();
- if resolved.config.settings.roneo_plugins.is_empty() {
- return Ok(reg);
- }
- if !is_trusted {
- return Err(RoneoError::UnsafeTemplate(
- "Template declares `_roneo_plugins` (WebAssembly extensions)".into(),
- ));
- }
- for rel_plugin in &resolved.config.settings.roneo_plugins {
- if Path::new(rel_plugin).is_absolute() {
- return Err(RoneoError::Plugin(format!(
- "Template plugin '{rel_plugin}' must be a relative path inside the template"
- )));
- }
- if let Some(bytes) = resolved.read_bytes(rel_plugin) {
- reg.add_wasm_bytes(&bytes)?;
- } else {
- return Err(RoneoError::Plugin(format!(
- "Template plugin '{rel_plugin}' not found inside template"
- )));
- }
- }
- Ok(reg)
- }
- fn build_prompt_initial_context(
- resolved: &ResolvedTemplate,
- dst_path: &Path,
- renderer: &TemplateRenderer,
- options: &CopyOptions,
- operation: &str,
- is_trusted: bool,
- ) -> Result<IndexMap<String, JsonValue>> {
- let mut init = IndexMap::new();
- let answers_file = options.answers_file.as_ref().map_or_else(
- || resolved.config.settings.answers_file.clone(),
- |p| p.to_string_lossy().into_owned(),
- );
- let conf = CopierConf {
- src_path: resolved.local_path.to_string_lossy().into_owned(),
- dst_path: dst_path.to_string_lossy().into_owned(),
- answers_file,
- vcs_ref: resolved.commit.clone(),
- vcs_ref_hash: resolved.commit_hash.clone(),
- sep: std::path::MAIN_SEPARATOR.to_string(),
- os: std::env::consts::OS.to_string(),
- stage: "prompt".to_string(),
- overwrite: options.overwrite,
- pretend: options.pretend,
- quiet: options.quiet,
- r#unsafe: is_trusted,
- cleanup_on_error: options.cleanup_on_error,
- context_lines: options.context_lines,
- exclude: options.exclude.clone(),
- skip_if_exists: options.skip_if_exists.clone(),
- };
- if let Ok(val) = serde_json::to_value(&conf) {
- init.insert("_copier_conf".into(), val);
- }
- init.insert("_copier_python".into(), JsonValue::String("python3".into()));
- init.insert(
- "_copier_operation".into(),
- JsonValue::String(operation.to_string()),
- );
- init.insert(
- "_folder_name".into(),
- JsonValue::String(folder_name_for(dst_path)),
- );
- if !resolved.config.settings.external_data.is_empty() {
- let mut seed = init.clone();
- for (k, v) in &options.data {
- seed.insert(k.clone(), v.clone());
- }
- let ext_data = load_external_data(resolved, dst_path, renderer, &seed, is_trusted)?;
- init.insert("_external_data".into(), ext_data);
- }
- Ok(init)
- }
- /// Load `_external_data` YAML/JSON files (matching Copier 9's `_external_data` setting).
- /// Untrusted templates are confined to files inside the template root or destination directory.
- fn load_external_data(
- resolved: &ResolvedTemplate,
- dst_path: &Path,
- renderer: &TemplateRenderer,
- ctx: &IndexMap<String, JsonValue>,
- is_trusted: bool,
- ) -> Result<JsonValue> {
- let mut out = serde_json::Map::new();
- let reader = resolved.file_reader();
- for (key, path_tpl) in &resolved.config.settings.external_data {
- let resolved_path = renderer.render_str(path_tpl, ctx, &format!("_external_data.{key}"))?;
- let trimmed = resolved_path.trim();
- if trimmed.is_empty() {
- continue;
- }
- let raw_opt = reader(trimmed).or_else(|| {
- let p = Path::new(trimmed);
- let escapes = trimmed.contains('\0')
- || p.is_absolute()
- || p.components().any(|c| {
- matches!(
- c,
- std::path::Component::ParentDir
- | std::path::Component::RootDir
- | std::path::Component::Prefix(_)
- )
- });
- if escapes && !is_trusted {
- return None;
- }
- if p.is_absolute() {
- fs::read_to_string(p).ok()
- } else {
- let in_dst = dst_path.join(p);
- let dst_ok = if is_trusted {
- true
- } else {
- fs::canonicalize(dst_path)
- .ok()
- .zip(fs::canonicalize(&in_dst).ok())
- .is_some_and(|(root, cand)| cand.starts_with(root))
- };
- if dst_ok {
- fs::read_to_string(&in_dst).ok()
- } else {
- None
- }
- .or_else(|| is_trusted.then(|| fs::read_to_string(p).ok()).flatten())
- }
- });
- let Some(raw) = raw_opt else {
- return Err(RoneoError::InvalidConfig(format!(
- "Failed to load `_external_data.{key}` from '{trimmed}'"
- )));
- };
- let yaml_val: serde_yaml_ng::Value = serde_yaml_ng::from_str(&raw)?;
- let json_val = serde_json::to_value(yaml_val)?;
- out.insert(key.clone(), json_val);
- }
- Ok(JsonValue::Object(out))
- }
- fn check_trust(
- resolved: &ResolvedTemplate,
- options: &CopyOptions,
- user_settings: &UserSettings,
- active_exts: &ExtensionRegistry,
- reporter: &dyn Reporter,
- ) -> Result<bool> {
- let config = &resolved.config;
- if !config.settings.jinja_extensions.is_empty() && active_exts.is_empty() {
- reporter.emit(ActionEvent::Warning(format!(
- "Template requests Python Jinja extensions ({}) which are not executed in native Rust mode (load a WASM plugin via `--plugin`).",
- config.settings.jinja_extensions.join(", ")
- )));
- }
- let is_trusted =
- options.trust || user_settings.is_trusted(&resolved.original_src, &resolved.resolved_src);
- if !options.skip_tasks && config.requires_trust() && !is_trusted {
- return Err(RoneoError::UnsafeTemplate(
- "Template defines `_tasks` or `_migrations` that execute shell commands".into(),
- ));
- }
- Ok(is_trusted)
- }
- /// Source descriptor for a single file scheduled for parallel rendering & writing.
- enum RenderItemSource {
- Disk {
- src_path: PathBuf,
- is_symlink: bool,
- file_mode: Option<u32>,
- },
- GitBlob {
- tree: Arc<InMemoryGitTree>,
- oid: gix::ObjectId,
- is_executable: bool,
- is_symlink: bool,
- },
- }
- struct PlannedFile {
- rel_src: PathBuf,
- rendered_rel: PathBuf,
- is_template_file: bool,
- extra_vars: Vec<(String, JsonValue)>,
- source: RenderItemSource,
- }
- #[derive(Debug, Clone, Copy, PartialEq, Eq)]
- enum OverwritePolicy {
- Force,
- Prompt,
- Skip,
- }
- #[derive(Debug)]
- enum PendingContent {
- File {
- bytes: Vec<u8>,
- src_for_perms: Option<PathBuf>,
- is_executable: bool,
- },
- Symlink {
- target: String,
- },
- }
- #[derive(Debug)]
- struct PendingOverwrite {
- rel: PathBuf,
- dst_entry_path: PathBuf,
- content: PendingContent,
- }
- #[derive(Debug)]
- enum FileOutcome {
- Created(PathBuf),
- Overwritten(PathBuf),
- Identical(PathBuf),
- Skipped(PathBuf),
- NeedsOverwriteConfirm(PendingOverwrite),
- }
- #[allow(clippy::too_many_arguments)]
- fn render_into_destination(
- resolved: &ResolvedTemplate,
- dst_path: &Path,
- answers: &AnswersMap,
- renderer: &TemplateRenderer,
- extensions: &ExtensionRegistry,
- options: &CopyOptions,
- stage: &str,
- is_trusted: bool,
- prompter: Option<&dyn Prompter>,
- reporter: &dyn Reporter,
- ) -> Result<(OperationReport, IndexMap<String, JsonValue>)> {
- let settings = &resolved.config.settings;
- let combined = answers.combined();
- let persistable = answers.persistable();
- let answers_rel_str = match &options.answers_file {
- Some(p) => p.to_string_lossy().into_owned(),
- None => renderer.render_str(&settings.answers_file, &combined, "_answers_file")?,
- };
- let answers_rel = PathBuf::from(&answers_rel_str);
- if options.answers_file.is_none()
- && (answers_rel_str.contains('\0')
- || answers_rel.is_absolute()
- || answers_rel.components().any(|c| {
- matches!(
- c,
- std::path::Component::ParentDir
- | std::path::Component::RootDir
- | std::path::Component::Prefix(_)
- )
- }))
- {
- return Err(RoneoError::InvalidConfig(format!(
- "`_answers_file` '{answers_rel_str}' escapes destination directory"
- )));
- }
- let rendered_subdir = match &settings.subdirectory {
- Some(sub_tpl) => Some(renderer.render_str(sub_tpl, &combined, "_subdirectory")?),
- None => None,
- };
- let conf = CopierConf {
- src_path: resolved.local_path.to_string_lossy().into_owned(),
- dst_path: dst_path.to_string_lossy().into_owned(),
- answers_file: answers_rel_str,
- vcs_ref: resolved.commit.clone(),
- vcs_ref_hash: resolved.commit_hash.clone(),
- sep: std::path::MAIN_SEPARATOR.to_string(),
- os: std::env::consts::OS.to_string(),
- stage: stage.to_string(),
- overwrite: options.overwrite,
- pretend: options.pretend,
- quiet: options.quiet,
- r#unsafe: is_trusted,
- cleanup_on_error: options.cleanup_on_error,
- context_lines: options.context_lines,
- exclude: options.exclude.clone(),
- skip_if_exists: options.skip_if_exists.clone(),
- };
- let mut ctx = build_render_context(&combined, &persistable, &conf);
- ctx.insert("_copier_phase".into(), JsonValue::String("render".into()));
- ctx.insert("_copier_python".into(), JsonValue::String("python3".into()));
- ctx.insert(
- "_copier_operation".into(),
- JsonValue::String(stage.to_string()),
- );
- ctx.insert(
- "_folder_name".into(),
- JsonValue::String(folder_name_for(dst_path)),
- );
- if !settings.external_data.is_empty() {
- let ext_data = load_external_data(resolved, dst_path, renderer, &ctx, is_trusted)?;
- ctx.insert("_external_data".into(), ext_data);
- }
- if !extensions.is_empty() {
- extensions.run_context_hooks("render", &mut ctx)?;
- }
- let mj_ctx = TemplateRenderer::compile_context(&ctx);
- let mut all_excludes = Vec::with_capacity(settings.exclude.len() + options.exclude.len());
- for pat in &settings.exclude {
- let expanded = renderer.render_str_value(pat, &mj_ctx, "_exclude")?;
- // Copier v9.18.0 (#2804): allow multiple newline-separated patterns in a single `_exclude` entry.
- for line in expanded.lines() {
- let trimmed = line.trim();
- if !trimmed.is_empty() {
- all_excludes.push(trimmed.to_string());
- }
- }
- }
- all_excludes.extend(options.exclude.iter().cloned());
- let mut all_skip =
- Vec::with_capacity(settings.skip_if_exists.len() + options.skip_if_exists.len());
- for pat in &settings.skip_if_exists {
- let expanded = renderer.render_str_value(pat, &mj_ctx, "_skip_if_exists")?;
- for line in expanded.lines() {
- let trimmed = line.trim();
- if !trimmed.is_empty() {
- all_skip.push(trimmed.to_string());
- }
- }
- }
- all_skip.extend(options.skip_if_exists.iter().cloned());
- let filter_root = Path::new("");
- let filter = PathFilter::new(
- filter_root,
- &all_excludes,
- &all_skip,
- options.use_default_excludes,
- )?;
- if !options.pretend {
- fs::create_dir_all(dst_path).map_err(|e| RoneoError::io(dst_path, e))?;
- }
- // Phase 1: Walk source tree (either in-memory `gix` tree or disk) and plan ONLY non-excluded files.
- // On GitTree, excluded directories (e.g. `tests/`, `docs/`, disabled `values/*`) are pruned BEFORE
- // reading any subtrees or decompressing any blobs!
- let mut planned_files: Vec<PlannedFile> = Vec::new();
- let mut planned_dirs: HashSet<PathBuf> = HashSet::new();
- match &resolved.backing {
- TemplateBacking::GitTree(tree) => {
- let tree_files = tree.walk_files(
- rendered_subdir.as_deref(),
- |rel_dir, rendered_parent, dir_name, extra_vars| {
- if filter.is_excluded(rel_dir, true) {
- return Ok(Vec::new());
- }
- let expanded = renderer.render_segment_expanded_value(
- dir_name,
- true,
- &settings.templates_suffix,
- &ctx,
- extra_vars,
- &mj_ctx,
- &format!("path:{}", rel_dir.display()),
- )?;
- let mut branches = Vec::with_capacity(expanded.len());
- for seg in expanded {
- let rendered_dir = if rendered_parent.as_os_str().is_empty() {
- PathBuf::from(seg.name)
- } else {
- rendered_parent.join(seg.name)
- };
- if filter.is_excluded(&rendered_dir, true) {
- continue;
- }
- let mut next_vars = extra_vars.to_vec();
- if let Some(binding) = seg.yield_binding {
- next_vars.push(binding);
- }
- branches.push((rendered_dir, next_vars));
- }
- Ok(branches)
- },
- )?;
- for entry in tree_files {
- if filter.is_excluded(&entry.rel_path, false) {
- continue;
- }
- let expanded = renderer.render_segment_expanded_value(
- &entry.file_name,
- false,
- &settings.templates_suffix,
- &ctx,
- &entry.extra_vars,
- &mj_ctx,
- &format!("path:{}", entry.rel_path.display()),
- )?;
- for seg in expanded {
- let rendered_rel = if entry.rendered_parent.as_os_str().is_empty() {
- PathBuf::from(seg.name)
- } else {
- entry.rendered_parent.join(seg.name)
- };
- if filter.is_excluded(&rendered_rel, false) {
- continue;
- }
- if let Some(parent) = rendered_rel.parent()
- && !parent.as_os_str().is_empty()
- {
- planned_dirs.insert(parent.to_path_buf());
- }
- let mut file_vars = entry.extra_vars.clone();
- if let Some(binding) = seg.yield_binding {
- file_vars.push(binding);
- }
- planned_files.push(PlannedFile {
- rel_src: entry.rel_path.clone(),
- rendered_rel,
- is_template_file: seg.is_template_file,
- extra_vars: file_vars,
- source: RenderItemSource::GitBlob {
- tree: Arc::clone(tree),
- oid: entry.oid,
- is_executable: entry.is_executable,
- is_symlink: entry.is_symlink,
- },
- });
- }
- }
- }
- TemplateBacking::Disk(_) => {
- let content_root = resolved.disk_content_root(rendered_subdir.as_deref())?;
- let plan_ctx = PlanCtx {
- root: &content_root,
- follow_symlinks: !settings.preserve_symlinks,
- templates_suffix: &settings.templates_suffix,
- renderer,
- base_ctx: &ctx,
- mj_ctx: &mj_ctx,
- filter: &filter,
- };
- plan_disk_dir(
- &plan_ctx,
- &content_root,
- Path::new(""),
- &[],
- &mut planned_dirs,
- &mut planned_files,
- )?;
- }
- }
- // Create all unique target directories upfront once (avoids redundant create_dir_all races in parallel).
- if !options.pretend {
- for dir in &planned_dirs {
- let full_dir = dst_path.join(dir);
- if !full_dir.exists() {
- fs::create_dir_all(&full_dir).map_err(|e| RoneoError::io(&full_dir, e))?;
- }
- }
- }
- let answers_file_written = planned_files.iter().any(|f| f.rendered_rel == answers_rel);
- let overwrite_policy = if options.overwrite {
- OverwritePolicy::Force
- } else if prompter.is_some() && !options.defaults && !options.pretend {
- OverwritePolicy::Prompt
- } else {
- OverwritePolicy::Skip
- };
- // Phase 2: Render & write files in parallel using `rayon`, reusing ONE thread-local
- // `gix::Repository` per worker thread (hot pack delta cache across all blobs!).
- let git_tree_opt = match &resolved.backing {
- TemplateBacking::GitTree(tree) => Some(Arc::clone(tree)),
- TemplateBacking::Disk(_) => None,
- };
- let file_ctx = FileRenderCtx {
- dst_path,
- renderer,
- base_ctx: &ctx,
- shared_mj_ctx: &mj_ctx,
- filter: &filter,
- preserve_symlinks: settings.preserve_symlinks,
- overwrite_policy,
- pretend: options.pretend,
- };
- let outcomes: Vec<FileOutcome> = planned_files
- .par_iter()
- .map_init(
- || git_tree_opt.as_ref().map(|t| t.thread_local_repo()),
- |thread_repo, item| process_planned_file(&file_ctx, item, thread_repo.as_ref()),
- )
- .collect::<Result<Vec<_>>>()?;
- let mut created = 0usize;
- let mut updated = 0usize;
- let mut skipped = 0usize;
- let mut overwrite_all = false;
- for outcome in outcomes {
- match outcome {
- FileOutcome::Created(rel) => {
- created += 1;
- reporter.emit(ActionEvent::Create(rel));
- }
- FileOutcome::Overwritten(rel) => {
- updated += 1;
- reporter.emit(ActionEvent::Overwrite(rel));
- }
- FileOutcome::Identical(rel) => {
- reporter.emit(ActionEvent::Identical(rel));
- }
- FileOutcome::Skipped(rel) => {
- skipped += 1;
- reporter.emit(ActionEvent::Skip(rel));
- }
- FileOutcome::NeedsOverwriteConfirm(pending) => {
- let should_write = if overwrite_all {
- true
- } else if let Some(p) = prompter {
- match p.confirm_overwrite(&pending.rel)? {
- OverwriteChoice::Yes => true,
- OverwriteChoice::All => {
- overwrite_all = true;
- true
- }
- OverwriteChoice::No => false,
- OverwriteChoice::Quit => return Err(RoneoError::UserAborted),
- }
- } else {
- false
- };
- if should_write {
- apply_pending_overwrite(&pending)?;
- updated += 1;
- reporter.emit(ActionEvent::Overwrite(pending.rel));
- } else {
- skipped += 1;
- reporter.emit(ActionEvent::Skip(pending.rel));
- }
- }
- }
- }
- let answers_dst = dst_path.join(&answers_rel);
- if !answers_file_written {
- let existed = answers_dst.exists();
- if !options.pretend {
- answers.save(&answers_dst)?;
- }
- if existed {
- updated += 1;
- reporter.emit(ActionEvent::Overwrite(answers_rel));
- } else {
- created += 1;
- reporter.emit(ActionEvent::Create(answers_rel));
- }
- }
- Ok((
- OperationReport {
- src_path: resolved.original_src.clone(),
- dst_path: dst_path.to_path_buf(),
- commit: resolved.commit.clone(),
- answers_file: answers_dst,
- created,
- updated,
- skipped,
- conflicts: Vec::new(),
- },
- ctx,
- ))
- }
- fn apply_pending_overwrite(pending: &PendingOverwrite) -> Result<()> {
- if let Some(parent) = pending.dst_entry_path.parent()
- && !parent.exists()
- {
- fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?;
- }
- match &pending.content {
- PendingContent::Symlink { target } => {
- let _ = fs::remove_file(&pending.dst_entry_path);
- create_symlink(Path::new(target), &pending.dst_entry_path)
- }
- PendingContent::File {
- bytes,
- src_for_perms,
- is_executable,
- } => {
- // Copier v9.18.2: unlink an existing destination symlink before writing a regular file.
- if pending
- .dst_entry_path
- .symlink_metadata()
- .is_ok_and(|m| m.file_type().is_symlink())
- {
- let _ = fs::remove_file(&pending.dst_entry_path);
- }
- fs::write(&pending.dst_entry_path, bytes)
- .map_err(|e| RoneoError::io(&pending.dst_entry_path, e))?;
- if let Some(src) = src_for_perms {
- copy_permissions(src, &pending.dst_entry_path)?;
- } else if *is_executable {
- set_executable(&pending.dst_entry_path)?;
- }
- Ok(())
- }
- }
- }
- struct PlanCtx<'a> {
- root: &'a Path,
- follow_symlinks: bool,
- templates_suffix: &'a str,
- renderer: &'a TemplateRenderer,
- base_ctx: &'a IndexMap<String, JsonValue>,
- mj_ctx: &'a minijinja::Value,
- filter: &'a PathFilter,
- }
- fn plan_disk_dir(
- pctx: &PlanCtx<'_>,
- current: &Path,
- rendered_parent: &Path,
- extra_vars: &[(String, JsonValue)],
- planned_dirs: &mut HashSet<PathBuf>,
- planned_files: &mut Vec<PlannedFile>,
- ) -> Result<()> {
- let mut entries: Vec<_> = fs::read_dir(current)
- .map_err(|e| RoneoError::io(current, e))?
- .collect::<std::result::Result<Vec<_>, _>>()
- .map_err(|e| RoneoError::io(current, e))?;
- entries.sort_by_key(fs::DirEntry::file_name);
- for entry in entries {
- let abs_path = entry.path();
- let rel_path = abs_path
- .strip_prefix(pctx.root)
- .map_or_else(|_| PathBuf::from(entry.file_name()), Path::to_path_buf);
- let sym_meta = fs::symlink_metadata(&abs_path).map_err(|e| RoneoError::io(&abs_path, e))?;
- let is_symlink = sym_meta.file_type().is_symlink();
- let is_dir = if is_symlink && pctx.follow_symlinks {
- fs::metadata(&abs_path).is_ok_and(|m| m.is_dir())
- } else {
- sym_meta.is_dir()
- };
- if pctx.filter.is_excluded(&rel_path, is_dir) {
- continue;
- }
- let name = entry.file_name().to_string_lossy().into_owned();
- let expanded = pctx.renderer.render_segment_expanded_value(
- &name,
- is_dir,
- pctx.templates_suffix,
- pctx.base_ctx,
- extra_vars,
- pctx.mj_ctx,
- &format!("path:{}", rel_path.display()),
- )?;
- for seg in expanded {
- let rendered_rel = if rendered_parent.as_os_str().is_empty() {
- PathBuf::from(seg.name)
- } else {
- rendered_parent.join(seg.name)
- };
- if pctx.filter.is_excluded(&rendered_rel, is_dir) {
- continue;
- }
- let mut next_vars = extra_vars.to_vec();
- if let Some(binding) = seg.yield_binding {
- next_vars.push(binding);
- }
- if is_dir {
- planned_dirs.insert(rendered_rel.clone());
- plan_disk_dir(
- pctx,
- &abs_path,
- &rendered_rel,
- &next_vars,
- planned_dirs,
- planned_files,
- )?;
- } else {
- if let Some(parent) = rendered_rel.parent()
- && !parent.as_os_str().is_empty()
- {
- planned_dirs.insert(parent.to_path_buf());
- }
- let file_mode = if is_symlink {
- None
- } else {
- file_mode_from_metadata(&sym_meta)
- };
- planned_files.push(PlannedFile {
- rel_src: rel_path.clone(),
- rendered_rel,
- is_template_file: seg.is_template_file,
- extra_vars: next_vars,
- source: RenderItemSource::Disk {
- src_path: abs_path.clone(),
- is_symlink,
- file_mode,
- },
- });
- }
- }
- }
- Ok(())
- }
- struct FileRenderCtx<'a> {
- dst_path: &'a Path,
- renderer: &'a TemplateRenderer,
- base_ctx: &'a IndexMap<String, JsonValue>,
- shared_mj_ctx: &'a minijinja::Value,
- filter: &'a PathFilter,
- preserve_symlinks: bool,
- overwrite_policy: OverwritePolicy,
- pretend: bool,
- }
- fn process_planned_file(
- fctx: &FileRenderCtx<'_>,
- item: &PlannedFile,
- thread_repo: Option<&gix::Repository>,
- ) -> Result<FileOutcome> {
- let overlay_ctx = if item.extra_vars.is_empty() {
- None
- } else {
- Some(TemplateRenderer::compile_context_with_extra(
- fctx.base_ctx,
- &item.extra_vars,
- ))
- };
- let ctx = overlay_ctx.as_ref().unwrap_or(fctx.shared_mj_ctx);
- let dst_entry_path = fctx.dst_path.join(&item.rendered_rel);
- // Handle symlinks when `_preserve_symlinks` is enabled.
- let is_symlink = match &item.source {
- RenderItemSource::Disk { is_symlink, .. }
- | RenderItemSource::GitBlob { is_symlink, .. } => *is_symlink,
- };
- if fctx.preserve_symlinks && is_symlink {
- let raw_target = match &item.source {
- RenderItemSource::Disk { src_path, .. } => fs::read_link(src_path)
- .map_err(|e| RoneoError::io(src_path, e))?
- .to_string_lossy()
- .into_owned(),
- RenderItemSource::GitBlob { tree, oid, .. } => {
- let bytes = match thread_repo {
- Some(repo) => InMemoryGitTree::read_blob_with_repo(repo, *oid)?,
- None => tree.read_blob_oid(*oid)?,
- };
- String::from_utf8_lossy(&bytes).into_owned()
- }
- };
- let rendered_target = fctx.renderer.render_str_value(
- &raw_target,
- ctx,
- &format!("symlink:{}", item.rel_src.display()),
- )?;
- let exists = dst_entry_path.symlink_metadata().is_ok();
- if exists {
- match fctx.overwrite_policy {
- OverwritePolicy::Force => {}
- OverwritePolicy::Prompt => {
- return Ok(FileOutcome::NeedsOverwriteConfirm(PendingOverwrite {
- rel: item.rendered_rel.clone(),
- dst_entry_path,
- content: PendingContent::Symlink {
- target: rendered_target,
- },
- }));
- }
- OverwritePolicy::Skip => {
- return Ok(FileOutcome::Skipped(item.rendered_rel.clone()));
- }
- }
- }
- if !fctx.pretend {
- verify_no_symlink_in_ancestors(fctx.dst_path, &item.rendered_rel)?;
- if let Some(parent) = dst_entry_path.parent()
- && !parent.exists()
- {
- fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?;
- }
- if exists {
- let _ = fs::remove_file(&dst_entry_path);
- }
- create_symlink(Path::new(&rendered_target), &dst_entry_path)?;
- }
- return Ok(if exists {
- FileOutcome::Overwritten(item.rendered_rel.clone())
- } else {
- FileOutcome::Created(item.rendered_rel.clone())
- });
- }
- // Fast path: check `_skip_if_exists` before reading/rendering if destination already exists
- // (use `symlink_metadata` so broken destination symlinks are also detected, Copier v9.18.2).
- let dst_meta = dst_entry_path.symlink_metadata().ok();
- let exists = dst_meta.is_some();
- let dst_is_symlink = dst_meta.is_some_and(|m| m.file_type().is_symlink());
- if exists && fctx.filter.should_skip_if_exists(&item.rendered_rel, false) {
- return Ok(FileOutcome::Skipped(item.rendered_rel.clone()));
- }
- // Read raw source bytes (reusing thread-local `gix::Repository` pack cache or disk).
- let raw_bytes = match &item.source {
- RenderItemSource::Disk { src_path, .. } => {
- fs::read(src_path).map_err(|e| RoneoError::io(src_path, e))?
- }
- RenderItemSource::GitBlob { tree, oid, .. } => match thread_repo {
- Some(repo) => InMemoryGitTree::read_blob_with_repo(repo, *oid)?,
- None => tree.read_blob_oid(*oid)?,
- },
- };
- let new_bytes = if item.is_template_file {
- let raw_text = String::from_utf8(raw_bytes).map_err(|e| {
- RoneoError::TemplateSource(format!(
- "Template file '{}' is not valid UTF-8: {e}",
- item.rel_src.display()
- ))
- })?;
- let rendered_text =
- fctx.renderer
- .render_str_value(&raw_text, ctx, &item.rel_src.to_string_lossy())?;
- rendered_text.into_bytes()
- } else {
- raw_bytes
- };
- if exists {
- if !dst_is_symlink
- && let Ok(existing_bytes) = fs::read(&dst_entry_path)
- && existing_bytes == new_bytes
- {
- return Ok(FileOutcome::Identical(item.rendered_rel.clone()));
- }
- match fctx.overwrite_policy {
- OverwritePolicy::Force => {}
- OverwritePolicy::Prompt => {
- let (src_for_perms, is_executable) = match &item.source {
- RenderItemSource::Disk { src_path, .. } => (Some(src_path.clone()), false),
- RenderItemSource::GitBlob { is_executable, .. } => (None, *is_executable),
- };
- return Ok(FileOutcome::NeedsOverwriteConfirm(PendingOverwrite {
- rel: item.rendered_rel.clone(),
- dst_entry_path,
- content: PendingContent::File {
- bytes: new_bytes,
- src_for_perms,
- is_executable,
- },
- }));
- }
- OverwritePolicy::Skip => {
- return Ok(FileOutcome::Skipped(item.rendered_rel.clone()));
- }
- }
- }
- if !fctx.pretend {
- verify_no_symlink_in_ancestors(fctx.dst_path, &item.rendered_rel)?;
- if let Some(parent) = dst_entry_path.parent()
- && !parent.exists()
- {
- fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?;
- }
- // Copier v9.18.2: replace an existing symlink instead of writing through it.
- if dst_is_symlink {
- let _ = fs::remove_file(&dst_entry_path);
- }
- fs::write(&dst_entry_path, &new_bytes).map_err(|e| RoneoError::io(&dst_entry_path, e))?;
- match &item.source {
- RenderItemSource::Disk {
- src_path,
- file_mode,
- ..
- } => {
- if let Some(mode) = file_mode {
- set_file_mode(&dst_entry_path, *mode)?;
- } else {
- copy_permissions(src_path, &dst_entry_path)?;
- }
- }
- RenderItemSource::GitBlob { is_executable, .. } => {
- if *is_executable {
- set_executable(&dst_entry_path)?;
- }
- }
- }
- }
- Ok(if exists {
- FileOutcome::Overwritten(item.rendered_rel.clone())
- } else {
- FileOutcome::Created(item.rendered_rel.clone())
- })
- }
- /// Reject writing through any pre-existing symlink directory under `dst_root` so a template
- /// or malicious destination symlink cannot redirect output outside `dst_root`.
- fn verify_no_symlink_in_ancestors(dst_root: &Path, rel: &Path) -> Result<()> {
- let Some(parent_rel) = rel.parent() else {
- return Ok(());
- };
- let mut cur = dst_root.to_path_buf();
- for comp in parent_rel.components() {
- cur.push(comp);
- if let Ok(meta) = cur.symlink_metadata()
- && meta.file_type().is_symlink()
- {
- return Err(RoneoError::InvalidConfig(format!(
- "Refusing to write through symlink directory '{}'",
- cur.display()
- )));
- }
- }
- Ok(())
- }
- #[derive(Default)]
- struct PatchSummary {
- created: Vec<String>,
- modified: Vec<String>,
- deleted: Vec<String>,
- }
- fn summarize_patch(patch: &[u8]) -> PatchSummary {
- let text = String::from_utf8_lossy(patch);
- let mut summary = PatchSummary::default();
- let mut current_path: Option<String> = None;
- let mut is_new = false;
- let mut is_deleted = false;
- let flush = |path: &mut Option<String>,
- is_new: &mut bool,
- is_deleted: &mut bool,
- summary: &mut PatchSummary| {
- if let Some(p) = path.take() {
- if *is_new {
- summary.created.push(p);
- } else if *is_deleted {
- summary.deleted.push(p);
- } else {
- summary.modified.push(p);
- }
- }
- *is_new = false;
- *is_deleted = false;
- };
- for line in text.lines() {
- if let Some(rest) = line.strip_prefix("diff --git ") {
- flush(
- &mut current_path,
- &mut is_new,
- &mut is_deleted,
- &mut summary,
- );
- // Handles standard `a/foo b/foo` as well as `--no-index --no-prefix` `b/foo b/foo` (new)
- // and `a/foo a/foo` (deleted).
- if let Some((_, b_part)) = rest.split_once(" b/") {
- current_path = Some(b_part.to_string());
- } else if let Some((_, a_part)) = rest.split_once(" a/") {
- current_path = Some(a_part.to_string());
- }
- } else if line.starts_with("new file mode") {
- is_new = true;
- } else if line.starts_with("deleted file mode") {
- is_deleted = true;
- }
- }
- flush(
- &mut current_path,
- &mut is_new,
- &mut is_deleted,
- &mut summary,
- );
- summary
- }