F1: remote checkout without a remote, git.lastMessage, shared git status store

- vcs: checking out a remote-tracking branch reads remote.<name>.fetch;
  without a matching refspec it creates the local branch with --no-track
  instead of leaving a dirty tree after git fails to set up tracking.
- vcs + engine: git.lastMessage returns HEAD's full message (null before
  the first commit); the Changes window prefills Amend with it.
- ui: stores/vcsStatus.ts is the only git.status caller; the Changes
  window, tree/tab colours and the branch item read its snapshot, so a
  gitChanged costs one status query. RepoSummary carries upstream,
  ahead and behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-27 17:16:53 +01:00
parent d567f3957d
commit 4bdfe521f2
14 changed files with 649 additions and 314 deletions

View file

@ -1,6 +1,6 @@
//! Git commands (M4.1, owner decision D20): status, stage, unstage, commit,
//! file contents at HEAD or in the index, branches, checkout and branch
//! creation, through the user's installed git (`lutra-vcs`).
//! the last commit message, file contents at HEAD or in the index,
//! branches, checkout and branch creation, through the user's installed git (`lutra-vcs`).
//!
//! **Off the lock.** git can take seconds (a big status, a commit hook), so
//! every command returns a pending outcome ([`crate::Pending`]): under the
@ -60,6 +60,7 @@ pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(Stage))?;
registry.register(Box::new(Unstage))?;
registry.register(Box::new(Commit))?;
registry.register(Box::new(LastMessage))?;
registry.register(Box::new(Show))?;
registry.register(Box::new(BranchesCommand))?;
registry.register(Box::new(Checkout))?;
@ -188,6 +189,8 @@ enum Op {
/// Amend the last commit.
amend: bool,
},
/// `git.lastMessage`.
LastMessage,
/// `git.show`.
Show(String, Rev),
/// `git.branches`.
@ -208,7 +211,10 @@ enum Op {
impl Op {
/// Whether the call changes the repository (and sends `gitChanged`).
fn mutates(&self) -> bool {
!matches!(self, Self::Status | Self::Show(..) | Self::Branches)
!matches!(
self,
Self::Status | Self::LastMessage | Self::Show(..) | Self::Branches
)
}
}
@ -406,6 +412,7 @@ fn run_op(repo: &Repo, op: &Op) -> Result<Value, VcsError> {
let info = repo.commit(message, *amend)?;
Ok(json!({"commit": info.commit, "summary": info.summary}))
}
Op::LastMessage => Ok(json!({"message": repo.last_message()?})),
Op::Show(path, rev) => {
let contents = repo.show(path, *rev)?;
Ok(json!({
@ -714,6 +721,31 @@ impl Command for Commit {
}
}
/// `git.lastMessage`.
struct LastMessage;
impl Command for LastMessage {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.lastMessage",
label: "Git: Last Commit Message",
menu_path: None,
default_shortcut: None,
params: "none; returns { message: string | null }: the full message of HEAD (trailing line breaks removed), null before the first commit; for prefilling an amend",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let _: serde_json::Map<String, Value> = parse(command, params)?;
start(state, command, Op::LastMessage)
}
}
/// Which version `git.show` returns.
#[derive(Debug, Clone, Copy, Deserialize)]
enum RefParam {

View file

@ -484,6 +484,7 @@ mod tests {
"git.checkout",
"git.commit",
"git.createBranch",
"git.lastMessage",
"git.lineChanges",
"git.show",
"git.stage",

View file

@ -180,6 +180,13 @@ fn status_stage_commit_show_and_branches() {
assert_eq!(commit["summary"], "second");
assert_eq!(commit["commit"], git(dir.path(), &["rev-parse", "HEAD"]));
assert_eq!(host.git_changes().len(), 1);
assert_eq!(
host.run("git.lastMessage", Value::Null).unwrap(),
json!({"message": "second\n\nbody"})
);
assert!(host.git_changes().is_empty());
let err = host.run("git.lastMessage", json!([1])).unwrap_err();
assert_eq!(err.code(), "invalid_params");
assert_eq!(
host.run("git.status", Value::Null).unwrap()["files"],
json!([])

View file

@ -290,6 +290,66 @@ pub fn parse_refs(bytes: &[u8]) -> Vec<RefEntry> {
.collect()
}
/// One `remote.<name>.fetch` refspec.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct FetchSpec {
/// The remote's name (case kept, may hold dots).
pub remote: String,
/// The refspec as configured, e.g. `+refs/heads/*:refs/remotes/origin/*`.
pub spec: String,
}
/// Parses `git config -z --get-regexp ^remote\..*\.fetch$` output: entries
/// separated by NUL, each `remote.<name>.fetch`, a line break and the value.
/// Entries without a value or with another key shape are skipped.
pub fn parse_fetch_specs(bytes: &[u8]) -> Vec<FetchSpec> {
bytes
.split(|b| *b == 0)
.filter_map(|entry| {
let text = String::from_utf8_lossy(entry);
let (key, value) = text.split_once('\n')?;
let remote = key.strip_prefix("remote.")?.strip_suffix(".fetch")?;
if remote.is_empty() || value.is_empty() {
return None;
}
Some(FetchSpec {
remote: remote.to_string(),
spec: value.to_string(),
})
})
.collect()
}
/// The local branch name git derives for checking out the remote-tracking
/// ref `refname` (`refs/remotes/origin/x`) with `--track`: the part a
/// configured fetch refspec's destination matches (`*`), or the source
/// branch of an exact refspec.
///
/// # Returns
/// `None` when no configured refspec maps a branch to `refname`; git can
/// then not set up tracking for it. Negative refspecs (`^…`) are skipped.
pub fn tracking_name(specs: &[FetchSpec], refname: &str) -> Option<String> {
specs.iter().find_map(|fetch| {
let spec = fetch.spec.strip_prefix('+').unwrap_or(&fetch.spec);
if spec.starts_with('^') {
return None;
}
let (src, dst) = spec.split_once(':')?;
match dst.split_once('*') {
Some((before, after)) => {
let name = refname.strip_prefix(before)?.strip_suffix(after)?;
src.contains('*').then_some(())?;
(!name.is_empty()).then(|| name.to_string())
}
None => (dst == refname)
.then(|| src.strip_prefix("refs/heads/"))
.flatten()
.filter(|n| !n.is_empty())
.map(str::to_string),
}
})
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::indexing_slicing)]
@ -394,6 +454,26 @@ u UU N... 100644 100644 100644 100644 a b c conflict.php\0\
assert!(refs[1].symbolic);
}
#[test]
fn fetch_specs_and_tracking_names() {
let out = b"remote.origin.fetch\n+refs/heads/*:refs/remotes/origin/*\0\
remote.my.fork.fetch\nrefs/heads/main:refs/remotes/my.fork/main\0\
remote.neg.fetch\n^refs/heads/secret\0remote..fetch\nx\0junk\0";
let specs = parse_fetch_specs(out);
assert_eq!(specs.len(), 3);
assert_eq!(specs[1].remote, "my.fork");
let name = |r: &str| tracking_name(&specs, r);
assert_eq!(
name("refs/remotes/origin/feature/x").as_deref(),
Some("feature/x")
);
assert_eq!(name("refs/remotes/my.fork/main").as_deref(), Some("main"));
assert_eq!(name("refs/remotes/my.fork/other"), None);
assert_eq!(name("refs/remotes/foo/x"), None);
assert_eq!(name("refs/remotes/origin/"), None);
assert_eq!(tracking_name(&[], "refs/remotes/origin/x"), None);
}
proptest! {
#[test]
fn status_parser_never_panics(bytes in proptest::collection::vec(any::<u8>(), 0..512)) {
@ -425,6 +505,8 @@ u UU N... 100644 100644 100644 100644 a b c conflict.php\0\
fn version_and_ref_parsers_never_panic(bytes in proptest::collection::vec(any::<u8>(), 0..256)) {
let _ = parse_version(&String::from_utf8_lossy(&bytes));
let _ = parse_refs(&bytes);
let specs = parse_fetch_specs(&bytes);
let _ = tracking_name(&specs, &String::from_utf8_lossy(&bytes));
}
}
}

View file

@ -10,7 +10,7 @@ use std::path::{Path, PathBuf};
use std::sync::{Mutex, MutexGuard, PoisonError};
use crate::VcsError;
use crate::porcelain::{self, FileStatus, Head, REF_FORMAT, Status, Version};
use crate::porcelain::{self, FetchSpec, FileStatus, Head, REF_FORMAT, Status, Version};
use crate::runner::{self, Call, HOOK_TIMEOUT};
/// Oldest supported git: 2.30 (porcelain v2 headers, `--pathspec-from-file`
@ -564,20 +564,55 @@ impl Repo {
.success())
}
/// Checks out a local branch, or creates a local branch tracking a
/// remote one (`origin/feature` → `feature`). Hooks run (120 s).
/// The configured `remote.<name>.fetch` refspecs.
///
/// # Errors
/// The runner's errors; no configured remote is an empty list.
fn fetch_specs(&self) -> Result<Vec<FetchSpec>, VcsError> {
let output = self.run(Call::read(
&self.root,
&["config", "-z", "--get-regexp", r"^remote\..*\.fetch$"],
SMALL_CAP,
))?;
if !output.success() {
return Ok(Vec::new());
}
Ok(porcelain::parse_fetch_specs(&output.stdout))
}
/// Checks out a local branch, or creates a local branch from a remote
/// one (`origin/feature` → `feature`). Hooks run (120 s).
///
/// The new branch tracks the remote one when a configured fetch refspec
/// maps a branch to it (the name comes from that refspec, as git
/// derives it). Without one (the remote was removed, or the ref was
/// created by hand) git could not set up tracking and would fail after
/// updating the work tree, so the branch is created with `--no-track`,
/// named after the part behind the first `/`.
///
/// # Errors
/// [`VcsError::InvalidName`], [`VcsError::Git`] for an unknown branch
/// or when git refuses (local changes would be overwritten); git's
/// message is passed on.
/// or when git refuses (local changes would be overwritten, the local
/// branch exists already); git's message is passed on.
pub fn checkout(&self, branch: &str) -> Result<(), VcsError> {
check_name(branch)?;
let _guard = self.lock();
let remote_ref = format!("refs/remotes/{branch}");
let local;
let args: Vec<&str> = if self.ref_exists(&format!("refs/heads/{branch}"))? {
vec!["switch", "-q", branch]
} else if self.ref_exists(&format!("refs/remotes/{branch}"))? {
vec!["switch", "-q", "--track", branch]
} else if self.ref_exists(&remote_ref)? {
let tracked = porcelain::tracking_name(&self.fetch_specs()?, &remote_ref);
let track = if tracked.is_some() {
"--track"
} else {
"--no-track"
};
local = tracked
.or_else(|| branch.split_once('/').map(|(_, rest)| rest.to_string()))
.unwrap_or_default();
check_name(&local)?;
vec!["switch", "-q", "-c", &local, track, branch]
} else {
return Err(VcsError::Git(format!("no branch named {branch}")));
};
@ -586,6 +621,29 @@ impl Repo {
Ok(())
}
/// The full message of the last commit, for prefilling an amend.
///
/// # Returns
/// `None` before the first commit; otherwise the raw message (`%B`)
/// with trailing line breaks removed.
///
/// # Errors
/// The runner's errors or git's refusal.
pub fn last_message(&self) -> Result<Option<String>, VcsError> {
if !self.has_head()? {
return Ok(None);
}
let output = self
.run(Call::read(
&self.root,
&["show", "-s", "--format=%B", "HEAD"],
SMALL_CAP,
))?
.checked()?;
let text = String::from_utf8_lossy(&output.stdout);
Ok(Some(text.trim_end_matches(['\n', '\r']).to_string()))
}
/// Creates a branch.
///
/// # Parameters

View file

@ -351,6 +351,60 @@ fn remote_branches_are_listed_and_checked_out_as_tracking_branches() {
repo.checkout("origin/remote-only").unwrap();
let branches = repo.branches().unwrap();
assert_eq!(branches.current.as_deref(), Some("remote-only"));
let local = branches.local.iter().find(|b| b.name == "remote-only");
assert_eq!(
local.and_then(|b| b.upstream.as_deref()),
Some("origin/remote-only")
);
}
#[test]
fn remote_branches_without_a_configured_remote_check_out_untracked_and_clean() {
let Some(cli) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
init(dir.path());
write(dir.path(), "a.php", "<?php\n");
git(dir.path(), &["add", "-A"]);
git(dir.path(), &["commit", "-q", "-m", "base"]);
git(dir.path(), &["checkout", "-q", "-b", "gone"]);
write(dir.path(), "b.php", "<?php // only on gone\n");
git(dir.path(), &["add", "-A"]);
git(dir.path(), &["commit", "-q", "-m", "gone"]);
git(dir.path(), &["checkout", "-q", "main"]);
git(dir.path(), &["update-ref", "refs/remotes/old/gone", "gone"]);
git(dir.path(), &["branch", "-q", "-D", "gone"]);
let repo = open(&cli, dir.path());
repo.checkout("old/gone").unwrap();
let status = repo.status().unwrap();
assert_eq!(status.head.branch.as_deref(), Some("gone"));
assert_eq!(status.head.upstream, None);
assert!(status.files.is_empty(), "{:?}", status.files);
assert!(dir.path().join("b.php").exists());
repo.checkout("main").unwrap();
let err = repo.checkout("old/gone").unwrap_err();
assert!(matches!(err, VcsError::Git(_)), "{err:?}");
let status = repo.status().unwrap();
assert_eq!(status.head.branch.as_deref(), Some("main"));
assert!(status.files.is_empty(), "{:?}", status.files);
}
#[test]
fn the_last_message_prefills_an_amend() {
let Some(cli) = installed() else { return };
let dir = tempfile::tempdir().unwrap();
init(dir.path());
let repo = open(&cli, dir.path());
assert_eq!(repo.last_message().unwrap(), None);
write(dir.path(), "a.php", "<?php\n");
repo.stage(&["a.php".into()]).unwrap();
repo.commit("Subject line\n\n# kept\nBody ü\n\n", false)
.unwrap();
assert_eq!(
repo.last_message().unwrap().as_deref(),
Some("Subject line\n\n# kept\nBody ü")
);
}
#[test]