Rinomina: crate akode-*, cartelle akode-rs/ e akode-cli/, binario akode, ~/.akode, AKODE_* (A)
Riapplica la fase 5 di aKode (86e7c72e) sulla base ripulita:
- crate codex-* -> akode-*, codex-rs -> akode-rs, codex-cli -> akode-cli, binario e ausiliari akode;
- ~/.codex -> ~/.akode, CODEX_HOME -> AKODE_HOME, variabili CODEX_* -> AKODE_*, .codex/ -> .akode/ di progetto;
nessun fallback a ~/.codex o a CODEX_*;
- testi per l'utente "Codex" -> "aKode"; testi verso il modello e istruzioni di sistema invariati;
- snapshot insta rinominati (non ancora rigenerati).
I conflitti con la base ripulita sono stati risolti riapplicando la rinomina ai file senza le
funzioni di imeAI (script di mappa dei token per file).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
855
akode-rs/git-utils/src/apply.rs
Normal file
855
akode-rs/git-utils/src/apply.rs
Normal file
@@ -0,0 +1,855 @@
|
||||
//! Helpers for applying unified diffs using the system `git` binary.
|
||||
//!
|
||||
//! The entry point is [`apply_git_patch`], which writes a diff to a temporary
|
||||
//! file, shells out to `git apply` with the right flags, and then parses the
|
||||
//! command’s output into structured details. Callers can opt into dry-run
|
||||
//! mode via [`ApplyGitRequest::preflight`] and inspect the resulting paths to
|
||||
//! learn what would change before applying for real.
|
||||
|
||||
use akode_protocol::shell_environment::scrub_non_inheritable_env_vars;
|
||||
use once_cell::sync::Lazy;
|
||||
use regex::Regex;
|
||||
use std::ffi::OsStr;
|
||||
use std::io;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Parameters for invoking [`apply_git_patch`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ApplyGitRequest {
|
||||
pub cwd: PathBuf,
|
||||
pub diff: String,
|
||||
pub revert: bool,
|
||||
pub preflight: bool,
|
||||
}
|
||||
|
||||
/// Result of running [`apply_git_patch`], including paths gleaned from stdout/stderr.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ApplyGitResult {
|
||||
pub exit_code: i32,
|
||||
pub applied_paths: Vec<String>,
|
||||
pub skipped_paths: Vec<String>,
|
||||
pub conflicted_paths: Vec<String>,
|
||||
pub stdout: String,
|
||||
pub stderr: String,
|
||||
pub cmd_for_log: String,
|
||||
}
|
||||
|
||||
/// Apply a unified diff to the target repository by shelling out to `git apply`.
|
||||
///
|
||||
/// When [`ApplyGitRequest::preflight`] is `true`, this behaves like `git apply --check` and
|
||||
/// leaves the working tree untouched while still parsing the command output for diagnostics.
|
||||
pub fn apply_git_patch(req: &ApplyGitRequest) -> io::Result<ApplyGitResult> {
|
||||
let git_root = resolve_git_root(&req.cwd)?;
|
||||
|
||||
// Write unified diff into a temporary file
|
||||
let (tmpdir, patch_path) = write_temp_patch(&req.diff)?;
|
||||
// Keep tmpdir alive until function end to ensure the file exists
|
||||
let _guard = tmpdir;
|
||||
|
||||
if req.revert && !req.preflight {
|
||||
// Stage WT paths first to avoid index mismatch on revert.
|
||||
stage_paths(&git_root, &req.diff)?;
|
||||
}
|
||||
|
||||
// Build git args
|
||||
let mut args: Vec<String> = vec!["apply".into(), "--3way".into()];
|
||||
if req.revert {
|
||||
args.push("-R".into());
|
||||
}
|
||||
|
||||
// Optional: additional git config via env knob (defaults OFF)
|
||||
let mut cfg_parts: Vec<String> = Vec::new();
|
||||
if let Ok(cfg) = std::env::var("AKODE_APPLY_GIT_CFG") {
|
||||
for pair in cfg.split(',') {
|
||||
let p = pair.trim();
|
||||
if p.is_empty() || !p.contains('=') {
|
||||
continue;
|
||||
}
|
||||
cfg_parts.push("-c".into());
|
||||
cfg_parts.push(p.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
args.push(patch_path.to_string_lossy().to_string());
|
||||
|
||||
// Optional preflight: dry-run only; do not modify working tree
|
||||
if req.preflight {
|
||||
let mut check_args = vec!["apply".to_string(), "--check".to_string()];
|
||||
if req.revert {
|
||||
check_args.push("-R".to_string());
|
||||
}
|
||||
check_args.push(patch_path.to_string_lossy().to_string());
|
||||
let rendered = render_command_for_log(&git_root, &cfg_parts, &check_args);
|
||||
let (c_code, c_out, c_err) = run_git(&git_root, &cfg_parts, &check_args)?;
|
||||
let (mut applied_paths, mut skipped_paths, mut conflicted_paths) =
|
||||
parse_git_apply_output(&c_out, &c_err);
|
||||
applied_paths.sort();
|
||||
applied_paths.dedup();
|
||||
skipped_paths.sort();
|
||||
skipped_paths.dedup();
|
||||
conflicted_paths.sort();
|
||||
conflicted_paths.dedup();
|
||||
return Ok(ApplyGitResult {
|
||||
exit_code: c_code,
|
||||
applied_paths,
|
||||
skipped_paths,
|
||||
conflicted_paths,
|
||||
stdout: c_out,
|
||||
stderr: c_err,
|
||||
cmd_for_log: rendered,
|
||||
});
|
||||
}
|
||||
|
||||
let cmd_for_log = render_command_for_log(&git_root, &cfg_parts, &args);
|
||||
let (code, stdout, stderr) = run_git(&git_root, &cfg_parts, &args)?;
|
||||
|
||||
let (mut applied_paths, mut skipped_paths, mut conflicted_paths) =
|
||||
parse_git_apply_output(&stdout, &stderr);
|
||||
applied_paths.sort();
|
||||
applied_paths.dedup();
|
||||
skipped_paths.sort();
|
||||
skipped_paths.dedup();
|
||||
conflicted_paths.sort();
|
||||
conflicted_paths.dedup();
|
||||
|
||||
Ok(ApplyGitResult {
|
||||
exit_code: code,
|
||||
applied_paths,
|
||||
skipped_paths,
|
||||
conflicted_paths,
|
||||
stdout,
|
||||
stderr,
|
||||
cmd_for_log,
|
||||
})
|
||||
}
|
||||
|
||||
fn resolve_git_root(cwd: &Path) -> io::Result<PathBuf> {
|
||||
let mut command = std::process::Command::new("git");
|
||||
command
|
||||
.args(["-c", crate::SAFE_BARE_REPOSITORY_CONFIG])
|
||||
.arg("rev-parse")
|
||||
.arg("--show-toplevel")
|
||||
.current_dir(cwd);
|
||||
scrub_non_inheritable_env_vars(&mut command);
|
||||
let out = command.output()?;
|
||||
let code = out.status.code().unwrap_or(-1);
|
||||
if code != 0 {
|
||||
return Err(io::Error::other(format!(
|
||||
"not a git repository (exit {}): {}",
|
||||
code,
|
||||
String::from_utf8_lossy(&out.stderr)
|
||||
)));
|
||||
}
|
||||
let root = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
Ok(PathBuf::from(root))
|
||||
}
|
||||
|
||||
fn write_temp_patch(diff: &str) -> io::Result<(tempfile::TempDir, PathBuf)> {
|
||||
let dir = tempfile::tempdir()?;
|
||||
let path = dir.path().join("patch.diff");
|
||||
std::fs::write(&path, diff)?;
|
||||
Ok((dir, path))
|
||||
}
|
||||
|
||||
fn run_git(cwd: &Path, git_cfg: &[String], args: &[String]) -> io::Result<(i32, String, String)> {
|
||||
let mut cmd = std::process::Command::new("git");
|
||||
for p in git_cfg {
|
||||
cmd.arg(p);
|
||||
}
|
||||
cmd.args(["-c", crate::SAFE_BARE_REPOSITORY_CONFIG]);
|
||||
for a in args {
|
||||
cmd.arg(a);
|
||||
}
|
||||
scrub_non_inheritable_env_vars(&mut cmd);
|
||||
let out = cmd.current_dir(cwd).output()?;
|
||||
let code = out.status.code().unwrap_or(-1);
|
||||
let stdout = String::from_utf8_lossy(&out.stdout).into_owned();
|
||||
let stderr = String::from_utf8_lossy(&out.stderr).into_owned();
|
||||
Ok((code, stdout, stderr))
|
||||
}
|
||||
|
||||
fn quote_shell(s: &str) -> String {
|
||||
let simple = s
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_alphanumeric() || "-_.:/@%+".contains(c));
|
||||
if simple {
|
||||
s.to_string()
|
||||
} else {
|
||||
format!("'{}'", s.replace('\'', "'\\''"))
|
||||
}
|
||||
}
|
||||
|
||||
fn render_command_for_log(cwd: &Path, git_cfg: &[String], args: &[String]) -> String {
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
parts.push("git".to_string());
|
||||
for a in git_cfg {
|
||||
parts.push(quote_shell(a));
|
||||
}
|
||||
for a in args {
|
||||
parts.push(quote_shell(a));
|
||||
}
|
||||
format!(
|
||||
"(cd {} && {})",
|
||||
quote_shell(&cwd.display().to_string()),
|
||||
parts.join(" ")
|
||||
)
|
||||
}
|
||||
|
||||
/// Collect every path referenced by the diff headers inside `diff --git` sections.
|
||||
pub fn extract_paths_from_patch(diff_text: &str) -> Vec<String> {
|
||||
let mut set = std::collections::BTreeSet::new();
|
||||
for raw_line in diff_text.lines() {
|
||||
let line = raw_line.trim();
|
||||
let Some(rest) = line.strip_prefix("diff --git ") else {
|
||||
continue;
|
||||
};
|
||||
let Some((a, b)) = parse_diff_git_paths(rest) else {
|
||||
continue;
|
||||
};
|
||||
if let Some(a) = normalize_diff_path(&a, "a/") {
|
||||
set.insert(a);
|
||||
}
|
||||
if let Some(b) = normalize_diff_path(&b, "b/") {
|
||||
set.insert(b);
|
||||
}
|
||||
}
|
||||
set.into_iter().collect()
|
||||
}
|
||||
|
||||
fn parse_diff_git_paths(line: &str) -> Option<(String, String)> {
|
||||
let mut chars = line.chars().peekable();
|
||||
let first = read_diff_git_token(&mut chars)?;
|
||||
let second = read_diff_git_token(&mut chars)?;
|
||||
Some((first, second))
|
||||
}
|
||||
|
||||
fn read_diff_git_token(chars: &mut std::iter::Peekable<std::str::Chars<'_>>) -> Option<String> {
|
||||
while matches!(chars.peek(), Some(c) if c.is_whitespace()) {
|
||||
chars.next();
|
||||
}
|
||||
let quote = match chars.peek().copied() {
|
||||
Some('"') | Some('\'') => chars.next(),
|
||||
_ => None,
|
||||
};
|
||||
let mut out = String::new();
|
||||
while let Some(c) = chars.next() {
|
||||
if let Some(q) = quote {
|
||||
if c == q {
|
||||
break;
|
||||
}
|
||||
if c == '\\' {
|
||||
out.push('\\');
|
||||
if let Some(next) = chars.next() {
|
||||
out.push(next);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
} else if c.is_whitespace() {
|
||||
break;
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
if out.is_empty() && quote.is_none() {
|
||||
None
|
||||
} else {
|
||||
Some(match quote {
|
||||
Some(_) => unescape_c_string(&out),
|
||||
None => out,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_diff_path(raw: &str, prefix: &str) -> Option<String> {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if trimmed == "/dev/null" || trimmed == format!("{prefix}dev/null") {
|
||||
return None;
|
||||
}
|
||||
let trimmed = trimmed.strip_prefix(prefix).unwrap_or(trimmed);
|
||||
if trimmed.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(trimmed.to_string())
|
||||
}
|
||||
|
||||
fn unescape_c_string(input: &str) -> String {
|
||||
let mut out = String::with_capacity(input.len());
|
||||
let mut chars = input.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
if c != '\\' {
|
||||
out.push(c);
|
||||
continue;
|
||||
}
|
||||
let Some(next) = chars.next() else {
|
||||
out.push('\\');
|
||||
break;
|
||||
};
|
||||
match next {
|
||||
'n' => out.push('\n'),
|
||||
'r' => out.push('\r'),
|
||||
't' => out.push('\t'),
|
||||
'b' => out.push('\u{0008}'),
|
||||
'f' => out.push('\u{000C}'),
|
||||
'a' => out.push('\u{0007}'),
|
||||
'v' => out.push('\u{000B}'),
|
||||
'\\' => out.push('\\'),
|
||||
'"' => out.push('"'),
|
||||
'\'' => out.push('\''),
|
||||
'0'..='7' => {
|
||||
let mut value = next.to_digit(8).unwrap_or(0);
|
||||
for _ in 0..2 {
|
||||
match chars.peek() {
|
||||
Some('0'..='7') => {
|
||||
if let Some(digit) = chars.next() {
|
||||
value = value * 8 + digit.to_digit(8).unwrap_or(0);
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
}
|
||||
if let Some(ch) = std::char::from_u32(value) {
|
||||
out.push(ch);
|
||||
}
|
||||
}
|
||||
other => out.push(other),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Stage only the files that actually exist on disk for the given diff.
|
||||
pub fn stage_paths(git_root: &Path, diff: &str) -> io::Result<()> {
|
||||
let paths = extract_paths_from_patch(diff);
|
||||
let mut existing: Vec<String> = Vec::new();
|
||||
for p in paths {
|
||||
let joined = git_root.join(&p);
|
||||
if std::fs::symlink_metadata(&joined).is_ok() {
|
||||
existing.push(p);
|
||||
}
|
||||
}
|
||||
if existing.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
let mut cmd = std::process::Command::new("git");
|
||||
cmd.args(["-c", crate::SAFE_BARE_REPOSITORY_CONFIG]);
|
||||
cmd.arg("add");
|
||||
cmd.arg("--");
|
||||
for p in &existing {
|
||||
cmd.arg(OsStr::new(p));
|
||||
}
|
||||
scrub_non_inheritable_env_vars(&mut cmd);
|
||||
let out = cmd.current_dir(git_root).output()?;
|
||||
let _code = out.status.code().unwrap_or(-1);
|
||||
// We do not hard fail staging; best-effort is OK. Return Ok even on non-zero.
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ============ Parser ported from VS Code (TS) ============
|
||||
|
||||
/// Parse `git apply` output into applied/skipped/conflicted path groupings.
|
||||
pub fn parse_git_apply_output(
|
||||
stdout: &str,
|
||||
stderr: &str,
|
||||
) -> (Vec<String>, Vec<String>, Vec<String>) {
|
||||
let combined = [stdout, stderr]
|
||||
.iter()
|
||||
.filter(|s| !s.is_empty())
|
||||
.cloned()
|
||||
.collect::<Vec<&str>>()
|
||||
.join("\n");
|
||||
|
||||
let mut applied = std::collections::BTreeSet::new();
|
||||
let mut skipped = std::collections::BTreeSet::new();
|
||||
let mut conflicted = std::collections::BTreeSet::new();
|
||||
let mut last_seen_path: Option<String> = None;
|
||||
|
||||
fn add(set: &mut std::collections::BTreeSet<String>, raw: &str) {
|
||||
let trimmed = raw.trim();
|
||||
if trimmed.is_empty() {
|
||||
return;
|
||||
}
|
||||
let first = trimmed.chars().next().unwrap_or('\0');
|
||||
let last = trimmed.chars().last().unwrap_or('\0');
|
||||
let unquoted = if (first == '"' || first == '\'') && last == first && trimmed.len() >= 2 {
|
||||
unescape_c_string(&trimmed[1..trimmed.len() - 1])
|
||||
} else {
|
||||
trimmed.to_string()
|
||||
};
|
||||
if !unquoted.is_empty() {
|
||||
set.insert(unquoted);
|
||||
}
|
||||
}
|
||||
|
||||
static APPLIED_CLEAN: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^Applied patch(?: to)?\\s+(?P<path>.+?)\\s+cleanly\\.?$"));
|
||||
static APPLIED_CONFLICTS: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^Applied patch(?: to)?\\s+(?P<path>.+?)\\s+with conflicts\\.?$"));
|
||||
static APPLYING_WITH_REJECTS: Lazy<Regex> = Lazy::new(|| {
|
||||
regex_ci("^Applying patch\\s+(?P<path>.+?)\\s+with\\s+\\d+\\s+rejects?\\.{0,3}$")
|
||||
});
|
||||
static CHECKING_PATCH: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^Checking patch\\s+(?P<path>.+?)\\.\\.\\.$"));
|
||||
static UNMERGED_LINE: Lazy<Regex> = Lazy::new(|| regex_ci("^U\\s+(?P<path>.+)$"));
|
||||
static PATCH_FAILED: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^error:\\s+patch failed:\\s+(?P<path>.+?)(?::\\d+)?(?:\\s|$)"));
|
||||
static DOES_NOT_APPLY: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^error:\\s+(?P<path>.+?):\\s+patch does not apply$"));
|
||||
static THREE_WAY_START: Lazy<Regex> = Lazy::new(|| {
|
||||
regex_ci("^(?:Performing three-way merge|Falling back to three-way merge)\\.\\.\\.$")
|
||||
});
|
||||
static THREE_WAY_FAILED: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^Failed to perform three-way merge\\.\\.\\.$"));
|
||||
static FALLBACK_DIRECT: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^Falling back to direct application\\.\\.\\.$"));
|
||||
static LACKS_BLOB: Lazy<Regex> = Lazy::new(|| {
|
||||
regex_ci(
|
||||
"^(?:error: )?repository lacks the necessary blob to (?:perform|fall back on) 3-?way merge\\.?$",
|
||||
)
|
||||
});
|
||||
static INDEX_MISMATCH: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^error:\\s+(?P<path>.+?):\\s+does not match index\\b"));
|
||||
static NOT_IN_INDEX: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^error:\\s+(?P<path>.+?):\\s+does not exist in index\\b"));
|
||||
static ALREADY_EXISTS_WT: Lazy<Regex> = Lazy::new(|| {
|
||||
regex_ci("^error:\\s+(?P<path>.+?)\\s+already exists in (?:the )?working directory\\b")
|
||||
});
|
||||
static FILE_EXISTS: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^error:\\s+patch failed:\\s+(?P<path>.+?)\\s+File exists"));
|
||||
static RENAMED_DELETED: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^error:\\s+path\\s+(?P<path>.+?)\\s+has been renamed\\/deleted"));
|
||||
static CANNOT_APPLY_BINARY: Lazy<Regex> = Lazy::new(|| {
|
||||
regex_ci(
|
||||
"^error:\\s+cannot apply binary patch to\\s+['\\\"]?(?P<path>.+?)['\\\"]?\\s+without full index line$",
|
||||
)
|
||||
});
|
||||
static BINARY_DOES_NOT_APPLY: Lazy<Regex> = Lazy::new(|| {
|
||||
regex_ci("^error:\\s+binary patch does not apply to\\s+['\\\"]?(?P<path>.+?)['\\\"]?$")
|
||||
});
|
||||
static BINARY_INCORRECT_RESULT: Lazy<Regex> = Lazy::new(|| {
|
||||
regex_ci(
|
||||
"^error:\\s+binary patch to\\s+['\\\"]?(?P<path>.+?)['\\\"]?\\s+creates incorrect result\\b",
|
||||
)
|
||||
});
|
||||
static CANNOT_READ_CURRENT: Lazy<Regex> = Lazy::new(|| {
|
||||
regex_ci("^error:\\s+cannot read the current contents of\\s+['\\\"]?(?P<path>.+?)['\\\"]?$")
|
||||
});
|
||||
static SKIPPED_PATCH: Lazy<Regex> =
|
||||
Lazy::new(|| regex_ci("^Skipped patch\\s+['\\\"]?(?P<path>.+?)['\\\"]\\.$"));
|
||||
static CANNOT_MERGE_BINARY_WARN: Lazy<Regex> = Lazy::new(|| {
|
||||
regex_ci(
|
||||
"^warning:\\s*Cannot merge binary files:\\s+(?P<path>.+?)\\s+\\(ours\\s+vs\\.\\s+theirs\\)",
|
||||
)
|
||||
});
|
||||
|
||||
for raw_line in combined.lines() {
|
||||
let line = raw_line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// === "Checking patch <path>..." tracking ===
|
||||
if let Some(c) = CHECKING_PATCH.captures(line) {
|
||||
if let Some(m) = c.name("path") {
|
||||
last_seen_path = Some(m.as_str().to_string());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// === Status lines ===
|
||||
if let Some(c) = APPLIED_CLEAN.captures(line) {
|
||||
if let Some(m) = c.name("path") {
|
||||
add(&mut applied, m.as_str());
|
||||
let p = applied.iter().next_back().cloned();
|
||||
if let Some(p) = p {
|
||||
conflicted.remove(&p);
|
||||
skipped.remove(&p);
|
||||
last_seen_path = Some(p);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(c) = APPLIED_CONFLICTS.captures(line) {
|
||||
if let Some(m) = c.name("path") {
|
||||
add(&mut conflicted, m.as_str());
|
||||
let p = conflicted.iter().next_back().cloned();
|
||||
if let Some(p) = p {
|
||||
applied.remove(&p);
|
||||
skipped.remove(&p);
|
||||
last_seen_path = Some(p);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if let Some(c) = APPLYING_WITH_REJECTS.captures(line) {
|
||||
if let Some(m) = c.name("path") {
|
||||
add(&mut conflicted, m.as_str());
|
||||
let p = conflicted.iter().next_back().cloned();
|
||||
if let Some(p) = p {
|
||||
applied.remove(&p);
|
||||
skipped.remove(&p);
|
||||
last_seen_path = Some(p);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// === “U <path>” after conflicts ===
|
||||
if let Some(c) = UNMERGED_LINE.captures(line) {
|
||||
if let Some(m) = c.name("path") {
|
||||
add(&mut conflicted, m.as_str());
|
||||
let p = conflicted.iter().next_back().cloned();
|
||||
if let Some(p) = p {
|
||||
applied.remove(&p);
|
||||
skipped.remove(&p);
|
||||
last_seen_path = Some(p);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// === Early hints ===
|
||||
if PATCH_FAILED.is_match(line) || DOES_NOT_APPLY.is_match(line) {
|
||||
if let Some(c) = PATCH_FAILED
|
||||
.captures(line)
|
||||
.or_else(|| DOES_NOT_APPLY.captures(line))
|
||||
&& let Some(m) = c.name("path")
|
||||
{
|
||||
add(&mut skipped, m.as_str());
|
||||
last_seen_path = Some(m.as_str().to_string());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// === Ignore narration ===
|
||||
if THREE_WAY_START.is_match(line) || FALLBACK_DIRECT.is_match(line) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// === 3-way failed entirely; attribute to last_seen_path ===
|
||||
if THREE_WAY_FAILED.is_match(line) || LACKS_BLOB.is_match(line) {
|
||||
if let Some(p) = last_seen_path.clone() {
|
||||
add(&mut skipped, &p);
|
||||
applied.remove(&p);
|
||||
conflicted.remove(&p);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// === Skips / I/O problems ===
|
||||
if let Some(c) = INDEX_MISMATCH
|
||||
.captures(line)
|
||||
.or_else(|| NOT_IN_INDEX.captures(line))
|
||||
.or_else(|| ALREADY_EXISTS_WT.captures(line))
|
||||
.or_else(|| FILE_EXISTS.captures(line))
|
||||
.or_else(|| RENAMED_DELETED.captures(line))
|
||||
.or_else(|| CANNOT_APPLY_BINARY.captures(line))
|
||||
.or_else(|| BINARY_DOES_NOT_APPLY.captures(line))
|
||||
.or_else(|| BINARY_INCORRECT_RESULT.captures(line))
|
||||
.or_else(|| CANNOT_READ_CURRENT.captures(line))
|
||||
.or_else(|| SKIPPED_PATCH.captures(line))
|
||||
{
|
||||
if let Some(m) = c.name("path") {
|
||||
add(&mut skipped, m.as_str());
|
||||
let p_now = skipped.iter().next_back().cloned();
|
||||
if let Some(p) = p_now {
|
||||
applied.remove(&p);
|
||||
conflicted.remove(&p);
|
||||
last_seen_path = Some(p);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
// === Warnings that imply conflicts ===
|
||||
if let Some(c) = CANNOT_MERGE_BINARY_WARN.captures(line) {
|
||||
if let Some(m) = c.name("path") {
|
||||
add(&mut conflicted, m.as_str());
|
||||
let p = conflicted.iter().next_back().cloned();
|
||||
if let Some(p) = p {
|
||||
applied.remove(&p);
|
||||
skipped.remove(&p);
|
||||
last_seen_path = Some(p);
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Final precedence: conflicts > applied > skipped
|
||||
for p in conflicted.iter() {
|
||||
applied.remove(p);
|
||||
skipped.remove(p);
|
||||
}
|
||||
for p in applied.iter() {
|
||||
skipped.remove(p);
|
||||
}
|
||||
|
||||
(
|
||||
applied.into_iter().collect(),
|
||||
skipped.into_iter().collect(),
|
||||
conflicted.into_iter().collect(),
|
||||
)
|
||||
}
|
||||
|
||||
fn regex_ci(pat: &str) -> Regex {
|
||||
Regex::new(&format!("(?i){pat}")).unwrap_or_else(|e| panic!("invalid regex: {e}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
fn env_lock() -> &'static Mutex<()> {
|
||||
static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
|
||||
LOCK.get_or_init(|| Mutex::new(()))
|
||||
}
|
||||
|
||||
fn run(cwd: &Path, args: &[&str]) -> (i32, String, String) {
|
||||
let out = std::process::Command::new(args[0])
|
||||
.args(&args[1..])
|
||||
.current_dir(cwd)
|
||||
.output()
|
||||
.expect("spawn ok");
|
||||
(
|
||||
out.status.code().unwrap_or(-1),
|
||||
String::from_utf8_lossy(&out.stdout).into_owned(),
|
||||
String::from_utf8_lossy(&out.stderr).into_owned(),
|
||||
)
|
||||
}
|
||||
|
||||
fn init_repo() -> tempfile::TempDir {
|
||||
let dir = tempfile::tempdir().expect("tempdir");
|
||||
let root = dir.path();
|
||||
// git init and minimal identity
|
||||
let _ = run(root, &["git", "init"]);
|
||||
let _ = run(root, &["git", "config", "user.email", "codex@example.com"]);
|
||||
let _ = run(root, &["git", "config", "user.name", "Codex"]);
|
||||
dir
|
||||
}
|
||||
|
||||
fn read_file_normalized(path: &Path) -> String {
|
||||
std::fs::read_to_string(path)
|
||||
.expect("read file")
|
||||
.replace("\r\n", "\n")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_paths_handles_quoted_headers() {
|
||||
let diff = "diff --git \"a/hello world.txt\" \"b/hello world.txt\"\nnew file mode 100644\n--- /dev/null\n+++ b/hello world.txt\n@@ -0,0 +1 @@\n+hi\n";
|
||||
let paths = extract_paths_from_patch(diff);
|
||||
assert_eq!(paths, vec!["hello world.txt".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_paths_ignores_dev_null_header() {
|
||||
let diff = "diff --git a/dev/null b/ok.txt\nnew file mode 100644\n--- /dev/null\n+++ b/ok.txt\n@@ -0,0 +1 @@\n+hi\n";
|
||||
let paths = extract_paths_from_patch(diff);
|
||||
assert_eq!(paths, vec!["ok.txt".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn extract_paths_unescapes_c_style_in_quoted_headers() {
|
||||
let diff = "diff --git \"a/hello\\tworld.txt\" \"b/hello\\tworld.txt\"\nnew file mode 100644\n--- /dev/null\n+++ b/hello\tworld.txt\n@@ -0,0 +1 @@\n+hi\n";
|
||||
let paths = extract_paths_from_patch(diff);
|
||||
assert_eq!(paths, vec!["hello\tworld.txt".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_output_unescapes_quoted_paths() {
|
||||
let stderr = "error: patch failed: \"hello\\tworld.txt\":1\n";
|
||||
let (applied, skipped, conflicted) = parse_git_apply_output("", stderr);
|
||||
assert_eq!(applied, Vec::<String>::new());
|
||||
assert_eq!(conflicted, Vec::<String>::new());
|
||||
assert_eq!(skipped, vec!["hello\tworld.txt".to_string()]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_add_success() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
|
||||
let diff = "diff --git a/hello.txt b/hello.txt\nnew file mode 100644\n--- /dev/null\n+++ b/hello.txt\n@@ -0,0 +1,2 @@\n+hello\n+world\n";
|
||||
let req = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
};
|
||||
let r = apply_git_patch(&req).expect("run apply");
|
||||
assert_eq!(r.exit_code, 0, "exit code 0");
|
||||
// File exists now
|
||||
assert!(root.join("hello.txt").exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_modify_conflict() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
// seed file and commit
|
||||
std::fs::write(root.join("file.txt"), "line1\nline2\nline3\n").unwrap();
|
||||
let _ = run(root, &["git", "add", "file.txt"]);
|
||||
let _ = run(root, &["git", "commit", "-m", "seed"]);
|
||||
// local edit (unstaged)
|
||||
std::fs::write(root.join("file.txt"), "line1\nlocal2\nline3\n").unwrap();
|
||||
// patch wants to change the same line differently
|
||||
let diff = "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1,3 +1,3 @@\n line1\n-line2\n+remote2\n line3\n";
|
||||
let req = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
};
|
||||
let r = apply_git_patch(&req).expect("run apply");
|
||||
assert_ne!(r.exit_code, 0, "non-zero exit on conflict");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_modify_skipped_missing_index() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
// Try to modify a file that is not in the index
|
||||
let diff = "diff --git a/ghost.txt b/ghost.txt\n--- a/ghost.txt\n+++ b/ghost.txt\n@@ -1,1 +1,1 @@\n-old\n+new\n";
|
||||
let req = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
};
|
||||
let r = apply_git_patch(&req).expect("run apply");
|
||||
assert_ne!(r.exit_code, 0, "non-zero exit on missing index");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn apply_then_revert_success() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
// Seed file and commit original content
|
||||
std::fs::write(root.join("file.txt"), "orig\n").unwrap();
|
||||
let _ = run(root, &["git", "add", "file.txt"]);
|
||||
let _ = run(root, &["git", "commit", "-m", "seed"]);
|
||||
|
||||
// Forward patch: orig -> ORIG
|
||||
let diff = "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1,1 +1,1 @@\n-orig\n+ORIG\n";
|
||||
let apply_req = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
};
|
||||
let res_apply = apply_git_patch(&apply_req).expect("apply ok");
|
||||
assert_eq!(res_apply.exit_code, 0, "forward apply succeeded");
|
||||
let after_apply = read_file_normalized(&root.join("file.txt"));
|
||||
assert_eq!(after_apply, "ORIG\n");
|
||||
|
||||
// Revert patch: ORIG -> orig (stage paths first; engine handles it)
|
||||
let revert_req = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.to_string(),
|
||||
revert: true,
|
||||
preflight: false,
|
||||
};
|
||||
let res_revert = apply_git_patch(&revert_req).expect("revert ok");
|
||||
assert_eq!(res_revert.exit_code, 0, "revert apply succeeded");
|
||||
let after_revert = read_file_normalized(&root.join("file.txt"));
|
||||
assert_eq!(after_revert, "orig\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn revert_preflight_does_not_stage_index() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
// Seed repo and apply forward patch so the working tree reflects the change.
|
||||
std::fs::write(root.join("file.txt"), "orig\n").unwrap();
|
||||
let _ = run(root, &["git", "add", "file.txt"]);
|
||||
let _ = run(root, &["git", "commit", "-m", "seed"]);
|
||||
|
||||
let diff = "diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1,1 +1,1 @@\n-orig\n+ORIG\n";
|
||||
let apply_req = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
};
|
||||
let res_apply = apply_git_patch(&apply_req).expect("apply ok");
|
||||
assert_eq!(res_apply.exit_code, 0, "forward apply succeeded");
|
||||
let (commit_code, _, commit_err) = run(root, &["git", "commit", "-am", "apply change"]);
|
||||
assert_eq!(commit_code, 0, "commit applied change: {commit_err}");
|
||||
|
||||
let (_code_before, staged_before, _stderr_before) =
|
||||
run(root, &["git", "diff", "--cached", "--name-only"]);
|
||||
|
||||
let preflight_req = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.to_string(),
|
||||
revert: true,
|
||||
preflight: true,
|
||||
};
|
||||
let res_preflight = apply_git_patch(&preflight_req).expect("preflight ok");
|
||||
assert_eq!(res_preflight.exit_code, 0, "revert preflight succeeded");
|
||||
let (_code_after, staged_after, _stderr_after) =
|
||||
run(root, &["git", "diff", "--cached", "--name-only"]);
|
||||
assert_eq!(
|
||||
staged_after.trim(),
|
||||
staged_before.trim(),
|
||||
"preflight should not stage new paths",
|
||||
);
|
||||
|
||||
let after_preflight = read_file_normalized(&root.join("file.txt"));
|
||||
assert_eq!(after_preflight, "ORIG\n");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn preflight_blocks_partial_changes() {
|
||||
let _g = env_lock().lock().unwrap();
|
||||
let repo = init_repo();
|
||||
let root = repo.path();
|
||||
// Build a multi-file diff: one valid add (ok.txt) and one invalid modify (ghost.txt)
|
||||
let diff = "diff --git a/ok.txt b/ok.txt\nnew file mode 100644\n--- /dev/null\n+++ b/ok.txt\n@@ -0,0 +1,2 @@\n+alpha\n+beta\n\n\
|
||||
diff --git a/ghost.txt b/ghost.txt\n--- a/ghost.txt\n+++ b/ghost.txt\n@@ -1,1 +1,1 @@\n-old\n+new\n";
|
||||
|
||||
// 1) With preflight enabled, nothing should be changed (even though ok.txt could be added)
|
||||
let req1 = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.to_string(),
|
||||
revert: false,
|
||||
preflight: true,
|
||||
};
|
||||
let r1 = apply_git_patch(&req1).expect("preflight apply");
|
||||
assert_ne!(r1.exit_code, 0, "preflight reports failure");
|
||||
assert!(
|
||||
!root.join("ok.txt").exists(),
|
||||
"preflight must prevent adding ok.txt"
|
||||
);
|
||||
assert!(
|
||||
r1.cmd_for_log.contains("--check"),
|
||||
"preflight path recorded --check"
|
||||
);
|
||||
|
||||
// 2) Without preflight, we should see no --check in the executed command
|
||||
let req2 = ApplyGitRequest {
|
||||
cwd: root.to_path_buf(),
|
||||
diff: diff.to_string(),
|
||||
revert: false,
|
||||
preflight: false,
|
||||
};
|
||||
let r2 = apply_git_patch(&req2).expect("direct apply");
|
||||
assert_ne!(r2.exit_code, 0, "apply is expected to fail overall");
|
||||
assert!(
|
||||
!r2.cmd_for_log.contains("--check"),
|
||||
"non-preflight path should not use --check"
|
||||
);
|
||||
}
|
||||
}
|
||||
949
akode-rs/git-utils/src/baseline.rs
Normal file
949
akode-rs/git-utils/src/baseline.rs
Normal file
@@ -0,0 +1,949 @@
|
||||
use anyhow::Context;
|
||||
use gix::hash::ObjectId;
|
||||
use gix::objs::Tree;
|
||||
use gix::objs::tree::Entry;
|
||||
use gix::objs::tree::EntryKind;
|
||||
use gix::objs::tree::EntryMode;
|
||||
use similar::TextDiff;
|
||||
use std::collections::BTreeMap;
|
||||
use std::collections::BTreeSet;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
#[cfg(windows)]
|
||||
use std::os::windows::fs::FileTypeExt;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use tokio::task;
|
||||
|
||||
use crate::operations::run_git_for_status;
|
||||
|
||||
// Match the default file limit for automatic ghost snapshots. A baseline is derived data.
|
||||
const MAX_BASELINE_FILE_BYTES: u64 = 10 * 1024 * 1024;
|
||||
const BASELINE_VERSION_FILE: &str = "codex-baseline-version";
|
||||
const BASELINE_VERSION: &[u8] = b"1\n";
|
||||
|
||||
const BASELINE_COMMIT_MESSAGE: &str =
|
||||
"Initialize Codex git baseline\n\nCo-authored-by: Codex <noreply@openai.com>";
|
||||
|
||||
/// File-level change status between a git baseline and the current directory.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum GitBaselineChangeStatus {
|
||||
Added,
|
||||
Modified,
|
||||
Deleted,
|
||||
}
|
||||
|
||||
impl GitBaselineChangeStatus {
|
||||
/// Returns the short git-style status label for this change.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
GitBaselineChangeStatus::Added => "A",
|
||||
GitBaselineChangeStatus::Modified => "M",
|
||||
GitBaselineChangeStatus::Deleted => "D",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// One changed file between a git baseline and the current directory.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct GitBaselineChange {
|
||||
pub status: GitBaselineChangeStatus,
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
/// Structured diff from the latest git baseline reset to the current directory.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct GitBaselineDiff {
|
||||
pub changes: Vec<GitBaselineChange>,
|
||||
pub unified_diff: String,
|
||||
}
|
||||
|
||||
impl GitBaselineDiff {
|
||||
pub fn has_changes(&self) -> bool {
|
||||
!self.changes.is_empty()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
struct GitBaselineFileEntry {
|
||||
oid: ObjectId,
|
||||
mode: EntryMode,
|
||||
}
|
||||
|
||||
/// Replaces any existing `.git` metadata in `root` with a fresh one-commit baseline.
|
||||
///
|
||||
/// This is intentionally destructive for `root/.git`. It is meant for internal directories where
|
||||
/// git is used only as a baseline/diff implementation detail, not for user repositories.
|
||||
pub async fn reset_git_repository(root: &Path) -> anyhow::Result<()> {
|
||||
with_baseline_lock(root, |root| {
|
||||
reset_git_repository_sync(root, BaselineContents::Current)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
/// Ensures the internal directory has a usable, size-bounded baseline.
|
||||
///
|
||||
/// Old or incomplete baselines are discarded without reading their blobs. The replacement is
|
||||
/// empty so all eligible working files remain visible to the next consolidation as additions.
|
||||
pub async fn ensure_git_baseline_repository(root: &Path) -> anyhow::Result<()> {
|
||||
with_baseline_lock(root, ensure_git_baseline_repository_sync).await
|
||||
}
|
||||
|
||||
fn ensure_git_baseline_repository_sync(root: &Path) -> anyhow::Result<()> {
|
||||
let git_dir = root.join(".git");
|
||||
let mut version = Vec::new();
|
||||
// Never follow a gitfile or directory symlink into another repository.
|
||||
if fs::symlink_metadata(&git_dir).is_ok_and(|metadata| metadata.is_dir())
|
||||
&& fs::File::open(git_dir.join(BASELINE_VERSION_FILE))
|
||||
.and_then(|file| {
|
||||
file.take(BASELINE_VERSION.len() as u64 + 1)
|
||||
.read_to_end(&mut version)
|
||||
})
|
||||
.is_ok()
|
||||
&& version == BASELINE_VERSION
|
||||
&& let Ok(repo) = gix::open::Options::isolated().open(&git_dir)
|
||||
{
|
||||
let repo = repo.to_thread_local();
|
||||
if repo.common_dir() == repo.git_dir() && head_file_entries(&repo).is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
reset_git_repository_sync(root, BaselineContents::Empty)
|
||||
}
|
||||
|
||||
// Imports and background consolidation can overlap, including across app-server processes.
|
||||
// A nested .git keeps the lock outside both the replaceable baseline and memory scans.
|
||||
async fn with_baseline_lock<T: Send + 'static>(
|
||||
root: &Path,
|
||||
operation: impl FnOnce(&Path) -> anyhow::Result<T> + Send + 'static,
|
||||
) -> anyhow::Result<T> {
|
||||
let root = root.to_owned();
|
||||
task::spawn_blocking(move || {
|
||||
fs::create_dir_all(&root)?;
|
||||
let root = fs::canonicalize(root)?;
|
||||
let control = baseline_control(&root);
|
||||
for dir in [root.join(".codex-baseline"), control.clone()] {
|
||||
match fs::create_dir(&dir) {
|
||||
Ok(()) => {}
|
||||
Err(err)
|
||||
if err.kind() == std::io::ErrorKind::AlreadyExists
|
||||
&& fs::symlink_metadata(&dir)?.is_dir()
|
||||
&& fs::canonicalize(&dir)? == dir => {}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
}
|
||||
anyhow::ensure!(
|
||||
!control.join("HEAD").try_exists()?,
|
||||
"baseline control directory contains a repository"
|
||||
);
|
||||
let lock = fs::File::options()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.create(true)
|
||||
.truncate(false)
|
||||
.open(control.join("codex-baseline.lock"))?;
|
||||
lock.lock().context("lock git baseline")?;
|
||||
operation(&root)
|
||||
})
|
||||
.await?
|
||||
}
|
||||
|
||||
fn baseline_control(root: &Path) -> PathBuf {
|
||||
root.join(".codex-baseline").join(".git")
|
||||
}
|
||||
|
||||
fn discard_baseline_path(path: &Path) -> anyhow::Result<()> {
|
||||
match path.symlink_metadata() {
|
||||
#[cfg(windows)]
|
||||
Ok(meta) if meta.file_type().is_symlink_dir() => fs::remove_dir(path)?,
|
||||
Ok(meta) if meta.is_dir() => {
|
||||
// Invalidate before deletion: interruption must not leave trusted partial metadata.
|
||||
match fs::remove_file(path.join(BASELINE_VERSION_FILE)) {
|
||||
Ok(()) => {}
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
fs::remove_dir_all(path)?;
|
||||
}
|
||||
Ok(_) => fs::remove_file(path)?,
|
||||
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(err) => return Err(err.into()),
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
enum BaselineContents {
|
||||
Empty,
|
||||
Current,
|
||||
}
|
||||
|
||||
fn reset_git_repository_sync(root: &Path, contents: BaselineContents) -> anyhow::Result<()> {
|
||||
let git_dir = root.join(".git");
|
||||
// Only metadata is disposable. An interrupted reset leaves no version marker, so the next
|
||||
// operation retries with an empty baseline rather than trusting a partial snapshot.
|
||||
discard_baseline_path(&git_dir)?;
|
||||
let repo = gix::ThreadSafeRepository::init_opts(
|
||||
root,
|
||||
gix::create::Kind::WithWorktree,
|
||||
gix::create::Options::default(),
|
||||
gix::open::Options::isolated(),
|
||||
)?
|
||||
.to_thread_local();
|
||||
let tree_id = match contents {
|
||||
BaselineContents::Empty => repo.write_object(Tree::default())?.detach(),
|
||||
BaselineContents::Current => write_tree(&repo, root)?,
|
||||
};
|
||||
let signature = codex_signature();
|
||||
let mut time = gix::date::parse::TimeBuf::default();
|
||||
let signature = signature.to_ref(&mut time);
|
||||
repo.commit_as(
|
||||
signature,
|
||||
signature,
|
||||
"HEAD",
|
||||
BASELINE_COMMIT_MESSAGE,
|
||||
tree_id,
|
||||
Vec::<ObjectId>::new(),
|
||||
)?;
|
||||
write_index_from_head(root)?;
|
||||
fs::write(git_dir.join(BASELINE_VERSION_FILE), BASELINE_VERSION)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn write_index_from_head(root: &Path) -> anyhow::Result<()> {
|
||||
// Pin the index write to this worktree. Relative paths also work with Git for Windows
|
||||
// when Rust has canonicalized the working directory to a verbatim path.
|
||||
run_git_for_status(
|
||||
root,
|
||||
["read-tree", "--reset", "HEAD"],
|
||||
Some(&[
|
||||
("GIT_DIR".into(), ".git".into()),
|
||||
("GIT_COMMON_DIR".into(), ".git".into()),
|
||||
("GIT_INDEX_FILE".into(), ".git/index".into()),
|
||||
("GIT_OBJECT_DIRECTORY".into(), ".git/objects".into()),
|
||||
("GIT_WORK_TREE".into(), ".".into()),
|
||||
]),
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the diff between the latest baseline and the current directory's bounded files.
|
||||
pub async fn diff_since_latest_init(root: &Path) -> anyhow::Result<GitBaselineDiff> {
|
||||
with_baseline_lock(root, |root| {
|
||||
ensure_git_baseline_repository_sync(root)?;
|
||||
let mut repo = gix::open::Options::isolated().open(root)?.to_thread_local();
|
||||
let mut head_entries = head_file_entries(&repo)?;
|
||||
let mut current_entries = BTreeMap::new();
|
||||
let mut excluded = BTreeSet::new();
|
||||
collect_current_entries(&repo, root, root, &mut current_entries, &mut excluded)?;
|
||||
// Inputs may grow during synchronization, after the initial baseline was prepared.
|
||||
if excluded.iter().any(|path| head_entries.contains_key(path)) {
|
||||
drop(repo);
|
||||
reset_git_repository_sync(root, BaselineContents::Empty)?;
|
||||
repo = gix::open::Options::isolated().open(root)?.to_thread_local();
|
||||
head_entries.clear();
|
||||
}
|
||||
let changes = diff_entries(&head_entries, ¤t_entries);
|
||||
let unified_diff =
|
||||
render_unified_diff(&repo, root, &head_entries, ¤t_entries, &changes)?;
|
||||
Ok(GitBaselineDiff {
|
||||
changes,
|
||||
unified_diff,
|
||||
})
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn codex_signature() -> gix::actor::Signature {
|
||||
gix::actor::Signature {
|
||||
name: "Codex".into(),
|
||||
email: "noreply@openai.com".into(),
|
||||
time: gix::date::Time {
|
||||
seconds: chrono::Utc::now().timestamp(),
|
||||
offset: 0,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn write_tree(repo: &gix::Repository, dir: &Path) -> anyhow::Result<ObjectId> {
|
||||
let mut entries = Vec::new();
|
||||
for entry in fs::read_dir(dir).with_context(|| format!("read {}", dir.display()))? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
let file_name = entry.file_name();
|
||||
if file_name == OsStr::new(".git") {
|
||||
continue;
|
||||
}
|
||||
|
||||
let file_type = entry.file_type()?;
|
||||
if file_type.is_dir() {
|
||||
let oid = write_tree(repo, &path)?;
|
||||
let tree = repo
|
||||
.find_tree(oid)
|
||||
.with_context(|| format!("load tree {}", path.display()))?;
|
||||
if tree.decode()?.entries.is_empty() {
|
||||
continue;
|
||||
}
|
||||
entries.push(Entry {
|
||||
mode: EntryKind::Tree.into(),
|
||||
filename: os_str_to_bstring(&file_name),
|
||||
oid,
|
||||
});
|
||||
} else if file_type.is_file() {
|
||||
let Some((bytes, mode)) = read_baseline_file(&path)? else {
|
||||
continue;
|
||||
};
|
||||
let oid = repo
|
||||
.write_blob(bytes)
|
||||
.with_context(|| format!("write blob {}", path.display()))?
|
||||
.detach();
|
||||
entries.push(Entry {
|
||||
mode,
|
||||
filename: os_str_to_bstring(&file_name),
|
||||
oid,
|
||||
});
|
||||
} else if file_type.is_symlink() {
|
||||
let target =
|
||||
fs::read_link(&path).with_context(|| format!("read symlink {}", path.display()))?;
|
||||
let oid = repo
|
||||
.write_blob(path_to_bytes(&target))
|
||||
.with_context(|| format!("write symlink blob {}", path.display()))?
|
||||
.detach();
|
||||
entries.push(Entry {
|
||||
mode: EntryKind::Link.into(),
|
||||
filename: os_str_to_bstring(&file_name),
|
||||
oid,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
entries.sort();
|
||||
repo.write_object(&Tree { entries })
|
||||
.context("write tree object")
|
||||
.map(gix::Id::detach)
|
||||
}
|
||||
|
||||
fn head_file_entries(
|
||||
repo: &gix::Repository,
|
||||
) -> anyhow::Result<BTreeMap<String, GitBaselineFileEntry>> {
|
||||
let tree_id = repo.head_tree_id().context("load HEAD tree id")?;
|
||||
let tree = repo.find_tree(tree_id.detach()).context("load HEAD tree")?;
|
||||
let mut entries = BTreeMap::new();
|
||||
collect_tree_entries(repo, tree, PathBuf::new(), &mut entries)?;
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn collect_tree_entries(
|
||||
repo: &gix::Repository,
|
||||
tree: gix::Tree<'_>,
|
||||
prefix: PathBuf,
|
||||
entries: &mut BTreeMap<String, GitBaselineFileEntry>,
|
||||
) -> anyhow::Result<()> {
|
||||
for entry in tree.iter() {
|
||||
let entry = entry?;
|
||||
let file_name = bstr_to_path(entry.inner.filename);
|
||||
let path = prefix.join(file_name);
|
||||
if entry.inner.mode.is_tree() {
|
||||
let tree = repo
|
||||
.find_tree(entry.inner.oid.to_owned())
|
||||
.context("load child tree")?;
|
||||
collect_tree_entries(repo, tree, path, entries)?;
|
||||
} else {
|
||||
entries.insert(
|
||||
path_to_slash_string(&path),
|
||||
GitBaselineFileEntry {
|
||||
oid: entry.inner.oid.to_owned(),
|
||||
mode: entry.inner.mode,
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn collect_current_entries(
|
||||
repo: &gix::Repository,
|
||||
root: &Path,
|
||||
dir: &Path,
|
||||
entries: &mut BTreeMap<String, GitBaselineFileEntry>,
|
||||
excluded: &mut BTreeSet<String>,
|
||||
) -> anyhow::Result<()> {
|
||||
for entry in fs::read_dir(dir).with_context(|| format!("read {}", dir.display()))? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if path.file_name() == Some(OsStr::new(".git")) {
|
||||
continue;
|
||||
}
|
||||
|
||||
let file_type = entry.file_type()?;
|
||||
if file_type.is_dir() {
|
||||
collect_current_entries(repo, root, &path, entries, excluded)?;
|
||||
} else if file_type.is_file() {
|
||||
let Some((bytes, mode)) = read_baseline_file(&path)? else {
|
||||
excluded.insert(relative_slash_path(root, &path)?);
|
||||
continue;
|
||||
};
|
||||
entries.insert(
|
||||
relative_slash_path(root, &path)?,
|
||||
GitBaselineFileEntry {
|
||||
oid: blob_oid(repo, &bytes)?,
|
||||
mode,
|
||||
},
|
||||
);
|
||||
} else if file_type.is_symlink() {
|
||||
let target =
|
||||
fs::read_link(&path).with_context(|| format!("read symlink {}", path.display()))?;
|
||||
entries.insert(
|
||||
relative_slash_path(root, &path)?,
|
||||
GitBaselineFileEntry {
|
||||
oid: blob_oid(repo, &path_to_bytes(&target))?,
|
||||
mode: EntryKind::Link.into(),
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Bounds the read even if a file grows between checking its size and reaching EOF.
|
||||
fn read_baseline_file(path: &Path) -> anyhow::Result<Option<(Vec<u8>, EntryMode)>> {
|
||||
let file = fs::File::open(path).with_context(|| format!("open {}", path.display()))?;
|
||||
let metadata = file.metadata()?;
|
||||
let len = metadata.len();
|
||||
if len > MAX_BASELINE_FILE_BYTES {
|
||||
return Ok(None);
|
||||
}
|
||||
// Reserve an EOF probe byte so bounded reads of stable files need no reallocation.
|
||||
let mut bytes = Vec::with_capacity(len as usize + 1);
|
||||
file.take(MAX_BASELINE_FILE_BYTES + 1)
|
||||
.read_to_end(&mut bytes)?;
|
||||
Ok((bytes.len() as u64 <= MAX_BASELINE_FILE_BYTES).then_some((bytes, file_mode(&metadata))))
|
||||
}
|
||||
|
||||
fn blob_oid(repo: &gix::Repository, bytes: &[u8]) -> anyhow::Result<ObjectId> {
|
||||
gix::objs::compute_hash(repo.object_hash(), gix::objs::Kind::Blob, bytes)
|
||||
.context("compute git baseline blob oid")
|
||||
}
|
||||
|
||||
fn diff_entries(
|
||||
head: &BTreeMap<String, GitBaselineFileEntry>,
|
||||
current: &BTreeMap<String, GitBaselineFileEntry>,
|
||||
) -> Vec<GitBaselineChange> {
|
||||
let mut entries = Vec::new();
|
||||
for (path, entry) in current {
|
||||
match head.get(path) {
|
||||
None => entries.push(GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Added,
|
||||
path: path.clone(),
|
||||
}),
|
||||
Some(head_entry) if head_entry != entry => entries.push(GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Modified,
|
||||
path: path.clone(),
|
||||
}),
|
||||
Some(_) => {}
|
||||
}
|
||||
}
|
||||
for path in head.keys() {
|
||||
if !current.contains_key(path) {
|
||||
entries.push(GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Deleted,
|
||||
path: path.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
entries.sort_by(|left, right| left.path.cmp(&right.path));
|
||||
entries
|
||||
}
|
||||
|
||||
fn render_unified_diff(
|
||||
repo: &gix::Repository,
|
||||
root: &Path,
|
||||
head_entries: &BTreeMap<String, GitBaselineFileEntry>,
|
||||
current_entries: &BTreeMap<String, GitBaselineFileEntry>,
|
||||
changes: &[GitBaselineChange],
|
||||
) -> anyhow::Result<String> {
|
||||
let mut rendered = String::new();
|
||||
for change in changes {
|
||||
rendered.push_str(&render_change_diff(
|
||||
repo,
|
||||
root,
|
||||
head_entries,
|
||||
current_entries,
|
||||
change,
|
||||
)?);
|
||||
}
|
||||
Ok(rendered)
|
||||
}
|
||||
|
||||
fn render_change_diff(
|
||||
repo: &gix::Repository,
|
||||
root: &Path,
|
||||
head_entries: &BTreeMap<String, GitBaselineFileEntry>,
|
||||
current_entries: &BTreeMap<String, GitBaselineFileEntry>,
|
||||
change: &GitBaselineChange,
|
||||
) -> anyhow::Result<String> {
|
||||
let old_entry = head_entries.get(&change.path);
|
||||
let new_entry = current_entries.get(&change.path);
|
||||
let old_bytes = old_entry
|
||||
.map(|entry| read_head_blob(repo, entry))
|
||||
.transpose()
|
||||
.with_context(|| format!("read HEAD content for {}", change.path))?;
|
||||
let new_bytes = new_entry
|
||||
.map(|_| read_current_file_bytes(root, &change.path))
|
||||
.transpose()
|
||||
.with_context(|| format!("read current content for {}", change.path))?;
|
||||
|
||||
let old_text = String::from_utf8_lossy(old_bytes.as_deref().unwrap_or_default());
|
||||
let new_text = String::from_utf8_lossy(new_bytes.as_deref().unwrap_or_default());
|
||||
let old_header = if old_bytes.is_some() {
|
||||
format!("a/{}", change.path)
|
||||
} else {
|
||||
"/dev/null".to_string()
|
||||
};
|
||||
let new_header = if new_bytes.is_some() {
|
||||
format!("b/{}", change.path)
|
||||
} else {
|
||||
"/dev/null".to_string()
|
||||
};
|
||||
|
||||
let mut section = format!("diff --git a/{0} b/{0}\n", change.path);
|
||||
match (old_entry, new_entry) {
|
||||
(None, Some(entry)) => {
|
||||
section.push_str(&format!("new file mode {}\n", mode_label(entry.mode)));
|
||||
}
|
||||
(Some(entry), None) => {
|
||||
section.push_str(&format!("deleted file mode {}\n", mode_label(entry.mode)));
|
||||
}
|
||||
(Some(old), Some(new)) if old.mode != new.mode => {
|
||||
section.push_str(&format!(
|
||||
"old mode {}\nnew mode {}\n",
|
||||
mode_label(old.mode),
|
||||
mode_label(new.mode)
|
||||
));
|
||||
}
|
||||
(Some(_), Some(_)) => {}
|
||||
(None, None) => return Ok(String::new()),
|
||||
}
|
||||
|
||||
let diff = TextDiff::from_lines(&old_text, &new_text)
|
||||
.unified_diff()
|
||||
.context_radius(3)
|
||||
.header(&old_header, &new_header)
|
||||
.to_string();
|
||||
section.push_str(&diff);
|
||||
if !section.ends_with('\n') {
|
||||
section.push('\n');
|
||||
}
|
||||
Ok(section)
|
||||
}
|
||||
|
||||
fn read_head_blob(repo: &gix::Repository, entry: &GitBaselineFileEntry) -> anyhow::Result<Vec<u8>> {
|
||||
anyhow::ensure!(
|
||||
repo.find_header(entry.oid)?.size() <= MAX_BASELINE_FILE_BYTES,
|
||||
"baseline blob exceeds the snapshot file limit"
|
||||
);
|
||||
let mut blob = repo.find_blob(entry.oid)?;
|
||||
Ok(blob.take_data())
|
||||
}
|
||||
|
||||
fn read_current_file_bytes(root: &Path, relative_path: &str) -> anyhow::Result<Vec<u8>> {
|
||||
let path = root.join(relative_path);
|
||||
let metadata =
|
||||
fs::symlink_metadata(&path).with_context(|| format!("stat {}", path.display()))?;
|
||||
if metadata.file_type().is_symlink() {
|
||||
let target =
|
||||
fs::read_link(&path).with_context(|| format!("read symlink {}", path.display()))?;
|
||||
Ok(path_to_bytes(&target))
|
||||
} else {
|
||||
read_baseline_file(&path)?
|
||||
.map(|(bytes, _mode)| bytes)
|
||||
.context("file grew beyond the snapshot file limit during diff")
|
||||
}
|
||||
}
|
||||
|
||||
fn mode_label(mode: EntryMode) -> &'static str {
|
||||
match mode.kind() {
|
||||
EntryKind::Blob => "100644",
|
||||
EntryKind::BlobExecutable => "100755",
|
||||
EntryKind::Link => "120000",
|
||||
EntryKind::Tree => "040000",
|
||||
EntryKind::Commit => "160000",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn file_mode(metadata: &fs::Metadata) -> EntryMode {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
if metadata.permissions().mode() & 0o111 == 0 {
|
||||
EntryKind::Blob.into()
|
||||
} else {
|
||||
EntryKind::BlobExecutable.into()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn file_mode(_metadata: &fs::Metadata) -> EntryMode {
|
||||
EntryKind::Blob.into()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn os_str_to_bstring(value: &OsStr) -> gix::bstr::BString {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
value.as_bytes().into()
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn os_str_to_bstring(value: &OsStr) -> gix::bstr::BString {
|
||||
value.to_string_lossy().as_bytes().into()
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn path_to_bytes(path: &Path) -> Vec<u8> {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
path.as_os_str().as_bytes().to_vec()
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn path_to_bytes(path: &Path) -> Vec<u8> {
|
||||
path.to_string_lossy().as_bytes().to_vec()
|
||||
}
|
||||
|
||||
fn bstr_to_path(value: &gix::bstr::BStr) -> PathBuf {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
PathBuf::from(OsStr::from_bytes(value))
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
PathBuf::from(value.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
fn relative_slash_path(root: &Path, path: &Path) -> anyhow::Result<String> {
|
||||
path.strip_prefix(root)
|
||||
.with_context(|| format!("strip {} from {}", root.display(), path.display()))
|
||||
.map(path_to_slash_string)
|
||||
}
|
||||
|
||||
fn path_to_slash_string(path: &Path) -> String {
|
||||
path.components()
|
||||
.map(|component| component.as_os_str().to_string_lossy())
|
||||
.collect::<Vec<_>>()
|
||||
.join("/")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "baseline_recovery_tests.rs"]
|
||||
mod recovery_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::process::Command;
|
||||
use tempfile::TempDir;
|
||||
|
||||
pub(super) fn git_stdout(root: &Path, args: &[&str]) -> String {
|
||||
let output = Command::new("git")
|
||||
.current_dir(root)
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("run git command");
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"git command failed: {args:?}\nstdout:\n{}\nstderr:\n{}",
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
String::from_utf8_lossy(&output.stdout).to_string()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reset_creates_fresh_baseline() {
|
||||
let home = TempDir::new().expect("tempdir");
|
||||
let root = home.path().join("repo");
|
||||
fs::create_dir_all(&root).expect("create root");
|
||||
fs::write(root.join("MEMORY.md"), "baseline").expect("write memory");
|
||||
|
||||
let oversized = root.join("large-output");
|
||||
fs::File::create(&oversized)
|
||||
.expect("create large file")
|
||||
.set_len(MAX_BASELINE_FILE_BYTES + 1)
|
||||
.expect("size large file");
|
||||
|
||||
reset_git_repository(&root).await.expect("reset repo");
|
||||
|
||||
assert!(root.join(".git").is_dir());
|
||||
assert!(root.join(".git/index").is_file());
|
||||
let diff = diff_since_latest_init(&root).await.expect("diff");
|
||||
assert!(!diff.has_changes());
|
||||
assert_eq!(diff.unified_diff, "");
|
||||
assert_eq!(
|
||||
git_stdout(&root, &["status", "--porcelain"]),
|
||||
"?? large-output\n"
|
||||
);
|
||||
assert_eq!(git_stdout(&root, &["ls-files"]), "MEMORY.md\n");
|
||||
|
||||
// An older baseline could already contain the oversized blob.
|
||||
git_stdout(&root, &["add", "large-output"]);
|
||||
git_stdout(
|
||||
&root,
|
||||
&[
|
||||
"-c",
|
||||
"user.name=Codex",
|
||||
"-c",
|
||||
"user.email=codex@example.com",
|
||||
"-c",
|
||||
"commit.gpgSign=false",
|
||||
"commit",
|
||||
"-m",
|
||||
"Legacy baseline",
|
||||
],
|
||||
);
|
||||
fs::remove_file(root.join(".git").join(BASELINE_VERSION_FILE)).expect("remove version");
|
||||
fs::write(root.join("MEMORY.md"), "pending edit").expect("edit memory");
|
||||
ensure_git_baseline_repository(&root)
|
||||
.await
|
||||
.expect("migrate legacy baseline");
|
||||
assert_eq!(
|
||||
git_stdout(&root, &["ls-tree", "-r", "--name-only", "HEAD"]),
|
||||
""
|
||||
);
|
||||
assert_eq!(git_stdout(&root, &["ls-files"]), "");
|
||||
let diff = diff_since_latest_init(&root)
|
||||
.await
|
||||
.expect("diff after migration");
|
||||
assert_eq!(
|
||||
diff.changes,
|
||||
vec![GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Added,
|
||||
path: "MEMORY.md".to_string(),
|
||||
}]
|
||||
);
|
||||
assert!(diff.unified_diff.contains("+pending edit"));
|
||||
assert_eq!(
|
||||
fs::metadata(oversized).expect("worktree file").len(),
|
||||
MAX_BASELINE_FILE_BYTES + 1
|
||||
);
|
||||
|
||||
// Phase 2 may grow a tracked input after preparation and before computing its diff.
|
||||
fs::write(root.join("memory_summary.md"), "summary").expect("write summary");
|
||||
reset_git_repository(&root)
|
||||
.await
|
||||
.expect("reset bounded baseline");
|
||||
fs::File::options()
|
||||
.write(true)
|
||||
.open(root.join("MEMORY.md"))
|
||||
.expect("open tracked")
|
||||
.set_len(MAX_BASELINE_FILE_BYTES + 1)
|
||||
.expect("grow tracked");
|
||||
let diff = diff_since_latest_init(&root)
|
||||
.await
|
||||
.expect("diff after input synchronization");
|
||||
assert_eq!(
|
||||
diff.changes,
|
||||
vec![GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Added,
|
||||
path: "memory_summary.md".to_string(),
|
||||
}]
|
||||
);
|
||||
assert_eq!(git_stdout(&root, &["ls-files"]), "");
|
||||
assert_eq!(git_stdout(&root, &["diff", "HEAD", "--stat"]), "");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn ensure_recovers_from_unborn_repository() {
|
||||
let home = TempDir::new().expect("tempdir");
|
||||
let root = home.path().join("repo");
|
||||
fs::create_dir_all(&root).expect("create root");
|
||||
fs::write(root.join("MEMORY.md"), "memory").expect("write memory");
|
||||
gix::init(&root).expect("init git repo without baseline commit");
|
||||
|
||||
ensure_git_baseline_repository(&root)
|
||||
.await
|
||||
.expect("ensure repo");
|
||||
|
||||
let diff = diff_since_latest_init(&root).await.expect("diff");
|
||||
assert_eq!(
|
||||
diff.changes,
|
||||
vec![GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Added,
|
||||
path: "MEMORY.md".to_string(),
|
||||
}]
|
||||
);
|
||||
assert_eq!(
|
||||
git_stdout(&root, &["status", "--porcelain"]),
|
||||
"?? MEMORY.md\n"
|
||||
);
|
||||
assert_eq!(git_stdout(&root, &["ls-files"]), "");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn write_index_ignores_configured_hooks_path() {
|
||||
let home = TempDir::new().expect("tempdir");
|
||||
let root = home.path().join("repo");
|
||||
let hooks_dir = root.join(".git/hooks-path-test");
|
||||
let marker_path = root.join("hook-ran");
|
||||
let hook_path = hooks_dir.join("post-index-change");
|
||||
|
||||
fs::create_dir_all(&root).expect("create root");
|
||||
fs::write(root.join("MEMORY.md"), "baseline").expect("write memory");
|
||||
reset_git_repository(&root).await.expect("reset repo");
|
||||
fs::create_dir_all(&hooks_dir).expect("create hook dir");
|
||||
akode_utils_cargo_bin::write_executable(
|
||||
&hook_path,
|
||||
&format!(
|
||||
"#!/bin/sh\nprintf ran > \"{}\"\n",
|
||||
marker_path.to_string_lossy()
|
||||
),
|
||||
)
|
||||
.expect("write post-index-change hook");
|
||||
git_stdout(
|
||||
&root,
|
||||
&[
|
||||
"config",
|
||||
"core.hooksPath",
|
||||
hooks_dir.to_string_lossy().as_ref(),
|
||||
],
|
||||
);
|
||||
|
||||
write_index_from_head(&root).expect("rewrite baseline index");
|
||||
|
||||
assert!(
|
||||
!marker_path.exists(),
|
||||
"baseline index writes should not invoke configured hook directories"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn diff_reports_added_modified_and_deleted_files() {
|
||||
let home = TempDir::new().expect("tempdir");
|
||||
let root = home.path().join("repo");
|
||||
fs::create_dir_all(root.join("rollout_summaries")).expect("create rollout summaries");
|
||||
fs::write(root.join("MEMORY.md"), "old").expect("write memory");
|
||||
fs::write(
|
||||
root.join("rollout_summaries/deleted.md"),
|
||||
"thread_id: 00000000-0000-4000-8000-000000000001\nimportant stale evidence\n",
|
||||
)
|
||||
.expect("write rollout summary");
|
||||
reset_git_repository(&root).await.expect("reset repo");
|
||||
|
||||
fs::write(root.join("MEMORY.md"), "new").expect("update memory");
|
||||
fs::write(root.join("memory_summary.md"), "summary").expect("write summary");
|
||||
fs::remove_file(root.join("rollout_summaries/deleted.md")).expect("delete summary");
|
||||
|
||||
let diff = diff_since_latest_init(&root).await.expect("diff");
|
||||
assert_eq!(
|
||||
diff.changes,
|
||||
vec![
|
||||
GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Modified,
|
||||
path: "MEMORY.md".to_string(),
|
||||
},
|
||||
GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Added,
|
||||
path: "memory_summary.md".to_string(),
|
||||
},
|
||||
GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Deleted,
|
||||
path: "rollout_summaries/deleted.md".to_string(),
|
||||
},
|
||||
]
|
||||
);
|
||||
assert!(
|
||||
diff.unified_diff
|
||||
.contains("diff --git a/MEMORY.md b/MEMORY.md")
|
||||
);
|
||||
assert!(diff.unified_diff.contains("-old"));
|
||||
assert!(diff.unified_diff.contains("+new"));
|
||||
assert!(
|
||||
diff.unified_diff
|
||||
.contains("diff --git a/memory_summary.md b/memory_summary.md")
|
||||
);
|
||||
assert!(diff.unified_diff.contains("+summary"));
|
||||
assert!(
|
||||
diff.unified_diff.contains(
|
||||
"diff --git a/rollout_summaries/deleted.md b/rollout_summaries/deleted.md"
|
||||
)
|
||||
);
|
||||
assert!(diff.unified_diff.contains("deleted file mode 100644"));
|
||||
assert!(
|
||||
diff.unified_diff
|
||||
.contains("-thread_id: 00000000-0000-4000-8000-000000000001")
|
||||
);
|
||||
assert!(diff.unified_diff.contains("-important stale evidence"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn reset_drops_previous_history() {
|
||||
let home = TempDir::new().expect("tempdir");
|
||||
let root = home.path().join("repo");
|
||||
fs::create_dir_all(&root).expect("create root");
|
||||
fs::write(root.join("MEMORY.md"), "old").expect("write memory");
|
||||
reset_git_repository(&root).await.expect("reset repo");
|
||||
|
||||
fs::write(root.join("MEMORY.md"), "new").expect("update memory");
|
||||
reset_git_repository(&root).await.expect("reset repo again");
|
||||
|
||||
let repo = gix::open(&root).expect("open repo");
|
||||
let head = repo.head_id().expect("head").detach();
|
||||
let commit = repo.find_commit(head).expect("find head commit");
|
||||
assert_eq!(commit.parent_ids().count(), 0);
|
||||
let diff = diff_since_latest_init(&root).await.expect("diff");
|
||||
assert!(!diff.has_changes());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_scan_does_not_write_added_file_blobs() {
|
||||
let home = TempDir::new().expect("tempdir");
|
||||
let root = home.path().join("repo");
|
||||
fs::create_dir_all(&root).expect("create root");
|
||||
reset_git_repository(&root).await.expect("reset repo");
|
||||
let added_content = b"new uncommitted memory";
|
||||
fs::write(root.join("MEMORY.md"), added_content).expect("write memory");
|
||||
|
||||
let diff = diff_since_latest_init(&root).await.expect("diff");
|
||||
assert!(diff.has_changes());
|
||||
|
||||
let repo = gix::open(&root).expect("open repo");
|
||||
let added_oid = blob_oid(&repo, added_content).expect("compute added oid");
|
||||
assert!(
|
||||
repo.find_blob(added_oid).is_err(),
|
||||
"status scans should hash current files without writing loose git objects"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn reports_executable_bit_changes_as_modified() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
|
||||
let home = TempDir::new().expect("tempdir");
|
||||
let root = home.path().join("repo");
|
||||
fs::create_dir_all(&root).expect("create root");
|
||||
let path = root.join("MEMORY.md");
|
||||
fs::write(&path, "same content").expect("write memory");
|
||||
reset_git_repository(&root).await.expect("reset repo");
|
||||
let mut permissions = fs::metadata(&path).expect("stat memory").permissions();
|
||||
permissions.set_mode(permissions.mode() | 0o111);
|
||||
fs::set_permissions(&path, permissions).expect("chmod memory");
|
||||
|
||||
let diff = diff_since_latest_init(&root).await.expect("diff");
|
||||
assert_eq!(
|
||||
diff.changes,
|
||||
vec![GitBaselineChange {
|
||||
status: GitBaselineChangeStatus::Modified,
|
||||
path: "MEMORY.md".to_string(),
|
||||
}]
|
||||
);
|
||||
assert!(diff.unified_diff.contains("old mode 100644"));
|
||||
assert!(diff.unified_diff.contains("new mode 100755"));
|
||||
}
|
||||
}
|
||||
119
akode-rs/git-utils/src/baseline_recovery_tests.rs
Normal file
119
akode-rs/git-utils/src/baseline_recovery_tests.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
//! Exercises cross-process serialization and retrying an interrupted baseline reset.
|
||||
|
||||
use super::baseline_control;
|
||||
use super::diff_since_latest_init;
|
||||
use super::ensure_git_baseline_repository;
|
||||
use super::reset_git_repository;
|
||||
use super::tests::git_stdout;
|
||||
use super::with_baseline_lock;
|
||||
use anyhow::Result;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::io::BufRead;
|
||||
use std::io::Read;
|
||||
use std::io::Write;
|
||||
use std::path::Path;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_operations_share_the_workspace_lock() -> Result<()> {
|
||||
const CHILD_ROOT: &str = "AKODE_TEST_BASELINE_LOCK_ROOT";
|
||||
const READY: &str = "holding workspace lock";
|
||||
if let Some(root) = std::env::var_os(CHILD_ROOT) {
|
||||
return with_baseline_lock(Path::new(&root), |_| {
|
||||
println!("{READY}");
|
||||
io::stdout().flush()?;
|
||||
io::stdin().read_exact(&mut [0])?;
|
||||
Ok(())
|
||||
})
|
||||
.await;
|
||||
}
|
||||
|
||||
let workspace = tempfile::tempdir()?;
|
||||
let root = workspace.path();
|
||||
fs::write(root.join("MEMORY.md"), "original\n")?;
|
||||
reset_git_repository(root).await?;
|
||||
fs::write(root.join("MEMORY.md"), "updated\n")?;
|
||||
|
||||
let mut child = akode_utils_process::background_command(std::env::current_exe()?)
|
||||
.args([
|
||||
"--exact",
|
||||
"baseline::recovery_tests::concurrent_operations_share_the_workspace_lock",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(CHILD_ROOT, root)
|
||||
.stdin(Stdio::piped())
|
||||
.stdout(Stdio::piped())
|
||||
.spawn()?;
|
||||
let stdout = io::BufReader::new(child.stdout.as_mut().expect("piped stdout"));
|
||||
assert!(
|
||||
stdout
|
||||
.lines()
|
||||
.any(|line| line.is_ok_and(|line| line.contains(READY))),
|
||||
"child exited before acquiring the lock"
|
||||
);
|
||||
let lock = fs::File::options()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(baseline_control(root).join("codex-baseline.lock"))?;
|
||||
let contended = matches!(lock.try_lock(), Err(fs::TryLockError::WouldBlock));
|
||||
drop(lock);
|
||||
|
||||
let reset = reset_git_repository(root);
|
||||
let ensure = ensure_git_baseline_repository(root);
|
||||
let diff = diff_since_latest_init(root);
|
||||
tokio::pin!(reset, ensure, diff);
|
||||
// Any one operation completing before the holder releases the lock is a regression.
|
||||
let completed_while_locked = tokio::select! {
|
||||
_ = &mut reset => Some("reset"),
|
||||
_ = &mut ensure => Some("ensure"),
|
||||
_ = &mut diff => Some("diff"),
|
||||
() = tokio::time::sleep(Duration::from_millis(500)) => None,
|
||||
};
|
||||
child.stdin.take().expect("piped stdin").write_all(b"x")?;
|
||||
assert!(child.wait()?.success(), "lock holder failed");
|
||||
assert!(contended, "another process must own the lock");
|
||||
assert_eq!(completed_while_locked, None);
|
||||
|
||||
let ((), (), diff) = tokio::try_join!(reset, ensure, diff)?;
|
||||
if diff.has_changes() {
|
||||
assert!(diff.unified_diff.contains("-original\n+updated"));
|
||||
}
|
||||
assert_eq!(git_stdout(root, &["show", "HEAD:MEMORY.md"]), "updated\n");
|
||||
assert_eq!(git_stdout(root, &["show", ":MEMORY.md"]), "updated\n");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn interrupted_reset_replays_working_files() -> Result<()> {
|
||||
let workspace = tempfile::tempdir()?;
|
||||
let root = workspace.path();
|
||||
let memory = root.join("MEMORY.md");
|
||||
fs::write(&memory, "original\n")?;
|
||||
reset_git_repository(root).await?;
|
||||
fs::write(&memory, "pending edit\n")?;
|
||||
|
||||
// Simulate exiting after committing the tree but before writing the index and version.
|
||||
fs::remove_file(root.join(".git").join(super::BASELINE_VERSION_FILE))?;
|
||||
fs::remove_file(root.join(".git/index"))?;
|
||||
ensure_git_baseline_repository(root).await?;
|
||||
ensure_git_baseline_repository(root).await?;
|
||||
assert_eq!(
|
||||
git_stdout(root, &["ls-tree", "-r", "--name-only", "HEAD"]),
|
||||
""
|
||||
);
|
||||
assert_eq!(git_stdout(root, &["ls-files"]), "");
|
||||
assert_eq!(fs::read_to_string(&memory)?, "pending edit\n");
|
||||
let diff = diff_since_latest_init(root).await?;
|
||||
assert_eq!(
|
||||
diff.changes,
|
||||
vec![super::GitBaselineChange {
|
||||
status: super::GitBaselineChangeStatus::Added,
|
||||
path: "MEMORY.md".to_string(),
|
||||
}]
|
||||
);
|
||||
assert!(diff.unified_diff.contains("+pending edit"));
|
||||
Ok(())
|
||||
}
|
||||
256
akode-rs/git-utils/src/branch.rs
Normal file
256
akode-rs/git-utils/src/branch.rs
Normal file
@@ -0,0 +1,256 @@
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
|
||||
use crate::GitToolingError;
|
||||
use crate::operations::ensure_git_repository;
|
||||
use crate::operations::resolve_head;
|
||||
use crate::operations::resolve_repository_root;
|
||||
use crate::operations::run_git_for_stdout;
|
||||
|
||||
/// Returns the merge-base commit between `HEAD` and the latest version between local
|
||||
/// and remote of the provided branch, if both exist.
|
||||
///
|
||||
/// The function mirrors `git merge-base HEAD <branch>` but returns `Ok(None)` when
|
||||
/// the repository has no `HEAD` yet or when the branch cannot be resolved.
|
||||
pub fn merge_base_with_head(
|
||||
repo_path: &Path,
|
||||
branch: &str,
|
||||
) -> Result<Option<String>, GitToolingError> {
|
||||
ensure_git_repository(repo_path)?;
|
||||
let repo_root = resolve_repository_root(repo_path)?;
|
||||
let head = match resolve_head(repo_root.as_path())? {
|
||||
Some(head) => head,
|
||||
None => return Ok(None),
|
||||
};
|
||||
|
||||
let Some(branch_ref) = resolve_branch_ref(repo_root.as_path(), branch)? else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
let preferred_ref =
|
||||
if let Some(upstream) = resolve_upstream_if_remote_ahead(repo_root.as_path(), branch)? {
|
||||
resolve_branch_ref(repo_root.as_path(), &upstream)?.unwrap_or(branch_ref)
|
||||
} else {
|
||||
branch_ref
|
||||
};
|
||||
|
||||
let merge_base = run_git_for_stdout(
|
||||
repo_root.as_path(),
|
||||
vec![
|
||||
OsString::from("merge-base"),
|
||||
OsString::from(head),
|
||||
OsString::from(preferred_ref),
|
||||
],
|
||||
/*env*/ None,
|
||||
)?;
|
||||
|
||||
Ok(Some(merge_base))
|
||||
}
|
||||
|
||||
fn resolve_branch_ref(repo_root: &Path, branch: &str) -> Result<Option<String>, GitToolingError> {
|
||||
let rev = run_git_for_stdout(
|
||||
repo_root,
|
||||
vec![
|
||||
OsString::from("rev-parse"),
|
||||
OsString::from("--verify"),
|
||||
OsString::from(branch),
|
||||
],
|
||||
/*env*/ None,
|
||||
);
|
||||
|
||||
match rev {
|
||||
Ok(rev) => Ok(Some(rev)),
|
||||
Err(GitToolingError::GitCommand { .. }) => Ok(None),
|
||||
Err(other) => Err(other),
|
||||
}
|
||||
}
|
||||
|
||||
fn resolve_upstream_if_remote_ahead(
|
||||
repo_root: &Path,
|
||||
branch: &str,
|
||||
) -> Result<Option<String>, GitToolingError> {
|
||||
let upstream = match run_git_for_stdout(
|
||||
repo_root,
|
||||
vec![
|
||||
OsString::from("rev-parse"),
|
||||
OsString::from("--abbrev-ref"),
|
||||
OsString::from("--symbolic-full-name"),
|
||||
OsString::from(format!("{branch}@{{upstream}}")),
|
||||
],
|
||||
/*env*/ None,
|
||||
) {
|
||||
Ok(name) => {
|
||||
let trimmed = name.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Ok(None);
|
||||
}
|
||||
trimmed.to_string()
|
||||
}
|
||||
Err(GitToolingError::GitCommand { .. }) => return Ok(None),
|
||||
Err(other) => return Err(other),
|
||||
};
|
||||
|
||||
let counts = match run_git_for_stdout(
|
||||
repo_root,
|
||||
vec![
|
||||
OsString::from("rev-list"),
|
||||
OsString::from("--left-right"),
|
||||
OsString::from("--count"),
|
||||
OsString::from(format!("{branch}...{upstream}")),
|
||||
],
|
||||
/*env*/ None,
|
||||
) {
|
||||
Ok(counts) => counts,
|
||||
Err(GitToolingError::GitCommand { .. }) => return Ok(None),
|
||||
Err(other) => return Err(other),
|
||||
};
|
||||
|
||||
let mut parts = counts.split_whitespace();
|
||||
let _left: i64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
|
||||
let right: i64 = parts.next().unwrap_or("0").parse().unwrap_or(0);
|
||||
|
||||
if right > 0 {
|
||||
Ok(Some(upstream))
|
||||
} else {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::merge_base_with_head;
|
||||
use crate::GitToolingError;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
use tempfile::tempdir;
|
||||
|
||||
fn run_git_in(repo_path: &Path, args: &[&str]) {
|
||||
let status = Command::new("git")
|
||||
.current_dir(repo_path)
|
||||
.args(args)
|
||||
.status()
|
||||
.expect("git command");
|
||||
assert!(status.success(), "git command failed: {args:?}");
|
||||
}
|
||||
|
||||
fn run_git_stdout(repo_path: &Path, args: &[&str]) -> String {
|
||||
let output = Command::new("git")
|
||||
.current_dir(repo_path)
|
||||
.args(args)
|
||||
.output()
|
||||
.expect("git command");
|
||||
assert!(output.status.success(), "git command failed: {args:?}");
|
||||
String::from_utf8_lossy(&output.stdout).trim().to_string()
|
||||
}
|
||||
|
||||
fn init_test_repo(repo_path: &Path) {
|
||||
run_git_in(repo_path, &["init", "--initial-branch=main"]);
|
||||
run_git_in(repo_path, &["config", "core.autocrlf", "false"]);
|
||||
}
|
||||
|
||||
fn commit(repo_path: &Path, message: &str) {
|
||||
run_git_in(
|
||||
repo_path,
|
||||
&[
|
||||
"-c",
|
||||
"user.name=Tester",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"commit",
|
||||
"-m",
|
||||
message,
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_base_returns_shared_commit() -> Result<(), GitToolingError> {
|
||||
let temp = tempdir()?;
|
||||
let repo = temp.path();
|
||||
init_test_repo(repo);
|
||||
|
||||
std::fs::write(repo.join("base.txt"), "base\n")?;
|
||||
run_git_in(repo, &["add", "base.txt"]);
|
||||
commit(repo, "base commit");
|
||||
|
||||
run_git_in(repo, &["checkout", "-b", "feature"]);
|
||||
std::fs::write(repo.join("feature.txt"), "feature change\n")?;
|
||||
run_git_in(repo, &["add", "feature.txt"]);
|
||||
commit(repo, "feature commit");
|
||||
|
||||
run_git_in(repo, &["checkout", "main"]);
|
||||
std::fs::write(repo.join("main.txt"), "main change\n")?;
|
||||
run_git_in(repo, &["add", "main.txt"]);
|
||||
commit(repo, "main commit");
|
||||
|
||||
run_git_in(repo, &["checkout", "feature"]);
|
||||
|
||||
let expected = run_git_stdout(repo, &["merge-base", "HEAD", "main"]);
|
||||
let merge_base = merge_base_with_head(repo, "main")?;
|
||||
assert_eq!(merge_base, Some(expected));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_base_prefers_upstream_when_remote_ahead() -> Result<(), GitToolingError> {
|
||||
let temp = tempdir()?;
|
||||
let repo = temp.path().join("repo");
|
||||
let remote = temp.path().join("remote.git");
|
||||
std::fs::create_dir_all(&repo)?;
|
||||
std::fs::create_dir_all(&remote)?;
|
||||
|
||||
run_git_in(&remote, &["init", "--bare"]);
|
||||
run_git_in(&repo, &["init", "--initial-branch=main"]);
|
||||
run_git_in(&repo, &["config", "core.autocrlf", "false"]);
|
||||
|
||||
std::fs::write(repo.join("base.txt"), "base\n")?;
|
||||
run_git_in(&repo, &["add", "base.txt"]);
|
||||
commit(&repo, "base commit");
|
||||
|
||||
run_git_in(
|
||||
&repo,
|
||||
&["remote", "add", "origin", remote.to_str().unwrap()],
|
||||
);
|
||||
run_git_in(&repo, &["push", "-u", "origin", "main"]);
|
||||
|
||||
run_git_in(&repo, &["checkout", "-b", "feature"]);
|
||||
std::fs::write(repo.join("feature.txt"), "feature change\n")?;
|
||||
run_git_in(&repo, &["add", "feature.txt"]);
|
||||
commit(&repo, "feature commit");
|
||||
|
||||
run_git_in(&repo, &["checkout", "--orphan", "rewrite"]);
|
||||
run_git_in(&repo, &["rm", "-rf", "."]);
|
||||
std::fs::write(repo.join("new-main.txt"), "rewritten main\n")?;
|
||||
run_git_in(&repo, &["add", "new-main.txt"]);
|
||||
commit(&repo, "rewrite main");
|
||||
run_git_in(&repo, &["branch", "-M", "rewrite", "main"]);
|
||||
run_git_in(&repo, &["branch", "--set-upstream-to=origin/main", "main"]);
|
||||
|
||||
run_git_in(&repo, &["checkout", "feature"]);
|
||||
run_git_in(&repo, &["fetch", "origin"]);
|
||||
|
||||
let expected = run_git_stdout(&repo, &["merge-base", "HEAD", "origin/main"]);
|
||||
let merge_base = merge_base_with_head(&repo, "main")?;
|
||||
assert_eq!(merge_base, Some(expected));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn merge_base_returns_none_when_branch_missing() -> Result<(), GitToolingError> {
|
||||
let temp = tempdir()?;
|
||||
let repo = temp.path();
|
||||
init_test_repo(repo);
|
||||
|
||||
std::fs::write(repo.join("tracked.txt"), "tracked\n")?;
|
||||
run_git_in(repo, &["add", "tracked.txt"]);
|
||||
commit(repo, "initial");
|
||||
|
||||
let merge_base = merge_base_with_head(repo, "missing-branch")?;
|
||||
assert_eq!(merge_base, None);
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
259
akode-rs/git-utils/src/diff_tests.rs
Normal file
259
akode-rs/git-utils/src/diff_tests.rs
Normal file
@@ -0,0 +1,259 @@
|
||||
//! Verifies patch compatibility and bounded, independent untracked-diff collections.
|
||||
|
||||
use super::diff_against_sha;
|
||||
use crate::GitSha;
|
||||
use akode_utils_process::background_command;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::path::Path;
|
||||
|
||||
fn git(cwd: &Path, args: &[&str]) {
|
||||
let output = background_command("git")
|
||||
.args(args)
|
||||
.current_dir(cwd)
|
||||
.output()
|
||||
.expect("run Git");
|
||||
assert!(output.status.success(), "Git {args:?} failed: {output:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn tracked_and_untracked_patches_preserve_order_and_apply() {
|
||||
let repo = tempfile::tempdir().expect("create repository");
|
||||
git(repo.path(), &["init", "-q"]);
|
||||
git(repo.path(), &["config", "core.autocrlf", "false"]);
|
||||
git(repo.path(), &["config", "core.fsmonitor", "false"]);
|
||||
std::fs::write(repo.path().join("tracked.txt"), "before\n").expect("write tracked file");
|
||||
git(repo.path(), &["add", "tracked.txt"]);
|
||||
git(
|
||||
repo.path(),
|
||||
&[
|
||||
"-c",
|
||||
"user.name=Codex Tests",
|
||||
"-c",
|
||||
"user.email=codex-tests@example.com",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
"-c",
|
||||
if cfg!(windows) {
|
||||
"core.hooksPath=NUL"
|
||||
} else {
|
||||
"core.hooksPath=/dev/null"
|
||||
},
|
||||
"commit",
|
||||
"-qm",
|
||||
"initial",
|
||||
],
|
||||
);
|
||||
let files: [(&str, &[u8]); 4] = [
|
||||
("tracked.txt", b"after\n"),
|
||||
("-new.txt", b"leading dash\n"),
|
||||
("a space.txt", b"space in filename\n"),
|
||||
("z.bin", b"\x00\x01\xffbinary\x00\xfe"),
|
||||
];
|
||||
for (name, contents) in files {
|
||||
std::fs::write(repo.path().join(name), contents).expect("write changed file");
|
||||
}
|
||||
let cwd = repo.path().to_path_buf();
|
||||
// The production caller spawns collection; this also checks its Send bound.
|
||||
let patch = tokio::spawn(async move {
|
||||
diff_against_sha(Path::new("git"), &cwd, &GitSha::new("HEAD")).await
|
||||
})
|
||||
.await
|
||||
.expect("join collection")
|
||||
.expect("collect patch");
|
||||
assert_eq!(
|
||||
patch
|
||||
.lines()
|
||||
.filter(|line| line.starts_with("diff --git "))
|
||||
.collect::<Vec<_>>(),
|
||||
vec![
|
||||
"diff --git a/tracked.txt b/tracked.txt",
|
||||
"diff --git a/-new.txt b/-new.txt",
|
||||
"diff --git a/a space.txt b/a space.txt",
|
||||
"diff --git a/z.bin b/z.bin",
|
||||
]
|
||||
);
|
||||
assert!(patch.contains("GIT binary patch"));
|
||||
git(repo.path(), &["reset", "--hard", "-q", "HEAD"]);
|
||||
for (name, _) in &files[1..] {
|
||||
std::fs::remove_file(repo.path().join(name)).expect("remove untracked file");
|
||||
}
|
||||
let patch_file = tempfile::NamedTempFile::new().expect("create patch file");
|
||||
std::fs::write(patch_file.path(), patch).expect("save patch");
|
||||
git(
|
||||
repo.path(),
|
||||
&[
|
||||
"apply",
|
||||
"--binary",
|
||||
patch_file.path().to_str().expect("patch path"),
|
||||
],
|
||||
);
|
||||
assert_eq!(
|
||||
files.map(|(name, _)| std::fs::read(repo.path().join(name)).expect("read applied file")),
|
||||
files.map(|(_, contents)| contents.to_vec())
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
struct GatedGit {
|
||||
directory: tempfile::TempDir,
|
||||
gates: Vec<std::fs::File>,
|
||||
ready: std::fs::File,
|
||||
events: futures::channel::mpsc::UnboundedReceiver<String>,
|
||||
reader: Option<std::thread::JoinHandle<()>>,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl GatedGit {
|
||||
fn new(file_counts: &[usize]) -> Self {
|
||||
use std::io::BufRead;
|
||||
|
||||
let directory = tempfile::tempdir().expect("create fixture directory");
|
||||
let ready_path = directory.path().join("ready");
|
||||
let mut paths = vec![ready_path];
|
||||
for (batch, count) in file_counts.iter().enumerate() {
|
||||
let cwd = directory.path().join(format!("batch-{batch}"));
|
||||
std::fs::create_dir(&cwd).expect("create batch directory");
|
||||
paths.extend((0..*count).map(|index| cwd.join(format!("file-{index:02}"))));
|
||||
}
|
||||
let output = background_command("mkfifo")
|
||||
.args(&paths)
|
||||
.output()
|
||||
.expect("create FIFO gates");
|
||||
assert!(output.status.success(), "mkfifo failed: {output:?}");
|
||||
let mut gates: Vec<_> = paths
|
||||
.iter()
|
||||
.map(|path| {
|
||||
// Linux permits O_RDWR on a FIFO without another opener, so cleanup
|
||||
// can always release gates even when their child has not started.
|
||||
std::fs::OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(path)
|
||||
.expect("open FIFO")
|
||||
})
|
||||
.collect();
|
||||
let ready = gates.remove(0);
|
||||
let input = ready.try_clone().expect("clone readiness FIFO");
|
||||
let (sender, events) = futures::channel::mpsc::unbounded();
|
||||
akode_utils_cargo_bin::write_executable(
|
||||
&directory.path().join("git"),
|
||||
r#"#!/bin/sh
|
||||
while [ "$1" = '-c' ]; do shift 2; done
|
||||
case "$1" in
|
||||
config) exit 1 ;;
|
||||
ls-files) for file in file-*; do printf '%s\n' "$file"; done ;;
|
||||
diff)
|
||||
case " $* " in
|
||||
*' --no-index '*)
|
||||
for file do :; done
|
||||
printf '%s/%s\n' "$PWD" "$file" > ../ready
|
||||
read -r release < "$file"
|
||||
if [ "$file" = 'file-04' ]; then printf 'failed-output\n'; exit 2; fi
|
||||
printf '%s\n' "$file"
|
||||
exit 1 ;;
|
||||
*) printf 'tracked\n' ;;
|
||||
esac ;;
|
||||
esac
|
||||
"#,
|
||||
)
|
||||
.expect("write fake Git");
|
||||
let reader = std::thread::spawn(move || {
|
||||
for line in std::io::BufReader::new(input).lines() {
|
||||
let Ok(line) = line else { break };
|
||||
if line == "stop" || sender.unbounded_send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
Self {
|
||||
directory,
|
||||
gates,
|
||||
ready,
|
||||
events,
|
||||
reader: Some(reader),
|
||||
}
|
||||
}
|
||||
|
||||
async fn ready(&mut self, batches: usize) {
|
||||
use futures::StreamExt;
|
||||
|
||||
for _ in 0..8 * batches {
|
||||
tokio::time::timeout(std::time::Duration::from_secs(3), self.events.next())
|
||||
.await
|
||||
.expect("each collection must fill its own eight slots")
|
||||
.expect("read readiness event");
|
||||
}
|
||||
}
|
||||
|
||||
fn children(&self) -> usize {
|
||||
use std::os::unix::ffi::OsStrExt;
|
||||
|
||||
let wrapper = self.directory.path().join("git");
|
||||
let mut children = std::collections::BTreeSet::new();
|
||||
for task in std::fs::read_dir("/proc/self/task").expect("list test threads") {
|
||||
let task = task.expect("read thread entry");
|
||||
if let Ok(pids) = std::fs::read_to_string(task.path().join("children")) {
|
||||
children.extend(pids.split_whitespace().map(str::to_string));
|
||||
}
|
||||
}
|
||||
children
|
||||
.into_iter()
|
||||
.filter(|pid| {
|
||||
std::fs::read(format!("/proc/{pid}/cmdline")).is_ok_and(|args| {
|
||||
args.split(|byte| *byte == 0)
|
||||
.any(|arg| arg == wrapper.as_os_str().as_bytes())
|
||||
})
|
||||
})
|
||||
.count()
|
||||
}
|
||||
|
||||
fn release(&mut self) {
|
||||
use std::io::Write;
|
||||
for gate in &mut self.gates {
|
||||
let _ = gate.write_all(b"go\n");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
impl Drop for GatedGit {
|
||||
fn drop(&mut self) {
|
||||
use std::io::Write;
|
||||
self.release();
|
||||
let _ = self.ready.write_all(b"stop\n");
|
||||
if let Some(reader) = self.reader.take() {
|
||||
reader.join().expect("join readiness reader");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[tokio::test]
|
||||
async fn untracked_collections_bound_children_independently_and_skip_failed_files() {
|
||||
// At most 16 Git children even if the bound regresses. Keeping both phases
|
||||
// in one test also prevents the fixtures from overlapping under nextest.
|
||||
for counts in [&[12][..], &[8, 8][..]] {
|
||||
let mut fixture = GatedGit::new(counts);
|
||||
let collections: Vec<_> = (0..counts.len())
|
||||
.map(|batch| {
|
||||
let git = fixture.directory.path().join("git");
|
||||
let cwd = fixture.directory.path().join(format!("batch-{batch}"));
|
||||
tokio::spawn(
|
||||
async move { diff_against_sha(&git, &cwd, &GitSha::new("HEAD")).await },
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
fixture.ready(counts.len()).await;
|
||||
let children = fixture.children();
|
||||
fixture.release();
|
||||
for (collection, count) in collections.into_iter().zip(counts) {
|
||||
let expected = "tracked\n".to_string()
|
||||
+ &(0..*count)
|
||||
.filter(|index| *index != 4)
|
||||
.map(|index| format!("file-{index:02}\n"))
|
||||
.collect::<String>();
|
||||
assert_eq!(collection.await.expect("join collection"), Some(expected));
|
||||
}
|
||||
assert_eq!(children, 8 * counts.len());
|
||||
}
|
||||
}
|
||||
35
akode-rs/git-utils/src/errors.rs
Normal file
35
akode-rs/git-utils/src/errors.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use std::path::PathBuf;
|
||||
use std::process::ExitStatus;
|
||||
use std::string::FromUtf8Error;
|
||||
|
||||
use thiserror::Error;
|
||||
use walkdir::Error as WalkdirError;
|
||||
|
||||
/// Errors returned while managing git worktree snapshots.
|
||||
#[derive(Debug, Error)]
|
||||
pub enum GitToolingError {
|
||||
#[error("git command `{command}` failed with status {status}: {stderr}")]
|
||||
GitCommand {
|
||||
command: String,
|
||||
status: ExitStatus,
|
||||
stderr: String,
|
||||
},
|
||||
#[error("git command `{command}` produced non-UTF-8 output")]
|
||||
GitOutputUtf8 {
|
||||
command: String,
|
||||
#[source]
|
||||
source: FromUtf8Error,
|
||||
},
|
||||
#[error("{path:?} is not a git repository")]
|
||||
NotAGitRepository { path: PathBuf },
|
||||
#[error("path {path:?} must be relative to the repository root")]
|
||||
NonRelativePath { path: PathBuf },
|
||||
#[error("path {path:?} escapes the repository root")]
|
||||
PathEscapesRepository { path: PathBuf },
|
||||
#[error("failed to process path inside worktree")]
|
||||
PathPrefix(#[from] std::path::StripPrefixError),
|
||||
#[error(transparent)]
|
||||
Walkdir(#[from] WalkdirError),
|
||||
#[error(transparent)]
|
||||
Io(#[from] std::io::Error),
|
||||
}
|
||||
129
akode-rs/git-utils/src/fsmonitor.rs
Normal file
129
akode-rs/git-utils/src/fsmonitor.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
//! Policy for preserving Git's built-in filesystem monitor.
|
||||
//!
|
||||
//! Codex overrides `core.fsmonitor` so repository configuration cannot select
|
||||
//! an executable helper. Preserve the built-in daemon only when the effective
|
||||
//! value is boolean true and Git advertises daemon support.
|
||||
//!
|
||||
//! The daemon avoids scanning every tracked file and untracked directory:
|
||||
//! https://github.com/git/git/blob/94f057755b7941b321fd11fec1b2e3ca5313a4e0/Documentation/git-fsmonitor--daemon.adoc#L49-L57
|
||||
//! https://github.com/git/git/blob/94f057755b7941b321fd11fec1b2e3ca5313a4e0/Documentation/git-update-index.adoc#L545-L550
|
||||
|
||||
use std::future::Future;
|
||||
|
||||
/// The safe `core.fsmonitor` override for an internal Git command.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub enum FsmonitorOverride {
|
||||
/// Disable repository-selected filesystem monitor helpers.
|
||||
Disabled,
|
||||
/// Preserve Git's built-in filesystem monitor daemon.
|
||||
BuiltIn,
|
||||
}
|
||||
|
||||
impl FsmonitorOverride {
|
||||
/// Returns the complete Git configuration override.
|
||||
pub const fn git_config_arg(self) -> &'static str {
|
||||
match self {
|
||||
Self::Disabled => "core.fsmonitor=false",
|
||||
Self::BuiltIn => "core.fsmonitor=true",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Executes the Git commands required by [`detect_fsmonitor_override`].
|
||||
///
|
||||
/// Implementations must return stdout only when Git exits successfully.
|
||||
/// Timeouts, spawn or transport failures, signal termination, and nonzero exit
|
||||
/// statuses must return `None`.
|
||||
pub trait FsmonitorProbeRunner: Send {
|
||||
/// Runs one bounded probe in the target repository.
|
||||
fn run_probe(&mut self, args: &[&str]) -> impl Future<Output = Option<Vec<u8>>> + Send;
|
||||
}
|
||||
|
||||
/// Returns the safe filesystem monitor override for the target repository.
|
||||
///
|
||||
/// This intentionally probes every time. Effective Git configuration is
|
||||
/// layered, may use conditional includes, and can change while Codex is
|
||||
/// running:
|
||||
/// https://git-scm.com/docs/git-config#SCOPES
|
||||
/// https://git-scm.com/docs/git-config#_conditional_includes
|
||||
pub async fn detect_fsmonitor_override(
|
||||
runner: &mut impl FsmonitorProbeRunner,
|
||||
) -> FsmonitorOverride {
|
||||
// A typed query converts every matching value before `--get` selects the
|
||||
// effective one. A shadowed helper path can therefore make a repository-
|
||||
// local true fail conversion. Query the raw effective value first.
|
||||
// https://github.com/git/git/blob/94f057755b7941b321fd11fec1b2e3ca5313a4e0/builtin/config.c#L482-L514
|
||||
// https://github.com/git/git/blob/94f057755b7941b321fd11fec1b2e3ca5313a4e0/builtin/config.c#L611-L614
|
||||
let Some(config) = runner
|
||||
.run_probe(&["config", "--null", "--get", "core.fsmonitor"])
|
||||
.await
|
||||
else {
|
||||
return FsmonitorOverride::Disabled;
|
||||
};
|
||||
let Some(config) = config.strip_suffix(b"\0") else {
|
||||
return FsmonitorOverride::Disabled;
|
||||
};
|
||||
if config.contains(&0) {
|
||||
return FsmonitorOverride::Disabled;
|
||||
}
|
||||
let Ok(config) = str::from_utf8(config) else {
|
||||
return FsmonitorOverride::Disabled;
|
||||
};
|
||||
|
||||
// Git accepts these case-insensitive spellings directly, as well as
|
||||
// valueless keys and nonzero integers. Ask Git to normalize uncommon
|
||||
// spellings, filtering by the raw effective value before conversion so a
|
||||
// shadowed helper pathname cannot make the query fail.
|
||||
// https://github.com/git/git/blob/94f057755b7941b321fd11fec1b2e3ca5313a4e0/parse.c#L158-L181
|
||||
// https://github.com/git/git/blob/94f057755b7941b321fd11fec1b2e3ca5313a4e0/builtin/config.c#L264-L279
|
||||
// https://github.com/git/git/blob/94f057755b7941b321fd11fec1b2e3ca5313a4e0/builtin/config.c#L496-L507
|
||||
let configured = if ["true", "yes", "on"]
|
||||
.iter()
|
||||
.any(|value| config.eq_ignore_ascii_case(value))
|
||||
{
|
||||
true
|
||||
} else if ["false", "no", "off"]
|
||||
.iter()
|
||||
.any(|value| config.eq_ignore_ascii_case(value))
|
||||
{
|
||||
false
|
||||
} else {
|
||||
let typed_args = [
|
||||
"config",
|
||||
"--null",
|
||||
"--type=bool",
|
||||
"--fixed-value",
|
||||
"--get",
|
||||
"core.fsmonitor",
|
||||
config,
|
||||
];
|
||||
matches!(
|
||||
runner.run_probe(&typed_args).await.as_deref(),
|
||||
Some(b"true\0")
|
||||
)
|
||||
};
|
||||
if !configured {
|
||||
return FsmonitorOverride::Disabled;
|
||||
}
|
||||
|
||||
// Git 2.35.1 and older interpret "true" as a hook pathname. Before Git
|
||||
// 2.26, a successful empty hook response can hide tracked changes. Require
|
||||
// the feature line Git added specifically for capability checks.
|
||||
// https://github.com/git/git/blob/94f057755b7941b321fd11fec1b2e3ca5313a4e0/Documentation/config/core.adoc#L90-L99
|
||||
// https://github.com/git/git/commit/dd77cf61a1a2fbf52c94d0cd986d555ad2ba8a4b
|
||||
let Some(build_options) = runner.run_probe(&["version", "--build-options"]).await else {
|
||||
return FsmonitorOverride::Disabled;
|
||||
};
|
||||
if build_options
|
||||
.split(|byte| *byte == b'\n')
|
||||
.any(|line| line.trim_ascii() == b"feature: fsmonitor--daemon")
|
||||
{
|
||||
FsmonitorOverride::BuiltIn
|
||||
} else {
|
||||
FsmonitorOverride::Disabled
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "fsmonitor_tests.rs"]
|
||||
mod tests;
|
||||
139
akode-rs/git-utils/src/fsmonitor_tests.rs
Normal file
139
akode-rs/git-utils/src/fsmonitor_tests.rs
Normal file
@@ -0,0 +1,139 @@
|
||||
use std::collections::VecDeque;
|
||||
use std::future::Future;
|
||||
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
use super::FsmonitorOverride;
|
||||
use super::FsmonitorProbeRunner;
|
||||
use super::detect_fsmonitor_override;
|
||||
|
||||
struct ProbeResponse {
|
||||
args: Vec<&'static str>,
|
||||
output: Option<Vec<u8>>,
|
||||
}
|
||||
|
||||
struct FakeRunner {
|
||||
responses: VecDeque<ProbeResponse>,
|
||||
}
|
||||
|
||||
impl FsmonitorProbeRunner for FakeRunner {
|
||||
fn run_probe(&mut self, args: &[&str]) -> impl Future<Output = Option<Vec<u8>>> + Send {
|
||||
let response = self.responses.pop_front().expect("missing probe response");
|
||||
assert_eq!(args, response.args);
|
||||
std::future::ready(response.output)
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn detects_supported_builtin_fsmonitor_values() {
|
||||
let cases = [
|
||||
(
|
||||
"missing config",
|
||||
vec![response(config_args(), /*output*/ None)],
|
||||
FsmonitorOverride::Disabled,
|
||||
),
|
||||
(
|
||||
"helper path",
|
||||
vec![
|
||||
response(config_args(), Some(b"/tmp/fsmonitor-helper\0")),
|
||||
response(
|
||||
typed_config_args("/tmp/fsmonitor-helper"),
|
||||
/*output*/ None,
|
||||
),
|
||||
],
|
||||
FsmonitorOverride::Disabled,
|
||||
),
|
||||
(
|
||||
"false spelling",
|
||||
vec![response(config_args(), Some(b"OFF\0"))],
|
||||
FsmonitorOverride::Disabled,
|
||||
),
|
||||
(
|
||||
"unsupported Git",
|
||||
vec![
|
||||
response(config_args(), Some(b"yes\0")),
|
||||
response(capability_args(), Some(b"")),
|
||||
],
|
||||
FsmonitorOverride::Disabled,
|
||||
),
|
||||
(
|
||||
"common true spelling",
|
||||
vec![
|
||||
response(config_args(), Some(b"On\0")),
|
||||
response(capability_args(), Some(fsmonitor_capability())),
|
||||
],
|
||||
FsmonitorOverride::BuiltIn,
|
||||
),
|
||||
(
|
||||
"numeric true",
|
||||
vec![
|
||||
response(config_args(), Some(b"2k\0")),
|
||||
response(typed_config_args("2k"), Some(b"true\0")),
|
||||
response(capability_args(), Some(fsmonitor_capability())),
|
||||
],
|
||||
FsmonitorOverride::BuiltIn,
|
||||
),
|
||||
(
|
||||
"valueless true",
|
||||
vec![
|
||||
response(config_args(), Some(b"\0")),
|
||||
response(typed_config_args(""), Some(b"true\0")),
|
||||
response(capability_args(), Some(fsmonitor_capability())),
|
||||
],
|
||||
FsmonitorOverride::BuiltIn,
|
||||
),
|
||||
(
|
||||
"explicit empty false",
|
||||
vec![
|
||||
response(config_args(), Some(b"\0")),
|
||||
response(typed_config_args(""), Some(b"false\0")),
|
||||
],
|
||||
FsmonitorOverride::Disabled,
|
||||
),
|
||||
];
|
||||
|
||||
for (name, responses, expected) in cases {
|
||||
let mut runner = FakeRunner {
|
||||
responses: responses.into(),
|
||||
};
|
||||
|
||||
let actual = detect_fsmonitor_override(&mut runner).await;
|
||||
|
||||
assert_eq!(
|
||||
(actual, runner.responses.len()),
|
||||
(expected, 0),
|
||||
"case: {name}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
fn response(args: Vec<&'static str>, output: Option<&[u8]>) -> ProbeResponse {
|
||||
ProbeResponse {
|
||||
args,
|
||||
output: output.map(<[u8]>::to_vec),
|
||||
}
|
||||
}
|
||||
|
||||
fn config_args() -> Vec<&'static str> {
|
||||
vec!["config", "--null", "--get", "core.fsmonitor"]
|
||||
}
|
||||
|
||||
fn typed_config_args(value: &'static str) -> Vec<&'static str> {
|
||||
vec![
|
||||
"config",
|
||||
"--null",
|
||||
"--type=bool",
|
||||
"--fixed-value",
|
||||
"--get",
|
||||
"core.fsmonitor",
|
||||
value,
|
||||
]
|
||||
}
|
||||
|
||||
fn capability_args() -> Vec<&'static str> {
|
||||
vec!["version", "--build-options"]
|
||||
}
|
||||
|
||||
fn fsmonitor_capability() -> &'static [u8] {
|
||||
b"feature: fsmonitor--daemon\n"
|
||||
}
|
||||
97
akode-rs/git-utils/src/git_process.rs
Normal file
97
akode-rs/git-utils/src/git_process.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
use std::process::Output;
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
|
||||
use akode_protocol::shell_environment::scrub_non_inheritable_env_vars;
|
||||
#[cfg(windows)]
|
||||
use akode_utils_pty::JobObject;
|
||||
#[cfg(unix)]
|
||||
use akode_utils_pty::process_group::kill_process_group;
|
||||
use tokio::process::Child;
|
||||
use tokio::process::Command;
|
||||
use tokio::time::timeout;
|
||||
|
||||
struct KillGitProcessTreeOnDrop {
|
||||
#[cfg(unix)]
|
||||
process_id: u32,
|
||||
#[cfg(windows)]
|
||||
job: Option<JobObject>,
|
||||
#[cfg(unix)]
|
||||
armed: bool,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl Drop for KillGitProcessTreeOnDrop {
|
||||
fn drop(&mut self) {
|
||||
if self.armed {
|
||||
let _ = kill_process_group(self.process_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn_git_command(command: &mut Command) -> Option<(Child, KillGitProcessTreeOnDrop)> {
|
||||
scrub_non_inheritable_env_vars(command.as_std_mut());
|
||||
#[cfg(unix)]
|
||||
command.process_group(0);
|
||||
command.kill_on_drop(true);
|
||||
|
||||
command
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
|
||||
#[cfg(windows)]
|
||||
let (child, job) = JobObject::spawn_background(command).ok()?;
|
||||
#[cfg(not(windows))]
|
||||
let child = command.spawn().ok()?;
|
||||
|
||||
let process_tree = KillGitProcessTreeOnDrop {
|
||||
#[cfg(unix)]
|
||||
process_id: child.id()?,
|
||||
#[cfg(windows)]
|
||||
job,
|
||||
#[cfg(unix)]
|
||||
armed: true,
|
||||
};
|
||||
|
||||
Some((child, process_tree))
|
||||
}
|
||||
|
||||
async fn wait_for_git_command_with_timeout_output(
|
||||
child: Child,
|
||||
process_tree: KillGitProcessTreeOnDrop,
|
||||
timeout_duration: Duration,
|
||||
) -> Option<Output> {
|
||||
#[cfg(unix)]
|
||||
let mut process_tree = process_tree;
|
||||
|
||||
let result = timeout(timeout_duration, child.wait_with_output()).await;
|
||||
|
||||
match result {
|
||||
Ok(Ok(output)) => {
|
||||
#[cfg(windows)]
|
||||
if let Some(job) = &process_tree.job {
|
||||
job.preserve_descendants().ok()?;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
{
|
||||
process_tree.armed = false;
|
||||
}
|
||||
Some(output)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) async fn run_git_command_with_timeout_output(
|
||||
command: &mut Command,
|
||||
timeout_duration: Duration,
|
||||
) -> Option<Output> {
|
||||
let (child, process_tree) = spawn_git_command(command)?;
|
||||
wait_for_git_command_with_timeout_output(child, process_tree, timeout_duration).await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "git_process_tests.rs"]
|
||||
mod tests;
|
||||
155
akode-rs/git-utils/src/git_process_tests.rs
Normal file
155
akode-rs/git-utils/src/git_process_tests.rs
Normal file
@@ -0,0 +1,155 @@
|
||||
use super::spawn_git_command;
|
||||
use super::wait_for_git_command_with_timeout_output;
|
||||
use pretty_assertions::assert_eq;
|
||||
#[cfg(windows)]
|
||||
use std::process::Stdio;
|
||||
use std::time::Duration;
|
||||
use tokio::process::Command;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum GitWrapperLifetime {
|
||||
WaitForChild,
|
||||
ExitBeforeTimeout,
|
||||
}
|
||||
|
||||
async fn assert_timed_out_git_wrapper_does_not_leave_child_process_running(
|
||||
wrapper_lifetime: GitWrapperLifetime,
|
||||
) {
|
||||
let temp_dir = tempfile::tempdir().expect("create temp dir");
|
||||
let child_pid_file = temp_dir.path().join("child.pid");
|
||||
let child_ready_file = temp_dir.path().join("child-ready");
|
||||
let release_child_file = temp_dir.path().join("release-child");
|
||||
let child_survived_file = temp_dir.path().join("child-survived");
|
||||
let release_wrapper_file = temp_dir.path().join("release-wrapper");
|
||||
#[cfg(unix)]
|
||||
let mut command = {
|
||||
let mut command = Command::new("/bin/sh");
|
||||
let wrapper_command = match wrapper_lifetime {
|
||||
GitWrapperLifetime::WaitForChild => {
|
||||
r#"( : > "$CHILD_READY_FILE"; while [ ! -f "$RELEASE_CHILD_FILE" ]; do sleep 0.01; done; sleep 1; : > "$CHILD_SURVIVED_FILE"; sleep 60 ) & child_pid=$!; printf '%s\n' "$child_pid" > "$CHILD_PID_FILE"; wait "$child_pid""#
|
||||
}
|
||||
GitWrapperLifetime::ExitBeforeTimeout => {
|
||||
r#"( : > "$CHILD_READY_FILE"; while [ ! -f "$RELEASE_CHILD_FILE" ]; do sleep 0.01; done; sleep 1; : > "$CHILD_SURVIVED_FILE"; sleep 60 ) & child_pid=$!; printf '%s\n' "$child_pid" > "$CHILD_PID_FILE"; while [ ! -f "$RELEASE_WRAPPER_FILE" ]; do sleep 0.01; done"#
|
||||
}
|
||||
};
|
||||
command.args(["-c", wrapper_command]);
|
||||
command
|
||||
};
|
||||
#[cfg(windows)]
|
||||
let mut command = {
|
||||
let script = temp_dir.path().join("git_wrapper.py");
|
||||
std::fs::write(
|
||||
&script,
|
||||
r#"import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
def wait_for(name):
|
||||
while not Path(os.environ[name]).exists():
|
||||
time.sleep(0.025)
|
||||
|
||||
if sys.argv[1] == "child":
|
||||
Path(os.environ["CHILD_READY_FILE"]).touch()
|
||||
wait_for("RELEASE_CHILD_FILE")
|
||||
time.sleep(1)
|
||||
Path(os.environ["CHILD_SURVIVED_FILE"]).touch()
|
||||
time.sleep(60)
|
||||
else:
|
||||
child = subprocess.Popen([sys.executable, __file__, "child"])
|
||||
Path(os.environ["CHILD_PID_FILE"]).write_text(str(child.pid))
|
||||
if sys.argv[1] == "wait":
|
||||
child.wait()
|
||||
else:
|
||||
wait_for("RELEASE_WRAPPER_FILE")
|
||||
"#,
|
||||
)
|
||||
.expect("write Git wrapper fixture");
|
||||
let mut command = Command::new("python.exe");
|
||||
command.arg(script).arg(match wrapper_lifetime {
|
||||
GitWrapperLifetime::WaitForChild => "wait",
|
||||
GitWrapperLifetime::ExitBeforeTimeout => "exit",
|
||||
});
|
||||
command
|
||||
};
|
||||
command
|
||||
.env("CHILD_PID_FILE", &child_pid_file)
|
||||
.env("CHILD_READY_FILE", &child_ready_file)
|
||||
.env("RELEASE_CHILD_FILE", &release_child_file)
|
||||
.env("CHILD_SURVIVED_FILE", &child_survived_file)
|
||||
.env("RELEASE_WRAPPER_FILE", &release_wrapper_file);
|
||||
|
||||
let (mut wrapper, process_tree) = spawn_git_command(&mut command).expect("spawn Git wrapper");
|
||||
let child_pid = tokio::time::timeout(Duration::from_secs(30), async {
|
||||
loop {
|
||||
if let Ok(child_pid) = std::fs::read_to_string(&child_pid_file)
|
||||
&& !child_pid.trim().is_empty()
|
||||
&& child_ready_file.exists()
|
||||
{
|
||||
break child_pid.trim().to_string();
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("wait for Git wrapper child readiness");
|
||||
|
||||
if matches!(wrapper_lifetime, GitWrapperLifetime::ExitBeforeTimeout) {
|
||||
std::fs::write(&release_wrapper_file, "release").expect("release Git wrapper");
|
||||
tokio::time::timeout(Duration::from_secs(10), async {
|
||||
loop {
|
||||
if wrapper
|
||||
.try_wait()
|
||||
.expect("check Git wrapper state")
|
||||
.is_some()
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("wait for Git wrapper exit");
|
||||
}
|
||||
|
||||
let output =
|
||||
wait_for_git_command_with_timeout_output(wrapper, process_tree, Duration::from_millis(100))
|
||||
.await;
|
||||
assert_eq!(output, None);
|
||||
|
||||
std::fs::write(&release_child_file, "release").expect("release Git wrapper child");
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
if !child_survived_file.exists() {
|
||||
return;
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
let _ = std::process::Command::new("kill")
|
||||
.args(["-KILL", &child_pid])
|
||||
.status();
|
||||
#[cfg(windows)]
|
||||
let _ = std::process::Command::new("taskkill")
|
||||
.args(["/PID", &child_pid, "/T", "/F"])
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::null())
|
||||
.stderr(Stdio::null())
|
||||
.status();
|
||||
panic!("Git wrapper child process {child_pid} survived timeout cleanup");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn timed_out_git_wrapper_does_not_leave_child_process_running() {
|
||||
assert_timed_out_git_wrapper_does_not_leave_child_process_running(
|
||||
GitWrapperLifetime::WaitForChild,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn timed_out_exited_git_wrapper_does_not_leave_child_process_running() {
|
||||
assert_timed_out_git_wrapper_does_not_leave_child_process_running(
|
||||
GitWrapperLifetime::ExitBeforeTimeout,
|
||||
)
|
||||
.await;
|
||||
}
|
||||
1210
akode-rs/git-utils/src/info.rs
Normal file
1210
akode-rs/git-utils/src/info.rs
Normal file
File diff suppressed because it is too large
Load Diff
59
akode-rs/git-utils/src/lib.rs
Normal file
59
akode-rs/git-utils/src/lib.rs
Normal file
@@ -0,0 +1,59 @@
|
||||
mod apply;
|
||||
mod baseline;
|
||||
mod branch;
|
||||
mod errors;
|
||||
mod fsmonitor;
|
||||
mod git_process;
|
||||
mod info;
|
||||
mod operations;
|
||||
mod platform;
|
||||
mod status;
|
||||
mod trust;
|
||||
mod worktree;
|
||||
|
||||
/// Git configuration that rejects implicitly discovered bare repositories while
|
||||
/// preserving repositories selected explicitly through `GIT_DIR` or `--git-dir`.
|
||||
pub const SAFE_BARE_REPOSITORY_CONFIG: &str = "safe.bareRepository=explicit";
|
||||
|
||||
pub use apply::ApplyGitRequest;
|
||||
pub use apply::ApplyGitResult;
|
||||
pub use apply::apply_git_patch;
|
||||
pub use apply::extract_paths_from_patch;
|
||||
pub use apply::parse_git_apply_output;
|
||||
pub use apply::stage_paths;
|
||||
pub use baseline::GitBaselineChange;
|
||||
pub use baseline::GitBaselineChangeStatus;
|
||||
pub use baseline::GitBaselineDiff;
|
||||
pub use baseline::diff_since_latest_init;
|
||||
pub use baseline::ensure_git_baseline_repository;
|
||||
pub use baseline::reset_git_repository;
|
||||
pub use branch::merge_base_with_head;
|
||||
pub use akode_protocol::SanitizedGitUrl;
|
||||
pub use akode_protocol::protocol::GitSha;
|
||||
pub use errors::GitToolingError;
|
||||
pub use fsmonitor::FsmonitorOverride;
|
||||
pub use fsmonitor::FsmonitorProbeRunner;
|
||||
pub use fsmonitor::detect_fsmonitor_override;
|
||||
pub use info::CommitLogEntry;
|
||||
pub use info::GitDiffToRemote;
|
||||
pub use info::GitInfo;
|
||||
pub use info::canonicalize_git_remote_url;
|
||||
pub use info::collect_git_info;
|
||||
pub use info::current_branch_name;
|
||||
pub use info::default_branch_name;
|
||||
pub use info::get_git_origin_url;
|
||||
pub use info::get_git_remote_urls;
|
||||
pub use info::get_git_remote_urls_assume_git_repo;
|
||||
pub use info::get_git_repo_root;
|
||||
pub use info::get_head_commit_hash;
|
||||
pub use info::git_diff_to_remote;
|
||||
pub use info::local_git_branches;
|
||||
pub use info::recent_commits;
|
||||
pub use operations::git_config_override_env;
|
||||
pub use platform::create_symlink;
|
||||
pub use status::get_has_changes_in_repo;
|
||||
pub use trust::resolve_root_git_project_for_trust;
|
||||
pub use trust::resolve_root_git_project_uri_for_trust;
|
||||
pub use worktree::RepositoryIdentity;
|
||||
pub use worktree::linked_worktree_cwds;
|
||||
pub use worktree::repository_identity;
|
||||
171
akode-rs/git-utils/src/operations.rs
Normal file
171
akode-rs/git-utils/src/operations.rs
Normal file
@@ -0,0 +1,171 @@
|
||||
use std::ffi::OsStr;
|
||||
use std::ffi::OsString;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use akode_protocol::shell_environment::scrub_non_inheritable_env_vars;
|
||||
|
||||
use crate::GitToolingError;
|
||||
|
||||
const DISABLED_HOOKS_PATH: &str = if cfg!(windows) { "NUL" } else { "/dev/null" };
|
||||
|
||||
/// Encodes Git overrides without treating equals signs in keys as separators.
|
||||
pub fn git_config_override_env(
|
||||
overrides: impl IntoIterator<Item = (String, String)>,
|
||||
) -> Vec<(String, String)> {
|
||||
let overrides: Vec<_> = overrides.into_iter().collect();
|
||||
if overrides.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let mut environment = vec![("GIT_CONFIG_COUNT".to_owned(), overrides.len().to_string())];
|
||||
for (index, (key, value)) in overrides.into_iter().enumerate() {
|
||||
environment.push((format!("GIT_CONFIG_KEY_{index}"), key));
|
||||
environment.push((format!("GIT_CONFIG_VALUE_{index}"), value));
|
||||
}
|
||||
environment
|
||||
}
|
||||
|
||||
pub(crate) fn ensure_git_repository(path: &Path) -> Result<(), GitToolingError> {
|
||||
match run_git_for_stdout(
|
||||
path,
|
||||
vec![
|
||||
OsString::from("rev-parse"),
|
||||
OsString::from("--is-inside-work-tree"),
|
||||
],
|
||||
/*env*/ None,
|
||||
) {
|
||||
Ok(output) if output.trim() == "true" => Ok(()),
|
||||
Ok(_) => Err(GitToolingError::NotAGitRepository {
|
||||
path: path.to_path_buf(),
|
||||
}),
|
||||
Err(GitToolingError::GitCommand { status, .. }) if status.code() == Some(128) => {
|
||||
Err(GitToolingError::NotAGitRepository {
|
||||
path: path.to_path_buf(),
|
||||
})
|
||||
}
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_head(path: &Path) -> Result<Option<String>, GitToolingError> {
|
||||
match run_git_for_stdout(
|
||||
path,
|
||||
vec![
|
||||
OsString::from("rev-parse"),
|
||||
OsString::from("--verify"),
|
||||
OsString::from("HEAD"),
|
||||
],
|
||||
/*env*/ None,
|
||||
) {
|
||||
Ok(sha) => Ok(Some(sha)),
|
||||
Err(GitToolingError::GitCommand { status, .. }) if status.code() == Some(128) => Ok(None),
|
||||
Err(other) => Err(other),
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_repository_root(path: &Path) -> Result<PathBuf, GitToolingError> {
|
||||
let root = run_git_for_stdout(
|
||||
path,
|
||||
vec![
|
||||
OsString::from("rev-parse"),
|
||||
OsString::from("--show-toplevel"),
|
||||
],
|
||||
/*env*/ None,
|
||||
)?;
|
||||
Ok(PathBuf::from(root))
|
||||
}
|
||||
|
||||
pub(crate) fn run_git_for_status<I, S>(
|
||||
dir: &Path,
|
||||
args: I,
|
||||
env: Option<&[(OsString, OsString)]>,
|
||||
) -> Result<(), GitToolingError>
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<OsStr>,
|
||||
{
|
||||
run_git(dir, args, env)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn run_git_for_stdout<I, S>(
|
||||
dir: &Path,
|
||||
args: I,
|
||||
env: Option<&[(OsString, OsString)]>,
|
||||
) -> Result<String, GitToolingError>
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<OsStr>,
|
||||
{
|
||||
let run = run_git(dir, args, env)?;
|
||||
String::from_utf8(run.output.stdout)
|
||||
.map(|value| value.trim().to_string())
|
||||
.map_err(|source| GitToolingError::GitOutputUtf8 {
|
||||
command: run.command,
|
||||
source,
|
||||
})
|
||||
}
|
||||
|
||||
fn run_git<I, S>(
|
||||
dir: &Path,
|
||||
args: I,
|
||||
env: Option<&[(OsString, OsString)]>,
|
||||
) -> Result<GitRun, GitToolingError>
|
||||
where
|
||||
I: IntoIterator<Item = S>,
|
||||
S: AsRef<OsStr>,
|
||||
{
|
||||
let iterator = args.into_iter();
|
||||
let (lower, upper) = iterator.size_hint();
|
||||
let mut args_vec = Vec::with_capacity(upper.unwrap_or(lower) + 4);
|
||||
args_vec.push(OsString::from("-c"));
|
||||
args_vec.push(OsString::from(crate::SAFE_BARE_REPOSITORY_CONFIG));
|
||||
// Keep internal Git helper commands independent of configured hook directories.
|
||||
args_vec.push(OsString::from("-c"));
|
||||
args_vec.push(OsString::from(format!(
|
||||
"core.hooksPath={DISABLED_HOOKS_PATH}"
|
||||
)));
|
||||
for arg in iterator {
|
||||
args_vec.push(OsString::from(arg.as_ref()));
|
||||
}
|
||||
let command_string = build_command_string(&args_vec);
|
||||
let mut command = akode_utils_process::background_command("git");
|
||||
command.current_dir(dir);
|
||||
if let Some(envs) = env {
|
||||
for (key, value) in envs {
|
||||
command.env(key, value);
|
||||
}
|
||||
}
|
||||
command.args(&args_vec);
|
||||
scrub_non_inheritable_env_vars(&mut command);
|
||||
let output = command.output()?;
|
||||
if !output.status.success() {
|
||||
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
|
||||
return Err(GitToolingError::GitCommand {
|
||||
command: command_string,
|
||||
status: output.status,
|
||||
stderr,
|
||||
});
|
||||
}
|
||||
Ok(GitRun {
|
||||
command: command_string,
|
||||
output,
|
||||
})
|
||||
}
|
||||
|
||||
fn build_command_string(args: &[OsString]) -> String {
|
||||
if args.is_empty() {
|
||||
return "git".to_string();
|
||||
}
|
||||
let joined = args
|
||||
.iter()
|
||||
.map(|arg| arg.to_string_lossy().into_owned())
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
format!("git {joined}")
|
||||
}
|
||||
|
||||
struct GitRun {
|
||||
command: String,
|
||||
output: std::process::Output,
|
||||
}
|
||||
37
akode-rs/git-utils/src/platform.rs
Normal file
37
akode-rs/git-utils/src/platform.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use std::path::Path;
|
||||
|
||||
use crate::GitToolingError;
|
||||
|
||||
#[cfg(unix)]
|
||||
pub fn create_symlink(
|
||||
_source: &Path,
|
||||
link_target: &Path,
|
||||
destination: &Path,
|
||||
) -> Result<(), GitToolingError> {
|
||||
use std::os::unix::fs::symlink;
|
||||
|
||||
symlink(link_target, destination)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
pub fn create_symlink(
|
||||
source: &Path,
|
||||
link_target: &Path,
|
||||
destination: &Path,
|
||||
) -> Result<(), GitToolingError> {
|
||||
use std::os::windows::fs::FileTypeExt;
|
||||
use std::os::windows::fs::symlink_dir;
|
||||
use std::os::windows::fs::symlink_file;
|
||||
|
||||
let metadata = std::fs::symlink_metadata(source)?;
|
||||
if metadata.file_type().is_symlink_dir() {
|
||||
symlink_dir(link_target, destination)?;
|
||||
} else {
|
||||
symlink_file(link_target, destination)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
compile_error!("codex-git symlink support is only implemented for Unix and Windows");
|
||||
83
akode-rs/git-utils/src/status.rs
Normal file
83
akode-rs/git-utils/src/status.rs
Normal file
@@ -0,0 +1,83 @@
|
||||
use std::collections::HashMap;
|
||||
use std::future::Future;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use futures::FutureExt;
|
||||
use futures::future::BoxFuture;
|
||||
use futures::future::WeakShared;
|
||||
|
||||
use crate::info::detect_local_fsmonitor_override;
|
||||
use crate::info::run_git_command_with_timeout_from;
|
||||
|
||||
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
|
||||
struct GitStatusKey {
|
||||
git: PathBuf,
|
||||
repo_root: PathBuf,
|
||||
}
|
||||
|
||||
type GitStatusFuture = BoxFuture<'static, Option<bool>>;
|
||||
|
||||
fn git_status_runs() -> &'static Mutex<HashMap<GitStatusKey, WeakShared<GitStatusFuture>>> {
|
||||
static RUNS: OnceLock<Mutex<HashMap<GitStatusKey, WeakShared<GitStatusFuture>>>> =
|
||||
OnceLock::new();
|
||||
RUNS.get_or_init(|| Mutex::new(HashMap::new()))
|
||||
}
|
||||
|
||||
pub async fn get_has_changes_in_repo(cwd: &Path, repo_root: &Path) -> Option<bool> {
|
||||
let git = PathBuf::from("git");
|
||||
let cwd = cwd.to_path_buf();
|
||||
let key = git_status_key(git.clone(), repo_root).await;
|
||||
share_git_status_run(key, move || async move {
|
||||
let fsmonitor = detect_local_fsmonitor_override(&git, &cwd).await;
|
||||
let output =
|
||||
run_git_command_with_timeout_from(&git, &["status", "--porcelain"], &cwd, fsmonitor)
|
||||
.await?;
|
||||
output.status.success().then_some(!output.stdout.is_empty())
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
async fn git_status_key(git: PathBuf, repo_root: &Path) -> GitStatusKey {
|
||||
let repo_root = tokio::fs::canonicalize(repo_root)
|
||||
.await
|
||||
.unwrap_or_else(|_| repo_root.to_path_buf());
|
||||
GitStatusKey { git, repo_root }
|
||||
}
|
||||
|
||||
async fn share_git_status_run<F, Fut>(key: GitStatusKey, run: F) -> Option<bool>
|
||||
where
|
||||
F: FnOnce() -> Fut,
|
||||
Fut: Future<Output = Option<bool>> + Send + 'static,
|
||||
{
|
||||
let result = {
|
||||
let mut runs = git_status_runs()
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner);
|
||||
if let Some(result) = runs
|
||||
.get(&key)
|
||||
.and_then(WeakShared::upgrade)
|
||||
.filter(|result| result.peek().is_none())
|
||||
{
|
||||
result
|
||||
} else {
|
||||
runs.retain(|_, result| {
|
||||
result
|
||||
.upgrade()
|
||||
.is_some_and(|result| result.peek().is_none())
|
||||
});
|
||||
let result = run().boxed().shared();
|
||||
if let Some(weak_result) = result.downgrade() {
|
||||
runs.insert(key, weak_result);
|
||||
}
|
||||
result
|
||||
}
|
||||
};
|
||||
result.await
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "status_tests.rs"]
|
||||
mod tests;
|
||||
302
akode-rs/git-utils/src/status_tests.rs
Normal file
302
akode-rs/git-utils/src/status_tests.rs
Normal file
@@ -0,0 +1,302 @@
|
||||
use std::path::PathBuf;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::AtomicUsize;
|
||||
use std::sync::atomic::Ordering;
|
||||
use std::time::Duration;
|
||||
|
||||
use futures::future::WeakShared;
|
||||
use futures::future::join_all;
|
||||
use pretty_assertions::assert_eq;
|
||||
use tempfile::TempDir;
|
||||
|
||||
use super::GitStatusKey;
|
||||
use super::get_has_changes_in_repo;
|
||||
use super::git_status_key;
|
||||
use super::git_status_runs;
|
||||
use super::share_git_status_run;
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_requests_from_sibling_directories_use_the_known_worktree_root() {
|
||||
let repository = TempDir::new().expect("create repository");
|
||||
gix::init(repository.path()).expect("initialize repository");
|
||||
let first_directory = repository.path().join("first");
|
||||
let second_directory = repository.path().join("second");
|
||||
std::fs::create_dir(&first_directory).expect("create first directory");
|
||||
std::fs::create_dir(&second_directory).expect("create second directory");
|
||||
|
||||
let results = tokio::join!(
|
||||
get_has_changes_in_repo(&first_directory, repository.path()),
|
||||
get_has_changes_in_repo(&second_directory, repository.path()),
|
||||
);
|
||||
|
||||
assert_eq!(results, (Some(false), Some(false)));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn status_keys_coalesce_symlink_aliases_of_the_same_worktree() {
|
||||
let temp_dir = TempDir::new().expect("create temp directory");
|
||||
let repository = temp_dir.path().join("repository");
|
||||
let repository_alias = temp_dir.path().join("repository-alias");
|
||||
std::fs::create_dir(&repository).expect("create repository");
|
||||
std::os::unix::fs::symlink(&repository, &repository_alias).expect("create repository alias");
|
||||
|
||||
let key = git_status_key(PathBuf::from("git"), &repository).await;
|
||||
let alias_key = git_status_key(PathBuf::from("git"), &repository_alias).await;
|
||||
|
||||
assert_eq!(key, alias_key);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn concurrent_status_requests_share_one_repository_scan() {
|
||||
let repository = TempDir::new().expect("create repository");
|
||||
let key = GitStatusKey {
|
||||
git: PathBuf::from("git"),
|
||||
repo_root: repository.path().to_path_buf(),
|
||||
};
|
||||
let scan_count = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let results = join_all((0..32).map(|_| {
|
||||
let key = key.clone();
|
||||
let scan_count = Arc::clone(&scan_count);
|
||||
share_git_status_run(key, move || async move {
|
||||
scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
Some(true)
|
||||
})
|
||||
}))
|
||||
.await;
|
||||
|
||||
assert_eq!(results, vec![Some(true); 32]);
|
||||
assert_eq!(scan_count.load(Ordering::Relaxed), 1);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn status_requests_do_not_share_different_repositories() {
|
||||
let first_repository = TempDir::new().expect("create first repository");
|
||||
let second_repository = TempDir::new().expect("create second repository");
|
||||
let scan_count = Arc::new(AtomicUsize::new(0));
|
||||
let first_key = git_status_key(PathBuf::from("git"), first_repository.path()).await;
|
||||
let second_key = git_status_key(PathBuf::from("git"), second_repository.path()).await;
|
||||
|
||||
let first_scan_count = Arc::clone(&scan_count);
|
||||
let second_scan_count = Arc::clone(&scan_count);
|
||||
let results = tokio::join!(
|
||||
share_git_status_run(first_key, move || async move {
|
||||
first_scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
Some(false)
|
||||
}),
|
||||
share_git_status_run(second_key, move || async move {
|
||||
second_scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
tokio::time::sleep(Duration::from_millis(25)).await;
|
||||
Some(true)
|
||||
}),
|
||||
);
|
||||
|
||||
assert_eq!(results, (Some(false), Some(true)));
|
||||
assert_eq!(scan_count.load(Ordering::Relaxed), 2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_status_requests_start_fresh_scans_and_prune_expired_entries() {
|
||||
let first_repository = TempDir::new().expect("create first repository");
|
||||
let first_key = GitStatusKey {
|
||||
git: PathBuf::from("git"),
|
||||
repo_root: first_repository.path().to_path_buf(),
|
||||
};
|
||||
let scan_count = Arc::new(AtomicUsize::new(0));
|
||||
|
||||
let first_scan_count = Arc::clone(&scan_count);
|
||||
assert_eq!(
|
||||
share_git_status_run(first_key.clone(), move || async move {
|
||||
first_scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
Some(true)
|
||||
})
|
||||
.await,
|
||||
Some(true)
|
||||
);
|
||||
|
||||
let second_scan_count = Arc::clone(&scan_count);
|
||||
assert_eq!(
|
||||
share_git_status_run(first_key.clone(), move || async move {
|
||||
second_scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
Some(false)
|
||||
})
|
||||
.await,
|
||||
Some(false)
|
||||
);
|
||||
assert_eq!(scan_count.load(Ordering::Relaxed), 2);
|
||||
|
||||
let second_repository = TempDir::new().expect("create second repository");
|
||||
let third_scan_count = Arc::clone(&scan_count);
|
||||
assert_eq!(
|
||||
share_git_status_run(
|
||||
GitStatusKey {
|
||||
git: PathBuf::from("git"),
|
||||
repo_root: second_repository.path().to_path_buf(),
|
||||
},
|
||||
move || async move {
|
||||
third_scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
Some(true)
|
||||
},
|
||||
)
|
||||
.await,
|
||||
Some(true)
|
||||
);
|
||||
assert_eq!(scan_count.load(Ordering::Relaxed), 3);
|
||||
assert!(
|
||||
!git_status_runs()
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.contains_key(&first_key)
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn completed_status_requests_are_not_reused_while_a_consumer_retains_them() {
|
||||
let repository = TempDir::new().expect("create repository");
|
||||
let key = GitStatusKey {
|
||||
git: PathBuf::from("git"),
|
||||
repo_root: repository.path().to_path_buf(),
|
||||
};
|
||||
let scan_count = Arc::new(AtomicUsize::new(0));
|
||||
let (release_sender, release_receiver) = tokio::sync::oneshot::channel();
|
||||
|
||||
let first_key = key.clone();
|
||||
let first_scan_count = Arc::clone(&scan_count);
|
||||
let first = tokio::spawn(async move {
|
||||
share_git_status_run(first_key, move || async move {
|
||||
first_scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
release_receiver.await.ok()?;
|
||||
Some(true)
|
||||
})
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
let retained_result = git_status_runs()
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(&key)
|
||||
.and_then(WeakShared::upgrade)
|
||||
.expect("retain the pending shared status scan");
|
||||
|
||||
release_sender.send(()).expect("release shared status scan");
|
||||
assert_eq!(first.await.expect("status task completed"), Some(true));
|
||||
assert_eq!(retained_result.peek(), Some(&Some(true)));
|
||||
|
||||
let second_scan_count = Arc::clone(&scan_count);
|
||||
let result = share_git_status_run(key, move || async move {
|
||||
second_scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
Some(false)
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(result, Some(false));
|
||||
assert_eq!(scan_count.load(Ordering::Relaxed), 2);
|
||||
assert_eq!(retained_result.peek(), Some(&Some(true)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn canceling_one_consumer_preserves_the_shared_status_scan() {
|
||||
let repository = TempDir::new().expect("create repository");
|
||||
let key = GitStatusKey {
|
||||
git: PathBuf::from("git"),
|
||||
repo_root: repository.path().to_path_buf(),
|
||||
};
|
||||
let scan_count = Arc::new(AtomicUsize::new(0));
|
||||
let (release_sender, release_receiver) = tokio::sync::oneshot::channel();
|
||||
|
||||
let first_key = key.clone();
|
||||
let first_scan_count = Arc::clone(&scan_count);
|
||||
let first = tokio::spawn(async move {
|
||||
share_git_status_run(first_key, move || async move {
|
||||
first_scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
release_receiver.await.ok()?;
|
||||
Some(true)
|
||||
})
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
|
||||
let second_key = key.clone();
|
||||
let second_scan_count = Arc::clone(&scan_count);
|
||||
let second = tokio::spawn(async move {
|
||||
share_git_status_run(second_key, move || async move {
|
||||
second_scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
Some(false)
|
||||
})
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
second.abort();
|
||||
assert!(
|
||||
second
|
||||
.await
|
||||
.expect_err("consumer was canceled")
|
||||
.is_cancelled()
|
||||
);
|
||||
assert_eq!(scan_count.load(Ordering::Relaxed), 1);
|
||||
|
||||
release_sender.send(()).expect("release shared status scan");
|
||||
assert_eq!(first.await.expect("status task completed"), Some(true));
|
||||
assert!(
|
||||
git_status_runs()
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(&key)
|
||||
.and_then(WeakShared::upgrade)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn canceling_the_last_consumer_allows_a_fresh_status_scan() {
|
||||
let repository = TempDir::new().expect("create repository");
|
||||
let key = GitStatusKey {
|
||||
git: PathBuf::from("git"),
|
||||
repo_root: repository.path().to_path_buf(),
|
||||
};
|
||||
let scan_count = Arc::new(AtomicUsize::new(0));
|
||||
let first_key = key.clone();
|
||||
let first_scan_count = Arc::clone(&scan_count);
|
||||
|
||||
let first = tokio::spawn(async move {
|
||||
share_git_status_run(first_key, move || async move {
|
||||
first_scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
std::future::pending::<Option<bool>>().await
|
||||
})
|
||||
.await
|
||||
});
|
||||
|
||||
tokio::task::yield_now().await;
|
||||
assert_eq!(scan_count.load(Ordering::Relaxed), 1);
|
||||
first.abort();
|
||||
assert!(
|
||||
first
|
||||
.await
|
||||
.expect_err("consumer was canceled")
|
||||
.is_cancelled()
|
||||
);
|
||||
|
||||
let second_scan_count = Arc::clone(&scan_count);
|
||||
let result = share_git_status_run(key.clone(), move || async move {
|
||||
second_scan_count.fetch_add(1, Ordering::Relaxed);
|
||||
Some(false)
|
||||
})
|
||||
.await;
|
||||
|
||||
assert_eq!(result, Some(false));
|
||||
assert_eq!(scan_count.load(Ordering::Relaxed), 2);
|
||||
assert!(
|
||||
git_status_runs()
|
||||
.lock()
|
||||
.unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
.get(&key)
|
||||
.and_then(WeakShared::upgrade)
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
250
akode-rs/git-utils/src/trust.rs
Normal file
250
akode-rs/git-utils/src/trust.rs
Normal file
@@ -0,0 +1,250 @@
|
||||
//! Resolve repository trust roots through local or remote filesystem access.
|
||||
|
||||
use akode_file_system::ExecutorFileSystem;
|
||||
use akode_file_system::FindUpErrorPolicy;
|
||||
use akode_file_system::find_nearest_ancestor_with_markers;
|
||||
use akode_file_system::find_nearest_native_ancestor_with_markers;
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
use akode_utils_path_uri::PathUri;
|
||||
|
||||
const MAX_GIT_METADATA_FILE_BYTES: u64 = 64 * 1024;
|
||||
|
||||
/// Resolve the path that should be used for trust checks. Similar to
|
||||
/// [`crate::get_git_repo_root`], but resolves to the root of the main
|
||||
/// repository. Handles worktrees via filesystem inspection without invoking
|
||||
/// the `git` executable.
|
||||
pub async fn resolve_root_git_project_for_trust(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
cwd: &AbsolutePathBuf,
|
||||
) -> Option<AbsolutePathBuf> {
|
||||
match resolve_root(fs, TrustPath::Native(cwd.clone())).await? {
|
||||
TrustPath::Native(root) => Some(root),
|
||||
TrustPath::Uri(_) => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Resolve the main repository's trust root using the executor's path convention.
|
||||
///
|
||||
/// Uses existing filesystem operations so this also works with independently
|
||||
/// deployed executors. Native callers should use [`resolve_root_git_project_for_trust`]
|
||||
/// to preserve paths whose URI representation is opaque.
|
||||
pub async fn resolve_root_git_project_uri_for_trust(
|
||||
fs: &dyn ExecutorFileSystem,
|
||||
cwd: &PathUri,
|
||||
) -> Option<PathUri> {
|
||||
resolve_root(fs, TrustPath::Uri(cwd.clone()))
|
||||
.await
|
||||
.map(|root| root.uri())
|
||||
}
|
||||
|
||||
// Keep native ancestry native: an opaque URI cannot supply parents or children.
|
||||
// Everything after ancestry discovery shares the same repository validation.
|
||||
#[derive(Clone)]
|
||||
enum TrustPath {
|
||||
Native(AbsolutePathBuf),
|
||||
Uri(PathUri),
|
||||
}
|
||||
|
||||
impl TrustPath {
|
||||
fn uri(&self) -> PathUri {
|
||||
match self {
|
||||
Self::Native(path) => PathUri::from_abs_path(path),
|
||||
Self::Uri(path) => path.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn parent(&self) -> Option<Self> {
|
||||
match self {
|
||||
Self::Native(path) => path.parent().map(Self::Native),
|
||||
Self::Uri(path) => path.parent().map(Self::Uri),
|
||||
}
|
||||
}
|
||||
|
||||
fn join(&self, component: &str) -> Option<Self> {
|
||||
match self {
|
||||
Self::Native(path) => Some(Self::Native(path.join(component))),
|
||||
Self::Uri(path) => path.join(component).ok().map(Self::Uri),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn resolve_root(fs: &dyn ExecutorFileSystem, cwd: TrustPath) -> Option<TrustPath> {
|
||||
let cwd_uri = cwd.uri();
|
||||
let base = match fs
|
||||
.get_metadata(&cwd_uri, Default::default(), /*sandbox*/ None)
|
||||
.await
|
||||
{
|
||||
Ok(metadata) if metadata.is_directory => cwd.clone(),
|
||||
_ => cwd.parent()?,
|
||||
};
|
||||
let mut base = base;
|
||||
let repo_root = loop {
|
||||
let candidate = match &base {
|
||||
TrustPath::Native(path) => find_nearest_native_ancestor_with_markers(
|
||||
fs,
|
||||
path,
|
||||
vec![".git".to_string()],
|
||||
FindUpErrorPolicy::Ignore,
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.ok()?
|
||||
.map(TrustPath::Native)?,
|
||||
TrustPath::Uri(path) => TrustPath::Uri(
|
||||
find_nearest_ancestor_with_markers(
|
||||
fs,
|
||||
path,
|
||||
vec![".git".to_string()],
|
||||
FindUpErrorPolicy::Ignore,
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.ok()??,
|
||||
),
|
||||
};
|
||||
let dot_git = candidate.join(".git")?;
|
||||
let metadata = fs
|
||||
.get_metadata(&dot_git.uri(), Default::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
if !metadata.is_directory
|
||||
|| fs
|
||||
.get_metadata(
|
||||
&dot_git.join("HEAD")?.uri(),
|
||||
Default::default(),
|
||||
/*sandbox*/ None,
|
||||
)
|
||||
.await
|
||||
.is_ok()
|
||||
{
|
||||
break candidate;
|
||||
}
|
||||
base = candidate.parent()?;
|
||||
};
|
||||
let dot_git_uri = repo_root.join(".git")?.uri();
|
||||
let dot_git_metadata = fs
|
||||
.get_metadata(&dot_git_uri, Default::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
if dot_git_metadata.is_directory {
|
||||
return Some(repo_root);
|
||||
}
|
||||
if !dot_git_metadata.is_file
|
||||
|| dot_git_metadata.is_symlink
|
||||
|| dot_git_metadata.size > MAX_GIT_METADATA_FILE_BYTES
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
let git_dir_uri = read_gitdir_file(fs, &dot_git_uri).await?;
|
||||
let git_dir_path = match &repo_root {
|
||||
TrustPath::Native(_) => TrustPath::Native(git_dir_uri.to_abs_path().ok()?),
|
||||
TrustPath::Uri(_) => TrustPath::Uri(git_dir_uri.clone()),
|
||||
};
|
||||
let git_dir_metadata = fs
|
||||
.get_metadata(&git_dir_uri, Default::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
if !git_dir_metadata.is_directory || git_dir_metadata.is_symlink {
|
||||
return None;
|
||||
}
|
||||
|
||||
let canonical_git_dir_uri = fs.canonicalize(&git_dir_uri, /*sandbox*/ None).await.ok()?;
|
||||
let worktrees_dir_uri = canonical_git_dir_uri.parent()?;
|
||||
if worktrees_dir_uri.basename().as_deref() != Some("worktrees") {
|
||||
return None;
|
||||
}
|
||||
let common_dir_uri = worktrees_dir_uri.parent()?;
|
||||
let worktree_gitdir_uri = canonical_git_dir_uri.join("gitdir").ok()?;
|
||||
let commondir_uri = canonical_git_dir_uri.join("commondir").ok()?;
|
||||
let (worktree_gitdir_bytes, commondir_bytes) = tokio::join!(
|
||||
read_metadata_file(fs, &worktree_gitdir_uri),
|
||||
read_metadata_file(fs, &commondir_uri),
|
||||
);
|
||||
let worktree_gitdir_bytes = worktree_gitdir_bytes?;
|
||||
let worktree_gitdir = worktree_gitdir_bytes.trim_ascii();
|
||||
if worktree_gitdir.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let worktree_dot_git_uri = canonical_git_dir_uri
|
||||
.join_native_bytes(worktree_gitdir)
|
||||
.ok()?;
|
||||
if worktree_dot_git_uri.basename().as_deref() != Some(".git") {
|
||||
return None;
|
||||
}
|
||||
let commondir_bytes = commondir_bytes?;
|
||||
let commondir = commondir_bytes.trim_ascii();
|
||||
if commondir.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let linked_common_dir_uri = canonical_git_dir_uri.join_native_bytes(commondir).ok()?;
|
||||
let registered_checkout_uri = worktree_dot_git_uri.parent()?;
|
||||
let checkout_uri = repo_root.uri();
|
||||
// Compare checkout directories, not the final .git entries. Following a
|
||||
// substituted .git symlink must never turn an unrelated checkout into the
|
||||
// registered one, even if it is swapped after the metadata check above.
|
||||
let (registered_checkout, checkout, linked_common_dir) = tokio::join!(
|
||||
fs.canonicalize(®istered_checkout_uri, /*sandbox*/ None),
|
||||
fs.canonicalize(&checkout_uri, /*sandbox*/ None),
|
||||
fs.canonicalize(&linked_common_dir_uri, /*sandbox*/ None),
|
||||
);
|
||||
// PathUri equality folds Windows ASCII case, but even Windows directories
|
||||
// can be case-sensitive. Canonical filesystem identities must match exactly.
|
||||
if registered_checkout.ok()?.to_url() != checkout.ok()?.to_url()
|
||||
|| linked_common_dir.ok()?.to_url() != common_dir_uri.to_url()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
// Preserve the existing trust key (including path aliases), but prove that
|
||||
// its main checkout actually owns the canonical common directory. A main
|
||||
// checkout made with --separate-git-dir may have a regular .git pointer.
|
||||
let common_dir = git_dir_path.parent()?.parent()?;
|
||||
let main_root = common_dir.parent()?;
|
||||
let main_dot_git_uri = main_root.join(".git")?.uri();
|
||||
let main_metadata = fs
|
||||
.get_metadata(&main_dot_git_uri, Default::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
let main_git_dir_uri = if main_metadata.is_directory {
|
||||
main_dot_git_uri
|
||||
} else {
|
||||
read_gitdir_file(fs, &main_dot_git_uri).await?
|
||||
};
|
||||
if fs
|
||||
.canonicalize(&main_git_dir_uri, /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?
|
||||
.to_url()
|
||||
!= common_dir_uri.to_url()
|
||||
{
|
||||
return None;
|
||||
}
|
||||
Some(main_root)
|
||||
}
|
||||
|
||||
async fn read_gitdir_file(fs: &dyn ExecutorFileSystem, path: &PathUri) -> Option<PathUri> {
|
||||
let contents = read_metadata_file(fs, path).await?;
|
||||
let target = contents.trim_ascii().strip_prefix(b"gitdir:")?.trim_ascii();
|
||||
if target.is_empty() {
|
||||
return None;
|
||||
}
|
||||
path.parent()?.join_native_bytes(target).ok()
|
||||
}
|
||||
|
||||
async fn read_metadata_file(fs: &dyn ExecutorFileSystem, path: &PathUri) -> Option<Vec<u8>> {
|
||||
let metadata = fs
|
||||
.get_metadata(path, Default::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
if !metadata.is_file || metadata.is_symlink || metadata.size > MAX_GIT_METADATA_FILE_BYTES {
|
||||
return None;
|
||||
}
|
||||
// Keep using fs/readFile for independently deployed older exec-servers.
|
||||
// Their streaming fs/open API is not universally available yet.
|
||||
let bytes = fs
|
||||
.read_file(path, Default::default(), /*sandbox*/ None)
|
||||
.await
|
||||
.ok()?;
|
||||
(bytes.len() as u64 <= MAX_GIT_METADATA_FILE_BYTES).then_some(bytes)
|
||||
}
|
||||
178
akode-rs/git-utils/src/worktree.rs
Normal file
178
akode-rs/git-utils/src/worktree.rs
Normal file
@@ -0,0 +1,178 @@
|
||||
//! Resolves repository identity and sibling checkouts from validated Git metadata.
|
||||
//! Administrative links must agree before a checkout participates in discovery.
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::ffi::OsStr;
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use akode_utils_absolute_path::AbsolutePathBuf;
|
||||
|
||||
use crate::get_git_repo_root;
|
||||
|
||||
/// The stable on-disk identity shared by a repository and its linked worktrees.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct RepositoryIdentity {
|
||||
/// Canonical shared Git administrative directory.
|
||||
pub common_dir: AbsolutePathBuf,
|
||||
/// Directory within the current checkout, preserved across linked worktrees.
|
||||
pub relative_cwd: PathBuf,
|
||||
/// Canonical root of the repository's primary checkout.
|
||||
pub primary_root: AbsolutePathBuf,
|
||||
}
|
||||
|
||||
fn canonicalize_native(path: impl AsRef<Path>) -> Option<PathBuf> {
|
||||
AbsolutePathBuf::from_absolute_path(path)
|
||||
.ok()?
|
||||
.canonicalize()
|
||||
.ok()
|
||||
.map(AbsolutePathBuf::into_path_buf)
|
||||
}
|
||||
|
||||
/// Identifies a checkout without executing Git or trusting unchecked administrative links.
|
||||
pub fn repository_identity(cwd: &Path) -> Option<RepositoryIdentity> {
|
||||
let canonical_cwd = canonicalize_native(cwd)?;
|
||||
if !canonical_cwd.is_dir() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let checkout_root = canonicalize_native(get_git_repo_root(&canonical_cwd)?)?;
|
||||
let relative_cwd = canonical_cwd
|
||||
.strip_prefix(&checkout_root)
|
||||
.ok()?
|
||||
.to_path_buf();
|
||||
let git_entry = checkout_root.join(".git");
|
||||
let entry_type = fs::symlink_metadata(&git_entry).ok()?.file_type();
|
||||
if entry_type.is_symlink() {
|
||||
return None;
|
||||
}
|
||||
|
||||
let common_dir = if entry_type.is_dir() {
|
||||
canonicalize_native(&git_entry)?
|
||||
} else if entry_type.is_file() {
|
||||
let git_dir = read_git_path(&git_entry, &checkout_root, "gitdir:")?;
|
||||
if !git_dir.is_dir() {
|
||||
return None;
|
||||
}
|
||||
let common_dir = read_git_path(&git_dir.join("commondir"), &git_dir, "")?;
|
||||
if !common_dir.is_dir() {
|
||||
return None;
|
||||
}
|
||||
let registered_root = canonicalize_native(common_dir.join("worktrees"))?;
|
||||
if git_dir.parent()? != registered_root {
|
||||
return None;
|
||||
}
|
||||
let backlink = read_git_path(&git_dir.join("gitdir"), &git_dir, "")?;
|
||||
if backlink != canonicalize_native(&git_entry)? {
|
||||
return None;
|
||||
}
|
||||
common_dir
|
||||
} else {
|
||||
return None;
|
||||
};
|
||||
|
||||
let primary_root = common_dir.parent()?.to_path_buf();
|
||||
let primary_git_entry = primary_root.join(".git");
|
||||
let primary_entry_type = fs::symlink_metadata(&primary_git_entry).ok()?.file_type();
|
||||
if !primary_entry_type.is_dir()
|
||||
|| primary_entry_type.is_symlink()
|
||||
|| canonicalize_native(primary_git_entry)? != common_dir
|
||||
{
|
||||
return None;
|
||||
}
|
||||
|
||||
Some(RepositoryIdentity {
|
||||
common_dir: AbsolutePathBuf::from_absolute_path_checked(common_dir).ok()?,
|
||||
relative_cwd,
|
||||
primary_root: AbsolutePathBuf::from_absolute_path_checked(primary_root).ok()?,
|
||||
})
|
||||
}
|
||||
|
||||
/// Returns corresponding existing directories in the current, primary, and linked checkouts.
|
||||
pub fn linked_worktree_cwds(cwd: &Path) -> Option<Vec<PathBuf>> {
|
||||
let identity = repository_identity(cwd)?;
|
||||
let current_cwd = canonicalize_native(cwd)?;
|
||||
let mut result = vec![cwd.to_path_buf()];
|
||||
let mut seen = HashSet::from([cwd.to_path_buf()]);
|
||||
if seen.insert(current_cwd.clone()) {
|
||||
result.push(current_cwd);
|
||||
}
|
||||
|
||||
append_linked_cwd(&mut result, &mut seen, &identity.primary_root, &identity);
|
||||
|
||||
let worktrees = identity.common_dir.join("worktrees");
|
||||
if !worktrees.exists() {
|
||||
return Some(result);
|
||||
}
|
||||
let worktrees = canonicalize_native(worktrees)?;
|
||||
let mut registered: Vec<_> = fs::read_dir(&worktrees)
|
||||
.ok()?
|
||||
.filter_map(Result::ok)
|
||||
.filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
|
||||
.collect();
|
||||
registered.sort_by_key(std::fs::DirEntry::file_name);
|
||||
|
||||
for entry in registered {
|
||||
let Some(git_dir) = canonicalize_native(entry.path()) else {
|
||||
continue;
|
||||
};
|
||||
if git_dir.parent() != Some(worktrees.as_path()) {
|
||||
continue;
|
||||
}
|
||||
let Some(git_file) = read_git_path(&git_dir.join("gitdir"), &git_dir, "") else {
|
||||
continue;
|
||||
};
|
||||
if git_file.file_name() != Some(OsStr::new(".git")) {
|
||||
continue;
|
||||
}
|
||||
let Some(checkout_root) = git_file.parent() else {
|
||||
continue;
|
||||
};
|
||||
append_linked_cwd(&mut result, &mut seen, checkout_root, &identity);
|
||||
}
|
||||
|
||||
Some(result)
|
||||
}
|
||||
|
||||
fn append_linked_cwd(
|
||||
result: &mut Vec<PathBuf>,
|
||||
seen: &mut HashSet<PathBuf>,
|
||||
checkout_root: &Path,
|
||||
identity: &RepositoryIdentity,
|
||||
) {
|
||||
let Some(checkout_root) = canonicalize_native(checkout_root) else {
|
||||
return;
|
||||
};
|
||||
let Some(candidate) = canonicalize_native(checkout_root.join(&identity.relative_cwd)) else {
|
||||
return;
|
||||
};
|
||||
if !candidate.is_dir() || !candidate.starts_with(&checkout_root) {
|
||||
return;
|
||||
}
|
||||
let Some(candidate_identity) = repository_identity(&candidate) else {
|
||||
return;
|
||||
};
|
||||
if candidate_identity.common_dir == identity.common_dir
|
||||
&& candidate_identity.relative_cwd == identity.relative_cwd
|
||||
&& seen.insert(candidate.clone())
|
||||
{
|
||||
result.push(candidate);
|
||||
}
|
||||
}
|
||||
|
||||
fn read_git_path(path: &Path, relative_to: &Path, prefix: &str) -> Option<PathBuf> {
|
||||
if !fs::symlink_metadata(path).ok()?.file_type().is_file() {
|
||||
return None;
|
||||
}
|
||||
let contents = fs::read_to_string(path).ok()?;
|
||||
let value = contents.trim().strip_prefix(prefix)?.trim();
|
||||
if value.is_empty() || value.contains('\n') || value.contains('\r') {
|
||||
return None;
|
||||
}
|
||||
canonicalize_native(relative_to.join(value))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "worktree_tests.rs"]
|
||||
mod tests;
|
||||
97
akode-rs/git-utils/src/worktree_tests.rs
Normal file
97
akode-rs/git-utils/src/worktree_tests.rs
Normal file
@@ -0,0 +1,97 @@
|
||||
//! Validates repository identity and discovery across linked checkout layouts.
|
||||
|
||||
use super::*;
|
||||
use pretty_assertions::assert_eq;
|
||||
|
||||
fn repository_with_linked_checkout() -> (tempfile::TempDir, PathBuf, PathBuf) {
|
||||
let root = tempfile::tempdir().expect("temporary repository");
|
||||
let primary = root.path().join("primary");
|
||||
let linked = root.path().join("linked");
|
||||
let admin = primary.join(".git").join("worktrees").join("linked");
|
||||
fs::create_dir_all(primary.join("nested")).expect("primary nested directory");
|
||||
fs::create_dir_all(linked.join("nested")).expect("linked nested directory");
|
||||
fs::create_dir_all(&admin).expect("worktree administrative directory");
|
||||
fs::write(primary.join(".git/HEAD"), "ref: refs/heads/main\n")
|
||||
.expect("primary repository HEAD");
|
||||
fs::write(admin.join("commondir"), "../..\n").expect("common directory");
|
||||
fs::write(
|
||||
admin.join("gitdir"),
|
||||
format!("{}\n", linked.join(".git").display()),
|
||||
)
|
||||
.expect("linked checkout backlink");
|
||||
fs::write(
|
||||
linked.join(".git"),
|
||||
format!("gitdir: {}\n", admin.display()),
|
||||
)
|
||||
.expect("linked checkout git file");
|
||||
(root, primary, linked)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repository_identity_is_shared_by_primary_and_linked_checkouts() {
|
||||
let (_root, primary, linked) = repository_with_linked_checkout();
|
||||
let primary_cwd = canonicalize_native(primary.join("nested")).expect("primary cwd");
|
||||
let linked_cwd = canonicalize_native(linked.join("nested")).expect("linked cwd");
|
||||
let expected = RepositoryIdentity {
|
||||
common_dir: AbsolutePathBuf::from_absolute_path_checked(
|
||||
canonicalize_native(primary.join(".git")).expect("common git directory"),
|
||||
)
|
||||
.expect("absolute common directory"),
|
||||
relative_cwd: PathBuf::from("nested"),
|
||||
primary_root: AbsolutePathBuf::from_absolute_path_checked(
|
||||
canonicalize_native(&primary).expect("primary checkout"),
|
||||
)
|
||||
.expect("absolute primary checkout"),
|
||||
};
|
||||
|
||||
assert_eq!(repository_identity(&primary_cwd), Some(expected.clone()));
|
||||
assert_eq!(repository_identity(&linked_cwd), Some(expected));
|
||||
assert_eq!(
|
||||
linked_worktree_cwds(&linked_cwd),
|
||||
Some(vec![linked_cwd, primary_cwd])
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn linked_worktree_discovery_preserves_logical_working_directory_aliases() {
|
||||
let (root, primary, linked) = repository_with_linked_checkout();
|
||||
let alias = root.path().join("primary-alias");
|
||||
std::os::unix::fs::symlink(&primary, &alias).expect("checkout alias");
|
||||
let logical_cwd = alias.join("nested");
|
||||
let canonical_cwd = fs::canonicalize(primary.join("nested")).expect("primary cwd");
|
||||
let linked_cwd = fs::canonicalize(linked.join("nested")).expect("linked cwd");
|
||||
|
||||
assert_eq!(
|
||||
linked_worktree_cwds(&logical_cwd),
|
||||
Some(vec![logical_cwd, canonical_cwd, linked_cwd])
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn linked_worktree_discovery_rejects_mismatched_backlinks() {
|
||||
let (_root, primary, linked) = repository_with_linked_checkout();
|
||||
let primary_cwd = canonicalize_native(primary.join("nested")).expect("primary cwd");
|
||||
let admin = primary.join(".git").join("worktrees").join("linked");
|
||||
fs::write(
|
||||
admin.join("gitdir"),
|
||||
primary.join(".git").display().to_string(),
|
||||
)
|
||||
.expect("invalid worktree backlink");
|
||||
|
||||
assert_eq!(repository_identity(&linked.join("nested")), None);
|
||||
assert_eq!(linked_worktree_cwds(&primary_cwd), Some(vec![primary_cwd]));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn linked_worktree_discovery_rejects_relative_directory_symlink_escapes() {
|
||||
let (root, primary, linked) = repository_with_linked_checkout();
|
||||
let primary_cwd = fs::canonicalize(primary.join("nested")).expect("primary cwd");
|
||||
let outside = root.path().join("outside");
|
||||
fs::create_dir(&outside).expect("outside directory");
|
||||
fs::remove_dir(linked.join("nested")).expect("remove linked nested directory");
|
||||
std::os::unix::fs::symlink(&outside, linked.join("nested")).expect("escaping symlink");
|
||||
|
||||
assert_eq!(linked_worktree_cwds(&primary_cwd), Some(vec![primary_cwd]));
|
||||
}
|
||||
Reference in New Issue
Block a user