forgeFRENBrowse the repositories

roneocratesroneo-coresrctemplate.rs

98ff76d5794bbd1480ad719803187d2c40e42403

At commit 98ff76d

394 lines · 15.2 KiBRustRaw
  1. use std::path::{Path, PathBuf};
  2. use std::sync::Arc;
  3. use crate::config::TemplateConfig;
  4. use crate::error::{Result, RoneoError};
  5. use crate::fs_util::TempDir;
  6. use crate::plugin::TemplateFileReader;
  7. use crate::vcs::{self, InMemoryGitTree};
  8. /// Backing storage for a resolved template: either a directory on disk or an in-memory `gix` tree
  9. /// (zero-TempDir, zero-clone reading for local Git repositories).
  10. #[derive(Debug)]
  11. pub enum TemplateBacking {
  12. Disk(PathBuf),
  13. GitTree(Arc<InMemoryGitTree>),
  14. }
  15. /// A resolved template ready for inspection or rendering.
  16. #[derive(Debug)]
  17. pub struct ResolvedTemplate {
  18. /// Original user-provided source string (preserved in `.copier-answers.yml` as `_src_path`).
  19. pub original_src: String,
  20. /// Normalized git URL or canonical local path.
  21. pub resolved_src: String,
  22. /// Local path on disk (for disk-backed templates, or the local repo path for git trees).
  23. pub local_path: PathBuf,
  24. /// Backing storage (`Disk` or zero-copy `GitTree`).
  25. pub backing: TemplateBacking,
  26. /// `_commit` value (e.g. `v1.0.0` or short hash) if template is backed by git.
  27. pub commit: Option<String>,
  28. /// Full 40-char commit hash if backed by git.
  29. pub commit_hash: Option<String>,
  30. /// Whether this template came from a remote URL (vs local path).
  31. pub is_remote: bool,
  32. /// Parsed `copier.yml` / `roneo.yml`.
  33. pub config: TemplateConfig,
  34. /// Keeps temporary clone alive for remote git templates (shared across sibling refs).
  35. temp_dir: Option<Arc<TempDir>>,
  36. }
  37. impl ResolvedTemplate {
  38. /// Resolve a template source (`local/dir`, `gh:owner/repo`, `gl:owner/repo`, or Git URL)
  39. /// at an optional `vcs_ref` (branch, tag, commit, or `HEAD`).
  40. pub fn resolve(src: &str, vcs_ref: Option<&str>) -> Result<Self> {
  41. Self::resolve_with_options(src, vcs_ref, false)
  42. }
  43. /// Resolve a template source with explicit prerelease tag selection control.
  44. pub fn resolve_with_options(
  45. src: &str,
  46. vcs_ref: Option<&str>,
  47. use_prereleases: bool,
  48. ) -> Result<Self> {
  49. let (normalized, is_remote) = normalize_source(src);
  50. if !is_remote {
  51. let path = PathBuf::from(&normalized);
  52. if !path.exists() {
  53. return Err(RoneoError::TemplateSource(format!(
  54. "Template path '{}' does not exist",
  55. path.display()
  56. )));
  57. }
  58. if path.is_file() && vcs::is_git_bundle(&path) {
  59. return Self::clone_and_checkout(src, &normalized, false, vcs_ref, use_prereleases);
  60. }
  61. if !path.is_dir() {
  62. return Err(RoneoError::TemplateSource(format!(
  63. "Template path '{}' is not a directory",
  64. path.display()
  65. )));
  66. }
  67. if !vcs::is_git_repo(&path) {
  68. let config = TemplateConfig::load_from_dir(&path)?;
  69. return Ok(Self {
  70. original_src: src.to_string(),
  71. resolved_src: normalized,
  72. backing: TemplateBacking::Disk(path.clone()),
  73. local_path: path,
  74. commit: None,
  75. commit_hash: None,
  76. is_remote: false,
  77. config,
  78. temp_dir: None,
  79. });
  80. }
  81. // Local git repo: if no explicit `vcs_ref` is requested and working tree is dirty,
  82. // render from working tree directly (matching Copier's developer workflow).
  83. if vcs_ref.is_none() && !vcs::is_clean(&path).unwrap_or(true) {
  84. let (desc, hash) =
  85. vcs::describe_and_hash_head(&path).map_or((None, None), |(d, h)| (d, Some(h)));
  86. let commit = desc.map(|c| format!("{c}-dirty"));
  87. let config = TemplateConfig::load_from_dir(&path)?;
  88. return Ok(Self {
  89. original_src: src.to_string(),
  90. resolved_src: normalized,
  91. backing: TemplateBacking::Disk(path.clone()),
  92. local_path: path,
  93. commit,
  94. commit_hash: hash,
  95. is_remote: false,
  96. config,
  97. temp_dir: None,
  98. });
  99. }
  100. // Fast zero-TempDir in-memory `gix` tree reading (no extraction to disk, no clone!).
  101. return Self::open_local_git_tree(src, &normalized, &path, vcs_ref, use_prereleases);
  102. }
  103. Self::clone_and_checkout(src, &normalized, true, vcs_ref, use_prereleases)
  104. }
  105. /// Resolve another VCS ref in the SAME template source, reusing the already-open
  106. /// `gix::ThreadSafeRepository` when backed by a local Git tree (eliminates reopening `.git`
  107. /// and re-reading pack indices during `update` / `diff`).
  108. pub fn resolve_sibling(&self, vcs_ref: Option<&str>, use_prereleases: bool) -> Result<Self> {
  109. if let TemplateBacking::GitTree(tree) = &self.backing {
  110. let sibling_tree = Arc::new(tree.open_sibling(vcs_ref, use_prereleases)?);
  111. let config = TemplateConfig::load_from_reader_with_glob(
  112. &|rel| sibling_tree.read_string(rel),
  113. &|pat| sibling_tree.list_matching_files(pat),
  114. )?;
  115. return Ok(Self {
  116. original_src: self.original_src.clone(),
  117. resolved_src: self.resolved_src.clone(),
  118. local_path: self.local_path.clone(),
  119. commit: sibling_tree.commit_describe.clone(),
  120. commit_hash: Some(sibling_tree.commit_hash.clone()),
  121. backing: TemplateBacking::GitTree(sibling_tree),
  122. is_remote: self.is_remote,
  123. config,
  124. temp_dir: self.temp_dir.clone(),
  125. });
  126. }
  127. // For a freshly cloned remote/bundle repo without submodules, read the sibling ref
  128. // directly from the existing local clone in memory (avoids a second network fetch/clone).
  129. if vcs::is_git_repo(&self.local_path) && !self.local_path.join(".gitmodules").is_file() {
  130. let sibling_tree = Arc::new(InMemoryGitTree::open(
  131. &self.local_path,
  132. vcs_ref,
  133. use_prereleases,
  134. )?);
  135. let config = TemplateConfig::load_from_reader_with_glob(
  136. &|rel| sibling_tree.read_string(rel),
  137. &|pat| sibling_tree.list_matching_files(pat),
  138. )?;
  139. return Ok(Self {
  140. original_src: self.original_src.clone(),
  141. resolved_src: self.resolved_src.clone(),
  142. local_path: self.local_path.clone(),
  143. commit: sibling_tree.commit_describe.clone(),
  144. commit_hash: Some(sibling_tree.commit_hash.clone()),
  145. backing: TemplateBacking::GitTree(sibling_tree),
  146. is_remote: self.is_remote,
  147. config,
  148. temp_dir: self.temp_dir.clone(),
  149. });
  150. }
  151. Self::resolve_with_options(&self.original_src, vcs_ref, use_prereleases)
  152. }
  153. fn open_local_git_tree(
  154. original_src: &str,
  155. resolved_src: &str,
  156. repo_path: &Path,
  157. vcs_ref: Option<&str>,
  158. use_prereleases: bool,
  159. ) -> Result<Self> {
  160. let tree = Arc::new(InMemoryGitTree::open(repo_path, vcs_ref, use_prereleases)?);
  161. let config =
  162. TemplateConfig::load_from_reader_with_glob(&|rel| tree.read_string(rel), &|pat| {
  163. tree.list_matching_files(pat)
  164. })?;
  165. Ok(Self {
  166. original_src: original_src.to_string(),
  167. resolved_src: resolved_src.to_string(),
  168. local_path: repo_path.to_path_buf(),
  169. commit: tree.commit_describe.clone(),
  170. commit_hash: Some(tree.commit_hash.clone()),
  171. backing: TemplateBacking::GitTree(tree),
  172. is_remote: false,
  173. config,
  174. temp_dir: None,
  175. })
  176. }
  177. fn clone_and_checkout(
  178. original_src: &str,
  179. clone_url: &str,
  180. is_remote: bool,
  181. vcs_ref: Option<&str>,
  182. use_prereleases: bool,
  183. ) -> Result<Self> {
  184. let temp_dir = TempDir::new()?;
  185. let checkout_path = temp_dir.path().join("template");
  186. if is_remote {
  187. vcs::clone_repo_cached(clone_url, &checkout_path)?;
  188. } else {
  189. vcs::clone_repo(clone_url, &checkout_path)?;
  190. }
  191. let target_ref = match vcs_ref {
  192. Some(r) => Some(r.to_string()),
  193. None => vcs::latest_version_tag(&checkout_path, use_prereleases)?,
  194. };
  195. if let Some(ref git_ref) = target_ref {
  196. vcs::checkout_ref(&checkout_path, git_ref)?;
  197. }
  198. let commit = vcs::describe_commit(&checkout_path).ok();
  199. let commit_hash = vcs::rev_parse_head(&checkout_path).ok();
  200. let config = TemplateConfig::load_from_dir(&checkout_path)?;
  201. Ok(Self {
  202. original_src: original_src.to_string(),
  203. resolved_src: clone_url.to_string(),
  204. backing: TemplateBacking::Disk(checkout_path.clone()),
  205. local_path: checkout_path,
  206. commit,
  207. commit_hash,
  208. is_remote,
  209. config,
  210. temp_dir: Some(Arc::new(temp_dir)),
  211. })
  212. }
  213. /// Return a closure that reads any file relative to template root (works for both `Disk` and `GitTree`),
  214. /// enforcing path containment so `{% include %}` symlinks or `../` cannot escape the template root
  215. /// (Copier v9.17.2 security hardening).
  216. pub fn file_reader(&self) -> TemplateFileReader {
  217. match &self.backing {
  218. TemplateBacking::Disk(root) => {
  219. let root = root.clone();
  220. let canon_root = std::fs::canonicalize(&root).ok();
  221. Arc::new(move |rel: &str| {
  222. let rel_path = Path::new(rel);
  223. if rel_path.is_absolute()
  224. || rel_path
  225. .components()
  226. .any(|c| matches!(c, std::path::Component::ParentDir))
  227. {
  228. return None;
  229. }
  230. let candidate = root.join(rel_path);
  231. if let Some(ref base_canon) = canon_root {
  232. let cand_canon = std::fs::canonicalize(&candidate).ok()?;
  233. if !cand_canon.starts_with(base_canon) {
  234. return None;
  235. }
  236. }
  237. std::fs::read_to_string(candidate).ok()
  238. })
  239. }
  240. TemplateBacking::GitTree(tree) => {
  241. let tree = Arc::clone(tree);
  242. Arc::new(move |rel: &str| {
  243. let rel_path = Path::new(rel);
  244. if rel_path.is_absolute()
  245. || rel_path
  246. .components()
  247. .any(|c| matches!(c, std::path::Component::ParentDir))
  248. {
  249. return None;
  250. }
  251. tree.read_string(rel)
  252. })
  253. }
  254. }
  255. }
  256. /// Read raw bytes of a file relative to template root (e.g. `.wasm` plugins declared via `_roneo_plugins`),
  257. /// enforcing strict path containment inside the template root.
  258. pub fn read_bytes(&self, rel: &str) -> Option<Vec<u8>> {
  259. if rel.contains('\0') {
  260. return None;
  261. }
  262. let rel_path = Path::new(rel);
  263. if rel_path.is_absolute()
  264. || rel_path.components().any(|c| {
  265. matches!(
  266. c,
  267. std::path::Component::ParentDir
  268. | std::path::Component::RootDir
  269. | std::path::Component::Prefix(_)
  270. )
  271. })
  272. {
  273. return None;
  274. }
  275. match &self.backing {
  276. TemplateBacking::Disk(root) => {
  277. let candidate = root.join(rel_path);
  278. let canon_root = std::fs::canonicalize(root).ok()?;
  279. let canon_cand = std::fs::canonicalize(&candidate).ok()?;
  280. if !canon_cand.starts_with(&canon_root) {
  281. return None;
  282. }
  283. std::fs::read(canon_cand).ok()
  284. }
  285. TemplateBacking::GitTree(tree) => tree.read_bytes(rel),
  286. }
  287. }
  288. /// Return the content root directory for `Disk`-backed templates (applying `_subdirectory` if set),
  289. /// rejecting any path or symlink that escapes the template root.
  290. pub fn disk_content_root(&self, rendered_subdirectory: Option<&str>) -> Result<PathBuf> {
  291. let Some(sub) = rendered_subdirectory.filter(|s| !s.trim().is_empty()) else {
  292. return Ok(self.local_path.clone());
  293. };
  294. let sub_path = Path::new(sub);
  295. if sub.contains('\0')
  296. || sub_path.is_absolute()
  297. || sub_path.components().any(|c| {
  298. matches!(
  299. c,
  300. std::path::Component::ParentDir
  301. | std::path::Component::RootDir
  302. | std::path::Component::Prefix(_)
  303. )
  304. })
  305. {
  306. return Err(RoneoError::TemplateSource(format!(
  307. "Template subdirectory '{sub}' escapes template root"
  308. )));
  309. }
  310. let path = self.local_path.join(sub_path);
  311. if !path.is_dir() {
  312. return Err(RoneoError::TemplateSource(format!(
  313. "Template subdirectory '{}' does not exist in '{}'",
  314. sub,
  315. self.local_path.display()
  316. )));
  317. }
  318. if let (Ok(canon_root), Ok(canon_sub)) = (
  319. std::fs::canonicalize(&self.local_path),
  320. std::fs::canonicalize(&path),
  321. ) && !canon_sub.starts_with(&canon_root)
  322. {
  323. return Err(RoneoError::TemplateSource(format!(
  324. "Template subdirectory '{sub}' escapes template root via symlink"
  325. )));
  326. }
  327. Ok(path)
  328. }
  329. }
  330. /// Expand Copier URL shorthands (`gh:`, `gl:`, `git+...`) and determine if source is remote.
  331. pub fn normalize_source(src: &str) -> (String, bool) {
  332. if let Some(rest) = src.strip_prefix("gh:") {
  333. let url = ensure_git_suffix(&format!("https://github.com/{rest}"));
  334. return (url, true);
  335. }
  336. if let Some(rest) = src.strip_prefix("gl:") {
  337. let url = ensure_git_suffix(&format!("https://gitlab.com/{rest}"));
  338. return (url, true);
  339. }
  340. if let Some(rest) = src.strip_prefix("git+") {
  341. return (rest.to_string(), true);
  342. }
  343. if src.starts_with("https://")
  344. || src.starts_with("http://")
  345. || src.starts_with("ssh://")
  346. || src.starts_with("git://")
  347. || src.starts_with("git@")
  348. {
  349. return (src.to_string(), true);
  350. }
  351. if let Some(file_path) = src.strip_prefix("file://") {
  352. return (file_path.to_string(), false);
  353. }
  354. let path = Path::new(src);
  355. if path.exists()
  356. && let Ok(canon) = path.canonicalize()
  357. {
  358. return (canon.to_string_lossy().into_owned(), false);
  359. }
  360. (src.to_string(), false)
  361. }
  362. fn ensure_git_suffix(url: &str) -> String {
  363. if Path::new(url)
  364. .extension()
  365. .is_some_and(|ext| ext.eq_ignore_ascii_case("git"))
  366. {
  367. url.to_string()
  368. } else {
  369. format!("{url}.git")
  370. }
  371. }