roneocratesroneo-coresrcvcs.rs
0518da6beb3fd562b82c5b5c2798b72e0d1591b2- use std::io::{Read, Write};
- use std::path::{Path, PathBuf};
- use std::process::{Command, Stdio};
- use gix::bstr::ByteSlice;
- use gix::object::tree::EntryKind;
- use serde_json::Value as JsonValue;
- use crate::error::{Result, RoneoError};
- use crate::filter::match_glob_path;
- use crate::version::Pep440Version;
- #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
- pub enum ConflictMode {
- /// Insert standard `<<<<<<<` / `=======` / `>>>>>>>` conflict markers via `git apply --3way`.
- #[default]
- Inline,
- /// Write `.rej` files alongside conflicted targets via `git apply --reject`.
- Rej,
- }
- #[derive(Debug, Clone)]
- pub struct ApplyResult {
- pub has_conflicts: bool,
- pub stderr: String,
- pub conflicted_files: Vec<String>,
- }
- /// Snapshot of a destination Git working tree obtained in ONE `git status` call.
- #[derive(Debug, Clone, Default)]
- pub struct WorkingTreeStatus {
- pub is_clean: bool,
- pub ignored_paths: Vec<String>,
- }
- fn open_gix_repo(dir: &Path) -> Result<gix::Repository> {
- gix::open_opts(dir, gix::open::Options::isolated())
- .map_err(|e| RoneoError::Vcs(format!("Failed to open git repo '{}': {e}", dir.display())))
- }
- /// Returns `true` if `dir` is the root of a git working tree (not merely a subdirectory of one),
- /// evaluated purely in-process via `gix`.
- pub fn is_git_repo(dir: &Path) -> bool {
- if !dir.is_dir() || !dir.join(".git").exists() {
- return false;
- }
- gix::open_opts(dir, gix::open::Options::isolated()).is_ok()
- }
- /// Fast zero-subprocess check for Git bundle files (`# v2 git bundle` / `# v3 git bundle`).
- pub fn is_git_bundle(path: &Path) -> bool {
- let Ok(mut f) = std::fs::File::open(path) else {
- return false;
- };
- let mut header = [0u8; 20];
- let Ok(n) = f.read(&mut header) else {
- return false;
- };
- let slice = &header[..n];
- slice.starts_with(b"# v2 git bundle\n") || slice.starts_with(b"# v3 git bundle\n")
- }
- /// Discover the enclosing Git working tree root for `dir` (supports updating a project that lives
- /// inside a subdirectory of a Git monorepo), evaluated purely in-process via `gix`.
- pub fn find_git_worktree_root(dir: &Path) -> Option<PathBuf> {
- let repo = gix::discover(dir).ok()?;
- repo.workdir().map(Path::to_path_buf)
- }
- /// Returns `true` if the working tree has no staged, unstaged, or untracked changes.
- pub fn is_clean(dir: &Path) -> Result<bool> {
- let status = run_git_checked(Some(dir), &["status", "--porcelain", "--no-renames"])?;
- Ok(status.is_empty())
- }
- /// Check cleanliness AND collect `.gitignore`-ignored paths in ONE NUL-delimited (`-z`)
- /// `git status` invocation (Copier post-v9.19.1 `1b54bbeb`: safe for spaces/quotes/unicode).
- pub fn inspect_working_tree(repo_root: &Path) -> Result<WorkingTreeStatus> {
- let out = run_git(
- Some(repo_root),
- &[
- "status",
- "--ignored=matching",
- "--porcelain",
- "-z",
- "--no-renames",
- ],
- )?;
- if !out.status.success() {
- let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
- return Err(RoneoError::Vcs(format!("`git status` failed: {stderr}")));
- }
- let mut is_clean = true;
- let mut ignored_paths = Vec::new();
- for record in out.stdout.split(|&b| b == 0) {
- if record.is_empty() {
- continue;
- }
- let text = String::from_utf8_lossy(record);
- if let Some(rest) = text.strip_prefix("!! ") {
- if !rest.is_empty() {
- ignored_paths.push(rest.to_string());
- }
- } else {
- is_clean = false;
- }
- }
- Ok(WorkingTreeStatus {
- is_clean,
- ignored_paths,
- })
- }
- /// Read BOTH `describe` (tag/commit) and 40-char `HEAD` hash in a single `gix` repo open.
- pub fn describe_and_hash_head(repo_path: &Path) -> Result<(Option<String>, String)> {
- let repo = open_gix_repo(repo_path)?;
- let commit = repo
- .rev_parse_single("HEAD")
- .map_err(|e| RoneoError::Vcs(format!("Failed to resolve HEAD: {e}")))?
- .object()
- .map_err(|e| RoneoError::Vcs(format!("Failed to read HEAD object: {e}")))?
- .peel_to_commit()
- .map_err(|e| RoneoError::Vcs(format!("HEAD is not a commit: {e}")))?;
- let hash = commit.id.to_string();
- let desc = fast_describe_commit(&repo, &commit).ok();
- Ok((desc, hash))
- }
- pub fn describe_commit(repo: &Path) -> Result<String> {
- describe_ref(repo, "HEAD")
- }
- /// Describe a git ref (`git describe --tags --always <ref>`) in-process via `gix`.
- pub fn describe_ref(repo_path: &Path, git_ref: &str) -> Result<String> {
- let repo = open_gix_repo(repo_path)?;
- let commit = repo
- .rev_parse_single(git_ref)
- .map_err(|e| RoneoError::Vcs(format!("Failed to resolve ref '{git_ref}': {e}")))?
- .object()
- .map_err(|e| RoneoError::Vcs(format!("Failed to read object for '{git_ref}': {e}")))?
- .peel_to_commit()
- .map_err(|e| RoneoError::Vcs(format!("Ref '{git_ref}' is not a commit: {e}")))?;
- fast_describe_commit(&repo, &commit)
- }
- /// Fast `git describe --tags --always` via `gix`:
- /// 1. First checks direct tag matches using `packed-refs` peeled OIDs (zero object decompression,
- /// ~2 ms even on monorepos with 8 000+ tags!).
- /// 2. Falls back to full `commit.describe()` graph walk only if the commit is not directly tagged.
- fn fast_describe_commit(repo: &gix::Repository, commit: &gix::Commit<'_>) -> Result<String> {
- if let Ok(refs) = repo.references()
- && let Ok(tags) = refs.tags()
- {
- let mut exact_matches: Vec<String> = Vec::new();
- for tag_ref in tags.flatten() {
- let matches_peeled = tag_ref.inner().peeled == Some(commit.id);
- let matches_direct = tag_ref.target().try_id() == Some(commit.id.as_ref());
- if matches_peeled || matches_direct {
- exact_matches.push(tag_ref.name().shorten().to_str_lossy().into_owned());
- }
- }
- if !exact_matches.is_empty() {
- exact_matches.sort();
- return Ok(exact_matches.swap_remove(0));
- }
- }
- let formatted = commit
- .describe()
- .names(gix::commit::describe::SelectRef::AllTags)
- .id_as_fallback(true)
- .format()
- .map_err(|e| RoneoError::Vcs(format!("Failed to describe commit: {e}")))?;
- Ok(formatted.to_string())
- }
- pub fn rev_parse_head(repo: &Path) -> Result<String> {
- rev_parse_ref(repo, "HEAD")
- }
- /// Resolve a git ref to its full 40-char commit hex ID in-process via `gix`.
- pub fn rev_parse_ref(repo_path: &Path, git_ref: &str) -> Result<String> {
- let repo = open_gix_repo(repo_path)?;
- let commit = repo
- .rev_parse_single(git_ref)
- .map_err(|e| RoneoError::Vcs(format!("Failed to resolve ref '{git_ref}': {e}")))?
- .object()
- .map_err(|e| RoneoError::Vcs(format!("Failed to read object for '{git_ref}': {e}")))?
- .peel_to_commit()
- .map_err(|e| RoneoError::Vcs(format!("Ref '{git_ref}' is not a commit: {e}")))?;
- Ok(commit.id.to_string())
- }
- /// A blob or symlink entry discovered while walking a `gix::Tree` in memory.
- #[derive(Debug, Clone)]
- pub struct GitTreeFile {
- /// Source path relative to the walked root (`_subdirectory` or repo root).
- pub rel_path: PathBuf,
- /// Already-rendered destination parent directory (computed once per directory, not per file).
- pub rendered_parent: PathBuf,
- /// Raw leaf filename (the only segment left to render for this entry).
- pub file_name: String,
- /// Any `{% yield var from list %}` bindings inherited from parent directories (empty in 99.9% of cases).
- pub extra_vars: Vec<(String, JsonValue)>,
- pub oid: gix::ObjectId,
- pub is_executable: bool,
- pub is_symlink: bool,
- }
- /// Thread-safe, zero-TempDir handle to a specific commit tree inside a local Git repository.
- /// Allows reading `copier.yml`, `!include` files, Jinja `{% include %}` partials, plugin files,
- /// and template blobs directly from Git packfiles in memory.
- pub struct InMemoryGitTree {
- sync_repo: gix::ThreadSafeRepository,
- pub tree_oid: gix::ObjectId,
- pub commit_describe: Option<String>,
- pub commit_hash: String,
- }
- impl std::fmt::Debug for InMemoryGitTree {
- fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- f.debug_struct("InMemoryGitTree")
- .field("commit_describe", &self.commit_describe)
- .field("commit_hash", &self.commit_hash)
- .finish_non_exhaustive()
- }
- }
- impl InMemoryGitTree {
- /// Open a local git repo ONCE via `gix` and resolve `vcs_ref` (or latest PEP 440 tag / `HEAD`).
- pub fn open(repo_path: &Path, vcs_ref: Option<&str>, use_prereleases: bool) -> Result<Self> {
- let repo = open_gix_repo(repo_path)?;
- Self::from_repo(repo, vcs_ref, use_prereleases)
- }
- /// Resolve another ref in the SAME repository without reopening `.git` or reloading pack indices.
- pub fn open_sibling(&self, vcs_ref: Option<&str>, use_prereleases: bool) -> Result<Self> {
- let repo = self.sync_repo.to_thread_local();
- Self::from_repo(repo, vcs_ref, use_prereleases)
- }
- fn from_repo(
- repo: gix::Repository,
- vcs_ref: Option<&str>,
- use_prereleases: bool,
- ) -> Result<Self> {
- let target_ref = match vcs_ref {
- Some(r) => {
- if r.starts_with('-') {
- return Err(RoneoError::Vcs(format!(
- "Invalid git ref '{r}': refs may not start with '-'"
- )));
- }
- r.to_string()
- }
- None => latest_version_tag_in_repo(&repo, use_prereleases)?
- .unwrap_or_else(|| "HEAD".to_string()),
- };
- let commit = repo
- .rev_parse_single(target_ref.as_str())
- .map_err(|e| RoneoError::Vcs(format!("Failed to resolve ref '{target_ref}': {e}")))?
- .object()
- .map_err(|e| RoneoError::Vcs(format!("Failed to read object '{target_ref}': {e}")))?
- .peel_to_commit()
- .map_err(|e| RoneoError::Vcs(format!("Ref '{target_ref}' is not a commit: {e}")))?;
- let commit_hash = commit.id.to_string();
- let commit_describe = fast_describe_commit(&repo, &commit).ok();
- let tree_oid = commit
- .tree_id()
- .map_err(|e| RoneoError::Vcs(format!("Failed to get commit tree id: {e}")))?
- .detach();
- drop(commit);
- Ok(Self {
- sync_repo: repo.into_sync(),
- tree_oid,
- commit_describe,
- commit_hash,
- })
- }
- /// Obtain a thread-local `gix::Repository` handle (reusable across many blob reads on one thread).
- pub fn thread_local_repo(&self) -> gix::Repository {
- self.sync_repo.to_thread_local()
- }
- /// Read raw bytes of a blob using an already-acquired thread-local `gix::Repository`.
- pub fn read_blob_with_repo(repo: &gix::Repository, oid: gix::ObjectId) -> Result<Vec<u8>> {
- let obj = repo
- .find_object(oid)
- .map_err(|e| RoneoError::Vcs(format!("Failed reading blob {oid}: {e}")))?;
- Ok(obj.data.clone())
- }
- /// Read a blob by relative path from the repo root directly in memory.
- pub fn read_bytes(&self, rel_path: &str) -> Option<Vec<u8>> {
- let repo = self.sync_repo.to_thread_local();
- let tree = repo.find_object(self.tree_oid).ok()?.into_tree();
- let entry = tree.lookup_entry_by_path(rel_path).ok()??;
- let obj = entry.object().ok()?;
- (obj.kind == gix::object::Kind::Blob).then(|| obj.data.clone())
- }
- /// Read a UTF-8 file by relative path from the repo root directly in memory.
- pub fn read_string(&self, rel_path: &str) -> Option<String> {
- String::from_utf8(self.read_bytes(rel_path)?).ok()
- }
- /// Read raw bytes of a blob by its `ObjectId` (used on parallel worker threads).
- pub fn read_blob_oid(&self, oid: gix::ObjectId) -> Result<Vec<u8>> {
- let repo = self.sync_repo.to_thread_local();
- let obj = repo
- .find_object(oid)
- .map_err(|e| RoneoError::Vcs(format!("Failed reading blob {oid}: {e}")))?;
- Ok(obj.data.clone())
- }
- /// List all relative file paths in the commit tree matching a glob pattern (e.g. `questions/*.yml`),
- /// pruning non-matching leading literal directory prefixes automatically.
- pub fn list_matching_files(&self, pattern: &str) -> Vec<String> {
- let repo = self.sync_repo.to_thread_local();
- let Ok(root_obj) = repo.find_object(self.tree_oid) else {
- return Vec::new();
- };
- let root_tree = root_obj.into_tree();
- // Narrow the walk to the longest static directory prefix before any wildcard.
- let mut static_prefix = PathBuf::new();
- for seg in pattern.trim_start_matches('/').split('/') {
- if seg.contains(['*', '?', '[']) || seg.is_empty() {
- break;
- }
- static_prefix.push(seg);
- }
- let (start_tree, base_prefix) = if static_prefix.as_os_str().is_empty() {
- (root_tree, PathBuf::new())
- } else if let Ok(Some(entry)) = root_tree.lookup_entry_by_path(&static_prefix)
- && entry.mode().kind() == EntryKind::Tree
- && let Ok(obj) = entry.object()
- {
- (obj.into_tree(), static_prefix)
- } else {
- return Vec::new();
- };
- let mut matches = Vec::new();
- collect_matching_in_tree(&repo, &start_tree, &base_prefix, pattern, &mut matches);
- matches.sort();
- matches
- }
- /// Walk `subdir` (or root tree) in memory, invoking `enter_dir` once per directory to prune
- /// excluded subtrees BEFORE touching their entries or decompressing any blobs, and expanding
- /// `{% yield %}` directories into multiple `(rendered_dir, extra_vars)` branches.
- pub fn walk_files<F>(&self, subdir: Option<&str>, mut enter_dir: F) -> Result<Vec<GitTreeFile>>
- where
- F: FnMut(
- &Path,
- &Path,
- &str,
- &[(String, JsonValue)],
- ) -> Result<Vec<(PathBuf, Vec<(String, JsonValue)>)>>,
- {
- let repo = self.sync_repo.to_thread_local();
- let root_tree = repo
- .find_object(self.tree_oid)
- .map_err(|e| RoneoError::Vcs(format!("Failed to load root tree: {e}")))?
- .into_tree();
- let start_tree = match subdir.filter(|s| !s.trim().is_empty()) {
- Some(sub) => {
- let entry = root_tree
- .lookup_entry_by_path(sub)
- .map_err(|e| RoneoError::Vcs(format!("Failed looking up '{sub}': {e}")))?
- .ok_or_else(|| {
- RoneoError::TemplateSource(format!(
- "Template subdirectory '{sub}' does not exist in git tree"
- ))
- })?;
- if entry.mode().kind() != EntryKind::Tree {
- return Err(RoneoError::TemplateSource(format!(
- "Template subdirectory '{sub}' is not a directory"
- )));
- }
- entry
- .object()
- .map_err(|e| RoneoError::Vcs(format!("Failed reading tree '{sub}': {e}")))?
- .into_tree()
- }
- None => root_tree,
- };
- let mut files = Vec::new();
- walk_tree_in_memory(
- &repo,
- &start_tree,
- Path::new(""),
- Path::new(""),
- &[],
- &mut enter_dir,
- &mut files,
- )?;
- files.sort_by(|a, b| {
- a.rendered_parent
- .cmp(&b.rendered_parent)
- .then_with(|| a.rel_path.cmp(&b.rel_path))
- });
- Ok(files)
- }
- }
- fn collect_matching_in_tree(
- repo: &gix::Repository,
- tree: &gix::Tree<'_>,
- prefix: &Path,
- pattern: &str,
- out: &mut Vec<String>,
- ) {
- for entry_res in tree.iter() {
- let Ok(entry) = entry_res else {
- continue;
- };
- let name = entry.filename().to_str_lossy();
- let rel = if prefix.as_os_str().is_empty() {
- PathBuf::from(name.as_ref())
- } else {
- prefix.join(name.as_ref())
- };
- match entry.mode().kind() {
- EntryKind::Tree => {
- if let Ok(obj) = repo.find_object(entry.id().detach()) {
- collect_matching_in_tree(repo, &obj.into_tree(), &rel, pattern, out);
- }
- }
- EntryKind::Blob | EntryKind::BlobExecutable => {
- if match_glob_path(pattern, &rel) {
- out.push(rel.to_string_lossy().replace('\\', "/"));
- }
- }
- EntryKind::Link | EntryKind::Commit => {}
- }
- }
- }
- fn walk_tree_in_memory<F>(
- repo: &gix::Repository,
- tree: &gix::Tree<'_>,
- src_prefix: &Path,
- rendered_prefix: &Path,
- extra_vars: &[(String, JsonValue)],
- enter_dir: &mut F,
- out: &mut Vec<GitTreeFile>,
- ) -> Result<()>
- where
- F: FnMut(
- &Path,
- &Path,
- &str,
- &[(String, JsonValue)],
- ) -> Result<Vec<(PathBuf, Vec<(String, JsonValue)>)>>,
- {
- for entry_res in tree.iter() {
- let entry =
- entry_res.map_err(|e| RoneoError::Vcs(format!("Failed iterating git tree: {e}")))?;
- let name = entry.filename().to_str_lossy();
- let rel = if src_prefix.as_os_str().is_empty() {
- PathBuf::from(name.as_ref())
- } else {
- src_prefix.join(name.as_ref())
- };
- match entry.mode().kind() {
- EntryKind::Tree => {
- let branches = enter_dir(&rel, rendered_prefix, name.as_ref(), extra_vars)?;
- if branches.is_empty() {
- continue;
- }
- let sub = repo
- .find_object(entry.id().detach())
- .map_err(|e| RoneoError::Vcs(format!("Failed reading subtree: {e}")))?
- .into_tree();
- for (next_rendered, next_vars) in branches {
- walk_tree_in_memory(
- repo,
- &sub,
- &rel,
- &next_rendered,
- &next_vars,
- enter_dir,
- out,
- )?;
- }
- }
- EntryKind::Blob => {
- out.push(GitTreeFile {
- rel_path: rel,
- rendered_parent: rendered_prefix.to_path_buf(),
- file_name: name.into_owned(),
- extra_vars: extra_vars.to_vec(),
- oid: entry.id().detach(),
- is_executable: false,
- is_symlink: false,
- });
- }
- EntryKind::BlobExecutable => {
- out.push(GitTreeFile {
- rel_path: rel,
- rendered_parent: rendered_prefix.to_path_buf(),
- file_name: name.into_owned(),
- extra_vars: extra_vars.to_vec(),
- oid: entry.id().detach(),
- is_executable: true,
- is_symlink: false,
- });
- }
- EntryKind::Link => {
- out.push(GitTreeFile {
- rel_path: rel,
- rendered_parent: rendered_prefix.to_path_buf(),
- file_name: name.into_owned(),
- extra_vars: extra_vars.to_vec(),
- oid: entry.id().detach(),
- is_executable: false,
- is_symlink: true,
- });
- }
- EntryKind::Commit => {}
- }
- }
- Ok(())
- }
- fn latest_version_tag_in_repo(
- repo: &gix::Repository,
- use_prereleases: bool,
- ) -> Result<Option<String>> {
- let refs = repo
- .references()
- .map_err(|e| RoneoError::Vcs(format!("Failed to list references: {e}")))?;
- let tags = refs
- .tags()
- .map_err(|e| RoneoError::Vcs(format!("Failed to list tags: {e}")))?;
- let mut all_parsed: Vec<(Pep440Version, String)> = Vec::new();
- for tag_ref in tags.flatten() {
- let short = tag_ref.name().shorten().to_str_lossy();
- if let Some(ver) = Pep440Version::parse(&short) {
- all_parsed.push((ver, short.into_owned()));
- }
- }
- if !use_prereleases {
- let mut stable: Vec<(Pep440Version, String)> = all_parsed
- .iter()
- .filter(|(v, _)| !v.is_prerelease())
- .cloned()
- .collect();
- if !stable.is_empty() {
- stable.sort_by(|a, b| a.0.cmp(&b.0));
- return Ok(stable.pop().map(|(_, tag)| tag));
- }
- }
- all_parsed.sort_by(|a, b| a.0.cmp(&b.0));
- Ok(all_parsed.pop().map(|(_, tag)| tag))
- }
- /// Return the highest PEP 440 tag in `repo`, evaluated purely in-process via `gix`.
- pub fn latest_version_tag(repo_path: &Path, use_prereleases: bool) -> Result<Option<String>> {
- let repo = open_gix_repo(repo_path)?;
- latest_version_tag_in_repo(&repo, use_prereleases)
- }
- // ---------------------------------------------------------------------------
- // Git CLI helpers for remote cloning & 3-way merge patching (`update` / `diff`)
- // ---------------------------------------------------------------------------
- fn run_git(cwd: Option<&Path>, args: &[&str]) -> Result<std::process::Output> {
- let mut cmd = Command::new("git");
- if let Some(dir) = cwd {
- cmd.current_dir(dir);
- }
- cmd.env("GIT_TERMINAL_PROMPT", "0");
- cmd.args(args);
- cmd.output()
- .map_err(|e| RoneoError::Vcs(format!("Failed to execute `git {}`: {e}", args.join(" "))))
- }
- fn run_git_checked(cwd: Option<&Path>, args: &[&str]) -> Result<String> {
- let out = run_git(cwd, args)?;
- if !out.status.success() {
- let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
- return Err(RoneoError::Vcs(format!(
- "`git {}` failed: {stderr}",
- args.join(" ")
- )));
- }
- Ok(String::from_utf8_lossy(&out.stdout).trim().to_string())
- }
- pub fn clone_repo(src: &str, dst: &Path) -> Result<()> {
- let dst_str = dst
- .to_str()
- .ok_or_else(|| RoneoError::Vcs("Non-UTF-8 temporary path".into()))?;
- let no_hooks = format!("core.hooksPath={}", null_device_path());
- run_git_checked(
- None,
- &["-c", &no_hooks, "clone", "--quiet", "--", src, dst_str],
- )?;
- if dst.join(".gitmodules").is_file() {
- let _ = run_git_checked(
- Some(dst),
- &[
- "-c",
- &no_hooks,
- "submodule",
- "update",
- "--init",
- "--recursive",
- "--quiet",
- ],
- );
- }
- Ok(())
- }
- /// Clone a remote repository using a persistent local bare mirror cache (`~/.cache/roneo/repos/<hash>`,
- /// matching Copier v9.16.0 `#2720`). Falls back to a direct clone if caching is disabled via
- /// `RONEO_NO_CACHE=1` or unavailable.
- pub fn clone_repo_cached(src: &str, dst: &Path) -> Result<()> {
- if std::env::var_os("RONEO_NO_CACHE").is_some_and(|v| v == "1" || v == "true") {
- return clone_repo(src, dst);
- }
- let Some(cache_root) = remote_mirror_cache_dir() else {
- return clone_repo(src, dst);
- };
- if std::fs::create_dir_all(&cache_root).is_err() {
- return clone_repo(src, dst);
- }
- let cache_key = strip_url_credentials(src);
- let mirror_dir = cache_root.join(format!("{:016x}.git", fnv1a_64(cache_key.as_bytes())));
- let mirror_str = mirror_dir.to_string_lossy().into_owned();
- let no_hooks = format!("core.hooksPath={}", null_device_path());
- let mirror_ready = if mirror_dir.join("HEAD").is_file() {
- run_git_checked(
- Some(&mirror_dir),
- &[
- "-c", &no_hooks, "fetch", "--prune", "--tags", "--quiet", "origin",
- ],
- )
- .is_ok()
- } else {
- if mirror_dir.exists() {
- let _ = std::fs::remove_dir_all(&mirror_dir);
- }
- let ok = run_git_checked(
- None,
- &[
- "-c",
- &no_hooks,
- "clone",
- "--mirror",
- "--quiet",
- "--",
- src,
- &mirror_str,
- ],
- )
- .is_ok();
- if !ok {
- let _ = std::fs::remove_dir_all(&mirror_dir);
- }
- ok
- };
- if mirror_ready {
- let dst_str = dst
- .to_str()
- .ok_or_else(|| RoneoError::Vcs("Non-UTF-8 temporary path".into()))?;
- if run_git_checked(
- None,
- &[
- "-c",
- &no_hooks,
- "clone",
- "--shared",
- "--quiet",
- "--",
- &mirror_str,
- dst_str,
- ],
- )
- .is_ok()
- {
- if dst.join(".gitmodules").is_file() {
- let _ = run_git_checked(
- Some(dst),
- &[
- "-c",
- &no_hooks,
- "submodule",
- "update",
- "--init",
- "--recursive",
- "--quiet",
- ],
- );
- }
- return Ok(());
- }
- }
- clone_repo(src, dst)
- }
- fn remote_mirror_cache_dir() -> Option<PathBuf> {
- if let Ok(custom) = std::env::var("RONEO_CACHE_DIR")
- && !custom.trim().is_empty()
- {
- return Some(PathBuf::from(custom).join("repos"));
- }
- if let Ok(xdg) = std::env::var("XDG_CACHE_HOME")
- && !xdg.trim().is_empty()
- {
- return Some(PathBuf::from(xdg).join("roneo/repos"));
- }
- let home = std::env::var("HOME")
- .or_else(|_| std::env::var("USERPROFILE"))
- .ok()?;
- Some(PathBuf::from(home).join(".cache/roneo/repos"))
- }
- /// Remove embedded `user:pass@` credentials from an HTTP(S)/SSH URL before hashing it for
- /// the local bare mirror cache key (matches Copier v9.16 `_strip_credentials`).
- fn strip_url_credentials(url: &str) -> std::borrow::Cow<'_, str> {
- let Some(scheme_end) = url.find("://") else {
- return std::borrow::Cow::Borrowed(url);
- };
- let rest = &url[scheme_end + 3..];
- let authority_end = rest.find(['/', '?', '#']).unwrap_or(rest.len());
- let authority = &rest[..authority_end];
- let Some(at_pos) = authority.rfind('@') else {
- return std::borrow::Cow::Borrowed(url);
- };
- let mut cleaned = String::with_capacity(url.len() - at_pos - 1);
- cleaned.push_str(&url[..scheme_end + 3]);
- cleaned.push_str(&rest[at_pos + 1..]);
- std::borrow::Cow::Owned(cleaned)
- }
- fn fnv1a_64(bytes: &[u8]) -> u64 {
- let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
- for &b in bytes {
- hash ^= u64::from(b);
- hash = hash.wrapping_mul(0x0100_0000_01b3);
- }
- hash
- }
- pub fn checkout_ref(repo: &Path, git_ref: &str) -> Result<()> {
- if git_ref.starts_with('-') {
- return Err(RoneoError::Vcs(format!(
- "Invalid git ref '{git_ref}': refs may not start with '-'"
- )));
- }
- let no_hooks = format!("core.hooksPath={}", null_device_path());
- run_git_checked(
- Some(repo),
- &[
- "-c", &no_hooks, "checkout", "--quiet", "--detach", git_ref, "--",
- ],
- )?;
- if repo.join(".gitmodules").is_file() {
- let _ = run_git_checked(
- Some(repo),
- &[
- "-c",
- &no_hooks,
- "submodule",
- "update",
- "--init",
- "--recursive",
- "--force",
- "--quiet",
- ],
- );
- }
- Ok(())
- }
- /// Produce a binary unified diff between sibling directories `old_name` (`a`) and `new_name` (`b`)
- /// inside `parent_dir` in ONE `git diff --no-index` call — zero `git init`, zero `git add`,
- /// zero `git commit`, zero working-tree copy/delete.
- pub fn diff_directories(
- parent_dir: &Path,
- old_name: &str,
- new_name: &str,
- context_lines: usize,
- ) -> Result<Vec<u8>> {
- let unified = format!("--unified={context_lines}");
- let out = run_git(
- Some(parent_dir),
- &[
- "diff",
- "--no-index",
- "--no-prefix",
- "--no-renames",
- "--binary",
- "--full-index",
- "--no-ext-diff",
- "--no-color",
- &unified,
- "--",
- old_name,
- new_name,
- ],
- )?;
- // `git diff --no-index` exits 0 (no changes), 1 (changes found), or >1 (error).
- if matches!(out.status.code(), Some(0 | 1)) {
- Ok(out.stdout)
- } else {
- let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
- Err(RoneoError::Vcs(format!(
- "`git diff --no-index` failed: {stderr}"
- )))
- }
- }
- /// Apply a binary unified diff patch to `repo_root` (optionally scoped to `subproject_subdir`
- /// when updating a project nested inside a Git monorepo) using 3-way merge (`--3way`) or `--reject`.
- ///
- /// When `mode == ConflictMode::Inline` and `git apply --3way` cannot locate base blobs in the
- /// destination ODB (e.g., after a squash merge, rebase, or fresh `git init`), automatically falls
- /// back to Copier's `git apply --reject` + `git merge-file` using `merge_snapshots` (`old_dir`, `new_dir`).
- pub fn apply_patch(
- repo_root: &Path,
- subproject_subdir: Option<&Path>,
- patch: &[u8],
- mode: ConflictMode,
- exclude_paths: &[String],
- merge_snapshots: Option<(&Path, &Path)>,
- ) -> Result<ApplyResult> {
- if patch.is_empty() {
- return Ok(ApplyResult {
- has_conflicts: false,
- stderr: String::new(),
- conflicted_files: Vec::new(),
- });
- }
- let flag = match mode {
- ConflictMode::Inline => "--3way",
- ConflictMode::Rej => "--reject",
- };
- let out = run_git_apply(repo_root, subproject_subdir, patch, flag, exclude_paths)?;
- let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
- if out.status.success() {
- return Ok(ApplyResult {
- has_conflicts: false,
- stderr,
- conflicted_files: Vec::new(),
- });
- }
- let strip_subdir = |repo_rel: &str| -> String {
- if let Some(sub) = subproject_subdir
- && !sub.as_os_str().is_empty()
- {
- let prefix = format!("{}/", sub.to_string_lossy().replace('\\', "/"));
- repo_rel
- .strip_prefix(&prefix)
- .unwrap_or(repo_rel)
- .to_string()
- } else {
- repo_rel.to_string()
- }
- };
- if mode == ConflictMode::Inline {
- let mut conflicted_files: Vec<String> =
- run_git_checked(Some(repo_root), &["diff", "--name-only", "--diff-filter=U"])
- .unwrap_or_default()
- .lines()
- .filter(|l| !l.trim().is_empty())
- .map(&strip_subdir)
- .collect();
- // Squash / missing-ODB fallback: `git apply --3way` failed without producing index
- // conflicts (e.g. `sha1 information is lacking or useless`). Run `git apply --reject`
- // followed by `git merge-file` directly against `(old_dir, new_dir)` snapshots (Copier).
- if conflicted_files.is_empty()
- && let Some((old_dir, new_dir)) = merge_snapshots
- {
- let rej_out = run_git_apply(
- repo_root,
- subproject_subdir,
- patch,
- "--reject",
- exclude_paths,
- )?;
- let rej_stderr = String::from_utf8_lossy(&rej_out.stderr).trim().to_string();
- let status_out = run_git(
- Some(repo_root),
- &[
- "status",
- "--porcelain",
- "-z",
- "--untracked-files=all",
- "--ignored=matching",
- "--no-renames",
- ],
- )?;
- for record in status_out.stdout.split(|&b| b == 0) {
- if record.is_empty() {
- continue;
- }
- let text = String::from_utf8_lossy(record);
- // Match both untracked (`?? `) and gitignored (`!! `) `.rej` files (Copier v9.15.2 `#2668`).
- let raw_path = text
- .strip_prefix("?? ")
- .or_else(|| text.strip_prefix("!! "));
- let Some(path_str) = raw_path else {
- continue;
- };
- let Some(repo_rel_file) = path_str.strip_suffix(".rej") else {
- continue;
- };
- let rej_abs = repo_root.join(path_str);
- let _ = std::fs::remove_file(&rej_abs);
- let sub_rel = strip_subdir(repo_rel_file);
- let dst_abs = repo_root.join(repo_rel_file);
- let old_abs = old_dir.join(&sub_rel);
- let new_abs = new_dir.join(&sub_rel);
- if old_abs.is_file() && new_abs.is_file() && dst_abs.is_file() {
- // Undo any partial hunks before performing a clean 3-way `git merge-file`.
- let null_hooks = format!("core.hooksPath={}", null_device_path());
- let _ = run_git(
- Some(repo_root),
- &["-c", &null_hooks, "checkout", "--", repo_rel_file],
- );
- let merge_out = run_git(
- Some(repo_root),
- &[
- "merge-file",
- "-L",
- "before updating",
- "-L",
- "last update",
- "-L",
- "after updating",
- "--",
- &dst_abs.to_string_lossy(),
- &old_abs.to_string_lossy(),
- &new_abs.to_string_lossy(),
- ],
- )?;
- if !merge_out.status.success() {
- conflicted_files.push(sub_rel);
- }
- } else {
- conflicted_files.push(sub_rel);
- }
- }
- return Ok(ApplyResult {
- has_conflicts: !conflicted_files.is_empty(),
- stderr: if conflicted_files.is_empty() {
- String::new()
- } else {
- rej_stderr
- },
- conflicted_files,
- });
- }
- return Ok(ApplyResult {
- has_conflicts: true,
- stderr,
- conflicted_files,
- });
- }
- let conflicted_files = stderr
- .lines()
- .filter_map(|line| {
- line.strip_prefix("Applying patch ")
- .and_then(|rest| rest.split(" with ").next())
- .map(ToOwned::to_owned)
- })
- .collect();
- Ok(ApplyResult {
- has_conflicts: true,
- stderr,
- conflicted_files,
- })
- }
- fn run_git_apply(
- repo_root: &Path,
- subproject_subdir: Option<&Path>,
- patch: &[u8],
- flag: &str,
- exclude_paths: &[String],
- ) -> Result<std::process::Output> {
- let mut args: Vec<String> = vec!["apply".into(), flag.into(), "--whitespace=nowarn".into()];
- if let Some(sub) = subproject_subdir
- && !sub.as_os_str().is_empty()
- {
- args.push(format!(
- "--directory={}",
- sub.to_string_lossy().replace('\\', "/")
- ));
- }
- for pat in exclude_paths {
- args.push("--exclude".into());
- args.push(pat.clone());
- }
- args.push("-".into());
- let mut child = Command::new("git")
- .current_dir(repo_root)
- .args(&args)
- .stdin(Stdio::piped())
- .stdout(Stdio::piped())
- .stderr(Stdio::piped())
- .spawn()
- .map_err(|e| RoneoError::Vcs(format!("Failed to spawn `git apply`: {e}")))?;
- if let Some(mut stdin) = child.stdin.take() {
- stdin
- .write_all(patch)
- .map_err(|e| RoneoError::Vcs(format!("Failed to write patch to `git apply`: {e}")))?;
- }
- child
- .wait_with_output()
- .map_err(|e| RoneoError::Vcs(format!("Failed waiting for `git apply`: {e}")))
- }
- #[cfg(unix)]
- fn null_device_path() -> &'static str {
- "/dev/null"
- }
- #[cfg(windows)]
- fn null_device_path() -> &'static str {
- "NUL"
- }
- #[cfg(test)]
- mod tests {
- use super::strip_url_credentials;
- #[test]
- fn strip_url_credentials_keeps_host_and_path() {
- assert_eq!(
- strip_url_credentials("https://user:secret@github.com/org/repo.git"),
- "https://github.com/org/repo.git"
- );
- assert_eq!(
- strip_url_credentials("https://github.com/org/repo.git"),
- "https://github.com/org/repo.git"
- );
- assert_eq!(
- strip_url_credentials("git@github.com:org/repo.git"),
- "git@github.com:org/repo.git"
- );
- }
- }