Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/git/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,13 @@ pub const DEFAULT_COMMIT_LIMIT: usize = 300;
/// Total number of `ModelPart` variants that `load_model_streaming` sends.
pub const MODEL_PART_COUNT: usize = 14;

/// Confirmed HEAD identity, read after a successful checkout.
pub struct HeadState {
pub hash: String,
/// Empty when HEAD is detached.
pub branch_name: String,
}

struct RepoPaths {
worktree_path: PathBuf,
repo_path: PathBuf,
Expand Down Expand Up @@ -339,6 +346,32 @@ impl GitCommands {
Ok(result.stdout_trimmed().to_string())
}

/// Read the full HEAD hash and symbolic ref with one Git subprocess.
pub fn head_state(&self) -> Result<HeadState> {
let result = self
.git()
.args(&["rev-parse", "HEAD", "--symbolic-full-name", "HEAD"])
.run_expecting_success()?;
let mut lines = result.stdout.lines();
let hash = lines
.next()
.ok_or_else(|| anyhow::anyhow!("Git did not return a HEAD hash"))?;
let reference = lines
.next()
.ok_or_else(|| anyhow::anyhow!("Git did not return a HEAD ref"))?;
let branch_name = if reference == "HEAD" {
""
} else {
reference
.strip_prefix("refs/heads/")
.ok_or_else(|| anyhow::anyhow!("Unexpected HEAD ref: {reference}"))?
};
Ok(HeadState {
hash: hash.to_string(),
branch_name: branch_name.to_string(),
})
}

/// Resolve a revision to a verified commit, peeling annotated tags.
/// Unlike `resolve_ref`, this rejects trees and option-like input.
fn resolve_commit_ref(&self, reference: &str) -> Result<String> {
Expand Down Expand Up @@ -484,6 +517,33 @@ mod tests {
String::from_utf8(output.stdout).unwrap().trim().to_string()
}

#[test]
fn head_state_reads_branch_names_and_detached_annotated_tags() {
let temp = TempDir::new("head-state");
let run = |args: &[&str]| run_test_git(temp.path(), args);
run(&["init", "-b", "main"]);
run(&["commit", "--allow-empty", "-m", "root"]);
let hash = run(&["rev-parse", "HEAD"]);
run(&["checkout", "-b", "feature/nested-name"]);
let git = GitCommands::new(temp.path()).unwrap();
let head = git.head_state().unwrap();
assert_eq!(head.hash, hash);
assert_eq!(head.branch_name, "feature/nested-name");
run(&["tag", "-a", "release", "-m", "release"]);
run(&["checkout", "release"]);
let head = git.head_state().unwrap();
assert_eq!(head.hash, hash);
assert!(head.branch_name.is_empty());
}

#[test]
fn head_state_rejects_unborn_head() {
let temp = TempDir::new("unborn-head-state");
run_test_git(temp.path(), &["init", "-b", "main"]);
let git = GitCommands::new(temp.path()).unwrap();
assert!(git.head_state().is_err());
}

#[test]
fn load_compare_commits_linear_history_and_commit_revisions() {
use crate::model::commit::Divergence;
Expand Down
27 changes: 6 additions & 21 deletions src/gui/controller/branches.rs
Original file line number Diff line number Diff line change
Expand Up @@ -106,13 +106,6 @@ fn checkout_branch(gui: &mut Gui) -> Result<()> {
}
let name = branch.name.clone();
drop(model);
// Optimistic head flip so the UI reacts immediately.
{
let mut model = gui.model.lock().unwrap();
for (i, b) in model.branches.iter_mut().enumerate() {
b.head = i == selected;
}
}
start_async_checkout(gui, name);
}
Ok(())
Expand All @@ -126,13 +119,6 @@ fn checkout_previous(gui: &mut Gui) -> Result<()> {
.git
.previous_branch_name()
.unwrap_or_else(|| "-".to_string());
// Optimistic: mark matching local branch as head if we can resolve it.
if name != "-" {
let mut model = gui.model.lock().unwrap();
for b in model.branches.iter_mut() {
b.head = b.name == name;
}
}
start_async_checkout(gui, name);
Ok(())
}
Expand Down Expand Up @@ -207,13 +193,6 @@ fn checkout_picker(gui: &mut Gui) -> Result<()> {
scroll_offset: 0,
},
on_confirm: Box::new(|gui, ref_name| {
// Optimistic head flip for local branches.
{
let mut model = gui.model.lock().unwrap();
for b in model.branches.iter_mut() {
b.head = b.name == ref_name;
}
}
start_async_checkout(gui, ref_name.to_string());
Ok(())
}),
Expand All @@ -222,6 +201,12 @@ fn checkout_picker(gui: &mut Gui) -> Result<()> {
}

fn start_async_checkout(gui: &mut Gui, name: String) {
if gui.remote_op_label.is_some() {
return;
}

// Keep HEAD sourced from Git: a rejected checkout must not change the
// displayed branch. Successful completion triggers the normal model refresh.
Comment on lines +208 to +209

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Refresh HEAD when checkout reports a post-hook error

When a repository has a post-checkout hook that exits nonzero, Git has already switched branches but propagates the hook's exit status; the official documentation confirms that the hook cannot affect the checkout outcome and only changes the command's exit status (Git githooks documentation). Here the closure consequently returns Err, while receive_remote_op_results does not request a refresh on errors; after removing the optimistic updates, the model therefore continues showing the old branch and hash even though the real HEAD moved. Refresh the model—or explicitly re-read HEAD—after a checkout error before deciding which branch to display.

Useful? React with 👍 / 👎.

gui.pending_checkout_by_name = Some(name.clone());
gui.start_remote_op(
"Checking out",
Expand Down
Loading
Loading