use std::path::{Path, PathBuf}; use std::sync::Arc; use crate::config::TemplateConfig; use crate::error::{Result, RoneoError}; use crate::fs_util::TempDir; use crate::plugin::TemplateFileReader; use crate::vcs::{self, InMemoryGitTree}; /// Backing storage for a resolved template: either a directory on disk or an in-memory `gix` tree /// (zero-TempDir, zero-clone reading for local Git repositories). #[derive(Debug)] pub enum TemplateBacking { Disk(PathBuf), GitTree(Arc), } /// A resolved template ready for inspection or rendering. #[derive(Debug)] pub struct ResolvedTemplate { /// Original user-provided source string (preserved in `.copier-answers.yml` as `_src_path`). pub original_src: String, /// Normalized git URL or canonical local path. pub resolved_src: String, /// Local path on disk (for disk-backed templates, or the local repo path for git trees). pub local_path: PathBuf, /// Backing storage (`Disk` or zero-copy `GitTree`). pub backing: TemplateBacking, /// `_commit` value (e.g. `v1.0.0` or short hash) if template is backed by git. pub commit: Option, /// Full 40-char commit hash if backed by git. pub commit_hash: Option, /// Whether this template came from a remote URL (vs local path). pub is_remote: bool, /// Parsed `copier.yml` / `roneo.yml`. pub config: TemplateConfig, /// Keeps temporary clone alive for remote git templates (shared across sibling refs). temp_dir: Option>, } impl ResolvedTemplate { /// Resolve a template source (`local/dir`, `gh:owner/repo`, `gl:owner/repo`, or Git URL) /// at an optional `vcs_ref` (branch, tag, commit, or `HEAD`). pub fn resolve(src: &str, vcs_ref: Option<&str>) -> Result { Self::resolve_with_options(src, vcs_ref, false) } /// Resolve a template source with explicit prerelease tag selection control. pub fn resolve_with_options( src: &str, vcs_ref: Option<&str>, use_prereleases: bool, ) -> Result { let (normalized, is_remote) = normalize_source(src); if !is_remote { let path = PathBuf::from(&normalized); if !path.exists() { return Err(RoneoError::TemplateSource(format!( "Template path '{}' does not exist", path.display() ))); } if path.is_file() && vcs::is_git_bundle(&path) { return Self::clone_and_checkout(src, &normalized, false, vcs_ref, use_prereleases); } if !path.is_dir() { return Err(RoneoError::TemplateSource(format!( "Template path '{}' is not a directory", path.display() ))); } if !vcs::is_git_repo(&path) { let config = TemplateConfig::load_from_dir(&path)?; return Ok(Self { original_src: src.to_string(), resolved_src: normalized, backing: TemplateBacking::Disk(path.clone()), local_path: path, commit: None, commit_hash: None, is_remote: false, config, temp_dir: None, }); } // Local git repo: if no explicit `vcs_ref` is requested and working tree is dirty, // render from working tree directly (matching Copier's developer workflow). if vcs_ref.is_none() && !vcs::is_clean(&path).unwrap_or(true) { let (desc, hash) = vcs::describe_and_hash_head(&path).map_or((None, None), |(d, h)| (d, Some(h))); let commit = desc.map(|c| format!("{c}-dirty")); let config = TemplateConfig::load_from_dir(&path)?; return Ok(Self { original_src: src.to_string(), resolved_src: normalized, backing: TemplateBacking::Disk(path.clone()), local_path: path, commit, commit_hash: hash, is_remote: false, config, temp_dir: None, }); } // Fast zero-TempDir in-memory `gix` tree reading (no extraction to disk, no clone!). return Self::open_local_git_tree(src, &normalized, &path, vcs_ref, use_prereleases); } Self::clone_and_checkout(src, &normalized, true, vcs_ref, use_prereleases) } /// Resolve another VCS ref in the SAME template source, reusing the already-open /// `gix::ThreadSafeRepository` when backed by a local Git tree (eliminates reopening `.git` /// and re-reading pack indices during `update` / `diff`). pub fn resolve_sibling(&self, vcs_ref: Option<&str>, use_prereleases: bool) -> Result { if let TemplateBacking::GitTree(tree) = &self.backing { let sibling_tree = Arc::new(tree.open_sibling(vcs_ref, use_prereleases)?); let config = TemplateConfig::load_from_reader_with_glob( &|rel| sibling_tree.read_string(rel), &|pat| sibling_tree.list_matching_files(pat), )?; return Ok(Self { original_src: self.original_src.clone(), resolved_src: self.resolved_src.clone(), local_path: self.local_path.clone(), commit: sibling_tree.commit_describe.clone(), commit_hash: Some(sibling_tree.commit_hash.clone()), backing: TemplateBacking::GitTree(sibling_tree), is_remote: self.is_remote, config, temp_dir: self.temp_dir.clone(), }); } // For a freshly cloned remote/bundle repo without submodules, read the sibling ref // directly from the existing local clone in memory (avoids a second network fetch/clone). if vcs::is_git_repo(&self.local_path) && !self.local_path.join(".gitmodules").is_file() { let sibling_tree = Arc::new(InMemoryGitTree::open( &self.local_path, vcs_ref, use_prereleases, )?); let config = TemplateConfig::load_from_reader_with_glob( &|rel| sibling_tree.read_string(rel), &|pat| sibling_tree.list_matching_files(pat), )?; return Ok(Self { original_src: self.original_src.clone(), resolved_src: self.resolved_src.clone(), local_path: self.local_path.clone(), commit: sibling_tree.commit_describe.clone(), commit_hash: Some(sibling_tree.commit_hash.clone()), backing: TemplateBacking::GitTree(sibling_tree), is_remote: self.is_remote, config, temp_dir: self.temp_dir.clone(), }); } Self::resolve_with_options(&self.original_src, vcs_ref, use_prereleases) } fn open_local_git_tree( original_src: &str, resolved_src: &str, repo_path: &Path, vcs_ref: Option<&str>, use_prereleases: bool, ) -> Result { let tree = Arc::new(InMemoryGitTree::open(repo_path, vcs_ref, use_prereleases)?); let config = TemplateConfig::load_from_reader_with_glob(&|rel| tree.read_string(rel), &|pat| { tree.list_matching_files(pat) })?; Ok(Self { original_src: original_src.to_string(), resolved_src: resolved_src.to_string(), local_path: repo_path.to_path_buf(), commit: tree.commit_describe.clone(), commit_hash: Some(tree.commit_hash.clone()), backing: TemplateBacking::GitTree(tree), is_remote: false, config, temp_dir: None, }) } fn clone_and_checkout( original_src: &str, clone_url: &str, is_remote: bool, vcs_ref: Option<&str>, use_prereleases: bool, ) -> Result { let temp_dir = TempDir::new()?; let checkout_path = temp_dir.path().join("template"); if is_remote { vcs::clone_repo_cached(clone_url, &checkout_path)?; } else { vcs::clone_repo(clone_url, &checkout_path)?; } let target_ref = match vcs_ref { Some(r) => Some(r.to_string()), None => vcs::latest_version_tag(&checkout_path, use_prereleases)?, }; if let Some(ref git_ref) = target_ref { vcs::checkout_ref(&checkout_path, git_ref)?; } let commit = vcs::describe_commit(&checkout_path).ok(); let commit_hash = vcs::rev_parse_head(&checkout_path).ok(); let config = TemplateConfig::load_from_dir(&checkout_path)?; Ok(Self { original_src: original_src.to_string(), resolved_src: clone_url.to_string(), backing: TemplateBacking::Disk(checkout_path.clone()), local_path: checkout_path, commit, commit_hash, is_remote, config, temp_dir: Some(Arc::new(temp_dir)), }) } /// Return a closure that reads any file relative to template root (works for both `Disk` and `GitTree`), /// enforcing path containment so `{% include %}` symlinks or `../` cannot escape the template root /// (Copier v9.17.2 security hardening). pub fn file_reader(&self) -> TemplateFileReader { match &self.backing { TemplateBacking::Disk(root) => { let root = root.clone(); let canon_root = std::fs::canonicalize(&root).ok(); Arc::new(move |rel: &str| { let rel_path = Path::new(rel); if rel_path.is_absolute() || rel_path .components() .any(|c| matches!(c, std::path::Component::ParentDir)) { return None; } let candidate = root.join(rel_path); if let Some(ref base_canon) = canon_root { let cand_canon = std::fs::canonicalize(&candidate).ok()?; if !cand_canon.starts_with(base_canon) { return None; } } std::fs::read_to_string(candidate).ok() }) } TemplateBacking::GitTree(tree) => { let tree = Arc::clone(tree); Arc::new(move |rel: &str| { let rel_path = Path::new(rel); if rel_path.is_absolute() || rel_path .components() .any(|c| matches!(c, std::path::Component::ParentDir)) { return None; } tree.read_string(rel) }) } } } /// Read raw bytes of a file relative to template root (e.g. `.wasm` plugins declared via `_roneo_plugins`), /// enforcing strict path containment inside the template root. pub fn read_bytes(&self, rel: &str) -> Option> { if rel.contains('\0') { return None; } let rel_path = Path::new(rel); if rel_path.is_absolute() || rel_path.components().any(|c| { matches!( c, std::path::Component::ParentDir | std::path::Component::RootDir | std::path::Component::Prefix(_) ) }) { return None; } match &self.backing { TemplateBacking::Disk(root) => { let candidate = root.join(rel_path); let canon_root = std::fs::canonicalize(root).ok()?; let canon_cand = std::fs::canonicalize(&candidate).ok()?; if !canon_cand.starts_with(&canon_root) { return None; } std::fs::read(canon_cand).ok() } TemplateBacking::GitTree(tree) => tree.read_bytes(rel), } } /// Return the content root directory for `Disk`-backed templates (applying `_subdirectory` if set), /// rejecting any path or symlink that escapes the template root. pub fn disk_content_root(&self, rendered_subdirectory: Option<&str>) -> Result { let Some(sub) = rendered_subdirectory.filter(|s| !s.trim().is_empty()) else { return Ok(self.local_path.clone()); }; let sub_path = Path::new(sub); if sub.contains('\0') || sub_path.is_absolute() || sub_path.components().any(|c| { matches!( c, std::path::Component::ParentDir | std::path::Component::RootDir | std::path::Component::Prefix(_) ) }) { return Err(RoneoError::TemplateSource(format!( "Template subdirectory '{sub}' escapes template root" ))); } let path = self.local_path.join(sub_path); if !path.is_dir() { return Err(RoneoError::TemplateSource(format!( "Template subdirectory '{}' does not exist in '{}'", sub, self.local_path.display() ))); } if let (Ok(canon_root), Ok(canon_sub)) = ( std::fs::canonicalize(&self.local_path), std::fs::canonicalize(&path), ) && !canon_sub.starts_with(&canon_root) { return Err(RoneoError::TemplateSource(format!( "Template subdirectory '{sub}' escapes template root via symlink" ))); } Ok(path) } } /// Expand Copier URL shorthands (`gh:`, `gl:`, `git+...`) and determine if source is remote. pub fn normalize_source(src: &str) -> (String, bool) { if let Some(rest) = src.strip_prefix("gh:") { let url = ensure_git_suffix(&format!("https://github.com/{rest}")); return (url, true); } if let Some(rest) = src.strip_prefix("gl:") { let url = ensure_git_suffix(&format!("https://gitlab.com/{rest}")); return (url, true); } if let Some(rest) = src.strip_prefix("git+") { return (rest.to_string(), true); } if src.starts_with("https://") || src.starts_with("http://") || src.starts_with("ssh://") || src.starts_with("git://") || src.starts_with("git@") { return (src.to_string(), true); } if let Some(file_path) = src.strip_prefix("file://") { return (file_path.to_string(), false); } let path = Path::new(src); if path.exists() && let Ok(canon) = path.canonicalize() { return (canon.to_string_lossy().into_owned(), false); } (src.to_string(), false) } fn ensure_git_suffix(url: &str) -> String { if Path::new(url) .extension() .is_some_and(|ext| ext.eq_ignore_ascii_case("git")) { url.to_string() } else { format!("{url}.git") } }