forgeFRENBrowse the repositories

roneocratesroneo-coretestsintegration.rs

98ff76d5794bbd1480ad719803187d2c40e42403

At commit 98ff76d

2 085 lines · 60.5 KiBRustRaw
  1. use std::fs;
  2. use std::path::Path;
  3. use std::process::Command;
  4. use indexmap::IndexMap;
  5. use roneo_core::fs_util::TempDir;
  6. use roneo_core::vcs::ConflictMode;
  7. use roneo_core::{
  8. AnswersMap, CopyOptions, NonInteractivePrompter, NoopReporter, OverwriteChoice, PromptRequest,
  9. Prompter, RoneoError, UserSettings, check_update, copy, diff_update, recopy, update,
  10. };
  11. use serde_json::json;
  12. fn git(dir: &Path, args: &[&str]) {
  13. let out = Command::new("git")
  14. .current_dir(dir)
  15. .args(args)
  16. .output()
  17. .expect("git command should run");
  18. assert!(
  19. out.status.success(),
  20. "git {:?} failed: {}",
  21. args,
  22. String::from_utf8_lossy(&out.stderr)
  23. );
  24. }
  25. fn init_git_repo(dir: &Path) {
  26. git(dir, &["init", "-b", "main"]);
  27. git(dir, &["config", "user.name", "Test"]);
  28. git(dir, &["config", "user.email", "test@example.com"]);
  29. git(dir, &["config", "commit.gpgsign", "false"]);
  30. }
  31. fn commit_all(dir: &Path, msg: &str) {
  32. git(dir, &["add", "-A"]);
  33. git(dir, &["commit", "-m", msg]);
  34. }
  35. #[test]
  36. fn copy_renders_copier_template_with_pycompat_paths_secrets_and_conditions() {
  37. let tpl_dir = TempDir::new().unwrap();
  38. let dst_dir = TempDir::new().unwrap();
  39. fs::write(
  40. tpl_dir.path().join("copier.yml"),
  41. r#"
  42. _subdirectory: template
  43. _exclude:
  44. - "ignored.txt"
  45. project_name:
  46. type: str
  47. default: my-cool-app
  48. module_name:
  49. type: str
  50. default: "{{ project_name.lower().replace('-', '_') }}"
  51. include_extras:
  52. type: bool
  53. default: false
  54. api_token:
  55. type: str
  56. secret: true
  57. default: super-secret-value
  58. "#,
  59. )
  60. .unwrap();
  61. let tpl_sub = tpl_dir.path().join("template");
  62. fs::create_dir_all(tpl_sub.join("src")).unwrap();
  63. fs::write(
  64. tpl_sub.join("README.md.jinja"),
  65. "# {{ project_name }}\nmodule={{ module_name }}\ntoken={{ api_token }}\n",
  66. )
  67. .unwrap();
  68. fs::write(
  69. tpl_sub.join("src/{{ module_name }}.txt.jinja"),
  70. "hello {{ module_name }}",
  71. )
  72. .unwrap();
  73. fs::write(
  74. tpl_sub.join("{% if include_extras %}extras.txt{% endif %}.jinja"),
  75. "extra content",
  76. )
  77. .unwrap();
  78. fs::write(tpl_sub.join("ignored.txt"), "should not be copied").unwrap();
  79. let mut data = IndexMap::new();
  80. data.insert("project_name".into(), json!("Roneo-Demo"));
  81. let opts = CopyOptions {
  82. data,
  83. defaults: true,
  84. ..CopyOptions::default()
  85. };
  86. let report = copy(
  87. tpl_dir.path().to_str().unwrap(),
  88. dst_dir.path(),
  89. &opts,
  90. &NonInteractivePrompter,
  91. &NoopReporter,
  92. )
  93. .unwrap();
  94. assert!(report.created >= 3);
  95. let readme = fs::read_to_string(dst_dir.path().join("README.md")).unwrap();
  96. assert!(readme.contains("# Roneo-Demo"));
  97. assert!(readme.contains("module=roneo_demo"));
  98. assert!(readme.contains("token=super-secret-value"));
  99. let mod_file = fs::read_to_string(dst_dir.path().join("src/roneo_demo.txt")).unwrap();
  100. assert_eq!(mod_file, "hello roneo_demo");
  101. // Conditional file skipped when false
  102. assert!(!dst_dir.path().join("extras.txt").exists());
  103. // Excluded file skipped
  104. assert!(!dst_dir.path().join("ignored.txt").exists());
  105. // Secret answer must NOT be written into .copier-answers.yml
  106. let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap();
  107. assert_eq!(answers.user.get("project_name"), Some(&json!("Roneo-Demo")));
  108. assert_eq!(answers.user.get("module_name"), Some(&json!("roneo_demo")));
  109. assert!(!answers.user.contains_key("api_token"));
  110. }
  111. #[test]
  112. fn pretend_mode_writes_nothing() {
  113. let tpl_dir = TempDir::new().unwrap();
  114. let dst_dir = TempDir::new().unwrap();
  115. fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap();
  116. fs::write(tpl_dir.path().join("hello.txt.jinja"), "Hi {{ name }}").unwrap();
  117. let opts = CopyOptions {
  118. defaults: true,
  119. pretend: true,
  120. ..CopyOptions::default()
  121. };
  122. let report = copy(
  123. tpl_dir.path().to_str().unwrap(),
  124. dst_dir.path(),
  125. &opts,
  126. &NonInteractivePrompter,
  127. &NoopReporter,
  128. )
  129. .unwrap();
  130. assert!(report.created >= 1);
  131. assert!(!dst_dir.path().join("hello.txt").exists());
  132. assert!(!dst_dir.path().join(".copier-answers.yml").exists());
  133. }
  134. #[test]
  135. fn recopy_reuses_previous_answers_and_updates_files() {
  136. let tpl_dir = TempDir::new().unwrap();
  137. let dst_dir = TempDir::new().unwrap();
  138. fs::write(
  139. tpl_dir.path().join("copier.yml"),
  140. "project_name: alpha\ngreeting: hello\n",
  141. )
  142. .unwrap();
  143. fs::write(
  144. tpl_dir.path().join("info.txt.jinja"),
  145. "{{ greeting }}, {{ project_name }}!\n",
  146. )
  147. .unwrap();
  148. let mut data = IndexMap::new();
  149. data.insert("project_name".into(), json!("beta"));
  150. copy(
  151. tpl_dir.path().to_str().unwrap(),
  152. dst_dir.path(),
  153. &CopyOptions {
  154. data,
  155. defaults: true,
  156. ..CopyOptions::default()
  157. },
  158. &NonInteractivePrompter,
  159. &NoopReporter,
  160. )
  161. .unwrap();
  162. assert_eq!(
  163. fs::read_to_string(dst_dir.path().join("info.txt")).unwrap(),
  164. "hello, beta!\n"
  165. );
  166. let mut override_data = IndexMap::new();
  167. override_data.insert("greeting".into(), json!("bonjour"));
  168. recopy(
  169. dst_dir.path(),
  170. None,
  171. &CopyOptions {
  172. data: override_data,
  173. defaults: true,
  174. ..CopyOptions::default()
  175. },
  176. &NonInteractivePrompter,
  177. &NoopReporter,
  178. )
  179. .unwrap();
  180. // `project_name` preserved from `.copier-answers.yml`, `greeting` updated!
  181. assert_eq!(
  182. fs::read_to_string(dst_dir.path().join("info.txt")).unwrap(),
  183. "bonjour, beta!\n"
  184. );
  185. }
  186. #[test]
  187. fn smart_update_preserves_local_edits_and_applies_upstream_changes() {
  188. let tpl_dir = TempDir::new().unwrap();
  189. let dst_dir = TempDir::new().unwrap();
  190. // Create git-backed template v1.0.0
  191. init_git_repo(tpl_dir.path());
  192. fs::write(tpl_dir.path().join("copier.yml"), "project_name: demo\n").unwrap();
  193. fs::write(
  194. tpl_dir.path().join("README.md.jinja"),
  195. "# {{ project_name }}\n\nTemplate header v1\n\n## Custom Notes\nWrite notes here.\n",
  196. )
  197. .unwrap();
  198. fs::write(tpl_dir.path().join("legacy.txt"), "old file\n").unwrap();
  199. commit_all(tpl_dir.path(), "v1.0.0");
  200. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  201. // Copy v1.0.0 into destination and commit as a git repo
  202. copy(
  203. tpl_dir.path().to_str().unwrap(),
  204. dst_dir.path(),
  205. &CopyOptions {
  206. defaults: true,
  207. ..CopyOptions::default()
  208. },
  209. &NonInteractivePrompter,
  210. &NoopReporter,
  211. )
  212. .unwrap();
  213. init_git_repo(dst_dir.path());
  214. commit_all(dst_dir.path(), "Initial scaffold");
  215. // User customizes README.md and adds a custom file
  216. fs::write(
  217. dst_dir.path().join("README.md"),
  218. "# demo\n\nTemplate header v1\n\n## Custom Notes\nMy precious user edits!\n",
  219. )
  220. .unwrap();
  221. fs::write(dst_dir.path().join("user_code.rs"), "fn main() {}\n").unwrap();
  222. commit_all(dst_dir.path(), "User edits");
  223. // Template releases v2.0.0: updates header, removes legacy.txt, adds CHANGELOG.md
  224. fs::write(
  225. tpl_dir.path().join("README.md.jinja"),
  226. "# {{ project_name }}\n\nTemplate header v2 (improved!)\n\n## Custom Notes\nWrite notes here.\n",
  227. )
  228. .unwrap();
  229. fs::remove_file(tpl_dir.path().join("legacy.txt")).unwrap();
  230. fs::write(
  231. tpl_dir.path().join("CHANGELOG.md.jinja"),
  232. "# Changelog for {{ project_name }}\n- v2.0.0\n",
  233. )
  234. .unwrap();
  235. commit_all(tpl_dir.path(), "v2.0.0");
  236. git(tpl_dir.path(), &["tag", "v2.0.0"]);
  237. // Run smart update!
  238. let report = update(
  239. dst_dir.path(),
  240. &CopyOptions {
  241. defaults: true,
  242. ..CopyOptions::default()
  243. },
  244. &NonInteractivePrompter,
  245. &NoopReporter,
  246. )
  247. .unwrap();
  248. assert!(
  249. report.conflicts.is_empty(),
  250. "Unexpected conflicts: {:?}",
  251. report.conflicts
  252. );
  253. assert_eq!(report.commit.as_deref(), Some("v2.0.0"));
  254. // README has BOTH v2 template update AND preserved user edits!
  255. let readme = fs::read_to_string(dst_dir.path().join("README.md")).unwrap();
  256. assert!(readme.contains("Template header v2 (improved!)"));
  257. assert!(readme.contains("My precious user edits!"));
  258. // New file added, legacy file removed, user custom file untouched
  259. assert!(dst_dir.path().join("CHANGELOG.md").exists());
  260. assert!(!dst_dir.path().join("legacy.txt").exists());
  261. assert!(dst_dir.path().join("user_code.rs").exists());
  262. // Answers file updated to v2.0.0
  263. let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap();
  264. assert_eq!(answers.commit(), Some("v2.0.0"));
  265. }
  266. #[test]
  267. fn smart_update_reports_three_way_conflicts_inline() {
  268. let tpl_dir = TempDir::new().unwrap();
  269. let dst_dir = TempDir::new().unwrap();
  270. init_git_repo(tpl_dir.path());
  271. fs::write(tpl_dir.path().join("copier.yml"), "name: app\n").unwrap();
  272. fs::write(tpl_dir.path().join("config.txt.jinja"), "port=8080\n").unwrap();
  273. commit_all(tpl_dir.path(), "v1");
  274. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  275. copy(
  276. tpl_dir.path().to_str().unwrap(),
  277. dst_dir.path(),
  278. &CopyOptions {
  279. defaults: true,
  280. ..CopyOptions::default()
  281. },
  282. &NonInteractivePrompter,
  283. &NoopReporter,
  284. )
  285. .unwrap();
  286. init_git_repo(dst_dir.path());
  287. commit_all(dst_dir.path(), "scaffold");
  288. // User edits same line
  289. fs::write(dst_dir.path().join("config.txt"), "port=9090\n").unwrap();
  290. commit_all(dst_dir.path(), "change port");
  291. // Upstream edits same line differently
  292. fs::write(tpl_dir.path().join("config.txt.jinja"), "port=3000\n").unwrap();
  293. commit_all(tpl_dir.path(), "v2");
  294. git(tpl_dir.path(), &["tag", "v2.0.0"]);
  295. let report = update(
  296. dst_dir.path(),
  297. &CopyOptions {
  298. defaults: true,
  299. conflict_mode: ConflictMode::Inline,
  300. ..CopyOptions::default()
  301. },
  302. &NonInteractivePrompter,
  303. &NoopReporter,
  304. )
  305. .unwrap();
  306. assert_eq!(report.conflicts, vec!["config.txt"]);
  307. let content = fs::read_to_string(dst_dir.path().join("config.txt")).unwrap();
  308. assert!(content.contains("<<<<<<<"));
  309. assert!(content.contains("port=9090"));
  310. assert!(content.contains("port=3000"));
  311. }
  312. #[test]
  313. fn tasks_require_trust_flag() {
  314. let tpl_dir = TempDir::new().unwrap();
  315. let dst_dir = TempDir::new().unwrap();
  316. fs::write(
  317. tpl_dir.path().join("copier.yml"),
  318. r#"
  319. _tasks:
  320. - "echo 'ran {{ name }}' > task_ran.txt"
  321. name: ok
  322. "#,
  323. )
  324. .unwrap();
  325. fs::write(tpl_dir.path().join("a.txt"), "hello").unwrap();
  326. // Without --trust -> rejected
  327. let err = copy(
  328. tpl_dir.path().to_str().unwrap(),
  329. dst_dir.path(),
  330. &CopyOptions {
  331. defaults: true,
  332. trust: false,
  333. ..CopyOptions::default()
  334. },
  335. &NonInteractivePrompter,
  336. &NoopReporter,
  337. )
  338. .unwrap_err();
  339. assert!(matches!(err, RoneoError::UnsafeTemplate(_)));
  340. // With --trust -> succeeds and executes task
  341. copy(
  342. tpl_dir.path().to_str().unwrap(),
  343. dst_dir.path(),
  344. &CopyOptions {
  345. defaults: true,
  346. trust: true,
  347. ..CopyOptions::default()
  348. },
  349. &NonInteractivePrompter,
  350. &NoopReporter,
  351. )
  352. .unwrap();
  353. let marker = fs::read_to_string(dst_dir.path().join("task_ran.txt")).unwrap();
  354. assert_eq!(marker.trim(), "ran ok");
  355. }
  356. #[test]
  357. fn external_data_and_extra_filters_render_cleanly() {
  358. let tpl_dir = TempDir::new().unwrap();
  359. let dst_dir = TempDir::new().unwrap();
  360. fs::write(
  361. tpl_dir.path().join("meta.yml"),
  362. "org: Acme\nports:\n - 80\n - 443\n",
  363. )
  364. .unwrap();
  365. fs::write(
  366. tpl_dir.path().join("copier.yml"),
  367. r#"
  368. _external_data:
  369. meta: meta.yml
  370. _exclude:
  371. - "meta.yml"
  372. title:
  373. type: str
  374. default: "Hello World 2026!"
  375. "#,
  376. )
  377. .unwrap();
  378. fs::write(
  379. tpl_dir.path().join("out.yml.jinja"),
  380. r#"org: {{ _external_data.meta.org }}
  381. slug: {{ title | slugify }}
  382. joined: {{ pathjoin("a", "b", "c.yml") }}
  383. parsed: {{ '{"k": 42}' | from_json | to_json }}
  384. bool_ok: {{ "yes" | to_bool }}
  385. "#,
  386. )
  387. .unwrap();
  388. copy(
  389. tpl_dir.path().to_str().unwrap(),
  390. dst_dir.path(),
  391. &CopyOptions {
  392. defaults: true,
  393. ..CopyOptions::default()
  394. },
  395. &NonInteractivePrompter,
  396. &NoopReporter,
  397. )
  398. .unwrap();
  399. let rendered = fs::read_to_string(dst_dir.path().join("out.yml")).unwrap();
  400. // AutoEscape::None means `.yml` strings are NOT wrapped in extra JSON quotes!
  401. assert!(rendered.contains("org: Acme\n"), "got:\n{rendered}");
  402. assert!(
  403. rendered.contains("slug: hello-world-2026\n"),
  404. "got:\n{rendered}"
  405. );
  406. assert!(rendered.contains("joined: a/b/c.yml\n"), "got:\n{rendered}");
  407. assert!(
  408. rendered.contains("parsed: {\"k\":42}\n"),
  409. "got:\n{rendered}"
  410. );
  411. assert!(rendered.contains("bool_ok: True\n"), "got:\n{rendered}");
  412. }
  413. #[test]
  414. fn pep440_prerelease_tags_and_in_memory_gix_includes() {
  415. let tpl_dir = TempDir::new().unwrap();
  416. let dst_stable = TempDir::new().unwrap();
  417. let dst_pre = TempDir::new().unwrap();
  418. init_git_repo(tpl_dir.path());
  419. fs::create_dir_all(tpl_dir.path().join("template/includes")).unwrap();
  420. fs::write(
  421. tpl_dir.path().join("copier.yml"),
  422. "_subdirectory: template\n---\n!include template/questions.yml\n",
  423. )
  424. .unwrap();
  425. fs::write(
  426. tpl_dir.path().join("template/questions.yml"),
  427. "_exclude:\n - questions.yml\n - includes\n - includes/**\nver_label: v1\n",
  428. )
  429. .unwrap();
  430. fs::write(
  431. tpl_dir.path().join("template/includes/part.jinja"),
  432. "included-v1-{{ ver_label }}",
  433. )
  434. .unwrap();
  435. fs::write(
  436. tpl_dir.path().join("template/out.txt.jinja"),
  437. "{% include 'template/includes/part.jinja' %}\n",
  438. )
  439. .unwrap();
  440. commit_all(tpl_dir.path(), "v1.0.0");
  441. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  442. // Add a PEP 440 pre-release tag v2.0.0rc1
  443. fs::write(
  444. tpl_dir.path().join("template/includes/part.jinja"),
  445. "included-rc-{{ ver_label }}",
  446. )
  447. .unwrap();
  448. commit_all(tpl_dir.path(), "v2.0.0rc1");
  449. git(tpl_dir.path(), &["tag", "v2.0.0rc1"]);
  450. // Default (`use_prereleases = false`) selects stable `v1.0.0`!
  451. let rep_stable = copy(
  452. tpl_dir.path().to_str().unwrap(),
  453. dst_stable.path(),
  454. &CopyOptions {
  455. defaults: true,
  456. ..CopyOptions::default()
  457. },
  458. &NonInteractivePrompter,
  459. &NoopReporter,
  460. )
  461. .unwrap();
  462. assert_eq!(rep_stable.commit.as_deref(), Some("v1.0.0"));
  463. assert_eq!(
  464. fs::read_to_string(dst_stable.path().join("out.txt")).unwrap(),
  465. "included-v1-v1\n"
  466. );
  467. // With `use_prereleases = true` selects `v2.0.0rc1`!
  468. let rep_pre = copy(
  469. tpl_dir.path().to_str().unwrap(),
  470. dst_pre.path(),
  471. &CopyOptions {
  472. defaults: true,
  473. use_prereleases: true,
  474. ..CopyOptions::default()
  475. },
  476. &NonInteractivePrompter,
  477. &NoopReporter,
  478. )
  479. .unwrap();
  480. assert_eq!(rep_pre.commit.as_deref(), Some("v2.0.0rc1"));
  481. assert_eq!(
  482. fs::read_to_string(dst_pre.path().join("out.txt")).unwrap(),
  483. "included-rc-v1\n"
  484. );
  485. }
  486. #[test]
  487. fn skipped_when_questions_not_persisted_and_unset_supported() {
  488. let tpl_dir = TempDir::new().unwrap();
  489. let dst_dir = TempDir::new().unwrap();
  490. fs::write(
  491. tpl_dir.path().join("copier.yml"),
  492. r#"
  493. enable_feature:
  494. type: bool
  495. default: false
  496. hidden_opt:
  497. type: str
  498. default: "fallback"
  499. when: "{{ enable_feature }}"
  500. unset_opt:
  501. type: str
  502. default: "{% if enable_feature %}set{% else %}{{ UNSET }}{% endif %}"
  503. when: "{{ enable_feature }}"
  504. "#,
  505. )
  506. .unwrap();
  507. fs::write(
  508. tpl_dir.path().join("f.txt.jinja"),
  509. "hidden={{ hidden_opt }}\n",
  510. )
  511. .unwrap();
  512. copy(
  513. tpl_dir.path().to_str().unwrap(),
  514. dst_dir.path(),
  515. &CopyOptions {
  516. defaults: true,
  517. ..CopyOptions::default()
  518. },
  519. &NonInteractivePrompter,
  520. &NoopReporter,
  521. )
  522. .unwrap();
  523. assert_eq!(
  524. fs::read_to_string(dst_dir.path().join("f.txt")).unwrap(),
  525. "hidden=fallback\n"
  526. );
  527. let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap();
  528. assert_eq!(answers.user.get("enable_feature"), Some(&json!(false)));
  529. assert!(!answers.user.contains_key("hidden_opt"));
  530. assert!(!answers.user.contains_key("unset_opt"));
  531. }
  532. #[test]
  533. fn diff_update_previews_patch_without_mutating_destination() {
  534. let tpl_dir = TempDir::new().unwrap();
  535. let dst_dir = TempDir::new().unwrap();
  536. init_git_repo(tpl_dir.path());
  537. fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap();
  538. fs::write(tpl_dir.path().join("app.txt.jinja"), "version=1\n").unwrap();
  539. commit_all(tpl_dir.path(), "v1.0.0");
  540. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  541. copy(
  542. tpl_dir.path().to_str().unwrap(),
  543. dst_dir.path(),
  544. &CopyOptions {
  545. defaults: true,
  546. ..CopyOptions::default()
  547. },
  548. &NonInteractivePrompter,
  549. &NoopReporter,
  550. )
  551. .unwrap();
  552. fs::write(tpl_dir.path().join("app.txt.jinja"), "version=2\n").unwrap();
  553. commit_all(tpl_dir.path(), "v2.0.0");
  554. git(tpl_dir.path(), &["tag", "v2.0.0"]);
  555. let diff = diff_update(
  556. dst_dir.path(),
  557. &CopyOptions {
  558. defaults: true,
  559. ..CopyOptions::default()
  560. },
  561. &NonInteractivePrompter,
  562. )
  563. .unwrap();
  564. assert_eq!(diff.from_commit, "v1.0.0");
  565. assert_eq!(diff.to_commit.as_deref(), Some("v2.0.0"));
  566. assert!(diff.patch.contains("-version=1"));
  567. assert!(diff.patch.contains("+version=2"));
  568. // Destination file remains untouched!
  569. assert_eq!(
  570. fs::read_to_string(dst_dir.path().join("app.txt")).unwrap(),
  571. "version=1\n"
  572. );
  573. }
  574. #[test]
  575. fn min_copier_version_and_user_settings_defaults_and_trust() {
  576. let tpl_dir = TempDir::new().unwrap();
  577. let dst_dir = TempDir::new().unwrap();
  578. // 1. Template requiring Copier 99.0.0 must be rejected.
  579. fs::write(
  580. tpl_dir.path().join("copier.yml"),
  581. "_min_copier_version: '99.0.0'\nname: demo\n",
  582. )
  583. .unwrap();
  584. let err = copy(
  585. tpl_dir.path().to_str().unwrap(),
  586. dst_dir.path(),
  587. &CopyOptions {
  588. defaults: true,
  589. ..CopyOptions::default()
  590. },
  591. &NonInteractivePrompter,
  592. &NoopReporter,
  593. )
  594. .unwrap_err();
  595. assert!(matches!(err, RoneoError::IncompatibleCopierVersion { .. }));
  596. // 2. Compatible `_min_copier_version` + `UserSettings` (`defaults` + `trust` prefix).
  597. fs::write(
  598. tpl_dir.path().join("copier.yml"),
  599. r#"
  600. _min_copier_version: "9.0.0"
  601. _tasks:
  602. - "echo 'trusted {{ author }}' > ran.txt"
  603. author:
  604. type: str
  605. default: anonymous
  606. "#,
  607. )
  608. .unwrap();
  609. fs::write(
  610. tpl_dir.path().join("info.txt.jinja"),
  611. "author={{ author }}\nfolder={{ _folder_name }}\nop={{ _copier_operation }}\nunsafe={{ _copier_conf.unsafe }}\n",
  612. )
  613. .unwrap();
  614. let mut user_settings = UserSettings::default();
  615. user_settings
  616. .defaults
  617. .insert("author".into(), json!("Jean"));
  618. user_settings
  619. .trust
  620. .push(format!("{}/", tpl_dir.path().parent().unwrap().display()));
  621. copy(
  622. tpl_dir.path().to_str().unwrap(),
  623. dst_dir.path(),
  624. &CopyOptions {
  625. defaults: true,
  626. trust: false, // Trusted via `user_settings.trust`!
  627. user_settings: Some(user_settings),
  628. ..CopyOptions::default()
  629. },
  630. &NonInteractivePrompter,
  631. &NoopReporter,
  632. )
  633. .unwrap();
  634. let info = fs::read_to_string(dst_dir.path().join("info.txt")).unwrap();
  635. let expected_folder = dst_dir.path().file_name().unwrap().to_str().unwrap();
  636. assert!(info.contains("author=Jean\n"), "got:\n{info}");
  637. assert!(
  638. info.contains(&format!("folder={expected_folder}\n")),
  639. "got:\n{info}"
  640. );
  641. assert!(info.contains("op=copy\n"), "got:\n{info}");
  642. assert!(info.contains("unsafe=True\n"), "got:\n{info}");
  643. assert_eq!(
  644. fs::read_to_string(dst_dir.path().join("ran.txt"))
  645. .unwrap()
  646. .trim(),
  647. "trusted Jean"
  648. );
  649. }
  650. #[test]
  651. fn update_with_current_vcs_ref_and_migration_stage() {
  652. let tpl_dir = TempDir::new().unwrap();
  653. let dst_dir = TempDir::new().unwrap();
  654. init_git_repo(tpl_dir.path());
  655. fs::write(
  656. tpl_dir.path().join("copier.yml"),
  657. r#"
  658. _migrations:
  659. - version: "2.0.0"
  660. when: "{{ _stage == 'before' }}"
  661. before:
  662. - "echo before >> migration.log"
  663. after:
  664. - "echo after >> migration.log"
  665. greeting:
  666. type: str
  667. default: hello
  668. "#,
  669. )
  670. .unwrap();
  671. fs::write(tpl_dir.path().join("msg.txt.jinja"), "{{ greeting }} v1\n").unwrap();
  672. commit_all(tpl_dir.path(), "v1.0.0");
  673. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  674. copy(
  675. tpl_dir.path().to_str().unwrap(),
  676. dst_dir.path(),
  677. &CopyOptions {
  678. defaults: true,
  679. trust: true,
  680. ..CopyOptions::default()
  681. },
  682. &NonInteractivePrompter,
  683. &NoopReporter,
  684. )
  685. .unwrap();
  686. init_git_repo(dst_dir.path());
  687. commit_all(dst_dir.path(), "scaffold");
  688. // Release v2.0.0 on the template, then update with `--vcs-ref :current:` to stay on v1.0.0
  689. // while changing an answer.
  690. fs::write(tpl_dir.path().join("msg.txt.jinja"), "{{ greeting }} v2\n").unwrap();
  691. commit_all(tpl_dir.path(), "v2.0.0");
  692. git(tpl_dir.path(), &["tag", "v2.0.0"]);
  693. let mut data = IndexMap::new();
  694. data.insert("greeting".into(), json!("bonjour"));
  695. let rep_current = update(
  696. dst_dir.path(),
  697. &CopyOptions {
  698. vcs_ref: Some(":current:".into()),
  699. data,
  700. defaults: true,
  701. trust: true,
  702. ..CopyOptions::default()
  703. },
  704. &NonInteractivePrompter,
  705. &NoopReporter,
  706. )
  707. .unwrap();
  708. assert_eq!(rep_current.commit.as_deref(), Some("v1.0.0"));
  709. assert_eq!(
  710. fs::read_to_string(dst_dir.path().join("msg.txt")).unwrap(),
  711. "bonjour v1\n"
  712. );
  713. commit_all(dst_dir.path(), "re-answered at current");
  714. // Now upgrade to v2.0.0 and verify `_stage == 'before'` only ran the `before` stage!
  715. let rep_v2 = update(
  716. dst_dir.path(),
  717. &CopyOptions {
  718. defaults: true,
  719. trust: true,
  720. ..CopyOptions::default()
  721. },
  722. &NonInteractivePrompter,
  723. &NoopReporter,
  724. )
  725. .unwrap();
  726. assert_eq!(rep_v2.commit.as_deref(), Some("v2.0.0"));
  727. assert_eq!(
  728. fs::read_to_string(dst_dir.path().join("msg.txt")).unwrap(),
  729. "bonjour v2\n"
  730. );
  731. assert_eq!(
  732. fs::read_to_string(dst_dir.path().join("migration.log"))
  733. .unwrap()
  734. .trim(),
  735. "before"
  736. );
  737. }
  738. #[test]
  739. fn interactive_overwrite_confirmation_respects_user_choice() {
  740. struct AlwaysYesPrompter;
  741. impl Prompter for AlwaysYesPrompter {
  742. fn prompt_string(&self, req: &PromptRequest) -> roneo_core::Result<String> {
  743. Ok(req.default_display.clone().unwrap_or_default())
  744. }
  745. fn prompt_bool(&self, _req: &PromptRequest, default: bool) -> roneo_core::Result<bool> {
  746. Ok(default)
  747. }
  748. fn prompt_select(
  749. &self,
  750. _req: &PromptRequest,
  751. choices: &[roneo_core::config::ChoiceSpec],
  752. default_idx: Option<usize>,
  753. ) -> roneo_core::Result<serde_json::Value> {
  754. Ok(choices[default_idx.unwrap_or(0)].value.clone())
  755. }
  756. fn prompt_multiselect(
  757. &self,
  758. _req: &PromptRequest,
  759. _choices: &[roneo_core::config::ChoiceSpec],
  760. _defaults: &[usize],
  761. ) -> roneo_core::Result<Vec<serde_json::Value>> {
  762. Ok(Vec::new())
  763. }
  764. fn show_validation_error(&self, _question: &str, _error: &str) {}
  765. fn confirm_overwrite(&self, _path: &Path) -> roneo_core::Result<OverwriteChoice> {
  766. Ok(OverwriteChoice::Yes)
  767. }
  768. }
  769. let tpl_dir = TempDir::new().unwrap();
  770. let dst_dir = TempDir::new().unwrap();
  771. fs::write(tpl_dir.path().join("copier.yml"), "name: new\n").unwrap();
  772. fs::write(
  773. tpl_dir.path().join("file.txt.jinja"),
  774. "content={{ name }}\n",
  775. )
  776. .unwrap();
  777. fs::write(dst_dir.path().join("file.txt"), "old content\n").unwrap();
  778. let mut data = IndexMap::new();
  779. data.insert("name".into(), json!("updated"));
  780. let rep = copy(
  781. tpl_dir.path().to_str().unwrap(),
  782. dst_dir.path(),
  783. &CopyOptions {
  784. data,
  785. defaults: false,
  786. overwrite: false,
  787. ..CopyOptions::default()
  788. },
  789. &AlwaysYesPrompter,
  790. &NoopReporter,
  791. )
  792. .unwrap();
  793. assert_eq!(rep.updated, 1);
  794. assert_eq!(
  795. fs::read_to_string(dst_dir.path().join("file.txt")).unwrap(),
  796. "content=updated\n"
  797. );
  798. }
  799. #[test]
  800. fn include_glob_merges_list_settings_and_supports_templated_question_fields() {
  801. let tpl_dir = TempDir::new().unwrap();
  802. let dst_dir = TempDir::new().unwrap();
  803. init_git_repo(tpl_dir.path());
  804. fs::create_dir_all(tpl_dir.path().join("parts")).unwrap();
  805. fs::write(
  806. tpl_dir.path().join("copier.yml"),
  807. r#"
  808. _exclude:
  809. - "parts"
  810. - "parts/**"
  811. - "drop1.txt"
  812. ---
  813. !include parts/*.yml
  814. "#,
  815. )
  816. .unwrap();
  817. fs::write(
  818. tpl_dir.path().join("parts/01_base.yml"),
  819. r#"
  820. _exclude:
  821. - "drop2.txt"
  822. use_int:
  823. type: bool
  824. default: true
  825. "#,
  826. )
  827. .unwrap();
  828. fs::write(
  829. tpl_dir.path().join("parts/02_dynamic.yml"),
  830. r#"
  831. dynamic_val:
  832. type: "{% if use_int %}int{% else %}str{% endif %}"
  833. default: "42"
  834. env_choice:
  835. type: str
  836. choices: "['dev', 'prod']"
  837. default: prod
  838. "#,
  839. )
  840. .unwrap();
  841. fs::write(tpl_dir.path().join("drop1.txt"), "excluded 1").unwrap();
  842. fs::write(tpl_dir.path().join("drop2.txt"), "excluded 2").unwrap();
  843. fs::write(
  844. tpl_dir.path().join("out.txt.jinja"),
  845. "val={{ dynamic_val + 1 }} env={{ env_choice }}\n",
  846. )
  847. .unwrap();
  848. commit_all(tpl_dir.path(), "v1.0.0");
  849. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  850. copy(
  851. tpl_dir.path().to_str().unwrap(),
  852. dst_dir.path(),
  853. &CopyOptions {
  854. defaults: true,
  855. ..CopyOptions::default()
  856. },
  857. &NonInteractivePrompter,
  858. &NoopReporter,
  859. )
  860. .unwrap();
  861. // Both `_exclude` lists (root + `!include parts/01_base.yml`) were merged!
  862. assert!(!dst_dir.path().join("drop1.txt").exists());
  863. assert!(!dst_dir.path().join("drop2.txt").exists());
  864. // Dynamic `type: int` coerced "42" -> 42 so `dynamic_val + 1 == 43`!
  865. assert_eq!(
  866. fs::read_to_string(dst_dir.path().join("out.txt")).unwrap(),
  867. "val=43 env=prod\n"
  868. );
  869. }
  870. #[test]
  871. fn copy_cleanup_on_error_respects_no_cleanup_flag() {
  872. let tpl_dir = TempDir::new().unwrap();
  873. let parent = TempDir::new().unwrap();
  874. fs::write(
  875. tpl_dir.path().join("copier.yml"),
  876. r#"
  877. _tasks:
  878. - "exit 1"
  879. name: demo
  880. "#,
  881. )
  882. .unwrap();
  883. fs::write(tpl_dir.path().join("hello.txt.jinja"), "hi {{ name }}").unwrap();
  884. // Default (`cleanup_on_error: true`): newly created destination is deleted on task failure.
  885. let dst_cleaned = parent.path().join("cleaned");
  886. let err = copy(
  887. tpl_dir.path().to_str().unwrap(),
  888. &dst_cleaned,
  889. &CopyOptions {
  890. defaults: true,
  891. trust: true,
  892. cleanup_on_error: true,
  893. ..CopyOptions::default()
  894. },
  895. &NonInteractivePrompter,
  896. &NoopReporter,
  897. )
  898. .unwrap_err();
  899. assert!(matches!(err, RoneoError::TaskFailed { .. }));
  900. assert!(
  901. !dst_cleaned.exists(),
  902. "destination should be cleaned up on error"
  903. );
  904. // `--no-cleanup` (`cleanup_on_error: false`): destination is kept on failure.
  905. let dst_kept = parent.path().join("kept");
  906. let err2 = copy(
  907. tpl_dir.path().to_str().unwrap(),
  908. &dst_kept,
  909. &CopyOptions {
  910. defaults: true,
  911. trust: true,
  912. cleanup_on_error: false,
  913. ..CopyOptions::default()
  914. },
  915. &NonInteractivePrompter,
  916. &NoopReporter,
  917. )
  918. .unwrap_err();
  919. assert!(matches!(err2, RoneoError::TaskFailed { .. }));
  920. assert!(dst_kept.join("hello.txt").exists());
  921. }
  922. #[test]
  923. fn update_in_monorepo_subdir_honors_skip_if_exists_new_excludes_and_operation_env() {
  924. let tpl_dir = TempDir::new().unwrap();
  925. let monorepo = TempDir::new().unwrap();
  926. // Template v1.0.0
  927. init_git_repo(tpl_dir.path());
  928. fs::write(
  929. tpl_dir.path().join("copier.yml"),
  930. r#"
  931. _skip_if_exists:
  932. - "local.env"
  933. _tasks:
  934. - "echo $COPIER_OPERATION > op.log"
  935. name: svc
  936. "#,
  937. )
  938. .unwrap();
  939. fs::write(tpl_dir.path().join("app.txt.jinja"), "v1 {{ name }}\n").unwrap();
  940. fs::write(tpl_dir.path().join("local.env.jinja"), "SECRET=v1\n").unwrap();
  941. fs::write(tpl_dir.path().join("keep_me.txt"), "v1 keep\n").unwrap();
  942. commit_all(tpl_dir.path(), "v1.0.0");
  943. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  944. // Scaffold into `services/my-svc` inside a Git monorepo
  945. init_git_repo(monorepo.path());
  946. let subproject = monorepo.path().join("services/my-svc");
  947. copy(
  948. tpl_dir.path().to_str().unwrap(),
  949. &subproject,
  950. &CopyOptions {
  951. defaults: true,
  952. trust: true,
  953. ..CopyOptions::default()
  954. },
  955. &NonInteractivePrompter,
  956. &NoopReporter,
  957. )
  958. .unwrap();
  959. assert_eq!(
  960. fs::read_to_string(subproject.join("op.log"))
  961. .unwrap()
  962. .trim(),
  963. "copy"
  964. );
  965. // User customizes local.env
  966. fs::write(subproject.join("local.env"), "SECRET=my-local-secret\n").unwrap();
  967. commit_all(monorepo.path(), "Initial monorepo commit");
  968. // Template v2.0.0 updates app.txt & local.env, and adds keep_me.txt to `_exclude`
  969. fs::write(
  970. tpl_dir.path().join("copier.yml"),
  971. r#"
  972. _exclude:
  973. - "keep_me.txt"
  974. _skip_if_exists:
  975. - "local.env"
  976. _tasks:
  977. - "echo $COPIER_OPERATION > op.log"
  978. name: svc
  979. "#,
  980. )
  981. .unwrap();
  982. fs::write(tpl_dir.path().join("app.txt.jinja"), "v2 {{ name }}\n").unwrap();
  983. fs::write(tpl_dir.path().join("local.env.jinja"), "SECRET=v2\n").unwrap();
  984. commit_all(tpl_dir.path(), "v2.0.0");
  985. git(tpl_dir.path(), &["tag", "v2.0.0"]);
  986. let report = update(
  987. &subproject,
  988. &CopyOptions {
  989. defaults: true,
  990. trust: true,
  991. context_lines: 2,
  992. ..CopyOptions::default()
  993. },
  994. &NonInteractivePrompter,
  995. &NoopReporter,
  996. )
  997. .unwrap();
  998. assert!(
  999. report.conflicts.is_empty(),
  1000. "Unexpected conflicts: {:?}",
  1001. report.conflicts
  1002. );
  1003. assert_eq!(report.commit.as_deref(), Some("v2.0.0"));
  1004. assert_eq!(
  1005. fs::read_to_string(subproject.join("app.txt")).unwrap(),
  1006. "v2 svc\n"
  1007. );
  1008. // `_skip_if_exists` prevented `local.env` from being overwritten on update!
  1009. assert_eq!(
  1010. fs::read_to_string(subproject.join("local.env")).unwrap(),
  1011. "SECRET=my-local-secret\n"
  1012. );
  1013. // Newly excluded `keep_me.txt` was NOT deleted from the user's subproject!
  1014. assert!(subproject.join("keep_me.txt").exists());
  1015. // Task received `COPIER_OPERATION=update`!
  1016. assert_eq!(
  1017. fs::read_to_string(subproject.join("op.log"))
  1018. .unwrap()
  1019. .trim(),
  1020. "update"
  1021. );
  1022. }
  1023. #[test]
  1024. fn yield_tag_expands_nested_dirs_and_files_on_disk_and_git_tree() {
  1025. let tpl_dir = TempDir::new().unwrap();
  1026. let dst_disk = TempDir::new().unwrap();
  1027. let dst_git = TempDir::new().unwrap();
  1028. fs::write(
  1029. tpl_dir.path().join("copier.yml"),
  1030. r"
  1031. services:
  1032. type: yaml
  1033. default:
  1034. - auth
  1035. - billing
  1036. envs:
  1037. type: yaml
  1038. default:
  1039. - dev
  1040. - prod
  1041. ",
  1042. )
  1043. .unwrap();
  1044. let nested_dir = tpl_dir
  1045. .path()
  1046. .join("{% yield svc from services %}{{ svc }}{% endyield %}");
  1047. fs::create_dir_all(&nested_dir).unwrap();
  1048. fs::write(
  1049. nested_dir.join("{% yield env from envs %}{{ env }}.yml{% endyield %}.jinja"),
  1050. "service: {{ svc }}\nenv: {{ env }}\n",
  1051. )
  1052. .unwrap();
  1053. // 1. Disk-backed template
  1054. copy(
  1055. tpl_dir.path().to_str().unwrap(),
  1056. dst_disk.path(),
  1057. &CopyOptions {
  1058. defaults: true,
  1059. ..CopyOptions::default()
  1060. },
  1061. &NonInteractivePrompter,
  1062. &NoopReporter,
  1063. )
  1064. .unwrap();
  1065. for svc in ["auth", "billing"] {
  1066. for env in ["dev", "prod"] {
  1067. let content =
  1068. fs::read_to_string(dst_disk.path().join(format!("{svc}/{env}.yml"))).unwrap();
  1069. assert_eq!(content, format!("service: {svc}\nenv: {env}\n"));
  1070. }
  1071. }
  1072. // 2. GitTree-backed (in-memory gix) template
  1073. init_git_repo(tpl_dir.path());
  1074. commit_all(tpl_dir.path(), "v1.0.0");
  1075. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  1076. copy(
  1077. tpl_dir.path().to_str().unwrap(),
  1078. dst_git.path(),
  1079. &CopyOptions {
  1080. defaults: true,
  1081. ..CopyOptions::default()
  1082. },
  1083. &NonInteractivePrompter,
  1084. &NoopReporter,
  1085. )
  1086. .unwrap();
  1087. for svc in ["auth", "billing"] {
  1088. for env in ["dev", "prod"] {
  1089. let content =
  1090. fs::read_to_string(dst_git.path().join(format!("{svc}/{env}.yml"))).unwrap();
  1091. assert_eq!(content, format!("service: {svc}\nenv: {env}\n"));
  1092. }
  1093. }
  1094. }
  1095. #[test]
  1096. fn extra_jinja_filters_task_extra_env_old_template_warning_and_git_bundle() {
  1097. use std::sync::Mutex;
  1098. struct CaptureReporter(Mutex<Vec<String>>);
  1099. impl roneo_core::Reporter for CaptureReporter {
  1100. fn emit(&self, event: roneo_core::ActionEvent) {
  1101. if let roneo_core::ActionEvent::Warning(w) = event {
  1102. self.0.lock().unwrap().push(w);
  1103. }
  1104. }
  1105. }
  1106. let tpl_dir = TempDir::new().unwrap();
  1107. let bundle_dir = TempDir::new().unwrap();
  1108. let dst_dir = TempDir::new().unwrap();
  1109. init_git_repo(tpl_dir.path());
  1110. fs::write(
  1111. tpl_dir.path().join("copier.yml"),
  1112. r#"
  1113. _min_copier_version: "8.0.0"
  1114. _tasks:
  1115. - command: "echo $CUSTOM_TAG > env.txt"
  1116. extra_env:
  1117. CUSTOM_TAG: "hello-{{ label | to_snake }}"
  1118. label:
  1119. type: str
  1120. default: "MySuperService"
  1121. qmark: "🚀"
  1122. "#,
  1123. )
  1124. .unwrap();
  1125. fs::write(
  1126. tpl_dir.path().join("filters.txt.jinja"),
  1127. r#"snake={{ label | to_snake }}
  1128. kebab={{ label | to_kebab }}
  1129. camel={{ label | to_camel }}
  1130. pascal={{ "my_super_service" | to_pascal }}
  1131. b64={{ "roneo!" | b64encode }}
  1132. dec={{ "cm9uZW8h" | b64decode }}
  1133. year_len={{ now("%Y") | length }}
  1134. "#,
  1135. )
  1136. .unwrap();
  1137. commit_all(tpl_dir.path(), "v1.0.0");
  1138. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  1139. // Export as a `.bundle` file and copy directly from the git bundle!
  1140. let bundle_path = bundle_dir.path().join("tpl.bundle");
  1141. git(
  1142. tpl_dir.path(),
  1143. &["bundle", "create", bundle_path.to_str().unwrap(), "--all"],
  1144. );
  1145. let reporter = CaptureReporter(Mutex::new(Vec::new()));
  1146. copy(
  1147. bundle_path.to_str().unwrap(),
  1148. dst_dir.path(),
  1149. &CopyOptions {
  1150. defaults: true,
  1151. trust: true,
  1152. ..CopyOptions::default()
  1153. },
  1154. &NonInteractivePrompter,
  1155. &reporter,
  1156. )
  1157. .unwrap();
  1158. let rendered = fs::read_to_string(dst_dir.path().join("filters.txt")).unwrap();
  1159. assert!(
  1160. rendered.contains("snake=my_super_service\n"),
  1161. "got:\n{rendered}"
  1162. );
  1163. assert!(
  1164. rendered.contains("kebab=my-super-service\n"),
  1165. "got:\n{rendered}"
  1166. );
  1167. assert!(
  1168. rendered.contains("camel=mySuperService\n"),
  1169. "got:\n{rendered}"
  1170. );
  1171. assert!(
  1172. rendered.contains("pascal=MySuperService\n"),
  1173. "got:\n{rendered}"
  1174. );
  1175. assert!(rendered.contains("b64=cm9uZW8h\n"), "got:\n{rendered}");
  1176. assert!(rendered.contains("dec=roneo!\n"), "got:\n{rendered}");
  1177. assert!(rendered.contains("year_len=4\n"), "got:\n{rendered}");
  1178. assert_eq!(
  1179. fs::read_to_string(dst_dir.path().join("env.txt"))
  1180. .unwrap()
  1181. .trim(),
  1182. "hello-my_super_service"
  1183. );
  1184. let warnings = reporter.0.lock().unwrap();
  1185. assert!(
  1186. warnings.iter().any(|w| w.contains("older Copier 8.0.0")),
  1187. "expected OldTemplateWarning, got: {warnings:?}"
  1188. );
  1189. }
  1190. #[test]
  1191. fn update_never_conflicts_on_answers_file_when_user_edits_header() {
  1192. let tpl_dir = TempDir::new().unwrap();
  1193. let dst_dir = TempDir::new().unwrap();
  1194. init_git_repo(tpl_dir.path());
  1195. fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap();
  1196. fs::write(tpl_dir.path().join("f.txt.jinja"), "v1 {{ name }}\n").unwrap();
  1197. commit_all(tpl_dir.path(), "v1.0.0");
  1198. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  1199. copy(
  1200. tpl_dir.path().to_str().unwrap(),
  1201. dst_dir.path(),
  1202. &CopyOptions {
  1203. defaults: true,
  1204. ..CopyOptions::default()
  1205. },
  1206. &NonInteractivePrompter,
  1207. &NoopReporter,
  1208. )
  1209. .unwrap();
  1210. init_git_repo(dst_dir.path());
  1211. commit_all(dst_dir.path(), "init");
  1212. // User modifies the comment line in `.copier-answers.yml` (classic cause of false conflict if patched).
  1213. let answers_path = dst_dir.path().join(".copier-answers.yml");
  1214. let raw = fs::read_to_string(&answers_path).unwrap();
  1215. fs::write(&answers_path, format!("# custom user comment\n{raw}")).unwrap();
  1216. commit_all(dst_dir.path(), "user edited answers comment");
  1217. fs::write(tpl_dir.path().join("f.txt.jinja"), "v2 {{ name }}\n").unwrap();
  1218. commit_all(tpl_dir.path(), "v2.0.0");
  1219. git(tpl_dir.path(), &["tag", "v2.0.0"]);
  1220. let rep = update(
  1221. dst_dir.path(),
  1222. &CopyOptions {
  1223. defaults: true,
  1224. ..CopyOptions::default()
  1225. },
  1226. &NonInteractivePrompter,
  1227. &NoopReporter,
  1228. )
  1229. .unwrap();
  1230. assert!(
  1231. rep.conflicts.is_empty(),
  1232. "Answers file must not conflict during update, got: {:?}",
  1233. rep.conflicts
  1234. );
  1235. let updated_answers = AnswersMap::load(&answers_path).unwrap();
  1236. assert_eq!(updated_answers.commit(), Some("v2.0.0"));
  1237. }
  1238. #[test]
  1239. fn update_inline_conflict_works_after_git_history_squash() {
  1240. let tpl_dir = TempDir::new().unwrap();
  1241. let dst_dir = TempDir::new().unwrap();
  1242. init_git_repo(tpl_dir.path());
  1243. fs::write(tpl_dir.path().join("copier.yml"), "name: app\n").unwrap();
  1244. fs::write(tpl_dir.path().join("config.txt.jinja"), "port=8080\n").unwrap();
  1245. commit_all(tpl_dir.path(), "v1.0.0");
  1246. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  1247. copy(
  1248. tpl_dir.path().to_str().unwrap(),
  1249. dst_dir.path(),
  1250. &CopyOptions {
  1251. defaults: true,
  1252. ..CopyOptions::default()
  1253. },
  1254. &NonInteractivePrompter,
  1255. &NoopReporter,
  1256. )
  1257. .unwrap();
  1258. // User edits config.txt BEFORE initializing git (simulating a squashed history where
  1259. // the original v1.0.0 blob OID does NOT exist in destination `.git/objects`!).
  1260. fs::write(dst_dir.path().join("config.txt"), "port=9090\n").unwrap();
  1261. init_git_repo(dst_dir.path());
  1262. commit_all(dst_dir.path(), "squashed initial commit");
  1263. // Upstream v2.0.0 changes same line differently
  1264. fs::write(tpl_dir.path().join("config.txt.jinja"), "port=3000\n").unwrap();
  1265. commit_all(tpl_dir.path(), "v2.0.0");
  1266. git(tpl_dir.path(), &["tag", "v2.0.0"]);
  1267. let report = update(
  1268. dst_dir.path(),
  1269. &CopyOptions {
  1270. defaults: true,
  1271. conflict_mode: ConflictMode::Inline,
  1272. ..CopyOptions::default()
  1273. },
  1274. &NonInteractivePrompter,
  1275. &NoopReporter,
  1276. )
  1277. .unwrap();
  1278. assert_eq!(report.conflicts, vec!["config.txt"]);
  1279. assert!(!dst_dir.path().join("config.txt.rej").exists());
  1280. let content = fs::read_to_string(dst_dir.path().join("config.txt")).unwrap();
  1281. assert!(
  1282. content.contains("<<<<<<< before updating"),
  1283. "got:\n{content}"
  1284. );
  1285. assert!(content.contains("port=9090"), "got:\n{content}");
  1286. assert!(content.contains("port=3000"), "got:\n{content}");
  1287. assert!(
  1288. content.contains(">>>>>>> after updating"),
  1289. "got:\n{content}"
  1290. );
  1291. }
  1292. #[test]
  1293. fn update_protects_gitignored_files_blocks_downgrades_and_cleans_renamed_answers_file() {
  1294. let tpl_dir = TempDir::new().unwrap();
  1295. let dst_dir = TempDir::new().unwrap();
  1296. init_git_repo(tpl_dir.path());
  1297. fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap();
  1298. fs::write(tpl_dir.path().join("app.txt.jinja"), "v1 {{ name }}\n").unwrap();
  1299. fs::write(tpl_dir.path().join("local.secret.jinja"), "SECRET=v1\n").unwrap();
  1300. commit_all(tpl_dir.path(), "v1.0.0");
  1301. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  1302. copy(
  1303. tpl_dir.path().to_str().unwrap(),
  1304. dst_dir.path(),
  1305. &CopyOptions {
  1306. defaults: true,
  1307. ..CopyOptions::default()
  1308. },
  1309. &NonInteractivePrompter,
  1310. &NoopReporter,
  1311. )
  1312. .unwrap();
  1313. // User gitignores `local.secret` and puts a private value in it.
  1314. fs::write(dst_dir.path().join(".gitignore"), "local.secret\n").unwrap();
  1315. init_git_repo(dst_dir.path());
  1316. commit_all(dst_dir.path(), "init");
  1317. fs::write(dst_dir.path().join("local.secret"), "SECRET=user-ignored\n").unwrap();
  1318. // Template v2.0.0 renames `_answers_file` and modifies both `app.txt` and `local.secret`.
  1319. fs::write(
  1320. tpl_dir.path().join("copier.yml"),
  1321. "_answers_file: .config/answers.yml\nname: demo\n",
  1322. )
  1323. .unwrap();
  1324. fs::write(tpl_dir.path().join("app.txt.jinja"), "v2 {{ name }}\n").unwrap();
  1325. fs::write(tpl_dir.path().join("local.secret.jinja"), "SECRET=v2\n").unwrap();
  1326. commit_all(tpl_dir.path(), "v2.0.0");
  1327. git(tpl_dir.path(), &["tag", "v2.0.0"]);
  1328. let rep = update(
  1329. dst_dir.path(),
  1330. &CopyOptions {
  1331. defaults: true,
  1332. ..CopyOptions::default()
  1333. },
  1334. &NonInteractivePrompter,
  1335. &NoopReporter,
  1336. )
  1337. .unwrap();
  1338. assert!(
  1339. rep.conflicts.is_empty(),
  1340. "Unexpected conflicts: {:?}",
  1341. rep.conflicts
  1342. );
  1343. assert_eq!(
  1344. fs::read_to_string(dst_dir.path().join("app.txt")).unwrap(),
  1345. "v2 demo\n"
  1346. );
  1347. // `.gitignore`-d `local.secret` was untouched!
  1348. assert_eq!(
  1349. fs::read_to_string(dst_dir.path().join("local.secret")).unwrap(),
  1350. "SECRET=user-ignored\n"
  1351. );
  1352. // Old `.copier-answers.yml` cleaned up and replaced by `.config/answers.yml`!
  1353. assert!(!dst_dir.path().join(".copier-answers.yml").exists());
  1354. assert!(dst_dir.path().join(".config/answers.yml").is_file());
  1355. commit_all(dst_dir.path(), "upgraded to v2.0.0");
  1356. // Attempting to downgrade from v2.0.0 -> v1.0.0 must be rejected!
  1357. let err = update(
  1358. dst_dir.path(),
  1359. &CopyOptions {
  1360. answers_file: Some(".config/answers.yml".into()),
  1361. vcs_ref: Some("v1.0.0".into()),
  1362. defaults: true,
  1363. ..CopyOptions::default()
  1364. },
  1365. &NonInteractivePrompter,
  1366. &NoopReporter,
  1367. )
  1368. .unwrap_err();
  1369. assert!(matches!(err, RoneoError::DowngradeNotSupported { .. }));
  1370. }
  1371. #[test]
  1372. fn task_stage_context_and_nullable_typed_defaults() {
  1373. let tpl_dir = TempDir::new().unwrap();
  1374. let dst_dir = TempDir::new().unwrap();
  1375. fs::write(
  1376. tpl_dir.path().join("copier.yml"),
  1377. r#"
  1378. _tasks:
  1379. - command: "echo {{ _stage }}:$STAGE > stage.txt"
  1380. when: "{{ _stage == 'task' }}"
  1381. opt_int:
  1382. type: int
  1383. default: null
  1384. opt_float:
  1385. type: float
  1386. default: null
  1387. opt_bool:
  1388. type: bool
  1389. default: null
  1390. "#,
  1391. )
  1392. .unwrap();
  1393. fs::write(
  1394. tpl_dir.path().join("vals.txt.jinja"),
  1395. "int={{ opt_int is none }} float={{ opt_float is none }} bool={{ opt_bool is none }}\n",
  1396. )
  1397. .unwrap();
  1398. copy(
  1399. tpl_dir.path().to_str().unwrap(),
  1400. dst_dir.path(),
  1401. &CopyOptions {
  1402. defaults: true,
  1403. trust: true,
  1404. ..CopyOptions::default()
  1405. },
  1406. &NonInteractivePrompter,
  1407. &NoopReporter,
  1408. )
  1409. .unwrap();
  1410. assert_eq!(
  1411. fs::read_to_string(dst_dir.path().join("stage.txt"))
  1412. .unwrap()
  1413. .trim(),
  1414. "task:task"
  1415. );
  1416. assert_eq!(
  1417. fs::read_to_string(dst_dir.path().join("vals.txt")).unwrap(),
  1418. "int=True float=True bool=True\n"
  1419. );
  1420. let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap();
  1421. assert_eq!(answers.user.get("opt_int"), Some(&json!(null)));
  1422. assert_eq!(answers.user.get("opt_float"), Some(&json!(null)));
  1423. assert_eq!(answers.user.get("opt_bool"), Some(&json!(null)));
  1424. }
  1425. #[test]
  1426. fn check_update_reports_available_updates_and_respects_prereleases() {
  1427. let tpl_dir = TempDir::new().unwrap();
  1428. let dst_dir = TempDir::new().unwrap();
  1429. init_git_repo(tpl_dir.path());
  1430. fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap();
  1431. fs::write(tpl_dir.path().join("app.txt.jinja"), "v1 {{ name }}\n").unwrap();
  1432. commit_all(tpl_dir.path(), "v1.0.0");
  1433. git(tpl_dir.path(), &["tag", "v1.0.0"]);
  1434. copy(
  1435. tpl_dir.path().to_str().unwrap(),
  1436. dst_dir.path(),
  1437. &CopyOptions {
  1438. defaults: true,
  1439. ..CopyOptions::default()
  1440. },
  1441. &NonInteractivePrompter,
  1442. &NoopReporter,
  1443. )
  1444. .unwrap();
  1445. // Up-to-date on v1.0.0
  1446. let rep = check_update(dst_dir.path(), &CopyOptions::default()).unwrap();
  1447. assert!(!rep.update_available);
  1448. assert_eq!(rep.current_version, "v1.0.0");
  1449. assert_eq!(rep.latest_version, "v1.0.0");
  1450. // Tag a prerelease v2.0.0rc1
  1451. fs::write(tpl_dir.path().join("app.txt.jinja"), "v2rc1 {{ name }}\n").unwrap();
  1452. commit_all(tpl_dir.path(), "v2.0.0rc1");
  1453. git(tpl_dir.path(), &["tag", "v2.0.0rc1"]);
  1454. let rep_stable = check_update(dst_dir.path(), &CopyOptions::default()).unwrap();
  1455. assert!(!rep_stable.update_available);
  1456. assert_eq!(rep_stable.latest_version, "v1.0.0");
  1457. let rep_pre = check_update(
  1458. dst_dir.path(),
  1459. &CopyOptions {
  1460. use_prereleases: true,
  1461. ..CopyOptions::default()
  1462. },
  1463. )
  1464. .unwrap();
  1465. assert!(rep_pre.update_available);
  1466. assert_eq!(rep_pre.current_version, "v1.0.0");
  1467. assert_eq!(rep_pre.latest_version, "v2.0.0rc1");
  1468. // Tag stable v2.0.0
  1469. fs::write(tpl_dir.path().join("app.txt.jinja"), "v2 {{ name }}\n").unwrap();
  1470. commit_all(tpl_dir.path(), "v2.0.0");
  1471. git(tpl_dir.path(), &["tag", "v2.0.0"]);
  1472. let rep_v2 = check_update(dst_dir.path(), &CopyOptions::default()).unwrap();
  1473. assert!(rep_v2.update_available);
  1474. assert_eq!(rep_v2.current_version, "v1.0.0");
  1475. assert_eq!(rep_v2.latest_version, "v2.0.0");
  1476. }
  1477. #[test]
  1478. fn question_ask_attribute_and_cli_ask_flag_override() {
  1479. use std::sync::Mutex;
  1480. struct RecordingPrompter {
  1481. asked: Mutex<Vec<String>>,
  1482. }
  1483. impl Prompter for RecordingPrompter {
  1484. fn prompt_string(&self, req: &PromptRequest) -> roneo_core::Result<String> {
  1485. self.asked.lock().unwrap().push(req.name.clone());
  1486. Ok(format!("prompted-{}", req.name))
  1487. }
  1488. fn prompt_bool(&self, req: &PromptRequest, default: bool) -> roneo_core::Result<bool> {
  1489. self.asked.lock().unwrap().push(req.name.clone());
  1490. Ok(default)
  1491. }
  1492. fn prompt_select(
  1493. &self,
  1494. req: &PromptRequest,
  1495. choices: &[roneo_core::config::ChoiceSpec],
  1496. default_idx: Option<usize>,
  1497. ) -> roneo_core::Result<serde_json::Value> {
  1498. self.asked.lock().unwrap().push(req.name.clone());
  1499. Ok(choices[default_idx.unwrap_or(0)].value.clone())
  1500. }
  1501. fn prompt_multiselect(
  1502. &self,
  1503. req: &PromptRequest,
  1504. _choices: &[roneo_core::config::ChoiceSpec],
  1505. _defaults: &[usize],
  1506. ) -> roneo_core::Result<Vec<serde_json::Value>> {
  1507. self.asked.lock().unwrap().push(req.name.clone());
  1508. Ok(Vec::new())
  1509. }
  1510. fn show_validation_error(&self, _name: &str, _message: &str) {}
  1511. }
  1512. let tpl_dir = TempDir::new().unwrap();
  1513. let dst_dir = TempDir::new().unwrap();
  1514. fs::write(
  1515. tpl_dir.path().join("copier.yml"),
  1516. r#"
  1517. project:
  1518. type: str
  1519. default: default-proj
  1520. silent_token:
  1521. type: str
  1522. default: auto-token
  1523. ask: false
  1524. conditional_field:
  1525. type: str
  1526. default: auto-cond
  1527. ask: "{{ project == 'custom' }}"
  1528. "#,
  1529. )
  1530. .unwrap();
  1531. fs::write(
  1532. tpl_dir.path().join("out.txt.jinja"),
  1533. "{{ project }}|{{ silent_token }}|{{ conditional_field }}\n",
  1534. )
  1535. .unwrap();
  1536. // 1. Interactive without `--defaults`: `silent_token` (`ask: false`) and `conditional_field`
  1537. // (`ask` evaluates false) must NOT be prompted; only `project` is asked.
  1538. let prompter = RecordingPrompter {
  1539. asked: Mutex::new(Vec::new()),
  1540. };
  1541. copy(
  1542. tpl_dir.path().to_str().unwrap(),
  1543. dst_dir.path(),
  1544. &CopyOptions::default(),
  1545. &prompter,
  1546. &NoopReporter,
  1547. )
  1548. .unwrap();
  1549. assert_eq!(*prompter.asked.lock().unwrap(), vec!["project"]);
  1550. assert_eq!(
  1551. fs::read_to_string(dst_dir.path().join("out.txt")).unwrap(),
  1552. "prompted-project|auto-token|auto-cond\n"
  1553. );
  1554. // 2. With `--defaults` AND `--ask silent_*` (fnmatch glob): ONLY `silent_token` is forced interactive!
  1555. let dst_dir2 = TempDir::new().unwrap();
  1556. let prompter2 = RecordingPrompter {
  1557. asked: Mutex::new(Vec::new()),
  1558. };
  1559. copy(
  1560. tpl_dir.path().to_str().unwrap(),
  1561. dst_dir2.path(),
  1562. &CopyOptions {
  1563. defaults: true,
  1564. ask_questions: vec!["silent_*".into()],
  1565. ..CopyOptions::default()
  1566. },
  1567. &prompter2,
  1568. &NoopReporter,
  1569. )
  1570. .unwrap();
  1571. assert_eq!(*prompter2.asked.lock().unwrap(), vec!["silent_token"]);
  1572. assert_eq!(
  1573. fs::read_to_string(dst_dir2.path().join("out.txt")).unwrap(),
  1574. "default-proj|prompted-silent_token|auto-cond\n"
  1575. );
  1576. }
  1577. #[test]
  1578. fn multiline_exclude_and_symlink_overwrite_without_following() {
  1579. let tpl_dir = TempDir::new().unwrap();
  1580. let dst_dir = TempDir::new().unwrap();
  1581. let outside_dir = TempDir::new().unwrap();
  1582. fs::write(
  1583. tpl_dir.path().join("copier.yml"),
  1584. r"
  1585. _exclude:
  1586. - |
  1587. {% if true %}
  1588. drop_a.txt
  1589. drop_b.txt
  1590. {% endif %}
  1591. name: demo
  1592. ",
  1593. )
  1594. .unwrap();
  1595. fs::write(tpl_dir.path().join("keep.txt.jinja"), "kept {{ name }}\n").unwrap();
  1596. fs::write(tpl_dir.path().join("drop_a.txt"), "a").unwrap();
  1597. fs::write(tpl_dir.path().join("drop_b.txt"), "b").unwrap();
  1598. fs::write(tpl_dir.path().join("broken_target.txt"), "fresh\n").unwrap();
  1599. // Pre-populate destination with:
  1600. // 1) a live symlink `keep.txt -> outside/secret.txt`
  1601. // 2) a broken symlink `broken_target.txt -> /nonexistent/path`
  1602. let outside_secret = outside_dir.path().join("secret.txt");
  1603. fs::write(&outside_secret, "DO NOT TOUCH\n").unwrap();
  1604. #[cfg(unix)]
  1605. {
  1606. std::os::unix::fs::symlink(&outside_secret, dst_dir.path().join("keep.txt")).unwrap();
  1607. std::os::unix::fs::symlink(
  1608. outside_dir.path().join("missing.txt"),
  1609. dst_dir.path().join("broken_target.txt"),
  1610. )
  1611. .unwrap();
  1612. }
  1613. copy(
  1614. tpl_dir.path().to_str().unwrap(),
  1615. dst_dir.path(),
  1616. &CopyOptions {
  1617. defaults: true,
  1618. overwrite: true,
  1619. ..CopyOptions::default()
  1620. },
  1621. &NonInteractivePrompter,
  1622. &NoopReporter,
  1623. )
  1624. .unwrap();
  1625. // Multi-line `_exclude` dropped both files.
  1626. assert!(!dst_dir.path().join("drop_a.txt").exists());
  1627. assert!(!dst_dir.path().join("drop_b.txt").exists());
  1628. // Destination symlinks were unlinked and replaced with regular files; external target untouched!
  1629. assert_eq!(
  1630. fs::read_to_string(dst_dir.path().join("keep.txt")).unwrap(),
  1631. "kept demo\n"
  1632. );
  1633. assert_eq!(
  1634. fs::read_to_string(dst_dir.path().join("broken_target.txt")).unwrap(),
  1635. "fresh\n"
  1636. );
  1637. assert_eq!(
  1638. fs::read_to_string(&outside_secret).unwrap(),
  1639. "DO NOT TOUCH\n"
  1640. );
  1641. #[cfg(unix)]
  1642. {
  1643. assert!(
  1644. !fs::symlink_metadata(dst_dir.path().join("keep.txt"))
  1645. .unwrap()
  1646. .file_type()
  1647. .is_symlink()
  1648. );
  1649. assert!(
  1650. !fs::symlink_metadata(dst_dir.path().join("broken_target.txt"))
  1651. .unwrap()
  1652. .file_type()
  1653. .is_symlink()
  1654. );
  1655. }
  1656. }
  1657. #[test]
  1658. fn security_path_containment_and_git_ref_injection_guard() {
  1659. // 1. `!include ../escape.yml` must be rejected.
  1660. let parent_dir = TempDir::new().unwrap();
  1661. let tpl_dir = parent_dir.path().join("tpl");
  1662. fs::create_dir_all(&tpl_dir).unwrap();
  1663. fs::write(parent_dir.path().join("escape.yml"), "secret: leaked\n").unwrap();
  1664. fs::write(tpl_dir.join("copier.yml"), "!include ../escape.yml\n").unwrap();
  1665. let dst_dir = TempDir::new().unwrap();
  1666. let err = copy(
  1667. tpl_dir.to_str().unwrap(),
  1668. dst_dir.path(),
  1669. &CopyOptions {
  1670. defaults: true,
  1671. ..CopyOptions::default()
  1672. },
  1673. &NonInteractivePrompter,
  1674. &NoopReporter,
  1675. )
  1676. .unwrap_err();
  1677. assert!(
  1678. err.to_string().contains("escapes template root") || err.to_string().contains("Invalid"),
  1679. "expected path containment error, got: {err}"
  1680. );
  1681. // 2. Jinja `{% include '../secret.txt' %}` and symlink escaping template root must be blocked.
  1682. let tpl_dir2 = parent_dir.path().join("tpl2");
  1683. fs::create_dir_all(&tpl_dir2).unwrap();
  1684. fs::write(parent_dir.path().join("secret.txt"), "TOP-SECRET").unwrap();
  1685. fs::write(tpl_dir2.join("copier.yml"), "name: ok\n").unwrap();
  1686. fs::write(
  1687. tpl_dir2.join("leak.txt.jinja"),
  1688. "{% include '../secret.txt' %}\n",
  1689. )
  1690. .unwrap();
  1691. let dst_dir2 = TempDir::new().unwrap();
  1692. let err2 = copy(
  1693. tpl_dir2.to_str().unwrap(),
  1694. dst_dir2.path(),
  1695. &CopyOptions {
  1696. defaults: true,
  1697. ..CopyOptions::default()
  1698. },
  1699. &NonInteractivePrompter,
  1700. &NoopReporter,
  1701. )
  1702. .unwrap_err();
  1703. assert!(
  1704. err2.to_string().contains("not found") || err2.to_string().contains("template"),
  1705. "expected Jinja include containment failure, got: {err2}"
  1706. );
  1707. // 3. Git refs starting with `-` must be rejected (argument injection defense).
  1708. let git_tpl = TempDir::new().unwrap();
  1709. init_git_repo(git_tpl.path());
  1710. fs::write(git_tpl.path().join("copier.yml"), "name: ok\n").unwrap();
  1711. fs::write(git_tpl.path().join("a.txt"), "hi\n").unwrap();
  1712. commit_all(git_tpl.path(), "init");
  1713. let dst_dir3 = TempDir::new().unwrap();
  1714. let err3 = copy(
  1715. git_tpl.path().to_str().unwrap(),
  1716. dst_dir3.path(),
  1717. &CopyOptions {
  1718. vcs_ref: Some("--upload-pack=evil".into()),
  1719. defaults: true,
  1720. ..CopyOptions::default()
  1721. },
  1722. &NonInteractivePrompter,
  1723. &NoopReporter,
  1724. )
  1725. .unwrap_err();
  1726. assert!(
  1727. err3.to_string().contains("may not start with '-'"),
  1728. "expected git ref injection error, got: {err3}"
  1729. );
  1730. }
  1731. #[test]
  1732. fn security_blocks_rendered_path_answers_subdir_and_external_data_traversal() {
  1733. let sandbox = TempDir::new().unwrap();
  1734. let victim_secret = sandbox.path().join("outside_secret.yml");
  1735. fs::write(&victim_secret, "token: topsecret\n").unwrap();
  1736. // 0. TempDir must be 0700 on Unix.
  1737. #[cfg(unix)]
  1738. {
  1739. use std::os::unix::fs::PermissionsExt;
  1740. let mode = fs::metadata(sandbox.path()).unwrap().permissions().mode() & 0o777;
  1741. assert_eq!(mode, 0o700, "TempDir must be private (0700)");
  1742. }
  1743. // 1. Rendered filename attempting `../pwned.txt` must be rejected.
  1744. let tpl1 = sandbox.path().join("tpl_path");
  1745. let dst1 = sandbox.path().join("dst1");
  1746. fs::create_dir_all(&tpl1).unwrap();
  1747. fs::write(tpl1.join("copier.yml"), "target: '../pwned.txt'\n").unwrap();
  1748. fs::write(tpl1.join("{{ target }}.jinja"), "pwned").unwrap();
  1749. let err = copy(
  1750. tpl1.to_str().unwrap(),
  1751. &dst1,
  1752. &CopyOptions {
  1753. defaults: true,
  1754. ..CopyOptions::default()
  1755. },
  1756. &NonInteractivePrompter,
  1757. &NoopReporter,
  1758. )
  1759. .unwrap_err();
  1760. assert!(
  1761. err.to_string().contains("escapes destination"),
  1762. "expected rendered path escape error, got: {err}"
  1763. );
  1764. assert!(!sandbox.path().join("pwned.txt").exists());
  1765. // 2. `_answers_file: ../pwned-answers.yml` must be rejected.
  1766. let tpl2 = sandbox.path().join("tpl_ans");
  1767. let dst2 = sandbox.path().join("dst2");
  1768. fs::create_dir_all(&tpl2).unwrap();
  1769. fs::write(
  1770. tpl2.join("copier.yml"),
  1771. "_answers_file: ../pwned-answers.yml\nname: x\n",
  1772. )
  1773. .unwrap();
  1774. fs::write(tpl2.join("ok.txt"), "hi").unwrap();
  1775. let err = copy(
  1776. tpl2.to_str().unwrap(),
  1777. &dst2,
  1778. &CopyOptions {
  1779. defaults: true,
  1780. ..CopyOptions::default()
  1781. },
  1782. &NonInteractivePrompter,
  1783. &NoopReporter,
  1784. )
  1785. .unwrap_err();
  1786. assert!(
  1787. err.to_string().contains("escapes destination"),
  1788. "expected answers_file escape error, got: {err}"
  1789. );
  1790. assert!(!sandbox.path().join("pwned-answers.yml").exists());
  1791. // 3. `_subdirectory: ../` must be rejected.
  1792. let tpl3 = sandbox.path().join("tpl_sub");
  1793. let dst3 = sandbox.path().join("dst3");
  1794. fs::create_dir_all(&tpl3).unwrap();
  1795. fs::write(tpl3.join("copier.yml"), "_subdirectory: ..\nname: x\n").unwrap();
  1796. let err = copy(
  1797. tpl3.to_str().unwrap(),
  1798. &dst3,
  1799. &CopyOptions {
  1800. defaults: true,
  1801. ..CopyOptions::default()
  1802. },
  1803. &NonInteractivePrompter,
  1804. &NoopReporter,
  1805. )
  1806. .unwrap_err();
  1807. assert!(
  1808. err.to_string().contains("escapes template root"),
  1809. "expected subdirectory escape error, got: {err}"
  1810. );
  1811. // 4. `_external_data` pointing outside template/dst without `--trust` must be rejected.
  1812. let tpl4 = sandbox.path().join("tpl_ext");
  1813. let dst4 = sandbox.path().join("dst4");
  1814. fs::create_dir_all(&tpl4).unwrap();
  1815. fs::write(
  1816. tpl4.join("copier.yml"),
  1817. format!(
  1818. "_external_data:\n leak: {}\nname: x\n",
  1819. victim_secret.display()
  1820. ),
  1821. )
  1822. .unwrap();
  1823. let err = copy(
  1824. tpl4.to_str().unwrap(),
  1825. &dst4,
  1826. &CopyOptions {
  1827. defaults: true,
  1828. trust: false,
  1829. ..CopyOptions::default()
  1830. },
  1831. &NonInteractivePrompter,
  1832. &NoopReporter,
  1833. )
  1834. .unwrap_err();
  1835. assert!(
  1836. err.to_string()
  1837. .contains("Failed to load `_external_data.leak`"),
  1838. "expected external_data containment error, got: {err}"
  1839. );
  1840. // 5. `_roneo_plugins` requires `--trust` and rejects absolute paths.
  1841. let tpl5 = sandbox.path().join("tpl_plug");
  1842. let dst5 = sandbox.path().join("dst5");
  1843. fs::create_dir_all(&tpl5).unwrap();
  1844. fs::write(
  1845. tpl5.join("copier.yml"),
  1846. "_roneo_plugins:\n - /tmp/evil.wasm\nname: x\n",
  1847. )
  1848. .unwrap();
  1849. let err_untrusted = copy(
  1850. tpl5.to_str().unwrap(),
  1851. &dst5,
  1852. &CopyOptions {
  1853. defaults: true,
  1854. trust: false,
  1855. ..CopyOptions::default()
  1856. },
  1857. &NonInteractivePrompter,
  1858. &NoopReporter,
  1859. )
  1860. .unwrap_err();
  1861. assert!(matches!(err_untrusted, RoneoError::UnsafeTemplate(_)));
  1862. let err_abs = copy(
  1863. tpl5.to_str().unwrap(),
  1864. &dst5,
  1865. &CopyOptions {
  1866. defaults: true,
  1867. trust: true,
  1868. ..CopyOptions::default()
  1869. },
  1870. &NonInteractivePrompter,
  1871. &NoopReporter,
  1872. )
  1873. .unwrap_err();
  1874. assert!(
  1875. err_abs.to_string().contains("must be a relative path"),
  1876. "expected relative path plugin error, got: {err_abs}"
  1877. );
  1878. // 6. Writing through a pre-existing symlink directory inside `dst` must be refused.
  1879. #[cfg(unix)]
  1880. {
  1881. let tpl6 = sandbox.path().join("tpl_symdir");
  1882. let dst6 = sandbox.path().join("dst6");
  1883. let outside = sandbox.path().join("outside_dir");
  1884. fs::create_dir_all(tpl6.join("sub")).unwrap();
  1885. fs::create_dir_all(&dst6).unwrap();
  1886. fs::create_dir_all(&outside).unwrap();
  1887. fs::write(tpl6.join("copier.yml"), "name: x\n").unwrap();
  1888. fs::write(tpl6.join("sub/pwn.txt"), "pwned").unwrap();
  1889. std::os::unix::fs::symlink(&outside, dst6.join("sub")).unwrap();
  1890. let err_sym = copy(
  1891. tpl6.to_str().unwrap(),
  1892. &dst6,
  1893. &CopyOptions {
  1894. defaults: true,
  1895. overwrite: true,
  1896. ..CopyOptions::default()
  1897. },
  1898. &NonInteractivePrompter,
  1899. &NoopReporter,
  1900. )
  1901. .unwrap_err();
  1902. assert!(
  1903. err_sym.to_string().contains("symlink directory"),
  1904. "expected symlink directory error, got: {err_sym}"
  1905. );
  1906. assert!(!outside.join("pwn.txt").exists());
  1907. }
  1908. }