use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
/// Snapshot of the workspace's git state, refreshed periodically and after
/// filesystem events. Cheap to compute on small repos; we shell out rather
/// than link `git2` to keep the dep graph small and the surface area testable.
#[derive(Default, Clone, Debug, PartialEq, Eq)]
pub struct GitStatus {
pub in_repo: bool,
/// `Some("main")` on a normal branch. `None` when the workspace is not
/// a git repo, or HEAD is detached (use `detached_hash` then).
pub branch: Option<String>,
pub detached_hash: Option<String>,
pub dirty: bool,
pub ahead: usize,
pub behind: usize,
/// The HEAD commit's full oid, or `None` outside a repo. Drives git-gutter
/// baseline invalidation: when this moves (commit, checkout, pull) the
/// cached HEAD file snapshots are stale and must be refetched.
pub head_oid: Option<String>,
/// Absolute paths of git-ignored files and directories, so the Explorer
/// can grey them out (VS Code's ignored-resource decoration). A fully
/// ignored directory appears as one collapsed entry — descendants are
/// resolved by walking ancestors, never enumerated. Arc: the status is
/// cloned per consumer each refresh and the set can be large.
pub ignored: Arc<HashSet<PathBuf>>,
/// The Explorer's git decorations (#1513): each changed file under the
/// workspace root with its status, and each folder above one with the
/// strongest status beneath it, keyed by absolute path in the root's
/// own spelling. Arc for the same reason as `ignored`.
pub decorations: Arc<HashMap<PathBuf, GitDecoration>>,
/// The repository toplevel containing the workspace root, or `None`
/// outside a repo. Porcelain and numstat paths are TOPLEVEL-relative,
/// so every consumer that joins a repo-relative path or names one on a
/// git command line must resolve against this, never the workspace
/// root — the two coincide only when the workspace root IS the
/// toplevel (#139).
pub repo_root: Option<PathBuf>,
/// Number of changed entries `git status --porcelain` reported —
/// available for EVERY workspace folder's worker, unlike the panel's
/// entry list which only the active repo fetches (#161: the
/// repositories overview and the cross-repo badge read this).
pub changed_count: usize,
/// The message git prepared for the commit in progress (#1282): a
/// conflicted merge, cherry-pick or revert writes `MERGE_MSG`, a
/// `merge --squash` writes `SQUASH_MSG`. Comment lines are dropped, as
/// `commit.cleanup=strip` would. Without either, the `commit.template`
/// file (#1620). `None` when there is none of them.
pub prepared_message: Option<String>,
/// The merge, rebase, cherry-pick, revert or bisect the repository is
/// in the middle of (#1356), from [`repo_operation`].
pub operation: Option<RepoOp>,
/// The branch a rebase is rewriting (#1647). HEAD is detached on the
/// commit being replayed onto throughout, so `branch` is `None`; git
/// keeps the branch's name in the rebase's `head-name` file. `None`
/// outside a rebase, and for a rebase of a detached HEAD.
pub rebasing_branch: Option<String>,
}
impl GitStatus {
/// What HEAD is called in the status bar and the Source Control header:
/// the branch, the branch a rebase is rewriting (#1647), else the short
/// hash of a detached HEAD.
pub fn head_label(&self) -> &str {
match (&self.branch, &self.rebasing_branch, &self.detached_hash) {
(Some(b), _, _) | (None, Some(b), _) => b,
(None, None, Some(h)) => h,
(None, None, None) => "(no head)",
}
}
}
/// An operation git stopped half-way through (#1356): what the status bar
/// names next to the branch, and what Abort / Continue / Skip act on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum RepoOp {
Merge,
/// `step` of `total` commits, as git counts them.
Rebase {
step: usize,
total: usize,
},
CherryPick,
Revert,
Bisect,
}
impl RepoOp {
/// The status-bar tag: `MERGING`, `REBASING 2/5`, `CHERRY-PICKING`,
/// `REVERTING`, `BISECTING`.
pub fn label(self) -> String {
match self {
RepoOp::Merge => String::from("MERGING"),
RepoOp::Rebase { step, total } => format!("REBASING {step}/{total}"),
RepoOp::CherryPick => String::from("CHERRY-PICKING"),
RepoOp::Revert => String::from("REVERTING"),
RepoOp::Bisect => String::from("BISECTING"),
}
}
/// The git command it belongs to, also its name in messages.
pub fn command(self) -> &'static str {
match self {
RepoOp::Merge => "merge",
RepoOp::Rebase { .. } => "rebase",
RepoOp::CherryPick => "cherry-pick",
RepoOp::Revert => "revert",
RepoOp::Bisect => "bisect",
}
}
}
/// The operation `root`'s repository is in the middle of (#1356), read
/// from the state files git leaves in its directory: `rebase-merge/` or
/// `rebase-apply/` (with the step counters), `MERGE_HEAD`,
/// `CHERRY_PICK_HEAD`, `REVERT_HEAD`, `BISECT_LOG`. Found through
/// `--git-path`, so a worktree reads its own. A `git am` (an
/// `rebase-apply/applying` marker) is not one of these and reads as none.
pub fn repo_operation(root: &Path) -> Option<RepoOp> {
const NAMES: [&str; 6] = [
"rebase-merge",
"rebase-apply",
"MERGE_HEAD",
"CHERRY_PICK_HEAD",
"REVERT_HEAD",
"BISECT_LOG",
];
let mut args = vec!["rev-parse"];
for name in NAMES {
args.extend(["--git-path", name]);
}
let out = run_git(root, &args).ok()?;
let paths: Vec<PathBuf> = out.lines().map(|l| root.join(l.trim())).collect();
if paths.len() != NAMES.len() {
return None;
}
let counter = |dir: &Path, name: &str| -> usize {
std::fs::read_to_string(dir.join(name))
.ok()
.and_then(|s| s.trim().parse().ok())
.unwrap_or(0)
};
if paths[0].is_dir() {
return Some(RepoOp::Rebase {
step: counter(&paths[0], "msgnum"),
total: counter(&paths[0], "end"),
});
}
if paths[1].is_dir() && !paths[1].join("applying").exists() {
return Some(RepoOp::Rebase {
step: counter(&paths[1], "next"),
total: counter(&paths[1], "last"),
});
}
let op = [
RepoOp::Merge,
RepoOp::CherryPick,
RepoOp::Revert,
RepoOp::Bisect,
]
.into_iter()
.zip(&paths[2..])
.find(|(_, p)| p.is_file())?;
Some(op.0)
}
/// Abort `op` (#1356): `merge --abort`, `rebase --abort`,
/// `cherry-pick --abort`, `revert --abort`, or `bisect reset` for a bisect.
pub fn abort_operation(root: &Path, op: RepoOp) -> Result<String, String> {
match op {
RepoOp::Bisect => run_mutation(root, &["bisect", "reset"]),
_ => run_mutation(root, &[op.command(), "--abort"]),
}
}
/// Continue `op` once its conflicts are resolved and staged (#1356),
/// keeping each commit's own message: git's editor is `true`, so it never
/// waits for one. A merge is concluded by a commit, and a bisect has no
/// continue; both are refused.
pub fn continue_operation(root: &Path, op: RepoOp) -> Result<String, String> {
match op {
RepoOp::Merge => Err(String::from("Commit to conclude the merge, or abort it")),
RepoOp::Bisect => Err(String::from(
"Mark the commit good or bad to go on with the bisect",
)),
_ => run_mutation_with_env(
root,
&[op.command(), "--continue"],
&[("GIT_EDITOR", "true")],
),
}
}
/// Skip the commit `op` stopped on (#1356): `rebase --skip`,
/// `cherry-pick --skip`, `revert --skip`. Refused for a merge or bisect.
pub fn skip_operation(root: &Path, op: RepoOp) -> Result<String, String> {
match op {
RepoOp::Merge | RepoOp::Bisect => Err(format!("A {} has no skip", op.command())),
_ => run_mutation_with_env(root, &[op.command(), "--skip"], &[("GIT_EDITOR", "true")]),
}
}
/// Mark the commit a bisect checked out good or bad (#1356).
pub fn bisect_mark(root: &Path, good: bool) -> Result<String, String> {
run_mutation(root, &["bisect", if good { "good" } else { "bad" }])
}
pub fn query(root: &Path) -> GitStatus {
// One probe answers both questions is_git_repo asked: exit status is
// repo membership, stdout is the toplevel every repo-relative path
// must resolve against.
let Some(repo_root) = repo_toplevel(root) else {
return GitStatus::default();
};
let branch = run_git(root, &["symbolic-ref", "--short", "HEAD"])
.ok()
.and_then(parse_branch);
let detached_hash = if branch.is_none() {
run_git(root, &["rev-parse", "--short", "HEAD"])
.ok()
.and_then(parse_branch)
} else {
None
};
// Raw `-z` bytes: `run_git` trims stdout, which would shift the first
// record's status column (` M a.py` -> `M a.py`), and a lossy string
// would not key a non-UTF-8 filename to its real path.
let porcelain = git_raw(
root,
&["status", "--porcelain", "-z", "--untracked-files=all"],
None,
)
.unwrap_or_default();
let prefix = run_git(root, &["rev-parse", "--show-prefix"]).unwrap_or_default();
let decorations = parse_decorations(root, &prefix, &porcelain);
let changed_count = porcelain_z_count(&porcelain);
let dirty = changed_count > 0;
let (ahead, behind) = match run_git(
root,
&["rev-list", "--left-right", "--count", "HEAD...@{u}"],
) {
Ok(s) => parse_ahead_behind(&s),
Err(_) => (0, 0),
};
let head_oid = run_git(root, &["rev-parse", "HEAD"])
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let prepared = prepared_message(root, &repo_root);
let operation = repo_operation(root);
GitStatus {
in_repo: true,
detached_hash,
dirty,
ahead,
behind,
head_oid,
ignored: Arc::new(query_ignored(root)),
decorations: Arc::new(decorations),
repo_root: Some(repo_root),
changed_count,
prepared_message: prepared,
rebasing_branch: match (&branch, operation) {
(None, Some(RepoOp::Rebase { .. })) => rebasing_branch(root),
_ => None,
},
branch,
operation,
}
}
/// The branch the rebase in progress is rewriting (#1647), from the
/// `head-name` git writes in `rebase-merge/` or `rebase-apply/`
/// (`refs/heads/feature`). A rebase of a detached HEAD writes `detached
/// HEAD` there, which names no branch.
fn rebasing_branch(root: &Path) -> Option<String> {
let out = run_git(
root,
&[
"rev-parse",
"--git-path",
"rebase-merge/head-name",
"--git-path",
"rebase-apply/head-name",
],
)
.ok()?;
out.lines()
.find_map(|l| std::fs::read_to_string(root.join(l.trim())).ok())
.and_then(|name| {
name.trim()
.strip_prefix("refs/heads/")
.filter(|b| !b.is_empty())
.map(String::from)
})
}
/// git's prepared message for the commit in progress (#1282): `MERGE_MSG`
/// (a conflicted merge, cherry-pick or revert), else `SQUASH_MSG`, found
/// through `--git-path` so a worktree or submodule reads its own; else the
/// `commit.template` file (#1620). Comment lines are dropped as
/// `commit.cleanup=strip` drops them, by git's own [`comment_marker`];
/// nothing left is no message.
fn prepared_message(root: &Path, top: &Path) -> Option<String> {
let paths = run_git(
root,
&[
"rev-parse",
"--git-path",
"MERGE_MSG",
"--git-path",
"SQUASH_MSG",
],
)
.ok()?;
// Asked only once there is text to strip: most refreshes have none.
let marker = std::cell::OnceCell::new();
let strip = |text: String| {
without_comments(
&text,
marker.get_or_init(|| comment_marker(root)).as_deref(),
)
};
paths
.lines()
.find_map(|p| strip(std::fs::read_to_string(root.join(p.trim())).ok()?))
.or_else(|| strip(commit_template(root, top)?))
}
/// `text` without the lines starting with `marker` and without outer
/// blank lines, or `None` when nothing is left. No marker drops no line.
fn without_comments(text: &str, marker: Option<&str>) -> Option<String> {
let kept: Vec<&str> = text
.lines()
.filter(|l| !marker.is_some_and(|m| l.starts_with(m)))
.map(str::trim_end)
.collect();
let message = kept.join("\n").trim().to_string();
(!message.is_empty()).then_some(message)
}
/// The marker that starts a comment line for `git commit` (#1620):
/// whichever of `core.commentChar` and `core.commentString` the config
/// sets last, as git reads them, else `#`. A team that writes `#123` in
/// its messages sets another, and its template's help lines start with
/// that one. `None` for `auto`: git then picks a marker no line of the
/// message starts with, so none of it is a comment.
fn comment_marker(root: &Path) -> Option<String> {
let set = run_git(
root,
&["config", "--get-regexp", r"^core\.comment(char|string)$"],
)
.unwrap_or_default();
match set.lines().last().and_then(|l| l.split_once(' ')) {
Some((_, v)) if v.eq_ignore_ascii_case("auto") => None,
Some((_, v)) => Some(v.to_string()),
None => Some(String::from("#")),
}
}
/// The text of the file git's `commit.template` names (#1620), for the
/// message box when no merge or squash message is prepared: croft commits
/// with `-m`, and with `-m` git skips the template, so a team's required
/// ticket prefix and headings were lost. `--path` expands `~`; a relative
/// path is taken from `top`, the repository's top level, where `git
/// commit` reads it.
fn commit_template(root: &Path, top: &Path) -> Option<String> {
let named = run_git(root, &["config", "--path", "commit.template"]).ok()?;
let named = Path::new(named.trim());
if named.as_os_str().is_empty() {
return None;
}
std::fs::read_to_string(top.join(named)).ok()
}
/// The git-ignored paths under `root`, absolute.
///
/// Two-step, because neither step alone is correct. `ls-files --directory`
/// gives a cheap candidate set (a fully-ignored directory collapses to one
/// entry instead of enumerating `target/`'s thousands of files), but it also
/// collapses any ENTIRELY UNTRACKED directory whose contents all happen to be
/// ignored — even when no rule matches the directory itself, so `logs/` shows
/// up merely because `logs/app.log` is ignored. `check-ignore` then answers
/// per path, exactly the per-resource question VS Code asks, and only its
/// verdicts reach the set.
///
/// Both calls go through [`git_raw`]: filenames may carry leading or trailing
/// whitespace (git sorts a leading-space name FIRST, so a blanket `trim()`
/// eats it) or bytes that are not UTF-8, so the `-z` output is split on NUL
/// and converted without lossy decoding.
fn query_ignored(root: &Path) -> HashSet<PathBuf> {
let listed = git_raw(
root,
&[
"ls-files",
"-z",
"--others",
"--ignored",
"--directory",
"--exclude-standard",
],
None,
)
.unwrap_or_default();
let mut stdin = Vec::with_capacity(listed.len());
for candidate in listed.split(|b| *b == 0).filter(|s| !s.is_empty()) {
stdin.extend_from_slice(candidate);
stdin.push(0);
}
if stdin.is_empty() {
return HashSet::new();
}
// check-ignore exits 1 when nothing matches: a verdict, not a failure, so
// `git_raw` deliberately does not gate on the exit status.
let confirmed =
git_raw(root, &["check-ignore", "-z", "--stdin"], Some(&stdin)).unwrap_or_default();
confirmed
.split(|b| *b == 0)
.filter(|s| !s.is_empty())
.map(|raw| join_raw(root, raw))
.collect()
}
/// Whether git ignores `path` under the repository at `root`: one
/// `check-ignore` call, for a single path's verdict (#263: a save of build
/// output or a `.env` does not rerun watched tests). Outside a repository,
/// or when git cannot answer, nothing is ignored.
pub fn is_ignored(root: &Path, path: &Path) -> bool {
let mut stdin = path.as_os_str().as_encoded_bytes().to_vec();
stdin.push(0);
git_raw(root, &["check-ignore", "-z", "--stdin"], Some(&stdin))
.is_some_and(|out| out.iter().any(|b| *b != 0))
}
/// Join a raw `-z` path (trailing `/` stripped) onto `root` without passing
/// through `str`: a filename is bytes, and on unix it need not be UTF-8.
fn join_raw(root: &Path, raw: &[u8]) -> PathBuf {
let trimmed = raw.strip_suffix(b"/").unwrap_or(raw);
#[cfg(unix)]
{
use std::os::unix::ffi::OsStrExt;
root.join(std::ffi::OsStr::from_bytes(trimmed))
}
#[cfg(not(unix))]
{
root.join(String::from_utf8_lossy(trimmed).as_ref())
}
}
/// Spawn `git` under `root` and hand back stdout as RAW BYTES, optionally
/// feeding `stdin_data` first. Unlike [`run_git`] this neither trims nor
/// UTF-8-decodes, and it ignores the exit status — the callers here read
/// NUL-separated filenames, and `check-ignore` uses exit 1 as an answer.
fn git_raw(root: &Path, args: &[&str], stdin_data: Option<&[u8]>) -> Option<Vec<u8>> {
use std::io::Write;
let mut cmd = Command::new("git");
cmd.arg("-C")
.arg(root)
// A read-only poll must never take `index.lock` out from under a user
// mutation — same reason `run_git` sets it.
.env("GIT_OPTIONAL_LOCKS", "0")
.args(args)
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.stdin(if stdin_data.is_some() {
std::process::Stdio::piped()
} else {
std::process::Stdio::null()
});
let mut child = cmd.spawn().ok()?;
// Feed stdin from its OWN thread and read stdout concurrently.
// `check-ignore` echoes each match back as it reads, so both pipes fill
// on a large set; writing all of stdin before reading a byte of stdout
// deadlocks — git blocks writing stdout, stops draining stdin, and the
// writer waits forever. Measured threshold on macOS: ~143 KB flows,
// ~957 KB blocks.
let writer = match stdin_data {
Some(data) => {
let mut pipe = child.stdin.take()?;
let data = data.to_vec();
Some(std::thread::spawn(move || {
let _ = pipe.write_all(&data);
// Dropping the pipe closes it, which is what tells
// check-ignore the list is complete.
}))
}
None => None,
};
let out = child.wait_with_output().ok();
if let Some(w) = writer {
let _ = w.join();
}
Some(out?.stdout)
}
/// The immediate subfolders of `dir` that hold a repository (a `.git`
/// entry: a folder, or a file for worktrees and submodules), sorted by
/// name. Hidden folders are skipped, like VS Code's depth-1 scan (#1227).
pub fn child_repos(dir: &Path) -> Vec<PathBuf> {
let Ok(rd) = std::fs::read_dir(dir) else {
return Vec::new();
};
let mut repos: Vec<PathBuf> = rd
.flatten()
.filter(|e| e.file_type().is_ok_and(|t| t.is_dir()))
.filter(|e| !e.file_name().to_string_lossy().starts_with('.'))
.map(|e| e.path())
.filter(|p| p.join(".git").exists())
.collect();
repos.sort();
repos
}
/// The toplevel of the repository containing `dir`, or `None` outside a
/// repo. This is the ONLY correct base for porcelain/numstat paths and
/// for rev pathspecs (`HEAD:<rel>`), which git resolves against the
/// toplevel regardless of `-C`; command-line pathspecs are cwd-relative,
/// so mutations that name a repo-relative path must run `-C` here too.
pub fn repo_toplevel(dir: &Path) -> Option<PathBuf> {
run_git(dir, &["rev-parse", "--show-toplevel"])
.ok()
.filter(|s| !s.is_empty())
.map(PathBuf::from)
}
fn run_git(path: &Path, args: &[&str]) -> std::io::Result<String> {
let path_str = path
.to_str()
.ok_or_else(|| std::io::Error::other("non-utf8 workspace path"))?;
let mut cmd = Command::new("git");
// Read-only queries must never take `.git/index.lock`: `git status` /
// `git diff` opportunistically rewrite the refreshed index, and that
// background lock races user-initiated mutations (`git add`, `git
// apply --cached`) into transient "index.lock exists" failures. This
// is exactly what git ships GIT_OPTIONAL_LOCKS for.
cmd.env("GIT_OPTIONAL_LOCKS", "0");
cmd.args(["-C", path_str]).args(args);
let output = cmd.output()?;
if !output.status.success() {
return Err(std::io::Error::other(format!(
"git {:?} failed with code {:?}",
args,
output.status.code()
)));
}
Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
}
/// Keep a git child from prompting on croft's terminal. A push or pull
/// needing a password or an ssh passphrase opened `/dev/tty`, drew over
/// the full-screen UI and waited for input croft never passed on. With no
/// terminal prompt and no controlling tty, git and ssh fail at once with a
/// message the panel shows; credential helpers and agents still work.
fn never_prompt(cmd: &mut Command) {
cmd.env("GIT_TERMINAL_PROMPT", "0")
.stdin(std::process::Stdio::null());
#[cfg(unix)]
detach_from_tty(cmd);
}
#[cfg(unix)]
fn detach_from_tty(cmd: &mut Command) {
use std::os::unix::process::CommandExt;
// SAFETY: `setsid` is async-signal-safe and the only call in the
// pre-exec hook; the forked child is never a process-group leader, so
// the call always succeeds.
unsafe {
cmd.pre_exec(|| {
libc::setsid();
Ok(())
});
}
}
/// Run a mutating git subcommand and return a human-readable summary.
///
/// Shared by every operation the Source Control panel invokes
/// synchronously (unstage, pull, sync, branch switch/create, stash) so
/// they don't each re-implement the spawn → check → pick-the-right-stream
/// dance. On success git often reports the interesting line on *stderr*
/// (push/pull print "Everything up-to-date" / ref updates there), so we
/// surface stderr when stdout is empty and vice-versa. On failure we
/// surface whichever stream carries the message verbatim, so the panel
/// shows the host's exact reason (e.g. "fatal: 'x' is not a commit").
fn run_mutation(root: &Path, args: &[&str]) -> Result<String, String> {
run_mutation_with(root, args, false)
}
/// [`run_mutation`] for an operation that can stop on conflicts: merge,
/// rebase, pull, stash apply and pop. Git names the conflicts on stdout
/// (`CONFLICT (content): Merge conflict in pricing.py`) and, for a rebase,
/// the failure on stderr (`error: could not apply …`); keeping stderr alone
/// lost the conflicts (#858), so a failure here carries both, stdout first.
fn run_mutation_keeping_conflicts(root: &Path, args: &[&str]) -> Result<String, String> {
run_mutation_with(root, args, true)
}
/// [`run_mutation`]'s body; `both_streams` makes a failure report stdout
/// and stderr together when git wrote to both.
fn run_mutation_with(root: &Path, args: &[&str], both_streams: bool) -> Result<String, String> {
run_mutation_inner(root, args, &[], both_streams)
}
/// [`run_mutation`] with extra environment variables for git.
fn run_mutation_with_env(
root: &Path,
args: &[&str],
envs: &[(&str, &str)],
) -> Result<String, String> {
run_mutation_inner(root, args, envs, false)
}
/// The body shared by [`run_mutation_with`] and [`run_mutation_with_env`].
fn run_mutation_inner(
root: &Path,
args: &[&str],
envs: &[(&str, &str)],
both_streams: bool,
) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
// Echo the command and its result into the OUTPUT panel's "Git" channel, so
// the user can see exactly what the Source Control panel ran (VS Code's Git
// output channel). Only mutations are logged here; status polls stay quiet.
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Info,
&format!("> git {}", args.join(" ")),
);
let mut cmd = Command::new("git");
cmd.args(["-C", path_str]).args(args);
cmd.envs(envs.iter().copied());
never_prompt(&mut cmd);
let output = cmd
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if output.status.success() {
let msg = if !stdout.is_empty() { stdout } else { stderr };
if !msg.is_empty() {
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Info,
&msg,
);
}
Ok(msg)
} else {
let msg = if both_streams && !stdout.is_empty() && !stderr.is_empty() {
// Appended to stdout's own buffer rather than formatted into a
// new one, however long git's text is.
let mut both = stdout;
both.reserve(1 + stderr.len());
both.push('\n');
both.push_str(&stderr);
both
} else if !stderr.is_empty() {
stderr
} else {
stdout
};
let err = if msg.is_empty() {
let verb = args.first().copied().unwrap_or("git");
format!("git {verb} failed with code {:?}", output.status.code())
} else {
msg
};
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Error,
&err,
);
Err(err)
}
}
/// Trim whitespace and treat empty as "no branch".
pub fn parse_branch(out: String) -> Option<String> {
let trimmed = out.trim();
if trimmed.is_empty() {
None
} else {
Some(trimmed.to_string())
}
}
/// Working-tree change reported by `git status --porcelain`. The Source
/// Control panel groups entries by `kind.section()` and renders a one-letter
/// badge per row.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ChangeEntry {
/// Workspace-relative path. For renames this is the destination path.
pub path: String,
pub kind: ChangeKind,
pub additions: usize,
pub deletions: usize,
}
impl Default for ChangeEntry {
fn default() -> Self {
Self {
path: String::new(),
kind: ChangeKind::Modified,
additions: 0,
deletions: 0,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChangeKind {
StagedAdded,
StagedModified,
StagedDeleted,
StagedRenamed,
Modified,
Deleted,
Untracked,
Conflicted,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChangeSection {
Staged,
Changes,
Untracked,
Conflicts,
}
impl ChangeKind {
pub fn section(self) -> ChangeSection {
match self {
Self::StagedAdded
| Self::StagedModified
| Self::StagedDeleted
| Self::StagedRenamed => ChangeSection::Staged,
Self::Modified | Self::Deleted => ChangeSection::Changes,
Self::Untracked => ChangeSection::Untracked,
Self::Conflicted => ChangeSection::Conflicts,
}
}
pub fn badge(self) -> char {
match self {
Self::StagedAdded => 'A',
Self::StagedModified | Self::Modified => 'M',
Self::StagedDeleted | Self::Deleted => 'D',
Self::StagedRenamed => 'R',
Self::Untracked => 'U',
Self::Conflicted => '!',
}
}
}
/// Undo the C-style quoting `git status --porcelain` applies to paths
/// containing unusual characters (space, control chars, double-quote,
/// backslash, or — when `core.quotepath = true`, which is the default —
/// any non-ASCII byte). Plain ASCII paths pass through unchanged.
///
/// Quoted form: surrounded by `"`, with `\a \b \t \n \v \f \r \" \\`
/// single-char escapes and `\NNN` 3-digit octal escapes for any other
/// byte. Octal escapes are collected into a byte buffer first so that
/// multi-byte UTF-8 sequences (e.g. `\303\244` for `ä`) decode back to
/// the original character.
pub fn unquote_porcelain_path(raw: &str) -> String {
if !raw.starts_with('"') {
return raw.to_string();
}
let bytes = raw.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut i: usize = 1;
while i < bytes.len() {
let b = bytes[i];
if b == b'"' {
break;
}
if b == b'\\' && i + 1 < bytes.len() {
let n = bytes[i + 1];
match n {
b'a' => {
out.push(0x07);
i += 2;
}
b'b' => {
out.push(0x08);
i += 2;
}
b't' => {
out.push(b'\t');
i += 2;
}
b'n' => {
out.push(b'\n');
i += 2;
}
b'v' => {
out.push(0x0B);
i += 2;
}
b'f' => {
out.push(0x0C);
i += 2;
}
b'r' => {
out.push(b'\r');
i += 2;
}
b'"' => {
out.push(b'"');
i += 2;
}
b'\\' => {
out.push(b'\\');
i += 2;
}
b'0'..=b'7' => {
// Consume a run of `\NNN` triplets so multi-byte
// UTF-8 sequences land in `out` as raw bytes ready
// for the lossy decode below.
while i + 3 < bytes.len()
&& bytes[i] == b'\\'
&& (b'0'..=b'7').contains(&bytes[i + 1])
&& (b'0'..=b'7').contains(&bytes[i + 2])
&& (b'0'..=b'7').contains(&bytes[i + 3])
{
let val = ((bytes[i + 1] - b'0') as u16) * 64
+ ((bytes[i + 2] - b'0') as u16) * 8
+ ((bytes[i + 3] - b'0') as u16);
out.push(val as u8);
i += 4;
}
}
_ => {
out.push(b'\\');
i += 1;
}
}
} else {
out.push(b);
i += 1;
}
}
String::from_utf8_lossy(&out).into_owned()
}
/// The change kinds one porcelain v1 `XY` status code reports: a conflict
/// or an untracked file is one kind; otherwise the index (`X`) and worktree
/// (`Y`) columns each contribute one when set.
fn status_kinds(x: char, y: char) -> [Option<ChangeKind>; 2] {
// Conflicts: AA, DD, AU, UA, DU, UD, UU.
let conflict = matches!(
(x, y),
('A', 'A') | ('D', 'D') | ('A', 'U') | ('U', 'A') | ('D', 'U') | ('U', 'D') | ('U', 'U')
);
if conflict {
return [Some(ChangeKind::Conflicted), None];
}
if x == '?' && y == '?' {
return [Some(ChangeKind::Untracked), None];
}
let staged = (x != ' ' && x != '?').then_some(match x {
'A' => ChangeKind::StagedAdded,
'M' => ChangeKind::StagedModified,
'D' => ChangeKind::StagedDeleted,
'R' | 'C' => ChangeKind::StagedRenamed,
_ => ChangeKind::StagedModified,
});
let unstaged = (y != ' ' && y != '?').then_some(match y {
'M' => ChangeKind::Modified,
'D' => ChangeKind::Deleted,
_ => ChangeKind::Modified,
});
[staged, unstaged]
}
/// Parse `git status --porcelain` (v1) into the change entries the Source
/// Control panel renders. Each line is `XY <path>` where `X` is the index
/// status and `Y` is the worktree status; renames carry both old and new
/// paths separated by ` -> `. Paths with special characters arrive in
/// C-style quoted form — see `unquote_porcelain_path`.
pub fn parse_porcelain_changes(out: &str) -> Vec<ChangeEntry> {
let mut entries = Vec::new();
for line in out.lines() {
if line.len() < 3 {
continue;
}
let bytes = line.as_bytes();
let x = bytes[0] as char;
let y = bytes[1] as char;
let path_part = &line[3..];
let path = if let Some((_, dst)) = path_part.split_once(" -> ") {
unquote_porcelain_path(dst)
} else {
unquote_porcelain_path(path_part)
};
for kind in status_kinds(x, y).into_iter().flatten() {
entries.push(ChangeEntry {
path: path.clone(),
kind,
..Default::default()
});
}
}
entries
}
/// How the Explorer marks a changed path (#1513), after VS Code's git
/// decorations. Ordered weakest to strongest: a folder wears the strongest
/// status among the files beneath it.
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum GitDecoration {
Untracked,
Added,
Renamed,
Deleted,
Modified,
Conflicted,
}
impl GitDecoration {
/// The letter VS Code puts after a changed file's name.
pub fn letter(self) -> char {
match self {
Self::Untracked => 'U',
Self::Added => 'A',
Self::Renamed => 'R',
Self::Deleted => 'D',
Self::Modified => 'M',
Self::Conflicted => '!',
}
}
fn from_kind(kind: ChangeKind) -> Self {
match kind {
ChangeKind::StagedAdded => Self::Added,
ChangeKind::StagedModified | ChangeKind::Modified => Self::Modified,
ChangeKind::StagedDeleted | ChangeKind::Deleted => Self::Deleted,
ChangeKind::StagedRenamed => Self::Renamed,
ChangeKind::Untracked => Self::Untracked,
ChangeKind::Conflicted => Self::Conflicted,
}
}
}
/// The Explorer's decorations from `git status --porcelain -z` output
/// (#1513). Porcelain paths are toplevel-relative, so `prefix` (`rev-parse
/// --show-prefix`: where `root` sits in the repository) is stripped and the
/// rest joined onto `root`; a change outside `root` is not in its tree. A
/// partially staged file keeps its strongest status, and each folder between
/// a file and `root` takes the strongest status beneath it.
///
/// `-z` records are `XY <path>` with raw, unquoted path bytes, and a rename
/// or copy is followed by one more record holding its source. Paths stay
/// bytes until joined, so a filename that is not UTF-8 or that contains
/// ` -> ` still keys the exact path the file tree holds.
pub fn parse_decorations(
root: &Path,
prefix: &str,
porcelain: &[u8],
) -> HashMap<PathBuf, GitDecoration> {
let prefix = prefix.trim().as_bytes();
let mut out: HashMap<PathBuf, GitDecoration> = HashMap::new();
let mut records = porcelain.split(|b| *b == 0);
while let Some(record) = records.next() {
if record.len() < 4 {
continue;
}
let (x, y) = (record[0] as char, record[1] as char);
if matches!(x, 'R' | 'C') {
// The source path; a rename decorates its destination.
records.next();
}
let Some(rel) = record[3..].strip_prefix(prefix) else {
continue;
};
if rel.is_empty() {
continue;
}
let Some(dec) = status_kinds(x, y)
.into_iter()
.flatten()
.map(GitDecoration::from_kind)
.max()
else {
continue;
};
let mut path = join_raw(root, rel);
loop {
match out.get(&path) {
// Every ancestor already wears at least this status.
Some(&have) if have >= dec => break,
_ => {
out.insert(path.clone(), dec);
}
}
match path.parent() {
Some(parent) if parent != root && parent.starts_with(root) => {
path = parent.to_path_buf();
}
_ => break,
}
}
}
out
}
/// How many changed entries `git status --porcelain -z` output lists: one
/// per record, not counting the source record a rename or copy carries.
fn porcelain_z_count(porcelain: &[u8]) -> usize {
let mut count = 0;
let mut records = porcelain.split(|b| *b == 0);
while let Some(record) = records.next() {
if record.is_empty() {
continue;
}
count += 1;
if matches!(record.first(), Some(b'R' | b'C')) {
records.next();
}
}
count
}
/// Run `git status --porcelain` against `root` and return parsed entries.
/// Returns an empty vec on any error so the panel renders cleanly even
/// when the workspace isn't a git repo or git is missing.
///
/// Does not call `run_git`: that helper trims stdout, which destroys the
/// fixed-width porcelain v1 format (a line like ` M README.md` becomes
/// `M README.md` after `.trim()`, shifting the status code by one column).
pub fn query_changes(root: &Path) -> Vec<ChangeEntry> {
// Porcelain and numstat paths are TOPLEVEL-relative whatever `-C`
// names, so any filesystem read of an entry must join the toplevel,
// not the workspace root (#139).
let Some(toplevel) = repo_toplevel(root) else {
return Vec::new();
};
let path_str = match root.to_str() {
Some(s) => s,
None => return Vec::new(),
};
let output = match Command::new("git")
// Poll without taking index.lock; see run_git.
.env("GIT_OPTIONAL_LOCKS", "0")
.args(["-C", path_str, "status", "--porcelain", "--untracked-files=all"])
.output()
{
Ok(o) if o.status.success() => o,
_ => return Vec::new(),
};
let raw = String::from_utf8_lossy(&output.stdout);
let mut entries = parse_porcelain_changes(&raw);
let staged = numstat_map(path_str, &["diff", "--cached", "--numstat", "-z"]);
let unstaged = numstat_map(path_str, &["diff", "--numstat", "-z"]);
for entry in &mut entries {
let stats = match entry.kind.section() {
ChangeSection::Staged => staged.get(&entry.path),
ChangeSection::Changes => unstaged.get(&entry.path),
ChangeSection::Untracked => None,
ChangeSection::Conflicts => None,
};
if let Some((a, d)) = stats {
entry.additions = *a;
entry.deletions = *d;
}
}
for entry in &mut entries {
if matches!(entry.kind, ChangeKind::Untracked) {
entry.additions = count_lines_in_file(&toplevel, &entry.path);
}
}
entries
}
/// Parse `git diff --numstat -z` output into a path→(additions, deletions)
/// map. Each record is `\d+\t\d+\t<path>\0` for a text diff, or
/// `-\t-\t<path>\0` for a binary file (mapped to (0, 0): there's no
/// meaningful line count). A rename or copy leaves the path field empty and
/// follows it with two more fields, `<old>\0<new>\0`; we key on the
/// destination so the lookup matches what porcelain emitted (#1164). Without
/// `-z` git writes a rename as `src/{old.rs => new.rs}`, which matches no
/// porcelain path, and `-z` paths are never C-quoted.
pub fn parse_numstat(out: &str) -> std::collections::HashMap<String, (usize, usize)> {
let mut map = std::collections::HashMap::new();
let mut fields = out.split('\0');
while let Some(record) = fields.next() {
let mut parts = record.splitn(3, '\t');
let (Some(adds), Some(dels), Some(path)) = (parts.next(), parts.next(), parts.next())
else {
continue;
};
let additions = adds.parse::<usize>().unwrap_or(0);
let deletions = dels.parse::<usize>().unwrap_or(0);
let path = if path.is_empty() {
let _old = fields.next();
match fields.next() {
Some(new) => new.to_string(),
None => break,
}
} else {
path.to_string()
};
map.insert(path, (additions, deletions));
}
map
}
fn numstat_map(workdir: &str, args: &[&str]) -> std::collections::HashMap<String, (usize, usize)> {
let output = match Command::new("git")
// Poll without taking index.lock; see run_git.
.env("GIT_OPTIONAL_LOCKS", "0")
.args(["-C", workdir])
.args(args)
.output()
{
Ok(o) if o.status.success() => o,
_ => return std::collections::HashMap::new(),
};
parse_numstat(&String::from_utf8_lossy(&output.stdout))
}
fn count_lines_in_file(root: &Path, rel_path: &str) -> usize {
let abs = root.join(rel_path);
let Ok(bytes) = std::fs::read(&abs) else {
return 0;
};
if bytes.is_empty() {
return 0;
}
let mut lines = bytes.iter().filter(|b| **b == b'\n').count();
if !bytes.ends_with(b"\n") {
lines += 1;
}
lines
}
/// The clean/smudge filter `rel_path` goes through (`lfs` for a Git LFS
/// file), from `git check-attr filter`. `None` when no filter applies.
pub fn path_filter(root: &Path, rel_path: &str) -> Option<String> {
let out = Command::new("git")
.arg("-C")
.arg(root)
.args(["check-attr", "filter", "--", rel_path])
.output()
.ok()?;
let text = String::from_utf8_lossy(&out.stdout);
let value = text.trim_end().rsplit(": ").next()?;
match value {
"" => None,
// check-attr prints these states and the same-named values alike
// (`filter` and `filter=set` both read `set`): only a configured
// driver makes one a filter.
"unspecified" | "unset" | "set" if !filter_driver_configured(root, value) => None,
name => Some(name.to_string()),
}
}
/// Whether git config defines a `filter.<name>` driver.
fn filter_driver_configured(root: &Path, name: &str) -> bool {
Command::new("git")
.arg("-C")
.arg(root)
.args(["config", "--get-regexp"])
.arg(format!(
r"^filter\.{}\.(clean|smudge|process)$",
regex::escape(name)
))
.output()
.is_ok_and(|o| o.status.success() && !o.stdout.is_empty())
}
/// Result of an attempted commit. `Ok(summary)` carries git's stdout/stderr
/// summary (e.g. "[main 4a5b6c7] message"); `Err` carries git's error
/// Read the HEAD-committed contents of `rel_path` (workspace-relative)
/// via `git show HEAD:<rel_path>`. Used by the Source Control panel to
/// surface a side-by-side diff between the working tree and HEAD when
/// the user clicks a Modified entry. Returns the raw bytes as a String;
/// non-UTF8 content (binary file) is reported as an error so the caller
/// can fall back to opening the file directly.
pub fn read_file_at_head(root: &Path, rel_path: &str) -> Result<String, String> {
let bytes = read_bytes_at_head(root, rel_path)?;
String::from_utf8(bytes).map_err(|_| format!("{rel_path} at HEAD is not UTF-8"))
}
/// The raw bytes of `rel_path` at HEAD (`git show HEAD:<rel_path>`), for a
/// caller that decodes them itself, with the encoding the file's tab uses.
pub fn read_bytes_at_head(root: &Path, rel_path: &str) -> Result<Vec<u8>, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let spec = format!("HEAD:{rel_path}");
let output = show_blob(Path::new(path_str), &spec, rel_path)
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
return Err(if stderr.is_empty() {
format!(
"git show {spec} failed with code {:?}",
output.status.code()
)
} else {
stderr
});
}
Ok(output.stdout)
}
/// The `git` command that prints the blob `spec` names, for `rel_path`.
///
/// A filtered file (Git LFS) is stored in its clean form, a pointer, while
/// the working tree holds the smudged content: such a blob is read through
/// the filter (`cat-file --filters`), so every view of a past version shows
/// the file and not the pointer (#1238, #1338). Anything else is read with
/// `git show`, byte for byte as git stores it.
fn show_blob(root: &Path, spec: &str, rel_path: &str) -> Command {
let mut cmd = Command::new("git");
cmd.arg("-C").arg(root);
match path_filter(root, rel_path) {
Some(_) => cmd.args(["cat-file", "--filters"]),
None => cmd.arg("show"),
};
cmd.arg(spec);
cmd
}
/// The contents of `rel_path` (relative to `root`) at revision `rev`, via
/// `git show <rev>:./<rel_path>` (through the filter for a filtered file). The `./` makes the path relative to
/// `root` rather than to the repository top, so a workspace opened in a
/// subdirectory of a repo still reads the right file. `Err` when the file
/// did not exist at that revision or is not UTF-8.
pub fn read_file_at_rev(root: &Path, rev: &str, rel_path: &str) -> Result<String, String> {
let spec = format!("{rev}:./{rel_path}");
let output = show_blob(root, &spec, rel_path)
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if !output.status.success() {
return Err(String::from_utf8_lossy(&output.stderr).trim().to_string());
}
String::from_utf8(output.stdout).map_err(|_| format!("{rel_path} at {rev} is not UTF-8"))
}
/// Read one index stage of an unmerged path via `git show :N:<rel_path>`
/// — 1 = common ancestor (base), 2 = ours, 3 = theirs. The merge
/// editor's input source (#253). Errors when the stage does not exist
/// (e.g. no base for an added-by-both conflict, or the path is not
/// actually unmerged) or the blob is not UTF-8; the caller decides
/// whether that's fatal or means "empty side".
pub fn read_file_at_stage(root: &Path, rel_path: &str, stage: u8) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let spec = format!(":{stage}:{rel_path}");
let output = show_blob(Path::new(path_str), &spec, rel_path)
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
return Err(if stderr.is_empty() {
format!(
"git show {spec} failed with code {:?}",
output.status.code()
)
} else {
stderr
});
}
String::from_utf8(output.stdout)
.map_err(|_| format!("{rel_path} at stage {stage} is not UTF-8"))
}
/// The unmerged `rel_path`'s three index stages merged again by
/// `git merge-file --diff3`, whose conflicts keep each side whole where
/// git's default style trims what the sides share (the inline Accept
/// Both's source, see `merge::untrimmed_both`). Errors when a stage is
/// missing (not unmerged, or an add/add with no base) or git fails.
pub fn remerge_diff3(root: &Path, rel_path: &str) -> Result<String, String> {
static SEQ: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
let sides = [
("ours", read_file_at_stage(root, rel_path, 2)?),
("base", read_file_at_stage(root, rel_path, 1)?),
("theirs", read_file_at_stage(root, rel_path, 3)?),
];
// A directory of our own, made fresh: `create_dir_all` would take one
// another local user made first at this guessable name, and the writes
// below would follow the symlinks they left in it.
let nanos = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.subsec_nanos());
let dir = std::env::temp_dir().join(format!(
"croft-remerge-{}-{}-{nanos}",
std::process::id(),
SEQ.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
));
let mut builder = std::fs::DirBuilder::new();
#[cfg(unix)]
std::os::unix::fs::DirBuilderExt::mode(&mut builder, 0o700);
builder.create(&dir).map_err(|e| e.to_string())?;
let merged = (|| {
for (name, text) in &sides {
std::fs::write(dir.join(name), text).map_err(|e| e.to_string())?;
}
let output = Command::new("git")
.arg("-C")
.arg(root)
.args(["merge-file", "-p", "-q", "--diff3"])
.args(sides.iter().map(|(name, _)| dir.join(name)))
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
// The exit code is the conflict count (at most 127); an error
// exits negative, which reads as 255.
match output.status.code() {
Some(0..=127) => String::from_utf8(output.stdout)
.map_err(|_| format!("{rel_path} merged is not UTF-8")),
_ => Err(String::from_utf8_lossy(&output.stderr).trim().to_string()),
}
})();
let _ = std::fs::remove_dir_all(&dir);
merged
}
#[derive(Clone, Copy)]
enum HunkSide {
Old,
New,
}
/// `patch` with each `@@ -a,b +c,d @@` header's two starts set to the
/// `side` one, counts untouched.
fn retarget_hunk_starts(patch: &str, side: HunkSide) -> String {
let fix = |line: &str| -> Option<String> {
let rest = line.strip_prefix("@@ -")?;
let (old, rest) = rest.split_once(" +")?;
let (new, tail) = rest.split_once(" @@")?;
let start = |range: &str| range.split(',').next().map(str::to_string);
let count = |range: &str| range.split_once(',').map(|(_, c)| format!(",{c}"));
let pick = match side {
HunkSide::Old => start(old)?,
HunkSide::New => start(new)?,
};
Some(format!(
"@@ -{pick}{} +{pick}{} @@{tail}",
count(old).unwrap_or_default(),
count(new).unwrap_or_default()
))
};
// Split on `\n` only: a CRLF file's patch lines end in `\r`, which
// `str::lines` would strip.
patch
.split('\n')
.map(|l| fix(l).unwrap_or_else(|| l.to_string()))
.collect::<Vec<_>>()
.join("\n")
}
/// The path a single-file patch writes, from its `+++ b/<path>` header.
fn patch_path(patch: &str) -> Option<&str> {
patch
.split('\n')
.find_map(|l| l.strip_prefix("+++ b/"))
.map(|p| p.trim_end_matches('\r'))
}
/// Whether `git add` turns this path's CRLF line endings into LF in the
/// index, whatever decides it (`.gitattributes` `eol`/`text`,
/// `core.autocrlf`, `core.eol`): git cleans a probe line for the path and
/// the result is compared with the plain LF line.
fn strips_cr_on_add(root: &Path, rel: &str) -> bool {
let hash = |input: &[u8], args: &[&str]| -> Option<String> {
use std::io::Write as _;
let mut child = Command::new("git")
.arg("-C")
.arg(root)
.args(["hash-object", "--stdin"])
.args(args)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::null())
.spawn()
.ok()?;
child.stdin.take()?.write_all(input).ok()?;
let out = child.wait_with_output().ok()?;
out.status
.success()
.then(|| String::from_utf8_lossy(&out.stdout).trim().to_string())
};
let path_arg = format!("--path={rel}");
match (
hash(b"croft\r\n", &[&path_arg]),
hash(b"croft\n", &["--no-filters"]),
) {
(Some(cleaned), Some(lf)) => cleaned == lf,
_ => false,
}
}
/// `patch` with the `\r` dropped from the end of every added line.
fn strip_added_crs(patch: &str) -> String {
patch
.split('\n')
.map(|l| {
if l.starts_with('+') && !l.starts_with("+++ ") {
l.strip_suffix('\r').unwrap_or(l)
} else {
l
}
})
.collect::<Vec<_>>()
.join("\n")
}
/// `patch` with a `\r` put back on every context and removed line (the
/// ones taken from HEAD), to match a CRLF working tree.
fn add_crs_to_head_lines(patch: &str) -> String {
patch
.split('\n')
.map(|l| {
let from_head = (l.starts_with(' ') || l.starts_with('-')) && !l.starts_with("--- ");
if from_head && !l.ends_with('\r') {
format!("{l}\r")
} else {
l.to_string()
}
})
.collect::<Vec<_>>()
.join("\n")
}
/// Apply a unified-diff patch fed on stdin via `git apply`. `cached`
/// targets the index (stage), `reverse` un-applies (`cached + reverse` =
/// unstage, `reverse` alone = revert the working tree). Logged to the
/// OUTPUT panel's Git channel like every other mutation; the caller gets
/// git's verbatim error when a hunk no longer applies.
pub fn apply_patch(
root: &Path,
patch: &str,
cached: bool,
reverse: bool,
) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut args: Vec<&str> = vec!["-C", path_str, "apply", "--whitespace=nowarn"];
if cached {
args.push("--cached");
}
if reverse {
args.push("-R");
}
args.push("-");
// The diff's `@@ -old +new @@` counts HEAD lines on one side and
// working-tree lines on the other, and `git apply` starts its offset
// search at the side it writes to. A single-hunk patch lands on a target
// where no earlier hunk was applied, so each side's number is right for
// one target only: staging writes the index (HEAD's numbering), a revert
// writes the working tree (its own). With the other number, a file with
// repeated context took the patch at the wrong place.
// `git apply` patches a file in git's clean form: `--cached` writes the
// result into the index as it is, skipping the clean filter `git add`
// runs, so a hunk of an LFS file put the raw content into git where a
// pointer belongs; on the working tree the patch is matched against the
// cleaned text (the pointer) and never applies (#1238).
let paths = patch.lines().filter_map(|l| {
l.strip_prefix("+++ b/")
.or_else(|| l.strip_prefix("--- a/"))
});
for rel in paths {
if let Some(filter) = path_filter(root, rel) {
let whole = match (cached, reverse) {
(true, false) => "stage",
(true, true) => "unstage",
_ => "discard",
};
return Err(format!(
"{rel} uses the {filter} filter: {whole} the whole file, not a part"
));
}
}
let retargeted = match (cached, reverse) {
(true, false) => retarget_hunk_starts(patch, HunkSide::Old),
(false, true) => retarget_hunk_starts(patch, HunkSide::New),
_ => patch.to_string(),
};
// A path git stores LF but checks out CRLF (`eol=crlf`,
// `core.autocrlf`) has two spellings, and the patch mixes them: its
// added lines come from the working tree (CRLF), its context and
// removed lines from HEAD (LF). `git apply` uses no conversion, so each
// target needs the patch in its own spelling (#1236): the index gets
// the added lines cleaned, as `git add` would (verbatim, a CRLF
// checkout's `\r` made the blob mixed), and the working tree gets the
// HEAD lines with its `\r` (without, a revert did not apply at all).
let retargeted = match patch_path(&retargeted) {
Some(rel) if strips_cr_on_add(root, rel) => {
if cached {
strip_added_crs(&retargeted)
} else if std::fs::read(root.join(rel))
.is_ok_and(|b| b.windows(2).any(|w| w == b"\r\n"))
{
add_crs_to_head_lines(&retargeted)
} else {
retargeted
}
}
_ => retargeted,
};
let patch = retargeted.as_str();
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Info,
&format!("> git {} <<patch", args[2..].join(" ")),
);
let mut child = Command::new("git")
.args(&args)
.stdin(std::process::Stdio::piped())
.stdout(std::process::Stdio::piped())
.stderr(std::process::Stdio::piped())
.spawn()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if let Some(stdin) = child.stdin.take() {
use std::io::Write;
let mut stdin = stdin;
if let Err(e) = stdin.write_all(patch.as_bytes()) {
// Reap before bailing or the failed child lingers as a zombie.
drop(stdin);
let _ = child.wait();
return Err(format!("failed to feed patch to git apply: {e}"));
}
}
let output = child
.wait_with_output()
.map_err(|e| format!("git apply did not exit cleanly: {e}"))?;
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if output.status.success() {
Ok(if !stdout.is_empty() { stdout } else { stderr })
} else {
let msg = if !stderr.is_empty() { stderr } else { stdout };
let err = if msg.is_empty() {
format!("git apply failed with code {:?}", output.status.code())
} else {
msg
};
crate::output::push(
crate::output::CHANNEL_GIT,
crate::output::OutputLevel::Error,
&err,
);
Err(err)
}
}
/// Commit the way the Commit button, Enter in the message box, Commit &
/// Push and Commit & Sync do, by VS Code's rule (#965): with anything
/// staged, only the index (`git commit -m`), so hunks staged by hand go in
/// and the rest stays in the working tree; with nothing staged, every
/// tracked change (`git commit -am`, VS Code's smart commit). The index is
/// read at commit time, not from the panel's last status poll. Refuses an
/// empty message and an unresolved merge ([`refuse_unmerged`]); on failure
/// returns git's message verbatim so the user sees exactly what blocked them.
pub fn commit(root: &Path, message: &str) -> Result<String, String> {
if message.trim().is_empty() {
return Err("Commit message is empty".to_string());
}
refuse_unmerged(root)?;
let flags = if has_staged_changes(root)? {
"-m"
} else {
"-am"
};
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
// A hook or signing helper that wants a terminal fails fast with its
// own message instead of fighting croft for the screen (#1153).
let mut cmd = Command::new("git");
cmd.args(["-C", path_str, "commit", flags, message]);
never_prompt(&mut cmd);
let output = cmd
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if output.status.success() {
let summary = if !stdout.is_empty() { stdout } else { stderr };
Ok(summary)
} else {
let msg = if !stderr.is_empty() { stderr } else { stdout };
Err(if msg.is_empty() {
format!("git commit failed with code {:?}", output.status.code())
} else {
msg
})
}
}
/// The note git prints for each file a merge, rebase or stash pop merged
/// (`Auto-merging pricing.py`), before the line that says how that went.
const AUTO_MERGING: &str = "Auto-merging ";
/// What git's conflict line says before the file (`CONFLICT (content):
/// Merge conflict in pricing.py`).
const MERGE_CONFLICT_IN: &str = "Merge conflict in ";
/// `line` as a terminal shows it. Git redraws a progress line (`Rebasing
/// (1/1)`) by returning the carriage and, on a capable terminal, erasing
/// the line (`ESC [K`) before the next text, so what is left on screen is
/// the last redraw that says something (#858).
fn shown(line: &str) -> &str {
line.rsplit('\r')
.map(|part| part.trim_start_matches("\u{1b}[K"))
.find(|part| !part.trim().is_empty())
.unwrap_or_default()
}
/// `line` with its runs of whitespace collapsed to one space.
fn squash(line: &str) -> String {
line.split_whitespace().collect::<Vec<_>>().join(" ")
}
/// The first line of git's `output` (for a commit, `[branch sha] subject`):
/// what the Source Control panel and the status bar report. The rest, a
/// commit's diffstat and one `create mode` row per new file, ran on past
/// both (#858); the Git Output log keeps it whole. A merge's `Auto-merging`
/// notes give way to the result after them ("Merge made by the 'ort'
/// strategy."), and a line git redrew reads as [`shown`] ("Successfully
/// rebased …", not "Rebasing (1/1)"); a text of nothing but those notes is
/// its first one, never an empty line.
pub fn headline(output: &str) -> &str {
let said = || {
output
.lines()
.map(shown)
.filter(|line| !line.trim().is_empty())
};
said()
.find(|line| !line.starts_with(AUTO_MERGING))
.or_else(|| said().next())
.unwrap_or_default()
.trim_end()
}
/// The one line of git's `output` the status bar and the Source Control
/// panel report (#858); the Git Output log keeps the whole text. For a push
/// that is its ref update (`5a6cd5c..9f1e2d3 main -> main`, `[new branch]
/// main -> main`, `[rejected] main -> main (fetch first)`), otherwise the
/// first line that is not `remote:` chatter, a `hint:`, the `To <url>`
/// destination, the `On branch` / `Your branch` preamble git prints before
/// "nothing to commit" or an `Auto-merging` note. Lines read as [`shown`],
/// and runs of spaces collapse to one. Empty when nothing is left, as for a
/// push that printed only `remote:` lines.
pub fn summary_line(output: &str) -> String {
const NOISE: [&str; 6] = [
"remote:",
"hint:",
"To ",
"On branch ",
"Your branch ",
AUTO_MERGING,
];
let lines = || {
output
.lines()
.map(|l| shown(l).trim())
.filter(|l| !l.is_empty() && !NOISE.iter().any(|n| l.starts_with(n)))
};
let Some(line) = lines()
.find(|l| l.contains(" -> "))
.or_else(|| lines().next())
else {
return String::new();
};
let mut words = line.split_whitespace().peekable();
// A ref update leads with git's one-character flag (`*`, `+`, `-`, `!`,
// `=`, or a space, which trimming already took).
if words
.peek()
.is_some_and(|w| matches!(*w, "*" | "+" | "-" | "!" | "="))
{
words.next();
}
words.collect::<Vec<_>>().join(" ")
}
/// The one line a git operation that succeeded reports in the status bar
/// and the Source Control panel (#858): git's result ("Already up to
/// date.", "Fast-forward", "Merge made by the 'ort' strategy.",
/// "Successfully rebased and updated refs/heads/main.", "Dropped
/// refs/stash@{0} (…)", "[main 5a6cd5c] subject"). Passed over on the way:
/// the fetch's `From <url>` and the push's `To <url>`, `remote:` chatter,
/// `hint:`s, `Updating a..b`, `Fetching <remote>`, `Auto-merging` notes,
/// the `warning:` / `error:` / `fatal:` asides a success can still carry
/// (a failed push negotiation), the `git status` dump a stash or a switch
/// prints, the `M\tpath` rows a switch lists, and every indented line (ref
/// updates, the diffstat, file lists). Lines read as [`shown`]. When
/// nothing else is left, the ref update if there is one ([`summary_line`]),
/// else empty, and the caller's own word ("Pulled", "Applied stash") says
/// it; the Git Output log keeps git's whole text.
pub fn result_line(output: &str) -> String {
const NOISE: [&str; 18] = [
"From ",
"To ",
"remote:",
"hint:",
"Updating ",
"Fetching ",
AUTO_MERGING,
"warning:",
"error:",
"fatal:",
"On branch ",
"Your branch ",
"Changes not staged for commit:",
"Changes to be committed:",
"Untracked files:",
"Unmerged paths:",
"no changes added to commit",
"nothing added to commit",
];
// `M\tpath`: a file `git switch` carried over.
let file_row = |line: &str| {
let bytes = line.as_bytes();
bytes.len() > 1 && bytes[0].is_ascii_uppercase() && bytes[1] == b'\t'
};
let result = output.lines().map(shown).find(|line| {
!line.trim().is_empty()
&& !line.starts_with(char::is_whitespace)
&& !file_row(line)
&& !NOISE.iter().any(|n| line.starts_with(n))
});
match result {
Some(line) => line.trim_end().to_string(),
None if output.contains(" -> ") => summary_line(output),
None => String::new(),
}
}
/// The conflicts git stopped on, from the `CONFLICT …` lines of its
/// `output` (#858): "1 conflict (pricing.py)", "2 conflicts (a.py, b.py)",
/// naming three files at most before "…". A lone conflict git words
/// without "Merge conflict in <file>" (`CONFLICT (modify/delete): …`) is
/// git's own line. `None` when git reported no conflict.
pub fn conflict_summary(output: &str) -> Option<String> {
const NAMED: usize = 3;
let conflicts: Vec<&str> = output
.lines()
.map(|l| shown(l).trim())
.filter(|l| l.starts_with("CONFLICT ("))
.collect();
match conflicts.as_slice() {
[] => return None,
[only] if !only.contains(MERGE_CONFLICT_IN) => return Some(squash(only)),
_ => {}
}
let mut files: Vec<&str> = Vec::new();
let mut unnamed = 0;
for line in &conflicts {
match line.split_once(MERGE_CONFLICT_IN) {
Some((_, file)) if !files.contains(&file.trim()) => files.push(file.trim()),
Some(_) => {}
None => unnamed += 1,
}
}
let count = files.len() + unnamed;
let noun = if count == 1 { "conflict" } else { "conflicts" };
if files.is_empty() {
return Some(format!("{count} {noun}"));
}
let mut names = files[..files.len().min(NAMED)].join(", ");
if count > NAMED.min(files.len()) {
names.push_str(", \u{2026}");
}
Some(format!("{count} {noun} ({names})"))
}
/// The one line of git's error text `err` the status bar and the Source
/// Control panel report (#858); the Git Output log keeps the whole text.
/// First the conflicts git stopped on ([`conflict_summary`]), then a
/// rejected ref update (`[rejected] main -> main (fetch first)`), then
/// git's first `error:` or `fatal:` line, with the files git listed under
/// it ([`with_listed_files`]), then [`summary_line`]. Failing all of those,
/// the first line, so a refusal always says something.
pub fn error_line(err: &str) -> String {
if let Some(conflicts) = conflict_summary(err) {
return conflicts;
}
let lines = || err.lines().map(|l| shown(l).trim());
if let Some(rejected) = lines().find_map(|l| l.strip_prefix('!').filter(|_| l.contains(" -> ")))
{
return squash(rejected);
}
if let Some(at) = lines().position(|l| l.starts_with("error:") || l.starts_with("fatal:")) {
let line = lines().nth(at).map(squash).unwrap_or_default();
return with_listed_files(line, err.lines().skip(at + 1));
}
let line = summary_line(err);
if line.is_empty() {
headline(err).to_string()
} else {
line
}
}
/// `line`, git's `error:` line, followed by the files git listed under it
/// when it ends in a colon (#925): "…would be overwritten by checkout:
/// a.txt" names what is in the way, where the line alone stopped at the
/// colon. Git indents each file on a line of its own after it; three are
/// named at most before "…".
fn with_listed_files<'a>(mut line: String, after: impl Iterator<Item = &'a str>) -> String {
const NAMED: usize = 3;
if !line.ends_with(':') {
return line;
}
let files: Vec<&str> = after
.map(shown)
.take_while(|l| l.starts_with(char::is_whitespace) && !l.trim().is_empty())
.map(str::trim)
.collect();
if files.is_empty() {
return line;
}
line.push(' ');
line.push_str(&files[..files.len().min(NAMED)].join(", "));
if files.len() > NAMED {
line.push_str(", \u{2026}");
}
line
}
/// Whether git refused a branch switch because it would overwrite local
/// changes (#925), the refusal a stash gets past. Git ends it with "Please
/// commit your changes or stash them before you switch branches."; a switch
/// blocked by untracked files asks to "move or remove them" instead, and
/// when git names both a stash of the tracked changes still leaves the
/// switch refused, so that is not one either.
pub fn local_changes_block_switch(err: &str) -> bool {
err.contains("commit your changes or stash them") && !err.contains("move or remove them")
}
/// A failed git operation's one line (#858), `noun` naming the operation
/// ("Merge", "Pop stash"): "Merge: 1 conflict (pricing.py)" when git
/// stopped on conflicts, which wait on the user to resolve them, otherwise
/// "Merge failed: " and git's [`error_line`].
pub fn failure_line(noun: &str, err: &str) -> String {
match conflict_summary(err) {
Some(conflicts) => format!("{noun}: {conflicts}"),
None => format!("{noun} failed: {}", error_line(err)),
}
}
/// Push the current branch to its upstream. Used by Commit & Push
/// (Cmd+Enter in the SC message box). Returns the trimmed stdout/stderr
/// summary verbatim so the panel can surface the host's full message —
/// `git push` typically reports the ref update on stderr even on success.
pub fn push_current_branch(root: &Path) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut cmd = Command::new("git");
cmd.args(["-C", path_str, "push"]);
never_prompt(&mut cmd);
let output = cmd
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
if output.status.success() {
let summary = if !stderr.is_empty() { stderr } else { stdout };
Ok(summary)
} else {
let msg = if !stderr.is_empty() { stderr } else { stdout };
Err(if msg.is_empty() {
format!("git push failed with code {:?}", output.status.code())
} else {
msg
})
}
}
/// Raw `git diff --staged` text — everything currently in the index that
/// would land in the next commit. Empty string when nothing is staged
/// (matches git's own zero-output behaviour). Errors carry stderr verbatim
/// so the panel can surface "fatal: not a git repository" etc.
pub fn diff_staged(root: &Path) -> Result<String, String> {
diff_text(root, &["diff", "--staged"])
}
/// The commit HEAD and `branch` last had in common (`git merge-base`), or
/// None when they share no history or `branch` does not resolve.
pub fn merge_base(root: &Path, branch: &str) -> Option<String> {
diff_text(root, &["merge-base", "HEAD", branch])
.ok()
.map(|out| out.trim().to_string())
.filter(|sha| !sha.is_empty())
}
/// The working tree against the point the current branch left `branch`
/// (its merge base), as a pull request diff shows it: every committed and
/// uncommitted change on this branch, and nothing `branch` gained since
/// (#1444). Diffing against `branch`'s tip listed that later work as this
/// branch deleting or reverting it. With no shared history it falls back
/// to the tip. Used by the Source Control dropdown's "View Changes vs
/// <default>" and that tab's refresh.
pub fn diff_against_branch(root: &Path, branch: &str) -> Result<String, String> {
match merge_base(root, branch) {
Some(base) => diff_text(root, &["diff", &base]),
None => diff_text(root, &["diff", branch]),
}
}
/// Raw `git diff HEAD~1` text — working-tree state versus the commit
/// before HEAD. Used by the Source Control dropdown's "View Changes vs
/// previous" so users can preview everything that changed since the last
/// commit. Errors (e.g. "fatal: ambiguous argument 'HEAD~1'" on a repo
/// with a single commit) carry stderr verbatim so the panel can surface
/// the reason instead of a silent no-op.
pub fn diff_previous_commit(root: &Path) -> Result<String, String> {
diff_text(root, &["diff", "HEAD~1"])
}
fn diff_text(root: &Path, args: &[&str]) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut cmd = Command::new("git");
cmd.args(["-C", path_str]);
match args.split_first() {
// The patch croft parses, never the user's display settings
// (#1447): `color.ui = always` wrapped every line in escape codes,
// and a `diff.external` tool (difftastic) printed its own view in
// place of the patch.
Some((sub, rest)) if matches!(*sub, "diff" | "show") => {
cmd.arg(sub)
.args(["--no-color", "--no-ext-diff"])
.args(rest);
}
_ => {
cmd.args(args);
}
}
let output = cmd
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if output.status.success() {
Ok(String::from_utf8_lossy(&output.stdout).into_owned())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let msg = if !stderr.is_empty() { stderr } else { stdout };
Err(if msg.is_empty() {
format!("git {args:?} failed with code {:?}", output.status.code())
} else {
msg
})
}
}
/// One commit in a file's history, for the Explorer TIMELINE view.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FileHistoryEntry {
pub short_hash: String,
pub summary: String,
pub author: String,
/// Seconds elapsed since the commit time, for [`humanize_age`].
pub age_secs: i64,
}
/// The folder to run a per-file query from, and the pathspec to pass it:
/// the file's own folder and name, so git finds the repo that holds the
/// file even when `root` (the workspace) sits above it (#1227). A
/// cwd-relative pathspec is exact with `-C`. Falls back to `root` and
/// `rel_path` when that folder is gone (a deleted file's history).
fn file_cwd(root: &Path, rel_path: &str) -> (PathBuf, String) {
let abs = root.join(rel_path);
match (abs.parent(), abs.file_name().and_then(|n| n.to_str())) {
(Some(dir), Some(name)) if dir.is_dir() => (dir.to_path_buf(), name.to_string()),
_ => (root.to_path_buf(), rel_path.to_string()),
}
}
/// The top of the repository that holds `rel_path`, found from the file's
/// own folder as [`file_cwd`] finds it, and the file's path from that top,
/// which is how the rename walk in [`path_at_commit`] names it. Git run in a
/// workspace that sits above a nested repository finds none (#1556). Falls
/// back to `root` and `rel_path` outside any repository.
fn repo_top_and_path(root: &Path, rel_path: &str) -> (PathBuf, String) {
let (dir, name) = file_cwd(root, rel_path);
let out = run_git(&dir, &["rev-parse", "--show-toplevel", "--show-prefix"]);
let mut lines = out.as_deref().unwrap_or_default().lines();
match lines.next() {
Some(top) if !top.is_empty() => {
let prefix = lines.next().unwrap_or_default();
(PathBuf::from(top), format!("{prefix}{name}"))
}
_ => (root.to_path_buf(), rel_path.to_string()),
}
}
/// Recent commits touching `rel_path`, newest first, via `git log --follow`
/// (so the history survives renames, like VS Code's Timeline). Returns an
/// empty vec when the path is untracked, the repo has no history, or git is
/// unavailable — the panel renders that as an empty state, never an error.
pub fn file_history(root: &Path, rel_path: &str, limit: usize) -> Vec<FileHistoryEntry> {
let (dir, name) = file_cwd(root, rel_path);
let Some(path_str) = dir.to_str() else {
return Vec::new();
};
let output = Command::new("git")
.args([
"-C",
path_str,
"log",
"--follow",
&format!("-n{limit}"),
"--format=%h\x1f%s\x1f%an\x1f%ct",
"--",
&name,
])
.output();
let Ok(output) = output else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
parse_file_history(
&String::from_utf8_lossy(&output.stdout),
current_unix_seconds(),
)
}
/// Parse the `%h\x1f%s\x1f%an\x1f%ct` lines emitted by [`file_history`] into
/// entries, computing each commit's age relative to `now` (unix seconds).
pub fn parse_file_history(out: &str, now: i64) -> Vec<FileHistoryEntry> {
out.lines()
.filter_map(|line| {
let mut parts = line.split('\x1f');
let short_hash = parts.next()?.to_string();
let summary = parts.next()?.to_string();
let author = parts.next()?.to_string();
let ct: i64 = parts.next()?.trim().parse().ok()?;
if short_hash.is_empty() {
return None;
}
Some(FileHistoryEntry {
short_hash,
summary,
author,
age_secs: now - ct,
})
})
.collect()
}
/// Raw `git show <hash> -- <rel_path>` text: the file's diff in that commit,
/// for opening a TIMELINE entry in the side-by-side diff viewer. Run in the
/// repository that holds the file, wherever the workspace `root` sits.
pub fn show_commit_file_diff(root: &Path, hash: &str, rel_path: &str) -> Result<String, String> {
let (top, path) = repo_top_and_path(root, rel_path);
let (root, rel_path) = (top.as_path(), path.as_str());
if path_filter(root, rel_path).is_some() {
return filtered_commit_file_diff(root, hash, rel_path);
}
let has_diff = |raw: &str| raw.lines().any(|l| l.starts_with("diff --git"));
let raw = diff_text(root, &["show", hash, "--", rel_path])?;
if has_diff(&raw) {
return Ok(raw);
}
// The TIMELINE lists history with `--follow`, so a commit from before a
// rename touched the file under its OLD name, and showing it under the
// current one was an empty diff. The follow walk says what it was called.
match path_at_commit(root, hash, rel_path) {
Some(old) if old != rel_path => diff_text(root, &["show", hash, "--", &old]),
_ => Ok(raw),
}
}
/// The commits that touched `rel_path`, newest first, each with the name
/// the file had there: `git log --follow`, so the walk carries on past a
/// rename under the old name (#1304). Paths are relative to `root`, as
/// [`read_file_at_rev`] takes them. Empty when git fails.
pub fn follow_names(root: &Path, rel_path: &str, limit: usize) -> Vec<(String, String)> {
let Ok(out) = run_git(
root,
&[
"log",
"--follow",
// The scrubber walks first parents: a rename merged from a side
// branch then lands on the merge, which a full walk skips for
// the side branch's own commits (#1304).
"--first-parent",
&format!("-n{limit}"),
"--name-only",
"--relative",
"--format=%x1e%H",
"--",
rel_path,
],
) else {
return Vec::new();
};
out.split('\x1e')
.filter_map(|record| {
let mut lines = record.lines();
let hash = lines.next()?.trim();
let path = lines.map(str::trim).find(|l| !l.is_empty())?;
(!hash.is_empty()).then(|| (hash.to_string(), unquote_porcelain_path(path)))
})
.collect()
}
/// [`show_commit_file_diff`] for a filtered file (#1338). `git show` diffs
/// the stored blobs, which for Git LFS are pointers whose only change is the
/// `oid` line, so the two sides are read through the filter instead and
/// diffed here, under the commit's own `git show` header, in the shape the
/// viewer parses for an unfiltered file.
fn filtered_commit_file_diff(root: &Path, hash: &str, rel_path: &str) -> Result<String, String> {
let name = match read_file_at_rev(root, hash, rel_path) {
Ok(_) => rel_path.to_string(),
Err(_) => path_at_commit(root, hash, rel_path).unwrap_or_else(|| rel_path.to_string()),
};
let new = read_file_at_rev(root, hash, &name)?;
// Absent before this commit (the file was added here, or this is the
// root commit): every line is new.
let old = read_file_at_rev(root, &format!("{hash}^"), &name).unwrap_or_default();
let body = similar::TextDiff::from_lines(&old, &new)
.unified_diff()
.header(&format!("a/{name}"), &format!("b/{name}"))
.to_string();
let header = diff_text(root, &["show", "-s", hash])?;
Ok(format!("{header}\ndiff --git a/{name} b/{name}\n{body}"))
}
/// The name `rel_path` had in commit `hash`, from the same `--follow` walk
/// [`file_history`] lists. None when the commit is not in that history.
fn path_at_commit(root: &Path, hash: &str, rel_path: &str) -> Option<String> {
let out = run_git(
root,
&[
"log",
"--follow",
// As deep as the TIMELINE lists (`file_history`'s 50), with room
// to spare: a row past it cannot be clicked, and the full walk
// of a long history was the slow part.
"-n200",
"--name-only",
"--format=%x1e%H",
"--",
rel_path,
],
)
.ok()?;
out.split('\x1e').find_map(|record| {
let mut lines = record.lines();
let full = lines.next()?.trim();
if hash.is_empty() || !full.starts_with(hash) {
return None;
}
lines
.map(str::trim)
.find(|l| !l.is_empty())
.map(unquote_porcelain_path)
})
}
/// The whole commit as text — header, message, diffstat, and full patch —
/// for the Source Control graph's click-to-open view (the tig / lazygit
/// idiom for inspecting a commit in a terminal).
pub fn show_commit(root: &Path, hash: &str) -> Result<String, String> {
diff_text(root, &["show", "--stat", "--patch", hash])
}
/// One commit of the repo-wide Source Control graph, straight off
/// `git log --topo-order` with its parent hashes (the lane layout's input)
/// and its decorations (branch / tag / HEAD ref names).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GraphCommit {
pub hash: String,
pub short_hash: String,
pub parents: Vec<String>,
/// Decoration names as git prints them (`HEAD -> main`, `origin/main`,
/// `tag: v1.0`), split per ref; empty for an undecorated commit.
pub refs: Vec<String>,
pub summary: String,
pub author: String,
/// Seconds elapsed since the commit time, for [`humanize_age`].
pub age_secs: i64,
}
/// The newest `limit` commits across local branches, tags, and HEAD in
/// topological order (parents never precede children), the input to the
/// Source Control graph. Empty on any failure — no repo, no commits, no git —
/// so the panel renders an empty state, never an error.
pub fn commit_graph(root: &Path, limit: usize) -> Vec<GraphCommit> {
let Some(path_str) = root.to_str() else {
return Vec::new();
};
let output = Command::new("git")
.args([
"-C",
path_str,
"log",
"--branches",
"--tags",
"HEAD",
"--topo-order",
&format!("-n{limit}"),
"--format=%H\x1f%h\x1f%P\x1f%D\x1f%s\x1f%an\x1f%ct",
])
.output();
let Ok(output) = output else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
parse_commit_graph(
&String::from_utf8_lossy(&output.stdout),
current_unix_seconds(),
)
}
/// A worktree lane: a branch and the sibling directory it lives in (#348).
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct WorktreeLane {
/// Absolute path of the worktree, a SIBLING of the repo.
pub path: PathBuf,
/// The branch created for the lane.
pub branch: String,
/// The branch the lane was cut FROM, recorded at creation (#348).
///
/// Not derivable later. `worktree add -b` takes no start-point, so the
/// lane forks from whatever HEAD was; git records that only in the
/// reflog, which is local, prunable and absent from a fresh clone — so a
/// lane made on one machine has no base to recover on another.
/// `merge-base` cannot help either: it needs the candidate, which is the
/// thing being asked for. Creation is the only moment the answer is free.
///
/// `None` when HEAD was detached at creation, which has no branch name
/// to record and must not be guessed at.
pub base: Option<String>,
}
impl WorktreeLane {
/// Plan a lane for `name` beside `repo`, or `None` when the name has
/// nothing usable in it.
///
/// Refused rather than defaulted: a name of `"..."` would otherwise
/// become the branch `agent/` and the directory `croft-`, and a branch
/// named after nothing is worse than being told to pick a name.
///
/// The slug is what makes both halves safe at once. git refuses a ref
/// containing `..`, whitespace, or any of `~^:?*[\`, and a directory
/// name carrying those is a different kind of trouble — so one pass
/// reducing to `[a-z0-9-]` covers the ref grammar and the filesystem
/// together, rather than sanitising twice with two chances to disagree.
pub fn plan(repo: &Path, name: &str) -> Option<Self> {
let slug = lane_slug(name)?;
// A SIBLING, never a child. A worktree inside its own repo is a
// working tree git then tries to track, and the Explorer would show
// the lane nested in the root it was cut from.
let parent = repo.parent()?;
let base = repo.file_name()?.to_string_lossy();
Some(Self {
path: parent.join(format!("{base}-{slug}")),
branch: format!("agent/{slug}"),
// `plan` is pure - it runs no git. The base is filled in by
// `add_worktree_lane`, which is already running git and is the
// moment HEAD is still the branch being forked from.
base: None,
})
}
}
/// Reduce `name` to `[a-z0-9-]`, or `None` when nothing survives.
fn lane_slug(name: &str) -> Option<String> {
let mapped: String = name
.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect();
// Collapse runs so `a b` is `a-b` rather than `a--b`, and trim so the
// branch never starts or ends on the separator — git refuses a ref
// component ending in `.`, and a trailing `-` merely looks broken.
let mut out = String::new();
for part in mapped.split('-').filter(|p| !p.is_empty()) {
if !out.is_empty() {
out.push('-');
}
out.push_str(part);
}
if out.is_empty() {
return None;
}
// Capped, because the slug becomes a DIRECTORY name as well as a branch:
// git accepts a ref of any length, but a filesystem component past ~255
// bytes fails at `mkdir` with "File name too long" — measured — and the
// user would see that instead of anything about lanes. 60 is far more
// than a lane name needs. Trimmed again because the cut can land on the
// separator.
let capped: String = out.chars().take(60).collect();
let capped = capped.trim_matches('-');
(!capped.is_empty()).then(|| capped.to_string())
}
/// Why `lane` must not be removed, or `None` when it is safe to remove.
///
/// `git worktree remove` DISCARDS a dirty tree, so this is the one check in
/// the lane flow where being wrong destroys work rather than annoying
/// someone. It answers with a reason rather than a bool so the caller can
/// tell the user what to do about it.
///
/// A tree git cannot report on is treated as unsafe: an unreadable status is
/// not evidence of cleanliness, and refusing costs a user one manual
/// `git worktree remove` while guessing costs them their work.
pub fn lane_removal_block(lane: &Path) -> Option<String> {
let Some(path_str) = lane.to_str() else {
return Some(format!("{} is not a readable path", lane.display()));
};
let output = Command::new("git")
.args(["-C", path_str, "status", "--porcelain", "--ignored"])
.output();
let Ok(output) = output else {
return Some(String::from(
"could not run git to check for uncommitted work",
));
};
if !output.status.success() {
return Some(format!("{path_str} does not look like a git worktree"));
}
let dirty = String::from_utf8_lossy(&output.stdout);
let mut changed = 0usize;
let mut ignored = 0usize;
for line in dirty.lines().filter(|l| !l.trim().is_empty()) {
// `!!` is an IGNORED entry, which `--ignored` adds and plain
// `--porcelain` omits entirely. Counted separately because the two
// want different words, but both must refuse: `git worktree remove`
// deletes ignored files without a murmur, and an agent lane is
// exactly where an uncommitted `.env`, a local database, or an
// expensive `node_modules` lives. Measured — a `.env` in a lane was
// destroyed while plain `--porcelain` reported the tree clean.
if line.starts_with("!!") {
ignored += 1;
} else {
changed += 1;
}
}
match (changed, ignored) {
(0, 0) => None,
(0, n) => Some(format!(
"this lane has {n} ignored file{} (build output, local config) that removal would \
delete — clear them by hand first",
if n == 1 { "" } else { "s" }
)),
(1, _) => Some(String::from(
"this lane has 1 file with uncommitted changes — commit or discard it first",
)),
(n, _) => Some(format!(
"this lane has {n} files with uncommitted changes — commit or discard them first"
)),
}
}
/// Run a MUTATING git command, returning git's own error text.
///
/// Separate from the read-only `run_git` above, which goes out of its way to
/// avoid taking `.git/index.lock` because `status` and `diff` opportunistically
/// rewrite the index. A worktree add or remove genuinely changes the repo and
/// must take the lock like any other write.
fn run_git_mut(dir: &Path, args: &[&str]) -> Result<(), String> {
let Some(dir) = dir.to_str() else {
return Err(String::from("path is not valid UTF-8"));
};
let output = Command::new("git")
.args(["-C", dir])
.args(args)
.output()
.map_err(|e| e.to_string())?;
if output.status.success() {
return Ok(());
}
// git's own message, which names the actual problem — a branch that
// exists, a path in use, a repo with no commits — far better than any
// sentence this could invent.
let err = String::from_utf8_lossy(&output.stderr);
Err(err
.trim()
.lines()
.next()
.unwrap_or("git failed")
.to_string())
}
/// Add `lane` as a worktree of `repo` on a new branch.
pub fn add_worktree_lane(repo: &Path, lane: &mut WorktreeLane) -> Result<(), String> {
let Some(path) = lane.path.to_str().map(str::to_owned) else {
return Err(String::from("lane path is not valid UTF-8"));
};
// READ before the command, while HEAD is still the branch the lane forks
// from - afterwards it is gone, see `WorktreeLane::base`. But ASSIGN only
// once creation succeeded: a failed `worktree add` leaves no lane, and a
// base recorded on one that does not exist is a fact about nothing that a
// retry would then carry.
let base = current_branch(repo);
run_git_mut(repo, &["worktree", "add", "-b", &lane.branch, &path])?;
lane.base = base;
Ok(())
}
/// The branch HEAD is on, or `None` when detached.
///
/// `--quiet` so a detached HEAD is an empty result rather than an error the
/// caller has to distinguish from a failure.
pub fn current_branch(root: &Path) -> Option<String> {
let out = run_git(root, &["symbolic-ref", "--quiet", "--short", "HEAD"]).ok()?;
let name = out.trim();
(!name.is_empty()).then(|| name.to_string())
}
/// Remove `lane`'s worktree.
///
/// No `--force`: the caller has already asked [`lane_removal_block`], and a
/// force here would defeat that check by making the refusal advisory. If git
/// refuses anyway, the reason reaches the user rather than being overridden.
pub fn remove_worktree_lane(lane: &Path) -> Result<(), String> {
let Some(path) = lane.to_str() else {
return Err(String::from("lane path is not valid UTF-8"));
};
// Run from the lane itself: git resolves the main worktree from there,
// so the caller does not have to remember which repo it was cut from.
run_git_mut(lane, &["worktree", "remove", path])
}
/// Where review mode checks pull request `number` out (#365): a sibling of
/// `repo`, like a worktree lane, never a child git would then see.
pub fn pr_worktree_path(repo: &Path, number: u64) -> Option<PathBuf> {
let name = repo.file_name()?.to_str()?;
Some(repo.parent()?.join(format!("{name}-pr-{number}")))
}
/// Which remote to fetch `owner/repo`'s pull requests from: the one whose
/// URL names it (`git@github.com:o/r.git`, `https://github.com/o/r`), else
/// the repository's own URL, which `git fetch` takes as well.
pub fn remote_for_slug(repo: &Path, slug: &str) -> String {
let slug = slug.to_ascii_lowercase();
let names = |url: &str| {
let url = url.trim().to_ascii_lowercase();
let url = url.strip_suffix(".git").unwrap_or(&url).to_string();
url.ends_with(&format!("/{slug}")) || url.ends_with(&format!(":{slug}"))
};
run_git(repo, &["remote", "-v"])
.ok()
.and_then(|out| {
out.lines().find_map(|l| {
let mut parts = l.split_whitespace();
let (name, url) = (parts.next()?, parts.next()?);
names(url).then(|| name.to_string())
})
})
.unwrap_or_else(|| format!("https://github.com/{slug}.git"))
}
/// Whether `path` is one of `repo`'s worktrees.
fn is_worktree_of(repo: &Path, path: &Path) -> bool {
let want = path.canonicalize().ok();
run_git(repo, &["worktree", "list", "--porcelain"]).is_ok_and(|out| {
out.lines()
.filter_map(|l| l.strip_prefix("worktree "))
.any(|w| Path::new(w).canonicalize().ok() == want)
})
}
/// A pull request head checked out by [`checkout_pr_worktree`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PrWorktree {
/// The commit checked out.
pub oid: String,
/// Whether this call created the worktree. One that was already there
/// is the user's as much as review mode's, and leaving never removes it.
pub created: bool,
}
/// Fetch pull request `number` from `remote` and check its head out,
/// detached, in a worktree at `path` (#365).
///
/// An existing worktree of the same repository is moved to the new head
/// only when that loses nothing: it is clean, and its HEAD is the fetched
/// head already or `previous`, the head review mode checked out there last.
/// Any other HEAD holds commits that a detached checkout would leave to the
/// reflog. Anything else already at `path` is refused, never touched.
pub fn checkout_pr_worktree(
repo: &Path,
remote: &str,
number: u64,
path: &Path,
previous: Option<&str>,
) -> Result<PrWorktree, String> {
let Some(path_s) = path.to_str() else {
return Err(String::from("worktree path is not valid UTF-8"));
};
let Some(repo_s) = repo.to_str() else {
return Err(String::from("repository path is not valid UTF-8"));
};
// No prompt: this runs off the UI thread, where a credential prompt,
// or ssh's own passphrase or host-key question on /dev/tty, would wait
// forever on a terminal nobody sees, or draw over the UI.
let mut fetch = Command::new("git");
fetch
.args(["-C", repo_s, "fetch", "--quiet", remote])
.arg(format!("refs/pull/{number}/head"));
never_prompt(&mut fetch);
let fetch = fetch.output().map_err(|e| e.to_string())?;
if !fetch.status.success() {
let err = String::from_utf8_lossy(&fetch.stderr);
return Err(err
.trim()
.lines()
.next()
.unwrap_or("git fetch failed")
.to_string());
}
let oid = run_git(repo, &["rev-parse", "FETCH_HEAD"])
.map_err(|e| e.to_string())?
.trim()
.to_string();
if path.exists() {
if !is_worktree_of(repo, path) {
return Err(format!(
"{path_s} already exists and is not a worktree of this repository"
));
}
let head = worktree_head(path);
if head.as_deref() != Some(oid.as_str()) {
if let Some(why) = lane_removal_block(path) {
return Err(format!("the existing checkout has work in it: {why}"));
}
if previous.is_none() || head.as_deref() != previous {
return Err(format!(
"{path_s} is at a commit review mode did not check out — put that work on a branch, or remove the worktree"
));
}
}
run_git_mut(path, &["checkout", "--quiet", "--detach", &oid])?;
Ok(PrWorktree {
oid,
created: false,
})
} else {
run_git_mut(repo, &["worktree", "add", "--detach", path_s, &oid])?;
Ok(PrWorktree { oid, created: true })
}
}
/// The commit a worktree's HEAD is on.
pub fn worktree_head(path: &Path) -> Option<String> {
run_git(path, &["rev-parse", "HEAD"])
.ok()
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
/// Why leaving review must keep the pull request's checkout: uncommitted or
/// ignored files (see [`lane_removal_block`]), or commits made on top of the
/// checked-out head, which a detached worktree would leave unreachable.
pub fn pr_worktree_keep_reason(path: &Path, checked_out: &str) -> Option<String> {
if let Some(why) = lane_removal_block(path) {
return Some(why);
}
match worktree_head(path) {
Some(head) if head == checked_out => None,
Some(_) => Some(String::from(
"it has commits beyond the pull request's head — put them on a branch first",
)),
None => Some(String::from("git cannot read its HEAD")),
}
}
/// The current branch's first-parent history, newest first (#371).
///
/// NOT [`commit_graph`], which logs `--branches --tags HEAD` to draw the
/// repo-wide graph: with any other branch present that list interleaves
/// commits the current branch does not contain, and topological order can
/// put one of them at index 0. A scrubber built on it steps back from the
/// working tree onto a commit that is not HEAD and may not even be an
/// ancestor of it.
///
/// `--first-parent` because a scrubber walks the branch as a line. A merge's
/// second parent is a different line of development, and stepping into one
/// would take the user somewhere they cannot step back out of in a straight
/// line.
///
/// Empty on any failure — no repo, no commits, no git — so the caller shows
/// an empty state rather than an error, matching `commit_graph`.
pub fn branch_history(root: &Path, limit: usize) -> Vec<GraphCommit> {
branch_history_range(root, "HEAD", limit)
}
/// [`branch_history`] over an explicit revision spec rather than `HEAD`.
///
/// Takes the spec as a string so a caller can pass a range: `base..lane`
/// lists the commits a lane added and none of the base's, which is what
/// "the branch's diff against the base" means for a worktree lane (#348).
/// `HEAD` reproduces the unranged behaviour exactly, which is why
/// `branch_history` is now a one-line call rather than a second copy of
/// this body.
///
/// Empty on any failure, like its caller: an unknown revision is a git
/// error, and the graph shows an empty state rather than an error row.
pub fn branch_history_range(root: &Path, revspec: &str, limit: usize) -> Vec<GraphCommit> {
let Some(path_str) = root.to_str() else {
return Vec::new();
};
let output = Command::new("git")
.args([
"-C",
path_str,
"log",
"--first-parent",
revspec,
&format!("-n{limit}"),
"--format=%H\x1f%h\x1f%P\x1f%D\x1f%s\x1f%an\x1f%ct",
])
.output();
let Ok(output) = output else {
return Vec::new();
};
if !output.status.success() {
return Vec::new();
}
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0);
parse_commit_graph(&String::from_utf8_lossy(&output.stdout), now)
}
/// Commit `rev`'s tree under a workspace root, as [`tree_paths`] lists it
/// for the Explorer's dimming while the scrubber sits on a commit (#371).
#[derive(Debug, Default)]
pub struct CommitTree {
/// Every path in the tree, absolute, directories included.
pub paths: HashSet<PathBuf>,
/// Submodule (gitlink) paths. `ls-tree` never lists their contents, so
/// anything beneath one counts as present rather than dimming a whole
/// submodule checkout.
pub submodules: Vec<PathBuf>,
}
impl CommitTree {
/// Whether `path` existed in the commit: listed, or inside a submodule.
pub fn contains(&self, path: &Path) -> bool {
self.paths.contains(path) || self.submodules.iter().any(|s| path.starts_with(s))
}
}
/// Every path in commit `rev`'s tree under `root`, absolute (`root`
/// joined), directories included — what the Explorer dims against while
/// the scrubber sits on a commit (#371).
///
/// `ls-tree` run with `-C root` and no `--full-tree` lists only the
/// entries under `root` and prints them relative to it, the same base
/// [`read_file_at_rev`]'s `./` gives, so a workspace opened in a
/// subdirectory of a repo joins onto its own root rather than the
/// toplevel. `-t` emits each directory on the way down, so a folder that
/// existed keeps its normal colour without deriving ancestors here.
///
/// `None` on any failure (no repo, unknown revision), so a caller dims
/// nothing rather than everything.
pub fn tree_paths(root: &Path, rev: &str) -> Option<CommitTree> {
let output = Command::new("git")
.arg("-C")
.arg(root)
.env("GIT_OPTIONAL_LOCKS", "0")
.args(["ls-tree", "-r", "-t", "-z", rev])
.stdin(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.output()
.ok()?;
if !output.status.success() {
return None;
}
let mut tree = CommitTree::default();
// Each entry is `<mode> <type> <object>\t<path>`.
for entry in output.stdout.split(|b| *b == 0).filter(|s| !s.is_empty()) {
let Some(tab) = entry.iter().position(|b| *b == b'\t') else {
continue;
};
let path = join_raw(root, &entry[tab + 1..]);
if entry[..tab].split(|b| *b == b' ').nth(1) == Some(b"commit") {
tree.submodules.push(path.clone());
}
tree.paths.insert(path);
}
Some(tree)
}
/// Parse the `%H\x1f%h\x1f%P\x1f%D\x1f%s\x1f%an\x1f%ct` lines emitted by
/// [`commit_graph`], computing each commit's age relative to `now`.
pub fn parse_commit_graph(out: &str, now: i64) -> Vec<GraphCommit> {
out.lines()
.filter_map(|line| {
let mut parts = line.split('\x1f');
let hash = parts.next()?.to_string();
let short_hash = parts.next()?.to_string();
let parents: Vec<String> = parts
.next()?
.split_whitespace()
.map(str::to_string)
.collect();
let refs: Vec<String> = parts
.next()?
.split(", ")
.filter(|s| !s.is_empty())
.map(str::to_string)
.collect();
let summary = parts.next()?.to_string();
let author = parts.next()?.to_string();
let ct: i64 = parts.next()?.trim().parse().ok()?;
if hash.is_empty() {
return None;
}
Some(GraphCommit {
hash,
short_hash,
parents,
refs,
summary,
author,
age_secs: (now - ct).max(0),
})
})
.collect()
}
/// The commit that last touched one or more lines, for GitLens-style inline
/// blame. Lines not yet committed (staged or unstaged working-tree edits)
/// blame against the all-zero hash, which [`parse_blame`] marks
/// `uncommitted`.
#[derive(Debug, PartialEq, Eq)]
pub struct BlameCommit {
/// The full hash, which Git: Copy Commit Hash for Line copies and Git:
/// Open Commit for Line shows (#1556).
pub hash: String,
pub summary: String,
pub author: String,
/// Seconds since the commit's author-time, for [`humanize_age`].
pub age_secs: i64,
/// True for a not-yet-committed line (the zero hash `git blame` reports
/// for working-tree changes).
pub uncommitted: bool,
}
impl BlameCommit {
/// The hash's first eight digits, as the inline blame names a commit.
pub fn short_hash(&self) -> &str {
&self.hash[..self.hash.len().min(8)]
}
}
/// A file's blame, line by line (#1707). Each line's commit is shared with
/// every other line it last touched, and the lines' text is packed: a file
/// names far fewer commits than it has lines, and a copy of the hash,
/// author, summary and text on every line cost ~330 bytes a line, 23 MB for
/// a 73,000-line file, in every tab blame had visited.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Blame {
commits: Vec<Arc<BlameCommit>>,
/// The lines' text as blamed, when known: the annotation is shown only
/// while the buffer's line still reads the same (see
/// `Editor::committed_blame_annotation`).
text: Option<crate::packed_lines::PackedLines>,
}
impl Blame {
/// Blame for lines whose commits are `commits`, in order, and whose
/// text as blamed is `text` when known.
pub fn new(
commits: Vec<Arc<BlameCommit>>,
text: Option<crate::packed_lines::PackedLines>,
) -> Self {
Self { commits, text }
}
/// How many lines were blamed.
pub fn len(&self) -> usize {
self.commits.len()
}
/// Whether no line was blamed (git failed, or the file is untracked).
pub fn is_empty(&self) -> bool {
self.commits.is_empty()
}
/// Line `i`'s commit, and its text as blamed when known.
pub fn line(&self, i: usize) -> Option<(&BlameCommit, Option<&str>)> {
let commit = self.commits.get(i)?;
Some((commit, self.text.as_ref().and_then(|t| t.get(i))))
}
}
/// Per-line blame for `rel_path`, indexed 0-based by result position (result
/// `[0]` is line 1). Uses `git blame --porcelain`, which describes each
/// commit once, where `--line-porcelain` repeated its author, time and
/// summary on every line it touched: several times the output to read for
/// the same answer. Returns empty on any failure so the caller renders no
/// annotation rather than an error.
pub fn blame(root: &Path, rel_path: &str) -> Blame {
let (dir, name) = file_cwd(root, rel_path);
let Some(path_str) = dir.to_str() else {
return Blame::default();
};
let output = Command::new("git")
.env("GIT_OPTIONAL_LOCKS", "0")
.args(["-C", path_str, "blame", "--porcelain", "--", &name])
.output();
let Ok(output) = output else {
return Blame::default();
};
if !output.status.success() {
return Blame::default();
}
parse_blame(
&String::from_utf8_lossy(&output.stdout),
current_unix_seconds(),
)
}
/// Parse `git blame --porcelain` output into the [`Blame`] of each source
/// line, in order. Porcelain groups each line as a header (`<hash> <orig>
/// <final> [group]`), then the commit's `author`, `author-time`, `summary`,
/// etc. the first time that commit appears, then a tab-prefixed content
/// line. A later line of the same commit shares the first one's
/// [`BlameCommit`]; `--line-porcelain`'s repeated metadata parses the same.
/// `now` (unix seconds) dates each commit.
pub fn parse_blame(out: &str, now: i64) -> Blame {
let mut lines = Vec::new();
let mut text = crate::packed_lines::PackedLines::default();
let mut commits: std::collections::HashMap<String, Arc<BlameCommit>> =
std::collections::HashMap::new();
let mut hash: Option<String> = None;
let mut author = String::new();
let mut summary = String::new();
let mut author_time: i64 = now;
for raw in out.lines() {
if let Some(rest) = raw.strip_prefix("author ") {
author = rest.to_string();
} else if let Some(rest) = raw.strip_prefix("author-time ") {
author_time = rest.trim().parse().unwrap_or(now);
} else if let Some(rest) = raw.strip_prefix("summary ") {
summary = rest.to_string();
} else if let Some(content) = raw.strip_prefix('\t') {
// The content line closes a group: emit the accumulated blame.
if let Some(full) = hash.take() {
let commit = commits.entry(full).or_insert_with_key(|full| {
Arc::new(BlameCommit {
hash: full.clone(),
summary: std::mem::take(&mut summary),
author: std::mem::take(&mut author),
age_secs: now - author_time,
uncommitted: full.chars().all(|c| c == '0'),
})
});
lines.push(Arc::clone(commit));
text.push(content);
}
} else if let Some(h) = raw.split(' ').next() {
// A header line begins with a 40-char hash; other porcelain
// metadata (previous/filename/committer/…) is ignored. A group's
// metadata is only what follows its own header.
if h.len() == 40 && h.chars().all(|c| c.is_ascii_hexdigit()) {
hash = Some(h.to_string());
author.clear();
summary.clear();
author_time = now;
}
}
}
Blame::new(lines, Some(text))
}
/// Repo's default branch name. Tries `origin/HEAD` first (set by
/// `git clone` / `git remote set-head -a origin`), then falls back to
/// common local names (`main`, `master`, `develop`, `trunk`) by checking
/// `git rev-parse --verify <name>`. Returns `Err` when none resolves so
/// the caller can surface the precise failure instead of guessing.
pub fn default_branch(root: &Path) -> Result<String, String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
if let Ok(out) = Command::new("git")
.args([
"-C",
path_str,
"symbolic-ref",
"--short",
"refs/remotes/origin/HEAD",
])
.output()
&& out.status.success()
{
let raw = String::from_utf8_lossy(&out.stdout).trim().to_string();
if let Some(short) = raw.strip_prefix("origin/") {
if !short.is_empty() {
return Ok(short.to_string());
}
} else if !raw.is_empty() {
return Ok(raw);
}
}
for candidate in ["main", "master", "develop", "trunk"] {
let out = Command::new("git")
.args([
"-C",
path_str,
"rev-parse",
"--verify",
"--quiet",
candidate,
])
.output();
if let Ok(o) = out
&& o.status.success()
{
return Ok(candidate.to_string());
}
}
Err(
"Could not resolve a default branch (tried origin/HEAD, main, master, develop, trunk)"
.to_string(),
)
}
/// Stage a single path. Convenience wrapper over `stage_paths` for the
/// inline "+" icon click path; multi-select staging goes through
/// `stage_paths` directly so all paths land in one atomic `git add`
/// invocation (the index.lock is held only once, so the background
/// status worker can't race us between adds).
pub fn stage_path(root: &Path, rel_path: &str) -> Result<(), String> {
stage_paths(root, std::slice::from_ref(&rel_path.to_string()))
}
/// `git rm` one path: out of the index and off the disk. Resolves a
/// modify/delete conflict in favour of the deletion (#1244).
pub fn remove_path(root: &Path, rel_path: &str) -> Result<(), String> {
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let out = Command::new("git")
.args([
"-C",
path_str,
"--literal-pathspecs",
"rm",
"-q",
"-f",
"--",
])
.arg(rel_path)
.output()
.map_err(|e| e.to_string())?;
if out.status.success() {
Ok(())
} else {
Err(String::from_utf8_lossy(&out.stderr).trim().to_string())
}
}
/// Stage all listed paths in a single `git add -- p1 p2 ...` invocation.
/// Atomic with respect to the index lock — running N separate `git add`
/// commands lets the background `git status` worker grab the lock
/// between them and fail later adds with "Unable to create index.lock".
pub fn stage_paths(root: &Path, rel_paths: &[String]) -> Result<(), String> {
if rel_paths.is_empty() {
return Ok(());
}
refuse_conflict_markers(root, Some(rel_paths))?;
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut cmd = Command::new("git");
// Literal: git reads a pathspec as a glob, so staging Next.js's
// `pages/[id].tsx` also staged `pages/i.tsx` and untracked `pages/d.tsx`.
cmd.args(["-C", path_str, "--literal-pathspecs", "add", "--"]);
for p in rel_paths {
cmd.arg(p);
}
let output = cmd
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if output.status.success() {
Ok(())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let msg = if !stderr.is_empty() { stderr } else { stdout };
Err(if msg.is_empty() {
format!("git add failed with code {:?}", output.status.code())
} else {
msg
})
}
}
/// Unstage a single path. Convenience wrapper over `unstage_paths` for
/// the inline "−" icon click on a staged row.
pub fn unstage_path(root: &Path, rel_path: &str) -> Result<(), String> {
unstage_paths(root, std::slice::from_ref(&rel_path.to_string()))
}
/// Move all listed paths out of the index and back into the working tree,
/// in one `git reset -q HEAD -- p1 p2 …` invocation. The mirror of
/// `stage_paths`: `git reset HEAD` is what VS Code's git extension runs to
/// unstage, and unlike `git restore --staged` it also unstages files added
/// in a repo's very first commit. Atomic w.r.t. the index lock, so the
/// background status worker can't race us between paths.
pub fn unstage_paths(root: &Path, rel_paths: &[String]) -> Result<(), String> {
if rel_paths.is_empty() {
return Ok(());
}
let mut args: Vec<&str> = vec!["--literal-pathspecs", "reset", "-q", "HEAD", "--"];
args.extend(rel_paths.iter().map(String::as_str));
run_mutation(root, &args).map(|_| ())
}
/// Whether `rel_path` is a submodule: a gitlink (mode `160000`) in the
/// index or in HEAD (#1235). Porcelain status lists one as a plain path, so
/// a Changes row cannot tell on its own, and a gitlink has no blob for
/// `git show HEAD:<path>` and nothing for `git checkout -- <path>` to do.
pub fn is_submodule(root: &Path, rel_path: &str) -> bool {
let gitlink = |args: &[&str]| {
run_git(root, args).is_ok_and(|out| out.lines().any(|l| l.starts_with("160000 ")))
};
gitlink(&["--literal-pathspecs", "ls-files", "--stage", "--", rel_path])
|| gitlink(&["--literal-pathspecs", "ls-tree", "HEAD", "--", rel_path])
}
/// What changed in submodule `rel_path` since HEAD, as `git diff` reports a
/// submodule: the commits it moved across (`--submodule=log`), then its
/// own changes, staged or not (`--submodule=diff`), with paths inside it.
pub fn submodule_diff(root: &Path, rel_path: &str) -> Result<String, String> {
let diff = |mode: &str| {
run_git(
root,
&[
"-c",
"color.ui=never",
"--literal-pathspecs",
"diff",
mode,
"HEAD",
"--",
rel_path,
],
)
.map_err(|e| e.to_string())
};
let log = diff("--submodule=log")?;
let content: String = diff("--submodule=diff")?
.lines()
.filter(|l| !l.starts_with("Submodule "))
.map(|l| format!("{l}\n"))
.collect();
Ok(if content.is_empty() {
log
} else {
format!("{log}\n{content}")
})
}
/// Discard a single path. A Changes row restores the working tree from the
/// INDEX (`git checkout -- <path>`), so a staged part of the same file is
/// kept, as VS Code does; restoring from HEAD threw the staged work away
/// too. A Staged row restores both from HEAD. Untracked entries are removed
/// from disk. Destructive: callers
/// MUST confirm with the user before invoking — the Source Control panel
/// shows a Y/N modal before reaching this function.
pub fn discard_path(
root: &Path,
rel_path: &str,
untracked: bool,
staged: bool,
) -> Result<(), String> {
if untracked {
let abs = root.join(rel_path);
if abs.is_dir() {
// Porcelain folds a directory holding any untracked file into one
// `?? dir/` row; `remove_dir_all` took the IGNORED files inside
// with it (`.env`, `node_modules/`). `git clean` removes only
// the untracked ones.
run_mutation(
root,
&["--literal-pathspecs", "clean", "-fdq", "--", rel_path],
)
.map(|_| ())
} else {
std::fs::remove_file(&abs)
.map_err(|e| format!("failed to remove {}: {e}", abs.display()))
}
} else {
// `git checkout -- <submodule>` exits 0 and changes nothing, which
// reported "Discarded" over a submodule still on its new commit
// with its edits intact (#1235). Say so instead.
if is_submodule(root, rel_path) {
return Err(format!(
"{rel_path} is a submodule; open it to discard its changes"
));
}
let path_str = root
.to_str()
.ok_or_else(|| "non-utf8 workspace path".to_string())?;
let mut cmd = Command::new("git");
cmd.args(["-C", path_str, "--literal-pathspecs", "checkout"]);
if staged {
cmd.arg("HEAD");
}
let output = cmd
.args(["--", rel_path])
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
if output.status.success() {
Ok(())
} else {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
let msg = if !stderr.is_empty() { stderr } else { stdout };
Err(if msg.is_empty() {
format!("git checkout failed with code {:?}", output.status.code())
} else {
msg
})
}
}
}
/// Pull the current branch from its upstream (`git pull`). Sibling of
/// `push_current_branch`; surfaced by the commit dropdown's "Pull" item
/// and used by `sync` below. Returns git's verbatim summary ("Already
/// up to date." / the fast-forward range) so the panel can echo it.
pub fn pull_current_branch(root: &Path) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["pull"])
}
/// A single branch the Checkout/Create picker can offer.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct BranchInfo {
/// What the user sees: the local branch name, or `origin/foo` for a
/// remote-tracking branch.
pub display: String,
/// The branch's own name: the local name, or a remote branch's name
/// without its remote (`feat` for `upstream/feat`). What merge, rebase,
/// delete and create-from act on.
pub checkout_name: String,
/// True for the branch currently checked out (marked in the picker,
/// never offered as a checkout target).
pub is_current: bool,
/// True for `origin/…` remote-tracking branches, listed below locals.
pub is_remote: bool,
/// For a remote-tracking branch, the ref to check out with `git switch
/// --track` (`upstream/feat`), so the local branch tracks the remote
/// the user picked. `git switch feat` refuses a name two remotes carry
/// (#1445). `None` for a local branch.
pub track: Option<String>,
}
/// List branches for the Checkout picker: local branches first (most
/// recently committed on top, the current one flagged), then remote-only
/// branches whose name has no local counterpart. Remote rows carry their
/// remote ref in `track`, so selecting `upstream/foo` runs `git switch
/// --track upstream/foo` and the new local branch tracks that remote.
pub fn list_branches(root: &Path) -> Result<Vec<BranchInfo>, String> {
let locals_raw = run_git(
root,
&[
"for-each-ref",
"--sort=-committerdate",
"--format=%(refname:short)%09%(HEAD)",
"refs/heads",
],
)
.map_err(|e| e.to_string())?;
let mut branches: Vec<BranchInfo> = Vec::new();
let mut local_names: std::collections::HashSet<String> = std::collections::HashSet::new();
for line in locals_raw.lines() {
let mut parts = line.split('\t');
let Some(name) = parts.next() else { continue };
if name.is_empty() {
continue;
}
let is_current = parts.next().map(|m| m.trim() == "*").unwrap_or(false);
local_names.insert(name.to_string());
branches.push(BranchInfo {
display: name.to_string(),
checkout_name: name.to_string(),
is_current,
is_remote: false,
track: None,
});
}
let remotes_raw = run_git(
root,
&[
"for-each-ref",
"--sort=-committerdate",
"--format=%(refname)%09%(symref)",
"refs/remotes",
],
)
.unwrap_or_default();
// Longest first, so `my/fork/x` splits at the `my/fork` remote and not
// at a `my` one; splitting at the first `/` broke a remote named with
// one (#1445).
let mut remotes: Vec<String> = run_git(root, &["remote"])
.unwrap_or_default()
.lines()
.filter(|l| !l.is_empty())
.map(str::to_string)
.collect();
remotes.sort_by_key(|r| std::cmp::Reverse(r.len()));
for line in remotes_raw.lines() {
let (refname, symref) = line.split_once('\t').unwrap_or((line, ""));
// `refs/remotes/origin/HEAD` is a pointer to a branch, not one: git
// shortens it to plain `origin`, which the old `/HEAD` check missed.
let Some(full) = refname.strip_prefix("refs/remotes/") else {
continue;
};
if full.is_empty() || !symref.is_empty() || full.ends_with("/HEAD") {
continue;
}
let short = remotes
.iter()
.find_map(|r| full.strip_prefix(r.as_str())?.strip_prefix('/'))
.or_else(|| full.split_once('/').map(|(_, s)| s))
.unwrap_or(full);
if local_names.contains(short) {
continue;
}
branches.push(BranchInfo {
display: full.to_string(),
checkout_name: short.to_string(),
is_current: false,
is_remote: true,
track: Some(full.to_string()),
});
}
Ok(branches)
}
/// Git's messages in English, whatever the user's locale (#925): a
/// refusal to switch is told apart by its text
/// ([`local_changes_block_switch`]), which a translated git words otherwise.
/// `LANGUAGE` picks gettext's catalog ahead of `LC_ALL` and `LANG` and
/// leaves the character set alone; git has no `en` catalog, so its own
/// text is what prints.
const ENGLISH_MESSAGES: (&str, &str) = ("LANGUAGE", "en");
/// Switch to an existing local branch (`git switch <name>`).
pub fn checkout_branch(root: &Path, name: &str) -> Result<String, String> {
run_mutation_with_env(root, &["switch", name], &[ENGLISH_MESSAGES])
}
/// Check out a remote-tracking branch as local branch `name` tracking it
/// (`git switch -c feat --track upstream/feat`): the remote the user
/// picked, even when another remote has a branch of the same name (#1445).
/// The name is spelled out because `--track` alone guesses it by cutting
/// at the first `/`, which makes `my/fork/solo` a `fork/solo` branch.
pub fn track_remote_branch(root: &Path, remote_ref: &str, name: &str) -> Result<String, String> {
run_mutation_with_env(
root,
&["switch", "-c", name, "--track", remote_ref],
&[ENGLISH_MESSAGES],
)
}
/// Create a new branch off the current HEAD and switch to it
/// (`git switch -c <name>`). Errors (e.g. name already exists) carry
/// git's verbatim message.
pub fn create_branch(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["switch", "-c", name])
}
/// Stash the working tree (`git stash push`). Tracked changes are saved
/// and the working tree reverts to HEAD, exactly like VS Code's Stash.
/// A `message` names the stash (`-m`, #1581); without one git calls it
/// `WIP on <branch>: <commit>`.
pub fn stash_push(root: &Path, message: Option<&str>) -> Result<String, String> {
stash_push_args(root, &[], message)
}
/// Which of Source Control's three stash commands is asking for a
/// message (#1581).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum StashKind {
/// `git stash push`.
Tracked,
/// `git stash push -u`.
IncludeUntracked,
/// `git stash push --staged`.
Staged,
}
/// `git stash push <extra> [-m <message>]`, a blank message counting as
/// none.
fn stash_push_args(root: &Path, extra: &[&str], message: Option<&str>) -> Result<String, String> {
let mut args = vec!["stash", "push"];
args.extend_from_slice(extra);
if let Some(message) = message.map(str::trim).filter(|m| !m.is_empty()) {
args.extend(["-m", message]);
}
run_mutation(root, &args)
}
/// Restore and drop the most recent stash (`git stash pop`). A pop
/// conflict surfaces git's verbatim message so the user can resolve it.
pub fn stash_pop(root: &Path) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["stash", "pop"])
}
// --- Fetch / Clone -------------------------------------------------------
/// Fetch from all remotes without merging (`git fetch --all --prune`).
/// VS Code's "Fetch" updates remote-tracking refs so ahead/behind counts
/// refresh; `--prune` drops refs deleted on the remote.
pub fn fetch_all(root: &Path) -> Result<String, String> {
run_mutation(root, &["fetch", "--all", "--prune"])
}
/// Derive the directory name a clone of `url` would land in: the final
/// path segment with any trailing `.git` and slash stripped. Returns
/// `None` when the URL has no usable segment.
pub fn clone_dir_name(url: &str) -> Option<String> {
let trimmed = url.trim().trim_end_matches('/');
let seg = trimmed.rsplit(['/', ':']).next()?.trim();
let name = seg.strip_suffix(".git").unwrap_or(seg).trim();
(!name.is_empty()).then(|| name.to_string())
}
/// Clone `url` into `parent/<repo-name>` and return the new repo path.
/// The Source Control "Clone" flow prompts for the URL, clones beside the
/// current workspace, then re-roots croft into the clone.
pub fn clone_into(parent: &Path, url: &str) -> Result<PathBuf, String> {
let name =
clone_dir_name(url).ok_or_else(|| format!("can't derive a folder name from {url}"))?;
let dest = parent.join(&name);
// run_mutation runs with `-C <parent>`, so the bare `<name>` clones into
// parent/<name>.
// `--`: a URL starting with `-` (`--upload-pack=<command>`) is
// otherwise an option, and that one runs a command.
run_mutation(parent, &["clone", "--", url, &name]).map(|_| dest)
}
// --- Commit variants -----------------------------------------------------
/// Paths git still holds as unmerged (`UU`, `AA`, `DU`, …): the MERGE
/// CONFLICTS group, read straight from the index.
pub fn unmerged_paths(root: &Path) -> Vec<String> {
let Ok(out) = Command::new("git")
.arg("-C")
.arg(root)
// `--no-relative`: with `diff.relative` set, a subdirectory root
// would hide the conflicts outside it, and `git add -A` stages them.
.args(["diff", "--no-relative", "--name-only", "--diff-filter=U", "-z"])
.output()
else {
return Vec::new();
};
let mut paths: Vec<String> = String::from_utf8_lossy(&out.stdout)
.split('\0')
.filter(|p| !p.is_empty())
.map(String::from)
.collect();
paths.dedup();
paths
}
/// Refuse to commit while a merge still has unresolved conflicts (#989).
/// `git commit -a` and `git add -A` stage an unmerged file as it is, so the
/// commit would record its `<<<<<<<` markers; a plain `git commit` refuses
/// here by itself, and this says the same thing up front for the paths that
/// stage on the user's behalf.
pub fn refuse_unmerged(root: &Path) -> Result<(), String> {
let paths = unmerged_paths(root);
if paths.is_empty() {
return Ok(());
}
let named = first_paths(&paths);
let (n, them) = match paths.len() {
1 => (String::from("1 merge conflict"), "it"),
n => (format!("{n} merge conflicts"), "them"),
};
Err(format!(
"Resolve {n} ({named}) and stage {them} before committing"
))
}
/// Whether the index holds anything a plain `git commit` would record: a
/// change against HEAD, or on an unborn branch any staged file.
fn has_staged_changes(root: &Path) -> Result<bool, String> {
let output = Command::new("git")
.arg("-C")
.arg(root)
.env("GIT_OPTIONAL_LOCKS", "0")
// `--no-relative`: with `diff.relative` set, a subdirectory root
// would see only what is staged under it, and a commit takes it all.
// `--ignore-submodules=none`: `diff.ignoreSubmodules` hides a staged
// submodule update from diff, but `git commit` still records it.
// `--no-ext-diff`: an external diff helper whose exit code is trusted
// (`diff.trustExitCode`, git 2.46+) could call a staged change equal.
.args([
"diff",
"--cached",
"--quiet",
"--no-relative",
"--ignore-submodules=none",
"--no-ext-diff",
])
.output()
.map_err(|e| format!("failed to spawn git: {e}"))?;
match output.status.code() {
Some(0) => Ok(false),
Some(1) => Ok(true),
code => {
let stderr = String::from_utf8_lossy(&output.stderr).trim().to_string();
Err(if stderr.is_empty() {
format!("git diff --cached failed with code {code:?}")
} else {
stderr
})
}
}
}
/// Up to three of `paths`, comma-separated, with `…` when there are more.
fn first_paths(paths: &[String]) -> String {
let mut named = paths.iter().take(3).cloned().collect::<Vec<_>>().join(", ");
if paths.len() > 3 {
named.push_str(", …");
}
named
}
/// Refuse to stage a conflicted file that still holds its conflict markers
/// (#989). `git add` is how git marks a conflict resolved, and it takes the
/// file as it is, so Stage All, or staging the file itself, would record
/// the `<<<<<<<` lines and the next commit would ship them. A conflicted
/// file whose markers have been edited away stages as usual. `scope` holds
/// the `root`-relative paths about to be staged; `None` means everything.
/// The markers are found by [`leftover_conflict_markers`].
fn refuse_conflict_markers(root: &Path, scope: Option<&[String]>) -> Result<(), String> {
let unmerged = unmerged_paths(root);
if unmerged.is_empty() {
return Ok(());
}
// `unmerged_paths` names paths from the top of the repository, which
// is not `root` when croft was opened on a subdirectory.
let Some(top) = repo_toplevel(root) else {
return Ok(());
};
let canon = |p: PathBuf| std::fs::canonicalize(&p).unwrap_or(p);
let scope: Option<Vec<PathBuf>> =
scope.map(|paths| paths.iter().map(|p| canon(root.join(p))).collect());
let marked: Vec<String> = unmerged
.into_iter()
.filter(|rel| {
let abs = canon(top.join(rel));
scope
.as_ref()
.is_none_or(|scope| scope.iter().any(|s| abs.starts_with(s)))
&& leftover_conflict_markers(&top, rel)
})
.collect();
if marked.is_empty() {
return Ok(());
}
let (has, them) = if marked.len() == 1 {
("has", "it")
} else {
("have", "them")
};
Err(format!(
"{} still {has} conflict markers: resolve {them} before staging",
first_paths(&marked)
))
}
/// Whether git's own `diff --check` finds conflict markers in the unmerged
/// `rel` (a path from the top of the repository at `top`). Reading the
/// file ourselves missed three cases git handles: a file in Latin-1 or
/// Shift_JIS, markers of another length set by a `conflict-marker-size`
/// attribute, and marker lines both sides already had, such as a doc
/// showing what a conflict looks like, which would block staging forever.
fn leftover_conflict_markers(top: &Path, rel: &str) -> bool {
Command::new("git")
.arg("-C")
.arg(top)
.args(["--literal-pathspecs", "diff", "--check", "--no-color", "--"])
.arg(rel)
.output()
.is_ok_and(|out| String::from_utf8_lossy(&out.stdout).contains("leftover conflict marker"))
}
/// Commit only what is already staged (`git commit -m`), leaving unstaged
/// changes in the working tree. With nothing staged git refuses it, where
/// [`commit`] would take every tracked change.
pub fn commit_staged(root: &Path, message: &str) -> Result<String, String> {
if message.trim().is_empty() {
return Err("Commit message is empty".to_string());
}
run_mutation(root, &["commit", "-m", message])
}
/// Amend the previous commit with a new message (`git commit --amend -m`),
/// folding any currently-staged changes into it. Rewrites history, so the
/// caller confirms before invoking.
pub fn commit_amend(root: &Path, message: &str) -> Result<String, String> {
if message.trim().is_empty() {
return Err("Commit message is empty".to_string());
}
run_mutation(root, &["commit", "--amend", "-m", message])
}
/// Amend the previous commit keeping its existing message
/// (`git commit --amend --no-edit`); folds staged changes into HEAD.
pub fn commit_amend_no_edit(root: &Path) -> Result<String, String> {
run_mutation(root, &["commit", "--amend", "--no-edit"])
}
/// Undo Last Commit (#1350), as VS Code does it: `git reset --soft HEAD~1`,
/// so HEAD moves to the parent and the commit's changes stay staged, or
/// on the root commit `git update-ref -d HEAD`, which leaves the branch
/// unborn with every file staged. Returns the undone commit's message, for
/// the message box. Refused while a merge, rebase, cherry-pick or revert
/// is in progress: moving HEAD under one of those breaks it.
pub fn undo_last_commit(root: &Path) -> Result<String, String> {
if let Some(op) = operation_in_progress(root) {
return Err(format!(
"a {op} is in progress; finish or abort it before undoing a commit"
));
}
let message = run_git(root, &["log", "-1", "--format=%B", "HEAD"])
.map_err(|_| String::from("there is no commit to undo"))?;
if run_git(root, &["rev-parse", "--verify", "-q", "HEAD~1"]).is_ok() {
run_mutation(root, &["reset", "--soft", "HEAD~1"])?;
} else {
// A shallow checkout cuts history at a commit that still has a
// parent: deleting the ref there would drop the branch tip.
let raw = run_git(root, &["cat-file", "commit", "HEAD"])
.map_err(|_| String::from("cannot read the last commit"))?;
if raw
.lines()
.take_while(|l| !l.is_empty())
.any(|l| l.starts_with("parent "))
{
return Err(String::from(
"the parent commit is not in this shallow checkout; deepen it before undoing a commit",
));
}
// On a detached HEAD, `update-ref -d HEAD` deletes `.git/HEAD`
// itself and the repository stops being one.
if run_git(root, &["symbolic-ref", "-q", "HEAD"]).is_err() {
return Err(String::from(
"HEAD is detached; check out a branch before undoing its root commit",
));
}
run_mutation(root, &["update-ref", "-d", "HEAD"])?;
}
Ok(message)
}
/// The git operation in progress in `root`'s repository, by the state
/// file git keeps for it, or `None`.
fn operation_in_progress(root: &Path) -> Option<&'static str> {
const STATES: [(&str, &str); 5] = [
("MERGE_HEAD", "merge"),
("rebase-merge", "rebase"),
("rebase-apply", "rebase"),
("CHERRY_PICK_HEAD", "cherry-pick"),
("REVERT_HEAD", "revert"),
];
let mut args = vec!["rev-parse"];
for (file, _) in STATES {
args.extend(["--git-path", file]);
}
let paths = run_git(root, &args).ok()?;
paths
.lines()
.zip(STATES)
.find(|(path, _)| root.join(path.trim()).exists())
.map(|(_, (_, op))| op)
}
/// Whether HEAD is already on its upstream (`HEAD` is an ancestor of
/// `@{u}`), so undoing it rewrites published history and needs a force
/// push later (#1350). No upstream is not pushed; an upstream that is
/// configured but cannot be checked (its tracking ref missing) counts as
/// pushed, so the warning errs on the side of showing.
pub fn head_is_on_upstream(root: &Path) -> bool {
let code = Command::new("git")
.env("GIT_OPTIONAL_LOCKS", "0")
.arg("-C")
.arg(root)
.args(["merge-base", "--is-ancestor", "HEAD", "@{u}"])
.output()
.ok()
.and_then(|o| o.status.code());
match code {
Some(0) => true,
Some(1) => false,
_ => run_git(root, &["symbolic-ref", "-q", "HEAD"])
.and_then(|branch| run_git(root, &["for-each-ref", "--format=%(upstream)", &branch]))
.is_ok_and(|upstream| !upstream.is_empty()),
}
}
// --- Bulk staging --------------------------------------------------------
/// Stage every change, tracked and untracked (`git add -A`). Refused while
/// a conflicted file still holds its markers.
pub fn stage_all(root: &Path) -> Result<String, String> {
refuse_conflict_markers(root, None)?;
run_mutation(root, &["add", "-A"])
}
/// Unstage everything (`git reset -q HEAD`), moving the whole index back
/// into the working tree.
pub fn unstage_all(root: &Path) -> Result<String, String> {
run_mutation(root, &["reset", "-q", "HEAD"])
}
/// Discard every tracked modification (`git checkout -- .`) — destructive,
/// the caller MUST confirm. Untracked files are left untouched (matching
/// the per-file discard, which deletes untracked only on explicit request).
pub fn discard_all_tracked(root: &Path) -> Result<String, String> {
run_mutation(root, &["checkout", "--", "."])
}
// --- Pull / Push variants ------------------------------------------------
/// Pull with rebase instead of merge (`git pull --rebase`).
pub fn pull_rebase(root: &Path) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["pull", "--rebase"])
}
/// Force-push the current branch, but only if the remote hasn't advanced
/// past what we last saw (`git push --force-with-lease`). Safer than a
/// bare `--force`; VS Code's "Push (Force)" uses the same lease guard.
pub fn push_force(root: &Path) -> Result<String, String> {
run_mutation(root, &["push", "--force-with-lease"])
}
/// Push the current branch to a specific remote (`git push <remote>`).
pub fn push_to_remote(root: &Path, remote: &str) -> Result<String, String> {
run_mutation(root, &["push", remote])
}
/// Publish the current branch: push it and set upstream tracking
/// (`git push -u <remote> <branch>`, the remote chosen by
/// [`publish_remote`]). Used when a local branch has no upstream yet.
pub fn publish_branch(root: &Path, branch: &str) -> Result<String, String> {
let remote = publish_remote(root)?;
run_mutation(root, &["push", "-u", &remote, branch])?;
Ok(format!("{branch} to {remote}"))
}
/// The current branch when it has no upstream to push to or pull from
/// (`@{u}` does not resolve), the case `git push` refuses with "has no
/// upstream branch". None on a tracked branch and on a detached HEAD.
pub fn unpublished_branch(root: &Path) -> Option<String> {
let branch = run_git(root, &["symbolic-ref", "--short", "HEAD"])
.ok()
.and_then(parse_branch)?;
let tracked = run_git(
root,
&["rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{u}"],
)
.is_ok();
(!tracked).then_some(branch)
}
/// The remote an unpublished branch goes to: `remote.pushDefault` when
/// set, else `origin`, else the only remote. With several remotes and
/// none of those, picking one would be a guess, so it is an error.
fn publish_remote(root: &Path) -> Result<String, String> {
match default_push_remote(root)? {
Some(remote) => Ok(remote),
None if run_git(root, &["remote"]).is_ok_and(|r| r.is_empty()) => {
Err(String::from("no remote to publish this branch to"))
}
None => Err(String::from(
"branch has no upstream and several remotes, none of them origin: set remote.pushDefault to pick one",
)),
}
}
/// `remote.pushDefault`, else the only remote, else `origin` among
/// several; `None` when there is no remote or several and none of those.
fn default_push_remote(root: &Path) -> Result<Option<String>, String> {
if let Ok(remote) = run_git(root, &["config", "--get", "remote.pushDefault"])
&& !remote.is_empty()
{
return Ok(Some(remote));
}
let listed = run_git(root, &["remote"]).map_err(|e| e.to_string())?;
let remotes: Vec<&str> = listed.lines().filter(|l| !l.is_empty()).collect();
Ok(match remotes.as_slice() {
[only] => Some((*only).to_string()),
several if several.contains(&"origin") => Some(String::from("origin")),
_ => None,
})
}
/// The remote tags are pushed to and deleted from (#1582): the one a new
/// branch is published to, by the same rules.
pub fn tag_remote(root: &Path) -> Result<String, String> {
match default_push_remote(root)? {
Some(remote) => Ok(remote),
None if run_git(root, &["remote"]).is_ok_and(|r| r.is_empty()) => {
Err(String::from("no remote to push tags to"))
}
None => Err(String::from(
"several remotes, none of them origin: set remote.pushDefault to pick one",
)),
}
}
/// Push the current branch, publishing it first if it has no upstream
/// (`git push -u <remote> <branch>`), as VS Code's Push and Sync do. A
/// plain `git push` would refuse with "has no upstream branch".
pub fn push_or_publish(root: &Path) -> Result<String, String> {
let Some(branch) = unpublished_branch(root) else {
return push_current_branch(root);
};
publish_branch(root, &branch).map(|summary| format!("published {summary}"))
}
// --- Branch management ---------------------------------------------------
/// Create a new branch off an explicit base ref and switch to it
/// (`git switch -c <name> <base>`). Powers "Create Branch from…".
pub fn create_branch_from(root: &Path, name: &str, base: &str) -> Result<String, String> {
run_mutation(root, &["switch", "-c", name, base])
}
/// Rename the current branch (`git branch -m <new>`).
pub fn rename_branch(root: &Path, new_name: &str) -> Result<String, String> {
run_mutation(root, &["branch", "-m", new_name])
}
/// Delete a branch (`git branch -d <name>`). Uses the safe `-d`, which
/// refuses to drop unmerged work; the error is surfaced verbatim so the
/// user can decide whether to force.
pub fn delete_branch(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["branch", "-d", name])
}
/// Merge `branch` into the current branch (`git merge <branch>`).
pub fn merge_branch(root: &Path, branch: &str) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["merge", branch])
}
/// Rebase the current branch onto `branch` (`git rebase <branch>`).
pub fn rebase_branch(root: &Path, branch: &str) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["rebase", branch])
}
// --- Commit actions (the COMMITS graph's right-click menu, #1627) ---------
/// Apply `hash` on top of HEAD (`git cherry-pick <hash>`). A conflict
/// leaves `CHERRY_PICK_HEAD`, so Git: Continue / Skip / Abort take over.
pub fn cherry_pick(root: &Path, hash: &str) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["cherry-pick", hash])
}
/// Commit the inverse of `hash` with git's own "Revert ..." message
/// (`git revert --no-edit <hash>`); a conflict leaves `REVERT_HEAD`.
pub fn revert_commit(root: &Path, hash: &str) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["revert", "--no-edit", hash])
}
/// Check out `hash` with no branch (`git switch --detach <hash>`).
pub fn checkout_detached(root: &Path, hash: &str) -> Result<String, String> {
run_mutation(root, &["switch", "--detach", hash])
}
/// Create a lightweight tag at `target` (`git tag <name> <target>`).
pub fn create_tag_at(root: &Path, name: &str, target: &str) -> Result<String, String> {
run_mutation(root, &["tag", name, target])
}
/// How far [`reset_to`] rewinds: HEAD only, HEAD and the index, or HEAD,
/// the index and the working tree.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ResetMode {
Soft,
Mixed,
Hard,
}
impl ResetMode {
fn flag(self) -> &'static str {
match self {
ResetMode::Soft => "--soft",
ResetMode::Mixed => "--mixed",
ResetMode::Hard => "--hard",
}
}
}
/// Move the current branch to `hash` (`git reset --soft|--mixed|--hard`).
pub fn reset_to(root: &Path, hash: &str, mode: ResetMode) -> Result<String, String> {
run_mutation(root, &["reset", "-q", mode.flag(), hash])
}
/// A snapshot of what a hard reset would throw away: HEAD and the branch
/// it is on (empty when detached), the index (each entry's blob, so
/// staging another hunk of an already-staged file changes it), the status
/// of every changed or untracked path, and each such file's size and
/// mtime, so a save to an already-modified file changes it too. A warned
/// Reset --hard (#1627) is confirmed only while this is unchanged.
pub fn worktree_fingerprint(root: &Path) -> String {
let head = run_git(root, &["rev-parse", "HEAD"]).unwrap_or_default();
let branch = run_git(root, &["symbolic-ref", "-q", "HEAD"]).unwrap_or_default();
let index = run_git(root, &["ls-files", "-s", "-z"]).unwrap_or_default();
// Not `run_git`: its trim would eat the first entry's leading status
// space (" M path"), and with it where that path starts.
let status = Command::new("git")
.env("GIT_OPTIONAL_LOCKS", "0")
.arg("-C")
.arg(root)
.args(["status", "--porcelain=v1", "-z", "--untracked-files=all"])
.output()
.map(|o| String::from_utf8_lossy(&o.stdout).into_owned())
.unwrap_or_default();
let top = repo_toplevel(root).unwrap_or_else(|| root.to_path_buf());
let mut out = format!("{head}\n{branch}\n{index}\n");
for entry in status.split('\0').filter(|e| !e.is_empty()) {
out.push_str(entry);
let path = entry.get(3..).unwrap_or(entry);
if let Ok(meta) = std::fs::metadata(top.join(path)) {
let mtime = meta
.modified()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map_or(0, |d| d.as_nanos());
out.push_str(&format!(" {} {mtime}", meta.len()));
}
out.push('\n');
}
out
}
/// The full message of `hash` (`git log -1 --format=%B`), trimmed.
pub fn commit_message(root: &Path, hash: &str) -> Result<String, String> {
run_git(root, &["log", "-1", "--format=%B", hash])
.map(|m| m.trim().to_string())
.map_err(|e| e.to_string())
}
/// The inline blame's hover card for `hash` (#1556): author and email, the
/// full date, the short hash and the whole message, which `git blame`
/// does not give (its `summary` is the first line). `--no-show-signature`
/// because a `log.showSignature = true` config would otherwise print gpg's
/// verdict above the card.
pub fn commit_card(dir: &Path, hash: &str) -> Result<String, String> {
let format = "--format=%an <%ae>%n%ad (%ar)%ncommit %h%n%n%B";
run_git(dir, &["log", "-1", "--no-show-signature", format, hash]).map_err(|e| e.to_string())
}
// --- Remotes -------------------------------------------------------------
/// A configured remote: its name and fetch URL, for the Remote submenu's
/// pickers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct RemoteInfo {
pub name: String,
pub url: String,
}
/// List configured remotes (`git remote -v`), de-duplicated to one row per
/// remote (the fetch URL).
pub fn list_remotes(root: &Path) -> Result<Vec<RemoteInfo>, String> {
let raw = run_git(root, &["remote", "-v"]).map_err(|e| e.to_string())?;
let mut out: Vec<RemoteInfo> = Vec::new();
for line in raw.lines() {
// Format: "<name>\t<url> (fetch|push)"
let mut parts = line.split_whitespace();
let (Some(name), Some(url)) = (parts.next(), parts.next()) else {
continue;
};
if out.iter().any(|r| r.name == name) {
continue;
}
out.push(RemoteInfo {
name: name.to_string(),
url: url.to_string(),
});
}
Ok(out)
}
/// Add a remote (`git remote add <name> <url>`).
pub fn add_remote(root: &Path, name: &str, url: &str) -> Result<String, String> {
run_mutation(root, &["remote", "add", name, url])
}
/// Remove a remote (`git remote remove <name>`).
pub fn remove_remote(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["remote", "remove", name])
}
// --- Stash (full set) ----------------------------------------------------
/// Stash including untracked files (`git stash push -u`).
pub fn stash_push_untracked(root: &Path, message: Option<&str>) -> Result<String, String> {
stash_push_args(root, &["-u"], message)
}
/// Stash only the staged changes (`git stash push --staged`).
pub fn stash_push_staged(root: &Path, message: Option<&str>) -> Result<String, String> {
stash_push_args(root, &["--staged"], message)
}
/// One entry in the stash list, for the apply/pop/drop pickers.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct StashInfo {
/// Stash index (`stash@{N}` is built from this).
pub index: usize,
/// The human description git stores (`WIP on main: …`).
pub message: String,
/// How long ago it was made (`5 minutes ago`, #1581).
pub age: String,
/// The files it holds, untracked ones included (#1581), so two stashes
/// on the same commit can be told apart.
pub files: Vec<String>,
}
impl StashInfo {
/// The picker row (#1581): `stash@{N}: <message> · <age> · <files>`,
/// naming at most three files.
pub fn label(&self) -> String {
let mut label = format!("stash@{{{}}}: {}", self.index, self.message);
if !self.age.is_empty() {
label.push_str(&format!(" \u{b7} {}", self.age));
}
if !self.files.is_empty() {
let shown: Vec<&str> = self.files.iter().take(3).map(String::as_str).collect();
label.push_str(&format!(" \u{b7} {}", shown.join(", ")));
if self.files.len() > 3 {
label.push_str(&format!(" +{}", self.files.len() - 3));
}
}
label
}
}
/// List stashes newest-first (`git stash list`), each with its age and
/// files. Two git processes however many stashes there are, since the
/// pickers call this on the UI thread: one `git stash list --name-only`
/// for the tracked files (diffed against the commit the stash was made
/// on) and one `git show` over every stash's untracked-files commit.
pub fn list_stashes(root: &Path) -> Result<Vec<StashInfo>, String> {
let raw = run_git(
root,
&[
"stash",
"list",
"-m",
"--name-only",
"--format=%x1e%gd%x1f%cr%x1f%P%x1f%gs",
],
)
.map_err(|e| e.to_string())?;
let mut out = Vec::new();
// The third parent, when there is one, holds the untracked files.
let mut untracked_commits: Vec<(usize, String)> = Vec::new();
for record in raw.split('\x1e') {
let mut lines = record.lines();
let Some(header) = lines.next().filter(|h| !h.is_empty()) else {
continue;
};
let mut parts = header.split('\x1f');
let reflog = parts.next().unwrap_or("");
let age = parts.next().unwrap_or("").to_string();
let parents = parts.next().unwrap_or("");
let message = parts.next().unwrap_or("").to_string();
// reflog looks like "stash@{2}" — pull the integer out.
let index = reflog
.trim_start_matches("stash@{")
.trim_end_matches('}')
.parse::<usize>()
.unwrap_or(out.len());
if let Some(untracked) = parents.split_whitespace().nth(2) {
untracked_commits.push((out.len(), untracked.to_string()));
}
let files = lines
.map(str::trim_end)
.filter(|l| !l.is_empty())
.map(str::to_string)
.collect();
out.push(StashInfo {
index,
message,
age,
files,
});
}
if !untracked_commits.is_empty() {
let mut args = vec!["show", "--root", "--name-only", "--format=%x1e%H"];
args.extend(untracked_commits.iter().map(|(_, hash)| hash.as_str()));
if let Ok(raw) = run_git(root, &args) {
let mut by_hash: std::collections::HashMap<&str, Vec<String>> =
std::collections::HashMap::new();
for record in raw.split('\x1e') {
let mut lines = record.lines();
let Some(hash) = lines.next().filter(|h| !h.is_empty()) else {
continue;
};
let names = lines
.map(str::trim_end)
.filter(|l| !l.is_empty())
.map(str::to_string)
.collect();
by_hash.insert(hash.trim(), names);
}
for (pos, hash) in &untracked_commits {
if let Some(names) = by_hash.remove(hash.as_str()) {
let files = &mut out[*pos].files;
files.extend(names);
files.sort();
files.dedup();
}
}
}
}
Ok(out)
}
/// A stash's changes as a patch against the commit it was made on,
/// untracked files included (`git stash show --stat --patch
/// --include-untracked stash@{N}`), for View Stash (#1581).
pub fn show_stash(root: &Path, index: usize) -> Result<String, String> {
diff_text(
root,
&[
"stash",
"show",
"--no-color",
"--no-ext-diff",
"--stat",
"--patch",
"--include-untracked",
&format!("stash@{{{index}}}"),
],
)
}
/// Apply a stash without dropping it (`git stash apply stash@{N}`).
pub fn stash_apply(root: &Path, index: usize) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["stash", "apply", &format!("stash@{{{index}}}")])
}
/// Apply and drop a specific stash (`git stash pop stash@{N}`).
pub fn stash_pop_at(root: &Path, index: usize) -> Result<String, String> {
run_mutation_keeping_conflicts(root, &["stash", "pop", &format!("stash@{{{index}}}")])
}
/// Drop a stash without applying it (`git stash drop stash@{N}`).
pub fn stash_drop(root: &Path, index: usize) -> Result<String, String> {
run_mutation(root, &["stash", "drop", &format!("stash@{{{index}}}")])
}
/// The commit a stash entry records (`git rev-parse stash@{N}`). Unlike its
/// index, it keeps naming the same stash while others are pushed or dropped.
pub fn stash_oid(root: &Path, index: usize) -> Result<String, String> {
run_git(
root,
&[
"rev-parse",
"--verify",
"--quiet",
&format!("stash@{{{index}}}"),
],
)
.map_err(|e| e.to_string())
}
/// Drop the stash whose commit is `oid`, at whatever index it holds now: a
/// stash pushed or dropped since it was picked shifts every index, and the
/// old one would name a different stash. Refuses when it is gone.
pub fn stash_drop_oid(root: &Path, oid: &str) -> Result<String, String> {
stash_drop(root, stash_index_of(root, oid)?)
}
/// Restore and drop the stash whose commit is `oid`, at whatever index it
/// holds now, as [`stash_drop_oid`] drops one: a stash pushed since, by a
/// checkout hook or another tool, would make a plain `git stash pop` restore
/// that one instead. Refuses when it is gone.
pub fn stash_pop_oid(root: &Path, oid: &str) -> Result<String, String> {
stash_pop_at(root, stash_index_of(root, oid)?)
}
/// The index the stash whose commit is `oid` holds now, or an error when it
/// is no longer in the stash list.
fn stash_index_of(root: &Path, oid: &str) -> Result<usize, String> {
let list = run_git(root, &["stash", "list", "--format=%H"]).map_err(|e| e.to_string())?;
list.lines()
.position(|hash| hash.trim() == oid)
.ok_or_else(|| String::from("that stash is no longer in the stash list"))
}
// --- Tags ----------------------------------------------------------------
/// List tags newest-first (`git tag --sort=-creatordate`).
pub fn list_tags(root: &Path) -> Result<Vec<String>, String> {
let raw = run_git(root, &["tag", "--sort=-creatordate"]).map_err(|e| e.to_string())?;
Ok(raw
.lines()
.filter(|l| !l.is_empty())
.map(str::to_string)
.collect())
}
/// Create a tag at HEAD: annotated (`git tag -a <name> -m <message>`)
/// when there is a message, as VS Code's Create Tag makes one (#1582),
/// else lightweight (`git tag <name>`).
pub fn create_tag(root: &Path, name: &str, message: Option<&str>) -> Result<String, String> {
match message.map(str::trim).filter(|m| !m.is_empty()) {
Some(message) => run_mutation(root, &["tag", "-a", name, "-m", message]),
None => run_mutation(root, &["tag", name]),
}
}
/// Push every local tag to `remote` (`git push <remote> --tags`, #1582).
/// A plain push sends none, so a tag made here stayed local.
pub fn push_tags(root: &Path, remote: &str) -> Result<String, String> {
run_mutation(root, &["push", remote, "--tags"])
}
/// The tags on `remote` (`git ls-remote --tags --refs`), by name (#1582).
pub fn list_remote_tags(root: &Path, remote: &str) -> Result<Vec<String>, String> {
let raw = run_mutation(root, &["ls-remote", "--tags", "--refs", remote])?;
Ok(parse_remote_tags(&raw))
}
/// The tag names in `git ls-remote --tags --refs` output; a peeled
/// `^{}` line, which `--refs` already drops, is the same tag again.
fn parse_remote_tags(raw: &str) -> Vec<String> {
raw.lines()
.filter_map(|line| line.split_once('\t')?.1.strip_prefix("refs/tags/"))
.filter(|tag| !tag.ends_with("^{}"))
.map(str::to_string)
.collect()
}
/// Delete tag `name` from `remote` (`git push <remote> --delete
/// refs/tags/<name>`, #1582); the local tag stays.
pub fn delete_remote_tag(root: &Path, remote: &str, name: &str) -> Result<String, String> {
run_mutation(
root,
&["push", remote, "--delete", &format!("refs/tags/{name}")],
)
}
/// Delete a tag (`git tag -d <name>`).
pub fn delete_tag(root: &Path, name: &str) -> Result<String, String> {
run_mutation(root, &["tag", "-d", name])
}
/// Render an elapsed-seconds count as a coarse relative time (e.g.
/// "2 hours ago"), used by the Explorer TIMELINE view. Negative inputs
/// clamp to zero.
pub fn humanize_age(secs_ago: i64) -> String {
let s = secs_ago.max(0);
if s < 60 {
return format!("{s} seconds ago");
}
let m = s / 60;
if m < 60 {
return format!("{m} minute{} ago", if m == 1 { "" } else { "s" });
}
let h = m / 60;
if h < 24 {
return format!("{h} hour{} ago", if h == 1 { "" } else { "s" });
}
let d = h / 24;
if d < 30 {
return format!("{d} day{} ago", if d == 1 { "" } else { "s" });
}
let mo = d / 30;
if mo < 12 {
return format!("{mo} month{} ago", if mo == 1 { "" } else { "s" });
}
let y = mo / 12;
format!("{y} year{} ago", if y == 1 { "" } else { "s" })
}
fn current_unix_seconds() -> i64 {
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// `git rev-list --left-right --count HEAD...@{u}` returns "<ahead>\t<behind>".
pub fn parse_ahead_behind(out: &str) -> (usize, usize) {
let mut parts = out.split_whitespace();
let a = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
let b = parts.next().and_then(|s| s.parse().ok()).unwrap_or(0);
(a, b)
}
/// Unit of work the App posts to the background git worker. Coalesced
/// inside the loop so a burst of clicks / FS-watcher ticks turns into a
/// single shell-out instead of N. `SetRoot` rebinds the worker's working
/// directory in-place — used by `App::change_workspace_root` so a Make
/// Root that lands inside a git repo can flip the Source Control panel
/// out of its no-repo empty state without recreating the worker thread.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GitRequest {
Status,
StatusAndChanges,
SetRoot(PathBuf),
}
impl GitRequest {
/// Merge two pending *query* requests into the strongest one.
/// `StatusAndChanges` dominates a bare `Status`; same+same is the same.
/// `SetRoot` is never a query and the worker drains it inline before
/// merging, so it must not appear here.
pub fn merge(self, other: Self) -> Self {
use GitRequest::*;
match (self, other) {
(SetRoot(_), _) | (_, SetRoot(_)) => {
unreachable!(
"SetRoot is drained inline before merge; it cannot reach the query merge"
)
}
(StatusAndChanges, _) | (_, StatusAndChanges) => StatusAndChanges,
(Status, Status) => Status,
}
}
}
/// Result the worker ships back. The variants mirror `GitRequest` 1:1
/// so the App can route each response to the right consumer without an
/// extra request-id channel.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum GitResponse {
Status(GitStatus),
StatusAndChanges(GitStatus, Vec<ChangeEntry>),
}
/// Background worker loop. Reads `GitRequest`s from `rx`, coalesces a
/// burst of pending requests into a single shell-out, runs `query` /
/// `query_changes` off the UI thread, and ships the result back via
/// `tx`. Terminates cleanly when either channel closes.
///
/// Croft was rewritten to Rust for raw input latency. `git status` on a
/// fresh shell adds 15-50 ms (process spawn + scanning the tree) — fine
/// off-thread, never on the hot path of a sidebar-icon click. The same
/// channel gate is used by both the click path (`refresh_source_control`)
/// and the FS-watcher tick (`refresh_git_status_debounced`).
pub fn git_worker_loop(
initial_root: PathBuf,
rx: std::sync::mpsc::Receiver<GitRequest>,
tx: std::sync::mpsc::Sender<GitResponse>,
) {
let mut root = initial_root;
while let Ok(first) = rx.recv() {
let mut pending: Option<GitRequest> = match first {
GitRequest::SetRoot(p) => {
root = p;
None
}
other => Some(other),
};
while let Ok(newer) = rx.try_recv() {
match newer {
GitRequest::SetRoot(p) => {
root = p;
}
other => {
pending = Some(match pending {
Some(prev) => prev.merge(other),
None => other,
});
}
}
}
let Some(req) = pending else {
continue;
};
let resp = match req {
GitRequest::Status => GitResponse::Status(query(&root)),
GitRequest::StatusAndChanges => {
let s = query(&root);
let c = query_changes(&root);
GitResponse::StatusAndChanges(s, c)
}
GitRequest::SetRoot(_) => unreachable!("SetRoot was drained inline"),
};
if tx.send(resp).is_err() {
return;
}
}
}
/// Which revision a shared link names (#1610): HEAD's commit for Git: Copy
/// Permalink, which keeps pointing at these lines as the branch moves, or
/// the branch for Git: Copy Head Link.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum LinkRev {
Commit,
Branch,
}
/// The web page for `file` at `rev`, scrolled to `lines` (1-based,
/// inclusive), on the current branch's remote, else `origin`, else the only
/// remote (#1610). `Err` says why there is no link rather than handing out
/// one that would not open: no repository or remote, a remote that is not
/// GitHub, GitLab or Bitbucket, a file that was never committed, or a
/// commit or branch that is not on the remote yet.
pub fn share_link(
file: &Path,
lines: Option<(usize, usize)>,
rev: LinkRev,
) -> Result<String, String> {
let dir = file.parent().ok_or("the file has no folder")?;
let top = repo_toplevel(dir).ok_or("the file is not in a git repository")?;
let rel = file
.canonicalize()
.ok()
.zip(top.canonicalize().ok())
.and_then(|(f, t)| f.strip_prefix(t).ok().map(Path::to_path_buf))
.ok_or("the file is not in a git repository")?;
let rel = rel
.components()
.map(|c| c.as_os_str().to_string_lossy())
.collect::<Vec<_>>()
.join("/");
let branch = run_git(&top, &["symbolic-ref", "--quiet", "--short", "HEAD"]).ok();
let config = |key: String| run_git(&top, &["config", "--get", &key]).ok();
let remotes = run_git(&top, &["remote"]).unwrap_or_default();
let remotes: Vec<&str> = remotes.lines().collect();
let remote = branch
.as_ref()
.and_then(|b| config(format!("branch.{b}.remote")))
.filter(|r| remotes.contains(&r.as_str()))
.or_else(|| remotes.contains(&"origin").then(|| String::from("origin")))
.or_else(|| (remotes.len() == 1).then(|| remotes[0].to_string()))
.ok_or("the repository has no remote to link to")?;
let url = run_git(&top, &["remote", "get-url", &remote])
.map_err(|_| format!("remote {remote} has no URL"))?;
let repo = crate::permalink::web_repo(&url)
.ok_or_else(|| format!("{remote} ({url}) is not a GitHub, GitLab or Bitbucket remote"))?;
// The file must be in HEAD's tree, which the linked commit or branch
// contains; being staged is not enough for the remote to show it.
if run_git(&top, &["cat-file", "-e", &format!("HEAD:{rel}")]).is_err() {
return Err(format!(
"{rel} is not committed, so {remote} has no page for it"
));
}
let rev = match rev {
LinkRev::Commit => {
let sha = run_git(&top, &["rev-parse", "HEAD"])
.map_err(|_| String::from("the repository has no commits"))?;
let pattern = format!("{remote}/*");
let pushed = run_git(
&top,
&["branch", "-r", "--contains", &sha, "--list", &pattern],
)
.is_ok_and(|out| !out.is_empty());
if !pushed {
return Err(format!(
"commit {} is not on {remote} yet, so the link would not open: push it first",
&sha[..sha.len().min(7)]
));
}
sha
}
LinkRev::Branch => {
let branch = branch.ok_or("HEAD is detached, so there is no branch to link to")?;
// The branch's name on the remote, which its upstream may spell
// differently; else the same name.
let name = config(format!("branch.{branch}.merge"))
.and_then(|m| m.strip_prefix("refs/heads/").map(str::to_string))
.unwrap_or_else(|| branch.clone());
let tracking = format!("refs/remotes/{remote}/{name}");
if run_git(&top, &["rev-parse", "--verify", "--quiet", &tracking]).is_err() {
return Err(format!(
"branch {name} is not on {remote} yet, so the link would not open: push it first"
));
}
// A tracking branch behind HEAD would show older lines.
if run_git(&top, &["merge-base", "--is-ancestor", "HEAD", &tracking]).is_err() {
return Err(format!(
"branch {name} on {remote} is behind your commits, so the link would show older lines: push it first"
));
}
name
}
};
Ok(crate::permalink::file_url(&repo, &rev, &rel, lines))
}
#[cfg(test)]
mod tests {
/// #858: the one line reported for git's output. A new branch's ref
/// update loses git's `*` flag but keeps its `[new branch]` tag; a
/// message with no ref update is its first line past the noise; git's
/// text of only noise is empty, and `error_line` then falls back to the
/// first line rather than saying nothing.
#[test]
fn summary_line_picks_the_ref_update_or_the_first_meaningful_line() {
assert_eq!(
summary_line("To /tmp/r.git\n * [new branch] main -> main"),
"[new branch] main -> main"
);
assert_eq!(
summary_line("Everything up-to-date"),
"Everything up-to-date"
);
assert_eq!(
summary_line("On branch main\nYour branch is up to date.\n\nnothing to commit"),
"nothing to commit"
);
assert_eq!(summary_line("remote: a\nremote: b\nhint: c"), "");
assert_eq!(error_line("hint: only a hint"), "hint: only a hint");
}
/// Git 2.43's text for a `git merge feature` that stopped on a conflict
/// (all of it on stdout).
const MERGE_CONFLICT_858: &str = "Auto-merging pricing.py\nCONFLICT (content): Merge conflict in pricing.py\nAutomatic merge failed; fix conflicts and then commit the result.";
/// The same merge with three conflicted files.
const MERGE_CONFLICTS_858: &str = "Auto-merging a.py\nCONFLICT (content): Merge conflict in a.py\nAuto-merging b.py\nCONFLICT (content): Merge conflict in b.py\nAuto-merging pricing.py\nCONFLICT (content): Merge conflict in pricing.py\nAutomatic merge failed; fix conflicts and then commit the result.";
/// `git rebase feature` stopped on a conflict: stdout (the conflict),
/// then stderr, whose first line git redrew over its `Rebasing (1/1)`
/// progress with a carriage return.
const REBASE_CONFLICT_858: &str = "Auto-merging pricing.py\nCONFLICT (content): Merge conflict in pricing.py\nRebasing (1/1)\rerror: could not apply ffb4d23... main: raise free shipping\nhint: Resolve all conflicts manually, mark them as resolved with\nhint: \"git add/rm <conflicted_files>\", then run \"git rebase --continue\".\nhint: You can instead skip this commit: run \"git rebase --skip\".\nhint: To abort and get back to the state before \"git rebase\", run \"git rebase --abort\".\nCould not apply ffb4d23... main: raise free shipping";
/// A `git pull` that fetched, then stopped merging on a conflict:
/// stdout, then the fetch's ref updates from stderr.
const PULL_CONFLICT_858: &str = "Auto-merging pricing.py\nCONFLICT (content): Merge conflict in pricing.py\nAutomatic merge failed; fix conflicts and then commit the result.\nFrom github.com:o/r\n 5a6cd5c..9f1e2d3 main -> origin/main";
/// `git stash pop` onto a conflicting commit.
const STASH_POP_CONFLICT_858: &str = "Auto-merging pricing.py\nCONFLICT (content): Merge conflict in pricing.py\nOn branch main\nUnmerged paths:\n (use \"git restore --staged <file>...\" to unstage)\n (use \"git add <file>...\" to mark resolution)\n\tboth modified: pricing.py\n\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\nThe stash entry is kept in case you need it again.";
/// #858: a merge, rebase, pull or stash pop that stopped on conflicts
/// is reported by its conflicts, not by git's first line, which is
/// `Auto-merging pricing.py` and reads like a step that went fine.
#[test]
fn error_line_names_the_conflicts_git_stopped_on() {
assert_eq!(error_line(MERGE_CONFLICT_858), "1 conflict (pricing.py)");
assert_eq!(
error_line(MERGE_CONFLICTS_858),
"3 conflicts (a.py, b.py, pricing.py)"
);
assert_eq!(error_line(REBASE_CONFLICT_858), "1 conflict (pricing.py)");
assert_eq!(
error_line(PULL_CONFLICT_858),
"1 conflict (pricing.py)",
"the conflict, not the fetch's ref update"
);
assert_eq!(
error_line(STASH_POP_CONFLICT_858),
"1 conflict (pricing.py)"
);
}
/// #858: with no conflict to name, git's `error:` or `fatal:` line wins
/// over a progress line or a fetched ref update printed before it, and
/// a line git redrew with a carriage return reads as its last redraw.
#[test]
fn error_line_prefers_git_s_error_and_fatal_lines() {
let rebase_stderr = "Rebasing (1/1)\rerror: could not apply ffb4d23... main: raise free shipping\nhint: Resolve all conflicts manually, mark them as resolved with\nCould not apply ffb4d23... main: raise free shipping";
assert_eq!(
error_line(rebase_stderr),
"error: could not apply ffb4d23... main: raise free shipping"
);
let pull = "From github.com:o/r\n * branch main -> FETCH_HEAD\nhint: Diverging branches can't be fast-forwarded.\nfatal: Not possible to fast-forward, aborting.";
assert_eq!(
error_line(pull),
"fatal: Not possible to fast-forward, aborting."
);
}
/// #858: git's result line, not the `Auto-merging` note printed before
/// it or the `Rebasing (1/1)` progress it redrew with a carriage return
/// and an erase-line sequence.
#[test]
fn headline_skips_auto_merging_and_reads_a_redrawn_line_as_shown() {
assert_eq!(
headline(
"Auto-merging pricing.py\nMerge made by the 'ort' strategy.\n pricing.py | 2 +-\n 1 file changed, 1 insertion(+), 1 deletion(-)"
),
"Merge made by the 'ort' strategy."
);
assert_eq!(
headline("Rebasing (1/1)\r\u{1b}[KSuccessfully rebased and updated refs/heads/rb."),
"Successfully rebased and updated refs/heads/rb."
);
}
/// #858 negative: a text of only `Auto-merging` notes still reports
/// something, never an empty line.
#[test]
fn error_line_of_only_auto_merging_notes_is_never_empty() {
assert_eq!(
error_line("Auto-merging pricing.py"),
"Auto-merging pricing.py"
);
let two = error_line("Auto-merging a.py\nAuto-merging b.py");
assert!(!two.is_empty(), "{two:?}");
assert!(!headline("Auto-merging pricing.py").is_empty());
}
/// #858 negative: the lines the push and commit reports already picked
/// are unchanged: a rejected ref update over git's `error:` line after
/// it, the first `fatal:` line, and "nothing to commit" past the
/// `On branch` preamble.
#[test]
fn error_line_keeps_the_push_and_commit_lines_it_already_picked() {
let rejected = "To github.com:o/r.git\n ! [rejected] main -> main (fetch first)\nerror: failed to push some refs to 'github.com:o/r.git'\nhint: Updates were rejected because the remote contains work that you do";
assert_eq!(
error_line(rejected),
"[rejected] main -> main (fetch first)"
);
let fatal = "fatal: 'origin' does not appear to be a git repository\nfatal: Could not read from remote repository.\n\nPlease make sure you have the correct access rights";
assert_eq!(
error_line(fatal),
"fatal: 'origin' does not appear to be a git repository"
);
assert_eq!(
error_line(
"On branch main\nYour branch is up to date with 'origin/main'.\n\nnothing to commit, working tree clean"
),
"nothing to commit, working tree clean"
);
assert_eq!(
headline("[main 5a6cd5c] fix: one line\n 1 file changed, 1 insertion(+)"),
"[main 5a6cd5c] fix: one line"
);
}
/// git 2.43's refusal to switch branches over a local edit.
const SWITCH_REFUSED_925: &str = "error: Your local changes to the following files would be overwritten by checkout:\n\ta.txt\nPlease commit your changes or stash them before you switch branches.\nAborting";
/// #925: a refusal that lists files under its `error:` line names them
/// (three at most) instead of stopping at the colon, and is the one a
/// stash gets past; a switch blocked by untracked files is not.
#[test]
fn error_line_names_the_files_git_listed_under_it() {
assert_eq!(
error_line(SWITCH_REFUSED_925),
"error: Your local changes to the following files would be overwritten by checkout: a.txt"
);
let many = SWITCH_REFUSED_925.replace("\ta.txt", "\ta.txt\n\tb.txt\n\tc.txt\n\td.txt");
assert_eq!(
error_line(&many),
"error: Your local changes to the following files would be overwritten by checkout: a.txt, b.txt, c.txt, \u{2026}"
);
assert!(local_changes_block_switch(SWITCH_REFUSED_925));
let untracked = "error: The following untracked working tree files would be overwritten by checkout:\n\tb.txt\nPlease move or remove them before you switch branches.\nAborting";
assert_eq!(
error_line(untracked),
"error: The following untracked working tree files would be overwritten by checkout: b.txt"
);
assert!(!local_changes_block_switch(untracked));
// Both at once, as git 2.43 words it: a stash would not clear it.
let both = SWITCH_REFUSED_925.replace("\nAborting", "\n") + untracked;
assert!(!local_changes_block_switch(&both));
}
/// #858: the conflicts are counted per file and named, three at most;
/// a lone conflict git words without a file is git's own line; a text
/// with no `CONFLICT` line has no conflict summary.
#[test]
fn conflict_summary_counts_and_names_the_conflicted_files() {
assert_eq!(
conflict_summary(MERGE_CONFLICT_858).as_deref(),
Some("1 conflict (pricing.py)")
);
let five = (1..=5)
.map(|i| format!("Auto-merging f{i}.py\nCONFLICT (content): Merge conflict in f{i}.py"))
.collect::<Vec<_>>()
.join("\n");
assert_eq!(
conflict_summary(&five).as_deref(),
Some("5 conflicts (f1.py, f2.py, f3.py, \u{2026})")
);
let twice = "CONFLICT (add/add): Merge conflict in a.py\nCONFLICT (content): Merge conflict in a.py";
assert_eq!(
conflict_summary(twice).as_deref(),
Some("1 conflict (a.py)")
);
let modify_delete = "CONFLICT (modify/delete): report.py deleted in feature and modified in HEAD. Version HEAD of report.py left in tree.\nAutomatic merge failed; fix conflicts and then commit the result.";
assert_eq!(
conflict_summary(modify_delete).as_deref(),
Some(
"CONFLICT (modify/delete): report.py deleted in feature and modified in HEAD. Version HEAD of report.py left in tree."
)
);
let mixed = format!("{modify_delete}\n{MERGE_CONFLICT_858}");
assert_eq!(
conflict_summary(&mixed).as_deref(),
Some("2 conflicts (pricing.py, \u{2026})")
);
assert_eq!(conflict_summary("Auto-merging pricing.py"), None);
assert_eq!(
conflict_summary("error: cannot rebase: You have unstaged changes."),
None
);
}
/// #858: a failure names the operation ("Merge failed", never the
/// "Merged failed" its success prefix made of it); one that stopped on
/// conflicts names them after the operation.
#[test]
fn failure_line_names_the_operation_and_why() {
assert_eq!(
failure_line("Merge", MERGE_CONFLICT_858),
"Merge: 1 conflict (pricing.py)"
);
assert_eq!(
failure_line("Rebase", REBASE_CONFLICT_858),
"Rebase: 1 conflict (pricing.py)"
);
assert_eq!(
failure_line(
"Rebase",
"error: cannot rebase: You have unstaged changes.\nerror: Please commit or stash them."
),
"Rebase failed: error: cannot rebase: You have unstaged changes."
);
assert_eq!(
failure_line("Merge", "merge: nosuch - not something we can merge"),
"Merge failed: merge: nosuch - not something we can merge"
);
assert_eq!(
failure_line("Merge", "Auto-merging pricing.py"),
"Merge failed: Auto-merging pricing.py",
"only noise: still says something, and still that the merge failed"
);
}
/// #858: the line a successful pull, fetch, push, stash or switch
/// reports, from git's own texts (2.43): its result, past the fetch and
/// push chatter, the range, the diffstat and `git status` dumps.
#[test]
fn result_line_names_what_git_did() {
let fast_forward = "Updating 5d25c91..f79a881\nFast-forward\n f.txt | 1 +\n 1 file changed, 1 insertion(+)";
assert_eq!(result_line(fast_forward), "Fast-forward");
let rebased = "From /tmp/r\n 5d25c91..f79a881 main -> origin/main\nRebasing (1/2)\rRebasing (2/2)\r\r\u{1b}[KSuccessfully rebased and updated refs/heads/main.";
assert_eq!(
result_line(rebased),
"Successfully rebased and updated refs/heads/main."
);
assert_eq!(
result_line("Auto-merging f.txt\nMerge made by the 'ort' strategy.\n f.txt | 1 +"),
"Merge made by the 'ort' strategy."
);
let popped = "On branch main\nChanges not staged for commit:\n (use \"git add <file>...\" to update what will be committed)\n\tmodified: g.txt\n\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\nDropped refs/stash@{0} (4f2e1d0)";
assert_eq!(result_line(popped), "Dropped refs/stash@{0} (4f2e1d0)");
assert_eq!(
result_line("[main 5a6cd5c] fix: a -> b twice\n 1 file changed"),
"[main 5a6cd5c] fix: a -> b twice",
"a commit's subject is kept as written"
);
let fetched = "From /tmp/r\n a3fecf9..117b94a main -> origin/main";
assert_eq!(result_line(fetched), "a3fecf9..117b94a main -> origin/main");
let negotiated = "fatal: expected 'acknowledgments', received 'packfile'\nwarning: push negotiation failed; proceeding anyway with push\nTo /tmp/r.git\n + 915bd5e...74d526d main -> main (forced update)";
assert_eq!(
result_line(negotiated),
"915bd5e...74d526d main -> main (forced update)"
);
}
/// #858 negative: a one-line result is kept whole, and a text with
/// nothing but noise and no ref update is empty, for the caller's own
/// word, never a stray `M\tpath` or `Your branch` line.
#[test]
fn result_line_keeps_a_lone_result_and_is_empty_for_pure_noise() {
assert_eq!(result_line("Already up to date."), "Already up to date.");
assert_eq!(
result_line("Everything up-to-date"),
"Everything up-to-date"
);
assert_eq!(
result_line("branch 'newb' set up to track 'origin/newb'."),
"branch 'newb' set up to track 'origin/newb'."
);
assert_eq!(
result_line("M\tseed.txt\nYour branch is up to date with 'origin/main'."),
""
);
assert_eq!(result_line(""), "");
}
use super::*;
use tempfile::TempDir;
#[test]
fn parse_branch_handles_typical_output() {
assert_eq!(parse_branch("main\n".into()), Some("main".to_string()));
assert_eq!(
parse_branch("feature/cool-thing\n".into()),
Some("feature/cool-thing".to_string())
);
}
#[test]
fn parse_branch_treats_empty_as_none() {
assert_eq!(parse_branch(String::new()), None);
assert_eq!(parse_branch(" \n".into()), None);
}
#[test]
fn porcelain_z_count_empty_means_clean() {
assert_eq!(porcelain_z_count(b""), 0);
assert_eq!(porcelain_z_count(b"\0"), 0);
}
#[test]
fn porcelain_z_count_counts_a_rename_once() {
assert_eq!(porcelain_z_count(b" M src/app.rs\0"), 1);
assert_eq!(porcelain_z_count(b"MM Cargo.toml\0 M src/lib.rs\0"), 2);
assert_eq!(
porcelain_z_count(b"R new.rs\0old.rs\0?? x.txt\0"),
2,
"a rename's source record is not a second change"
);
}
#[test]
fn parse_ahead_behind_typical() {
assert_eq!(parse_ahead_behind("3\t2"), (3, 2));
assert_eq!(parse_ahead_behind("0\t0"), (0, 0));
assert_eq!(parse_ahead_behind("12\t0\n"), (12, 0));
}
#[test]
fn parse_ahead_behind_falls_back_to_zero_on_garbage() {
assert_eq!(parse_ahead_behind(""), (0, 0));
assert_eq!(parse_ahead_behind("?"), (0, 0));
}
#[test]
fn parse_commit_graph_splits_parents_and_refs() {
let line = format!(
"{h}\x1f{s}\x1f{p1} {p2}\x1fHEAD -> main, tag: v1.0, origin/main\x1ffeat: merge\x1fvitali87\x1f1000",
h = "a".repeat(40),
s = "aaaaaaa",
p1 = "b".repeat(40),
p2 = "c".repeat(40),
);
let commits = parse_commit_graph(&line, 4600);
assert_eq!(commits.len(), 1);
let c = &commits[0];
assert_eq!(c.short_hash, "aaaaaaa");
assert_eq!(c.parents, vec!["b".repeat(40), "c".repeat(40)]);
assert_eq!(
c.refs,
vec![
"HEAD -> main".to_string(),
"tag: v1.0".to_string(),
"origin/main".to_string()
]
);
assert_eq!(c.summary, "feat: merge");
assert_eq!(c.age_secs, 3600);
// A root commit has an empty %P field → no parents.
let root_line = format!(
"{h}\x1fddddddd\x1f\x1f\x1finit\x1ft\x1f1",
h = "d".repeat(40)
);
let commits = parse_commit_graph(&root_line, 1);
assert!(commits[0].parents.is_empty());
assert!(commits[0].refs.is_empty());
}
/// End to end against a REAL repo: init, commit, branch, merge — then
/// assert `commit_graph` + the lane layout produce the diamond rails.
#[test]
fn commit_graph_of_a_real_merge_lays_out_the_diamond() {
let tmp = TempDir::new().unwrap();
let root = tmp.path().canonicalize().unwrap();
let run = |args: &[&str]| {
let ok = Command::new("git")
.args(["-C", root.to_str().unwrap()])
.args(args)
.output()
.unwrap()
.status
.success();
assert!(ok, "git {args:?} failed");
};
run(&["init", "-q", "-b", "main"]);
run(&["config", "user.email", "t@t"]);
run(&["config", "user.name", "t"]);
std::fs::write(root.join("a.txt"), "1\n").unwrap();
run(&["add", "."]);
run(&["commit", "-q", "-m", "root"]);
run(&["checkout", "-q", "-b", "feature"]);
std::fs::write(root.join("b.txt"), "2\n").unwrap();
run(&["add", "."]);
run(&["commit", "-q", "-m", "feature work"]);
run(&["checkout", "-q", "main"]);
std::fs::write(root.join("c.txt"), "3\n").unwrap();
run(&["add", "."]);
run(&["commit", "-q", "-m", "main work"]);
run(&["merge", "-q", "--no-ff", "-m", "merge feature", "feature"]);
let commits = commit_graph(&root, 50);
assert_eq!(commits.len(), 4, "root, two branches, one merge");
assert_eq!(commits[0].summary, "merge feature");
assert_eq!(commits[0].parents.len(), 2, "the merge has two parents");
assert!(
commits[0].refs.iter().any(|r| r.contains("main")),
"HEAD decoration must survive parsing; got {:?}",
commits[0].refs
);
let rows = crate::widgets::commit_graph::layout_graph(commits);
let rails: Vec<String> = rows
.iter()
.map(|r| r.cells.iter().map(|(ch, _)| *ch).collect())
.collect();
// git's --topo-order emits the second parent's subtree (feature work,
// lane 1) before the first parent's (main work, lane 0) here; either
// interleaving is a valid diamond, the shape is what matters.
assert_eq!(
rails,
vec!["●╮", "│●", "●│", "●╯"],
"a no-ff merge of one branch must draw the diamond"
);
}
/// Init a repo, commit a 20-line file, then edit line 2 and line 18
/// so the working tree carries two well-separated hunks.
fn repo_with_two_hunks(root: &Path) {
let run = |args: &[&str]| {
let ok = Command::new("git")
.args(["-C", root.to_str().unwrap()])
.args(args)
.output()
.unwrap()
.status
.success();
assert!(ok, "git {args:?} failed");
};
run(&["init", "-q", "-b", "main"]);
run(&["config", "user.email", "t@t"]);
run(&["config", "user.name", "t"]);
let original: String = (1..=20).map(|i| format!("line{i}\n")).collect();
std::fs::write(root.join("f.txt"), original).unwrap();
run(&["add", "f.txt"]);
run(&["commit", "-q", "-m", "init"]);
let mut edited: Vec<String> = (1..=20).map(|i| format!("line{i}")).collect();
edited[1] = "LINE2".into();
edited[17] = "LINE18".into();
std::fs::write(root.join("f.txt"), edited.join("\n") + "\n").unwrap();
}
fn git_stdout(root: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.args(["-C", root.to_str().unwrap()])
.args(args)
.output()
.unwrap();
String::from_utf8_lossy(&out.stdout).to_string()
}
#[test]
fn apply_patch_cached_stages_only_the_given_hunk() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
repo_with_two_hunks(root);
let head = read_file_at_head(root, "f.txt").unwrap();
let work = std::fs::read_to_string(root.join("f.txt")).unwrap();
let diff = crate::widgets::diff::DiffData::build(
std::path::PathBuf::new(),
std::path::PathBuf::new(),
head.lines().map(str::to_string).collect(),
work.lines().map(str::to_string).collect(),
);
let range = diff.hunk_range_at(0).unwrap();
let patch = diff.hunk_patch("f.txt", range);
apply_patch(root, &patch, true, false).unwrap();
let staged = git_stdout(root, &["diff", "--cached"]);
assert!(staged.contains("+LINE2"), "hunk 1 must be staged: {staged}");
assert!(
!staged.contains("LINE18"),
"hunk 2 must NOT be staged: {staged}"
);
let unstaged = git_stdout(root, &["diff"]);
assert!(
unstaged.contains("+LINE18"),
"hunk 2 must stay in the working tree: {unstaged}"
);
// Round-trip: unstage the same hunk again.
apply_patch(root, &patch, true, true).unwrap();
let staged = git_stdout(root, &["diff", "--cached"]);
assert!(
staged.trim().is_empty(),
"reverse cached apply must empty the index diff: {staged}"
);
}
/// #1236: `run.bat` stored LF in the index and CRLF in the working tree,
/// with `echo two` changed to `echo TWO`; `config` is extra setup.
fn crlf_checkout_with_one_edit(root: &Path, attrs: &str, config: &[(&str, &str)]) -> String {
let git = |args: &[&str]| {
let out = Command::new("git")
.arg("-C")
.arg(root)
.args(args)
.output()
.unwrap();
assert!(
out.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
};
git(&["init", "-q", "-b", "main"]);
git(&["config", "user.email", "a@b"]);
git(&["config", "user.name", "a"]);
for (k, v) in config {
git(&["config", k, v]);
}
std::fs::write(root.join(".gitattributes"), attrs).unwrap();
let head = "echo one\r\necho two\r\necho three\r\necho four\r\n";
std::fs::write(root.join("run.bat"), head).unwrap();
git(&["add", "."]);
git(&["commit", "-qm", "init"]);
let work = head.replace("two", "TWO");
std::fs::write(root.join("run.bat"), &work).unwrap();
let head = read_file_at_head(root, "run.bat").unwrap();
let diff = crate::widgets::diff::DiffData::build_with_byte_check(
std::path::PathBuf::new(),
root.join("run.bat"),
head.lines().map(str::to_string).collect(),
work.lines().map(str::to_string).collect(),
Some(&head),
Some(&work),
);
diff.hunk_patch("run.bat", diff.hunk_range_at(0).unwrap())
}
#[test]
fn staging_a_hunk_of_an_eol_crlf_file_stores_lf_like_git_add() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let patch = crlf_checkout_with_one_edit(root, "*.bat text eol=crlf\n", &[]);
apply_patch(root, &patch, true, false).unwrap();
let eol = git_stdout(root, &["ls-files", "--eol", "run.bat"]);
assert!(eol.starts_with("i/lf "), "the index blob: {eol}");
let status = git_stdout(root, &["status", "--porcelain", "run.bat"]);
assert_eq!(status, "M run.bat\n", "nothing is left unstaged");
// And back out again: the unstage patch must match the LF index.
apply_patch(root, &patch, true, true).unwrap();
assert_eq!(git_stdout(root, &["diff", "--cached"]), "");
}
#[test]
fn staging_a_hunk_under_core_autocrlf_stores_lf_like_git_add() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let patch = crlf_checkout_with_one_edit(root, "", &[("core.autocrlf", "true")]);
apply_patch(root, &patch, true, false).unwrap();
let eol = git_stdout(root, &["ls-files", "--eol", "run.bat"]);
assert!(eol.starts_with("i/lf "), "the index blob: {eol}");
}
#[test]
fn staging_a_hunk_of_a_file_kept_as_crlf_keeps_its_crs() {
// Negative: with no conversion configured, the index holds CRLF and
// `git add` keeps it, so the staged line keeps its `\r` too.
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let patch = crlf_checkout_with_one_edit(root, "", &[("core.autocrlf", "false")]);
apply_patch(root, &patch, true, false).unwrap();
let eol = git_stdout(root, &["ls-files", "--eol", "run.bat"]);
assert!(eol.starts_with("i/crlf "), "the index blob: {eol}");
assert_eq!(
git_stdout(root, &["status", "--porcelain", "run.bat"]),
"M run.bat\n"
);
}
#[test]
fn reverting_a_hunk_of_an_eol_crlf_file_writes_crlf_to_the_work_tree() {
// Negative: a revert writes the working tree, which keeps CRLF.
let tmp = TempDir::new().unwrap();
let root = tmp.path();
let patch = crlf_checkout_with_one_edit(root, "*.bat text eol=crlf\n", &[]);
apply_patch(root, &patch, false, true).unwrap();
assert_eq!(
std::fs::read(root.join("run.bat")).unwrap(),
b"echo one\r\necho two\r\necho three\r\necho four\r\n"
);
}
#[test]
fn apply_patch_reverse_reverts_only_the_given_hunk_in_the_working_tree() {
let tmp = TempDir::new().unwrap();
let root = tmp.path();
repo_with_two_hunks(root);
let head = read_file_at_head(root, "f.txt").unwrap();
let work = std::fs::read_to_string(root.join("f.txt")).unwrap();
let diff = crate::widgets::diff::DiffData::build(
std::path::PathBuf::new(),
std::path::PathBuf::new(),
head.lines().map(str::to_string).collect(),
work.lines().map(str::to_string).collect(),
);
let range = diff.hunk_range_at(0).unwrap();
let patch = diff.hunk_patch("f.txt", range);
apply_patch(root, &patch, false, true).unwrap();
let after = std::fs::read_to_string(root.join("f.txt")).unwrap();
assert!(after.contains("line2\n"), "hunk 1 must be reverted");
assert!(!after.contains("LINE2"), "hunk 1 edit must be gone");
assert!(after.contains("LINE18"), "hunk 2 must survive the revert");
}
#[test]
fn query_outside_a_git_repo_returns_in_repo_false() {
let tmp = TempDir::new().unwrap();
let s = query(tmp.path());
assert!(!s.in_repo);
assert!(s.branch.is_none());
assert!(!s.dirty);
}
#[test]
fn query_in_a_fresh_repo_finds_branch_and_clean() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
// Init the repo non-interactively.
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
// Empty repo: HEAD points at unborn branch "main", but symbolic-ref
// still works.
let s = query(p);
assert!(s.in_repo);
assert_eq!(s.branch.as_deref(), Some("main"));
assert!(!s.dirty);
}
#[test]
fn query_reports_dirty_after_a_file_appears() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
// Make a working-tree change.
std::fs::write(p.join("hello.txt"), "hi").unwrap();
let s = query(p);
assert!(s.in_repo);
assert!(s.dirty);
}
#[test]
fn query_collects_ignored_files_and_collapsed_dirs() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(p.join(".gitignore"), "*.log\nbuild/\n").unwrap();
std::fs::write(p.join("app.log"), "").unwrap();
std::fs::write(p.join("keep.txt"), "").unwrap();
std::fs::create_dir(p.join("build")).unwrap();
std::fs::write(p.join("build/out.txt"), "").unwrap();
let s = query(p);
assert!(s.ignored.contains(&p.join("app.log")));
assert!(
s.ignored.contains(&p.join("build")),
"a fully-ignored directory collapses to one entry, not its contents"
);
assert!(
!s.ignored.contains(&p.join("build/out.txt")),
"children of a collapsed ignored dir are not enumerated"
);
assert!(!s.ignored.contains(&p.join("keep.txt")));
assert!(!s.ignored.contains(&p.join(".gitignore")));
}
#[test]
fn a_directory_git_does_not_ignore_is_not_reported_as_ignored() {
// `ls-files --directory` collapses any ENTIRELY untracked directory
// whose contents all happen to be ignored, even when no rule matches
// the directory itself. Reporting it would grey a folder VS Code
// paints normally (it asks check-ignore per resource).
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(p.join(".gitignore"), "*.log\n").unwrap();
std::fs::create_dir(p.join("logs")).unwrap();
std::fs::write(p.join("logs/app.log"), "").unwrap();
let s = query(p);
assert!(
s.ignored.contains(&p.join("logs/app.log")),
"the ignored file itself is still reported"
);
assert!(
!s.ignored.contains(&p.join("logs")),
"no rule matches `logs` itself, so it must not be greyed"
);
}
#[test]
fn git_raw_does_not_deadlock_on_a_payload_past_the_pipe_buffer() {
// check-ignore echoes each match back as it reads, so BOTH pipes
// fill. Writing all of stdin before reading a byte of stdout
// deadlocks once the payload passes the buffer: git blocks writing
// stdout, stops draining stdin, and the writer blocks forever.
// Measured on this machine: 143 KB flows, 957 KB blocks — so this
// uses ~1 MB. On the single-threaded version this test hangs.
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(p.join(".gitignore"), "*.log\n").unwrap();
let n = 20_000;
let mut payload = Vec::new();
for i in 0..n {
payload.extend_from_slice(
format!("padded-name-to-widen-the-pipe-payload-{i:06}.log").as_bytes(),
);
payload.push(0);
}
let out =
git_raw(p, &["check-ignore", "-z", "--stdin"], Some(&payload)).unwrap_or_default();
let got = out.split(|b| *b == 0).filter(|s| !s.is_empty()).count();
assert_eq!(
got, n,
"every path must come back instead of stalling on a full pipe"
);
}
#[test]
fn a_filename_with_a_leading_space_is_reported_intact() {
// git sorts its output, so a leading-space name comes first — and a
// blanket trim() on the NUL-separated blob eats that space, naming a
// file that does not exist while the real one stays unmarked.
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(p.join(".gitignore"), "*.log\n").unwrap();
std::fs::write(p.join(" leading.log"), "").unwrap();
std::fs::write(p.join("zz.log"), "").unwrap();
let s = query(p);
assert!(
s.ignored.contains(&p.join(" leading.log")),
"the leading space belongs to the filename; got {:?}",
s.ignored
);
assert!(s.ignored.contains(&p.join("zz.log")));
}
#[test]
fn one_paths_ignore_verdict_matches_the_rules() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
std::fs::write(p.join(".gitignore"), "*.log\nout/\n").unwrap();
assert!(is_ignored(p, &p.join("a.log")));
assert!(
is_ignored(p, &p.join("out/deep/gen.rs")),
"under an ignored dir"
);
assert!(!is_ignored(p, &p.join("src/lib.rs")));
let bare = TempDir::new().unwrap();
assert!(
!is_ignored(bare.path(), &bare.path().join("a.log")),
"no repo"
);
}
#[test]
fn query_outside_a_repo_has_an_empty_ignored_set() {
let tmp = TempDir::new().unwrap();
let s = query(tmp.path());
assert!(s.ignored.is_empty());
}
#[test]
fn diff_previous_commit_shows_the_delta_since_the_last_commit() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let git = |args: &[&str]| {
Command::new("git")
.arg("-C")
.arg(p)
.args(["-c", "user.email=t@t", "-c", "user.name=t"])
.args(args)
.output()
.unwrap();
};
git(&["init", "-q", "-b", "main"]);
std::fs::write(p.join("f.txt"), "one\n").unwrap();
git(&["add", "."]);
git(&["commit", "-q", "-m", "first"]);
std::fs::write(p.join("f.txt"), "two\n").unwrap();
git(&["add", "."]);
git(&["commit", "-q", "-m", "second"]);
// Working tree matches HEAD (the second commit), so `git diff HEAD~1`
// is exactly the first->second delta.
let raw = diff_previous_commit(p).unwrap();
assert!(
raw.contains("-one"),
"diff vs previous commit must show the removed line; got: {raw}"
);
assert!(
raw.contains("+two"),
"diff vs previous commit must show the added line; got: {raw}"
);
}
#[test]
fn humanize_seconds_minutes_hours_days() {
assert_eq!(humanize_age(0), "0 seconds ago");
assert_eq!(humanize_age(45), "45 seconds ago");
assert_eq!(humanize_age(60), "1 minute ago");
assert_eq!(humanize_age(120), "2 minutes ago");
assert_eq!(humanize_age(3600), "1 hour ago");
assert_eq!(humanize_age(7200), "2 hours ago");
assert_eq!(humanize_age(86_400), "1 day ago");
assert_eq!(humanize_age(2 * 86_400), "2 days ago");
}
#[test]
fn humanize_clamps_negatives_to_zero() {
assert_eq!(humanize_age(-100), "0 seconds ago");
}
#[test]
fn parse_porcelain_changes_handles_unstaged_modified() {
let entries = parse_porcelain_changes(" M src/app.rs\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "src/app.rs".to_string(),
kind: ChangeKind::Modified,
..Default::default()
}]
);
}
#[test]
fn parse_porcelain_changes_handles_staged_modified() {
let entries = parse_porcelain_changes("M src/app.rs\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "src/app.rs".to_string(),
kind: ChangeKind::StagedModified,
..Default::default()
}]
);
}
#[test]
fn parse_porcelain_changes_emits_two_entries_for_partially_staged() {
// MM: staged content then further modified in worktree.
let entries = parse_porcelain_changes("MM src/app.rs\n");
assert_eq!(
entries,
vec![
ChangeEntry {
path: "src/app.rs".to_string(),
kind: ChangeKind::StagedModified,
..Default::default()
},
ChangeEntry {
path: "src/app.rs".to_string(),
kind: ChangeKind::Modified,
..Default::default()
},
]
);
}
#[test]
fn parse_porcelain_changes_handles_untracked() {
let entries = parse_porcelain_changes("?? scratch.txt\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "scratch.txt".to_string(),
kind: ChangeKind::Untracked,
..Default::default()
}]
);
}
#[test]
fn parse_porcelain_changes_handles_rename_takes_destination_path() {
let entries = parse_porcelain_changes("R old.txt -> new.txt\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "new.txt".to_string(),
kind: ChangeKind::StagedRenamed,
..Default::default()
}]
);
}
#[test]
fn unquote_porcelain_path_passes_plain_ascii_paths_through() {
assert_eq!(unquote_porcelain_path("README.md"), "README.md");
assert_eq!(unquote_porcelain_path("src/main.rs"), "src/main.rs");
}
#[test]
fn unquote_porcelain_path_strips_double_quotes_and_unescapes_spaces() {
// `git status --porcelain` wraps filenames containing spaces in
// double quotes. The user's repro: a Finder "Duplicate" producing
// `linked_list copy.py`, which arrives as `"linked_list copy.py"`.
assert_eq!(
unquote_porcelain_path("\"linked_list copy.py\""),
"linked_list copy.py",
);
}
#[test]
fn unquote_porcelain_path_decodes_c_style_escapes() {
assert_eq!(
unquote_porcelain_path(r#""line\nbreak.txt""#),
"line\nbreak.txt"
);
assert_eq!(
unquote_porcelain_path(r#""quote\"inside.txt""#),
"quote\"inside.txt"
);
assert_eq!(
unquote_porcelain_path(r#""back\\slash.txt""#),
"back\\slash.txt"
);
}
#[test]
fn unquote_porcelain_path_decodes_octal_utf8_sequences() {
// `core.quotepath = true` (default) escapes non-ASCII bytes as
// 3-digit octal. `ä` is UTF-8 0xC3 0xA4 → `\303\244`.
assert_eq!(unquote_porcelain_path(r#""f\303\244.txt""#), "fä.txt");
}
#[test]
fn parse_porcelain_changes_de_quotes_paths_with_spaces() {
// Regression for the user's "Stage failed: fatal: pathspec
// '"linked_list copy.py"' did not match any files" report.
// The parser must strip the surrounding double quotes so the
// downstream `git add -- <path>` call hits the real filename.
let entries = parse_porcelain_changes("?? \"linked_list copy.py\"\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "linked_list copy.py".to_string(),
kind: ChangeKind::Untracked,
..Default::default()
}]
);
}
#[test]
fn parse_porcelain_changes_handles_conflict() {
let entries = parse_porcelain_changes("UU merge.txt\n");
assert_eq!(
entries,
vec![ChangeEntry {
path: "merge.txt".to_string(),
kind: ChangeKind::Conflicted,
..Default::default()
}]
);
}
#[test]
fn parse_numstat_extracts_additions_deletions_per_path() {
let out = "12\t3\tsrc/app.rs\x005\t0\tREADME.md\x00-\t-\tassets/logo.png\x00";
let map = parse_numstat(out);
assert_eq!(map.get("src/app.rs"), Some(&(12, 3)));
assert_eq!(map.get("README.md"), Some(&(5, 0)));
assert_eq!(map.get("assets/logo.png"), Some(&(0, 0)));
// `-z` paths are never quoted: a space or a quote is the name itself.
let map = parse_numstat("1\t0\tmy \"notes\".md\x00");
assert_eq!(map.get("my \"notes\".md"), Some(&(1, 0)));
}
#[test]
fn parse_numstat_keys_renames_on_destination_path() {
// What `git diff --cached --numstat -z` prints for a rename into
// another folder, a rename beside a plain edit, and a rename
// inside one folder (#1164).
let out = "1\t1\t\x00dir1/a.txt\x00dir2/a.txt\x00\
1\t1\tplain.txt\x00\
2\t1\t\x00src/old.rs\x00src/new.rs\x00";
let map = parse_numstat(out);
assert_eq!(map.get("dir2/a.txt"), Some(&(1, 1)));
assert_eq!(map.get("plain.txt"), Some(&(1, 1)));
assert_eq!(map.get("src/new.rs"), Some(&(2, 1)));
assert_eq!(map.len(), 3, "{map:?}");
}
#[test]
fn a_staged_rename_counts_the_lines_it_changed() {
// #1164: a renamed file that was also edited reported 0/0, so the
// staged total undercounted the commit.
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::create_dir_all(p.join("src")).unwrap();
std::fs::write(p.join("src/old.rs"), "l1\nl2\nl3\nl4\nl5\n").unwrap();
sh_git(p, &["add", "."]);
sh_git(p, &["commit", "-qm", "add"]);
sh_git(p, &["mv", "src/old.rs", "src/new.rs"]);
std::fs::write(p.join("src/new.rs"), "EDITED\nl2\nl3\nl4\nl5\n").unwrap();
sh_git(p, &["add", "-A"]);
let entries = query_changes(p);
let renamed = entries
.iter()
.find(|e| e.path == "src/new.rs")
.expect("the rename is listed under its new name");
assert_eq!((renamed.additions, renamed.deletions), (1, 1));
}
#[test]
fn change_kind_section_groups_correctly() {
assert_eq!(ChangeKind::StagedAdded.section(), ChangeSection::Staged);
assert_eq!(ChangeKind::Modified.section(), ChangeSection::Changes);
assert_eq!(ChangeKind::Untracked.section(), ChangeSection::Untracked);
assert_eq!(ChangeKind::Conflicted.section(), ChangeSection::Conflicts);
}
#[test]
fn commit_rejects_empty_message() {
let tmp = TempDir::new().unwrap();
assert!(commit(tmp.path(), "").is_err());
assert!(commit(tmp.path(), " \n").is_err());
}
/// GIT_TERMINAL_PROMPT and a null stdin are checked too, but the session
/// is what tells: a test runner has no terminal to hand on and may set
/// GIT_TERMINAL_PROMPT=0 itself, while a hook still in croft's session
/// can open croft's `/dev/tty`.
#[cfg(target_os = "linux")]
#[test]
fn commit_never_offers_its_hooks_the_terminal() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
let git = |args: &[&str]| {
Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.output()
.unwrap();
};
git(&["init", "-q"]);
git(&["config", "user.email", "a@b"]);
git(&["config", "user.name", "a"]);
std::fs::write(p.join("f.txt"), "one\n").unwrap();
git(&["add", "f.txt"]);
git(&["commit", "-qm", "init"]);
let hook = p.join(".git/hooks/pre-commit");
std::fs::create_dir_all(hook.parent().unwrap()).unwrap();
std::fs::write(
&hook,
"#!/bin/sh\necho \"prompt=$GIT_TERMINAL_PROMPT\" > seen\n\
if [ -t 0 ]; then echo stdin=tty >> seen; else echo stdin=none >> seen; fi\n\
if [ \"$(cut -d' ' -f6 /proc/$$/stat)\" = \"$(cat croft_sid)\" ]; \
then echo session=croft >> seen; else echo session=own >> seen; fi\n",
)
.unwrap();
// SAFETY: getsid(0) only reads the calling process's session id.
let sid = unsafe { libc::getsid(0) };
std::fs::write(p.join("croft_sid"), sid.to_string()).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&hook, std::fs::Permissions::from_mode(0o755)).unwrap();
}
std::fs::write(p.join("f.txt"), "two\n").unwrap();
commit(p, "two").unwrap();
assert_eq!(
std::fs::read_to_string(p.join("seen")).unwrap(),
"prompt=0\nstdin=none\nsession=own\n"
);
}
#[test]
fn commit_creates_a_commit_in_a_real_repo() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.email", "a@b"])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.name", "a"])
.status();
std::fs::write(p.join("hello.txt"), "hi").unwrap();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["add", "."])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["commit", "-m", "init", "--quiet"])
.status();
std::fs::write(p.join("hello.txt"), "hi v2").unwrap();
let summary = commit(p, "second commit").expect("commit should succeed");
assert!(
summary.contains("second commit") || summary.contains("main"),
"summary was: {summary}"
);
assert!(
query_changes(p).is_empty(),
"post-commit working tree should be clean"
);
}
#[test]
fn git_request_merge_collapses_status_and_changes_into_status_and_changes() {
assert_eq!(
GitRequest::Status.merge(GitRequest::Status),
GitRequest::Status,
);
assert_eq!(
GitRequest::Status.merge(GitRequest::StatusAndChanges),
GitRequest::StatusAndChanges,
);
assert_eq!(
GitRequest::StatusAndChanges.merge(GitRequest::Status),
GitRequest::StatusAndChanges,
);
}
#[test]
fn git_worker_loop_processes_a_status_and_changes_request_and_returns_entries() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.email", "a@b"])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.name", "a"])
.status();
std::fs::write(p.join("untracked.txt"), "x").unwrap();
let (req_tx, req_rx) = std::sync::mpsc::channel::<GitRequest>();
let (resp_tx, resp_rx) = std::sync::mpsc::channel::<GitResponse>();
let root = p.to_path_buf();
let join = std::thread::spawn(move || git_worker_loop(root, req_rx, resp_tx));
req_tx.send(GitRequest::StatusAndChanges).unwrap();
let resp = resp_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("worker must reply within 10s");
match resp {
GitResponse::StatusAndChanges(_, entries) => {
assert_eq!(
entries.len(),
1,
"expected 1 untracked entry, got {entries:?}"
);
assert_eq!(entries[0].kind, ChangeKind::Untracked);
}
other => panic!("expected StatusAndChanges, got {other:?}"),
}
drop(req_tx);
join.join().unwrap();
}
#[test]
fn git_worker_loop_set_root_redirects_subsequent_query_to_the_new_root() {
let tmp_no_repo = TempDir::new().unwrap();
let tmp_repo = TempDir::new().unwrap();
let p_repo = tmp_repo.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p_repo)
.args(["init", "-q", "-b", "feature-x"])
.output();
let _ = Command::new("git")
.args(["-C"])
.arg(p_repo)
.args(["config", "user.email", "a@b"])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p_repo)
.args(["config", "user.name", "a"])
.status();
let (req_tx, req_rx) = std::sync::mpsc::channel::<GitRequest>();
let (resp_tx, resp_rx) = std::sync::mpsc::channel::<GitResponse>();
let initial_root = tmp_no_repo.path().to_path_buf();
let join = std::thread::spawn(move || git_worker_loop(initial_root, req_rx, resp_tx));
req_tx
.send(GitRequest::SetRoot(p_repo.to_path_buf()))
.unwrap();
req_tx.send(GitRequest::Status).unwrap();
let resp = resp_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("worker must reply within 10s after SetRoot+Status");
match resp {
GitResponse::Status(status) => {
assert!(
status.in_repo,
"after SetRoot to a real git repo the next Status must report in_repo=true (the bug was that SetRoot didn't exist, so queries kept hitting the stale root captured at thread spawn)"
);
assert_eq!(status.branch.as_deref(), Some("feature-x"));
}
other => panic!("expected Status, got {other:?}"),
}
drop(req_tx);
join.join().unwrap();
}
#[test]
fn git_worker_loop_coalesces_a_burst_into_one_status_and_changes_response() {
// Two pending requests (Status + Changes) that arrive faster than
// the worker wakes up must collapse to a single
// StatusAndChanges response (the coalesce drains rx via
// try_recv before the second .recv()). Without the merge, the
// worker would shell out twice for what the App treats as one
// logical refresh.
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.email", "a@b"])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.name", "a"])
.status();
let (req_tx, req_rx) = std::sync::mpsc::channel::<GitRequest>();
let (resp_tx, resp_rx) = std::sync::mpsc::channel::<GitResponse>();
let root = p.to_path_buf();
// Queue two requests BEFORE the worker starts so the first
// recv() succeeds and the try_recv coalesce sees the second one.
req_tx.send(GitRequest::Status).unwrap();
req_tx.send(GitRequest::StatusAndChanges).unwrap();
let join = std::thread::spawn(move || git_worker_loop(root, req_rx, resp_tx));
let first = resp_rx
.recv_timeout(std::time::Duration::from_secs(10))
.expect("worker must reply within 10s");
assert!(
matches!(first, GitResponse::StatusAndChanges(_, _)),
"burst must coalesce into one StatusAndChanges response, got {first:?}",
);
// No second response — the two pending requests merged.
let second = resp_rx.recv_timeout(std::time::Duration::from_millis(200));
assert!(
second.is_err(),
"coalesce must produce exactly one response per burst, got an extra {second:?}",
);
drop(req_tx);
join.join().unwrap();
}
fn sh_git(p: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.output()
.unwrap();
String::from_utf8_lossy(&out.stdout).into_owned()
}
#[test]
fn staging_a_bracketed_path_stages_only_that_file() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::create_dir(p.join("pages")).unwrap();
std::fs::write(p.join("pages/[id].tsx"), "a").unwrap();
std::fs::write(p.join("pages/i.tsx"), "b").unwrap();
stage_paths(p, &[String::from("pages/[id].tsx")]).unwrap();
let staged = sh_git(p, &["diff", "--cached", "--name-only"]);
assert_eq!(staged.trim(), "pages/[id].tsx");
unstage_paths(p, &[String::from("pages/[id].tsx")]).unwrap();
assert_eq!(sh_git(p, &["diff", "--cached", "--name-only"]).trim(), "");
}
#[test]
fn discarding_a_changes_row_keeps_the_staged_part() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "staged\n").unwrap();
sh_git(p, &["add", "seed.txt"]);
std::fs::write(p.join("seed.txt"), "staged\nunstaged\n").unwrap();
discard_path(p, "seed.txt", false, false).unwrap();
assert_eq!(
std::fs::read_to_string(p.join("seed.txt")).unwrap(),
"staged\n"
);
assert_eq!(
sh_git(p, &["diff", "--cached", "--name-only"]).trim(),
"seed.txt"
);
}
#[test]
fn discarding_an_untracked_folder_keeps_its_ignored_files() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join(".gitignore"), ".env\n").unwrap();
sh_git(p, &["add", ".gitignore"]);
sh_git(p, &["commit", "-qm", "ignore"]);
std::fs::create_dir(p.join("app")).unwrap();
std::fs::write(p.join("app/new.rs"), "x").unwrap();
std::fs::write(p.join("app/.env"), "SECRET=1").unwrap();
discard_path(p, "app/", true, false).unwrap();
assert!(!p.join("app/new.rs").exists());
assert!(
p.join("app/.env").exists(),
"an ignored file is not the discard's to delete"
);
}
#[test]
fn a_single_hunk_stages_and_reverts_at_its_own_lines() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
// Repeated context, and an earlier unstaged hunk that shifts every
// later working-tree line by three.
let head: String = (0..12)
.map(|i| if i % 2 == 0 { "a\n" } else { "c\n" })
.collect();
std::fs::write(p.join("f.txt"), &head).unwrap();
sh_git(p, &["add", "f.txt"]);
sh_git(p, &["commit", "-qm", "f"]);
let mut work: Vec<&str> = head.lines().collect();
work.insert(9, "cz");
for _ in 0..3 {
work.insert(0, "top");
}
let work_text = work.join("\n") + "\n";
std::fs::write(p.join("f.txt"), &work_text).unwrap();
// The later hunk alone: `cz` after HEAD line 9, context a/c around it.
let patch = "--- a/f.txt\n+++ b/f.txt\n@@ -9,2 +12,3 @@\n a\n+cz\n c\n";
apply_patch(p, patch, true, false).unwrap();
let staged = sh_git(p, &["show", ":f.txt"]);
let mut want: Vec<&str> = head.lines().collect();
want.insert(9, "cz");
assert_eq!(staged, want.join("\n") + "\n", "staged at HEAD line 9");
sh_git(p, &["reset", "-q"]);
apply_patch(p, patch, false, true).unwrap();
let reverted = std::fs::read_to_string(p.join("f.txt")).unwrap();
let mut want: Vec<&str> = work_text.lines().collect();
want.remove(12);
assert_eq!(
reverted,
want.join("\n") + "\n",
"reverted at working line 12"
);
}
/// #365: review mode's checkout fetches `refs/pull/N/head` into a
/// detached sibling worktree, moves it on a re-run after a new push,
/// refuses a directory that is not its worktree, and says why leaving
/// must keep a checkout with edits or new commits in it.
#[test]
fn a_pull_request_head_checks_out_into_a_sibling_worktree() {
let tmp = tempfile::tempdir().unwrap();
let git = |dir: &Path, args: &[&str]| {
let out = Command::new("git")
.arg("-C")
.arg(dir)
.args(args)
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
};
let up = tmp.path().join("up");
std::fs::create_dir(&up).unwrap();
init_repo_with_commit(&up);
let pr_commit = |msg: &str| {
std::fs::write(up.join("pr.txt"), msg).unwrap();
git(&up, &["add", "."]);
git(&up, &["commit", "-q", "-m", msg]);
let sha = git(&up, &["rev-parse", "HEAD"]);
git(&up, &["update-ref", "refs/pull/7/head", &sha]);
sha
};
let first = pr_commit("one");
let app = tmp.path().join("app");
git(tmp.path(), &["clone", "-q", up.to_str().unwrap(), "app"]);
git(&app, &["config", "user.email", "a@b"]);
git(&app, &["config", "user.name", "a"]);
let path = pr_worktree_path(&app, 7).unwrap();
assert_eq!(path, tmp.path().join("app-pr-7"));
let remote = remote_for_slug(&app, "o/r");
assert_eq!(remote, "https://github.com/o/r.git", "no remote names o/r");
assert_eq!(
checkout_pr_worktree(&app, "origin", 7, &path, None),
Ok(PrWorktree {
oid: first.clone(),
created: true
})
);
assert_eq!(std::fs::read_to_string(path.join("pr.txt")).unwrap(), "one");
assert_eq!(pr_worktree_keep_reason(&path, &first), None);
// A new push moves the checkout review mode made, and only that:
// not knowing what it last checked out there, it refuses.
let second = pr_commit("two");
let err = checkout_pr_worktree(&app, "origin", 7, &path, None).unwrap_err();
assert!(err.contains("did not check out"), "{err}");
assert_eq!(
checkout_pr_worktree(&app, "origin", 7, &path, Some(&first)),
Ok(PrWorktree {
oid: second.clone(),
created: false
})
);
assert_eq!(std::fs::read_to_string(path.join("pr.txt")).unwrap(), "two");
// Edits and new commits are reasons to keep it.
std::fs::write(path.join("pr.txt"), "edited").unwrap();
assert!(pr_worktree_keep_reason(&path, &second).is_some());
git(&path, &["commit", "-q", "-am", "mine"]);
let why = pr_worktree_keep_reason(&path, &second).expect("a new commit keeps it");
assert!(why.contains("commits"), "{why}");
// ...and a refresh will not detach away from that commit either.
let mine = git(&path, &["rev-parse", "HEAD"]);
let third = pr_commit("three");
let err = checkout_pr_worktree(&app, "origin", 7, &path, Some(&second)).unwrap_err();
assert!(err.contains("did not check out"), "{err}");
assert_eq!(worktree_head(&path).as_deref(), Some(mine.as_str()));
assert_ne!(mine, third);
// Something else at the path is never touched.
let stray = pr_worktree_path(&app, 8).unwrap();
std::fs::create_dir(&stray).unwrap();
let second_pr = git(&up, &["rev-parse", "HEAD"]);
git(&up, &["update-ref", "refs/pull/8/head", &second_pr]);
let err = checkout_pr_worktree(&app, "origin", 8, &stray, None).unwrap_err();
assert!(err.contains("not a worktree"), "{err}");
}
#[test]
fn the_pull_request_remote_is_the_one_naming_the_repository() {
let tmp = tempfile::tempdir().unwrap();
init_repo_with_commit(tmp.path());
for (name, url) in [
("origin", "git@github.com:me/fork.git"),
("upstream", "https://github.com/Owner/Repo"),
] {
let _ = Command::new("git")
.arg("-C")
.arg(tmp.path())
.args(["remote", "add", name, url])
.status();
}
assert_eq!(remote_for_slug(tmp.path(), "owner/repo"), "upstream");
assert_eq!(remote_for_slug(tmp.path(), "me/fork"), "origin");
}
fn init_repo_with_commit(p: &Path) {
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["init", "-q", "-b", "main"])
.output();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.email", "a@b"])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["config", "user.name", "a"])
.status();
std::fs::write(p.join("seed.txt"), "one\ntwo\n").unwrap();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["add", "."])
.status();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["commit", "-m", "init", "--quiet"])
.status();
}
/// `git -C p <args>`, asserting it succeeded; its stdout, trimmed.
fn git_in(p: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
/// #1350: Undo Last Commit is `reset --soft HEAD~1`: HEAD goes back to
/// the parent, the commit's changes are staged, and its message comes
/// back for the box.
#[test]
fn undo_last_commit_moves_head_back_and_keeps_the_changes_staged() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let parent = git_in(p, &["rev-parse", "HEAD"]);
std::fs::write(p.join("b.txt"), "b\n").unwrap();
git_in(p, &["add", "b.txt"]);
git_in(p, &["commit", "-q", "-m", "Add b\n\nWith a body."]);
assert_eq!(undo_last_commit(p).as_deref(), Ok("Add b\n\nWith a body."));
assert_eq!(git_in(p, &["rev-parse", "HEAD"]), parent);
assert_eq!(git_in(p, &["diff", "--cached", "--name-only"]), "b.txt");
assert_eq!(std::fs::read_to_string(p.join("b.txt")).unwrap(), "b\n");
}
/// #1350: undoing the root commit leaves the branch unborn with every
/// file staged, as VS Code does with `update-ref -d HEAD`.
#[test]
fn undo_last_commit_on_the_root_commit_leaves_an_unborn_branch_staged() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
assert_eq!(undo_last_commit(p).as_deref(), Ok("init"));
let head = Command::new("git")
.arg("-C")
.arg(p)
.args(["rev-parse", "--verify", "-q", "HEAD"])
.output()
.unwrap();
assert!(!head.status.success(), "the branch is unborn");
assert_eq!(git_in(p, &["symbolic-ref", "--short", "HEAD"]), "main");
assert_eq!(git_in(p, &["diff", "--cached", "--name-only"]), "seed.txt");
}
/// #1350 negative: in the middle of a merge, rebase, cherry-pick or
/// revert the undo is refused, says why, and leaves HEAD alone.
#[test]
fn undo_last_commit_refuses_during_a_merge() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let head = git_in(p, &["rev-parse", "HEAD"]);
std::fs::write(p.join(".git/MERGE_HEAD"), format!("{head}\n")).unwrap();
let err = undo_last_commit(p).unwrap_err();
assert!(err.contains("merge"), "{err}");
assert_eq!(git_in(p, &["rev-parse", "HEAD"]), head);
}
/// #1350 negative: a repository with no commit has nothing to undo.
#[test]
fn undo_last_commit_with_no_commit_says_so() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
git_in(p, &["init", "-q", "-b", "main"]);
let err = undo_last_commit(p).unwrap_err();
assert!(err.contains("no commit"), "{err}");
}
/// #1582: a message makes an annotated tag; without one (or a blank
/// one) the tag is lightweight, as before.
#[test]
fn create_tag_with_a_message_is_annotated() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
create_tag(p, "v1", Some("Release 1")).unwrap();
assert_eq!(git_in(p, &["cat-file", "-t", "v1"]), "tag");
assert_eq!(
git_in(p, &["tag", "-l", "--format=%(contents:subject)", "v1"]),
"Release 1"
);
create_tag(p, "v0", None).unwrap();
create_tag(p, "v0b", Some(" ")).unwrap();
assert_eq!(git_in(p, &["cat-file", "-t", "v0"]), "commit");
assert_eq!(git_in(p, &["cat-file", "-t", "v0b"]), "commit");
}
/// #1582: Push Tags sends local tags to the remote, the remote's tags
/// list by name, and Delete Remote Tag removes one there only.
#[test]
fn tags_push_list_and_delete_on_the_remote() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let remote = TempDir::new().unwrap();
git_in(remote.path(), &["init", "-q", "--bare"]);
git_in(
p,
&["remote", "add", "origin", remote.path().to_str().unwrap()],
);
git_in(p, &["tag", "v1"]);
git_in(p, &["tag", "-a", "v2", "-m", "two"]);
assert_eq!(tag_remote(p).as_deref(), Ok("origin"));
assert_eq!(list_remote_tags(p, "origin"), Ok(Vec::new()));
push_tags(p, "origin").unwrap();
assert_eq!(
list_remote_tags(p, "origin"),
Ok(vec![String::from("v1"), String::from("v2")])
);
delete_remote_tag(p, "origin", "v1").unwrap();
assert_eq!(list_remote_tags(p, "origin"), Ok(vec![String::from("v2")]));
assert_eq!(git_in(p, &["tag"]), "v1\nv2", "local tags stay");
}
/// #1582, negative: no remote, or several with none of them origin and
/// no `remote.pushDefault`, is no remote to guess; `pushDefault` wins.
/// ls-remote's peeled and non-tag lines are not tags.
#[test]
fn the_tag_remote_is_never_a_guess() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
assert_eq!(
tag_remote(p),
Err(String::from("no remote to push tags to"))
);
git_in(p, &["remote", "add", "a", "/nowhere/a"]);
git_in(p, &["remote", "add", "b", "/nowhere/b"]);
assert!(tag_remote(p).unwrap_err().contains("remote.pushDefault"));
git_in(p, &["config", "remote.pushDefault", "b"]);
assert_eq!(tag_remote(p).as_deref(), Ok("b"));
assert_eq!(
parse_remote_tags(
"abc\trefs/tags/v1\ndef\trefs/heads/main\nfff\trefs/tags/v2^{}\nnoise"
),
["v1"]
);
}
/// #1350: whether HEAD is already on its upstream, so the app can warn
/// that undoing it means a force push later. No upstream is not pushed.
#[test]
fn head_on_upstream_follows_the_tracking_branch() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
assert!(!head_is_on_upstream(p), "no upstream yet");
let remote = TempDir::new().unwrap();
git_in(remote.path(), &["init", "-q", "--bare"]);
git_in(
p,
&["remote", "add", "origin", remote.path().to_str().unwrap()],
);
git_in(p, &["push", "-q", "-u", "origin", "main"]);
assert!(head_is_on_upstream(p), "pushed");
std::fs::write(p.join("c.txt"), "c\n").unwrap();
git_in(p, &["add", "c.txt"]);
git_in(p, &["commit", "-q", "-m", "local only"]);
assert!(!head_is_on_upstream(p), "a local commit is not pushed");
git_in(p, &["update-ref", "-d", "refs/remotes/origin/main"]);
assert!(
head_is_on_upstream(p),
"an upstream whose tracking ref is missing cannot be ruled out"
);
}
/// #1350 negative: in a shallow checkout HEAD~1 is missing but the
/// commit has a parent; deleting the ref would drop the branch tip.
#[test]
fn undo_last_commit_refuses_at_a_shallow_boundary() {
let src = TempDir::new().unwrap();
init_repo_with_commit(src.path());
std::fs::write(src.path().join("b.txt"), "b\n").unwrap();
git_in(src.path(), &["add", "b.txt"]);
git_in(src.path(), &["commit", "-q", "-m", "Add b"]);
let tmp = TempDir::new().unwrap();
let p = tmp.path().join("shallow");
let url = format!("file://{}", src.path().display());
git_in(
tmp.path(),
&["clone", "-q", "--depth=1", &url, p.to_str().unwrap()],
);
let head = git_in(&p, &["rev-parse", "HEAD"]);
let err = undo_last_commit(&p).unwrap_err();
assert!(err.contains("shallow"), "{err}");
assert_eq!(git_in(&p, &["rev-parse", "HEAD"]), head);
}
/// #1350 negative: a detached HEAD on a root commit is refused, since
/// `update-ref -d HEAD` would delete `.git/HEAD` itself.
#[test]
fn undo_last_commit_refuses_a_detached_root_commit() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
git_in(p, &["checkout", "-q", "--detach"]);
let head = git_in(p, &["rev-parse", "HEAD"]);
let err = undo_last_commit(p).unwrap_err();
assert!(err.contains("detached"), "{err}");
assert!(p.join(".git/HEAD").exists());
assert_eq!(git_in(p, &["rev-parse", "HEAD"]), head);
}
#[test]
fn repo_toplevel_resolves_from_a_subdirectory_and_refuses_outside_a_repo() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let sub = p.join("crates").join("foo");
std::fs::create_dir_all(&sub).unwrap();
let top = repo_toplevel(&sub).expect("a repo subdirectory resolves to its toplevel");
assert_eq!(
top.canonicalize().unwrap(),
p.canonicalize().unwrap(),
"the toplevel is the repo root, not the subdirectory"
);
let outside = TempDir::new().unwrap();
assert_eq!(
repo_toplevel(outside.path()),
None,
"outside a repo there is no toplevel"
);
}
/// #1513: each porcelain status maps to its Explorer letter, a partially
/// staged file keeps its strongest status, and each folder above a
/// change takes the strongest status beneath it, whatever order the
/// lines come in. The root itself is never decorated.
#[test]
fn decorations_carry_each_status_and_roll_up_to_folders() {
use GitDecoration as D;
let root = Path::new("/w");
let porcelain = b" M a.py\0?? c.py\0A d.py\0R new.py\0old.py\0UU x.py\0 D gone.py\0AM part.py\0?? pkg/new.py\0 M pkg/old.py\0?? pkg/deep/n.py\0 M lib/x/y.py\0?? lib/z.py\0";
let got = parse_decorations(root, "", porcelain);
let at = |p: &str| got.get(&root.join(p)).copied();
assert_eq!(at("a.py"), Some(D::Modified));
assert_eq!(at("c.py"), Some(D::Untracked));
assert_eq!(at("d.py"), Some(D::Added));
assert_eq!(at("new.py"), Some(D::Renamed));
assert_eq!(at("old.py"), None, "a rename decorates its destination");
assert_eq!(at("x.py"), Some(D::Conflicted));
assert_eq!(at("gone.py"), Some(D::Deleted));
assert_eq!(
at("part.py"),
Some(D::Modified),
"AM: the strongest of the two"
);
assert_eq!(
at("pkg"),
Some(D::Modified),
"untracked first, modified wins"
);
assert_eq!(at("pkg/deep"), Some(D::Untracked));
assert_eq!(
at("lib"),
Some(D::Modified),
"modified first, untracked does not demote"
);
assert_eq!(at("lib/x"), Some(D::Modified));
assert_eq!(got.get(root), None, "the root row is never decorated");
let letters: String = [
D::Untracked,
D::Added,
D::Renamed,
D::Deleted,
D::Modified,
D::Conflicted,
]
.map(GitDecoration::letter)
.iter()
.collect();
assert_eq!(letters, "UARDM!");
}
/// #1513 negatives: a workspace root inside the repository keeps only
/// its own changes (porcelain paths are toplevel-relative), and a clean
/// tree has no decorations.
#[test]
fn decorations_stay_inside_the_workspace_root() {
let root = Path::new("/repo/app");
let got = parse_decorations(
root,
"app/\n",
b" M app/src/x.py\0 M other/y.py\0?? apple.py\0",
);
assert_eq!(
got.keys().cloned().collect::<HashSet<_>>(),
HashSet::from([root.join("src/x.py"), root.join("src")])
);
assert!(parse_decorations(Path::new("/w"), "", b"").is_empty());
}
/// #1513: a decoration keys the exact path bytes, so a filename that is
/// not UTF-8 and a rename whose source contains ` -> ` still mark the
/// file the tree holds.
#[cfg(unix)]
#[test]
fn decorations_keep_exact_path_bytes() {
use std::ffi::OsStr;
use std::os::unix::ffi::OsStrExt;
let root = Path::new("/w");
let got = parse_decorations(
root,
"",
b" M bad\xff.py\0R new.py\0a -> b.py\0?? sp ace.py\0",
);
assert_eq!(
got.get(&root.join(OsStr::from_bytes(b"bad\xff.py"))),
Some(&GitDecoration::Modified)
);
assert_eq!(got.get(&root.join("new.py")), Some(&GitDecoration::Renamed));
assert_eq!(
got.get(&root.join("sp ace.py")),
Some(&GitDecoration::Untracked)
);
assert_eq!(got.len(), 3, "the rename source is not decorated: {got:?}");
}
/// #1513, end to end over the issue's repro: modified, staged and
/// untracked files are decorated from a real `git status`, and the
/// unchanged file is not.
#[test]
fn query_decorates_changed_files_and_their_folders() {
use GitDecoration as D;
let tmp = TempDir::new().unwrap();
let p = tmp.path();
std::fs::create_dir_all(p.join("sub")).unwrap();
for f in ["a.py", "b.py", "sub/e.py"] {
std::fs::write(p.join(f), "x = 1\n").unwrap();
}
init_repo_with_commit(p);
std::fs::write(p.join("a.py"), "x = 1\ny = 2\n").unwrap();
std::fs::write(p.join("sub/e.py"), "x = 1\ny = 2\n").unwrap();
std::fs::write(p.join("c.py"), "new = 1\n").unwrap();
std::fs::write(p.join("d.py"), "staged = 1\n").unwrap();
Command::new("git")
.arg("-C")
.arg(p)
.args(["add", "d.py"])
.status()
.unwrap();
let st = query(p);
let at = |f: &str| st.decorations.get(&p.join(f)).copied();
assert_eq!(at("a.py"), Some(D::Modified));
assert_eq!(at("sub/e.py"), Some(D::Modified));
assert_eq!(at("sub"), Some(D::Modified));
assert_eq!(at("c.py"), Some(D::Untracked));
assert_eq!(at("d.py"), Some(D::Added));
assert_eq!(at("b.py"), None, "an unchanged file is not decorated");
}
/// A new folder lists each of its files (#1279), not one `dir/` row
/// that opens nothing and has no line count.
#[test]
fn a_new_folder_lists_each_of_its_files() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::create_dir_all(p.join("src/billing")).unwrap();
std::fs::write(
p.join("src/billing/invoice.py"),
"def invoice(total):\n return round(total * 1.2, 2)\n",
)
.unwrap();
std::fs::write(p.join("src/billing/tax.py"), "RATE = 0.2\n").unwrap();
let entries = query_changes(p);
let untracked: Vec<(&str, usize)> = entries
.iter()
.filter(|e| e.kind == ChangeKind::Untracked)
.map(|e| (e.path.as_str(), e.additions))
.collect();
assert_eq!(
untracked,
[("src/billing/invoice.py", 2), ("src/billing/tax.py", 1)]
);
assert_eq!(query(p).changed_count, 2, "the badge counts files too");
}
#[test]
fn an_ignored_folder_still_lists_nothing() {
// Negative: `-uall` lists untracked files, never ignored ones.
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join(".gitignore"), "build/\n").unwrap();
sh_git(p, &["add", ".gitignore"]);
sh_git(p, &["commit", "-qm", "ignore"]);
std::fs::create_dir_all(p.join("build/out")).unwrap();
std::fs::write(p.join("build/out/a.o"), "x").unwrap();
assert!(query_changes(p).is_empty());
assert_eq!(query(p).changed_count, 0);
}
/// git's prepared message for a conflicted merge (#1282), comments
/// dropped, and a squash's when there is no merge message.
#[test]
fn a_merge_in_progress_carries_gits_prepared_message() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
assert_eq!(query(p).prepared_message, None, "no merge, no message");
std::fs::write(
p.join(".git/SQUASH_MSG"),
"Squashed commit of the following:\n\ncommit abc\n",
)
.unwrap();
assert_eq!(
query(p).prepared_message.as_deref(),
Some("Squashed commit of the following:\n\ncommit abc")
);
std::fs::write(
p.join(".git/MERGE_MSG"),
"Merge branch 'other'\n\n# Conflicts:\n#\tf.txt\n",
)
.unwrap();
assert_eq!(
query(p).prepared_message.as_deref(),
Some("Merge branch 'other'")
);
}
/// #1620: `commit.template` fills the message, comments dropped, read
/// from the repository's top level even when croft is in a subfolder;
/// a merge's own message wins over it.
#[test]
fn the_commit_template_is_the_message_when_nothing_is_prepared() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(
p.join(".gitmessage"),
"PROJ-: \n\nWhy:\n\n# Subject: PROJ-<ticket>: <summary>, at most 50 characters\n",
)
.unwrap();
run_git(p, &["config", "commit.template", ".gitmessage"]).unwrap();
assert_eq!(query(p).prepared_message.as_deref(), Some("PROJ-:\n\nWhy:"));
std::fs::create_dir(p.join("sub")).unwrap();
assert_eq!(
query(&p.join("sub")).prepared_message.as_deref(),
Some("PROJ-:\n\nWhy:"),
"relative to the top level, not the folder croft is in"
);
std::fs::write(p.join(".git/MERGE_MSG"), "Merge branch 'other'\n").unwrap();
assert_eq!(
query(p).prepared_message.as_deref(),
Some("Merge branch 'other'")
);
}
/// #1620: with `core.commentChar` set, lines starting with it are the
/// comments, and `#` lines are message text.
#[test]
fn the_configured_comment_char_marks_template_comments() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join(".gitmessage"), "#42: \n; helper text\n").unwrap();
run_git(p, &["config", "commit.template", ".gitmessage"]).unwrap();
run_git(p, &["config", "core.commentChar", ";"]).unwrap();
assert_eq!(query(p).prepared_message.as_deref(), Some("#42:"));
}
/// Negative (#1620): a template that names no readable file, or holds
/// only comments, is no message; an absolute path is read as named.
#[test]
fn a_missing_or_comment_only_template_is_no_message() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
run_git(p, &["config", "commit.template", "nope.txt"]).unwrap();
assert_eq!(query(p).prepared_message, None);
let only = tmp.path().join("only-comments.txt");
std::fs::write(&only, "# write something\n\n").unwrap();
run_git(p, &["config", "commit.template", only.to_str().unwrap()]).unwrap();
assert_eq!(query(p).prepared_message, None);
let abs = tmp.path().join("abs.txt");
std::fs::write(&abs, "Ticket: \n").unwrap();
run_git(p, &["config", "commit.template", abs.to_str().unwrap()]).unwrap();
assert_eq!(query(p).prepared_message.as_deref(), Some("Ticket:"));
}
/// #1620: under `core.commentChar=auto` git picks a marker no line of
/// the template starts with, so every line of it is the message.
#[test]
fn under_an_auto_comment_char_every_template_line_is_kept() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join(".gitmessage"), "#42: \n; helper text\n").unwrap();
run_git(p, &["config", "commit.template", ".gitmessage"]).unwrap();
run_git(p, &["config", "core.commentChar", "auto"]).unwrap();
assert_eq!(
query(p).prepared_message.as_deref(),
Some("#42:\n; helper text")
);
}
#[test]
fn a_prepared_message_of_only_comments_is_none() {
// Negative: nothing left after stripping is no message.
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join(".git/MERGE_MSG"), "# Conflicts:\n#\tf.txt\n\n").unwrap();
assert_eq!(query(p).prepared_message, None);
}
#[test]
fn query_from_a_subdir_carries_the_repo_root_and_counts_untracked_lines() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let sub = p.join("crates").join("foo");
std::fs::create_dir_all(&sub).unwrap();
// An untracked file at the TOPLEVEL: porcelain reports it
// toplevel-relative, so a join against the subdir workspace root
// reads a nonexistent path and silently counts 0 lines.
std::fs::write(p.join("notes.txt"), "one\ntwo\nthree\n").unwrap();
let status = query(&sub);
assert!(status.in_repo, "a subdir of a repo is inside the repo");
assert_eq!(
status
.repo_root
.as_ref()
.expect("the status carries the discovered toplevel")
.canonicalize()
.unwrap(),
p.canonicalize().unwrap(),
);
let entries = query_changes(&sub);
let notes = entries
.iter()
.find(|e| e.path == "notes.txt")
.expect("porcelain reports the toplevel file from a subdir workspace");
assert_eq!(
notes.additions, 3,
"untracked line counts must join the porcelain path against the TOPLEVEL"
);
}
/// The scrubber's history is the CURRENT BRANCH, and index 0 is HEAD.
///
/// `commit_graph` logs `--branches --tags HEAD` because it draws the
/// repo-wide graph. Feeding a scrubber from it means that with any other
/// branch present, index 0 is whatever topological order put first —
/// demonstrated here with a sibling branch carrying a future committer
/// date, which sorts ahead of HEAD. Stepping back from the working tree
/// then lands on a commit the current branch does not contain (#371).
/// A lane's branch name and directory come from one slug, and both are
/// safe to hand to git and to the filesystem (#348).
#[test]
fn a_lane_name_becomes_a_safe_branch_and_directory() {
let plan = |name: &str| WorktreeLane::plan(Path::new("/repos/croft"), name);
let p = plan("fix the parser").expect("an ordinary name");
assert_eq!(p.branch, "agent/fix-the-parser");
assert_eq!(p.path, PathBuf::from("/repos/croft-fix-the-parser"));
// The directory is a SIBLING of the repo, never inside it: a
// worktree nested in its own repo is a working tree git will then
// try to track, and the Explorer would show the lane inside the
// root it was cut from.
assert!(
!p.path.starts_with("/repos/croft/"),
"a lane must not nest inside its own repo: {}",
p.path.display()
);
// Shapes git refuses in a ref name, or the shell would mangle:
// every one collapses to the separator rather than reaching git.
for name in [
"a..b", "a b", "a~b", "a^b", "a:b", "a?b", "a*b", "a[b", "a\\b",
] {
let p = plan(name).unwrap_or_else(|| panic!("{name} should still plan"));
assert!(
!p.branch.contains("..")
&& !p.branch.contains(' ')
&& !p.branch.contains(['~', '^', ':', '?', '*', '[', '\\']),
"{name} produced an unsafe branch: {}",
p.branch
);
}
// A very long name is capped: the slug becomes a directory name as
// well as a branch, and a component past ~255 bytes fails at
// `mkdir` with "File name too long" — the user would see that
// instead of anything about lanes.
let long = plan(&"parser".repeat(50)).expect("a long name still plans");
let dir = long
.path
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
assert!(dir.len() < 100, "directory name is {} bytes", dir.len());
assert!(!long.branch.ends_with('-'), "branch: {}", long.branch);
// A name with nothing usable in it is REFUSED rather than silently
// becoming `agent/` — a branch named after nothing is worse than
// being told to pick a name.
for empty in ["", " ", "///", "..."] {
assert!(plan(empty).is_none(), "{empty:?} must not yield a lane");
}
}
/// A lane with uncommitted work refuses to be removed, and says so.
///
/// This is the safety rule the issue names, and it is the one place
/// where being wrong destroys work rather than merely annoying someone:
/// `git worktree remove` on a dirty tree discards it.
#[test]
fn a_dirty_lane_refuses_removal_and_a_clean_one_allows_it() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
// Inside the TempDir's own parent would collide with a leftover from
// an earlier run; a second TempDir gives this test a private
// directory that is still a sibling of the repo.
let side = TempDir::new().unwrap();
let lane = side.path().join("lane-clean");
let git = |args: &[&str]| {
let _ = Command::new("git").args(["-C"]).arg(p).args(args).status();
};
git(&[
"worktree",
"add",
"-q",
"-b",
"lane",
lane.to_str().unwrap(),
]);
assert!(lane.is_dir(), "staging: the worktree exists");
// Clean: removal is allowed.
assert_eq!(lane_removal_block(&lane), None, "a clean lane may go");
// Dirty: refused, and the reason names the tree.
std::fs::write(lane.join("scratch.txt"), "unsaved").unwrap();
let why = lane_removal_block(&lane).expect("a dirty lane must be refused");
assert!(
why.contains("uncommitted"),
"the refusal must say why: {why}"
);
// IGNORED files refuse too. Plain `--porcelain` omits them, so the
// check reported this tree clean while `git worktree remove`
// destroyed a `.env` — measured. An agent lane is exactly where an
// uncommitted local config or an expensive `node_modules` lives.
// The dirty file from above goes first, so this case starts clean
// and the only thing the check can be reacting to is the ignored one.
std::fs::remove_file(lane.join("scratch.txt")).unwrap();
std::fs::write(lane.join(".gitignore"), "*.local\n").unwrap();
let lane_git0 = |args: &[&str]| {
let _ = Command::new("git")
.args(["-C"])
.arg(&lane)
.args(args)
.status();
};
lane_git0(&["add", "-A"]);
lane_git0(&["commit", "-q", "-m", "ignore"]);
std::fs::write(lane.join("secrets.local"), "TOKEN=1").unwrap();
assert!(
plain_status_is_clean(&lane),
"control: plain --porcelain sees nothing, which is the trap"
);
let why = lane_removal_block(&lane).expect("ignored files must refuse");
assert!(
why.contains("ignored"),
"the refusal must name what it is protecting: {why}"
);
std::fs::remove_file(lane.join("secrets.local")).unwrap();
// Committing it makes the lane clean again.
let lane_git = |args: &[&str]| {
let _ = Command::new("git")
.args(["-C"])
.arg(&lane)
.args(args)
.status();
};
lane_git(&["add", "-A"]);
lane_git(&["commit", "-q", "-m", "keep"]);
assert_eq!(
lane_removal_block(&lane),
None,
"a committed lane is clean again"
);
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["worktree", "remove", "--force", lane.to_str().unwrap()])
.status();
// A path git CANNOT report on is refused, not assumed clean. This is
// the branch where being wrong destroys work: `git worktree remove`
// discards a dirty tree, so an unreadable status must fail closed.
// Without this case the whole not-a-worktree arm could be replaced
// by `return None` and every other assertion here would still pass.
let outside = TempDir::new().unwrap();
let why = lane_removal_block(outside.path())
.expect("a directory that is not a worktree must be refused");
assert!(
why.contains("worktree") || why.contains("could not run"),
"the refusal must say what went wrong: {why}"
);
// And a path that does not exist at all.
let gone = outside.path().join("no-such-lane");
assert!(
lane_removal_block(&gone).is_some(),
"a missing path must be refused rather than reported clean"
);
}
/// The scrubber's history is the CURRENT BRANCH, and index 0 is HEAD.
///
/// `commit_graph` logs `--branches --tags HEAD` because it draws the
/// repo-wide graph. Feeding a scrubber from it means that with any other
/// branch present, index 0 is whatever topological order put first —
/// demonstrated here with a sibling branch carrying a future committer
/// date, which sorts ahead of HEAD. Stepping back from the working tree
/// then lands on a commit the current branch does not contain (#371).
#[test]
fn branch_history_is_the_current_branch_with_head_first() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let git = |args: &[&str]| {
let _ = Command::new("git").args(["-C"]).arg(p).args(args).status();
};
// A sibling branch whose commit dates FUTURE, so any date- or
// topo-ordered listing across all branches puts it first.
git(&["checkout", "-q", "-b", "sibling"]);
std::fs::write(p.join("sibling.txt"), "s").unwrap();
git(&["add", "-A"]);
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["commit", "-q", "-m", "sibling-future"])
.env("GIT_COMMITTER_DATE", "2038-01-01T00:00:00")
.env("GIT_AUTHOR_DATE", "2038-01-01T00:00:00")
.status();
// Back to the original branch.
git(&["checkout", "-q", "-"]);
let head = Command::new("git")
.args(["-C"])
.arg(p)
.args(["rev-parse", "HEAD"])
.output()
.expect("rev-parse");
let head = String::from_utf8_lossy(&head.stdout).trim().to_string();
let hist = branch_history(p, 50);
assert!(!hist.is_empty(), "the branch has commits");
assert_eq!(
hist[0].hash, head,
"index 0 must be HEAD, not whatever sorted first across branches"
);
assert!(
hist.iter().all(|c| c.summary != "sibling-future"),
"a sibling branch's commit leaked into the branch history: {:?}",
hist.iter().map(|c| &c.summary).collect::<Vec<_>>()
);
// The positive control: the graph DOES include it, so the assertion
// above is about the ref set rather than about the repo being empty.
let graph = commit_graph(p, 50);
assert!(
graph.iter().any(|c| c.summary == "sibling-future"),
"control: commit_graph should see every branch"
);
}
/// #371: a file added in HEAD is absent from HEAD~1's tree and present
/// in HEAD's — the positive control, so an absence is about the commit
/// rather than about the listing being empty. Directories are listed,
/// and a workspace in a repo subdirectory gets paths joined onto itself.
#[test]
fn tree_paths_lists_a_commits_files_and_folders_under_the_root() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let git = |args: &[&str]| {
let _ = Command::new("git").args(["-C"]).arg(p).args(args).status();
};
std::fs::create_dir_all(p.join("sub/deep")).unwrap();
std::fs::write(p.join("sub/deep/new.txt"), "n").unwrap();
git(&["add", "-A"]);
git(&["commit", "-q", "-m", "add new"]);
let before = tree_paths(p, "HEAD~1").expect("HEAD~1 lists");
assert!(before.contains(&p.join("seed.txt")));
assert!(!before.contains(&p.join("sub/deep/new.txt")));
assert!(!before.contains(&p.join("sub")));
let head = tree_paths(p, "HEAD").expect("HEAD lists");
assert!(head.contains(&p.join("sub/deep/new.txt")));
assert!(head.contains(&p.join("sub")), "folders are listed too");
assert!(head.contains(&p.join("sub/deep")));
// Opened in a subdirectory: only its entries, joined onto it.
let sub = p.join("sub");
let nested = tree_paths(&sub, "HEAD").expect("subdir lists");
assert!(nested.contains(&sub.join("deep/new.txt")));
assert!(!nested.paths.iter().any(|q| q.ends_with("seed.txt")));
assert!(tree_paths(p, "no-such-rev").is_none());
// A submodule's contents are never listed, so they count as present.
let head_sha = String::from_utf8(
Command::new("git")
.arg("-C")
.arg(p)
.args(["rev-parse", "HEAD"])
.output()
.unwrap()
.stdout,
)
.unwrap();
let cacheinfo = format!("160000,{},vendored", head_sha.trim());
git(&["update-index", "--add", "--cacheinfo", &cacheinfo]);
git(&["commit", "-q", "-m", "add submodule"]);
let with_sub = tree_paths(p, "HEAD").expect("HEAD lists");
assert_eq!(with_sub.submodules, vec![p.join("vendored")]);
assert!(with_sub.contains(&p.join("vendored/src/lib.rs")));
assert!(!with_sub.contains(&p.join("vendoredx")));
}
/// What plain `--porcelain` (no `--ignored`) reports, as the positive
/// control for the ignored-file case: it must see NOTHING there, or the
/// assertion that `lane_removal_block` catches it proves nothing.
fn plain_status_is_clean(lane: &Path) -> bool {
let out = Command::new("git")
.args(["-C"])
.arg(lane)
.args(["status", "--porcelain"])
.output()
.expect("git status");
String::from_utf8_lossy(&out.stdout).trim().is_empty()
}
/// A failed creation leaves the base untouched (#348).
///
/// The read has to happen BEFORE the command, while HEAD is still the
/// fork point - but writing it before the command succeeds records a
/// base for a lane that does not exist, which a retry would then carry.
/// Driven through the real duplicate-name refusal rather than a mocked
/// failure, so it fails the way callers actually see it.
#[test]
fn a_failed_lane_creation_leaves_the_base_unset() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
run_git_mut(p, &["checkout", "-b", "release-9"]).expect("branch");
let mut first = WorktreeLane::plan(p, "parser work").expect("planned");
add_worktree_lane(p, &mut first).expect("the first lane is created");
assert_eq!(first.base.as_deref(), Some("release-9"), "precondition");
// Same name: git refuses, so nothing was created to have a base.
let mut second = WorktreeLane::plan(p, "parser work").expect("planned");
assert!(add_worktree_lane(p, &mut second).is_err(), "precondition");
assert_eq!(
second.base, None,
"a lane git refused to create records no base"
);
remove_worktree_lane(&first.path).expect("cleanup");
}
/// The base is recorded at creation and is not derivable afterwards
/// (#348). Asserts against a branch the fixture NAMES, so a bug that
/// wrote a constant, or the lane's own branch, fails here rather than
/// looking plausible.
#[test]
fn a_lane_records_the_branch_it_was_cut_from() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
// A NON-default name, so passing "main"/"master" through cannot pass.
run_git_mut(p, &["checkout", "-b", "release-42"]).expect("branch");
let mut lane = WorktreeLane::plan(p, "parser work").expect("planned");
assert_eq!(lane.base, None, "plan is pure and reads no git");
add_worktree_lane(p, &mut lane).expect("git worktree add should succeed");
assert_eq!(
lane.base.as_deref(),
Some("release-42"),
"the lane records the branch HEAD was on, not a default"
);
assert_ne!(
lane.base.as_deref(),
Some(lane.branch.as_str()),
"the base is what it forked FROM, never the lane's own branch"
);
remove_worktree_lane(&lane.path).expect("cleanup");
}
/// A lane round-trips through the real git commands (#348).
///
/// Driven through `add_worktree_lane` / `remove_worktree_lane` rather
/// than asserting on the strings they would build: the argument order
/// and the working directory each command runs in are the parts that go
/// wrong, and only running them can show that.
#[test]
fn a_lane_is_created_and_removed_through_git() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let mut lane = WorktreeLane::plan(p, "parser work").expect("planned");
assert!(lane.path.starts_with(p.parent().unwrap()), "a sibling");
add_worktree_lane(p, &mut lane).expect("git worktree add should succeed");
assert!(lane.path.is_dir(), "the lane directory exists");
// The branch really was created, and the lane is on it.
let out = Command::new("git")
.args(["-C"])
.arg(&lane.path)
.args(["rev-parse", "--abbrev-ref", "HEAD"])
.output()
.expect("rev-parse");
assert_eq!(
String::from_utf8_lossy(&out.stdout).trim(),
lane.branch,
"the lane must be on its own branch"
);
// A second lane of the same name is refused by git rather than
// silently reusing the branch.
assert!(
add_worktree_lane(p, &mut lane).is_err(),
"a duplicate lane must fail rather than adopt the existing one"
);
// A LOCKED worktree reports a clean status — `lane_removal_block`
// asks "is there uncommitted work", which is a different question
// from "will git remove this" — and git then refuses. Pinned
// because it is why the caller runs git BEFORE dropping the
// workspace folder: the other order leaves the lane gone from the
// workspace and the directory still on disk.
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["worktree", "lock", lane.path.to_str().unwrap()])
.status();
assert_eq!(
lane_removal_block(&lane.path),
None,
"a locked-but-clean lane has no uncommitted work"
);
assert!(
remove_worktree_lane(&lane.path).is_err(),
"git must refuse a locked worktree, and the caller must hear it"
);
assert!(lane.path.is_dir(), "the refusal left the lane in place");
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["worktree", "unlock", lane.path.to_str().unwrap()])
.status();
remove_worktree_lane(&lane.path).expect("a clean lane removes");
assert!(!lane.path.exists(), "the lane directory is gone");
}
#[test]
fn diff_staged_returns_only_indexed_changes() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nthree\n").unwrap();
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["add", "seed.txt"])
.status();
std::fs::write(p.join("untracked.txt"), "z").unwrap();
let out = diff_staged(p).expect("git diff --staged should succeed");
assert!(
out.contains("+three"),
"staged diff must include the +three line that was indexed: {out}"
);
assert!(
!out.contains("untracked.txt"),
"untracked file must NOT appear in staged diff: {out}"
);
}
#[test]
fn default_branch_resolves_main_when_only_local() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let b = default_branch(p).expect("default branch must resolve");
assert_eq!(b, "main", "freshly init -b main repo must resolve to main");
}
/// #1447 fixture: a repo with `app.py` committed and an edit staged.
fn repo_with_a_staged_edit() -> (TempDir, String) {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let head = sh_git(p, &["rev-parse", "HEAD"]);
std::fs::write(p.join("seed.txt"), "one\nTWO\n").unwrap();
sh_git(p, &["add", "seed.txt"]);
(tmp, head.trim().to_string())
}
/// #1447: `color.ui = always` (here in the repo's own config, which
/// git reads the same way as `~/.gitconfig`) never reaches the text
/// croft parses as a patch.
#[test]
fn git_diff_views_ignore_a_color_always_config() {
let (tmp, head) = repo_with_a_staged_edit();
let p = tmp.path();
sh_git(p, &["config", "color.ui", "always"]);
sh_git(p, &["config", "color.diff", "always"]);
let coloured = sh_git(p, &["diff", "--staged"]);
assert!(
coloured.contains('\x1b'),
"the config colours git's own output: {coloured:?}"
);
let staged = diff_staged(p).unwrap();
assert!(staged.starts_with("diff --git"), "{staged:?}");
assert!(!staged.contains('\x1b'), "{staged:?}");
assert!(staged.contains("\n+TWO\n"), "{staged:?}");
let previous = diff_against_branch(p, &head).unwrap();
assert!(!previous.contains('\x1b'), "{previous:?}");
sh_git(p, &["commit", "-qm", "two"]);
let commit = show_commit(p, "HEAD").unwrap();
assert!(commit.starts_with("commit "), "{commit:?}");
assert!(!commit.contains('\x1b'), "{commit:?}");
let file = show_commit_file_diff(p, "HEAD", "seed.txt").unwrap();
assert!(!file.contains('\x1b'), "{file:?}");
assert!(!diff_previous_commit(p).unwrap().contains('\x1b'));
}
/// #1447: a `diff.external` tool (difftastic's recommended setup) does
/// not replace the patch with its own output.
#[test]
fn git_diff_views_ignore_an_external_diff_tool() {
let (tmp, _) = repo_with_a_staged_edit();
let p = tmp.path();
let tool = p.join("external-diff.sh");
std::fs::write(&tool, "#!/bin/sh\necho EXTERNAL\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap();
}
sh_git(p, &["config", "diff.external", tool.to_str().unwrap()]);
assert!(sh_git(p, &["diff", "--staged"]).contains("EXTERNAL"));
let staged = diff_staged(p).unwrap();
assert!(staged.starts_with("diff --git"), "{staged:?}");
assert!(!staged.contains("EXTERNAL"), "{staged:?}");
}
/// #1447 negative: with git's default colour settings the text is
/// exactly what plain `git diff` / `git show` print.
#[test]
fn git_diff_views_are_unchanged_without_colour_config() {
let (tmp, _) = repo_with_a_staged_edit();
let p = tmp.path();
assert_eq!(diff_staged(p).unwrap(), sh_git(p, &["diff", "--staged"]));
sh_git(p, &["commit", "-qm", "two"]);
assert_eq!(
show_commit(p, "HEAD").unwrap(),
sh_git(p, &["show", "--stat", "--patch", "HEAD"])
);
}
#[test]
fn diff_against_branch_shows_working_tree_versus_branch() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nthree\n").unwrap();
let out = diff_against_branch(p, "main").expect("diff main should succeed");
assert!(
out.contains("+three"),
"diff vs branch must include the new +three line: {out}"
);
}
/// #1444 fixture: `feature` branched from `main` and added
/// `feature.py`; `main` then got a teammate's `teammate.py` and an
/// `app.py` change. HEAD is `feature`.
fn branch_behind_a_moved_main() -> TempDir {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let git = |args: &[&str]| {
let o = Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.output()
.unwrap();
assert!(
o.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&o.stderr)
);
};
git(&["init", "-q", "-b", "main"]);
git(&["config", "user.email", "a@b"]);
git(&["config", "user.name", "a"]);
std::fs::write(p.join("app.py"), "def a():\n return 1\n").unwrap();
git(&["add", "."]);
git(&["commit", "-qm", "init"]);
git(&["checkout", "-qb", "feature"]);
std::fs::write(p.join("feature.py"), "def feature():\n return 2\n").unwrap();
git(&["add", "."]);
git(&["commit", "-qm", "add feature"]);
git(&["checkout", "-q", "main"]);
std::fs::write(p.join("teammate.py"), "def teammate():\n return 3\n").unwrap();
std::fs::write(p.join("app.py"), "def a():\n return 10\n").unwrap();
git(&["add", "."]);
git(&["commit", "-qm", "teammate work"]);
git(&["checkout", "-q", "feature"]);
tmp
}
/// #1444: the view holds the branch's own changes only, as a pull
/// request diff does, not main's later work shown in reverse.
#[test]
fn diff_against_branch_starts_from_the_merge_base() {
let tmp = branch_behind_a_moved_main();
let out = diff_against_branch(tmp.path(), "main").unwrap();
assert!(out.contains("+++ b/feature.py"), "{out}");
assert!(!out.contains("teammate.py"), "{out}");
assert!(!out.contains("app.py"), "{out}");
}
/// #1444: uncommitted work on the branch is still in the view.
#[test]
fn diff_against_branch_keeps_uncommitted_edits() {
let tmp = branch_behind_a_moved_main();
std::fs::write(
tmp.path().join("feature.py"),
"def feature():\n return 22\n",
)
.unwrap();
let out = diff_against_branch(tmp.path(), "main").unwrap();
assert!(out.contains("+ return 22"), "{out}");
assert!(!out.contains("teammate.py"), "{out}");
}
/// #1444 negative: when main has not moved, the view is exactly
/// `git diff main`, as before.
#[test]
fn diff_against_an_unmoved_branch_is_the_plain_diff() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let git = |args: &[&str]| {
Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.output()
.unwrap()
};
git(&["checkout", "-qb", "feature"]);
std::fs::write(p.join("seed.txt"), "one\ntwo\nthree\n").unwrap();
git(&["commit", "-qam", "three"]);
std::fs::write(p.join("new.txt"), "x\n").unwrap();
git(&["add", "new.txt"]);
let plain = String::from_utf8(git(&["diff", "main"]).stdout).unwrap();
assert!(plain.contains("+three"), "{plain}");
assert_eq!(diff_against_branch(p, "main").unwrap(), plain);
}
/// #1444 negative: with no shared history there is no merge base, and
/// the view falls back to the tip diff instead of failing.
#[test]
fn diff_against_an_unrelated_branch_falls_back_to_its_tip() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
let git = |args: &[&str]| {
Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.output()
.unwrap()
};
git(&["checkout", "-q", "--orphan", "other"]);
git(&["rm", "-rfq", "."]);
std::fs::write(p.join("other.txt"), "other\n").unwrap();
git(&["add", "."]);
git(&["commit", "-qm", "other root"]);
assert_eq!(merge_base(p, "main"), None);
let plain = String::from_utf8(git(&["diff", "main"]).stdout).unwrap();
assert!(plain.contains("seed.txt"), "{plain}");
assert_eq!(diff_against_branch(p, "main").unwrap(), plain);
}
/// #1444 negative: a branch git does not know still errors, as before.
#[test]
fn diff_against_an_unknown_branch_still_errors() {
let tmp = TempDir::new().unwrap();
init_repo_with_commit(tmp.path());
assert!(diff_against_branch(tmp.path(), "no-such-branch").is_err());
}
#[test]
fn a_commit_from_before_a_rename_shows_its_diff_under_the_old_name() {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
let git = |args: &[&str]| {
let o = Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.output()
.unwrap();
assert!(
o.status.success(),
"{args:?}: {}",
String::from_utf8_lossy(&o.stderr)
);
String::from_utf8_lossy(&o.stdout).trim().to_string()
};
git(&["init", "-q", "-b", "main"]);
git(&["config", "user.email", "a@b"]);
git(&["config", "user.name", "a"]);
std::fs::write(p.join("old.txt"), "one\ntwo\nthree\nfour\n").unwrap();
git(&["add", "."]);
git(&["commit", "-qm", "add"]);
std::fs::write(p.join("old.txt"), "one\ntwo\nthree\nFOUR\n").unwrap();
git(&["commit", "-qam", "edit"]);
let edit = git(&["rev-parse", "--short", "HEAD"]);
git(&["mv", "old.txt", "new.txt"]);
git(&["commit", "-qm", "rename"]);
let diff = show_commit_file_diff(p, &edit, "new.txt").unwrap();
assert!(diff.contains("+FOUR"), "{diff}");
}
#[test]
fn parse_file_history_splits_fields_and_computes_age() {
// Two commits, newest first, in the %h\x1f%s\x1f%an\x1f%ct format.
let now = 10_000i64;
let out = "abc123\x1ffix: thing\x1fvitali87\x1f9_996\n\
def456\x1ffeat: thing\x1falice\x1f7600"
.replace('_', "");
let entries = parse_file_history(&out, now);
assert_eq!(entries.len(), 2);
assert_eq!(entries[0].short_hash, "abc123");
assert_eq!(entries[0].summary, "fix: thing");
assert_eq!(entries[0].author, "vitali87");
assert_eq!(
entries[0].age_secs, 4,
"now (10000) minus commit time (9996)"
);
assert_eq!(entries[1].age_secs, 2400);
// A summary containing the field separator is impossible (git emits the
// literal subject), but a malformed line missing fields is dropped.
assert!(parse_file_history("oops-no-fields", now).is_empty());
}
#[test]
fn follow_names_lists_the_old_name_before_a_rename() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let git = |args: &[&str]| {
assert!(
Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.output()
.unwrap()
.status
.success(),
"git {args:?}"
);
};
git(&["init", "-q", "-b", "main"]);
git(&["config", "user.email", "a@b"]);
git(&["config", "user.name", "a"]);
std::fs::create_dir(p.join("sub")).unwrap();
std::fs::write(p.join("sub/old.py"), "a = 1\nb = 2\nc = 3\n").unwrap();
git(&["add", "."]);
git(&["commit", "-q", "-m", "add"]);
git(&["mv", "sub/old.py", "sub/new.py"]);
git(&["commit", "-q", "-m", "rename"]);
let names: Vec<String> = follow_names(p, "sub/new.py", 10)
.into_iter()
.map(|(hash, path)| {
assert_eq!(hash.len(), 40, "full hashes, as the scrubber keys them");
path
})
.collect();
assert_eq!(names, ["sub/new.py", "sub/old.py"]);
// From a workspace rooted in the subfolder, paths are relative to it.
let names: Vec<String> = follow_names(&p.join("sub"), "new.py", 10)
.into_iter()
.map(|(_, path)| path)
.collect();
assert_eq!(names, ["new.py", "old.py"]);
assert!(follow_names(p, "missing.py", 10).is_empty());
}
/// #1304: a rename merged from a side branch is listed on the merge,
/// one of the first-parent commits the scrubber walks. A full walk
/// went down the side branch and skipped the merge, so the scrubber
/// read the merge under the old name, which did not exist there.
#[test]
fn follow_names_lists_a_rename_merged_from_a_side_branch_on_the_merge() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
let git = |args: &[&str]| {
let out = Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.output()
.unwrap();
assert!(out.status.success(), "git {args:?}");
String::from_utf8_lossy(&out.stdout).trim().to_string()
};
git(&["init", "-q", "-b", "main"]);
git(&["config", "user.email", "a@b"]);
git(&["config", "user.name", "a"]);
std::fs::write(p.join("old.py"), "a = 1\nb = 2\nc = 3\n").unwrap();
git(&["add", "."]);
git(&["commit", "-q", "-m", "add"]);
let added = git(&["rev-parse", "HEAD"]);
git(&["checkout", "-q", "-b", "side"]);
git(&["mv", "old.py", "new.py"]);
git(&["commit", "-q", "-m", "rename"]);
git(&["checkout", "-q", "main"]);
std::fs::write(p.join("other.txt"), "x\n").unwrap();
git(&["add", "."]);
git(&["commit", "-q", "-m", "other"]);
git(&["merge", "-q", "--no-ff", "side", "-m", "merge"]);
let merge = git(&["rev-parse", "HEAD"]);
assert_eq!(
follow_names(p, "new.py", 10),
[(merge, "new.py".to_string()), (added, "old.py".to_string())]
);
}
#[test]
fn file_history_returns_real_commits_for_a_tracked_file() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
// init_repo_with_commit commits seed.txt; its history has >=1 entry.
let hist = file_history(p, "seed.txt", 10);
assert!(
!hist.is_empty(),
"a committed file must have at least one history entry"
);
}
#[test]
fn parse_blame_groups_porcelain_into_one_entry_per_line() {
let now = 10_000i64;
// Two source lines: line 1 committed, line 2 an uncommitted edit
// (the all-zero hash git reports for working-tree changes).
let out = "\
abcdef0123456789abcdef0123456789abcdef01 1 1 1
author Vitali
author-time 9996
summary fix: the thing
filename seed.txt
\tone
0000000000000000000000000000000000000000 2 2 1
author Not Committed Yet
author-time 9999
summary Version of seed.txt from seed.txt
filename seed.txt
\ttwo
";
let b = parse_blame(out, now);
assert_eq!(b.len(), 2, "one entry per source line");
let (first, text) = b.line(0).unwrap();
assert_eq!(first.hash, "abcdef0123456789abcdef0123456789abcdef01");
assert_eq!(first.short_hash(), "abcdef01");
assert_eq!(first.author, "Vitali");
assert_eq!(first.summary, "fix: the thing");
assert_eq!(first.age_secs, 4, "now (10000) minus author-time (9996)");
assert!(!first.uncommitted);
assert_eq!(text, Some("one"));
assert!(
b.line(1).unwrap().0.uncommitted,
"the zero hash marks an uncommitted line"
);
}
/// `--porcelain` describes a commit only the first time it appears
/// (#1707): every later line of it must still read its author, age and
/// summary, from the one record they share.
#[test]
fn parse_blame_gives_a_commits_later_lines_its_first_description() {
let now = 10_000i64;
let out = "\
abcdef0123456789abcdef0123456789abcdef01 1 1 1
author Vitali
author-time 9996
summary fix: the thing
filename seed.txt
\tone
1111111111111111111111111111111111111111 2 2 1
author Alice
author-time 9000
summary add two
filename seed.txt
\ttwo
abcdef0123456789abcdef0123456789abcdef01 3 3 1
filename seed.txt
\tthree
";
let b = parse_blame(out, now);
assert_eq!(b.len(), 3, "one entry per source line");
let (third, text) = b.line(2).unwrap();
assert_eq!(text, Some("three"));
assert_eq!(third.author, "Vitali");
assert_eq!(third.summary, "fix: the thing");
assert_eq!(third.age_secs, 4);
assert_eq!(third.short_hash(), "abcdef01");
assert!(
std::ptr::eq(b.line(0).unwrap().0, third),
"two lines of one commit share its record"
);
assert_eq!(b.line(1).unwrap().0.author, "Alice");
}
#[test]
fn blame_returns_one_entry_per_committed_line() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
// seed.txt is "one\ntwo\n" — two committed lines.
let b = blame(p, "seed.txt");
assert_eq!(b.len(), 2, "blame reports every source line");
let (first, _) = b.line(0).unwrap();
assert_eq!(
first.author, "a",
"committed by init_repo_with_commit's user"
);
assert!(!first.uncommitted);
assert_eq!(first.hash.len(), 40, "the full hash");
assert_eq!(
b.line(1).unwrap().0.author,
"a",
"a commit's second line reads its author too"
);
}
/// A workspace opened one folder ABOVE its repo (#1227): `tl/` holding
/// the repo `tl/sub/`. Running git from the workspace root fails there,
/// so history and blame must resolve from the file's own folder.
#[test]
fn file_history_finds_the_repo_below_the_workspace_root() {
let tmp = TempDir::new().unwrap();
let sub = tmp.path().join("sub");
std::fs::create_dir(&sub).unwrap();
init_repo_with_commit(&sub);
let hist = file_history(tmp.path(), "sub/seed.txt", 10);
assert_eq!(hist.len(), 1, "the commit in sub/ must be listed");
}
/// #1556: a TIMELINE row or Git: Open Commit for Line in a workspace
/// opened above the repository must still show the commit's diff.
#[test]
fn a_commits_file_diff_comes_from_the_repo_below_the_workspace_root() {
let tmp = TempDir::new().unwrap();
let sub = tmp.path().join("sub");
std::fs::create_dir(&sub).unwrap();
init_repo_with_commit(&sub);
let raw = show_commit_file_diff(tmp.path(), "HEAD", "sub/seed.txt").unwrap();
assert!(raw.contains("diff --git a/seed.txt b/seed.txt"), "{raw}");
assert!(raw.lines().any(|l| l == "+two"), "{raw}");
}
#[test]
fn blame_finds_the_repo_below_the_workspace_root() {
let tmp = TempDir::new().unwrap();
let sub = tmp.path().join("sub");
std::fs::create_dir(&sub).unwrap();
init_repo_with_commit(&sub);
let b = blame(tmp.path(), "sub/seed.txt");
assert_eq!(b.len(), 2, "blame of sub/seed.txt from the parent");
assert!(!b.line(0).unwrap().0.uncommitted);
}
#[test]
fn file_history_of_a_file_in_a_repo_subfolder_still_resolves() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::create_dir(p.join("dir")).unwrap();
std::fs::write(p.join("dir/x.txt"), "x\n").unwrap();
let _ = Command::new("git")
.arg("-C")
.arg(p)
.args(["add", "."])
.status();
let _ = Command::new("git")
.arg("-C")
.arg(p)
.args(["commit", "-qm", "x"])
.status();
assert_eq!(file_history(p, "dir/x.txt", 10).len(), 1);
assert_eq!(blame(p, "dir/x.txt").len(), 1);
}
#[test]
fn history_and_blame_stay_empty_outside_any_repo() {
let tmp = TempDir::new().unwrap();
let sub = tmp.path().join("sub");
std::fs::create_dir(&sub).unwrap();
std::fs::write(sub.join("plain.txt"), "one\n").unwrap();
assert!(file_history(tmp.path(), "sub/plain.txt", 10).is_empty());
assert!(blame(tmp.path(), "sub/plain.txt").is_empty());
}
#[test]
fn history_of_a_file_untracked_in_a_nested_repo_is_empty() {
let tmp = TempDir::new().unwrap();
let sub = tmp.path().join("sub");
std::fs::create_dir(&sub).unwrap();
init_repo_with_commit(&sub);
std::fs::write(sub.join("new.txt"), "new\n").unwrap();
assert!(file_history(tmp.path(), "sub/new.txt", 10).is_empty());
}
#[test]
fn child_repos_finds_repos_one_level_down_only() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
for d in ["web", "api", "plain", ".hidden", "deep/inner"] {
std::fs::create_dir_all(p.join(d)).unwrap();
}
init_repo_with_commit(&p.join("web"));
init_repo_with_commit(&p.join("api"));
init_repo_with_commit(&p.join(".hidden"));
init_repo_with_commit(&p.join("deep/inner"));
std::fs::write(p.join("worktree_file_dir_marker"), "").unwrap();
std::fs::create_dir(p.join("wt")).unwrap();
std::fs::write(p.join("wt/.git"), "gitdir: /elsewhere\n").unwrap();
assert_eq!(
child_repos(p),
vec![p.join("api"), p.join("web"), p.join("wt")],
"sorted, depth 1, hidden skipped, a .git file counts"
);
}
#[test]
fn child_repos_is_empty_for_a_missing_or_repo_free_folder() {
let tmp = TempDir::new().unwrap();
std::fs::create_dir(tmp.path().join("plain")).unwrap();
assert!(child_repos(tmp.path()).is_empty());
assert!(child_repos(&tmp.path().join("gone")).is_empty());
}
/// Stage a path so we can exercise `unstage_*` against a real index.
fn stage(p: &Path, rel: &str) {
let _ = Command::new("git")
.args(["-C"])
.arg(p)
.args(["add", rel])
.status();
}
/// True when `rel` shows up as a staged entry in `git status --porcelain`
/// (index column non-space, non-`?`).
fn is_staged(p: &Path, rel: &str) -> bool {
query_changes(p)
.iter()
.any(|e| e.path == rel && e.kind.section() == ChangeSection::Staged)
}
#[test]
fn unstage_path_moves_a_staged_file_back_to_changes() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nthree\n").unwrap();
stage(p, "seed.txt");
assert!(is_staged(p, "seed.txt"), "precondition: seed.txt is staged");
unstage_path(p, "seed.txt").expect("unstage must succeed");
assert!(
!is_staged(p, "seed.txt"),
"after unstage the modification is back in the working tree, not the index"
);
}
#[test]
fn unstage_paths_is_a_noop_on_an_empty_list() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
assert!(unstage_paths(p, &[]).is_ok());
}
#[test]
fn create_branch_then_list_branches_marks_the_new_current_branch() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
create_branch(p, "feature/x").expect("create_branch must succeed");
let branches = list_branches(p).expect("list_branches must succeed");
let current: Vec<&BranchInfo> = branches.iter().filter(|b| b.is_current).collect();
assert_eq!(current.len(), 1, "exactly one branch is current");
assert_eq!(current[0].display, "feature/x");
// The original branch is still listed, just not current.
assert!(
branches
.iter()
.any(|b| b.display == "main" && !b.is_current)
);
}
#[test]
fn checkout_branch_switches_back_to_an_existing_branch() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
create_branch(p, "feature/x").unwrap();
checkout_branch(p, "main").expect("checkout_branch must succeed");
let branch = query(p).branch;
assert_eq!(branch.as_deref(), Some("main"));
}
#[test]
fn stash_push_then_pop_round_trips_a_working_tree_change() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nstashed\n").unwrap();
stash_push(p, None).expect("stash push must succeed");
// The dirty edit is gone from the working tree after stashing.
assert_eq!(
std::fs::read_to_string(p.join("seed.txt")).unwrap(),
"one\ntwo\n"
);
stash_pop(p).expect("stash pop must succeed");
assert_eq!(
std::fs::read_to_string(p.join("seed.txt")).unwrap(),
"one\ntwo\nstashed\n",
"pop restores the stashed edit"
);
}
#[test]
fn clone_dir_name_strips_dot_git_and_path() {
assert_eq!(
clone_dir_name("https://codeberg.org/vitali87/croft.git").as_deref(),
Some("croft")
);
assert_eq!(
clone_dir_name("git@github.com:owner/repo.git").as_deref(),
Some("repo")
);
assert_eq!(
clone_dir_name("https://host/path/thing/").as_deref(),
Some("thing")
);
assert_eq!(clone_dir_name(" ").as_deref(), None);
}
#[test]
fn stage_all_then_unstage_all_round_trips_the_index() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nthree\n").unwrap();
std::fs::write(p.join("new.txt"), "x").unwrap();
stage_all(p).expect("stage_all");
assert!(is_staged(p, "seed.txt"));
assert!(is_staged(p, "new.txt"), "untracked file is staged by -A");
unstage_all(p).expect("unstage_all");
assert!(!is_staged(p, "seed.txt"));
assert!(!is_staged(p, "new.txt"));
}
#[test]
fn discard_all_tracked_reverts_modifications_but_keeps_untracked() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nDIRTY\n").unwrap();
std::fs::write(p.join("scratch.txt"), "keep me").unwrap();
discard_all_tracked(p).expect("discard_all_tracked");
assert_eq!(
std::fs::read_to_string(p.join("seed.txt")).unwrap(),
"one\ntwo\n",
"tracked modification is reverted to HEAD"
);
assert!(
p.join("scratch.txt").exists(),
"untracked files survive a tracked-only discard"
);
}
#[test]
fn commit_staged_commits_only_the_index() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nstaged\n").unwrap();
std::fs::write(p.join("other.txt"), "unstaged").unwrap();
stage(p, "seed.txt");
commit_staged(p, "only staged").expect("commit_staged");
// other.txt is still untracked/uncommitted after the staged commit.
assert!(
query_changes(p).iter().any(|e| e.path == "other.txt"),
"an unstaged file must remain a pending change after commit_staged"
);
}
/// A committed repo with `seed.txt` and `wip.txt` both edited.
fn repo_with_two_edits(p: &Path) {
init_repo_with_commit(p);
std::fs::write(p.join("wip.txt"), "draft\n").unwrap();
git_in(p, &["add", "wip.txt"]);
git_in(p, &["commit", "-qm", "add wip"]);
std::fs::write(p.join("seed.txt"), "one\ntwo\nready\n").unwrap();
std::fs::write(p.join("wip.txt"), "draft\nnot ready\n").unwrap();
}
#[test]
fn commit_takes_only_the_index_when_anything_is_staged() {
// #965: `git commit -am` swept the unstaged edit in with the staged one.
let tmp = TempDir::new().unwrap();
let p = tmp.path();
repo_with_two_edits(p);
stage(p, "seed.txt");
commit(p, "ready part").expect("commit");
assert_eq!(git_in(p, &["show", "HEAD:seed.txt"]), "one\ntwo\nready");
assert_eq!(git_in(p, &["show", "HEAD:wip.txt"]), "draft");
assert_eq!(
std::fs::read_to_string(p.join("wip.txt")).unwrap(),
"draft\nnot ready\n",
"the unstaged edit stays in the working tree"
);
assert_eq!(git_in(p, &["diff", "--name-only"]), "wip.txt");
}
#[test]
fn commit_takes_every_tracked_change_when_nothing_is_staged() {
// Negative: with an empty index it is still VS Code's smart commit.
let tmp = TempDir::new().unwrap();
let p = tmp.path();
repo_with_two_edits(p);
std::fs::write(p.join("new.txt"), "untracked\n").unwrap();
commit(p, "everything").expect("commit");
assert_eq!(git_in(p, &["show", "HEAD:seed.txt"]), "one\ntwo\nready");
assert_eq!(git_in(p, &["show", "HEAD:wip.txt"]), "draft\nnot ready");
assert_eq!(git_in(p, &["status", "--porcelain"]), "?? new.txt");
}
#[test]
fn a_subdirectory_root_with_diff_relative_still_sees_what_is_staged() {
// `diff.relative` would scope the check to the subdirectory, and
// `-a` would then sweep in the unstaged edit as well.
let tmp = TempDir::new().unwrap();
let p = tmp.path();
repo_with_two_edits(p);
git_in(p, &["config", "diff.relative", "true"]);
stage(p, "seed.txt");
let sub = p.join("sub");
std::fs::create_dir(&sub).unwrap();
assert_eq!(has_staged_changes(&sub), Ok(true));
commit(&sub, "ready part").expect("commit");
assert_eq!(git_in(p, &["show", "HEAD:wip.txt"]), "draft");
}
#[test]
fn a_staged_submodule_update_counts_despite_diff_ignore_submodules() {
// `diff.ignoreSubmodules=all` hid the staged gitlink, so the commit
// took `-a` and swept the unstaged edit in with it.
let tmp = TempDir::new().unwrap();
let p = tmp.path();
repo_with_two_edits(p);
git_in(p, &["config", "diff.ignoreSubmodules", "all"]);
let head = git_in(p, &["rev-parse", "HEAD"]);
git_in(
p,
&[
"update-index",
"--add",
"--cacheinfo",
&format!("160000,{head},lib"),
],
);
assert_eq!(has_staged_changes(p), Ok(true));
commit(p, "bump lib").expect("commit");
assert_eq!(git_in(p, &["show", "HEAD:wip.txt"]), "draft");
}
#[test]
fn a_staged_change_counts_despite_a_trusted_external_diff() {
// From git 2.46 a `diff.external` whose exit code is trusted decides
// what `--quiet` reports; one answering "equal" hid the staged edit,
// so the commit took `-a` and swept the unstaged one in with it.
let tmp = TempDir::new().unwrap();
let p = tmp.path();
repo_with_two_edits(p);
stage(p, "seed.txt");
git_in(p, &["config", "diff.external", "true"]);
git_in(p, &["config", "diff.trustExitCode", "true"]);
assert_eq!(has_staged_changes(p), Ok(true));
commit(p, "ready part").expect("commit");
assert_eq!(git_in(p, &["show", "HEAD:wip.txt"]), "draft");
}
#[test]
fn rename_branch_changes_the_current_branch_name() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
rename_branch(p, "renamed").expect("rename_branch");
assert_eq!(query(p).branch.as_deref(), Some("renamed"));
}
#[test]
fn delete_branch_removes_a_merged_branch() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
create_branch(p, "throwaway").unwrap();
checkout_branch(p, "main").unwrap();
// throwaway points at the same commit as main, so -d is safe.
delete_branch(p, "throwaway").expect("delete_branch");
assert!(
!list_branches(p)
.unwrap()
.iter()
.any(|b| b.display == "throwaway"),
"the deleted branch must be gone"
);
}
#[test]
fn add_then_list_then_remove_remote_round_trips() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
add_remote(p, "upstream", "https://example.com/x.git").expect("add_remote");
let remotes = list_remotes(p).unwrap();
assert!(
remotes
.iter()
.any(|r| r.name == "upstream" && r.url == "https://example.com/x.git")
);
remove_remote(p, "upstream").expect("remove_remote");
assert!(
!list_remotes(p)
.unwrap()
.iter()
.any(|r| r.name == "upstream")
);
}
#[test]
fn create_then_list_then_delete_tag_round_trips() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
create_tag(p, "v1.0.0", None).expect("create_tag");
assert!(list_tags(p).unwrap().contains(&"v1.0.0".to_string()));
delete_tag(p, "v1.0.0").expect("delete_tag");
assert!(!list_tags(p).unwrap().contains(&"v1.0.0".to_string()));
}
#[test]
fn stash_list_indexes_newest_first_and_apply_drop_work() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nfirst\n").unwrap();
stash_push(p, None).expect("first stash");
std::fs::write(p.join("seed.txt"), "one\ntwo\nsecond\n").unwrap();
stash_push(p, None).expect("second stash");
let stashes = list_stashes(p).unwrap();
assert_eq!(stashes.len(), 2);
assert_eq!(stashes[0].index, 0, "newest stash is stash@{{0}}");
// Apply the older stash (index 1) without dropping it.
stash_apply(p, 1).expect("stash_apply");
assert_eq!(
std::fs::read_to_string(p.join("seed.txt")).unwrap(),
"one\ntwo\nfirst\n"
);
// Both stashes still present after apply.
assert_eq!(list_stashes(p).unwrap().len(), 2);
// Drop the newest; one remains.
stash_drop(p, 0).expect("stash_drop");
assert_eq!(list_stashes(p).unwrap().len(), 1);
}
// #1581: a stash takes the name it is given, for every kind of stash,
// and its row says how old it is and which files it holds.
#[test]
fn a_stash_message_names_the_stash_and_the_row_lists_its_files() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\ntracked\n").unwrap();
stash_push(p, Some("retry tweak")).expect("named stash");
std::fs::write(p.join("new.txt"), "untracked\n").unwrap();
stash_push_untracked(p, Some("with the new file")).expect("named -u stash");
std::fs::write(p.join("seed.txt"), "one\ntwo\nstaged\n").unwrap();
run_git(p, &["add", "seed.txt"]).unwrap();
stash_push_staged(p, Some("only staged")).expect("named --staged stash");
let stashes = list_stashes(p).unwrap();
let messages: Vec<&str> = stashes.iter().map(|s| s.message.as_str()).collect();
assert_eq!(
messages,
[
"On main: only staged",
"On main: with the new file",
"On main: retry tweak"
]
);
assert_eq!(stashes[1].files, ["new.txt"], "untracked files are listed");
assert_eq!(stashes[2].files, ["seed.txt"]);
assert!(!stashes[2].age.is_empty(), "{:?}", stashes[2]);
let label = stashes[2].label();
assert!(
label.starts_with("stash@{2}: On main: retry tweak \u{b7} ")
&& label.ends_with(" \u{b7} seed.txt"),
"{label}"
);
}
// #1581: the file lists come from one listing for every stash, so a
// stash's tracked and untracked files are merged into one row and
// each stash keeps its own files.
#[test]
fn stash_rows_merge_tracked_and_untracked_files_per_stash() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nmixed\n").unwrap();
std::fs::write(p.join("a_new.txt"), "untracked\n").unwrap();
stash_push_untracked(p, Some("mixed")).unwrap();
std::fs::write(p.join("seed.txt"), "one\ntwo\nplain\n").unwrap();
stash_push(p, Some("plain")).unwrap();
std::fs::write(p.join("z_new.txt"), "only untracked\n").unwrap();
stash_push_untracked(p, Some("untracked only")).unwrap();
let stashes = list_stashes(p).unwrap();
assert_eq!(stashes.len(), 3);
assert_eq!(stashes[0].files, ["z_new.txt"]);
assert_eq!(stashes[1].files, ["seed.txt"]);
assert_eq!(stashes[2].files, ["a_new.txt", "seed.txt"]);
assert_eq!(
stashes.iter().map(|s| s.index).collect::<Vec<_>>(),
[0, 1, 2]
);
}
// Negative (#1581): a blank or missing message leaves git's own
// `WIP on` name, and a row never lists more than three files.
#[test]
fn a_blank_stash_message_keeps_the_wip_name_and_long_file_lists_are_cut() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nblank\n").unwrap();
stash_push(p, Some(" ")).expect("blank-named stash");
let stashes = list_stashes(p).unwrap();
assert!(
stashes[0].message.starts_with("WIP on main: "),
"{:?}",
stashes[0]
);
let info = StashInfo {
index: 4,
message: "On main: big".into(),
age: String::new(),
files: ["a", "b", "c", "d", "e"].map(String::from).to_vec(),
};
assert_eq!(info.label(), "stash@{4}: On main: big \u{b7} a, b, c +2");
}
// #1581: View Stash shows the stash's diff, untracked files included,
// without applying it.
#[test]
fn show_stash_is_the_patch_without_applying_it() {
let tmp = TempDir::new().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::write(p.join("seed.txt"), "one\ntwo\nretries = 5\n").unwrap();
std::fs::write(p.join("extra.txt"), "brand new\n").unwrap();
stash_push_untracked(p, Some("retries")).unwrap();
let patch = show_stash(p, 0).expect("show_stash");
assert!(patch.contains("+retries = 5"), "{patch}");
assert!(patch.contains("+brand new"), "untracked: {patch}");
assert!(patch.contains("2 files changed"), "the stat: {patch}");
assert_eq!(
std::fs::read_to_string(p.join("seed.txt")).unwrap(),
"one\ntwo\n",
"viewing does not apply"
);
assert_eq!(list_stashes(p).unwrap().len(), 1, "viewing does not drop");
assert!(show_stash(p, 3).is_err(), "no such stash");
}
#[test]
fn pull_on_an_up_to_date_clone_succeeds() {
let upstream = TempDir::new().unwrap();
let up = upstream.path();
init_repo_with_commit(up);
let clone = TempDir::new().unwrap();
let clone_path = clone.path().join("work");
let ok = Command::new("git")
.args(["clone", "-q"])
.arg(up)
.arg(&clone_path)
.status()
.map(|s| s.success())
.unwrap_or(false);
assert!(ok, "clone of the local upstream must succeed");
// Nothing new upstream, so pull is a no-op but must return Ok with
// git's "up to date" summary rather than erroring.
let summary = pull_current_branch(&clone_path).expect("pull must succeed");
assert!(
summary.to_lowercase().contains("up to date") || summary.is_empty(),
"an up-to-date pull reports no new work (got: {summary:?})"
);
}
/// #989: the issue's repro, a merge stopped on a conflict in README.md.
fn repo_in_a_conflicted_merge() -> TempDir {
let tmp = TempDir::new().unwrap();
let script = r#"set -e
git init -q -b main && git config user.email a@b && git config user.name a
printf '# Orders\n\nRun `python pricing.py`.\n' > README.md && git add . && git commit -qm init
git checkout -qb hotfix && sed 's/python pricing.py/python -m pricing/' README.md > README.tmp && mv README.tmp README.md && git commit -qam fix
git checkout -q main && sed 's/python pricing.py/uv run pricing.py/' README.md > README.tmp && mv README.tmp README.md && git commit -qam uv
! git merge -q hotfix >/dev/null 2>&1"#;
let out = Command::new("sh")
.args(["-c", script])
.current_dir(tmp.path())
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
tmp
}
fn head_of(p: &Path) -> String {
let out = Command::new("git")
.arg("-C")
.arg(p)
.args(["rev-parse", "HEAD"])
.output()
.unwrap();
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
#[test]
fn commit_refuses_while_a_merge_has_unresolved_conflicts() {
// `git commit -a` stages an unmerged file as it is, so the merge
// commit recorded the conflict markers.
let tmp = repo_in_a_conflicted_merge();
let p = tmp.path();
let before = head_of(p);
let err = commit(p, "Merge hotfix").expect_err("the commit must be refused");
assert!(
err.contains("Resolve 1 merge conflict (README.md)"),
"{err}"
);
assert_eq!(head_of(p), before, "no commit was made");
assert_eq!(unmerged_paths(p), vec![String::from("README.md")]);
assert!(
p.join(".git/MERGE_HEAD").exists(),
"the merge is still open"
);
}
#[test]
fn a_merge_whose_conflicts_are_resolved_and_staged_still_commits() {
// Negative: the guard only holds back unresolved paths.
let tmp = repo_in_a_conflicted_merge();
let p = tmp.path();
std::fs::write(
p.join("README.md"),
"# Orders\n\nRun `uv run -m pricing`.\n",
)
.unwrap();
run_mutation(p, &["add", "README.md"]).unwrap();
assert!(unmerged_paths(p).is_empty());
commit(p, "Merge hotfix").expect("a resolved merge commits");
let parents = Command::new("git")
.arg("-C")
.arg(p)
.args(["rev-list", "--parents", "-n1", "HEAD"])
.output()
.unwrap();
assert_eq!(
String::from_utf8_lossy(&parents.stdout)
.split_whitespace()
.count(),
3,
"a merge commit with two parents"
);
}
#[test]
fn the_commits_that_do_not_stage_are_refused_by_git_itself() {
// Negative: Commit Staged and Amend run a plain `git commit`, which
// refuses an unmerged index on its own, so they need no guard.
let tmp = repo_in_a_conflicted_merge();
let p = tmp.path();
let before = head_of(p);
assert!(commit_staged(p, "Merge hotfix").is_err());
assert!(commit_amend(p, "amended").is_err());
assert!(commit_amend_no_edit(p).is_err());
assert_eq!(head_of(p), before);
}
#[test]
fn a_subdirectory_root_with_diff_relative_still_sees_the_conflicts() {
// `diff.relative` scoped the check to the subdirectory, so a
// conflict outside it slipped past the guard.
let tmp = repo_in_a_conflicted_merge();
let p = tmp.path();
run_mutation(p, &["config", "diff.relative", "true"]).unwrap();
let sub = p.join("sub");
std::fs::create_dir(&sub).unwrap();
assert_eq!(unmerged_paths(&sub), vec![String::from("README.md")]);
assert!(refuse_unmerged(&sub).is_err());
}
#[test]
fn staging_a_conflict_that_still_has_its_markers_is_refused() {
// `git add` marks the conflict resolved with the markers in it, so
// Stage All, then Commit, recorded them.
let tmp = repo_in_a_conflicted_merge();
let p = tmp.path();
let err = stage_all(p).expect_err("Stage All must refuse");
assert_eq!(
err,
"README.md still has conflict markers: resolve it before staging"
);
let err = stage_path(p, "README.md").expect_err("staging the file must refuse");
assert!(
err.contains("README.md still has conflict markers"),
"{err}"
);
assert_eq!(unmerged_paths(p), vec![String::from("README.md")]);
}
#[test]
fn a_conflict_in_a_non_utf8_file_is_refused_too() {
// A Latin-1 file can't be read as UTF-8; its markers still count.
let tmp = repo_in_a_conflicted_merge();
let p = tmp.path();
std::fs::write(
p.join("README.md"),
b"# Caf\xe9\n<<<<<<< HEAD\nuv\n=======\npython -m\n>>>>>>> hotfix\n",
)
.unwrap();
assert!(stage_all(p).is_err());
assert_eq!(unmerged_paths(p), vec![String::from("README.md")]);
}
#[test]
fn markers_of_a_conflict_marker_size_attribute_are_refused_too() {
// git writes ten-character markers for this file, which a scan for
// seven-character ones read as resolved.
let tmp = repo_in_a_conflicted_merge();
let p = tmp.path();
std::fs::write(
p.join(".gitattributes"),
"README.md conflict-marker-size=10\n",
)
.unwrap();
run_mutation(p, &["checkout", "--conflict=merge", "--", "README.md"]).unwrap();
let text = std::fs::read_to_string(p.join("README.md")).unwrap();
assert!(text.contains("<<<<<<<<<< ours"), "{text}");
assert!(stage_path(p, "README.md").is_err());
}
#[test]
fn a_resolved_file_that_shows_a_marker_example_both_sides_had_stages() {
// Negative: a doc that shows what a conflict looks like keeps that
// block after its real conflict is resolved; it must not block
// staging forever.
let tmp = TempDir::new().unwrap();
let script = r#"set -e
git init -q -b main && git config user.email a@b && git config user.name a
printf 'Example:\n<<<<<<< HEAD\nmine\n=======\nyours\n>>>>>>> br\n\nRun `python pricing.py`.\n' > GUIDE.md && git add . && git commit -qm init
git checkout -qb hotfix && sed 's/python pricing.py/python -m pricing/' GUIDE.md > g.tmp && mv g.tmp GUIDE.md && git commit -qam fix
git checkout -q main && sed 's/python pricing.py/uv run pricing.py/' GUIDE.md > g.tmp && mv g.tmp GUIDE.md && git commit -qam uv
! git merge -q hotfix >/dev/null 2>&1
sed -n '1,7p' GUIDE.md > g.tmp && echo 'Run `uv run -m pricing`.' >> g.tmp && mv g.tmp GUIDE.md"#;
let out = Command::new("sh")
.args(["-c", script])
.current_dir(tmp.path())
.output()
.unwrap();
assert!(
out.status.success(),
"{}",
String::from_utf8_lossy(&out.stderr)
);
let p = tmp.path();
assert_eq!(unmerged_paths(p), vec![String::from("GUIDE.md")]);
stage_all(p).expect("the example both sides had is not a conflict");
assert!(unmerged_paths(p).is_empty());
}
#[test]
fn a_conflict_resolved_in_the_file_stages_as_before() {
// Negative: once the markers are edited away, staging is how the
// conflict is marked resolved.
let tmp = repo_in_a_conflicted_merge();
let p = tmp.path();
std::fs::write(
p.join("README.md"),
"# Orders\n\nRun `uv run -m pricing`.\n",
)
.unwrap();
stage_all(p).expect("a resolved conflict stages");
assert!(unmerged_paths(p).is_empty());
}
#[test]
fn staging_from_a_subdirectory_checks_only_what_it_stages() {
// The conflict sits above the subdirectory root: Stage All covers
// the whole repository and refuses, staging a file beside it does
// not reach the conflict and goes ahead.
let tmp = repo_in_a_conflicted_merge();
let p = tmp.path();
let sub = p.join("sub");
std::fs::create_dir(&sub).unwrap();
std::fs::write(sub.join("notes.txt"), "todo\n").unwrap();
assert!(stage_all(&sub).is_err());
stage_path(&sub, "notes.txt").expect("an unrelated file stages");
assert_eq!(unmerged_paths(p), vec![String::from("README.md")]);
}
#[test]
fn a_repo_with_no_merge_in_progress_has_no_unmerged_paths() {
// Negative: ordinary edits are not conflicts.
let tmp = repo_in_a_conflicted_merge();
let p = tmp.path();
run_mutation(p, &["merge", "--abort"]).unwrap();
std::fs::write(p.join("README.md"), "edited\n").unwrap();
assert!(unmerged_paths(p).is_empty());
commit(p, "edit").expect("an ordinary commit goes through");
}
/// A repo whose `*.txt` files go through a rot13 clean/smudge filter: the
/// index and HEAD hold rot13 text, the working tree plain text, the way
/// Git LFS keeps a pointer in git and the real file on disk (#1238).
fn filtered_repo(root: &Path) {
filtered_repo_with(root, "rot13");
}
/// [`filtered_repo`] with the driver configured under `name`.
fn filtered_repo_with(root: &Path, name: &str) {
let run = |args: &[&str]| {
assert!(
Command::new("git")
.arg("-C")
.arg(root)
.args(args)
.status()
.unwrap()
.success(),
"git {args:?}"
)
};
run(&["init", "-q", "-b", "main"]);
run(&["config", "user.email", "t@t"]);
run(&["config", "user.name", "t"]);
let rot13 = "tr A-Za-z N-ZA-Mn-za-m";
run(&["config", &format!("filter.{name}.clean"), rot13]);
run(&["config", &format!("filter.{name}.smudge"), rot13]);
std::fs::write(
root.join(".gitattributes"),
format!("*.txt filter={name}\n"),
)
.unwrap();
let body: String = (1..=12).map(|i| format!("row {i}\n")).collect();
std::fs::write(root.join("data.txt"), &body).unwrap();
std::fs::write(root.join("notes.md"), &body).unwrap();
run(&["add", "."]);
run(&["commit", "-q", "-m", "init"]);
let edit = |name: &str| {
let text = std::fs::read_to_string(root.join(name)).unwrap();
std::fs::write(root.join(name), text.replace("row 5\n", "row FIVE\n")).unwrap();
};
edit("data.txt");
edit("notes.md");
}
fn head_vs_work_patch(root: &Path, rel: &str) -> String {
let head = read_file_at_head(root, rel).unwrap();
let work = std::fs::read_to_string(root.join(rel)).unwrap();
let diff = crate::widgets::diff::DiffData::build(
std::path::PathBuf::new(),
std::path::PathBuf::new(),
head.lines().map(str::to_string).collect(),
work.lines().map(str::to_string).collect(),
);
diff.hunk_patch(rel, diff.hunk_range_at(0).unwrap())
}
#[test]
fn a_filtered_files_head_side_is_what_the_filter_checks_out() {
let tmp = TempDir::new().unwrap();
filtered_repo(tmp.path());
assert_eq!(
sh_git(tmp.path(), &["show", "HEAD:data.txt"])
.lines()
.next(),
Some("ebj 1"),
"sanity: git stores the cleaned form"
);
let head = read_file_at_head(tmp.path(), "data.txt").unwrap();
assert_eq!(
head.lines().next(),
Some("row 1"),
"the diff compares like with like"
);
let patch = head_vs_work_patch(tmp.path(), "data.txt");
assert_eq!(
patch
.lines()
.filter(|l| l.starts_with(['-', '+'])
&& !l.starts_with("---")
&& !l.starts_with("+++"))
.collect::<Vec<_>>(),
vec!["-row 5", "+row FIVE"],
"a one-line edit is a one-line change: {patch}"
);
}
#[test]
fn staging_a_hunk_of_a_filtered_file_is_refused_and_leaves_the_index() {
let tmp = TempDir::new().unwrap();
filtered_repo(tmp.path());
let before = sh_git(tmp.path(), &["show", ":data.txt"]);
let patch = head_vs_work_patch(tmp.path(), "data.txt");
let err = apply_patch(tmp.path(), &patch, true, false).unwrap_err();
assert_eq!(
err,
"data.txt uses the rot13 filter: stage the whole file, not a part"
);
assert_eq!(
sh_git(tmp.path(), &["show", ":data.txt"]),
before,
"index untouched"
);
let err = apply_patch(tmp.path(), &patch, true, true).unwrap_err();
assert!(
err.contains("unstage the whole file"),
"unstaging is refused too: {err}"
);
}
#[test]
fn reverting_a_hunk_of_a_filtered_file_says_why_it_cannot() {
let tmp = TempDir::new().unwrap();
filtered_repo(tmp.path());
let patch = head_vs_work_patch(tmp.path(), "data.txt");
let err = apply_patch(tmp.path(), &patch, false, true).unwrap_err();
assert_eq!(
err,
"data.txt uses the rot13 filter: discard the whole file, not a part"
);
let work = std::fs::read_to_string(tmp.path().join("data.txt")).unwrap();
assert!(
work.contains("row FIVE\n"),
"the working file is untouched: {work}"
);
}
/// [`filtered_repo`] with its edits committed: HEAD~1 holds `row 5`,
/// HEAD holds `row FIVE`, in both the filtered and the plain file.
fn filtered_history(root: &Path) {
filtered_repo(root);
sh_git(root, &["commit", "-q", "-am", "Rename row 5"]);
}
/// The `-`/`+` lines of a unified diff, headers left out.
fn changed_lines(diff: &str) -> Vec<&str> {
diff.lines()
.filter(|l| l.starts_with(['-', '+']) && !l.starts_with("---") && !l.starts_with("+++"))
.collect()
}
#[test]
fn a_filtered_files_past_versions_read_as_the_file_not_what_git_stores() {
// #1338: Scrub History read the pointer (here, rot13 text) at every
// past commit, and the merge editor's sides had the same gap.
let tmp = TempDir::new().unwrap();
filtered_history(tmp.path());
let past = read_file_at_rev(tmp.path(), "HEAD~1", "data.txt").unwrap();
assert!(past.starts_with("row 1\n"), "{past}");
assert!(past.contains("row 5\n") && !past.contains("FIVE"), "{past}");
let now = read_file_at_rev(tmp.path(), "HEAD", "data.txt").unwrap();
assert!(now.contains("row FIVE\n"), "{now}");
let staged = read_file_at_stage(tmp.path(), "data.txt", 0).unwrap();
assert_eq!(staged, now, "an index stage reads through the filter too");
}
#[test]
fn a_filtered_files_timeline_diff_shows_what_changed_in_the_file() {
let tmp = TempDir::new().unwrap();
filtered_history(tmp.path());
let hash = sh_git(tmp.path(), &["rev-parse", "--short", "HEAD"]);
let raw = show_commit_file_diff(tmp.path(), hash.trim(), "data.txt").unwrap();
assert!(
raw.starts_with("commit ") && raw.contains(" Rename row 5\n\ndiff --git"),
"the commit header an unfiltered file's diff carries: {raw}"
);
assert_eq!(
changed_lines(&raw),
vec!["-row 5", "+row FIVE"],
"the content change, not the stored form's: {raw}"
);
let view = crate::widgets::diff::DiffData::build_side_by_side_from_git_text(
std::path::PathBuf::from("data.txt"),
&raw,
);
assert!(
view.left_lines.iter().any(|l| l == "row 5"),
"{view:?}",
view = view.left_lines
);
assert!(
view.right_lines.iter().any(|l| l == "row FIVE"),
"{view:?}",
view = view.right_lines
);
// The commit that added the file: every line is new, nothing fails.
let first = sh_git(tmp.path(), &["rev-parse", "--short", "HEAD~1"]);
let raw = show_commit_file_diff(tmp.path(), first.trim(), "data.txt").unwrap();
let lines = changed_lines(&raw);
assert_eq!(lines.len(), 12, "{raw}");
assert_eq!(lines[0], "+row 1");
}
#[test]
fn an_unfiltered_files_history_reads_exactly_as_git_shows_it() {
let tmp = TempDir::new().unwrap();
filtered_history(tmp.path());
assert_eq!(path_filter(tmp.path(), "notes.md"), None, "precondition");
assert_eq!(
read_file_at_rev(tmp.path(), "HEAD~1", "notes.md").unwrap(),
sh_git(tmp.path(), &["show", "HEAD~1:notes.md"])
);
let hash = sh_git(tmp.path(), &["rev-parse", "--short", "HEAD"]);
let raw = show_commit_file_diff(tmp.path(), hash.trim(), "notes.md").unwrap();
assert_eq!(
raw,
sh_git(tmp.path(), &["show", hash.trim(), "--", "notes.md"]),
"an unfiltered file keeps git's own diff, commit header and all"
);
// And what git stores for the filtered file is still the cleaned
// form: only croft's reading of it changed.
assert!(sh_git(tmp.path(), &["show", "HEAD~1:data.txt"]).starts_with("ebj 1"));
}
#[test]
fn a_driver_named_like_a_check_attr_state_is_still_a_filter() {
// `git check-attr` prints `filter: set` both for a bare `filter` and
// for `filter=set`; the configured driver tells them apart.
for name in ["set", "unset", "unspecified"] {
let tmp = TempDir::new().unwrap();
filtered_repo_with(tmp.path(), name);
assert_eq!(path_filter(tmp.path(), "data.txt").as_deref(), Some(name));
let head = read_file_at_head(tmp.path(), "data.txt").unwrap();
assert_eq!(head.lines().next(), Some("row 1"), "{name}");
let patch = head_vs_work_patch(tmp.path(), "data.txt");
let err = apply_patch(tmp.path(), &patch, true, false).unwrap_err();
assert!(err.contains(&format!("the {name} filter")), "{err}");
}
}
#[test]
fn a_bare_or_unset_filter_attribute_names_no_filter() {
// Negative: with no driver behind them these are not filters.
let tmp = TempDir::new().unwrap();
filtered_repo(tmp.path());
std::fs::write(
tmp.path().join(".gitattributes"),
"*.txt filter=rot13\nbare.md filter\noff.md -filter\n",
)
.unwrap();
assert_eq!(path_filter(tmp.path(), "bare.md"), None);
assert_eq!(path_filter(tmp.path(), "off.md"), None);
assert_eq!(path_filter(tmp.path(), "notes.md"), None);
assert_eq!(
path_filter(tmp.path(), "data.txt").as_deref(),
Some("rot13")
);
}
#[test]
fn an_unfiltered_file_beside_a_filtered_one_still_stages_a_hunk() {
let tmp = TempDir::new().unwrap();
filtered_repo(tmp.path());
let patch = head_vs_work_patch(tmp.path(), "notes.md");
apply_patch(tmp.path(), &patch, true, false).unwrap();
assert!(sh_git(tmp.path(), &["diff", "--cached"]).contains("+row FIVE"));
}
/// A repository with `src/main.rs` committed on `main` and `origin` at
/// `url`; `pushed` fakes the push with a remote-tracking ref.
fn share_repo(url: &str, pushed: bool) -> (tempfile::TempDir, PathBuf, String) {
let tmp = tempfile::tempdir().unwrap();
let p = tmp.path();
init_repo_with_commit(p);
std::fs::create_dir(p.join("src")).unwrap();
std::fs::write(
p.join("src/main.rs"),
"fn main() {\n println!(\"hi\");\n}\n",
)
.unwrap();
let git = |args: &[&str]| {
assert!(
Command::new("git")
.arg("-C")
.arg(p)
.args(args)
.status()
.unwrap()
.success()
);
};
git(&["add", "."]);
git(&["commit", "-q", "-m", "main"]);
git(&["remote", "add", "origin", url]);
if pushed {
git(&["update-ref", "refs/remotes/origin/main", "HEAD"]);
}
let sha = run_git(p, &["rev-parse", "HEAD"]).unwrap();
let file = p.join("src/main.rs");
(tmp, file, sha)
}
/// #1610: the permalink names HEAD's commit and the selected lines, the
/// same from an ssh or an https origin; the head link names the branch.
#[test]
fn share_links_name_the_commit_or_branch_and_the_lines() {
for url in [
"git@github.com:acme/widgets.git",
"https://github.com/acme/widgets",
] {
let (_tmp, file, sha) = share_repo(url, true);
assert_eq!(
share_link(&file, Some((2, 4)), LinkRev::Commit).unwrap(),
format!("https://github.com/acme/widgets/blob/{sha}/src/main.rs#L2-L4")
);
assert_eq!(
share_link(&file, Some((2, 2)), LinkRev::Branch).unwrap(),
"https://github.com/acme/widgets/blob/main/src/main.rs#L2"
);
}
let (_tmp, file, sha) = share_repo("git@gitlab.com:acme/widgets.git", true);
assert_eq!(
share_link(&file, Some((1, 3)), LinkRev::Commit).unwrap(),
format!("https://gitlab.com/acme/widgets/-/blob/{sha}/src/main.rs#L1-3")
);
}
/// #1610 negatives: an unpushed commit or branch, an uncommitted file,
/// an unknown host and a repository with no remote each say why instead
/// of giving a link that would not open.
#[test]
fn share_links_refuse_what_the_remote_cannot_show() {
let (tmp, file, sha) = share_repo("git@github.com:acme/widgets.git", false);
let err = share_link(&file, None, LinkRev::Commit).unwrap_err();
assert!(
err.contains(&sha[..7]) && err.contains("push it first"),
"{err}"
);
let err = share_link(&file, None, LinkRev::Branch).unwrap_err();
assert!(err.contains("branch main is not on origin"), "{err}");
std::fs::write(tmp.path().join("src/new.rs"), "x\n").unwrap();
let _ = Command::new("git")
.arg("-C")
.arg(tmp.path())
.args(["update-ref", "refs/remotes/origin/main", "HEAD"])
.status();
let err = share_link(&tmp.path().join("src/new.rs"), None, LinkRev::Commit).unwrap_err();
assert!(err.contains("src/new.rs is not committed"), "{err}");
// Staged but not committed is still not on the remote.
let git = |args: &[&str]| {
assert!(
Command::new("git")
.arg("-C")
.arg(tmp.path())
.args(args)
.status()
.unwrap()
.success()
);
};
git(&["add", "src/new.rs"]);
let err = share_link(&tmp.path().join("src/new.rs"), None, LinkRev::Commit).unwrap_err();
assert!(err.contains("src/new.rs is not committed"), "{err}");
// A local commit the tracking branch does not have yet.
git(&["commit", "-q", "-m", "local"]);
let err = share_link(&file, None, LinkRev::Branch).unwrap_err();
assert!(err.contains("branch main on origin is behind"), "{err}");
let (_t, file, _) = share_repo("git@git.example.com:acme/widgets.git", true);
let err = share_link(&file, None, LinkRev::Commit).unwrap_err();
assert!(
err.contains("not a GitHub, GitLab or Bitbucket remote"),
"{err}"
);
let bare = tempfile::tempdir().unwrap();
init_repo_with_commit(bare.path());
let err = share_link(&bare.path().join("seed.txt"), None, LinkRev::Commit).unwrap_err();
assert_eq!(err, "the repository has no remote to link to");
let outside = tempfile::tempdir().unwrap();
std::fs::write(outside.path().join("a.txt"), "x").unwrap();
assert!(share_link(&outside.path().join("a.txt"), None, LinkRev::Commit).is_err());
}
}