M4.1: Git backend through the installed git

New crate lutra-vcs (L3): a safe git runner (argument arrays, no prompts,
GIT_OPTIONAL_LOCKS=0 for reads, timeouts 30 s / 120 s for hooks, output
caps, one spawn function for H1's kill-on-close helper), porcelain v2 / -z
parsers (property-tested), Repo operations (status, stage, unstage before
the first commit, commit and amend, show at HEAD/index, branches, checkout
with remote tracking, branch creation checked by check-ref-format) and a
.git poll (RepoWatch).

Engine: git.status, git.stage, git.unstage, git.commit, git.show,
git.branches, git.checkout, git.createBranch on pending outcomes, off the
engine lock; gitChanged after changes and debounced 300 ms on .git or
project changes; setting git.executable (section Git).

Tests against real temp repositories, engine tests through run_waiting,
docs (architecture, gaps G8, Git parity row, roadmap M4 row).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
danny 2026-10-25 13:23:13 +01:00
parent cd8c34b094
commit 13e7b0aa12
28 changed files with 3485 additions and 9 deletions

View file

@ -0,0 +1,887 @@
//! Git commands (M4.1, owner decision D20): status, stage, unstage, commit,
//! file contents at HEAD or in the index, branches, checkout and branch
//! creation, through the user's installed git (`lutra-vcs`).
//!
//! **Off the lock.** git can take seconds (a big status, a commit hook), so
//! every command returns a pending outcome ([`crate::Pending`]): under the
//! lock it only parses its params and takes what it needs from the state;
//! a thread then detects git (once per `git.executable` value), opens the
//! repository containing the project root (once per project), runs the
//! call and puts the [`Reply`] into a slot. The finish, under the lock
//! again, caches git and the repository, starts the `.git` watch and
//! returns the value. Calls that change the repository are serialised per
//! repository inside `lutra-vcs`.
//!
//! **`gitChanged`** (`{available, repo, filesChanged}`) follows every
//! successful change, and, debounced by 300 ms (at most 2 s after the first
//! change), changes the `.git` watch sees (HEAD, index, refs) or the
//! project watcher reports. Clients re-query `git.status`.
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::mpsc::{self, Receiver, TryRecvError};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::{Duration, Instant};
use lutra_vcs::{Branch, FileStatus, Git, Head, Repo, RepoWatch, Rev, VcsError};
use lutra_vfs::VfsEvent;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use super::params::{parse, project_path};
use crate::workspace::path_string;
use crate::{Command, CommandSpec, EngineError, Event, Outcome, Pending, Registry, State};
/// The setting naming the git program; empty means `git` from `PATH`.
pub const EXECUTABLE_SETTING: &str = "git.executable";
/// How long after the last noticed change `gitChanged` is sent.
pub const DEBOUNCE: Duration = Duration::from_millis(300);
/// Longest delay of `gitChanged` while changes keep coming.
const DEBOUNCE_MAX: Duration = Duration::from_secs(2);
/// How often the `.git` watch polls.
const WATCH_INTERVAL: Duration = Duration::from_millis(250);
/// Most git calls running at once; more are refused.
const MAX_RUNNING: usize = 32;
/// Longest wait for a call: detection, opening and a hook-running call,
/// each with its own timeout, plus slack. The runner kills git first.
const WAIT: Duration = Duration::from_secs(200);
/// Registers the `git.*` commands.
///
/// # Errors
/// [`EngineError::Internal`] if an id is taken.
pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
registry.register(Box::new(StatusCommand))?;
registry.register(Box::new(Stage))?;
registry.register(Box::new(Unstage))?;
registry.register(Box::new(Commit))?;
registry.register(Box::new(Show))?;
registry.register(Box::new(BranchesCommand))?;
registry.register(Box::new(Checkout))?;
registry.register(Box::new(CreateBranch))?;
Ok(())
}
/// The repository of the open project and its watch.
#[derive(Debug)]
struct Opened {
/// The project root it was opened from.
project: PathBuf,
/// The repository.
repo: Arc<Repo>,
/// Polls `.git`.
watch: RepoWatch,
}
/// Git state of the engine.
#[derive(Debug, Default)]
pub struct GitState {
/// The detected git and the setting value it was detected for.
git: Option<(String, Arc<Git>)>,
/// The repository of the open project, once a command found it.
opened: Option<Opened>,
/// When the pending `gitChanged` is due, and when the first change
/// behind it was seen.
due: Option<(Instant, Instant)>,
/// A running summary query for `gitChanged`.
refresh: Option<Receiver<Result<Head, VcsError>>>,
/// Git calls running now.
running: Arc<AtomicUsize>,
}
/// The repository part of `git.status` and `gitChanged`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RepoSummary {
/// The work tree root as git prints it (absolute, `/` separators).
pub root: String,
/// The current branch; absent when detached.
#[serde(skip_serializing_if = "Option::is_none")]
pub branch: Option<String>,
/// HEAD is detached.
pub detached: bool,
/// The commit of HEAD; absent before the first commit.
#[serde(skip_serializing_if = "Option::is_none")]
pub head: Option<String>,
/// The upstream branch, e.g. `origin/main`.
#[serde(skip_serializing_if = "Option::is_none")]
pub upstream: Option<String>,
/// Commits ahead of the upstream.
#[serde(skip_serializing_if = "Option::is_none")]
pub ahead: Option<u64>,
/// Commits behind the upstream.
#[serde(skip_serializing_if = "Option::is_none")]
pub behind: Option<u64>,
}
impl RepoSummary {
/// The summary of `repo` with HEAD `head`.
fn new(repo: &Repo, head: Head) -> Self {
Self {
root: path_string(repo.root()),
branch: head.branch,
detached: head.detached,
head: head.head,
upstream: head.upstream,
ahead: head.ahead,
behind: head.behind,
}
}
}
/// Payload of [`Event::GitChanged`]: the repository may have changed;
/// refetch `git.status`.
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GitChanged {
/// git is usable.
pub available: bool,
/// The repository, as in `git.status`.
pub repo: Option<RepoSummary>,
/// Files may have changed; always true for now.
pub files_changed: bool,
}
/// What a git thread hands back to the finish.
struct Reply {
/// git, when it was detected by this call.
git: Option<(String, Arc<Git>)>,
/// The repository, when it was opened by this call.
opened: Option<Arc<Repo>>,
/// The command's value or error.
value: Result<Value, EngineError>,
/// After a successful change: HEAD for `gitChanged`.
changed: Option<Head>,
}
/// What a git thread needs, taken from the state under the lock.
struct Job {
/// The command id, for errors.
command: &'static str,
/// The `git.executable` setting.
setting: String,
/// git, if already detected for this setting.
git: Option<Arc<Git>>,
/// The project root.
project: PathBuf,
/// The repository, if already opened.
repo: Option<Arc<Repo>>,
}
/// What one command does on its thread.
enum Op {
/// `git.status`.
Status,
/// `git.stage`.
Stage(Vec<String>),
/// `git.unstage`.
Unstage(Vec<String>),
/// `git.commit`.
Commit {
/// The message.
message: String,
/// Amend the last commit.
amend: bool,
},
/// `git.show`.
Show(String, Rev),
/// `git.branches`.
Branches,
/// `git.checkout`.
Checkout(String),
/// `git.createBranch`.
CreateBranch {
/// The new branch.
name: String,
/// Its start.
from: Option<String>,
/// Check it out.
checkout: bool,
},
}
impl Op {
/// Whether the call changes the repository (and sends `gitChanged`).
fn mutates(&self) -> bool {
!matches!(self, Self::Status | Self::Show(..) | Self::Branches)
}
}
/// Turns a backend error into the engine's: the caller's mistakes are
/// `invalid_params`, everything else `failed`.
fn engine_error(command: &str, error: VcsError) -> EngineError {
if error.is_invalid_input() {
EngineError::invalid_params(command, error.to_string())
} else {
EngineError::Failed(error.to_string())
}
}
/// Runs `op` on a new thread and returns the pending outcome.
///
/// # Errors
/// [`EngineError::Disabled`] without a project, [`EngineError::Failed`]
/// when [`MAX_RUNNING`] calls are running already.
fn start(state: &mut State, command: &'static str, op: Op) -> Result<Outcome, EngineError> {
let project = state
.project
.as_ref()
.ok_or_else(|| EngineError::Disabled(command.to_string()))?
.project
.root()
.to_path_buf();
let setting = state
.settings
.get(EXECUTABLE_SETTING)
.and_then(|v| v.as_str().map(str::to_string))
.unwrap_or_default();
let git_state = &mut state.git;
if git_state
.opened
.as_ref()
.is_some_and(|o| o.project != project)
{
git_state.opened = None;
git_state.due = None;
git_state.refresh = None;
}
let git = git_state
.git
.as_ref()
.filter(|(s, _)| *s == setting)
.map(|(_, g)| Arc::clone(g));
let repo = git_state.opened.as_ref().map(|o| Arc::clone(&o.repo));
let running = Arc::clone(&git_state.running);
if running.fetch_add(1, Ordering::SeqCst) >= MAX_RUNNING {
running.fetch_sub(1, Ordering::SeqCst);
return Err(EngineError::Failed(
"too many git operations are running".into(),
));
}
let job = Job {
command,
setting,
git,
project: project.clone(),
repo,
};
let slot: Arc<Mutex<Option<Reply>>> = Arc::new(Mutex::new(None));
let (tx, rx) = mpsc::channel();
let filled = Arc::clone(&slot);
let spawned = std::thread::Builder::new()
.name("lutra-git".into())
.spawn(move || {
let reply = work(job, &op);
*filled.lock().unwrap_or_else(PoisonError::into_inner) = Some(reply);
running.fetch_sub(1, Ordering::SeqCst);
let _ = tx.send(Ok(Value::Null));
});
if let Err(e) = spawned {
state.git.running.fetch_sub(1, Ordering::SeqCst);
return Err(EngineError::Failed(format!("cannot start git: {e}")));
}
Ok(Outcome::pending(Pending::new(rx, WAIT, move |state, _| {
let reply = slot
.lock()
.unwrap_or_else(PoisonError::into_inner)
.take()
.ok_or_else(|| EngineError::Failed("git did not answer in time".into()))?;
finish(state, &project, reply)
})))
}
/// The thread's work: detect git and open the repository if needed, then
/// run `op`. The reply's sender is ignored when it fails: the waiter then
/// reports no answer.
fn work(job: Job, op: &Op) -> Reply {
let command = job.command;
let mut reply = Reply {
git: None,
opened: None,
value: Ok(Value::Null),
changed: None,
};
let git = match job.git {
Some(git) => git,
None => match Git::detect(&job.setting) {
Ok(git) => {
let git = Arc::new(git);
reply.git = Some((job.setting.clone(), Arc::clone(&git)));
git
}
Err(e) => {
reply.value = match op {
Op::Status => Ok(unavailable(&e)),
_ => Err(EngineError::Failed(e.to_string())),
};
return reply;
}
},
};
let repo = match job.repo {
Some(repo) => repo,
None => match git.open(&job.project) {
Ok(Some(repo)) => {
let repo = Arc::new(repo);
reply.opened = Some(Arc::clone(&repo));
repo
}
Ok(None) => {
reply.value = match op {
Op::Status => Ok(json!({"available": true, "repo": null, "files": []})),
_ => Err(EngineError::Failed(
"the project is not inside a Git repository".into(),
)),
};
return reply;
}
Err(e) => {
reply.value = match op {
Op::Status => Ok(json!({
"available": true,
"error": e.to_string(),
"repo": null,
"files": [],
})),
_ => Err(EngineError::Failed(e.to_string())),
};
return reply;
}
},
};
reply.value = run_op(&repo, op).map_err(|e| engine_error(command, e));
if reply.value.is_ok() && op.mutates() {
reply.changed = Some(repo.head().unwrap_or_default());
}
reply
}
/// `git.status`'s value without a usable git.
fn unavailable(error: &VcsError) -> Value {
json!({"available": false, "error": error.to_string(), "repo": null, "files": []})
}
/// One file of `git.status`.
fn file_json(file: &FileStatus) -> Value {
let mut value = json!({
"path": file.path,
"index": file.index.as_str(),
"worktree": file.worktree.as_str(),
});
if let (Some(orig), Some(map)) = (&file.orig_path, value.as_object_mut()) {
map.insert("origPath".into(), json!(orig));
}
value
}
/// One branch of `git.branches`.
fn branch_json(branch: &Branch, local: bool) -> Value {
let mut value = json!({"name": branch.name, "head": branch.head});
if let (true, Some(up), Some(map)) = (local, &branch.upstream, value.as_object_mut()) {
map.insert("upstream".into(), json!(up));
}
value
}
/// Runs one operation against the repository.
fn run_op(repo: &Repo, op: &Op) -> Result<Value, VcsError> {
match op {
Op::Status => {
let status = repo.status()?;
let files: Vec<Value> = status.files.iter().map(file_json).collect();
Ok(json!({
"available": true,
"repo": RepoSummary::new(repo, status.head),
"files": files,
}))
}
Op::Stage(paths) => repo.stage(paths).map(|()| json!({})),
Op::Unstage(paths) => repo.unstage(paths).map(|()| json!({})),
Op::Commit { message, amend } => {
let info = repo.commit(message, *amend)?;
Ok(json!({"commit": info.commit, "summary": info.summary}))
}
Op::Show(path, rev) => {
let contents = repo.show(path, *rev)?;
Ok(json!({
"text": contents.text,
"binary": contents.binary,
"tooLarge": contents.too_large,
}))
}
Op::Branches => {
let branches = repo.branches()?;
let local: Vec<Value> = branches
.local
.iter()
.map(|b| branch_json(b, true))
.collect();
let remote: Vec<Value> = branches
.remote
.iter()
.map(|b| branch_json(b, false))
.collect();
Ok(json!({"current": branches.current, "local": local, "remote": remote}))
}
Op::Checkout(branch) => repo.checkout(branch).map(|()| json!({})),
Op::CreateBranch {
name,
from,
checkout,
} => repo
.create_branch(name, from.as_deref(), *checkout)
.map(|()| json!({})),
}
}
/// Under the lock again: caches what the thread found (unless the project
/// or the setting changed meanwhile), starts the `.git` watch, sends
/// `gitChanged` after a change, and returns the value.
///
/// # Errors
/// The command's error.
fn finish(state: &mut State, project: &Path, reply: Reply) -> Result<Value, EngineError> {
let current = state
.project
.as_ref()
.map(|w| w.project.root().to_path_buf());
let same_project = current.as_deref() == Some(project);
let setting = state
.settings
.get(EXECUTABLE_SETTING)
.and_then(|v| v.as_str().map(str::to_string))
.unwrap_or_default();
if let Some((detected_for, git)) = reply.git
&& detected_for == setting
{
state.git.git = Some((detected_for, git));
}
if let Some(repo) = reply.opened
&& same_project
&& state.git.opened.is_none()
{
let watch = RepoWatch::start(repo.git_dir(), repo.common_dir(), WATCH_INTERVAL);
state.git.opened = Some(Opened {
project: project.to_path_buf(),
repo,
watch,
});
}
if let Some(head) = reply.changed
&& same_project
&& let Some(opened) = &state.git.opened
{
opened.watch.rebase();
let summary = RepoSummary::new(&opened.repo, head);
state.git.due = None;
state.emit(Event::GitChanged(GitChanged {
available: true,
repo: Some(summary),
files_changed: true,
}));
}
reply.value
}
/// Notes changes the project watcher saw; `gitChanged` follows after the
/// debounce if a repository is open.
pub fn note_disk_changes(state: &mut State, changes: &[VfsEvent]) {
if !changes.is_empty() && state.git.opened.is_some() {
schedule(&mut state.git, Instant::now());
}
}
/// Moves the `gitChanged` deadline to `now` + [`DEBOUNCE`], but never more
/// than [`DEBOUNCE_MAX`] after the first change behind it.
fn schedule(git: &mut GitState, now: Instant) {
let first = git.due.map_or(now, |(_, first)| first);
let due = (now + DEBOUNCE).min(first + DEBOUNCE_MAX);
git.due = Some((due, first));
}
/// Sends `gitChanged` when it is due: checks the `.git` watch, starts a
/// summary query on its own thread when the debounce ran out, and emits
/// the event when that query answers. A project change drops the
/// repository. Called from [`crate::Engine::pump_vfs`].
pub fn pump(state: &mut State) {
let root = state.project.as_ref().map(|w| w.project.root());
let stale = match (&state.git.opened, root) {
(Some(opened), Some(root)) => opened.project != root,
(Some(_), None) => true,
(None, _) => false,
};
if stale {
state.git.opened = None;
state.git.due = None;
state.git.refresh = None;
}
let now = Instant::now();
if state.git.opened.as_ref().is_some_and(|o| o.watch.changed()) {
schedule(&mut state.git, now);
}
if let Some(rx) = &state.git.refresh {
match rx.try_recv() {
Ok(head) => {
state.git.refresh = None;
let repo = state
.git
.opened
.as_ref()
.map(|o| RepoSummary::new(&o.repo, head.unwrap_or_default()));
if repo.is_some() {
state.emit(Event::GitChanged(GitChanged {
available: true,
repo,
files_changed: true,
}));
}
}
Err(TryRecvError::Empty) => return,
Err(TryRecvError::Disconnected) => state.git.refresh = None,
}
}
let Some((due, _)) = state.git.due else {
return;
};
if now < due {
return;
}
let Some(opened) = &state.git.opened else {
state.git.due = None;
return;
};
state.git.due = None;
let repo = Arc::clone(&opened.repo);
let (tx, rx) = mpsc::channel();
let spawned = std::thread::Builder::new()
.name("lutra-git-refresh".into())
.spawn(move || {
let _ = tx.send(repo.head());
});
if spawned.is_ok() {
state.git.refresh = Some(rx);
}
}
/// Resolves a path param to a project-relative path with `/`.
fn rel_path(state: &State, command: &str, path: &str) -> Result<String, EngineError> {
Ok(path_string(&project_path(state, command, path)?))
}
/// Params of `git.stage` and `git.unstage`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct PathsParams {
/// Project-relative (or absolute, inside the project) paths.
paths: Vec<String>,
}
/// Resolves `{paths}`.
fn paths(state: &State, command: &str, params: Value) -> Result<Vec<String>, EngineError> {
let p: PathsParams = parse(command, params)?;
if p.paths.is_empty() {
return Err(EngineError::invalid_params(command, "paths is empty"));
}
p.paths
.iter()
.map(|path| rel_path(state, command, path))
.collect()
}
/// `git.status`.
struct StatusCommand;
impl Command for StatusCommand {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.status",
label: "Git Status",
menu_path: None,
default_shortcut: None,
params: "none; returns { available, error?, repo: { root, branch?, detached, head?, upstream?, ahead?, behind? } | null, files: [{ path, origPath?, index, worktree }] } with states unmodified|modified|added|deleted|renamed|copied|untracked|ignored|conflicted; repo is null outside a repository, available false without a usable git (2.30+)",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let _: serde_json::Map<String, Value> = parse(command, params)?;
start(state, command, Op::Status)
}
}
/// `git.stage`.
struct Stage;
impl Command for Stage {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.stage",
label: "Git: Stage Files",
menu_path: None,
default_shortcut: None,
params: "{ paths: [project-relative path] } (new, changed and deleted files); returns {}",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let paths = paths(state, command, params)?;
start(state, command, Op::Stage(paths))
}
}
/// `git.unstage`.
struct Unstage;
impl Command for Unstage {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.unstage",
label: "Git: Unstage Files",
menu_path: None,
default_shortcut: None,
params: "{ paths: [project-relative path] } (pass both paths of a staged rename); works before the first commit; the work tree is not touched; returns {}",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let paths = paths(state, command, params)?;
start(state, command, Op::Unstage(paths))
}
}
/// Params of `git.commit`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CommitParams {
/// The message.
message: String,
/// Amend the last commit.
#[serde(default)]
amend: bool,
}
/// `git.commit`.
struct Commit;
impl Command for Commit {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.commit",
label: "Git: Commit Staged Changes",
menu_path: None,
default_shortcut: None,
params: "{ message: non-blank string, amend?: bool (false) }; commits what is staged, hooks run (120 s); returns { commit, summary }; a failing hook's output is the error message (16 KiB at most)",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: CommitParams = parse(command, params)?;
if p.message.trim().is_empty() {
return Err(engine_error(command, VcsError::EmptyMessage));
}
start(
state,
command,
Op::Commit {
message: p.message,
amend: p.amend,
},
)
}
}
/// Which version `git.show` returns.
#[derive(Debug, Clone, Copy, Deserialize)]
enum RefParam {
/// The last commit.
#[serde(rename = "HEAD")]
Head,
/// The staged version.
#[serde(rename = "index")]
Index,
}
/// Params of `git.show`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct ShowParams {
/// The file.
path: String,
/// The version.
#[serde(rename = "ref")]
rev: RefParam,
}
/// `git.show`.
struct Show;
impl Command for Show {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.show",
label: "Git: Show File at Revision",
menu_path: None,
default_shortcut: None,
params: "{ path: project-relative path, ref: \"HEAD\" | \"index\" }; returns { text: string | null, binary, tooLarge } (null when the path does not exist there, is binary or larger than 32 MiB); the blob as stored, without filters or line-ending conversion",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: ShowParams = parse(command, params)?;
let path = rel_path(state, command, &p.path)?;
let rev = match p.rev {
RefParam::Head => Rev::Head,
RefParam::Index => Rev::Index,
};
start(state, command, Op::Show(path, rev))
}
}
/// `git.branches`.
struct BranchesCommand;
impl Command for BranchesCommand {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.branches",
label: "Git: Branches",
menu_path: None,
default_shortcut: None,
params: "none; returns { current: string | null, local: [{ name, head, upstream? }], remote: [{ name, head }] }, sorted by name",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let _: serde_json::Map<String, Value> = parse(command, params)?;
start(state, command, Op::Branches)
}
}
/// Params of `git.checkout`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CheckoutParams {
/// A local branch, or a remote one (`origin/x`) to track.
branch: String,
}
/// `git.checkout`.
struct Checkout;
impl Command for Checkout {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.checkout",
label: "Git: Check Out Branch",
menu_path: None,
default_shortcut: None,
params: "{ branch: local branch, or remote branch such as origin/x (creates a local tracking branch) }; returns {}; fails with git's message when git refuses (local changes would be overwritten). Save dirty buffers first.",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: CheckoutParams = parse(command, params)?;
start(state, command, Op::Checkout(p.branch))
}
}
/// Params of `git.createBranch`.
#[derive(Debug, Deserialize)]
#[serde(deny_unknown_fields)]
struct CreateBranchParams {
/// The new branch.
name: String,
/// Where it starts; HEAD when absent.
#[serde(default)]
from: Option<String>,
/// Check it out as well.
checkout: bool,
}
/// `git.createBranch`.
struct CreateBranch;
impl Command for CreateBranch {
fn spec(&self) -> &CommandSpec {
&CommandSpec {
id: "git.createBranch",
label: "Git: New Branch",
menu_path: None,
default_shortcut: None,
params: "{ name: branch name (checked with git check-ref-format --branch), from?: revision (HEAD), checkout: bool }; returns {}",
}
}
fn enabled(&self, state: &State) -> bool {
state.has_project()
}
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
let command = self.spec().id;
let p: CreateBranchParams = parse(command, params)?;
start(
state,
command,
Op::CreateBranch {
name: p.name,
from: p.from,
checkout: p.checkout,
},
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debounce_waits_but_not_forever() {
let mut git = GitState::default();
let start = Instant::now();
schedule(&mut git, start);
assert_eq!(git.due.map(|d| d.0), Some(start + DEBOUNCE));
let later = start + Duration::from_millis(1900);
schedule(&mut git, later);
assert_eq!(git.due.map(|d| d.0), Some(start + DEBOUNCE_MAX));
}
}

View file

@ -3,6 +3,7 @@
mod app;
mod buffer;
mod file;
pub mod git;
pub mod goto;
mod lsp_assist;
mod lsp_diagnostics;
@ -64,5 +65,6 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
lsp_diagnostics::register(registry)?;
lsp_assist::register(registry)?;
lsp_nav::register(registry)?;
git::register(registry)?;
Ok(())
}

View file

@ -152,6 +152,7 @@ impl Engine {
cmd::toolchain::pump(state);
cmd::terminal::pump(state);
crate::lsp::pump(state);
cmd::git::pump(state);
Ok(())
})?;
Ok(state.take_events())
@ -472,6 +473,14 @@ mod tests {
"file.open",
"file.save",
"file.saveAll",
"git.branches",
"git.checkout",
"git.commit",
"git.createBranch",
"git.show",
"git.stage",
"git.status",
"git.unstage",
"goto.class",
"goto.file",
"goto.symbol",

View file

@ -203,6 +203,8 @@ pub enum Event {
/// The diagnostics of one file changed: `{path, items}`; empty items
/// mean the file has none any more. Fetch all with `diagnostics.list`.
DiagnosticsChanged(crate::lsp::FileDiagnostics),
/// The Git repository may have changed: `{available, repo, filesChanged}`; refetch `git.status` (M4.1).
GitChanged(crate::cmd::git::GitChanged),
/// Terminal events (`terminalOutput`, `terminalExited`), see [`crate::cmd::terminal`].
#[serde(untagged)]
Terminal(crate::cmd::terminal::TerminalEvent),

View file

@ -275,6 +275,14 @@ pub const DEFS: &[Def] = &[
description_key: "settings.editor.hover.delayMs.description",
section: "editor",
},
Def {
key: "git.executable",
kind: Kind::Str { max_len: 4096 },
default: DefaultValue::Str(""),
label_key: "settings.git.executable.label",
description_key: "settings.git.executable.description",
section: "git",
},
];
/// Looks a known setting up by key.

View file

@ -47,6 +47,8 @@ pub struct State {
pub terminals: crate::cmd::terminal::Terminals,
/// The language server session and its diagnostics (M3.3).
pub lsp: crate::lsp::Lsp,
/// git and the project's repository (`git.*`, M4.1).
pub git: crate::cmd::git::GitState,
/// Number of notifications emitted, for their ids.
notifications: u64,
/// Events queued for the host, oldest first.

View file

@ -246,6 +246,7 @@ pub fn pump(state: &mut State) {
let (changes, failure) = workspace.drain();
let root = workspace.project.root().to_path_buf();
crate::cmd::goto::note_disk_changes(state, &changes);
crate::cmd::git::note_disk_changes(state, &changes);
let mut dirs: Vec<PathBuf> = Vec::new();
let mut add_dir = |path: &Path| {
let dir = path.parent().map(Path::to_path_buf).unwrap_or_default();