roneocratesroneo-coretestsintegration.rs
98ff76d5794bbd1480ad719803187d2c40e42403- use std::fs;
- use std::path::Path;
- use std::process::Command;
- use indexmap::IndexMap;
- use roneo_core::fs_util::TempDir;
- use roneo_core::vcs::ConflictMode;
- use roneo_core::{
- AnswersMap, CopyOptions, NonInteractivePrompter, NoopReporter, OverwriteChoice, PromptRequest,
- Prompter, RoneoError, UserSettings, check_update, copy, diff_update, recopy, update,
- };
- use serde_json::json;
- fn git(dir: &Path, args: &[&str]) {
- let out = Command::new("git")
- .current_dir(dir)
- .args(args)
- .output()
- .expect("git command should run");
- assert!(
- out.status.success(),
- "git {:?} failed: {}",
- args,
- String::from_utf8_lossy(&out.stderr)
- );
- }
- fn init_git_repo(dir: &Path) {
- git(dir, &["init", "-b", "main"]);
- git(dir, &["config", "user.name", "Test"]);
- git(dir, &["config", "user.email", "test@example.com"]);
- git(dir, &["config", "commit.gpgsign", "false"]);
- }
- fn commit_all(dir: &Path, msg: &str) {
- git(dir, &["add", "-A"]);
- git(dir, &["commit", "-m", msg]);
- }
- #[test]
- fn copy_renders_copier_template_with_pycompat_paths_secrets_and_conditions() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- _subdirectory: template
- _exclude:
- - "ignored.txt"
- project_name:
- type: str
- default: my-cool-app
- module_name:
- type: str
- default: "{{ project_name.lower().replace('-', '_') }}"
- include_extras:
- type: bool
- default: false
- api_token:
- type: str
- secret: true
- default: super-secret-value
- "#,
- )
- .unwrap();
- let tpl_sub = tpl_dir.path().join("template");
- fs::create_dir_all(tpl_sub.join("src")).unwrap();
- fs::write(
- tpl_sub.join("README.md.jinja"),
- "# {{ project_name }}\nmodule={{ module_name }}\ntoken={{ api_token }}\n",
- )
- .unwrap();
- fs::write(
- tpl_sub.join("src/{{ module_name }}.txt.jinja"),
- "hello {{ module_name }}",
- )
- .unwrap();
- fs::write(
- tpl_sub.join("{% if include_extras %}extras.txt{% endif %}.jinja"),
- "extra content",
- )
- .unwrap();
- fs::write(tpl_sub.join("ignored.txt"), "should not be copied").unwrap();
- let mut data = IndexMap::new();
- data.insert("project_name".into(), json!("Roneo-Demo"));
- let opts = CopyOptions {
- data,
- defaults: true,
- ..CopyOptions::default()
- };
- let report = copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &opts,
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert!(report.created >= 3);
- let readme = fs::read_to_string(dst_dir.path().join("README.md")).unwrap();
- assert!(readme.contains("# Roneo-Demo"));
- assert!(readme.contains("module=roneo_demo"));
- assert!(readme.contains("token=super-secret-value"));
- let mod_file = fs::read_to_string(dst_dir.path().join("src/roneo_demo.txt")).unwrap();
- assert_eq!(mod_file, "hello roneo_demo");
- // Conditional file skipped when false
- assert!(!dst_dir.path().join("extras.txt").exists());
- // Excluded file skipped
- assert!(!dst_dir.path().join("ignored.txt").exists());
- // Secret answer must NOT be written into .copier-answers.yml
- let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap();
- assert_eq!(answers.user.get("project_name"), Some(&json!("Roneo-Demo")));
- assert_eq!(answers.user.get("module_name"), Some(&json!("roneo_demo")));
- assert!(!answers.user.contains_key("api_token"));
- }
- #[test]
- fn pretend_mode_writes_nothing() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap();
- fs::write(tpl_dir.path().join("hello.txt.jinja"), "Hi {{ name }}").unwrap();
- let opts = CopyOptions {
- defaults: true,
- pretend: true,
- ..CopyOptions::default()
- };
- let report = copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &opts,
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert!(report.created >= 1);
- assert!(!dst_dir.path().join("hello.txt").exists());
- assert!(!dst_dir.path().join(".copier-answers.yml").exists());
- }
- #[test]
- fn recopy_reuses_previous_answers_and_updates_files() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- "project_name: alpha\ngreeting: hello\n",
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("info.txt.jinja"),
- "{{ greeting }}, {{ project_name }}!\n",
- )
- .unwrap();
- let mut data = IndexMap::new();
- data.insert("project_name".into(), json!("beta"));
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- data,
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("info.txt")).unwrap(),
- "hello, beta!\n"
- );
- let mut override_data = IndexMap::new();
- override_data.insert("greeting".into(), json!("bonjour"));
- recopy(
- dst_dir.path(),
- None,
- &CopyOptions {
- data: override_data,
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- // `project_name` preserved from `.copier-answers.yml`, `greeting` updated!
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("info.txt")).unwrap(),
- "bonjour, beta!\n"
- );
- }
- #[test]
- fn smart_update_preserves_local_edits_and_applies_upstream_changes() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- // Create git-backed template v1.0.0
- init_git_repo(tpl_dir.path());
- fs::write(tpl_dir.path().join("copier.yml"), "project_name: demo\n").unwrap();
- fs::write(
- tpl_dir.path().join("README.md.jinja"),
- "# {{ project_name }}\n\nTemplate header v1\n\n## Custom Notes\nWrite notes here.\n",
- )
- .unwrap();
- fs::write(tpl_dir.path().join("legacy.txt"), "old file\n").unwrap();
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- // Copy v1.0.0 into destination and commit as a git repo
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- init_git_repo(dst_dir.path());
- commit_all(dst_dir.path(), "Initial scaffold");
- // User customizes README.md and adds a custom file
- fs::write(
- dst_dir.path().join("README.md"),
- "# demo\n\nTemplate header v1\n\n## Custom Notes\nMy precious user edits!\n",
- )
- .unwrap();
- fs::write(dst_dir.path().join("user_code.rs"), "fn main() {}\n").unwrap();
- commit_all(dst_dir.path(), "User edits");
- // Template releases v2.0.0: updates header, removes legacy.txt, adds CHANGELOG.md
- fs::write(
- tpl_dir.path().join("README.md.jinja"),
- "# {{ project_name }}\n\nTemplate header v2 (improved!)\n\n## Custom Notes\nWrite notes here.\n",
- )
- .unwrap();
- fs::remove_file(tpl_dir.path().join("legacy.txt")).unwrap();
- fs::write(
- tpl_dir.path().join("CHANGELOG.md.jinja"),
- "# Changelog for {{ project_name }}\n- v2.0.0\n",
- )
- .unwrap();
- commit_all(tpl_dir.path(), "v2.0.0");
- git(tpl_dir.path(), &["tag", "v2.0.0"]);
- // Run smart update!
- let report = update(
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert!(
- report.conflicts.is_empty(),
- "Unexpected conflicts: {:?}",
- report.conflicts
- );
- assert_eq!(report.commit.as_deref(), Some("v2.0.0"));
- // README has BOTH v2 template update AND preserved user edits!
- let readme = fs::read_to_string(dst_dir.path().join("README.md")).unwrap();
- assert!(readme.contains("Template header v2 (improved!)"));
- assert!(readme.contains("My precious user edits!"));
- // New file added, legacy file removed, user custom file untouched
- assert!(dst_dir.path().join("CHANGELOG.md").exists());
- assert!(!dst_dir.path().join("legacy.txt").exists());
- assert!(dst_dir.path().join("user_code.rs").exists());
- // Answers file updated to v2.0.0
- let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap();
- assert_eq!(answers.commit(), Some("v2.0.0"));
- }
- #[test]
- fn smart_update_reports_three_way_conflicts_inline() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- init_git_repo(tpl_dir.path());
- fs::write(tpl_dir.path().join("copier.yml"), "name: app\n").unwrap();
- fs::write(tpl_dir.path().join("config.txt.jinja"), "port=8080\n").unwrap();
- commit_all(tpl_dir.path(), "v1");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- init_git_repo(dst_dir.path());
- commit_all(dst_dir.path(), "scaffold");
- // User edits same line
- fs::write(dst_dir.path().join("config.txt"), "port=9090\n").unwrap();
- commit_all(dst_dir.path(), "change port");
- // Upstream edits same line differently
- fs::write(tpl_dir.path().join("config.txt.jinja"), "port=3000\n").unwrap();
- commit_all(tpl_dir.path(), "v2");
- git(tpl_dir.path(), &["tag", "v2.0.0"]);
- let report = update(
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- conflict_mode: ConflictMode::Inline,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(report.conflicts, vec!["config.txt"]);
- let content = fs::read_to_string(dst_dir.path().join("config.txt")).unwrap();
- assert!(content.contains("<<<<<<<"));
- assert!(content.contains("port=9090"));
- assert!(content.contains("port=3000"));
- }
- #[test]
- fn tasks_require_trust_flag() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- _tasks:
- - "echo 'ran {{ name }}' > task_ran.txt"
- name: ok
- "#,
- )
- .unwrap();
- fs::write(tpl_dir.path().join("a.txt"), "hello").unwrap();
- // Without --trust -> rejected
- let err = copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- trust: false,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(matches!(err, RoneoError::UnsafeTemplate(_)));
- // With --trust -> succeeds and executes task
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- trust: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- let marker = fs::read_to_string(dst_dir.path().join("task_ran.txt")).unwrap();
- assert_eq!(marker.trim(), "ran ok");
- }
- #[test]
- fn external_data_and_extra_filters_render_cleanly() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- fs::write(
- tpl_dir.path().join("meta.yml"),
- "org: Acme\nports:\n - 80\n - 443\n",
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- _external_data:
- meta: meta.yml
- _exclude:
- - "meta.yml"
- title:
- type: str
- default: "Hello World 2026!"
- "#,
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("out.yml.jinja"),
- r#"org: {{ _external_data.meta.org }}
- slug: {{ title | slugify }}
- joined: {{ pathjoin("a", "b", "c.yml") }}
- parsed: {{ '{"k": 42}' | from_json | to_json }}
- bool_ok: {{ "yes" | to_bool }}
- "#,
- )
- .unwrap();
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- let rendered = fs::read_to_string(dst_dir.path().join("out.yml")).unwrap();
- // AutoEscape::None means `.yml` strings are NOT wrapped in extra JSON quotes!
- assert!(rendered.contains("org: Acme\n"), "got:\n{rendered}");
- assert!(
- rendered.contains("slug: hello-world-2026\n"),
- "got:\n{rendered}"
- );
- assert!(rendered.contains("joined: a/b/c.yml\n"), "got:\n{rendered}");
- assert!(
- rendered.contains("parsed: {\"k\":42}\n"),
- "got:\n{rendered}"
- );
- assert!(rendered.contains("bool_ok: True\n"), "got:\n{rendered}");
- }
- #[test]
- fn pep440_prerelease_tags_and_in_memory_gix_includes() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_stable = TempDir::new().unwrap();
- let dst_pre = TempDir::new().unwrap();
- init_git_repo(tpl_dir.path());
- fs::create_dir_all(tpl_dir.path().join("template/includes")).unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- "_subdirectory: template\n---\n!include template/questions.yml\n",
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("template/questions.yml"),
- "_exclude:\n - questions.yml\n - includes\n - includes/**\nver_label: v1\n",
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("template/includes/part.jinja"),
- "included-v1-{{ ver_label }}",
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("template/out.txt.jinja"),
- "{% include 'template/includes/part.jinja' %}\n",
- )
- .unwrap();
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- // Add a PEP 440 pre-release tag v2.0.0rc1
- fs::write(
- tpl_dir.path().join("template/includes/part.jinja"),
- "included-rc-{{ ver_label }}",
- )
- .unwrap();
- commit_all(tpl_dir.path(), "v2.0.0rc1");
- git(tpl_dir.path(), &["tag", "v2.0.0rc1"]);
- // Default (`use_prereleases = false`) selects stable `v1.0.0`!
- let rep_stable = copy(
- tpl_dir.path().to_str().unwrap(),
- dst_stable.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(rep_stable.commit.as_deref(), Some("v1.0.0"));
- assert_eq!(
- fs::read_to_string(dst_stable.path().join("out.txt")).unwrap(),
- "included-v1-v1\n"
- );
- // With `use_prereleases = true` selects `v2.0.0rc1`!
- let rep_pre = copy(
- tpl_dir.path().to_str().unwrap(),
- dst_pre.path(),
- &CopyOptions {
- defaults: true,
- use_prereleases: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(rep_pre.commit.as_deref(), Some("v2.0.0rc1"));
- assert_eq!(
- fs::read_to_string(dst_pre.path().join("out.txt")).unwrap(),
- "included-rc-v1\n"
- );
- }
- #[test]
- fn skipped_when_questions_not_persisted_and_unset_supported() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- enable_feature:
- type: bool
- default: false
- hidden_opt:
- type: str
- default: "fallback"
- when: "{{ enable_feature }}"
- unset_opt:
- type: str
- default: "{% if enable_feature %}set{% else %}{{ UNSET }}{% endif %}"
- when: "{{ enable_feature }}"
- "#,
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("f.txt.jinja"),
- "hidden={{ hidden_opt }}\n",
- )
- .unwrap();
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("f.txt")).unwrap(),
- "hidden=fallback\n"
- );
- let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap();
- assert_eq!(answers.user.get("enable_feature"), Some(&json!(false)));
- assert!(!answers.user.contains_key("hidden_opt"));
- assert!(!answers.user.contains_key("unset_opt"));
- }
- #[test]
- fn diff_update_previews_patch_without_mutating_destination() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- init_git_repo(tpl_dir.path());
- fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap();
- fs::write(tpl_dir.path().join("app.txt.jinja"), "version=1\n").unwrap();
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- fs::write(tpl_dir.path().join("app.txt.jinja"), "version=2\n").unwrap();
- commit_all(tpl_dir.path(), "v2.0.0");
- git(tpl_dir.path(), &["tag", "v2.0.0"]);
- let diff = diff_update(
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- )
- .unwrap();
- assert_eq!(diff.from_commit, "v1.0.0");
- assert_eq!(diff.to_commit.as_deref(), Some("v2.0.0"));
- assert!(diff.patch.contains("-version=1"));
- assert!(diff.patch.contains("+version=2"));
- // Destination file remains untouched!
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("app.txt")).unwrap(),
- "version=1\n"
- );
- }
- #[test]
- fn min_copier_version_and_user_settings_defaults_and_trust() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- // 1. Template requiring Copier 99.0.0 must be rejected.
- fs::write(
- tpl_dir.path().join("copier.yml"),
- "_min_copier_version: '99.0.0'\nname: demo\n",
- )
- .unwrap();
- let err = copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(matches!(err, RoneoError::IncompatibleCopierVersion { .. }));
- // 2. Compatible `_min_copier_version` + `UserSettings` (`defaults` + `trust` prefix).
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- _min_copier_version: "9.0.0"
- _tasks:
- - "echo 'trusted {{ author }}' > ran.txt"
- author:
- type: str
- default: anonymous
- "#,
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("info.txt.jinja"),
- "author={{ author }}\nfolder={{ _folder_name }}\nop={{ _copier_operation }}\nunsafe={{ _copier_conf.unsafe }}\n",
- )
- .unwrap();
- let mut user_settings = UserSettings::default();
- user_settings
- .defaults
- .insert("author".into(), json!("Jean"));
- user_settings
- .trust
- .push(format!("{}/", tpl_dir.path().parent().unwrap().display()));
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- trust: false, // Trusted via `user_settings.trust`!
- user_settings: Some(user_settings),
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- let info = fs::read_to_string(dst_dir.path().join("info.txt")).unwrap();
- let expected_folder = dst_dir.path().file_name().unwrap().to_str().unwrap();
- assert!(info.contains("author=Jean\n"), "got:\n{info}");
- assert!(
- info.contains(&format!("folder={expected_folder}\n")),
- "got:\n{info}"
- );
- assert!(info.contains("op=copy\n"), "got:\n{info}");
- assert!(info.contains("unsafe=True\n"), "got:\n{info}");
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("ran.txt"))
- .unwrap()
- .trim(),
- "trusted Jean"
- );
- }
- #[test]
- fn update_with_current_vcs_ref_and_migration_stage() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- init_git_repo(tpl_dir.path());
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- _migrations:
- - version: "2.0.0"
- when: "{{ _stage == 'before' }}"
- before:
- - "echo before >> migration.log"
- after:
- - "echo after >> migration.log"
- greeting:
- type: str
- default: hello
- "#,
- )
- .unwrap();
- fs::write(tpl_dir.path().join("msg.txt.jinja"), "{{ greeting }} v1\n").unwrap();
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- trust: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- init_git_repo(dst_dir.path());
- commit_all(dst_dir.path(), "scaffold");
- // Release v2.0.0 on the template, then update with `--vcs-ref :current:` to stay on v1.0.0
- // while changing an answer.
- fs::write(tpl_dir.path().join("msg.txt.jinja"), "{{ greeting }} v2\n").unwrap();
- commit_all(tpl_dir.path(), "v2.0.0");
- git(tpl_dir.path(), &["tag", "v2.0.0"]);
- let mut data = IndexMap::new();
- data.insert("greeting".into(), json!("bonjour"));
- let rep_current = update(
- dst_dir.path(),
- &CopyOptions {
- vcs_ref: Some(":current:".into()),
- data,
- defaults: true,
- trust: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(rep_current.commit.as_deref(), Some("v1.0.0"));
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("msg.txt")).unwrap(),
- "bonjour v1\n"
- );
- commit_all(dst_dir.path(), "re-answered at current");
- // Now upgrade to v2.0.0 and verify `_stage == 'before'` only ran the `before` stage!
- let rep_v2 = update(
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- trust: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(rep_v2.commit.as_deref(), Some("v2.0.0"));
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("msg.txt")).unwrap(),
- "bonjour v2\n"
- );
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("migration.log"))
- .unwrap()
- .trim(),
- "before"
- );
- }
- #[test]
- fn interactive_overwrite_confirmation_respects_user_choice() {
- struct AlwaysYesPrompter;
- impl Prompter for AlwaysYesPrompter {
- fn prompt_string(&self, req: &PromptRequest) -> roneo_core::Result<String> {
- Ok(req.default_display.clone().unwrap_or_default())
- }
- fn prompt_bool(&self, _req: &PromptRequest, default: bool) -> roneo_core::Result<bool> {
- Ok(default)
- }
- fn prompt_select(
- &self,
- _req: &PromptRequest,
- choices: &[roneo_core::config::ChoiceSpec],
- default_idx: Option<usize>,
- ) -> roneo_core::Result<serde_json::Value> {
- Ok(choices[default_idx.unwrap_or(0)].value.clone())
- }
- fn prompt_multiselect(
- &self,
- _req: &PromptRequest,
- _choices: &[roneo_core::config::ChoiceSpec],
- _defaults: &[usize],
- ) -> roneo_core::Result<Vec<serde_json::Value>> {
- Ok(Vec::new())
- }
- fn show_validation_error(&self, _question: &str, _error: &str) {}
- fn confirm_overwrite(&self, _path: &Path) -> roneo_core::Result<OverwriteChoice> {
- Ok(OverwriteChoice::Yes)
- }
- }
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- fs::write(tpl_dir.path().join("copier.yml"), "name: new\n").unwrap();
- fs::write(
- tpl_dir.path().join("file.txt.jinja"),
- "content={{ name }}\n",
- )
- .unwrap();
- fs::write(dst_dir.path().join("file.txt"), "old content\n").unwrap();
- let mut data = IndexMap::new();
- data.insert("name".into(), json!("updated"));
- let rep = copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- data,
- defaults: false,
- overwrite: false,
- ..CopyOptions::default()
- },
- &AlwaysYesPrompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(rep.updated, 1);
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("file.txt")).unwrap(),
- "content=updated\n"
- );
- }
- #[test]
- fn include_glob_merges_list_settings_and_supports_templated_question_fields() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- init_git_repo(tpl_dir.path());
- fs::create_dir_all(tpl_dir.path().join("parts")).unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- _exclude:
- - "parts"
- - "parts/**"
- - "drop1.txt"
- ---
- !include parts/*.yml
- "#,
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("parts/01_base.yml"),
- r#"
- _exclude:
- - "drop2.txt"
- use_int:
- type: bool
- default: true
- "#,
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("parts/02_dynamic.yml"),
- r#"
- dynamic_val:
- type: "{% if use_int %}int{% else %}str{% endif %}"
- default: "42"
- env_choice:
- type: str
- choices: "['dev', 'prod']"
- default: prod
- "#,
- )
- .unwrap();
- fs::write(tpl_dir.path().join("drop1.txt"), "excluded 1").unwrap();
- fs::write(tpl_dir.path().join("drop2.txt"), "excluded 2").unwrap();
- fs::write(
- tpl_dir.path().join("out.txt.jinja"),
- "val={{ dynamic_val + 1 }} env={{ env_choice }}\n",
- )
- .unwrap();
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- // Both `_exclude` lists (root + `!include parts/01_base.yml`) were merged!
- assert!(!dst_dir.path().join("drop1.txt").exists());
- assert!(!dst_dir.path().join("drop2.txt").exists());
- // Dynamic `type: int` coerced "42" -> 42 so `dynamic_val + 1 == 43`!
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("out.txt")).unwrap(),
- "val=43 env=prod\n"
- );
- }
- #[test]
- fn copy_cleanup_on_error_respects_no_cleanup_flag() {
- let tpl_dir = TempDir::new().unwrap();
- let parent = TempDir::new().unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- _tasks:
- - "exit 1"
- name: demo
- "#,
- )
- .unwrap();
- fs::write(tpl_dir.path().join("hello.txt.jinja"), "hi {{ name }}").unwrap();
- // Default (`cleanup_on_error: true`): newly created destination is deleted on task failure.
- let dst_cleaned = parent.path().join("cleaned");
- let err = copy(
- tpl_dir.path().to_str().unwrap(),
- &dst_cleaned,
- &CopyOptions {
- defaults: true,
- trust: true,
- cleanup_on_error: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(matches!(err, RoneoError::TaskFailed { .. }));
- assert!(
- !dst_cleaned.exists(),
- "destination should be cleaned up on error"
- );
- // `--no-cleanup` (`cleanup_on_error: false`): destination is kept on failure.
- let dst_kept = parent.path().join("kept");
- let err2 = copy(
- tpl_dir.path().to_str().unwrap(),
- &dst_kept,
- &CopyOptions {
- defaults: true,
- trust: true,
- cleanup_on_error: false,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(matches!(err2, RoneoError::TaskFailed { .. }));
- assert!(dst_kept.join("hello.txt").exists());
- }
- #[test]
- fn update_in_monorepo_subdir_honors_skip_if_exists_new_excludes_and_operation_env() {
- let tpl_dir = TempDir::new().unwrap();
- let monorepo = TempDir::new().unwrap();
- // Template v1.0.0
- init_git_repo(tpl_dir.path());
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- _skip_if_exists:
- - "local.env"
- _tasks:
- - "echo $COPIER_OPERATION > op.log"
- name: svc
- "#,
- )
- .unwrap();
- fs::write(tpl_dir.path().join("app.txt.jinja"), "v1 {{ name }}\n").unwrap();
- fs::write(tpl_dir.path().join("local.env.jinja"), "SECRET=v1\n").unwrap();
- fs::write(tpl_dir.path().join("keep_me.txt"), "v1 keep\n").unwrap();
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- // Scaffold into `services/my-svc` inside a Git monorepo
- init_git_repo(monorepo.path());
- let subproject = monorepo.path().join("services/my-svc");
- copy(
- tpl_dir.path().to_str().unwrap(),
- &subproject,
- &CopyOptions {
- defaults: true,
- trust: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(
- fs::read_to_string(subproject.join("op.log"))
- .unwrap()
- .trim(),
- "copy"
- );
- // User customizes local.env
- fs::write(subproject.join("local.env"), "SECRET=my-local-secret\n").unwrap();
- commit_all(monorepo.path(), "Initial monorepo commit");
- // Template v2.0.0 updates app.txt & local.env, and adds keep_me.txt to `_exclude`
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- _exclude:
- - "keep_me.txt"
- _skip_if_exists:
- - "local.env"
- _tasks:
- - "echo $COPIER_OPERATION > op.log"
- name: svc
- "#,
- )
- .unwrap();
- fs::write(tpl_dir.path().join("app.txt.jinja"), "v2 {{ name }}\n").unwrap();
- fs::write(tpl_dir.path().join("local.env.jinja"), "SECRET=v2\n").unwrap();
- commit_all(tpl_dir.path(), "v2.0.0");
- git(tpl_dir.path(), &["tag", "v2.0.0"]);
- let report = update(
- &subproject,
- &CopyOptions {
- defaults: true,
- trust: true,
- context_lines: 2,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert!(
- report.conflicts.is_empty(),
- "Unexpected conflicts: {:?}",
- report.conflicts
- );
- assert_eq!(report.commit.as_deref(), Some("v2.0.0"));
- assert_eq!(
- fs::read_to_string(subproject.join("app.txt")).unwrap(),
- "v2 svc\n"
- );
- // `_skip_if_exists` prevented `local.env` from being overwritten on update!
- assert_eq!(
- fs::read_to_string(subproject.join("local.env")).unwrap(),
- "SECRET=my-local-secret\n"
- );
- // Newly excluded `keep_me.txt` was NOT deleted from the user's subproject!
- assert!(subproject.join("keep_me.txt").exists());
- // Task received `COPIER_OPERATION=update`!
- assert_eq!(
- fs::read_to_string(subproject.join("op.log"))
- .unwrap()
- .trim(),
- "update"
- );
- }
- #[test]
- fn yield_tag_expands_nested_dirs_and_files_on_disk_and_git_tree() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_disk = TempDir::new().unwrap();
- let dst_git = TempDir::new().unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r"
- services:
- type: yaml
- default:
- - auth
- - billing
- envs:
- type: yaml
- default:
- - dev
- - prod
- ",
- )
- .unwrap();
- let nested_dir = tpl_dir
- .path()
- .join("{% yield svc from services %}{{ svc }}{% endyield %}");
- fs::create_dir_all(&nested_dir).unwrap();
- fs::write(
- nested_dir.join("{% yield env from envs %}{{ env }}.yml{% endyield %}.jinja"),
- "service: {{ svc }}\nenv: {{ env }}\n",
- )
- .unwrap();
- // 1. Disk-backed template
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_disk.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- for svc in ["auth", "billing"] {
- for env in ["dev", "prod"] {
- let content =
- fs::read_to_string(dst_disk.path().join(format!("{svc}/{env}.yml"))).unwrap();
- assert_eq!(content, format!("service: {svc}\nenv: {env}\n"));
- }
- }
- // 2. GitTree-backed (in-memory gix) template
- init_git_repo(tpl_dir.path());
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_git.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- for svc in ["auth", "billing"] {
- for env in ["dev", "prod"] {
- let content =
- fs::read_to_string(dst_git.path().join(format!("{svc}/{env}.yml"))).unwrap();
- assert_eq!(content, format!("service: {svc}\nenv: {env}\n"));
- }
- }
- }
- #[test]
- fn extra_jinja_filters_task_extra_env_old_template_warning_and_git_bundle() {
- use std::sync::Mutex;
- struct CaptureReporter(Mutex<Vec<String>>);
- impl roneo_core::Reporter for CaptureReporter {
- fn emit(&self, event: roneo_core::ActionEvent) {
- if let roneo_core::ActionEvent::Warning(w) = event {
- self.0.lock().unwrap().push(w);
- }
- }
- }
- let tpl_dir = TempDir::new().unwrap();
- let bundle_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- init_git_repo(tpl_dir.path());
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- _min_copier_version: "8.0.0"
- _tasks:
- - command: "echo $CUSTOM_TAG > env.txt"
- extra_env:
- CUSTOM_TAG: "hello-{{ label | to_snake }}"
- label:
- type: str
- default: "MySuperService"
- qmark: "🚀"
- "#,
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("filters.txt.jinja"),
- r#"snake={{ label | to_snake }}
- kebab={{ label | to_kebab }}
- camel={{ label | to_camel }}
- pascal={{ "my_super_service" | to_pascal }}
- b64={{ "roneo!" | b64encode }}
- dec={{ "cm9uZW8h" | b64decode }}
- year_len={{ now("%Y") | length }}
- "#,
- )
- .unwrap();
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- // Export as a `.bundle` file and copy directly from the git bundle!
- let bundle_path = bundle_dir.path().join("tpl.bundle");
- git(
- tpl_dir.path(),
- &["bundle", "create", bundle_path.to_str().unwrap(), "--all"],
- );
- let reporter = CaptureReporter(Mutex::new(Vec::new()));
- copy(
- bundle_path.to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- trust: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &reporter,
- )
- .unwrap();
- let rendered = fs::read_to_string(dst_dir.path().join("filters.txt")).unwrap();
- assert!(
- rendered.contains("snake=my_super_service\n"),
- "got:\n{rendered}"
- );
- assert!(
- rendered.contains("kebab=my-super-service\n"),
- "got:\n{rendered}"
- );
- assert!(
- rendered.contains("camel=mySuperService\n"),
- "got:\n{rendered}"
- );
- assert!(
- rendered.contains("pascal=MySuperService\n"),
- "got:\n{rendered}"
- );
- assert!(rendered.contains("b64=cm9uZW8h\n"), "got:\n{rendered}");
- assert!(rendered.contains("dec=roneo!\n"), "got:\n{rendered}");
- assert!(rendered.contains("year_len=4\n"), "got:\n{rendered}");
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("env.txt"))
- .unwrap()
- .trim(),
- "hello-my_super_service"
- );
- let warnings = reporter.0.lock().unwrap();
- assert!(
- warnings.iter().any(|w| w.contains("older Copier 8.0.0")),
- "expected OldTemplateWarning, got: {warnings:?}"
- );
- }
- #[test]
- fn update_never_conflicts_on_answers_file_when_user_edits_header() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- init_git_repo(tpl_dir.path());
- fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap();
- fs::write(tpl_dir.path().join("f.txt.jinja"), "v1 {{ name }}\n").unwrap();
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- init_git_repo(dst_dir.path());
- commit_all(dst_dir.path(), "init");
- // User modifies the comment line in `.copier-answers.yml` (classic cause of false conflict if patched).
- let answers_path = dst_dir.path().join(".copier-answers.yml");
- let raw = fs::read_to_string(&answers_path).unwrap();
- fs::write(&answers_path, format!("# custom user comment\n{raw}")).unwrap();
- commit_all(dst_dir.path(), "user edited answers comment");
- fs::write(tpl_dir.path().join("f.txt.jinja"), "v2 {{ name }}\n").unwrap();
- commit_all(tpl_dir.path(), "v2.0.0");
- git(tpl_dir.path(), &["tag", "v2.0.0"]);
- let rep = update(
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert!(
- rep.conflicts.is_empty(),
- "Answers file must not conflict during update, got: {:?}",
- rep.conflicts
- );
- let updated_answers = AnswersMap::load(&answers_path).unwrap();
- assert_eq!(updated_answers.commit(), Some("v2.0.0"));
- }
- #[test]
- fn update_inline_conflict_works_after_git_history_squash() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- init_git_repo(tpl_dir.path());
- fs::write(tpl_dir.path().join("copier.yml"), "name: app\n").unwrap();
- fs::write(tpl_dir.path().join("config.txt.jinja"), "port=8080\n").unwrap();
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- // User edits config.txt BEFORE initializing git (simulating a squashed history where
- // the original v1.0.0 blob OID does NOT exist in destination `.git/objects`!).
- fs::write(dst_dir.path().join("config.txt"), "port=9090\n").unwrap();
- init_git_repo(dst_dir.path());
- commit_all(dst_dir.path(), "squashed initial commit");
- // Upstream v2.0.0 changes same line differently
- fs::write(tpl_dir.path().join("config.txt.jinja"), "port=3000\n").unwrap();
- commit_all(tpl_dir.path(), "v2.0.0");
- git(tpl_dir.path(), &["tag", "v2.0.0"]);
- let report = update(
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- conflict_mode: ConflictMode::Inline,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(report.conflicts, vec!["config.txt"]);
- assert!(!dst_dir.path().join("config.txt.rej").exists());
- let content = fs::read_to_string(dst_dir.path().join("config.txt")).unwrap();
- assert!(
- content.contains("<<<<<<< before updating"),
- "got:\n{content}"
- );
- assert!(content.contains("port=9090"), "got:\n{content}");
- assert!(content.contains("port=3000"), "got:\n{content}");
- assert!(
- content.contains(">>>>>>> after updating"),
- "got:\n{content}"
- );
- }
- #[test]
- fn update_protects_gitignored_files_blocks_downgrades_and_cleans_renamed_answers_file() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- init_git_repo(tpl_dir.path());
- fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap();
- fs::write(tpl_dir.path().join("app.txt.jinja"), "v1 {{ name }}\n").unwrap();
- fs::write(tpl_dir.path().join("local.secret.jinja"), "SECRET=v1\n").unwrap();
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- // User gitignores `local.secret` and puts a private value in it.
- fs::write(dst_dir.path().join(".gitignore"), "local.secret\n").unwrap();
- init_git_repo(dst_dir.path());
- commit_all(dst_dir.path(), "init");
- fs::write(dst_dir.path().join("local.secret"), "SECRET=user-ignored\n").unwrap();
- // Template v2.0.0 renames `_answers_file` and modifies both `app.txt` and `local.secret`.
- fs::write(
- tpl_dir.path().join("copier.yml"),
- "_answers_file: .config/answers.yml\nname: demo\n",
- )
- .unwrap();
- fs::write(tpl_dir.path().join("app.txt.jinja"), "v2 {{ name }}\n").unwrap();
- fs::write(tpl_dir.path().join("local.secret.jinja"), "SECRET=v2\n").unwrap();
- commit_all(tpl_dir.path(), "v2.0.0");
- git(tpl_dir.path(), &["tag", "v2.0.0"]);
- let rep = update(
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert!(
- rep.conflicts.is_empty(),
- "Unexpected conflicts: {:?}",
- rep.conflicts
- );
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("app.txt")).unwrap(),
- "v2 demo\n"
- );
- // `.gitignore`-d `local.secret` was untouched!
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("local.secret")).unwrap(),
- "SECRET=user-ignored\n"
- );
- // Old `.copier-answers.yml` cleaned up and replaced by `.config/answers.yml`!
- assert!(!dst_dir.path().join(".copier-answers.yml").exists());
- assert!(dst_dir.path().join(".config/answers.yml").is_file());
- commit_all(dst_dir.path(), "upgraded to v2.0.0");
- // Attempting to downgrade from v2.0.0 -> v1.0.0 must be rejected!
- let err = update(
- dst_dir.path(),
- &CopyOptions {
- answers_file: Some(".config/answers.yml".into()),
- vcs_ref: Some("v1.0.0".into()),
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(matches!(err, RoneoError::DowngradeNotSupported { .. }));
- }
- #[test]
- fn task_stage_context_and_nullable_typed_defaults() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- _tasks:
- - command: "echo {{ _stage }}:$STAGE > stage.txt"
- when: "{{ _stage == 'task' }}"
- opt_int:
- type: int
- default: null
- opt_float:
- type: float
- default: null
- opt_bool:
- type: bool
- default: null
- "#,
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("vals.txt.jinja"),
- "int={{ opt_int is none }} float={{ opt_float is none }} bool={{ opt_bool is none }}\n",
- )
- .unwrap();
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- trust: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("stage.txt"))
- .unwrap()
- .trim(),
- "task:task"
- );
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("vals.txt")).unwrap(),
- "int=True float=True bool=True\n"
- );
- let answers = AnswersMap::load(&dst_dir.path().join(".copier-answers.yml")).unwrap();
- assert_eq!(answers.user.get("opt_int"), Some(&json!(null)));
- assert_eq!(answers.user.get("opt_float"), Some(&json!(null)));
- assert_eq!(answers.user.get("opt_bool"), Some(&json!(null)));
- }
- #[test]
- fn check_update_reports_available_updates_and_respects_prereleases() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- init_git_repo(tpl_dir.path());
- fs::write(tpl_dir.path().join("copier.yml"), "name: demo\n").unwrap();
- fs::write(tpl_dir.path().join("app.txt.jinja"), "v1 {{ name }}\n").unwrap();
- commit_all(tpl_dir.path(), "v1.0.0");
- git(tpl_dir.path(), &["tag", "v1.0.0"]);
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- // Up-to-date on v1.0.0
- let rep = check_update(dst_dir.path(), &CopyOptions::default()).unwrap();
- assert!(!rep.update_available);
- assert_eq!(rep.current_version, "v1.0.0");
- assert_eq!(rep.latest_version, "v1.0.0");
- // Tag a prerelease v2.0.0rc1
- fs::write(tpl_dir.path().join("app.txt.jinja"), "v2rc1 {{ name }}\n").unwrap();
- commit_all(tpl_dir.path(), "v2.0.0rc1");
- git(tpl_dir.path(), &["tag", "v2.0.0rc1"]);
- let rep_stable = check_update(dst_dir.path(), &CopyOptions::default()).unwrap();
- assert!(!rep_stable.update_available);
- assert_eq!(rep_stable.latest_version, "v1.0.0");
- let rep_pre = check_update(
- dst_dir.path(),
- &CopyOptions {
- use_prereleases: true,
- ..CopyOptions::default()
- },
- )
- .unwrap();
- assert!(rep_pre.update_available);
- assert_eq!(rep_pre.current_version, "v1.0.0");
- assert_eq!(rep_pre.latest_version, "v2.0.0rc1");
- // Tag stable v2.0.0
- fs::write(tpl_dir.path().join("app.txt.jinja"), "v2 {{ name }}\n").unwrap();
- commit_all(tpl_dir.path(), "v2.0.0");
- git(tpl_dir.path(), &["tag", "v2.0.0"]);
- let rep_v2 = check_update(dst_dir.path(), &CopyOptions::default()).unwrap();
- assert!(rep_v2.update_available);
- assert_eq!(rep_v2.current_version, "v1.0.0");
- assert_eq!(rep_v2.latest_version, "v2.0.0");
- }
- #[test]
- fn question_ask_attribute_and_cli_ask_flag_override() {
- use std::sync::Mutex;
- struct RecordingPrompter {
- asked: Mutex<Vec<String>>,
- }
- impl Prompter for RecordingPrompter {
- fn prompt_string(&self, req: &PromptRequest) -> roneo_core::Result<String> {
- self.asked.lock().unwrap().push(req.name.clone());
- Ok(format!("prompted-{}", req.name))
- }
- fn prompt_bool(&self, req: &PromptRequest, default: bool) -> roneo_core::Result<bool> {
- self.asked.lock().unwrap().push(req.name.clone());
- Ok(default)
- }
- fn prompt_select(
- &self,
- req: &PromptRequest,
- choices: &[roneo_core::config::ChoiceSpec],
- default_idx: Option<usize>,
- ) -> roneo_core::Result<serde_json::Value> {
- self.asked.lock().unwrap().push(req.name.clone());
- Ok(choices[default_idx.unwrap_or(0)].value.clone())
- }
- fn prompt_multiselect(
- &self,
- req: &PromptRequest,
- _choices: &[roneo_core::config::ChoiceSpec],
- _defaults: &[usize],
- ) -> roneo_core::Result<Vec<serde_json::Value>> {
- self.asked.lock().unwrap().push(req.name.clone());
- Ok(Vec::new())
- }
- fn show_validation_error(&self, _name: &str, _message: &str) {}
- }
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r#"
- project:
- type: str
- default: default-proj
- silent_token:
- type: str
- default: auto-token
- ask: false
- conditional_field:
- type: str
- default: auto-cond
- ask: "{{ project == 'custom' }}"
- "#,
- )
- .unwrap();
- fs::write(
- tpl_dir.path().join("out.txt.jinja"),
- "{{ project }}|{{ silent_token }}|{{ conditional_field }}\n",
- )
- .unwrap();
- // 1. Interactive without `--defaults`: `silent_token` (`ask: false`) and `conditional_field`
- // (`ask` evaluates false) must NOT be prompted; only `project` is asked.
- let prompter = RecordingPrompter {
- asked: Mutex::new(Vec::new()),
- };
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions::default(),
- &prompter,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(*prompter.asked.lock().unwrap(), vec!["project"]);
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("out.txt")).unwrap(),
- "prompted-project|auto-token|auto-cond\n"
- );
- // 2. With `--defaults` AND `--ask silent_*` (fnmatch glob): ONLY `silent_token` is forced interactive!
- let dst_dir2 = TempDir::new().unwrap();
- let prompter2 = RecordingPrompter {
- asked: Mutex::new(Vec::new()),
- };
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir2.path(),
- &CopyOptions {
- defaults: true,
- ask_questions: vec!["silent_*".into()],
- ..CopyOptions::default()
- },
- &prompter2,
- &NoopReporter,
- )
- .unwrap();
- assert_eq!(*prompter2.asked.lock().unwrap(), vec!["silent_token"]);
- assert_eq!(
- fs::read_to_string(dst_dir2.path().join("out.txt")).unwrap(),
- "default-proj|prompted-silent_token|auto-cond\n"
- );
- }
- #[test]
- fn multiline_exclude_and_symlink_overwrite_without_following() {
- let tpl_dir = TempDir::new().unwrap();
- let dst_dir = TempDir::new().unwrap();
- let outside_dir = TempDir::new().unwrap();
- fs::write(
- tpl_dir.path().join("copier.yml"),
- r"
- _exclude:
- - |
- {% if true %}
- drop_a.txt
- drop_b.txt
- {% endif %}
- name: demo
- ",
- )
- .unwrap();
- fs::write(tpl_dir.path().join("keep.txt.jinja"), "kept {{ name }}\n").unwrap();
- fs::write(tpl_dir.path().join("drop_a.txt"), "a").unwrap();
- fs::write(tpl_dir.path().join("drop_b.txt"), "b").unwrap();
- fs::write(tpl_dir.path().join("broken_target.txt"), "fresh\n").unwrap();
- // Pre-populate destination with:
- // 1) a live symlink `keep.txt -> outside/secret.txt`
- // 2) a broken symlink `broken_target.txt -> /nonexistent/path`
- let outside_secret = outside_dir.path().join("secret.txt");
- fs::write(&outside_secret, "DO NOT TOUCH\n").unwrap();
- #[cfg(unix)]
- {
- std::os::unix::fs::symlink(&outside_secret, dst_dir.path().join("keep.txt")).unwrap();
- std::os::unix::fs::symlink(
- outside_dir.path().join("missing.txt"),
- dst_dir.path().join("broken_target.txt"),
- )
- .unwrap();
- }
- copy(
- tpl_dir.path().to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- overwrite: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap();
- // Multi-line `_exclude` dropped both files.
- assert!(!dst_dir.path().join("drop_a.txt").exists());
- assert!(!dst_dir.path().join("drop_b.txt").exists());
- // Destination symlinks were unlinked and replaced with regular files; external target untouched!
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("keep.txt")).unwrap(),
- "kept demo\n"
- );
- assert_eq!(
- fs::read_to_string(dst_dir.path().join("broken_target.txt")).unwrap(),
- "fresh\n"
- );
- assert_eq!(
- fs::read_to_string(&outside_secret).unwrap(),
- "DO NOT TOUCH\n"
- );
- #[cfg(unix)]
- {
- assert!(
- !fs::symlink_metadata(dst_dir.path().join("keep.txt"))
- .unwrap()
- .file_type()
- .is_symlink()
- );
- assert!(
- !fs::symlink_metadata(dst_dir.path().join("broken_target.txt"))
- .unwrap()
- .file_type()
- .is_symlink()
- );
- }
- }
- #[test]
- fn security_path_containment_and_git_ref_injection_guard() {
- // 1. `!include ../escape.yml` must be rejected.
- let parent_dir = TempDir::new().unwrap();
- let tpl_dir = parent_dir.path().join("tpl");
- fs::create_dir_all(&tpl_dir).unwrap();
- fs::write(parent_dir.path().join("escape.yml"), "secret: leaked\n").unwrap();
- fs::write(tpl_dir.join("copier.yml"), "!include ../escape.yml\n").unwrap();
- let dst_dir = TempDir::new().unwrap();
- let err = copy(
- tpl_dir.to_str().unwrap(),
- dst_dir.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(
- err.to_string().contains("escapes template root") || err.to_string().contains("Invalid"),
- "expected path containment error, got: {err}"
- );
- // 2. Jinja `{% include '../secret.txt' %}` and symlink escaping template root must be blocked.
- let tpl_dir2 = parent_dir.path().join("tpl2");
- fs::create_dir_all(&tpl_dir2).unwrap();
- fs::write(parent_dir.path().join("secret.txt"), "TOP-SECRET").unwrap();
- fs::write(tpl_dir2.join("copier.yml"), "name: ok\n").unwrap();
- fs::write(
- tpl_dir2.join("leak.txt.jinja"),
- "{% include '../secret.txt' %}\n",
- )
- .unwrap();
- let dst_dir2 = TempDir::new().unwrap();
- let err2 = copy(
- tpl_dir2.to_str().unwrap(),
- dst_dir2.path(),
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(
- err2.to_string().contains("not found") || err2.to_string().contains("template"),
- "expected Jinja include containment failure, got: {err2}"
- );
- // 3. Git refs starting with `-` must be rejected (argument injection defense).
- let git_tpl = TempDir::new().unwrap();
- init_git_repo(git_tpl.path());
- fs::write(git_tpl.path().join("copier.yml"), "name: ok\n").unwrap();
- fs::write(git_tpl.path().join("a.txt"), "hi\n").unwrap();
- commit_all(git_tpl.path(), "init");
- let dst_dir3 = TempDir::new().unwrap();
- let err3 = copy(
- git_tpl.path().to_str().unwrap(),
- dst_dir3.path(),
- &CopyOptions {
- vcs_ref: Some("--upload-pack=evil".into()),
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(
- err3.to_string().contains("may not start with '-'"),
- "expected git ref injection error, got: {err3}"
- );
- }
- #[test]
- fn security_blocks_rendered_path_answers_subdir_and_external_data_traversal() {
- let sandbox = TempDir::new().unwrap();
- let victim_secret = sandbox.path().join("outside_secret.yml");
- fs::write(&victim_secret, "token: topsecret\n").unwrap();
- // 0. TempDir must be 0700 on Unix.
- #[cfg(unix)]
- {
- use std::os::unix::fs::PermissionsExt;
- let mode = fs::metadata(sandbox.path()).unwrap().permissions().mode() & 0o777;
- assert_eq!(mode, 0o700, "TempDir must be private (0700)");
- }
- // 1. Rendered filename attempting `../pwned.txt` must be rejected.
- let tpl1 = sandbox.path().join("tpl_path");
- let dst1 = sandbox.path().join("dst1");
- fs::create_dir_all(&tpl1).unwrap();
- fs::write(tpl1.join("copier.yml"), "target: '../pwned.txt'\n").unwrap();
- fs::write(tpl1.join("{{ target }}.jinja"), "pwned").unwrap();
- let err = copy(
- tpl1.to_str().unwrap(),
- &dst1,
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(
- err.to_string().contains("escapes destination"),
- "expected rendered path escape error, got: {err}"
- );
- assert!(!sandbox.path().join("pwned.txt").exists());
- // 2. `_answers_file: ../pwned-answers.yml` must be rejected.
- let tpl2 = sandbox.path().join("tpl_ans");
- let dst2 = sandbox.path().join("dst2");
- fs::create_dir_all(&tpl2).unwrap();
- fs::write(
- tpl2.join("copier.yml"),
- "_answers_file: ../pwned-answers.yml\nname: x\n",
- )
- .unwrap();
- fs::write(tpl2.join("ok.txt"), "hi").unwrap();
- let err = copy(
- tpl2.to_str().unwrap(),
- &dst2,
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(
- err.to_string().contains("escapes destination"),
- "expected answers_file escape error, got: {err}"
- );
- assert!(!sandbox.path().join("pwned-answers.yml").exists());
- // 3. `_subdirectory: ../` must be rejected.
- let tpl3 = sandbox.path().join("tpl_sub");
- let dst3 = sandbox.path().join("dst3");
- fs::create_dir_all(&tpl3).unwrap();
- fs::write(tpl3.join("copier.yml"), "_subdirectory: ..\nname: x\n").unwrap();
- let err = copy(
- tpl3.to_str().unwrap(),
- &dst3,
- &CopyOptions {
- defaults: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(
- err.to_string().contains("escapes template root"),
- "expected subdirectory escape error, got: {err}"
- );
- // 4. `_external_data` pointing outside template/dst without `--trust` must be rejected.
- let tpl4 = sandbox.path().join("tpl_ext");
- let dst4 = sandbox.path().join("dst4");
- fs::create_dir_all(&tpl4).unwrap();
- fs::write(
- tpl4.join("copier.yml"),
- format!(
- "_external_data:\n leak: {}\nname: x\n",
- victim_secret.display()
- ),
- )
- .unwrap();
- let err = copy(
- tpl4.to_str().unwrap(),
- &dst4,
- &CopyOptions {
- defaults: true,
- trust: false,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(
- err.to_string()
- .contains("Failed to load `_external_data.leak`"),
- "expected external_data containment error, got: {err}"
- );
- // 5. `_roneo_plugins` requires `--trust` and rejects absolute paths.
- let tpl5 = sandbox.path().join("tpl_plug");
- let dst5 = sandbox.path().join("dst5");
- fs::create_dir_all(&tpl5).unwrap();
- fs::write(
- tpl5.join("copier.yml"),
- "_roneo_plugins:\n - /tmp/evil.wasm\nname: x\n",
- )
- .unwrap();
- let err_untrusted = copy(
- tpl5.to_str().unwrap(),
- &dst5,
- &CopyOptions {
- defaults: true,
- trust: false,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(matches!(err_untrusted, RoneoError::UnsafeTemplate(_)));
- let err_abs = copy(
- tpl5.to_str().unwrap(),
- &dst5,
- &CopyOptions {
- defaults: true,
- trust: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(
- err_abs.to_string().contains("must be a relative path"),
- "expected relative path plugin error, got: {err_abs}"
- );
- // 6. Writing through a pre-existing symlink directory inside `dst` must be refused.
- #[cfg(unix)]
- {
- let tpl6 = sandbox.path().join("tpl_symdir");
- let dst6 = sandbox.path().join("dst6");
- let outside = sandbox.path().join("outside_dir");
- fs::create_dir_all(tpl6.join("sub")).unwrap();
- fs::create_dir_all(&dst6).unwrap();
- fs::create_dir_all(&outside).unwrap();
- fs::write(tpl6.join("copier.yml"), "name: x\n").unwrap();
- fs::write(tpl6.join("sub/pwn.txt"), "pwned").unwrap();
- std::os::unix::fs::symlink(&outside, dst6.join("sub")).unwrap();
- let err_sym = copy(
- tpl6.to_str().unwrap(),
- &dst6,
- &CopyOptions {
- defaults: true,
- overwrite: true,
- ..CopyOptions::default()
- },
- &NonInteractivePrompter,
- &NoopReporter,
- )
- .unwrap_err();
- assert!(
- err_sym.to_string().contains("symlink directory"),
- "expected symlink directory error, got: {err_sym}"
- );
- assert!(!outside.join("pwn.txt").exists());
- }
- }