forgeFRENParcourir les dépôts

roneocratesroneo-coresrcworker.rs

0518da6beb3fd562b82c5b5c2798b72e0d1591b2

At commit 0518da6

1 979 lines · 67.3 KiBRustRaw
  1. use std::collections::HashSet;
  2. use std::fs;
  3. use std::path::{Path, PathBuf};
  4. use std::sync::Arc;
  5. use indexmap::IndexMap;
  6. use rayon::prelude::*;
  7. use serde_json::Value as JsonValue;
  8. use crate::answers::AnswersMap;
  9. use crate::config::TemplateConfig;
  10. use crate::error::{Result, RoneoError};
  11. use crate::filter::PathFilter;
  12. use crate::fs_util::{
  13. TempDir, copy_permissions, create_symlink, file_mode_from_metadata, set_executable,
  14. set_file_mode,
  15. };
  16. use crate::plugin::{ExtensionInitContext, ExtensionRegistry};
  17. use crate::prompt::{
  18. AnswerCollectionOptions, NonInteractivePrompter, OverwriteChoice, Prompter, collect_answers,
  19. };
  20. use crate::renderer::{CopierConf, TemplateRenderer, build_render_context};
  21. use crate::settings::UserSettings;
  22. use crate::tasks::{MigrationRun, MigrationStage, run_migrations, run_tasks};
  23. use crate::template::{ResolvedTemplate, TemplateBacking};
  24. use crate::vcs::{self, ConflictMode, InMemoryGitTree};
  25. use crate::version::Pep440Version;
  26. /// Highest Copier specification version that Ronéo declares compatibility with
  27. /// when validating `_min_copier_version`.
  28. pub const COPIER_COMPAT_VERSION: &str = "9.19.1";
  29. /// Options controlling `copy`, `recopy`, and `update`.
  30. #[derive(Debug, Clone)]
  31. pub struct CopyOptions {
  32. pub vcs_ref: Option<String>,
  33. pub data: IndexMap<String, JsonValue>,
  34. pub answers_file: Option<PathBuf>,
  35. pub exclude: Vec<String>,
  36. pub skip_if_exists: Vec<String>,
  37. pub use_default_excludes: bool,
  38. pub use_prereleases: bool,
  39. pub overwrite: bool,
  40. pub pretend: bool,
  41. pub defaults: bool,
  42. pub skip_answered: bool,
  43. pub ask_questions: Vec<String>,
  44. pub skip_tasks: bool,
  45. pub trust: bool,
  46. pub conflict_mode: ConflictMode,
  47. pub context_lines: usize,
  48. pub cleanup_on_error: bool,
  49. pub skip_git_check: bool,
  50. pub quiet: bool,
  51. pub user_settings: Option<UserSettings>,
  52. pub extensions: ExtensionRegistry,
  53. }
  54. impl Default for CopyOptions {
  55. fn default() -> Self {
  56. Self {
  57. vcs_ref: None,
  58. data: IndexMap::new(),
  59. answers_file: None,
  60. exclude: Vec::new(),
  61. skip_if_exists: Vec::new(),
  62. use_default_excludes: true,
  63. use_prereleases: false,
  64. overwrite: false,
  65. pretend: false,
  66. defaults: false,
  67. skip_answered: false,
  68. ask_questions: Vec::new(),
  69. skip_tasks: false,
  70. trust: false,
  71. conflict_mode: ConflictMode::Inline,
  72. context_lines: 3,
  73. cleanup_on_error: true,
  74. skip_git_check: false,
  75. quiet: false,
  76. user_settings: None,
  77. extensions: ExtensionRegistry::new(),
  78. }
  79. }
  80. }
  81. /// High-level events emitted during copy/recopy/update for UI/CLI reporting.
  82. #[derive(Debug, Clone)]
  83. pub enum ActionEvent {
  84. Create(PathBuf),
  85. Overwrite(PathBuf),
  86. Update(PathBuf),
  87. Delete(PathBuf),
  88. Identical(PathBuf),
  89. Skip(PathBuf),
  90. Conflict(PathBuf),
  91. RunTask(String),
  92. Message(String),
  93. Warning(String),
  94. }
  95. pub trait Reporter {
  96. fn emit(&self, event: ActionEvent);
  97. }
  98. #[derive(Debug, Default)]
  99. pub struct NoopReporter;
  100. impl Reporter for NoopReporter {
  101. fn emit(&self, _event: ActionEvent) {}
  102. }
  103. /// Summary returned after `copy`, `recopy`, or `update`.
  104. #[derive(Debug, Clone)]
  105. pub struct OperationReport {
  106. pub src_path: String,
  107. pub dst_path: PathBuf,
  108. pub commit: Option<String>,
  109. pub answers_file: PathBuf,
  110. pub created: usize,
  111. pub updated: usize,
  112. pub skipped: usize,
  113. pub conflicts: Vec<String>,
  114. }
  115. /// Result of previewing a 3-way template update via `diff_update`.
  116. #[derive(Debug, Clone)]
  117. pub struct UpdateDiff {
  118. pub src_path: String,
  119. pub from_commit: String,
  120. pub to_commit: Option<String>,
  121. pub patch: String,
  122. pub created: Vec<String>,
  123. pub modified: Vec<String>,
  124. pub deleted: Vec<String>,
  125. }
  126. /// Result of checking whether a newer template version is available (`roneo check-update`).
  127. #[derive(Debug, Clone, serde::Serialize)]
  128. pub struct CheckUpdateReport {
  129. pub src_path: String,
  130. pub current_version: String,
  131. pub latest_version: String,
  132. pub update_available: bool,
  133. }
  134. /// Check whether a newer template version is available for an existing project without
  135. /// modifying any files (matching Copier's `check-update` / `get_update_data`).
  136. pub fn check_update(dst_path: &Path, options: &CopyOptions) -> Result<CheckUpdateReport> {
  137. let answers_path = AnswersMap::find_in_dir(dst_path, options.answers_file.as_deref())
  138. .ok_or_else(|| RoneoError::MissingAnswersFile(dst_path.to_path_buf()))?;
  139. let previous = AnswersMap::load(&answers_path)?;
  140. let src = previous
  141. .src_path()
  142. .ok_or_else(|| RoneoError::InvalidConfig("Answers file is missing `_src_path`".into()))?
  143. .to_string();
  144. let current_commit = previous
  145. .commit()
  146. .ok_or_else(|| {
  147. RoneoError::InvalidConfig(
  148. "Answers file is missing `_commit`. Cannot check updates for a non-git template."
  149. .into(),
  150. )
  151. })?
  152. .to_string();
  153. let current_tpl = ResolvedTemplate::resolve(&src, Some(&current_commit))?;
  154. let latest_tpl = current_tpl.resolve_sibling(None, options.use_prereleases)?;
  155. let latest_commit = latest_tpl
  156. .commit
  157. .clone()
  158. .or_else(|| latest_tpl.commit_hash.clone())
  159. .unwrap_or_else(|| "HEAD".to_string());
  160. let update_available = match (
  161. Pep440Version::parse(&current_commit),
  162. Pep440Version::parse(&latest_commit),
  163. ) {
  164. (Some(cur_ver), Some(lat_ver)) => lat_ver > cur_ver,
  165. _ => match (&current_tpl.commit_hash, &latest_tpl.commit_hash) {
  166. (Some(c), Some(l)) => c != l,
  167. _ => current_commit != latest_commit,
  168. },
  169. };
  170. Ok(CheckUpdateReport {
  171. src_path: src,
  172. current_version: current_commit,
  173. latest_version: latest_commit,
  174. update_available,
  175. })
  176. }
  177. /// Render a new project from `src_path` into `dst_path`.
  178. ///
  179. /// If `dst_path` did not exist prior to `copy` and an error occurs, `dst_path` is automatically
  180. /// removed unless `options.cleanup_on_error` is `false` (Copier's `--no-cleanup`).
  181. pub fn copy(
  182. src_path: &str,
  183. dst_path: &Path,
  184. options: &CopyOptions,
  185. prompter: &dyn Prompter,
  186. reporter: &dyn Reporter,
  187. ) -> Result<OperationReport> {
  188. let dst_existed = dst_path.exists();
  189. let result = copy_inner(src_path, dst_path, options, prompter, reporter);
  190. if result.is_err()
  191. && !dst_existed
  192. && options.cleanup_on_error
  193. && !options.pretend
  194. && dst_path.exists()
  195. {
  196. let _ = fs::remove_dir_all(dst_path);
  197. }
  198. result
  199. }
  200. fn copy_inner(
  201. src_path: &str,
  202. dst_path: &Path,
  203. options: &CopyOptions,
  204. prompter: &dyn Prompter,
  205. reporter: &dyn Reporter,
  206. ) -> Result<OperationReport> {
  207. let resolved = ResolvedTemplate::resolve_with_options(
  208. src_path,
  209. options.vcs_ref.as_deref(),
  210. options.use_prereleases,
  211. )?;
  212. check_min_copier_version(&resolved.config, reporter)?;
  213. let user_settings = resolve_user_settings(options);
  214. let is_trusted_pre =
  215. options.trust || user_settings.is_trusted(&resolved.original_src, &resolved.resolved_src);
  216. let active_exts = build_active_extensions(&resolved, options, is_trusted_pre)?;
  217. let is_trusted = check_trust(&resolved, options, &user_settings, &active_exts, reporter)?;
  218. let file_reader = resolved.file_reader();
  219. let init_ctx = ExtensionInitContext {
  220. template_root: resolved.local_path.clone(),
  221. dst_path: dst_path.to_path_buf(),
  222. file_reader: Arc::clone(&file_reader),
  223. };
  224. let renderer = TemplateRenderer::with_extensions(
  225. &resolved.config.settings.envops,
  226. Some(file_reader),
  227. Some(&active_exts),
  228. Some(&init_ctx),
  229. )?;
  230. if let Some(msg) = &resolved.config.settings.message_before_copy {
  231. let banner = renderer.render_str(msg, &options.data, "_message_before_copy")?;
  232. if !banner.trim().is_empty() {
  233. reporter.emit(ActionEvent::Message(banner));
  234. }
  235. }
  236. let prompt_init_ctx =
  237. build_prompt_initial_context(&resolved, dst_path, &renderer, options, "copy", is_trusted)?;
  238. let mut answers = collect_answers(
  239. &resolved.config,
  240. &renderer,
  241. prompter,
  242. &AnswerCollectionOptions {
  243. data: &options.data,
  244. previous_answers: None,
  245. user_defaults: Some(&user_settings.defaults),
  246. initial_context: Some(&prompt_init_ctx),
  247. extensions: Some(&active_exts),
  248. use_defaults: options.defaults,
  249. skip_answered: options.skip_answered,
  250. ask_questions: &options.ask_questions,
  251. },
  252. )?;
  253. answers.set_src_path(&resolved.original_src);
  254. if let Some(commit) = &resolved.commit {
  255. answers.set_commit(commit);
  256. }
  257. let (report, ctx) = render_into_destination(
  258. &resolved,
  259. dst_path,
  260. &answers,
  261. &renderer,
  262. &active_exts,
  263. options,
  264. "copy",
  265. is_trusted,
  266. Some(prompter),
  267. reporter,
  268. )?;
  269. if !options.skip_tasks && !resolved.config.settings.tasks.is_empty() {
  270. run_tasks(
  271. &resolved.config.settings.tasks,
  272. dst_path,
  273. &renderer,
  274. &ctx,
  275. &[],
  276. options.pretend,
  277. |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())),
  278. )?;
  279. }
  280. if let Some(msg) = &resolved.config.settings.message_after_copy {
  281. let banner = renderer.render_str(msg, &ctx, "_message_after_copy")?;
  282. if !banner.trim().is_empty() {
  283. reporter.emit(ActionEvent::Message(banner));
  284. }
  285. }
  286. Ok(report)
  287. }
  288. /// Re-apply a template onto an existing project using saved answers, without 3-way diffing.
  289. pub fn recopy(
  290. dst_path: &Path,
  291. src_override: Option<&str>,
  292. options: &CopyOptions,
  293. prompter: &dyn Prompter,
  294. reporter: &dyn Reporter,
  295. ) -> Result<OperationReport> {
  296. let answers_path = AnswersMap::find_in_dir(dst_path, options.answers_file.as_deref())
  297. .ok_or_else(|| RoneoError::MissingAnswersFile(dst_path.to_path_buf()))?;
  298. let previous = AnswersMap::load(&answers_path)?;
  299. let src = src_override
  300. .or_else(|| previous.src_path())
  301. .ok_or_else(|| {
  302. RoneoError::InvalidConfig(
  303. "Answers file is missing `_src_path`; pass a template source explicitly".into(),
  304. )
  305. })?;
  306. let resolved = ResolvedTemplate::resolve_with_options(
  307. src,
  308. options.vcs_ref.as_deref(),
  309. options.use_prereleases,
  310. )?;
  311. check_min_copier_version(&resolved.config, reporter)?;
  312. let user_settings = resolve_user_settings(options);
  313. let is_trusted_pre =
  314. options.trust || user_settings.is_trusted(&resolved.original_src, &resolved.resolved_src);
  315. let active_exts = build_active_extensions(&resolved, options, is_trusted_pre)?;
  316. let is_trusted = check_trust(&resolved, options, &user_settings, &active_exts, reporter)?;
  317. let file_reader = resolved.file_reader();
  318. let init_ctx = ExtensionInitContext {
  319. template_root: resolved.local_path.clone(),
  320. dst_path: dst_path.to_path_buf(),
  321. file_reader: Arc::clone(&file_reader),
  322. };
  323. let renderer = TemplateRenderer::with_extensions(
  324. &resolved.config.settings.envops,
  325. Some(file_reader),
  326. Some(&active_exts),
  327. Some(&init_ctx),
  328. )?;
  329. let prompt_init_ctx = build_prompt_initial_context(
  330. &resolved, dst_path, &renderer, options, "recopy", is_trusted,
  331. )?;
  332. let mut answers = collect_answers(
  333. &resolved.config,
  334. &renderer,
  335. prompter,
  336. &AnswerCollectionOptions {
  337. data: &options.data,
  338. previous_answers: Some(&previous),
  339. user_defaults: Some(&user_settings.defaults),
  340. initial_context: Some(&prompt_init_ctx),
  341. extensions: Some(&active_exts),
  342. use_defaults: options.defaults,
  343. skip_answered: options.skip_answered,
  344. ask_questions: &options.ask_questions,
  345. },
  346. )?;
  347. answers.set_src_path(&resolved.original_src);
  348. if let Some(commit) = &resolved.commit {
  349. answers.set_commit(commit);
  350. }
  351. let mut recopy_opts = options.clone();
  352. recopy_opts.overwrite = true;
  353. let (report, ctx) = render_into_destination(
  354. &resolved,
  355. dst_path,
  356. &answers,
  357. &renderer,
  358. &active_exts,
  359. &recopy_opts,
  360. "recopy",
  361. is_trusted,
  362. None,
  363. reporter,
  364. )?;
  365. if !options.skip_tasks && !resolved.config.settings.tasks.is_empty() {
  366. run_tasks(
  367. &resolved.config.settings.tasks,
  368. dst_path,
  369. &renderer,
  370. &ctx,
  371. &[],
  372. options.pretend,
  373. |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())),
  374. )?;
  375. }
  376. Ok(report)
  377. }
  378. /// Update an existing git-tracked project to a newer template version via 3-way merge,
  379. /// preserving local user edits cleanly (Copier's smart update algorithm).
  380. ///
  381. /// Works both when `dst_path` is a Git repository root and when it is a subdirectory inside
  382. /// a Git monorepo.
  383. pub fn update(
  384. dst_path: &Path,
  385. options: &CopyOptions,
  386. prompter: &dyn Prompter,
  387. reporter: &dyn Reporter,
  388. ) -> Result<OperationReport> {
  389. let (git_root, subproject_subdir) = resolve_git_destination(dst_path, options)?;
  390. let wt_status = if options.skip_git_check {
  391. vcs::WorkingTreeStatus {
  392. is_clean: true,
  393. ignored_paths: Vec::new(),
  394. }
  395. } else {
  396. let status = vcs::inspect_working_tree(&git_root)?;
  397. if !options.pretend && !status.is_clean {
  398. return Err(RoneoError::DirtyDestination(dst_path.to_path_buf()));
  399. }
  400. status
  401. };
  402. let prepared = prepare_update_patch(dst_path, options, prompter, reporter, true)?;
  403. // Reject downgrades on PEP 440 versioned templates (matching Copier's DowngradeError).
  404. let new_commit_str = prepared.new_template.commit.as_deref().unwrap_or("");
  405. if let (Some(old_ver), Some(new_ver)) = (
  406. Pep440Version::parse(&prepared.old_commit),
  407. Pep440Version::parse(new_commit_str),
  408. ) && new_ver < old_ver
  409. {
  410. return Err(RoneoError::DowngradeNotSupported {
  411. from: prepared.old_commit,
  412. to: new_commit_str.to_string(),
  413. });
  414. }
  415. let diff_summary = summarize_patch(&prepared.patch);
  416. for path in &diff_summary.created {
  417. reporter.emit(ActionEvent::Create(PathBuf::from(path)));
  418. }
  419. for path in &diff_summary.modified {
  420. reporter.emit(ActionEvent::Update(PathBuf::from(path)));
  421. }
  422. for path in &diff_summary.deleted {
  423. reporter.emit(ActionEvent::Delete(PathBuf::from(path)));
  424. }
  425. if !options.skip_tasks && !prepared.new_template.config.settings.migrations.is_empty() {
  426. run_migrations(
  427. &prepared.new_template.config.settings.migrations,
  428. &MigrationRun {
  429. version_from: &prepared.old_commit,
  430. version_to: new_commit_str,
  431. stage: MigrationStage::Before,
  432. dst_path,
  433. renderer: &prepared.new_renderer,
  434. ctx: &prepared.new_ctx,
  435. pretend: options.pretend,
  436. },
  437. |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())),
  438. )?;
  439. }
  440. // Honor `_skip_if_exists` / `-s`, `.gitignore`-ignored files, AND exclude `.copier-answers.yml`
  441. // from `git apply` (written cleanly afterwards to prevent spurious merge conflicts, matching Copier).
  442. let mut apply_excludes = collect_update_skip_excludes(
  443. dst_path,
  444. subproject_subdir.as_deref(),
  445. &diff_summary,
  446. &prepared.new_skip_filter,
  447. );
  448. let skipped_count = apply_excludes.len();
  449. for ignored in &wt_status.ignored_paths {
  450. apply_excludes.push(ignored.clone());
  451. }
  452. let format_repo_rel = |rel: &Path| -> String {
  453. match subproject_subdir.as_deref() {
  454. Some(sub) if !sub.as_os_str().is_empty() => {
  455. sub.join(rel).to_string_lossy().replace('\\', "/")
  456. }
  457. _ => rel.to_string_lossy().replace('\\', "/"),
  458. }
  459. };
  460. apply_excludes.push(format_repo_rel(&prepared.new_answers_rel));
  461. if let Ok(old_rel) = prepared.old_answers_path.strip_prefix(dst_path)
  462. && old_rel != prepared.new_answers_rel
  463. {
  464. apply_excludes.push(format_repo_rel(old_rel));
  465. }
  466. let old_snapshot_dir = prepared.diff_root.path().join("a");
  467. let new_snapshot_dir = prepared.diff_root.path().join("b");
  468. let mut conflicts = Vec::new();
  469. if !options.pretend && !prepared.patch.is_empty() {
  470. let apply_res = vcs::apply_patch(
  471. &git_root,
  472. subproject_subdir.as_deref(),
  473. &prepared.patch,
  474. options.conflict_mode,
  475. &apply_excludes,
  476. Some((&old_snapshot_dir, &new_snapshot_dir)),
  477. )?;
  478. if apply_res.has_conflicts {
  479. for c in &apply_res.conflicted_files {
  480. reporter.emit(ActionEvent::Conflict(PathBuf::from(c)));
  481. }
  482. if apply_res.conflicted_files.is_empty() && !apply_res.stderr.is_empty() {
  483. reporter.emit(ActionEvent::Warning(apply_res.stderr.clone()));
  484. }
  485. conflicts = apply_res.conflicted_files;
  486. }
  487. }
  488. // Write the updated answers file directly (never conflicted by `git apply`), and clean up
  489. // the previous answers file if `_answers_file` was renamed between template versions.
  490. let answers_dst = dst_path.join(&prepared.new_answers_rel);
  491. if !options.pretend
  492. && let Some(bytes) = &prepared.new_answers_bytes
  493. {
  494. if let Some(parent) = answers_dst.parent() {
  495. fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?;
  496. }
  497. fs::write(&answers_dst, bytes).map_err(|e| RoneoError::io(&answers_dst, e))?;
  498. let old_canon = fs::canonicalize(&prepared.old_answers_path).ok();
  499. let new_canon = fs::canonicalize(&answers_dst).ok();
  500. if old_canon != new_canon && prepared.old_answers_path.is_file() {
  501. let _ = fs::remove_file(&prepared.old_answers_path);
  502. if let Ok(rel) = prepared.old_answers_path.strip_prefix(dst_path) {
  503. reporter.emit(ActionEvent::Delete(rel.to_path_buf()));
  504. }
  505. }
  506. }
  507. if !options.skip_tasks {
  508. if !prepared.new_template.config.settings.migrations.is_empty() {
  509. run_migrations(
  510. &prepared.new_template.config.settings.migrations,
  511. &MigrationRun {
  512. version_from: &prepared.old_commit,
  513. version_to: new_commit_str,
  514. stage: MigrationStage::After,
  515. dst_path,
  516. renderer: &prepared.new_renderer,
  517. ctx: &prepared.new_ctx,
  518. pretend: options.pretend,
  519. },
  520. |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())),
  521. )?;
  522. }
  523. if !prepared.new_template.config.settings.tasks.is_empty() {
  524. run_tasks(
  525. &prepared.new_template.config.settings.tasks,
  526. dst_path,
  527. &prepared.new_renderer,
  528. &prepared.new_ctx,
  529. &[],
  530. options.pretend,
  531. |cmd| reporter.emit(ActionEvent::RunTask(cmd.to_string())),
  532. )?;
  533. }
  534. }
  535. if let Some(msg) = &prepared.new_template.config.settings.message_after_update {
  536. let banner =
  537. prepared
  538. .new_renderer
  539. .render_str(msg, &prepared.new_ctx, "_message_after_update")?;
  540. if !banner.trim().is_empty() {
  541. reporter.emit(ActionEvent::Message(banner));
  542. }
  543. }
  544. Ok(OperationReport {
  545. src_path: prepared.src,
  546. dst_path: dst_path.to_path_buf(),
  547. commit: prepared.new_template.commit,
  548. answers_file: answers_dst,
  549. created: diff_summary.created.len(),
  550. updated: diff_summary.modified.len() + diff_summary.deleted.len(),
  551. skipped: skipped_count,
  552. conflicts,
  553. })
  554. }
  555. /// Preview the exact unified diff that `update` would apply, without modifying `dst_path`.
  556. pub fn diff_update(
  557. dst_path: &Path,
  558. options: &CopyOptions,
  559. prompter: &dyn Prompter,
  560. ) -> Result<UpdateDiff> {
  561. let noop = NoopReporter;
  562. let prepared = prepare_update_patch(dst_path, options, prompter, &noop, false)?;
  563. let summary = summarize_patch(&prepared.patch);
  564. Ok(UpdateDiff {
  565. src_path: prepared.src,
  566. from_commit: prepared.old_commit,
  567. to_commit: prepared.new_template.commit,
  568. patch: String::from_utf8_lossy(&prepared.patch).into_owned(),
  569. created: summary.created,
  570. modified: summary.modified,
  571. deleted: summary.deleted,
  572. })
  573. }
  574. struct PreparedUpdate {
  575. src: String,
  576. old_commit: String,
  577. old_answers_path: PathBuf,
  578. new_template: ResolvedTemplate,
  579. new_renderer: TemplateRenderer,
  580. new_answers_rel: PathBuf,
  581. new_answers_bytes: Option<Vec<u8>>,
  582. new_ctx: IndexMap<String, JsonValue>,
  583. new_skip_filter: PathFilter,
  584. diff_root: TempDir,
  585. patch: Vec<u8>,
  586. }
  587. fn resolve_git_destination(
  588. dst_path: &Path,
  589. options: &CopyOptions,
  590. ) -> Result<(PathBuf, Option<PathBuf>)> {
  591. if let Some(root) = vcs::find_git_worktree_root(dst_path) {
  592. let canon_root = fs::canonicalize(&root).unwrap_or(root);
  593. let canon_dst = fs::canonicalize(dst_path).unwrap_or_else(|_| dst_path.to_path_buf());
  594. let subdir = canon_dst
  595. .strip_prefix(&canon_root)
  596. .ok()
  597. .filter(|p| !p.as_os_str().is_empty())
  598. .map(Path::to_path_buf);
  599. return Ok((canon_root, subdir));
  600. }
  601. if options.skip_git_check {
  602. return Ok((dst_path.to_path_buf(), None));
  603. }
  604. Err(RoneoError::NotAGitRepo(dst_path.to_path_buf()))
  605. }
  606. fn collect_update_skip_excludes(
  607. dst_path: &Path,
  608. subproject_subdir: Option<&Path>,
  609. summary: &PatchSummary,
  610. skip_filter: &PathFilter,
  611. ) -> Vec<String> {
  612. let mut out = Vec::new();
  613. for rel in summary.modified.iter().chain(summary.deleted.iter()) {
  614. let rel_path = Path::new(rel);
  615. if dst_path.join(rel_path).exists() && skip_filter.should_skip_if_exists(rel_path, false) {
  616. let full = match subproject_subdir {
  617. Some(sub) if !sub.as_os_str().is_empty() => {
  618. sub.join(rel_path).to_string_lossy().replace('\\', "/")
  619. }
  620. _ => rel.clone(),
  621. };
  622. out.push(full);
  623. }
  624. }
  625. out
  626. }
  627. /// Shared fast-path engine for both `update` and `diff_update`:
  628. /// - Reuses one `gix::ThreadSafeRepository` for both old & new commits (`resolve_sibling`).
  629. /// - Renders `old_template` into `tmp/a` and `new_template` into `tmp/b` in parallel via `rayon::join`.
  630. /// - Produces the binary unified patch in ONE `git diff --no-index --no-prefix` call (zero `git init/add/commit`
  631. /// and zero working-tree copy/delete).
  632. fn prepare_update_patch(
  633. dst_path: &Path,
  634. options: &CopyOptions,
  635. prompter: &dyn Prompter,
  636. reporter: &dyn Reporter,
  637. enforce_trust: bool,
  638. ) -> Result<PreparedUpdate> {
  639. let answers_path = AnswersMap::find_in_dir(dst_path, options.answers_file.as_deref())
  640. .ok_or_else(|| RoneoError::MissingAnswersFile(dst_path.to_path_buf()))?;
  641. let previous = AnswersMap::load(&answers_path)?;
  642. let src = previous
  643. .src_path()
  644. .ok_or_else(|| RoneoError::InvalidConfig("Answers file is missing `_src_path`".into()))?
  645. .to_string();
  646. let old_commit = previous
  647. .commit()
  648. .ok_or_else(|| {
  649. RoneoError::InvalidConfig(
  650. "Answers file is missing `_commit`. Cannot smart-update a non-git template; use `recopy`."
  651. .into(),
  652. )
  653. })?
  654. .to_string();
  655. let old_template = ResolvedTemplate::resolve(&src, Some(&old_commit))?;
  656. let target_ref = if options.vcs_ref.as_deref() == Some(":current:") {
  657. Some(old_commit.as_str())
  658. } else {
  659. options.vcs_ref.as_deref()
  660. };
  661. let new_template = old_template.resolve_sibling(target_ref, options.use_prereleases)?;
  662. check_min_copier_version(&new_template.config, reporter)?;
  663. let user_settings = resolve_user_settings(options);
  664. let is_trusted_pre = options.trust
  665. || user_settings.is_trusted(&new_template.original_src, &new_template.resolved_src);
  666. let old_exts = build_active_extensions(&old_template, options, is_trusted_pre)?;
  667. let new_exts = build_active_extensions(&new_template, options, is_trusted_pre)?;
  668. let is_trusted = if enforce_trust {
  669. check_trust(&new_template, options, &user_settings, &new_exts, reporter)?
  670. } else {
  671. is_trusted_pre
  672. };
  673. let old_reader = old_template.file_reader();
  674. let new_reader = new_template.file_reader();
  675. let old_init = ExtensionInitContext {
  676. template_root: old_template.local_path.clone(),
  677. dst_path: dst_path.to_path_buf(),
  678. file_reader: Arc::clone(&old_reader),
  679. };
  680. let new_init = ExtensionInitContext {
  681. template_root: new_template.local_path.clone(),
  682. dst_path: dst_path.to_path_buf(),
  683. file_reader: Arc::clone(&new_reader),
  684. };
  685. let old_renderer = TemplateRenderer::with_extensions(
  686. &old_template.config.settings.envops,
  687. Some(old_reader),
  688. Some(&old_exts),
  689. Some(&old_init),
  690. )?;
  691. let new_renderer = TemplateRenderer::with_extensions(
  692. &new_template.config.settings.envops,
  693. Some(new_reader),
  694. Some(&new_exts),
  695. Some(&new_init),
  696. )?;
  697. if enforce_trust && let Some(msg) = &new_template.config.settings.message_before_update {
  698. let banner =
  699. new_renderer.render_str(msg, &previous.combined(), "_message_before_update")?;
  700. if !banner.trim().is_empty() {
  701. reporter.emit(ActionEvent::Message(banner));
  702. }
  703. }
  704. let prompt_init_ctx = build_prompt_initial_context(
  705. &new_template,
  706. dst_path,
  707. &new_renderer,
  708. options,
  709. "update",
  710. is_trusted,
  711. )?;
  712. let mut new_answers = collect_answers(
  713. &new_template.config,
  714. &new_renderer,
  715. prompter,
  716. &AnswerCollectionOptions {
  717. data: &options.data,
  718. previous_answers: Some(&previous),
  719. user_defaults: Some(&user_settings.defaults),
  720. initial_context: Some(&prompt_init_ctx),
  721. extensions: Some(&new_exts),
  722. use_defaults: options.defaults,
  723. skip_answered: options.skip_answered,
  724. ask_questions: &options.ask_questions,
  725. },
  726. )?;
  727. new_answers.set_src_path(&src);
  728. if let Some(commit) = &new_template.commit {
  729. new_answers.set_commit(commit);
  730. }
  731. // One TempDir with sibling `a/` (old snapshot) and `b/` (new snapshot) rendered in parallel.
  732. let diff_root = TempDir::with_prefix("roneo-diff")?;
  733. let old_dir = diff_root.path().join("a");
  734. let new_dir = diff_root.path().join("b");
  735. fs::create_dir(&old_dir).map_err(|e| RoneoError::io(&old_dir, e))?;
  736. fs::create_dir(&new_dir).map_err(|e| RoneoError::io(&new_dir, e))?;
  737. let mut new_temp_opts = options.clone();
  738. new_temp_opts.overwrite = true;
  739. new_temp_opts.pretend = false;
  740. new_temp_opts.skip_tasks = true;
  741. // Copier discussion #2345: also apply the new template's `_exclude` patterns when rendering
  742. // the old snapshot so newly excluded files are not treated as deleted in the diff.
  743. let mut old_temp_opts = new_temp_opts.clone();
  744. for pat in &new_template.config.settings.exclude {
  745. if !pat.contains("{{") && !pat.contains("{%") {
  746. for line in pat.lines() {
  747. let trimmed = line.trim();
  748. if !trimmed.is_empty() {
  749. old_temp_opts.exclude.push(trimmed.to_string());
  750. }
  751. }
  752. }
  753. }
  754. // Reconstruct full `old_answers` (including `when: false` defaults for strict-undefined
  755. // templates) AND render `old_template` IN PARALLEL with rendering `new_template`!
  756. let noop = NoopReporter;
  757. let (old_res, new_res) = rayon::join(
  758. || -> Result<()> {
  759. let old_prompt_init_ctx = build_prompt_initial_context(
  760. &old_template,
  761. dst_path,
  762. &old_renderer,
  763. options,
  764. "update",
  765. is_trusted,
  766. )?;
  767. let mut old_answers = collect_answers(
  768. &old_template.config,
  769. &old_renderer,
  770. &NonInteractivePrompter,
  771. &AnswerCollectionOptions {
  772. data: &previous.user,
  773. previous_answers: Some(&previous),
  774. user_defaults: Some(&user_settings.defaults),
  775. initial_context: Some(&old_prompt_init_ctx),
  776. extensions: Some(&old_exts),
  777. use_defaults: true,
  778. skip_answered: true,
  779. ask_questions: &[],
  780. },
  781. )?;
  782. old_answers.metadata.clone_from(&previous.metadata);
  783. render_into_destination(
  784. &old_template,
  785. &old_dir,
  786. &old_answers,
  787. &old_renderer,
  788. &old_exts,
  789. &old_temp_opts,
  790. "update",
  791. is_trusted,
  792. None,
  793. &noop,
  794. )?;
  795. Ok(())
  796. },
  797. || {
  798. render_into_destination(
  799. &new_template,
  800. &new_dir,
  801. &new_answers,
  802. &new_renderer,
  803. &new_exts,
  804. &new_temp_opts,
  805. "update",
  806. is_trusted,
  807. None,
  808. &noop,
  809. )
  810. },
  811. );
  812. old_res?;
  813. let (new_render_report, new_ctx) = new_res?;
  814. let new_answers_rel = new_render_report
  815. .answers_file
  816. .strip_prefix(&new_dir)
  817. .map_or_else(
  818. |_| {
  819. PathBuf::from(
  820. new_render_report
  821. .answers_file
  822. .file_name()
  823. .unwrap_or_default(),
  824. )
  825. },
  826. Path::to_path_buf,
  827. );
  828. let new_answers_bytes = fs::read(&new_render_report.answers_file).ok();
  829. let mut all_skip = Vec::with_capacity(
  830. new_template.config.settings.skip_if_exists.len() + options.skip_if_exists.len(),
  831. );
  832. for pat in &new_template.config.settings.skip_if_exists {
  833. let expanded = new_renderer.render_str(pat, &new_ctx, "_skip_if_exists")?;
  834. for line in expanded.lines() {
  835. let trimmed = line.trim();
  836. if !trimmed.is_empty() {
  837. all_skip.push(trimmed.to_string());
  838. }
  839. }
  840. }
  841. all_skip.extend(options.skip_if_exists.iter().cloned());
  842. let new_skip_filter = PathFilter::new(Path::new(""), &[], &all_skip, false)?;
  843. let patch = vcs::diff_directories(diff_root.path(), "a", "b", options.context_lines)?;
  844. Ok(PreparedUpdate {
  845. src,
  846. old_commit,
  847. old_answers_path: answers_path,
  848. new_template,
  849. new_renderer,
  850. new_answers_rel,
  851. new_answers_bytes,
  852. new_ctx,
  853. new_skip_filter,
  854. diff_root,
  855. patch,
  856. })
  857. }
  858. fn resolve_user_settings(options: &CopyOptions) -> UserSettings {
  859. options
  860. .user_settings
  861. .clone()
  862. .unwrap_or_else(UserSettings::load_default)
  863. }
  864. fn check_min_copier_version(config: &TemplateConfig, reporter: &dyn Reporter) -> Result<()> {
  865. let Some(required_raw) = config.settings.min_copier_version.as_deref() else {
  866. return Ok(());
  867. };
  868. let trimmed = required_raw.trim();
  869. if trimmed.is_empty() {
  870. return Ok(());
  871. }
  872. if let (Some(required), Some(supported)) = (
  873. Pep440Version::parse(trimmed),
  874. Pep440Version::parse(COPIER_COMPAT_VERSION),
  875. ) {
  876. if required > supported {
  877. return Err(RoneoError::IncompatibleCopierVersion {
  878. required: trimmed.to_string(),
  879. supported: COPIER_COMPAT_VERSION.to_string(),
  880. });
  881. }
  882. if required.release.first() < supported.release.first() {
  883. reporter.emit(ActionEvent::Warning(format!(
  884. "Template targets older Copier {trimmed} (Roneo targets Copier {COPIER_COMPAT_VERSION})."
  885. )));
  886. }
  887. }
  888. Ok(())
  889. }
  890. fn folder_name_for(dst_path: &Path) -> String {
  891. dst_path
  892. .file_name()
  893. .map(|s| s.to_string_lossy().into_owned())
  894. .or_else(|| {
  895. fs::canonicalize(dst_path)
  896. .or_else(|_| std::env::current_dir())
  897. .ok()
  898. .and_then(|p| p.file_name().map(|s| s.to_string_lossy().into_owned()))
  899. })
  900. .unwrap_or_default()
  901. }
  902. fn build_active_extensions(
  903. resolved: &ResolvedTemplate,
  904. options: &CopyOptions,
  905. is_trusted: bool,
  906. ) -> Result<ExtensionRegistry> {
  907. let mut reg = options.extensions.clone();
  908. if resolved.config.settings.roneo_plugins.is_empty() {
  909. return Ok(reg);
  910. }
  911. if !is_trusted {
  912. return Err(RoneoError::UnsafeTemplate(
  913. "Template declares `_roneo_plugins` (WebAssembly extensions)".into(),
  914. ));
  915. }
  916. for rel_plugin in &resolved.config.settings.roneo_plugins {
  917. if Path::new(rel_plugin).is_absolute() {
  918. return Err(RoneoError::Plugin(format!(
  919. "Template plugin '{rel_plugin}' must be a relative path inside the template"
  920. )));
  921. }
  922. if let Some(bytes) = resolved.read_bytes(rel_plugin) {
  923. reg.add_wasm_bytes(&bytes)?;
  924. } else {
  925. return Err(RoneoError::Plugin(format!(
  926. "Template plugin '{rel_plugin}' not found inside template"
  927. )));
  928. }
  929. }
  930. Ok(reg)
  931. }
  932. fn build_prompt_initial_context(
  933. resolved: &ResolvedTemplate,
  934. dst_path: &Path,
  935. renderer: &TemplateRenderer,
  936. options: &CopyOptions,
  937. operation: &str,
  938. is_trusted: bool,
  939. ) -> Result<IndexMap<String, JsonValue>> {
  940. let mut init = IndexMap::new();
  941. let answers_file = options.answers_file.as_ref().map_or_else(
  942. || resolved.config.settings.answers_file.clone(),
  943. |p| p.to_string_lossy().into_owned(),
  944. );
  945. let conf = CopierConf {
  946. src_path: resolved.local_path.to_string_lossy().into_owned(),
  947. dst_path: dst_path.to_string_lossy().into_owned(),
  948. answers_file,
  949. vcs_ref: resolved.commit.clone(),
  950. vcs_ref_hash: resolved.commit_hash.clone(),
  951. sep: std::path::MAIN_SEPARATOR.to_string(),
  952. os: std::env::consts::OS.to_string(),
  953. stage: "prompt".to_string(),
  954. overwrite: options.overwrite,
  955. pretend: options.pretend,
  956. quiet: options.quiet,
  957. r#unsafe: is_trusted,
  958. cleanup_on_error: options.cleanup_on_error,
  959. context_lines: options.context_lines,
  960. exclude: options.exclude.clone(),
  961. skip_if_exists: options.skip_if_exists.clone(),
  962. };
  963. if let Ok(val) = serde_json::to_value(&conf) {
  964. init.insert("_copier_conf".into(), val);
  965. }
  966. init.insert("_copier_python".into(), JsonValue::String("python3".into()));
  967. init.insert(
  968. "_copier_operation".into(),
  969. JsonValue::String(operation.to_string()),
  970. );
  971. init.insert(
  972. "_folder_name".into(),
  973. JsonValue::String(folder_name_for(dst_path)),
  974. );
  975. if !resolved.config.settings.external_data.is_empty() {
  976. let mut seed = init.clone();
  977. for (k, v) in &options.data {
  978. seed.insert(k.clone(), v.clone());
  979. }
  980. let ext_data = load_external_data(resolved, dst_path, renderer, &seed, is_trusted)?;
  981. init.insert("_external_data".into(), ext_data);
  982. }
  983. Ok(init)
  984. }
  985. /// Load `_external_data` YAML/JSON files (matching Copier 9's `_external_data` setting).
  986. /// Untrusted templates are confined to files inside the template root or destination directory.
  987. fn load_external_data(
  988. resolved: &ResolvedTemplate,
  989. dst_path: &Path,
  990. renderer: &TemplateRenderer,
  991. ctx: &IndexMap<String, JsonValue>,
  992. is_trusted: bool,
  993. ) -> Result<JsonValue> {
  994. let mut out = serde_json::Map::new();
  995. let reader = resolved.file_reader();
  996. for (key, path_tpl) in &resolved.config.settings.external_data {
  997. let resolved_path = renderer.render_str(path_tpl, ctx, &format!("_external_data.{key}"))?;
  998. let trimmed = resolved_path.trim();
  999. if trimmed.is_empty() {
  1000. continue;
  1001. }
  1002. let raw_opt = reader(trimmed).or_else(|| {
  1003. let p = Path::new(trimmed);
  1004. let escapes = trimmed.contains('\0')
  1005. || p.is_absolute()
  1006. || p.components().any(|c| {
  1007. matches!(
  1008. c,
  1009. std::path::Component::ParentDir
  1010. | std::path::Component::RootDir
  1011. | std::path::Component::Prefix(_)
  1012. )
  1013. });
  1014. if escapes && !is_trusted {
  1015. return None;
  1016. }
  1017. if p.is_absolute() {
  1018. fs::read_to_string(p).ok()
  1019. } else {
  1020. let in_dst = dst_path.join(p);
  1021. let dst_ok = if is_trusted {
  1022. true
  1023. } else {
  1024. fs::canonicalize(dst_path)
  1025. .ok()
  1026. .zip(fs::canonicalize(&in_dst).ok())
  1027. .is_some_and(|(root, cand)| cand.starts_with(root))
  1028. };
  1029. if dst_ok {
  1030. fs::read_to_string(&in_dst).ok()
  1031. } else {
  1032. None
  1033. }
  1034. .or_else(|| is_trusted.then(|| fs::read_to_string(p).ok()).flatten())
  1035. }
  1036. });
  1037. let Some(raw) = raw_opt else {
  1038. return Err(RoneoError::InvalidConfig(format!(
  1039. "Failed to load `_external_data.{key}` from '{trimmed}'"
  1040. )));
  1041. };
  1042. let yaml_val: serde_yaml_ng::Value = serde_yaml_ng::from_str(&raw)?;
  1043. let json_val = serde_json::to_value(yaml_val)?;
  1044. out.insert(key.clone(), json_val);
  1045. }
  1046. Ok(JsonValue::Object(out))
  1047. }
  1048. fn check_trust(
  1049. resolved: &ResolvedTemplate,
  1050. options: &CopyOptions,
  1051. user_settings: &UserSettings,
  1052. active_exts: &ExtensionRegistry,
  1053. reporter: &dyn Reporter,
  1054. ) -> Result<bool> {
  1055. let config = &resolved.config;
  1056. if !config.settings.jinja_extensions.is_empty() && active_exts.is_empty() {
  1057. reporter.emit(ActionEvent::Warning(format!(
  1058. "Template requests Python Jinja extensions ({}) which are not executed in native Rust mode (load a WASM plugin via `--plugin`).",
  1059. config.settings.jinja_extensions.join(", ")
  1060. )));
  1061. }
  1062. let is_trusted =
  1063. options.trust || user_settings.is_trusted(&resolved.original_src, &resolved.resolved_src);
  1064. if !options.skip_tasks && config.requires_trust() && !is_trusted {
  1065. return Err(RoneoError::UnsafeTemplate(
  1066. "Template defines `_tasks` or `_migrations` that execute shell commands".into(),
  1067. ));
  1068. }
  1069. Ok(is_trusted)
  1070. }
  1071. /// Source descriptor for a single file scheduled for parallel rendering & writing.
  1072. enum RenderItemSource {
  1073. Disk {
  1074. src_path: PathBuf,
  1075. is_symlink: bool,
  1076. file_mode: Option<u32>,
  1077. },
  1078. GitBlob {
  1079. tree: Arc<InMemoryGitTree>,
  1080. oid: gix::ObjectId,
  1081. is_executable: bool,
  1082. is_symlink: bool,
  1083. },
  1084. }
  1085. struct PlannedFile {
  1086. rel_src: PathBuf,
  1087. rendered_rel: PathBuf,
  1088. is_template_file: bool,
  1089. extra_vars: Vec<(String, JsonValue)>,
  1090. source: RenderItemSource,
  1091. }
  1092. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  1093. enum OverwritePolicy {
  1094. Force,
  1095. Prompt,
  1096. Skip,
  1097. }
  1098. #[derive(Debug)]
  1099. enum PendingContent {
  1100. File {
  1101. bytes: Vec<u8>,
  1102. src_for_perms: Option<PathBuf>,
  1103. is_executable: bool,
  1104. },
  1105. Symlink {
  1106. target: String,
  1107. },
  1108. }
  1109. #[derive(Debug)]
  1110. struct PendingOverwrite {
  1111. rel: PathBuf,
  1112. dst_entry_path: PathBuf,
  1113. content: PendingContent,
  1114. }
  1115. #[derive(Debug)]
  1116. enum FileOutcome {
  1117. Created(PathBuf),
  1118. Overwritten(PathBuf),
  1119. Identical(PathBuf),
  1120. Skipped(PathBuf),
  1121. NeedsOverwriteConfirm(PendingOverwrite),
  1122. }
  1123. #[allow(clippy::too_many_arguments)]
  1124. fn render_into_destination(
  1125. resolved: &ResolvedTemplate,
  1126. dst_path: &Path,
  1127. answers: &AnswersMap,
  1128. renderer: &TemplateRenderer,
  1129. extensions: &ExtensionRegistry,
  1130. options: &CopyOptions,
  1131. stage: &str,
  1132. is_trusted: bool,
  1133. prompter: Option<&dyn Prompter>,
  1134. reporter: &dyn Reporter,
  1135. ) -> Result<(OperationReport, IndexMap<String, JsonValue>)> {
  1136. let settings = &resolved.config.settings;
  1137. let combined = answers.combined();
  1138. let persistable = answers.persistable();
  1139. let answers_rel_str = match &options.answers_file {
  1140. Some(p) => p.to_string_lossy().into_owned(),
  1141. None => renderer.render_str(&settings.answers_file, &combined, "_answers_file")?,
  1142. };
  1143. let answers_rel = PathBuf::from(&answers_rel_str);
  1144. if options.answers_file.is_none()
  1145. && (answers_rel_str.contains('\0')
  1146. || answers_rel.is_absolute()
  1147. || answers_rel.components().any(|c| {
  1148. matches!(
  1149. c,
  1150. std::path::Component::ParentDir
  1151. | std::path::Component::RootDir
  1152. | std::path::Component::Prefix(_)
  1153. )
  1154. }))
  1155. {
  1156. return Err(RoneoError::InvalidConfig(format!(
  1157. "`_answers_file` '{answers_rel_str}' escapes destination directory"
  1158. )));
  1159. }
  1160. let rendered_subdir = match &settings.subdirectory {
  1161. Some(sub_tpl) => Some(renderer.render_str(sub_tpl, &combined, "_subdirectory")?),
  1162. None => None,
  1163. };
  1164. let conf = CopierConf {
  1165. src_path: resolved.local_path.to_string_lossy().into_owned(),
  1166. dst_path: dst_path.to_string_lossy().into_owned(),
  1167. answers_file: answers_rel_str,
  1168. vcs_ref: resolved.commit.clone(),
  1169. vcs_ref_hash: resolved.commit_hash.clone(),
  1170. sep: std::path::MAIN_SEPARATOR.to_string(),
  1171. os: std::env::consts::OS.to_string(),
  1172. stage: stage.to_string(),
  1173. overwrite: options.overwrite,
  1174. pretend: options.pretend,
  1175. quiet: options.quiet,
  1176. r#unsafe: is_trusted,
  1177. cleanup_on_error: options.cleanup_on_error,
  1178. context_lines: options.context_lines,
  1179. exclude: options.exclude.clone(),
  1180. skip_if_exists: options.skip_if_exists.clone(),
  1181. };
  1182. let mut ctx = build_render_context(&combined, &persistable, &conf);
  1183. ctx.insert("_copier_phase".into(), JsonValue::String("render".into()));
  1184. ctx.insert("_copier_python".into(), JsonValue::String("python3".into()));
  1185. ctx.insert(
  1186. "_copier_operation".into(),
  1187. JsonValue::String(stage.to_string()),
  1188. );
  1189. ctx.insert(
  1190. "_folder_name".into(),
  1191. JsonValue::String(folder_name_for(dst_path)),
  1192. );
  1193. if !settings.external_data.is_empty() {
  1194. let ext_data = load_external_data(resolved, dst_path, renderer, &ctx, is_trusted)?;
  1195. ctx.insert("_external_data".into(), ext_data);
  1196. }
  1197. if !extensions.is_empty() {
  1198. extensions.run_context_hooks("render", &mut ctx)?;
  1199. }
  1200. let mj_ctx = TemplateRenderer::compile_context(&ctx);
  1201. let mut all_excludes = Vec::with_capacity(settings.exclude.len() + options.exclude.len());
  1202. for pat in &settings.exclude {
  1203. let expanded = renderer.render_str_value(pat, &mj_ctx, "_exclude")?;
  1204. // Copier v9.18.0 (#2804): allow multiple newline-separated patterns in a single `_exclude` entry.
  1205. for line in expanded.lines() {
  1206. let trimmed = line.trim();
  1207. if !trimmed.is_empty() {
  1208. all_excludes.push(trimmed.to_string());
  1209. }
  1210. }
  1211. }
  1212. all_excludes.extend(options.exclude.iter().cloned());
  1213. let mut all_skip =
  1214. Vec::with_capacity(settings.skip_if_exists.len() + options.skip_if_exists.len());
  1215. for pat in &settings.skip_if_exists {
  1216. let expanded = renderer.render_str_value(pat, &mj_ctx, "_skip_if_exists")?;
  1217. for line in expanded.lines() {
  1218. let trimmed = line.trim();
  1219. if !trimmed.is_empty() {
  1220. all_skip.push(trimmed.to_string());
  1221. }
  1222. }
  1223. }
  1224. all_skip.extend(options.skip_if_exists.iter().cloned());
  1225. let filter_root = Path::new("");
  1226. let filter = PathFilter::new(
  1227. filter_root,
  1228. &all_excludes,
  1229. &all_skip,
  1230. options.use_default_excludes,
  1231. )?;
  1232. if !options.pretend {
  1233. fs::create_dir_all(dst_path).map_err(|e| RoneoError::io(dst_path, e))?;
  1234. }
  1235. // Phase 1: Walk source tree (either in-memory `gix` tree or disk) and plan ONLY non-excluded files.
  1236. // On GitTree, excluded directories (e.g. `tests/`, `docs/`, disabled `values/*`) are pruned BEFORE
  1237. // reading any subtrees or decompressing any blobs!
  1238. let mut planned_files: Vec<PlannedFile> = Vec::new();
  1239. let mut planned_dirs: HashSet<PathBuf> = HashSet::new();
  1240. match &resolved.backing {
  1241. TemplateBacking::GitTree(tree) => {
  1242. let tree_files = tree.walk_files(
  1243. rendered_subdir.as_deref(),
  1244. |rel_dir, rendered_parent, dir_name, extra_vars| {
  1245. if filter.is_excluded(rel_dir, true) {
  1246. return Ok(Vec::new());
  1247. }
  1248. let expanded = renderer.render_segment_expanded_value(
  1249. dir_name,
  1250. true,
  1251. &settings.templates_suffix,
  1252. &ctx,
  1253. extra_vars,
  1254. &mj_ctx,
  1255. &format!("path:{}", rel_dir.display()),
  1256. )?;
  1257. let mut branches = Vec::with_capacity(expanded.len());
  1258. for seg in expanded {
  1259. let rendered_dir = if rendered_parent.as_os_str().is_empty() {
  1260. PathBuf::from(seg.name)
  1261. } else {
  1262. rendered_parent.join(seg.name)
  1263. };
  1264. if filter.is_excluded(&rendered_dir, true) {
  1265. continue;
  1266. }
  1267. let mut next_vars = extra_vars.to_vec();
  1268. if let Some(binding) = seg.yield_binding {
  1269. next_vars.push(binding);
  1270. }
  1271. branches.push((rendered_dir, next_vars));
  1272. }
  1273. Ok(branches)
  1274. },
  1275. )?;
  1276. for entry in tree_files {
  1277. if filter.is_excluded(&entry.rel_path, false) {
  1278. continue;
  1279. }
  1280. let expanded = renderer.render_segment_expanded_value(
  1281. &entry.file_name,
  1282. false,
  1283. &settings.templates_suffix,
  1284. &ctx,
  1285. &entry.extra_vars,
  1286. &mj_ctx,
  1287. &format!("path:{}", entry.rel_path.display()),
  1288. )?;
  1289. for seg in expanded {
  1290. let rendered_rel = if entry.rendered_parent.as_os_str().is_empty() {
  1291. PathBuf::from(seg.name)
  1292. } else {
  1293. entry.rendered_parent.join(seg.name)
  1294. };
  1295. if filter.is_excluded(&rendered_rel, false) {
  1296. continue;
  1297. }
  1298. if let Some(parent) = rendered_rel.parent()
  1299. && !parent.as_os_str().is_empty()
  1300. {
  1301. planned_dirs.insert(parent.to_path_buf());
  1302. }
  1303. let mut file_vars = entry.extra_vars.clone();
  1304. if let Some(binding) = seg.yield_binding {
  1305. file_vars.push(binding);
  1306. }
  1307. planned_files.push(PlannedFile {
  1308. rel_src: entry.rel_path.clone(),
  1309. rendered_rel,
  1310. is_template_file: seg.is_template_file,
  1311. extra_vars: file_vars,
  1312. source: RenderItemSource::GitBlob {
  1313. tree: Arc::clone(tree),
  1314. oid: entry.oid,
  1315. is_executable: entry.is_executable,
  1316. is_symlink: entry.is_symlink,
  1317. },
  1318. });
  1319. }
  1320. }
  1321. }
  1322. TemplateBacking::Disk(_) => {
  1323. let content_root = resolved.disk_content_root(rendered_subdir.as_deref())?;
  1324. let plan_ctx = PlanCtx {
  1325. root: &content_root,
  1326. follow_symlinks: !settings.preserve_symlinks,
  1327. templates_suffix: &settings.templates_suffix,
  1328. renderer,
  1329. base_ctx: &ctx,
  1330. mj_ctx: &mj_ctx,
  1331. filter: &filter,
  1332. };
  1333. plan_disk_dir(
  1334. &plan_ctx,
  1335. &content_root,
  1336. Path::new(""),
  1337. &[],
  1338. &mut planned_dirs,
  1339. &mut planned_files,
  1340. )?;
  1341. }
  1342. }
  1343. // Create all unique target directories upfront once (avoids redundant create_dir_all races in parallel).
  1344. if !options.pretend {
  1345. for dir in &planned_dirs {
  1346. let full_dir = dst_path.join(dir);
  1347. if !full_dir.exists() {
  1348. fs::create_dir_all(&full_dir).map_err(|e| RoneoError::io(&full_dir, e))?;
  1349. }
  1350. }
  1351. }
  1352. let answers_file_written = planned_files.iter().any(|f| f.rendered_rel == answers_rel);
  1353. let overwrite_policy = if options.overwrite {
  1354. OverwritePolicy::Force
  1355. } else if prompter.is_some() && !options.defaults && !options.pretend {
  1356. OverwritePolicy::Prompt
  1357. } else {
  1358. OverwritePolicy::Skip
  1359. };
  1360. // Phase 2: Render & write files in parallel using `rayon`, reusing ONE thread-local
  1361. // `gix::Repository` per worker thread (hot pack delta cache across all blobs!).
  1362. let git_tree_opt = match &resolved.backing {
  1363. TemplateBacking::GitTree(tree) => Some(Arc::clone(tree)),
  1364. TemplateBacking::Disk(_) => None,
  1365. };
  1366. let file_ctx = FileRenderCtx {
  1367. dst_path,
  1368. renderer,
  1369. base_ctx: &ctx,
  1370. shared_mj_ctx: &mj_ctx,
  1371. filter: &filter,
  1372. preserve_symlinks: settings.preserve_symlinks,
  1373. overwrite_policy,
  1374. pretend: options.pretend,
  1375. };
  1376. let outcomes: Vec<FileOutcome> = planned_files
  1377. .par_iter()
  1378. .map_init(
  1379. || git_tree_opt.as_ref().map(|t| t.thread_local_repo()),
  1380. |thread_repo, item| process_planned_file(&file_ctx, item, thread_repo.as_ref()),
  1381. )
  1382. .collect::<Result<Vec<_>>>()?;
  1383. let mut created = 0usize;
  1384. let mut updated = 0usize;
  1385. let mut skipped = 0usize;
  1386. let mut overwrite_all = false;
  1387. for outcome in outcomes {
  1388. match outcome {
  1389. FileOutcome::Created(rel) => {
  1390. created += 1;
  1391. reporter.emit(ActionEvent::Create(rel));
  1392. }
  1393. FileOutcome::Overwritten(rel) => {
  1394. updated += 1;
  1395. reporter.emit(ActionEvent::Overwrite(rel));
  1396. }
  1397. FileOutcome::Identical(rel) => {
  1398. reporter.emit(ActionEvent::Identical(rel));
  1399. }
  1400. FileOutcome::Skipped(rel) => {
  1401. skipped += 1;
  1402. reporter.emit(ActionEvent::Skip(rel));
  1403. }
  1404. FileOutcome::NeedsOverwriteConfirm(pending) => {
  1405. let should_write = if overwrite_all {
  1406. true
  1407. } else if let Some(p) = prompter {
  1408. match p.confirm_overwrite(&pending.rel)? {
  1409. OverwriteChoice::Yes => true,
  1410. OverwriteChoice::All => {
  1411. overwrite_all = true;
  1412. true
  1413. }
  1414. OverwriteChoice::No => false,
  1415. OverwriteChoice::Quit => return Err(RoneoError::UserAborted),
  1416. }
  1417. } else {
  1418. false
  1419. };
  1420. if should_write {
  1421. apply_pending_overwrite(&pending)?;
  1422. updated += 1;
  1423. reporter.emit(ActionEvent::Overwrite(pending.rel));
  1424. } else {
  1425. skipped += 1;
  1426. reporter.emit(ActionEvent::Skip(pending.rel));
  1427. }
  1428. }
  1429. }
  1430. }
  1431. let answers_dst = dst_path.join(&answers_rel);
  1432. if !answers_file_written {
  1433. let existed = answers_dst.exists();
  1434. if !options.pretend {
  1435. answers.save(&answers_dst)?;
  1436. }
  1437. if existed {
  1438. updated += 1;
  1439. reporter.emit(ActionEvent::Overwrite(answers_rel));
  1440. } else {
  1441. created += 1;
  1442. reporter.emit(ActionEvent::Create(answers_rel));
  1443. }
  1444. }
  1445. Ok((
  1446. OperationReport {
  1447. src_path: resolved.original_src.clone(),
  1448. dst_path: dst_path.to_path_buf(),
  1449. commit: resolved.commit.clone(),
  1450. answers_file: answers_dst,
  1451. created,
  1452. updated,
  1453. skipped,
  1454. conflicts: Vec::new(),
  1455. },
  1456. ctx,
  1457. ))
  1458. }
  1459. fn apply_pending_overwrite(pending: &PendingOverwrite) -> Result<()> {
  1460. if let Some(parent) = pending.dst_entry_path.parent()
  1461. && !parent.exists()
  1462. {
  1463. fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?;
  1464. }
  1465. match &pending.content {
  1466. PendingContent::Symlink { target } => {
  1467. let _ = fs::remove_file(&pending.dst_entry_path);
  1468. create_symlink(Path::new(target), &pending.dst_entry_path)
  1469. }
  1470. PendingContent::File {
  1471. bytes,
  1472. src_for_perms,
  1473. is_executable,
  1474. } => {
  1475. // Copier v9.18.2: unlink an existing destination symlink before writing a regular file.
  1476. if pending
  1477. .dst_entry_path
  1478. .symlink_metadata()
  1479. .is_ok_and(|m| m.file_type().is_symlink())
  1480. {
  1481. let _ = fs::remove_file(&pending.dst_entry_path);
  1482. }
  1483. fs::write(&pending.dst_entry_path, bytes)
  1484. .map_err(|e| RoneoError::io(&pending.dst_entry_path, e))?;
  1485. if let Some(src) = src_for_perms {
  1486. copy_permissions(src, &pending.dst_entry_path)?;
  1487. } else if *is_executable {
  1488. set_executable(&pending.dst_entry_path)?;
  1489. }
  1490. Ok(())
  1491. }
  1492. }
  1493. }
  1494. struct PlanCtx<'a> {
  1495. root: &'a Path,
  1496. follow_symlinks: bool,
  1497. templates_suffix: &'a str,
  1498. renderer: &'a TemplateRenderer,
  1499. base_ctx: &'a IndexMap<String, JsonValue>,
  1500. mj_ctx: &'a minijinja::Value,
  1501. filter: &'a PathFilter,
  1502. }
  1503. fn plan_disk_dir(
  1504. pctx: &PlanCtx<'_>,
  1505. current: &Path,
  1506. rendered_parent: &Path,
  1507. extra_vars: &[(String, JsonValue)],
  1508. planned_dirs: &mut HashSet<PathBuf>,
  1509. planned_files: &mut Vec<PlannedFile>,
  1510. ) -> Result<()> {
  1511. let mut entries: Vec<_> = fs::read_dir(current)
  1512. .map_err(|e| RoneoError::io(current, e))?
  1513. .collect::<std::result::Result<Vec<_>, _>>()
  1514. .map_err(|e| RoneoError::io(current, e))?;
  1515. entries.sort_by_key(fs::DirEntry::file_name);
  1516. for entry in entries {
  1517. let abs_path = entry.path();
  1518. let rel_path = abs_path
  1519. .strip_prefix(pctx.root)
  1520. .map_or_else(|_| PathBuf::from(entry.file_name()), Path::to_path_buf);
  1521. let sym_meta = fs::symlink_metadata(&abs_path).map_err(|e| RoneoError::io(&abs_path, e))?;
  1522. let is_symlink = sym_meta.file_type().is_symlink();
  1523. let is_dir = if is_symlink && pctx.follow_symlinks {
  1524. fs::metadata(&abs_path).is_ok_and(|m| m.is_dir())
  1525. } else {
  1526. sym_meta.is_dir()
  1527. };
  1528. if pctx.filter.is_excluded(&rel_path, is_dir) {
  1529. continue;
  1530. }
  1531. let name = entry.file_name().to_string_lossy().into_owned();
  1532. let expanded = pctx.renderer.render_segment_expanded_value(
  1533. &name,
  1534. is_dir,
  1535. pctx.templates_suffix,
  1536. pctx.base_ctx,
  1537. extra_vars,
  1538. pctx.mj_ctx,
  1539. &format!("path:{}", rel_path.display()),
  1540. )?;
  1541. for seg in expanded {
  1542. let rendered_rel = if rendered_parent.as_os_str().is_empty() {
  1543. PathBuf::from(seg.name)
  1544. } else {
  1545. rendered_parent.join(seg.name)
  1546. };
  1547. if pctx.filter.is_excluded(&rendered_rel, is_dir) {
  1548. continue;
  1549. }
  1550. let mut next_vars = extra_vars.to_vec();
  1551. if let Some(binding) = seg.yield_binding {
  1552. next_vars.push(binding);
  1553. }
  1554. if is_dir {
  1555. planned_dirs.insert(rendered_rel.clone());
  1556. plan_disk_dir(
  1557. pctx,
  1558. &abs_path,
  1559. &rendered_rel,
  1560. &next_vars,
  1561. planned_dirs,
  1562. planned_files,
  1563. )?;
  1564. } else {
  1565. if let Some(parent) = rendered_rel.parent()
  1566. && !parent.as_os_str().is_empty()
  1567. {
  1568. planned_dirs.insert(parent.to_path_buf());
  1569. }
  1570. let file_mode = if is_symlink {
  1571. None
  1572. } else {
  1573. file_mode_from_metadata(&sym_meta)
  1574. };
  1575. planned_files.push(PlannedFile {
  1576. rel_src: rel_path.clone(),
  1577. rendered_rel,
  1578. is_template_file: seg.is_template_file,
  1579. extra_vars: next_vars,
  1580. source: RenderItemSource::Disk {
  1581. src_path: abs_path.clone(),
  1582. is_symlink,
  1583. file_mode,
  1584. },
  1585. });
  1586. }
  1587. }
  1588. }
  1589. Ok(())
  1590. }
  1591. struct FileRenderCtx<'a> {
  1592. dst_path: &'a Path,
  1593. renderer: &'a TemplateRenderer,
  1594. base_ctx: &'a IndexMap<String, JsonValue>,
  1595. shared_mj_ctx: &'a minijinja::Value,
  1596. filter: &'a PathFilter,
  1597. preserve_symlinks: bool,
  1598. overwrite_policy: OverwritePolicy,
  1599. pretend: bool,
  1600. }
  1601. fn process_planned_file(
  1602. fctx: &FileRenderCtx<'_>,
  1603. item: &PlannedFile,
  1604. thread_repo: Option<&gix::Repository>,
  1605. ) -> Result<FileOutcome> {
  1606. let overlay_ctx = if item.extra_vars.is_empty() {
  1607. None
  1608. } else {
  1609. Some(TemplateRenderer::compile_context_with_extra(
  1610. fctx.base_ctx,
  1611. &item.extra_vars,
  1612. ))
  1613. };
  1614. let ctx = overlay_ctx.as_ref().unwrap_or(fctx.shared_mj_ctx);
  1615. let dst_entry_path = fctx.dst_path.join(&item.rendered_rel);
  1616. // Handle symlinks when `_preserve_symlinks` is enabled.
  1617. let is_symlink = match &item.source {
  1618. RenderItemSource::Disk { is_symlink, .. }
  1619. | RenderItemSource::GitBlob { is_symlink, .. } => *is_symlink,
  1620. };
  1621. if fctx.preserve_symlinks && is_symlink {
  1622. let raw_target = match &item.source {
  1623. RenderItemSource::Disk { src_path, .. } => fs::read_link(src_path)
  1624. .map_err(|e| RoneoError::io(src_path, e))?
  1625. .to_string_lossy()
  1626. .into_owned(),
  1627. RenderItemSource::GitBlob { tree, oid, .. } => {
  1628. let bytes = match thread_repo {
  1629. Some(repo) => InMemoryGitTree::read_blob_with_repo(repo, *oid)?,
  1630. None => tree.read_blob_oid(*oid)?,
  1631. };
  1632. String::from_utf8_lossy(&bytes).into_owned()
  1633. }
  1634. };
  1635. let rendered_target = fctx.renderer.render_str_value(
  1636. &raw_target,
  1637. ctx,
  1638. &format!("symlink:{}", item.rel_src.display()),
  1639. )?;
  1640. let exists = dst_entry_path.symlink_metadata().is_ok();
  1641. if exists {
  1642. match fctx.overwrite_policy {
  1643. OverwritePolicy::Force => {}
  1644. OverwritePolicy::Prompt => {
  1645. return Ok(FileOutcome::NeedsOverwriteConfirm(PendingOverwrite {
  1646. rel: item.rendered_rel.clone(),
  1647. dst_entry_path,
  1648. content: PendingContent::Symlink {
  1649. target: rendered_target,
  1650. },
  1651. }));
  1652. }
  1653. OverwritePolicy::Skip => {
  1654. return Ok(FileOutcome::Skipped(item.rendered_rel.clone()));
  1655. }
  1656. }
  1657. }
  1658. if !fctx.pretend {
  1659. verify_no_symlink_in_ancestors(fctx.dst_path, &item.rendered_rel)?;
  1660. if let Some(parent) = dst_entry_path.parent()
  1661. && !parent.exists()
  1662. {
  1663. fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?;
  1664. }
  1665. if exists {
  1666. let _ = fs::remove_file(&dst_entry_path);
  1667. }
  1668. create_symlink(Path::new(&rendered_target), &dst_entry_path)?;
  1669. }
  1670. return Ok(if exists {
  1671. FileOutcome::Overwritten(item.rendered_rel.clone())
  1672. } else {
  1673. FileOutcome::Created(item.rendered_rel.clone())
  1674. });
  1675. }
  1676. // Fast path: check `_skip_if_exists` before reading/rendering if destination already exists
  1677. // (use `symlink_metadata` so broken destination symlinks are also detected, Copier v9.18.2).
  1678. let dst_meta = dst_entry_path.symlink_metadata().ok();
  1679. let exists = dst_meta.is_some();
  1680. let dst_is_symlink = dst_meta.is_some_and(|m| m.file_type().is_symlink());
  1681. if exists && fctx.filter.should_skip_if_exists(&item.rendered_rel, false) {
  1682. return Ok(FileOutcome::Skipped(item.rendered_rel.clone()));
  1683. }
  1684. // Read raw source bytes (reusing thread-local `gix::Repository` pack cache or disk).
  1685. let raw_bytes = match &item.source {
  1686. RenderItemSource::Disk { src_path, .. } => {
  1687. fs::read(src_path).map_err(|e| RoneoError::io(src_path, e))?
  1688. }
  1689. RenderItemSource::GitBlob { tree, oid, .. } => match thread_repo {
  1690. Some(repo) => InMemoryGitTree::read_blob_with_repo(repo, *oid)?,
  1691. None => tree.read_blob_oid(*oid)?,
  1692. },
  1693. };
  1694. let new_bytes = if item.is_template_file {
  1695. let raw_text = String::from_utf8(raw_bytes).map_err(|e| {
  1696. RoneoError::TemplateSource(format!(
  1697. "Template file '{}' is not valid UTF-8: {e}",
  1698. item.rel_src.display()
  1699. ))
  1700. })?;
  1701. let rendered_text =
  1702. fctx.renderer
  1703. .render_str_value(&raw_text, ctx, &item.rel_src.to_string_lossy())?;
  1704. rendered_text.into_bytes()
  1705. } else {
  1706. raw_bytes
  1707. };
  1708. if exists {
  1709. if !dst_is_symlink
  1710. && let Ok(existing_bytes) = fs::read(&dst_entry_path)
  1711. && existing_bytes == new_bytes
  1712. {
  1713. return Ok(FileOutcome::Identical(item.rendered_rel.clone()));
  1714. }
  1715. match fctx.overwrite_policy {
  1716. OverwritePolicy::Force => {}
  1717. OverwritePolicy::Prompt => {
  1718. let (src_for_perms, is_executable) = match &item.source {
  1719. RenderItemSource::Disk { src_path, .. } => (Some(src_path.clone()), false),
  1720. RenderItemSource::GitBlob { is_executable, .. } => (None, *is_executable),
  1721. };
  1722. return Ok(FileOutcome::NeedsOverwriteConfirm(PendingOverwrite {
  1723. rel: item.rendered_rel.clone(),
  1724. dst_entry_path,
  1725. content: PendingContent::File {
  1726. bytes: new_bytes,
  1727. src_for_perms,
  1728. is_executable,
  1729. },
  1730. }));
  1731. }
  1732. OverwritePolicy::Skip => {
  1733. return Ok(FileOutcome::Skipped(item.rendered_rel.clone()));
  1734. }
  1735. }
  1736. }
  1737. if !fctx.pretend {
  1738. verify_no_symlink_in_ancestors(fctx.dst_path, &item.rendered_rel)?;
  1739. if let Some(parent) = dst_entry_path.parent()
  1740. && !parent.exists()
  1741. {
  1742. fs::create_dir_all(parent).map_err(|e| RoneoError::io(parent, e))?;
  1743. }
  1744. // Copier v9.18.2: replace an existing symlink instead of writing through it.
  1745. if dst_is_symlink {
  1746. let _ = fs::remove_file(&dst_entry_path);
  1747. }
  1748. fs::write(&dst_entry_path, &new_bytes).map_err(|e| RoneoError::io(&dst_entry_path, e))?;
  1749. match &item.source {
  1750. RenderItemSource::Disk {
  1751. src_path,
  1752. file_mode,
  1753. ..
  1754. } => {
  1755. if let Some(mode) = file_mode {
  1756. set_file_mode(&dst_entry_path, *mode)?;
  1757. } else {
  1758. copy_permissions(src_path, &dst_entry_path)?;
  1759. }
  1760. }
  1761. RenderItemSource::GitBlob { is_executable, .. } => {
  1762. if *is_executable {
  1763. set_executable(&dst_entry_path)?;
  1764. }
  1765. }
  1766. }
  1767. }
  1768. Ok(if exists {
  1769. FileOutcome::Overwritten(item.rendered_rel.clone())
  1770. } else {
  1771. FileOutcome::Created(item.rendered_rel.clone())
  1772. })
  1773. }
  1774. /// Reject writing through any pre-existing symlink directory under `dst_root` so a template
  1775. /// or malicious destination symlink cannot redirect output outside `dst_root`.
  1776. fn verify_no_symlink_in_ancestors(dst_root: &Path, rel: &Path) -> Result<()> {
  1777. let Some(parent_rel) = rel.parent() else {
  1778. return Ok(());
  1779. };
  1780. let mut cur = dst_root.to_path_buf();
  1781. for comp in parent_rel.components() {
  1782. cur.push(comp);
  1783. if let Ok(meta) = cur.symlink_metadata()
  1784. && meta.file_type().is_symlink()
  1785. {
  1786. return Err(RoneoError::InvalidConfig(format!(
  1787. "Refusing to write through symlink directory '{}'",
  1788. cur.display()
  1789. )));
  1790. }
  1791. }
  1792. Ok(())
  1793. }
  1794. #[derive(Default)]
  1795. struct PatchSummary {
  1796. created: Vec<String>,
  1797. modified: Vec<String>,
  1798. deleted: Vec<String>,
  1799. }
  1800. fn summarize_patch(patch: &[u8]) -> PatchSummary {
  1801. let text = String::from_utf8_lossy(patch);
  1802. let mut summary = PatchSummary::default();
  1803. let mut current_path: Option<String> = None;
  1804. let mut is_new = false;
  1805. let mut is_deleted = false;
  1806. let flush = |path: &mut Option<String>,
  1807. is_new: &mut bool,
  1808. is_deleted: &mut bool,
  1809. summary: &mut PatchSummary| {
  1810. if let Some(p) = path.take() {
  1811. if *is_new {
  1812. summary.created.push(p);
  1813. } else if *is_deleted {
  1814. summary.deleted.push(p);
  1815. } else {
  1816. summary.modified.push(p);
  1817. }
  1818. }
  1819. *is_new = false;
  1820. *is_deleted = false;
  1821. };
  1822. for line in text.lines() {
  1823. if let Some(rest) = line.strip_prefix("diff --git ") {
  1824. flush(
  1825. &mut current_path,
  1826. &mut is_new,
  1827. &mut is_deleted,
  1828. &mut summary,
  1829. );
  1830. // Handles standard `a/foo b/foo` as well as `--no-index --no-prefix` `b/foo b/foo` (new)
  1831. // and `a/foo a/foo` (deleted).
  1832. if let Some((_, b_part)) = rest.split_once(" b/") {
  1833. current_path = Some(b_part.to_string());
  1834. } else if let Some((_, a_part)) = rest.split_once(" a/") {
  1835. current_path = Some(a_part.to_string());
  1836. }
  1837. } else if line.starts_with("new file mode") {
  1838. is_new = true;
  1839. } else if line.starts_with("deleted file mode") {
  1840. is_deleted = true;
  1841. }
  1842. }
  1843. flush(
  1844. &mut current_path,
  1845. &mut is_new,
  1846. &mut is_deleted,
  1847. &mut summary,
  1848. );
  1849. summary
  1850. }