Make /diff worktree-wide from subdirectories (#65094)

## Why

Running `/diff` from a subdirectory can omit untracked files elsewhere in
the worktree. With `diff.relative` enabled, it can also omit unstaged
changes to tracked files outside that subdirectory.

## What changed

Run Git from the discovered worktree root while retaining the session
directory for permission resolution. Pin the Git directory and worktree so
relative Git environment settings keep resolving to the same repository.

Decode Git's quoted untracked paths before generating patches. If a path
cannot be represented as UTF-8, warn that the diff is incomplete and
continue with the remaining files.

## Testing

Cover matching output from the root and a subdirectory with
`diff.relative` enabled and with an explicit Git directory and worktree.
Cover quoted UTF-8 filenames and warnings for invalid UTF-8 paths.

GitOrigin-RevId: 7dd604f543976f4ba88ae0facf9e9b573baa9c0f
This commit is contained in:
Eric Traut
2026-12-01 21:56:27 +00:00
committed by copyberry
parent 30fdd9bd68
commit 997204b7f9
3 changed files with 163 additions and 74 deletions
+1
View File
@@ -52,6 +52,7 @@ pub use info::git_diff_to_remote;
pub use info::local_git_branches;
pub use info::observe_git_remote_urls;
pub use info::recent_commits;
pub use operations::decode_git_path;
pub use operations::git_config_override_env;
pub use platform::create_symlink;
pub use status::GitWorktreeStatus;
+10
View File
@@ -9,6 +9,16 @@ use crate::GitToolingError;
const DISABLED_HOOKS_PATH: &str = if cfg!(windows) { "NUL" } else { "/dev/null" };
/// Decode one Git C-quoted path for a text-only command argument.
/// Reject invalid UTF-8 instead of substituting a different filename.
pub fn decode_git_path(line: &str) -> Option<String> {
let (bytes, consumed) = gix::quote::ansi_c::undo(line.into()).ok()?;
if consumed != line.len() {
return None;
}
std::str::from_utf8(bytes.as_ref()).ok().map(str::to_owned)
}
/// Encodes Git overrides without treating equals signs in keys as separators.
pub fn git_config_override_env(
overrides: impl IntoIterator<Item = (String, String)>,
+152 -74
View File
@@ -1,4 +1,4 @@
//! Utility to compute the current Git diff for the working directory.
//! Compute the unstaged Git diff and untracked patches relative to the worktree root.
//!
//! The implementation mirrors the behaviour of the TypeScript version in
//! `codex-cli`: it returns the diff for tracked changes as well as any
@@ -13,6 +13,7 @@ use crate::workspace_command::WorkspaceCommandExecutor;
use crate::workspace_command::WorkspaceCommandOutput;
use codex_git_utils::FsmonitorOverride;
use codex_git_utils::FsmonitorProbeRunner;
use codex_git_utils::decode_git_path;
use codex_git_utils::detect_fsmonitor_override;
const DIFF_COMMAND_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30);
@@ -21,6 +22,19 @@ const DISABLE_HOOKS_CONFIG: &str = if cfg!(windows) {
} else {
"core.hooksPath=/dev/null"
};
const WORKTREE_PROBE: &[&str] = &[
"rev-parse",
"--is-inside-work-tree",
"--show-cdup",
"--absolute-git-dir",
];
const UNTRACKED_LIST: &[&str] = &[
"-c",
"core.quotePath=true",
"ls-files",
"--others",
"--exclude-standard",
];
const EXECUTABLE_FILTER_CONFIG_PATTERN: &str = r"^filter\..*\.(clean|process)$";
// `/diff` may execute Git through a remote workspace, so git-utils owns the
@@ -29,12 +43,15 @@ const EXECUTABLE_FILTER_CONFIG_PATTERN: &str = r"^filter\..*\.(clean|process)$";
struct DiffCommands<'a> {
runner: &'a dyn WorkspaceCommandExecutor,
cwd: &'a Path,
root_args: Vec<String>,
permission_profile: Option<&'a str>,
}
impl DiffCommands<'_> {
fn command(&self, argv: impl IntoIterator<Item = impl Into<String>>) -> WorkspaceCommand {
let mut command = WorkspaceCommand::new(argv, self.cwd.to_path_buf());
// Keep the session cwd for permission resolution. Only Git changes directory.
command.argv.splice(1..1, self.root_args.iter().cloned());
if let Some(profile) = self.permission_profile {
command.permission_profile = Some(profile.to_owned());
// A thread profile can grant network access outside the application's
@@ -83,12 +100,13 @@ pub(crate) async fn get_git_diff(
let mut commands = DiffCommands {
runner,
cwd,
root_args: Vec::new(),
permission_profile,
};
// First check if we are inside a Git repository.
if !inside_git_repo(&commands).await? {
let Some(root_args) = worktree_root_args(&commands).await? else {
return Ok((false, String::new()));
}
};
commands.root_args = root_args;
// Probe once per `/diff` and reuse the result for all subsequent Git commands.
let fsmonitor = detect_fsmonitor_override(&mut commands).await;
@@ -109,17 +127,21 @@ pub(crate) async fn get_git_diff(
"--color",
]
),
run_git_capture_stdout(
&commands,
fsmonitor,
&["ls-files", "--others", "--exclude-standard", "-z"]
),
run_git_capture_stdout(&commands, fsmonitor, UNTRACKED_LIST),
);
let mut diff = tracked_diff_res?.stdout;
let untracked_output = untracked_output_res?;
let mut warnings = String::new();
for file in untracked_output.split_terminator('\0') {
// The workspace runner decodes stdout as text. Keep the listing ASCII
// until each pathname can be decoded independently and without loss.
for line in untracked_output.lines() {
let Some(file) = decode_git_path(line) else {
warnings.push_str(&format!(
"Warning: incomplete diff. Unsupported untracked path {line}.\n"
));
continue;
};
// Git lists untracked nested repositories as directories.
if file.ends_with('/') {
continue;
@@ -135,7 +157,7 @@ pub(crate) async fn get_git_diff(
"--",
// Git recognizes /dev/null even on Windows. The workspace may be remote.
"/dev/null",
file,
&file,
];
let output =
run_git_capture_diff(&commands, fsmonitor, &diff_config_overrides, &args).await?;
@@ -233,17 +255,13 @@ async fn diff_filter_config_overrides(
.collect())
}
/// Determine if the current directory is inside a Git repository.
async fn inside_git_repo(commands: &DiffCommands<'_>) -> Result<bool, String> {
/// Pin the discovered repository when changing Git's directory. Relative
/// GIT_DIR and GIT_WORK_TREE would otherwise be reinterpreted after -C.
async fn worktree_root_args(commands: &DiffCommands<'_>) -> Result<Option<Vec<String>>, String> {
// `rev-parse` does not inspect the worktree, and probing before this check
// would also run extra Git commands outside repositories.
let output = run_git_command(
commands,
FsmonitorOverride::Disabled,
&[],
&["rev-parse", "--is-inside-work-tree"],
)
.await?;
let output =
run_git_command(commands, FsmonitorOverride::Disabled, &[], WORKTREE_PROBE).await?;
// Exit 128 also covers inaccessible worktree metadata. Recognize the
// ordinary discovery miss and preserve other (including localized) diagnostics.
let stderr = output.stderr.trim_end();
@@ -257,7 +275,27 @@ async fn inside_git_repo(commands: &DiffCommands<'_>) -> Result<bool, String> {
output.exit_code,
));
}
Ok(output.success())
let mut fields = output.stdout.splitn(3, '\n');
if !output.success() || fields.next() != Some("true") {
return Ok(None);
}
let Some(root) = fields.next() else {
return Err("git rev-parse did not return the worktree root".to_string());
};
if root.is_empty() {
return Ok(Some(Vec::new()));
}
let git_dir = fields
.next()
.and_then(|dir| dir.strip_suffix('\n'))
.filter(|dir| !dir.is_empty())
.ok_or_else(|| "git rev-parse did not return the Git directory".to_string())?;
Ok(Some(vec![
"-C".to_string(),
root.to_string(),
format!("--git-dir={git_dir}"),
"--work-tree=.".to_string(),
]))
}
async fn run_git_command(
@@ -382,10 +420,7 @@ mod tests {
async fn get_git_diff_returns_not_git_for_non_git_cwd() {
let cwd = PathBuf::from("/workspace");
let mut probe = response(
git_command(
FsmonitorOverride::Disabled,
&["rev-parse", "--is-inside-work-tree"],
),
git_command(FsmonitorOverride::Disabled, WORKTREE_PROBE),
/*exit_code*/ 128,
"",
);
@@ -401,10 +436,7 @@ mod tests {
#[tokio::test]
async fn get_git_diff_preserves_profiled_worktree_discovery_errors() {
let mut probe = response(
git_command(
FsmonitorOverride::Disabled,
&["rev-parse", "--is-inside-work-tree"],
),
git_command(FsmonitorOverride::Disabled, WORKTREE_PROBE),
/*exit_code*/ 128,
"",
);
@@ -425,12 +457,9 @@ mod tests {
let cwd = PathBuf::from("/workspace");
let runner = FakeRunner::new(vec![
response(
git_command(
FsmonitorOverride::Disabled,
&["rev-parse", "--is-inside-work-tree"],
),
git_command(FsmonitorOverride::Disabled, WORKTREE_PROBE),
/*exit_code*/ 0,
"true\n",
"true\n\n/workspace/.git\n",
),
response(
git_probe_command(&["config", "--null", "--get", "core.fsmonitor"]),
@@ -480,12 +509,9 @@ mod tests {
"tracked\n",
),
response(
git_command(
FsmonitorOverride::Disabled,
&["ls-files", "--others", "--exclude-standard", "-z"],
),
git_command(FsmonitorOverride::Disabled, UNTRACKED_LIST),
/*exit_code*/ 0,
"new.txt\0",
"new.txt\n",
),
response(
git_command(
@@ -544,16 +570,13 @@ mod tests {
};
let mut missing = response(untracked("gone.txt"), /*exit_code*/ 1, "");
missing.output.stderr = "error: Could not access 'gone.txt'\n".into();
let mut patch = response(untracked("new.txt"), /*exit_code*/ 1, "untracked\n");
let mut patch = response(untracked("bad-é"), /*exit_code*/ 1, "untracked\n");
patch.output.stderr = "warning: LF will be replaced by CRLF\n".into();
let runner = FakeRunner::new(vec![
response(
git_command(
FsmonitorOverride::Disabled,
&["rev-parse", "--is-inside-work-tree"],
),
git_command(FsmonitorOverride::Disabled, WORKTREE_PROBE),
/*exit_code*/ 0,
"true\n",
"true\n\n/workspace/.git\n",
),
response(
git_probe_command(&["config", "--null", "--get", "core.fsmonitor"]),
@@ -595,12 +618,9 @@ mod tests {
"tracked\n",
),
response(
git_command(
FsmonitorOverride::BuiltIn,
&["ls-files", "--others", "--exclude-standard", "-z"],
),
git_command(FsmonitorOverride::BuiltIn, UNTRACKED_LIST),
/*exit_code*/ 0,
"gone.txt\0new.txt\0",
"gone.txt\n\"bad-\\351\"\n\"bad-\\303\\251\"\n",
),
missing,
patch,
@@ -612,6 +632,7 @@ mod tests {
assert!(is_repo);
insta::assert_snapshot!(diff, @r#"
Warning: incomplete diff. Could not compare "gone.txt".
Warning: incomplete diff. Unsupported untracked path "bad-\351".
tracked
untracked
"#);
@@ -623,12 +644,9 @@ mod tests {
let cwd = PathBuf::from("/workspace");
let runner = FakeRunner::new(vec![
response(
git_command(
FsmonitorOverride::Disabled,
&["rev-parse", "--is-inside-work-tree"],
),
git_command(FsmonitorOverride::Disabled, WORKTREE_PROBE),
/*exit_code*/ 0,
"true\n",
"true\n\n/workspace/.git\n",
),
response(
git_probe_command(&["config", "--null", "--get", "core.fsmonitor"]),
@@ -665,10 +683,7 @@ mod tests {
"tracked\n",
),
response(
git_command(
FsmonitorOverride::Disabled,
&["ls-files", "--others", "--exclude-standard", "-z"],
),
git_command(FsmonitorOverride::Disabled, UNTRACKED_LIST),
/*exit_code*/ 0,
"",
),
@@ -685,12 +700,9 @@ mod tests {
let cwd = PathBuf::from("/workspace");
let runner = FakeRunner::new(vec![
response(
git_command(
FsmonitorOverride::Disabled,
&["rev-parse", "--is-inside-work-tree"],
),
git_command(FsmonitorOverride::Disabled, WORKTREE_PROBE),
/*exit_code*/ 0,
"true\n",
"true\n\n/workspace/.git\n",
),
response(
git_probe_command(&["config", "--null", "--get", "core.fsmonitor"]),
@@ -727,10 +739,7 @@ mod tests {
"",
),
response(
git_command(
FsmonitorOverride::Disabled,
&["ls-files", "--others", "--exclude-standard", "-z"],
),
git_command(FsmonitorOverride::Disabled, UNTRACKED_LIST),
/*exit_code*/ 0,
"",
),
@@ -747,6 +756,61 @@ mod tests {
assert_command_metadata(&runner.commands(), &cwd);
}
#[cfg(unix)]
#[tokio::test]
async fn subdirectory_diff_matches_worktree_root() {
let repo = tempfile::tempdir().unwrap();
let root = repo.path();
// The directory prefix must survive untracked path parsing verbatim.
let src = root.join(" src");
fs::create_dir(&src).unwrap();
run_git_setup(root, &["init", "-q"]);
run_git_setup(root, &["config", "diff.relative", "true"]);
run_git_setup(root, &["config", "core.quotePath", "false"]);
fs::write(root.join("same.txt"), "before\n").unwrap();
fs::write(src.join("tracked.txt"), "before\n").unwrap();
run_git_setup(root, &["add", "same.txt", " src/tracked.txt"]);
fs::write(root.join("outside-猫.txt"), "outside\n").unwrap();
let (_, diff) = get_git_diff(&LOCAL_RUNNER, &src, /*permission_profile*/ None)
.await
.unwrap();
assert!(diff.contains("outside-猫.txt"));
fs::write(root.join("same.txt"), "edited\n").unwrap();
fs::write(src.join("tracked.txt"), "edited\n").unwrap();
fs::write(src.join("same.txt"), "created\n").unwrap();
let from_root = get_git_diff(&LOCAL_RUNNER, root, /*permission_profile*/ None)
.await
.unwrap();
let from_src = get_git_diff(&LOCAL_RUNNER, &src, /*permission_profile*/ None)
.await
.unwrap();
assert_eq!(from_src, from_root);
let explicit = LocalRunner {
explicit_worktree: Some(root.to_path_buf()),
};
assert_eq!(
get_git_diff(&explicit, &src, /*permission_profile*/ None)
.await
.unwrap(),
from_root
);
let headers = from_src
.1
.lines()
.map(|line| codex_ansi_escape::ansi_escape_line(line).to_string())
.filter(|line| line.starts_with("diff --git"))
.collect::<Vec<_>>()
.join("\n");
insta::assert_snapshot!(headers, @r"
diff --git a/ src/tracked.txt b/ src/tracked.txt
diff --git a/same.txt b/same.txt
diff --git a/ src/same.txt b/ src/same.txt
diff --git a/outside-猫.txt b/outside-猫.txt
");
}
#[cfg(unix)]
#[tokio::test]
async fn get_git_diff_with_thread_permissions_does_not_fetch_missing_blobs() {
@@ -767,7 +831,7 @@ mod tests {
);
fs::write(repo.join("missing"), "changed").unwrap();
get_git_diff(&LocalRunner, repo, Some(":workspace"))
get_git_diff(&LOCAL_RUNNER, repo, Some(":workspace"))
.await
.expect_err("missing blob");
assert!(!repo.join("fetched").exists());
@@ -792,7 +856,7 @@ mod tests {
run_git_setup(&repo, &["commit", "-qm", "initial"]);
assert_eq!(
get_git_diff(&LocalRunner, &repo, /*permission_profile*/ None).await,
get_git_diff(&LOCAL_RUNNER, &repo, /*permission_profile*/ None).await,
Ok((true, String::new()))
);
@@ -843,7 +907,7 @@ mod tests {
fs::write(repo.join(" café.txt"), "new work\n").expect("create untracked file");
run_git_setup(&repo, &["init", "-q", "nested"]);
let result = get_git_diff(&LocalRunner, &repo, /*permission_profile*/ None)
let result = get_git_diff(&LOCAL_RUNNER, &repo, /*permission_profile*/ None)
.await
.expect("generate diff without invoking helpers");
@@ -911,7 +975,7 @@ mod tests {
std::thread::sleep(Duration::from_secs(/*secs*/ 1));
fs::write(checkout.join("tracked.txt"), "before\n").expect("refresh child tracked file");
let result = get_git_diff(&LocalRunner, &repo, /*permission_profile*/ None)
let result = get_git_diff(&LOCAL_RUNNER, &repo, /*permission_profile*/ None)
.await
.expect("generate diff without inspecting submodule worktrees");
@@ -984,6 +1048,7 @@ mod tests {
let output = ProcessCommand::new("git")
.args(args)
.current_dir(cwd)
.env("GIT_CONFIG_GLOBAL", "/dev/null")
.output()
.expect("run git setup command");
assert_eq!(
@@ -1071,7 +1136,14 @@ mod tests {
}
#[cfg(unix)]
struct LocalRunner;
const LOCAL_RUNNER: LocalRunner = LocalRunner {
explicit_worktree: None,
};
#[cfg(unix)]
struct LocalRunner {
explicit_worktree: Option<PathBuf>,
}
#[cfg(unix)]
impl WorkspaceCommandExecutor for LocalRunner {
@@ -1087,7 +1159,13 @@ mod tests {
> {
Box::pin(async move {
let mut process = ProcessCommand::new(&command.argv[0]);
process.args(&command.argv[1..]).current_dir(command.cwd);
process
.args(&command.argv[1..])
.current_dir(command.cwd)
.env("GIT_CONFIG_GLOBAL", "/dev/null");
if let Some(root) = &self.explicit_worktree {
process.env("GIT_DIR", "../.git").env("GIT_WORK_TREE", root);
}
for (key, value) in command.env {
match value {
Some(value) => {