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:
parent
d567f3957d
commit
4bdfe521f2
14 changed files with 649 additions and 314 deletions
|
|
@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue