mirror of
https://github.com/openai/codex.git
synced 2026-12-03 00:41:03 +00:00
Show staged changes in /diff (#65211)
## Why `/diff` skipped staged patches, so users could miss changes that would go into their next commit. ## What changed Compare the index with `HEAD` and the working tree with the index. Show the staged patch under **Staged** and, when both are present, put the remaining patches under **Unstaged and untracked**. Keep Git operations local and show a warning alongside the working-tree patches if the staged comparison fails. ## Testing Cover staged files before the first commit and a staged edit that is reversed in the working tree. The tests also cover the staged comparison warning, missing blobs without a fetch, and the refreshed sidebar rendering both sections. GitOrigin-RevId: 2cb032d7766caf313363eb4c330abb3f6a95f017
This commit is contained in:
@@ -83,10 +83,11 @@ async fn slash_diff_opens_one_reader_and_only_the_latest_result_updates_it() ->
|
||||
assert!(refreshing.contains("Refreshing…"));
|
||||
assert!(refreshing.contains("+const FEE: u32 = 7;"));
|
||||
app.focus_workspace_composer(&mut tui);
|
||||
let updated = patch.replace("= 7", "= 8");
|
||||
let updated =
|
||||
crate::get_git_diff::format_diff(patch, patch.replace("= 7", "= 8").replace("= 5", "= 7"));
|
||||
boxed_future!(app.handle_event(&mut tui, &mut server, complete(refresh, &updated))).await?;
|
||||
assert_eq!(app.panel_focus(), Some(PaneFocus::Main));
|
||||
let split = side_frame(&mut app, &mut tui, wide)?;
|
||||
let split = side_frame(&mut app, &mut tui, Size { height: 14, ..wide })?;
|
||||
assert!(!split.contains("Refreshing…"));
|
||||
let sidebar_text = |frame: &str| {
|
||||
frame
|
||||
|
||||
+7
-5
@@ -32,16 +32,18 @@ Refreshing at 42 columns
|
||||
|
||||
Refreshed beside chat
|
||||
Diff × + ›
|
||||
Staged
|
||||
diff --git a/fees.rs b/fees.rs
|
||||
@@ -1 +1 @@
|
||||
-const FEE: u32 = 5;
|
||||
+const FEE: u32 = 7;
|
||||
|
||||
Unstaged and untracked
|
||||
diff --git a/fees.rs b/fees.rs
|
||||
@@ -1 +1 @@
|
||||
-const FEE: u32 = 7;
|
||||
+const FEE: u32 = 8;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
⌃x s focus sidebar
|
||||
|
||||
Refreshing a clean tree beside chat
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
//! 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
|
||||
//! untracked files. When the current directory is not inside a Git
|
||||
//! repository, the function returns `Ok((false, String::new()))`.
|
||||
//! Collect staged, unstaged, and untracked patches relative to the worktree root for `/diff`.
|
||||
//! Both comparisons are needed even when the working tree matches the last commit.
|
||||
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
@@ -16,6 +12,14 @@ use codex_git_utils::FsmonitorProbeRunner;
|
||||
use codex_git_utils::decode_git_path;
|
||||
use codex_git_utils::detect_fsmonitor_override;
|
||||
|
||||
const DIFF_ARGS: &[&str] = &[
|
||||
"diff",
|
||||
"--no-textconv",
|
||||
"--no-ext-diff",
|
||||
"--submodule=short",
|
||||
"--ignore-submodules=dirty",
|
||||
"--color",
|
||||
];
|
||||
const DIFF_COMMAND_TIMEOUT: Duration = Duration::from_secs(/*secs*/ 30);
|
||||
const DISABLE_HOOKS_CONFIG: &str = if cfg!(windows) {
|
||||
"core.hooksPath=NUL"
|
||||
@@ -49,17 +53,15 @@ struct DiffCommands<'a> {
|
||||
|
||||
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 Git local regardless of the session's network permissions. Deny all
|
||||
// transports for older Git versions that ignore GIT_NO_LAZY_FETCH.
|
||||
let mut command = WorkspaceCommand::new(argv, self.cwd.to_path_buf())
|
||||
.env("GIT_NO_LAZY_FETCH", "1")
|
||||
.env("GIT_ALLOW_PROTOCOL", "");
|
||||
// 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
|
||||
// destination policy. Keep Git local even on older versions that
|
||||
// ignore GIT_NO_LAZY_FETCH by denying all transport protocols.
|
||||
command = command
|
||||
.env("GIT_NO_LAZY_FETCH", "1")
|
||||
.env("GIT_ALLOW_PROTOCOL", "");
|
||||
}
|
||||
command
|
||||
}
|
||||
@@ -113,26 +115,23 @@ pub(crate) async fn get_git_diff(
|
||||
|
||||
// Keep `/diff` informational: repository configuration must not select executable diff helpers.
|
||||
let diff_config_overrides = diff_filter_config_overrides(&commands, fsmonitor).await?;
|
||||
let (tracked_diff_res, untracked_output_res) = tokio::join!(
|
||||
run_git_capture_diff(
|
||||
&commands,
|
||||
fsmonitor,
|
||||
&diff_config_overrides,
|
||||
&[
|
||||
"diff",
|
||||
"--no-textconv",
|
||||
"--no-ext-diff",
|
||||
"--submodule=short",
|
||||
"--ignore-submodules=dirty",
|
||||
"--color",
|
||||
]
|
||||
),
|
||||
let (unstaged, staged, untracked) = tokio::join!(
|
||||
run_git_capture_diff(&commands, fsmonitor, &diff_config_overrides, &[]),
|
||||
run_git_capture_diff(&commands, fsmonitor, &diff_config_overrides, &["--cached"]),
|
||||
run_git_capture_stdout(&commands, fsmonitor, UNTRACKED_LIST),
|
||||
);
|
||||
let mut diff = tracked_diff_res?.stdout;
|
||||
let untracked_output = untracked_output_res?;
|
||||
let mut working_tree = unstaged?.stdout;
|
||||
let untracked_output = untracked?;
|
||||
|
||||
let mut warnings = String::new();
|
||||
// A partial clone may lack a HEAD blob needed only for the staged comparison.
|
||||
let staged = match staged {
|
||||
Ok(output) => output.stdout,
|
||||
Err(_) => {
|
||||
warnings.push_str("Warning: incomplete diff. Staged changes are unavailable.\n");
|
||||
String::new()
|
||||
}
|
||||
};
|
||||
// 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() {
|
||||
@@ -146,19 +145,8 @@ pub(crate) async fn get_git_diff(
|
||||
if file.ends_with('/') {
|
||||
continue;
|
||||
}
|
||||
let args = [
|
||||
"diff",
|
||||
"--no-textconv",
|
||||
"--no-ext-diff",
|
||||
"--submodule=short",
|
||||
"--ignore-submodules=dirty",
|
||||
"--color",
|
||||
"--no-index",
|
||||
"--",
|
||||
// Git recognizes /dev/null even on Windows. The workspace may be remote.
|
||||
"/dev/null",
|
||||
&file,
|
||||
];
|
||||
// Git recognizes /dev/null even on Windows. The workspace may be remote.
|
||||
let args = ["--no-index", "--", "/dev/null", &file];
|
||||
let output =
|
||||
run_git_capture_diff(&commands, fsmonitor, &diff_config_overrides, &args).await?;
|
||||
// An input can disappear between ls-files and diff. Keep the other patches visible.
|
||||
@@ -167,13 +155,27 @@ pub(crate) async fn get_git_diff(
|
||||
"Warning: incomplete diff. Could not compare {file:?}.\n"
|
||||
));
|
||||
}
|
||||
diff.push_str(&output.stdout);
|
||||
working_tree.push_str(&output.stdout);
|
||||
}
|
||||
|
||||
let mut diff = format_diff(&staged, working_tree);
|
||||
diff.insert_str(0, &warnings);
|
||||
Ok((true, diff))
|
||||
}
|
||||
|
||||
pub(crate) fn format_diff(staged: &str, working_tree: String) -> String {
|
||||
if staged.is_empty() {
|
||||
return working_tree;
|
||||
}
|
||||
|
||||
let mut diff = format!("\x1b[1mStaged\x1b[0m\n{staged}");
|
||||
if !working_tree.is_empty() {
|
||||
diff.push_str("\n\x1b[1mUnstaged and untracked\x1b[0m\n");
|
||||
diff.push_str(&working_tree);
|
||||
}
|
||||
diff
|
||||
}
|
||||
|
||||
/// Helper that executes `git` with the given `args` and returns `stdout` as a
|
||||
/// UTF-8 string. Any non-zero exit status is considered an *error*.
|
||||
async fn run_git_capture_stdout(
|
||||
@@ -199,7 +201,8 @@ async fn run_git_capture_diff(
|
||||
config_overrides: &[(String, String)],
|
||||
args: &[&str],
|
||||
) -> Result<WorkspaceCommandOutput, String> {
|
||||
let output = run_git_command(commands, fsmonitor, config_overrides, args).await?;
|
||||
let args = [DIFF_ARGS, args].concat();
|
||||
let output = run_git_command(commands, fsmonitor, config_overrides, &args).await?;
|
||||
if output.success() || output.exit_code == 1 {
|
||||
Ok(output)
|
||||
} else {
|
||||
@@ -341,15 +344,23 @@ mod tests {
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::VecDeque;
|
||||
#[cfg(unix)]
|
||||
use std::fs;
|
||||
use std::future::Future;
|
||||
use std::path::PathBuf;
|
||||
use std::pin::Pin;
|
||||
#[cfg(unix)]
|
||||
use std::process::Command as ProcessCommand;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const STAGED_ARGS: &[&str] = &[
|
||||
"diff",
|
||||
"--no-textconv",
|
||||
"--no-ext-diff",
|
||||
"--submodule=short",
|
||||
"--ignore-submodules=dirty",
|
||||
"--color",
|
||||
"--cached",
|
||||
];
|
||||
|
||||
#[tokio::test]
|
||||
async fn diff_profile_after_live_reattachment() -> color_eyre::Result<()> {
|
||||
use crate::app_server_session::ResumeModelSettings;
|
||||
@@ -508,6 +519,11 @@ mod tests {
|
||||
/*exit_code*/ 1,
|
||||
"tracked\n",
|
||||
),
|
||||
response(
|
||||
git_command(FsmonitorOverride::Disabled, STAGED_ARGS),
|
||||
/*exit_code*/ 128,
|
||||
"",
|
||||
),
|
||||
response(
|
||||
git_command(FsmonitorOverride::Disabled, UNTRACKED_LIST),
|
||||
/*exit_code*/ 0,
|
||||
@@ -536,7 +552,13 @@ mod tests {
|
||||
|
||||
let result = get_git_diff(&runner, &cwd, Some(":workspace")).await;
|
||||
|
||||
assert_eq!(result, Ok((true, "tracked\nuntracked\n".to_string())));
|
||||
let (is_repo, diff) = result.expect("show readable patches even if staged changes fail");
|
||||
assert!(is_repo);
|
||||
insta::assert_snapshot!(diff, @r#"
|
||||
Warning: incomplete diff. Staged changes are unavailable.
|
||||
tracked
|
||||
untracked
|
||||
"#);
|
||||
let commands = runner.commands();
|
||||
assert_command_metadata(&commands, &cwd);
|
||||
assert!(
|
||||
@@ -545,7 +567,8 @@ mod tests {
|
||||
.all(|command| command.permission_profile.as_deref() == Some(":workspace"))
|
||||
);
|
||||
assert_eq!(commands[4].env, filter_override_env("filter.evil"));
|
||||
assert_eq!(commands[6].env, filter_override_env("filter.evil"));
|
||||
assert_eq!(commands[5].env, filter_override_env("filter.evil"));
|
||||
assert_eq!(commands[7].env, filter_override_env("filter.evil"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
@@ -617,6 +640,11 @@ mod tests {
|
||||
/*exit_code*/ 1,
|
||||
"tracked\n",
|
||||
),
|
||||
response(
|
||||
git_command(FsmonitorOverride::BuiltIn, STAGED_ARGS),
|
||||
/*exit_code*/ 0,
|
||||
"ready\n",
|
||||
),
|
||||
response(
|
||||
git_command(FsmonitorOverride::BuiltIn, UNTRACKED_LIST),
|
||||
/*exit_code*/ 0,
|
||||
@@ -630,9 +658,13 @@ mod tests {
|
||||
.await
|
||||
.expect("show remaining patches");
|
||||
assert!(is_repo);
|
||||
insta::assert_snapshot!(diff, @r#"
|
||||
insta::assert_snapshot!(codex_ansi_escape::ansi_escape(&diff).to_string(), @r#"
|
||||
Warning: incomplete diff. Could not compare "gone.txt".
|
||||
Warning: incomplete diff. Unsupported untracked path "bad-\351".
|
||||
Staged
|
||||
ready
|
||||
|
||||
Unstaged and untracked
|
||||
tracked
|
||||
untracked
|
||||
"#);
|
||||
@@ -682,6 +714,11 @@ mod tests {
|
||||
/*exit_code*/ 1,
|
||||
"tracked\n",
|
||||
),
|
||||
response(
|
||||
git_command(FsmonitorOverride::Disabled, STAGED_ARGS),
|
||||
/*exit_code*/ 0,
|
||||
"",
|
||||
),
|
||||
response(
|
||||
git_command(FsmonitorOverride::Disabled, UNTRACKED_LIST),
|
||||
/*exit_code*/ 0,
|
||||
@@ -738,6 +775,11 @@ mod tests {
|
||||
/*exit_code*/ 2,
|
||||
"",
|
||||
),
|
||||
response(
|
||||
git_command(FsmonitorOverride::Disabled, STAGED_ARGS),
|
||||
/*exit_code*/ 0,
|
||||
"",
|
||||
),
|
||||
response(
|
||||
git_command(FsmonitorOverride::Disabled, UNTRACKED_LIST),
|
||||
/*exit_code*/ 0,
|
||||
@@ -756,6 +798,40 @@ mod tests {
|
||||
assert_command_metadata(&runner.commands(), &cwd);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn staged_changes_remain_visible_when_reversed_in_the_working_tree() {
|
||||
let tempdir = tempfile::tempdir().unwrap();
|
||||
let repo = tempdir.path();
|
||||
run_git_setup(repo, &["init", "-q"]);
|
||||
run_git_setup(repo, &["config", "user.name", "test"]);
|
||||
run_git_setup(repo, &["config", "user.email", "test@example.com"]);
|
||||
let diff = || async {
|
||||
let (_, text) = get_git_diff(&LOCAL_RUNNER, repo, /*permission_profile*/ None)
|
||||
.await
|
||||
.unwrap();
|
||||
codex_ansi_escape::ansi_escape(text.trim_end()).to_string()
|
||||
};
|
||||
|
||||
fs::write(repo.join("tracked.txt"), "before\n").unwrap();
|
||||
run_git_setup(repo, &["add", "tracked.txt"]);
|
||||
assert!(diff().await.contains("+before"));
|
||||
run_git_setup(repo, &["commit", "--no-gpg-sign", "-qm", "initial"]);
|
||||
|
||||
fs::write(repo.join("tracked.txt"), "after\n").unwrap();
|
||||
fs::write(repo.join("new.txt"), "new file\n").unwrap();
|
||||
run_git_setup(repo, &["add", "tracked.txt", "new.txt"]);
|
||||
let staged = diff().await;
|
||||
assert!(staged.starts_with("Staged\n"));
|
||||
assert!(staged.contains("+new file"));
|
||||
assert!(staged.contains("-before\n+after"));
|
||||
|
||||
fs::write(repo.join("tracked.txt"), "before\n").unwrap();
|
||||
let mixed = diff().await;
|
||||
let (committing, remaining) = mixed.split_once("\n\nUnstaged and untracked\n").unwrap();
|
||||
assert_eq!(committing, staged);
|
||||
assert!(remaining.contains("-after\n+before"));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn subdirectory_diff_matches_worktree_root() {
|
||||
@@ -800,10 +876,18 @@ mod tests {
|
||||
.1
|
||||
.lines()
|
||||
.map(|line| codex_ansi_escape::ansi_escape_line(line).to_string())
|
||||
.filter(|line| line.starts_with("diff --git"))
|
||||
.filter(|line| {
|
||||
line.starts_with("diff --git")
|
||||
|| line == "Staged"
|
||||
|| line == "Unstaged and untracked"
|
||||
})
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n");
|
||||
insta::assert_snapshot!(headers, @r"
|
||||
Staged
|
||||
diff --git a/ src/tracked.txt b/ src/tracked.txt
|
||||
diff --git a/same.txt b/same.txt
|
||||
Unstaged and untracked
|
||||
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
|
||||
@@ -813,7 +897,7 @@ mod tests {
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn get_git_diff_with_thread_permissions_does_not_fetch_missing_blobs() {
|
||||
async fn get_git_diff_does_not_fetch_missing_blobs() {
|
||||
let tempdir = tempfile::tempdir().unwrap();
|
||||
let repo = tempdir.path();
|
||||
run_git_setup(repo, &["init", "-q"]);
|
||||
@@ -831,10 +915,12 @@ mod tests {
|
||||
);
|
||||
fs::write(repo.join("missing"), "changed").unwrap();
|
||||
|
||||
get_git_diff(&LOCAL_RUNNER, repo, Some(":workspace"))
|
||||
.await
|
||||
.expect_err("missing blob");
|
||||
assert!(!repo.join("fetched").exists());
|
||||
for profile in [Some(":workspace"), None] {
|
||||
get_git_diff(&LOCAL_RUNNER, repo, profile)
|
||||
.await
|
||||
.expect_err("missing blob");
|
||||
assert!(!repo.join("fetched").exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -1043,7 +1129,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn run_git_setup(cwd: &Path, args: &[&str]) {
|
||||
let output = ProcessCommand::new("git")
|
||||
.args(args)
|
||||
@@ -1135,17 +1220,14 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
const LOCAL_RUNNER: LocalRunner = LocalRunner {
|
||||
explicit_worktree: None,
|
||||
};
|
||||
|
||||
#[cfg(unix)]
|
||||
struct LocalRunner {
|
||||
explicit_worktree: Option<PathBuf>,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
impl WorkspaceCommandExecutor for LocalRunner {
|
||||
fn run(
|
||||
&self,
|
||||
|
||||
Reference in New Issue
Block a user