forgeFRENParcourir les dépôts

roneocratesroneo-coresrcvcs.rs

0518da6beb3fd562b82c5b5c2798b72e0d1591b2

At commit 0518da6

1 075 lines · 36.8 KiBRustRaw
  1. use std::io::{Read, Write};
  2. use std::path::{Path, PathBuf};
  3. use std::process::{Command, Stdio};
  4. use gix::bstr::ByteSlice;
  5. use gix::object::tree::EntryKind;
  6. use serde_json::Value as JsonValue;
  7. use crate::error::{Result, RoneoError};
  8. use crate::filter::match_glob_path;
  9. use crate::version::Pep440Version;
  10. #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
  11. pub enum ConflictMode {
  12. /// Insert standard `<<<<<<<` / `=======` / `>>>>>>>` conflict markers via `git apply --3way`.
  13. #[default]
  14. Inline,
  15. /// Write `.rej` files alongside conflicted targets via `git apply --reject`.
  16. Rej,
  17. }
  18. #[derive(Debug, Clone)]
  19. pub struct ApplyResult {
  20. pub has_conflicts: bool,
  21. pub stderr: String,
  22. pub conflicted_files: Vec<String>,
  23. }
  24. /// Snapshot of a destination Git working tree obtained in ONE `git status` call.
  25. #[derive(Debug, Clone, Default)]
  26. pub struct WorkingTreeStatus {
  27. pub is_clean: bool,
  28. pub ignored_paths: Vec<String>,
  29. }
  30. fn open_gix_repo(dir: &Path) -> Result<gix::Repository> {
  31. gix::open_opts(dir, gix::open::Options::isolated())
  32. .map_err(|e| RoneoError::Vcs(format!("Failed to open git repo '{}': {e}", dir.display())))
  33. }
  34. /// Returns `true` if `dir` is the root of a git working tree (not merely a subdirectory of one),
  35. /// evaluated purely in-process via `gix`.
  36. pub fn is_git_repo(dir: &Path) -> bool {
  37. if !dir.is_dir() || !dir.join(".git").exists() {
  38. return false;
  39. }
  40. gix::open_opts(dir, gix::open::Options::isolated()).is_ok()
  41. }
  42. /// Fast zero-subprocess check for Git bundle files (`# v2 git bundle` / `# v3 git bundle`).
  43. pub fn is_git_bundle(path: &Path) -> bool {
  44. let Ok(mut f) = std::fs::File::open(path) else {
  45. return false;
  46. };
  47. let mut header = [0u8; 20];
  48. let Ok(n) = f.read(&mut header) else {
  49. return false;
  50. };
  51. let slice = &header[..n];
  52. slice.starts_with(b"# v2 git bundle\n") || slice.starts_with(b"# v3 git bundle\n")
  53. }
  54. /// Discover the enclosing Git working tree root for `dir` (supports updating a project that lives
  55. /// inside a subdirectory of a Git monorepo), evaluated purely in-process via `gix`.
  56. pub fn find_git_worktree_root(dir: &Path) -> Option<PathBuf> {
  57. let repo = gix::discover(dir).ok()?;
  58. repo.workdir().map(Path::to_path_buf)
  59. }
  60. /// Returns `true` if the working tree has no staged, unstaged, or untracked changes.
  61. pub fn is_clean(dir: &Path) -> Result<bool> {
  62. let status = run_git_checked(Some(dir), &["status", "--porcelain", "--no-renames"])?;
  63. Ok(status.is_empty())
  64. }
  65. /// Check cleanliness AND collect `.gitignore`-ignored paths in ONE NUL-delimited (`-z`)
  66. /// `git status` invocation (Copier post-v9.19.1 `1b54bbeb`: safe for spaces/quotes/unicode).
  67. pub fn inspect_working_tree(repo_root: &Path) -> Result<WorkingTreeStatus> {
  68. let out = run_git(
  69. Some(repo_root),
  70. &[
  71. "status",
  72. "--ignored=matching",
  73. "--porcelain",
  74. "-z",
  75. "--no-renames",
  76. ],
  77. )?;
  78. if !out.status.success() {
  79. let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
  80. return Err(RoneoError::Vcs(format!("`git status` failed: {stderr}")));
  81. }
  82. let mut is_clean = true;
  83. let mut ignored_paths = Vec::new();
  84. for record in out.stdout.split(|&b| b == 0) {
  85. if record.is_empty() {
  86. continue;
  87. }
  88. let text = String::from_utf8_lossy(record);
  89. if let Some(rest) = text.strip_prefix("!! ") {
  90. if !rest.is_empty() {
  91. ignored_paths.push(rest.to_string());
  92. }
  93. } else {
  94. is_clean = false;
  95. }
  96. }
  97. Ok(WorkingTreeStatus {
  98. is_clean,
  99. ignored_paths,
  100. })
  101. }
  102. /// Read BOTH `describe` (tag/commit) and 40-char `HEAD` hash in a single `gix` repo open.
  103. pub fn describe_and_hash_head(repo_path: &Path) -> Result<(Option<String>, String)> {
  104. let repo = open_gix_repo(repo_path)?;
  105. let commit = repo
  106. .rev_parse_single("HEAD")
  107. .map_err(|e| RoneoError::Vcs(format!("Failed to resolve HEAD: {e}")))?
  108. .object()
  109. .map_err(|e| RoneoError::Vcs(format!("Failed to read HEAD object: {e}")))?
  110. .peel_to_commit()
  111. .map_err(|e| RoneoError::Vcs(format!("HEAD is not a commit: {e}")))?;
  112. let hash = commit.id.to_string();
  113. let desc = fast_describe_commit(&repo, &commit).ok();
  114. Ok((desc, hash))
  115. }
  116. pub fn describe_commit(repo: &Path) -> Result<String> {
  117. describe_ref(repo, "HEAD")
  118. }
  119. /// Describe a git ref (`git describe --tags --always <ref>`) in-process via `gix`.
  120. pub fn describe_ref(repo_path: &Path, git_ref: &str) -> Result<String> {
  121. let repo = open_gix_repo(repo_path)?;
  122. let commit = repo
  123. .rev_parse_single(git_ref)
  124. .map_err(|e| RoneoError::Vcs(format!("Failed to resolve ref '{git_ref}': {e}")))?
  125. .object()
  126. .map_err(|e| RoneoError::Vcs(format!("Failed to read object for '{git_ref}': {e}")))?
  127. .peel_to_commit()
  128. .map_err(|e| RoneoError::Vcs(format!("Ref '{git_ref}' is not a commit: {e}")))?;
  129. fast_describe_commit(&repo, &commit)
  130. }
  131. /// Fast `git describe --tags --always` via `gix`:
  132. /// 1. First checks direct tag matches using `packed-refs` peeled OIDs (zero object decompression,
  133. /// ~2 ms even on monorepos with 8 000+ tags!).
  134. /// 2. Falls back to full `commit.describe()` graph walk only if the commit is not directly tagged.
  135. fn fast_describe_commit(repo: &gix::Repository, commit: &gix::Commit<'_>) -> Result<String> {
  136. if let Ok(refs) = repo.references()
  137. && let Ok(tags) = refs.tags()
  138. {
  139. let mut exact_matches: Vec<String> = Vec::new();
  140. for tag_ref in tags.flatten() {
  141. let matches_peeled = tag_ref.inner().peeled == Some(commit.id);
  142. let matches_direct = tag_ref.target().try_id() == Some(commit.id.as_ref());
  143. if matches_peeled || matches_direct {
  144. exact_matches.push(tag_ref.name().shorten().to_str_lossy().into_owned());
  145. }
  146. }
  147. if !exact_matches.is_empty() {
  148. exact_matches.sort();
  149. return Ok(exact_matches.swap_remove(0));
  150. }
  151. }
  152. let formatted = commit
  153. .describe()
  154. .names(gix::commit::describe::SelectRef::AllTags)
  155. .id_as_fallback(true)
  156. .format()
  157. .map_err(|e| RoneoError::Vcs(format!("Failed to describe commit: {e}")))?;
  158. Ok(formatted.to_string())
  159. }
  160. pub fn rev_parse_head(repo: &Path) -> Result<String> {
  161. rev_parse_ref(repo, "HEAD")
  162. }
  163. /// Resolve a git ref to its full 40-char commit hex ID in-process via `gix`.
  164. pub fn rev_parse_ref(repo_path: &Path, git_ref: &str) -> Result<String> {
  165. let repo = open_gix_repo(repo_path)?;
  166. let commit = repo
  167. .rev_parse_single(git_ref)
  168. .map_err(|e| RoneoError::Vcs(format!("Failed to resolve ref '{git_ref}': {e}")))?
  169. .object()
  170. .map_err(|e| RoneoError::Vcs(format!("Failed to read object for '{git_ref}': {e}")))?
  171. .peel_to_commit()
  172. .map_err(|e| RoneoError::Vcs(format!("Ref '{git_ref}' is not a commit: {e}")))?;
  173. Ok(commit.id.to_string())
  174. }
  175. /// A blob or symlink entry discovered while walking a `gix::Tree` in memory.
  176. #[derive(Debug, Clone)]
  177. pub struct GitTreeFile {
  178. /// Source path relative to the walked root (`_subdirectory` or repo root).
  179. pub rel_path: PathBuf,
  180. /// Already-rendered destination parent directory (computed once per directory, not per file).
  181. pub rendered_parent: PathBuf,
  182. /// Raw leaf filename (the only segment left to render for this entry).
  183. pub file_name: String,
  184. /// Any `{% yield var from list %}` bindings inherited from parent directories (empty in 99.9% of cases).
  185. pub extra_vars: Vec<(String, JsonValue)>,
  186. pub oid: gix::ObjectId,
  187. pub is_executable: bool,
  188. pub is_symlink: bool,
  189. }
  190. /// Thread-safe, zero-TempDir handle to a specific commit tree inside a local Git repository.
  191. /// Allows reading `copier.yml`, `!include` files, Jinja `{% include %}` partials, plugin files,
  192. /// and template blobs directly from Git packfiles in memory.
  193. pub struct InMemoryGitTree {
  194. sync_repo: gix::ThreadSafeRepository,
  195. pub tree_oid: gix::ObjectId,
  196. pub commit_describe: Option<String>,
  197. pub commit_hash: String,
  198. }
  199. impl std::fmt::Debug for InMemoryGitTree {
  200. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  201. f.debug_struct("InMemoryGitTree")
  202. .field("commit_describe", &self.commit_describe)
  203. .field("commit_hash", &self.commit_hash)
  204. .finish_non_exhaustive()
  205. }
  206. }
  207. impl InMemoryGitTree {
  208. /// Open a local git repo ONCE via `gix` and resolve `vcs_ref` (or latest PEP 440 tag / `HEAD`).
  209. pub fn open(repo_path: &Path, vcs_ref: Option<&str>, use_prereleases: bool) -> Result<Self> {
  210. let repo = open_gix_repo(repo_path)?;
  211. Self::from_repo(repo, vcs_ref, use_prereleases)
  212. }
  213. /// Resolve another ref in the SAME repository without reopening `.git` or reloading pack indices.
  214. pub fn open_sibling(&self, vcs_ref: Option<&str>, use_prereleases: bool) -> Result<Self> {
  215. let repo = self.sync_repo.to_thread_local();
  216. Self::from_repo(repo, vcs_ref, use_prereleases)
  217. }
  218. fn from_repo(
  219. repo: gix::Repository,
  220. vcs_ref: Option<&str>,
  221. use_prereleases: bool,
  222. ) -> Result<Self> {
  223. let target_ref = match vcs_ref {
  224. Some(r) => {
  225. if r.starts_with('-') {
  226. return Err(RoneoError::Vcs(format!(
  227. "Invalid git ref '{r}': refs may not start with '-'"
  228. )));
  229. }
  230. r.to_string()
  231. }
  232. None => latest_version_tag_in_repo(&repo, use_prereleases)?
  233. .unwrap_or_else(|| "HEAD".to_string()),
  234. };
  235. let commit = repo
  236. .rev_parse_single(target_ref.as_str())
  237. .map_err(|e| RoneoError::Vcs(format!("Failed to resolve ref '{target_ref}': {e}")))?
  238. .object()
  239. .map_err(|e| RoneoError::Vcs(format!("Failed to read object '{target_ref}': {e}")))?
  240. .peel_to_commit()
  241. .map_err(|e| RoneoError::Vcs(format!("Ref '{target_ref}' is not a commit: {e}")))?;
  242. let commit_hash = commit.id.to_string();
  243. let commit_describe = fast_describe_commit(&repo, &commit).ok();
  244. let tree_oid = commit
  245. .tree_id()
  246. .map_err(|e| RoneoError::Vcs(format!("Failed to get commit tree id: {e}")))?
  247. .detach();
  248. drop(commit);
  249. Ok(Self {
  250. sync_repo: repo.into_sync(),
  251. tree_oid,
  252. commit_describe,
  253. commit_hash,
  254. })
  255. }
  256. /// Obtain a thread-local `gix::Repository` handle (reusable across many blob reads on one thread).
  257. pub fn thread_local_repo(&self) -> gix::Repository {
  258. self.sync_repo.to_thread_local()
  259. }
  260. /// Read raw bytes of a blob using an already-acquired thread-local `gix::Repository`.
  261. pub fn read_blob_with_repo(repo: &gix::Repository, oid: gix::ObjectId) -> Result<Vec<u8>> {
  262. let obj = repo
  263. .find_object(oid)
  264. .map_err(|e| RoneoError::Vcs(format!("Failed reading blob {oid}: {e}")))?;
  265. Ok(obj.data.clone())
  266. }
  267. /// Read a blob by relative path from the repo root directly in memory.
  268. pub fn read_bytes(&self, rel_path: &str) -> Option<Vec<u8>> {
  269. let repo = self.sync_repo.to_thread_local();
  270. let tree = repo.find_object(self.tree_oid).ok()?.into_tree();
  271. let entry = tree.lookup_entry_by_path(rel_path).ok()??;
  272. let obj = entry.object().ok()?;
  273. (obj.kind == gix::object::Kind::Blob).then(|| obj.data.clone())
  274. }
  275. /// Read a UTF-8 file by relative path from the repo root directly in memory.
  276. pub fn read_string(&self, rel_path: &str) -> Option<String> {
  277. String::from_utf8(self.read_bytes(rel_path)?).ok()
  278. }
  279. /// Read raw bytes of a blob by its `ObjectId` (used on parallel worker threads).
  280. pub fn read_blob_oid(&self, oid: gix::ObjectId) -> Result<Vec<u8>> {
  281. let repo = self.sync_repo.to_thread_local();
  282. let obj = repo
  283. .find_object(oid)
  284. .map_err(|e| RoneoError::Vcs(format!("Failed reading blob {oid}: {e}")))?;
  285. Ok(obj.data.clone())
  286. }
  287. /// List all relative file paths in the commit tree matching a glob pattern (e.g. `questions/*.yml`),
  288. /// pruning non-matching leading literal directory prefixes automatically.
  289. pub fn list_matching_files(&self, pattern: &str) -> Vec<String> {
  290. let repo = self.sync_repo.to_thread_local();
  291. let Ok(root_obj) = repo.find_object(self.tree_oid) else {
  292. return Vec::new();
  293. };
  294. let root_tree = root_obj.into_tree();
  295. // Narrow the walk to the longest static directory prefix before any wildcard.
  296. let mut static_prefix = PathBuf::new();
  297. for seg in pattern.trim_start_matches('/').split('/') {
  298. if seg.contains(['*', '?', '[']) || seg.is_empty() {
  299. break;
  300. }
  301. static_prefix.push(seg);
  302. }
  303. let (start_tree, base_prefix) = if static_prefix.as_os_str().is_empty() {
  304. (root_tree, PathBuf::new())
  305. } else if let Ok(Some(entry)) = root_tree.lookup_entry_by_path(&static_prefix)
  306. && entry.mode().kind() == EntryKind::Tree
  307. && let Ok(obj) = entry.object()
  308. {
  309. (obj.into_tree(), static_prefix)
  310. } else {
  311. return Vec::new();
  312. };
  313. let mut matches = Vec::new();
  314. collect_matching_in_tree(&repo, &start_tree, &base_prefix, pattern, &mut matches);
  315. matches.sort();
  316. matches
  317. }
  318. /// Walk `subdir` (or root tree) in memory, invoking `enter_dir` once per directory to prune
  319. /// excluded subtrees BEFORE touching their entries or decompressing any blobs, and expanding
  320. /// `{% yield %}` directories into multiple `(rendered_dir, extra_vars)` branches.
  321. pub fn walk_files<F>(&self, subdir: Option<&str>, mut enter_dir: F) -> Result<Vec<GitTreeFile>>
  322. where
  323. F: FnMut(
  324. &Path,
  325. &Path,
  326. &str,
  327. &[(String, JsonValue)],
  328. ) -> Result<Vec<(PathBuf, Vec<(String, JsonValue)>)>>,
  329. {
  330. let repo = self.sync_repo.to_thread_local();
  331. let root_tree = repo
  332. .find_object(self.tree_oid)
  333. .map_err(|e| RoneoError::Vcs(format!("Failed to load root tree: {e}")))?
  334. .into_tree();
  335. let start_tree = match subdir.filter(|s| !s.trim().is_empty()) {
  336. Some(sub) => {
  337. let entry = root_tree
  338. .lookup_entry_by_path(sub)
  339. .map_err(|e| RoneoError::Vcs(format!("Failed looking up '{sub}': {e}")))?
  340. .ok_or_else(|| {
  341. RoneoError::TemplateSource(format!(
  342. "Template subdirectory '{sub}' does not exist in git tree"
  343. ))
  344. })?;
  345. if entry.mode().kind() != EntryKind::Tree {
  346. return Err(RoneoError::TemplateSource(format!(
  347. "Template subdirectory '{sub}' is not a directory"
  348. )));
  349. }
  350. entry
  351. .object()
  352. .map_err(|e| RoneoError::Vcs(format!("Failed reading tree '{sub}': {e}")))?
  353. .into_tree()
  354. }
  355. None => root_tree,
  356. };
  357. let mut files = Vec::new();
  358. walk_tree_in_memory(
  359. &repo,
  360. &start_tree,
  361. Path::new(""),
  362. Path::new(""),
  363. &[],
  364. &mut enter_dir,
  365. &mut files,
  366. )?;
  367. files.sort_by(|a, b| {
  368. a.rendered_parent
  369. .cmp(&b.rendered_parent)
  370. .then_with(|| a.rel_path.cmp(&b.rel_path))
  371. });
  372. Ok(files)
  373. }
  374. }
  375. fn collect_matching_in_tree(
  376. repo: &gix::Repository,
  377. tree: &gix::Tree<'_>,
  378. prefix: &Path,
  379. pattern: &str,
  380. out: &mut Vec<String>,
  381. ) {
  382. for entry_res in tree.iter() {
  383. let Ok(entry) = entry_res else {
  384. continue;
  385. };
  386. let name = entry.filename().to_str_lossy();
  387. let rel = if prefix.as_os_str().is_empty() {
  388. PathBuf::from(name.as_ref())
  389. } else {
  390. prefix.join(name.as_ref())
  391. };
  392. match entry.mode().kind() {
  393. EntryKind::Tree => {
  394. if let Ok(obj) = repo.find_object(entry.id().detach()) {
  395. collect_matching_in_tree(repo, &obj.into_tree(), &rel, pattern, out);
  396. }
  397. }
  398. EntryKind::Blob | EntryKind::BlobExecutable => {
  399. if match_glob_path(pattern, &rel) {
  400. out.push(rel.to_string_lossy().replace('\\', "/"));
  401. }
  402. }
  403. EntryKind::Link | EntryKind::Commit => {}
  404. }
  405. }
  406. }
  407. fn walk_tree_in_memory<F>(
  408. repo: &gix::Repository,
  409. tree: &gix::Tree<'_>,
  410. src_prefix: &Path,
  411. rendered_prefix: &Path,
  412. extra_vars: &[(String, JsonValue)],
  413. enter_dir: &mut F,
  414. out: &mut Vec<GitTreeFile>,
  415. ) -> Result<()>
  416. where
  417. F: FnMut(
  418. &Path,
  419. &Path,
  420. &str,
  421. &[(String, JsonValue)],
  422. ) -> Result<Vec<(PathBuf, Vec<(String, JsonValue)>)>>,
  423. {
  424. for entry_res in tree.iter() {
  425. let entry =
  426. entry_res.map_err(|e| RoneoError::Vcs(format!("Failed iterating git tree: {e}")))?;
  427. let name = entry.filename().to_str_lossy();
  428. let rel = if src_prefix.as_os_str().is_empty() {
  429. PathBuf::from(name.as_ref())
  430. } else {
  431. src_prefix.join(name.as_ref())
  432. };
  433. match entry.mode().kind() {
  434. EntryKind::Tree => {
  435. let branches = enter_dir(&rel, rendered_prefix, name.as_ref(), extra_vars)?;
  436. if branches.is_empty() {
  437. continue;
  438. }
  439. let sub = repo
  440. .find_object(entry.id().detach())
  441. .map_err(|e| RoneoError::Vcs(format!("Failed reading subtree: {e}")))?
  442. .into_tree();
  443. for (next_rendered, next_vars) in branches {
  444. walk_tree_in_memory(
  445. repo,
  446. &sub,
  447. &rel,
  448. &next_rendered,
  449. &next_vars,
  450. enter_dir,
  451. out,
  452. )?;
  453. }
  454. }
  455. EntryKind::Blob => {
  456. out.push(GitTreeFile {
  457. rel_path: rel,
  458. rendered_parent: rendered_prefix.to_path_buf(),
  459. file_name: name.into_owned(),
  460. extra_vars: extra_vars.to_vec(),
  461. oid: entry.id().detach(),
  462. is_executable: false,
  463. is_symlink: false,
  464. });
  465. }
  466. EntryKind::BlobExecutable => {
  467. out.push(GitTreeFile {
  468. rel_path: rel,
  469. rendered_parent: rendered_prefix.to_path_buf(),
  470. file_name: name.into_owned(),
  471. extra_vars: extra_vars.to_vec(),
  472. oid: entry.id().detach(),
  473. is_executable: true,
  474. is_symlink: false,
  475. });
  476. }
  477. EntryKind::Link => {
  478. out.push(GitTreeFile {
  479. rel_path: rel,
  480. rendered_parent: rendered_prefix.to_path_buf(),
  481. file_name: name.into_owned(),
  482. extra_vars: extra_vars.to_vec(),
  483. oid: entry.id().detach(),
  484. is_executable: false,
  485. is_symlink: true,
  486. });
  487. }
  488. EntryKind::Commit => {}
  489. }
  490. }
  491. Ok(())
  492. }
  493. fn latest_version_tag_in_repo(
  494. repo: &gix::Repository,
  495. use_prereleases: bool,
  496. ) -> Result<Option<String>> {
  497. let refs = repo
  498. .references()
  499. .map_err(|e| RoneoError::Vcs(format!("Failed to list references: {e}")))?;
  500. let tags = refs
  501. .tags()
  502. .map_err(|e| RoneoError::Vcs(format!("Failed to list tags: {e}")))?;
  503. let mut all_parsed: Vec<(Pep440Version, String)> = Vec::new();
  504. for tag_ref in tags.flatten() {
  505. let short = tag_ref.name().shorten().to_str_lossy();
  506. if let Some(ver) = Pep440Version::parse(&short) {
  507. all_parsed.push((ver, short.into_owned()));
  508. }
  509. }
  510. if !use_prereleases {
  511. let mut stable: Vec<(Pep440Version, String)> = all_parsed
  512. .iter()
  513. .filter(|(v, _)| !v.is_prerelease())
  514. .cloned()
  515. .collect();
  516. if !stable.is_empty() {
  517. stable.sort_by(|a, b| a.0.cmp(&b.0));
  518. return Ok(stable.pop().map(|(_, tag)| tag));
  519. }
  520. }
  521. all_parsed.sort_by(|a, b| a.0.cmp(&b.0));
  522. Ok(all_parsed.pop().map(|(_, tag)| tag))
  523. }
  524. /// Return the highest PEP 440 tag in `repo`, evaluated purely in-process via `gix`.
  525. pub fn latest_version_tag(repo_path: &Path, use_prereleases: bool) -> Result<Option<String>> {
  526. let repo = open_gix_repo(repo_path)?;
  527. latest_version_tag_in_repo(&repo, use_prereleases)
  528. }
  529. // ---------------------------------------------------------------------------
  530. // Git CLI helpers for remote cloning & 3-way merge patching (`update` / `diff`)
  531. // ---------------------------------------------------------------------------
  532. fn run_git(cwd: Option<&Path>, args: &[&str]) -> Result<std::process::Output> {
  533. let mut cmd = Command::new("git");
  534. if let Some(dir) = cwd {
  535. cmd.current_dir(dir);
  536. }
  537. cmd.env("GIT_TERMINAL_PROMPT", "0");
  538. cmd.args(args);
  539. cmd.output()
  540. .map_err(|e| RoneoError::Vcs(format!("Failed to execute `git {}`: {e}", args.join(" "))))
  541. }
  542. fn run_git_checked(cwd: Option<&Path>, args: &[&str]) -> Result<String> {
  543. let out = run_git(cwd, args)?;
  544. if !out.status.success() {
  545. let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
  546. return Err(RoneoError::Vcs(format!(
  547. "`git {}` failed: {stderr}",
  548. args.join(" ")
  549. )));
  550. }
  551. Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
  552. }
  553. pub fn clone_repo(src: &str, dst: &Path) -> Result<()> {
  554. let dst_str = dst
  555. .to_str()
  556. .ok_or_else(|| RoneoError::Vcs("Non-UTF-8 temporary path".into()))?;
  557. let no_hooks = format!("core.hooksPath={}", null_device_path());
  558. run_git_checked(
  559. None,
  560. &["-c", &no_hooks, "clone", "--quiet", "--", src, dst_str],
  561. )?;
  562. if dst.join(".gitmodules").is_file() {
  563. let _ = run_git_checked(
  564. Some(dst),
  565. &[
  566. "-c",
  567. &no_hooks,
  568. "submodule",
  569. "update",
  570. "--init",
  571. "--recursive",
  572. "--quiet",
  573. ],
  574. );
  575. }
  576. Ok(())
  577. }
  578. /// Clone a remote repository using a persistent local bare mirror cache (`~/.cache/roneo/repos/<hash>`,
  579. /// matching Copier v9.16.0 `#2720`). Falls back to a direct clone if caching is disabled via
  580. /// `RONEO_NO_CACHE=1` or unavailable.
  581. pub fn clone_repo_cached(src: &str, dst: &Path) -> Result<()> {
  582. if std::env::var_os("RONEO_NO_CACHE").is_some_and(|v| v == "1" || v == "true") {
  583. return clone_repo(src, dst);
  584. }
  585. let Some(cache_root) = remote_mirror_cache_dir() else {
  586. return clone_repo(src, dst);
  587. };
  588. if std::fs::create_dir_all(&cache_root).is_err() {
  589. return clone_repo(src, dst);
  590. }
  591. let cache_key = strip_url_credentials(src);
  592. let mirror_dir = cache_root.join(format!("{:016x}.git", fnv1a_64(cache_key.as_bytes())));
  593. let mirror_str = mirror_dir.to_string_lossy().into_owned();
  594. let no_hooks = format!("core.hooksPath={}", null_device_path());
  595. let mirror_ready = if mirror_dir.join("HEAD").is_file() {
  596. run_git_checked(
  597. Some(&mirror_dir),
  598. &[
  599. "-c", &no_hooks, "fetch", "--prune", "--tags", "--quiet", "origin",
  600. ],
  601. )
  602. .is_ok()
  603. } else {
  604. if mirror_dir.exists() {
  605. let _ = std::fs::remove_dir_all(&mirror_dir);
  606. }
  607. let ok = run_git_checked(
  608. None,
  609. &[
  610. "-c",
  611. &no_hooks,
  612. "clone",
  613. "--mirror",
  614. "--quiet",
  615. "--",
  616. src,
  617. &mirror_str,
  618. ],
  619. )
  620. .is_ok();
  621. if !ok {
  622. let _ = std::fs::remove_dir_all(&mirror_dir);
  623. }
  624. ok
  625. };
  626. if mirror_ready {
  627. let dst_str = dst
  628. .to_str()
  629. .ok_or_else(|| RoneoError::Vcs("Non-UTF-8 temporary path".into()))?;
  630. if run_git_checked(
  631. None,
  632. &[
  633. "-c",
  634. &no_hooks,
  635. "clone",
  636. "--shared",
  637. "--quiet",
  638. "--",
  639. &mirror_str,
  640. dst_str,
  641. ],
  642. )
  643. .is_ok()
  644. {
  645. if dst.join(".gitmodules").is_file() {
  646. let _ = run_git_checked(
  647. Some(dst),
  648. &[
  649. "-c",
  650. &no_hooks,
  651. "submodule",
  652. "update",
  653. "--init",
  654. "--recursive",
  655. "--quiet",
  656. ],
  657. );
  658. }
  659. return Ok(());
  660. }
  661. }
  662. clone_repo(src, dst)
  663. }
  664. fn remote_mirror_cache_dir() -> Option<PathBuf> {
  665. if let Ok(custom) = std::env::var("RONEO_CACHE_DIR")
  666. && !custom.trim().is_empty()
  667. {
  668. return Some(PathBuf::from(custom).join("repos"));
  669. }
  670. if let Ok(xdg) = std::env::var("XDG_CACHE_HOME")
  671. && !xdg.trim().is_empty()
  672. {
  673. return Some(PathBuf::from(xdg).join("roneo/repos"));
  674. }
  675. let home = std::env::var("HOME")
  676. .or_else(|_| std::env::var("USERPROFILE"))
  677. .ok()?;
  678. Some(PathBuf::from(home).join(".cache/roneo/repos"))
  679. }
  680. /// Remove embedded `user:pass@` credentials from an HTTP(S)/SSH URL before hashing it for
  681. /// the local bare mirror cache key (matches Copier v9.16 `_strip_credentials`).
  682. fn strip_url_credentials(url: &str) -> std::borrow::Cow<'_, str> {
  683. let Some(scheme_end) = url.find("://") else {
  684. return std::borrow::Cow::Borrowed(url);
  685. };
  686. let rest = &url[scheme_end + 3..];
  687. let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
  688. let authority = &rest[..authority_end];
  689. let Some(at_pos) = authority.rfind('@') else {
  690. return std::borrow::Cow::Borrowed(url);
  691. };
  692. let mut cleaned = String::with_capacity(url.len() - at_pos - 1);
  693. cleaned.push_str(&url[..scheme_end + 3]);
  694. cleaned.push_str(&rest[at_pos + 1..]);
  695. std::borrow::Cow::Owned(cleaned)
  696. }
  697. fn fnv1a_64(bytes: &[u8]) -> u64 {
  698. let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
  699. for &b in bytes {
  700. hash ^= u64::from(b);
  701. hash = hash.wrapping_mul(0x0100_0000_01b3);
  702. }
  703. hash
  704. }
  705. pub fn checkout_ref(repo: &Path, git_ref: &str) -> Result<()> {
  706. if git_ref.starts_with('-') {
  707. return Err(RoneoError::Vcs(format!(
  708. "Invalid git ref '{git_ref}': refs may not start with '-'"
  709. )));
  710. }
  711. let no_hooks = format!("core.hooksPath={}", null_device_path());
  712. run_git_checked(
  713. Some(repo),
  714. &[
  715. "-c", &no_hooks, "checkout", "--quiet", "--detach", git_ref, "--",
  716. ],
  717. )?;
  718. if repo.join(".gitmodules").is_file() {
  719. let _ = run_git_checked(
  720. Some(repo),
  721. &[
  722. "-c",
  723. &no_hooks,
  724. "submodule",
  725. "update",
  726. "--init",
  727. "--recursive",
  728. "--force",
  729. "--quiet",
  730. ],
  731. );
  732. }
  733. Ok(())
  734. }
  735. /// Produce a binary unified diff between sibling directories `old_name` (`a`) and `new_name` (`b`)
  736. /// inside `parent_dir` in ONE `git diff --no-index` call — zero `git init`, zero `git add`,
  737. /// zero `git commit`, zero working-tree copy/delete.
  738. pub fn diff_directories(
  739. parent_dir: &Path,
  740. old_name: &str,
  741. new_name: &str,
  742. context_lines: usize,
  743. ) -> Result<Vec<u8>> {
  744. let unified = format!("--unified={context_lines}");
  745. let out = run_git(
  746. Some(parent_dir),
  747. &[
  748. "diff",
  749. "--no-index",
  750. "--no-prefix",
  751. "--no-renames",
  752. "--binary",
  753. "--full-index",
  754. "--no-ext-diff",
  755. "--no-color",
  756. &unified,
  757. "--",
  758. old_name,
  759. new_name,
  760. ],
  761. )?;
  762. // `git diff --no-index` exits 0 (no changes), 1 (changes found), or >1 (error).
  763. if matches!(out.status.code(), Some(0 | 1)) {
  764. Ok(out.stdout)
  765. } else {
  766. let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
  767. Err(RoneoError::Vcs(format!(
  768. "`git diff --no-index` failed: {stderr}"
  769. )))
  770. }
  771. }
  772. /// Apply a binary unified diff patch to `repo_root` (optionally scoped to `subproject_subdir`
  773. /// when updating a project nested inside a Git monorepo) using 3-way merge (`--3way`) or `--reject`.
  774. ///
  775. /// When `mode == ConflictMode::Inline` and `git apply --3way` cannot locate base blobs in the
  776. /// destination ODB (e.g., after a squash merge, rebase, or fresh `git init`), automatically falls
  777. /// back to Copier's `git apply --reject` + `git merge-file` using `merge_snapshots` (`old_dir`, `new_dir`).
  778. pub fn apply_patch(
  779. repo_root: &Path,
  780. subproject_subdir: Option<&Path>,
  781. patch: &[u8],
  782. mode: ConflictMode,
  783. exclude_paths: &[String],
  784. merge_snapshots: Option<(&Path, &Path)>,
  785. ) -> Result<ApplyResult> {
  786. if patch.is_empty() {
  787. return Ok(ApplyResult {
  788. has_conflicts: false,
  789. stderr: String::new(),
  790. conflicted_files: Vec::new(),
  791. });
  792. }
  793. let flag = match mode {
  794. ConflictMode::Inline => "--3way",
  795. ConflictMode::Rej => "--reject",
  796. };
  797. let out = run_git_apply(repo_root, subproject_subdir, patch, flag, exclude_paths)?;
  798. let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
  799. if out.status.success() {
  800. return Ok(ApplyResult {
  801. has_conflicts: false,
  802. stderr,
  803. conflicted_files: Vec::new(),
  804. });
  805. }
  806. let strip_subdir = |repo_rel: &str| -> String {
  807. if let Some(sub) = subproject_subdir
  808. && !sub.as_os_str().is_empty()
  809. {
  810. let prefix = format!("{}/", sub.to_string_lossy().replace('\\', "/"));
  811. repo_rel
  812. .strip_prefix(&prefix)
  813. .unwrap_or(repo_rel)
  814. .to_string()
  815. } else {
  816. repo_rel.to_string()
  817. }
  818. };
  819. if mode == ConflictMode::Inline {
  820. let mut conflicted_files: Vec<String> =
  821. run_git_checked(Some(repo_root), &["diff", "--name-only", "--diff-filter=U"])
  822. .unwrap_or_default()
  823. .lines()
  824. .filter(|l| !l.trim().is_empty())
  825. .map(&strip_subdir)
  826. .collect();
  827. // Squash / missing-ODB fallback: `git apply --3way` failed without producing index
  828. // conflicts (e.g. `sha1 information is lacking or useless`). Run `git apply --reject`
  829. // followed by `git merge-file` directly against `(old_dir, new_dir)` snapshots (Copier).
  830. if conflicted_files.is_empty()
  831. && let Some((old_dir, new_dir)) = merge_snapshots
  832. {
  833. let rej_out = run_git_apply(
  834. repo_root,
  835. subproject_subdir,
  836. patch,
  837. "--reject",
  838. exclude_paths,
  839. )?;
  840. let rej_stderr = String::from_utf8_lossy(&rej_out.stderr).trim().to_string();
  841. let status_out = run_git(
  842. Some(repo_root),
  843. &[
  844. "status",
  845. "--porcelain",
  846. "-z",
  847. "--untracked-files=all",
  848. "--ignored=matching",
  849. "--no-renames",
  850. ],
  851. )?;
  852. for record in status_out.stdout.split(|&b| b == 0) {
  853. if record.is_empty() {
  854. continue;
  855. }
  856. let text = String::from_utf8_lossy(record);
  857. // Match both untracked (`?? `) and gitignored (`!! `) `.rej` files (Copier v9.15.2 `#2668`).
  858. let raw_path = text
  859. .strip_prefix("?? ")
  860. .or_else(|| text.strip_prefix("!! "));
  861. let Some(path_str) = raw_path else {
  862. continue;
  863. };
  864. let Some(repo_rel_file) = path_str.strip_suffix(".rej") else {
  865. continue;
  866. };
  867. let rej_abs = repo_root.join(path_str);
  868. let _ = std::fs::remove_file(&rej_abs);
  869. let sub_rel = strip_subdir(repo_rel_file);
  870. let dst_abs = repo_root.join(repo_rel_file);
  871. let old_abs = old_dir.join(&sub_rel);
  872. let new_abs = new_dir.join(&sub_rel);
  873. if old_abs.is_file() && new_abs.is_file() && dst_abs.is_file() {
  874. // Undo any partial hunks before performing a clean 3-way `git merge-file`.
  875. let null_hooks = format!("core.hooksPath={}", null_device_path());
  876. let _ = run_git(
  877. Some(repo_root),
  878. &["-c", &null_hooks, "checkout", "--", repo_rel_file],
  879. );
  880. let merge_out = run_git(
  881. Some(repo_root),
  882. &[
  883. "merge-file",
  884. "-L",
  885. "before updating",
  886. "-L",
  887. "last update",
  888. "-L",
  889. "after updating",
  890. "--",
  891. &dst_abs.to_string_lossy(),
  892. &old_abs.to_string_lossy(),
  893. &new_abs.to_string_lossy(),
  894. ],
  895. )?;
  896. if !merge_out.status.success() {
  897. conflicted_files.push(sub_rel);
  898. }
  899. } else {
  900. conflicted_files.push(sub_rel);
  901. }
  902. }
  903. return Ok(ApplyResult {
  904. has_conflicts: !conflicted_files.is_empty(),
  905. stderr: if conflicted_files.is_empty() {
  906. String::new()
  907. } else {
  908. rej_stderr
  909. },
  910. conflicted_files,
  911. });
  912. }
  913. return Ok(ApplyResult {
  914. has_conflicts: true,
  915. stderr,
  916. conflicted_files,
  917. });
  918. }
  919. let conflicted_files = stderr
  920. .lines()
  921. .filter_map(|line| {
  922. line.strip_prefix("Applying patch ")
  923. .and_then(|rest| rest.split(" with ").next())
  924. .map(ToOwned::to_owned)
  925. })
  926. .collect();
  927. Ok(ApplyResult {
  928. has_conflicts: true,
  929. stderr,
  930. conflicted_files,
  931. })
  932. }
  933. fn run_git_apply(
  934. repo_root: &Path,
  935. subproject_subdir: Option<&Path>,
  936. patch: &[u8],
  937. flag: &str,
  938. exclude_paths: &[String],
  939. ) -> Result<std::process::Output> {
  940. let mut args: Vec<String> = vec!["apply".into(), flag.into(), "--whitespace=nowarn".into()];
  941. if let Some(sub) = subproject_subdir
  942. && !sub.as_os_str().is_empty()
  943. {
  944. args.push(format!(
  945. "--directory={}",
  946. sub.to_string_lossy().replace('\\', "/")
  947. ));
  948. }
  949. for pat in exclude_paths {
  950. args.push("--exclude".into());
  951. args.push(pat.clone());
  952. }
  953. args.push("-".into());
  954. let mut child = Command::new("git")
  955. .current_dir(repo_root)
  956. .args(&args)
  957. .stdin(Stdio::piped())
  958. .stdout(Stdio::piped())
  959. .stderr(Stdio::piped())
  960. .spawn()
  961. .map_err(|e| RoneoError::Vcs(format!("Failed to spawn `git apply`: {e}")))?;
  962. if let Some(mut stdin) = child.stdin.take() {
  963. stdin
  964. .write_all(patch)
  965. .map_err(|e| RoneoError::Vcs(format!("Failed to write patch to `git apply`: {e}")))?;
  966. }
  967. child
  968. .wait_with_output()
  969. .map_err(|e| RoneoError::Vcs(format!("Failed waiting for `git apply`: {e}")))
  970. }
  971. #[cfg(unix)]
  972. fn null_device_path() -> &'static str {
  973. "/dev/null"
  974. }
  975. #[cfg(windows)]
  976. fn null_device_path() -> &'static str {
  977. "NUL"
  978. }
  979. #[cfg(test)]
  980. mod tests {
  981. use super::strip_url_credentials;
  982. #[test]
  983. fn strip_url_credentials_keeps_host_and_path() {
  984. assert_eq!(
  985. strip_url_credentials("https://user:secret@github.com/org/repo.git"),
  986. "https://github.com/org/repo.git"
  987. );
  988. assert_eq!(
  989. strip_url_credentials("https://github.com/org/repo.git"),
  990. "https://github.com/org/repo.git"
  991. );
  992. assert_eq!(
  993. strip_url_credentials("git@github.com:org/repo.git"),
  994. "git@github.com:org/repo.git"
  995. );
  996. }
  997. }