- Disk conflicts per buffer (changed / removed), reported in buffer.get as diskConflict; diskConflictResolved when settled. - Every watcher event only means "look again": delete + create (git checkout, atomic saves) reloads instead of losing the buffer; a file that disappears keeps its buffer as unsaved. - file.save checks mtime + hash and fails with disk_changed instead of overwriting a newer file (overwrite: true after asking); saveAll lists such buffers under diskChanged. New file.reload and file.readDisk. - Local History store in the data dir (content-addressed SHA-256 blobs, index.jsonl, 14 days / 200 MB, pruned on open); snapshots on save, before reloads, on deletion, before lsp.rename and file-changing git commands. Commands history.list / history.read / history.revert. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1021 lines
33 KiB
Rust
1021 lines
33 KiB
Rust
//! Git commands (M4.1, owner decision D20): status, stage, unstage, commit,
|
|
//! the last commit message, file contents at HEAD or in the index,
|
|
//! branches, checkout and branch creation, through the user's installed git (`lutra-vcs`).
|
|
//!
|
|
//! **Off the lock.** git can take seconds (a big status, a commit hook), so
|
|
//! every command returns a pending outcome ([`crate::Pending`]): under the
|
|
//! 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(LastMessage))?;
|
|
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>>,
|
|
}
|
|
|
|
/// A git call defined outside this module, run on the git thread.
|
|
///
|
|
/// **Extension pattern** for new git commands (log, blame, merge, stash):
|
|
/// the backend goes into its own `crates/vcs/src/<area>.rs` as an
|
|
/// `impl Repo` block using the crate-internal `Repo::run`, `check_name` and
|
|
/// `SMALL_CAP`; the commands go into their own `cmd/git_<area>.rs`, whose
|
|
/// `run` resolves paths with [`rel_path`] and calls
|
|
/// `start_with(state, id, mutates, Box::new(move |repo| …))`. That becomes
|
|
/// an [`Op::Custom`] and runs like the commands here: a pending outcome,
|
|
/// git and the repository detected and cached, `gitChanged` after a call
|
|
/// with `mutates`. Neither this file nor `repo.rs` needs another change.
|
|
pub(super) type RepoFn = Box<dyn Fn(&Repo) -> Result<Value, VcsError> + Send>;
|
|
|
|
/// A step run under the lock after a [`start_then`] call succeeded: it
|
|
/// takes the call's value and returns the command's (chunk revert edits
|
|
/// the editor buffer here).
|
|
pub(super) type ThenFn = Box<dyn FnOnce(&mut State, Value) -> Result<Value, EngineError> + Send>;
|
|
|
|
/// 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.lastMessage`.
|
|
LastMessage,
|
|
/// `git.show`.
|
|
Show(String, Rev),
|
|
/// `git.branches`.
|
|
Branches,
|
|
/// `git.checkout`.
|
|
Checkout(String),
|
|
/// A command defined in another module (log, blame, merge, stash),
|
|
/// started through [`start_with`].
|
|
#[allow(
|
|
dead_code,
|
|
reason = "extension hook; constructed once the first module uses start_with"
|
|
)]
|
|
Custom {
|
|
/// Whether it changes the repository (and sends `gitChanged`).
|
|
mutates: bool,
|
|
/// The call against the repository.
|
|
run: RepoFn,
|
|
},
|
|
/// `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 {
|
|
if let Self::Custom { mutates, .. } = self {
|
|
return *mutates;
|
|
}
|
|
!matches!(
|
|
self,
|
|
Self::Status | Self::LastMessage | 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 a git call defined in another module (log, blame, merge, stash)
|
|
/// exactly like the commands here: a pending outcome, git and the
|
|
/// repository detected and cached, `gitChanged` after a change.
|
|
///
|
|
/// # Parameters
|
|
/// - `command`: the command id, for errors.
|
|
/// - `mutates`: the call changes the repository.
|
|
/// - `run`: the call; its errors map like the built-in ones.
|
|
///
|
|
/// # Errors
|
|
/// As [`start`].
|
|
#[allow(
|
|
dead_code,
|
|
reason = "extension hook; used by the history, blame, merge and stash modules"
|
|
)]
|
|
pub(super) fn start_with(
|
|
state: &mut State,
|
|
command: &'static str,
|
|
mutates: bool,
|
|
run: RepoFn,
|
|
) -> Result<Outcome, EngineError> {
|
|
start(state, command, Op::Custom { mutates, run }, None)
|
|
}
|
|
|
|
/// As [`start_with`], then runs `then` under the lock with the call's value
|
|
/// once it succeeded.
|
|
///
|
|
/// # Errors
|
|
/// As [`start`]; the outcome fails with `then`'s error.
|
|
pub(super) fn start_then(
|
|
state: &mut State,
|
|
command: &'static str,
|
|
mutates: bool,
|
|
run: RepoFn,
|
|
then: ThenFn,
|
|
) -> Result<Outcome, EngineError> {
|
|
start(state, command, Op::Custom { mutates, run }, Some(then))
|
|
}
|
|
|
|
/// Runs `op` on a new thread and returns the pending outcome. A command
|
|
/// that changes files first snapshots the open buffers into the Local
|
|
/// History ([`crate::history::before_git`]).
|
|
///
|
|
/// # 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,
|
|
then: Option<ThenFn>,
|
|
) -> Result<Outcome, EngineError> {
|
|
crate::history::before_git(state, command);
|
|
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()))?;
|
|
let value = finish(state, &project, reply)?;
|
|
match then {
|
|
Some(then) => then(state, value),
|
|
None => Ok(value),
|
|
}
|
|
})))
|
|
}
|
|
|
|
/// 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::LastMessage => Ok(json!({"message": repo.last_message()?})),
|
|
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::Custom { run, .. } => run(repo),
|
|
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 `/`.
|
|
pub(super) 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, None)
|
|
}
|
|
}
|
|
|
|
/// `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), None)
|
|
}
|
|
}
|
|
|
|
/// `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), None)
|
|
}
|
|
}
|
|
|
|
/// 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,
|
|
},
|
|
None,
|
|
)
|
|
}
|
|
}
|
|
|
|
/// `git.lastMessage`.
|
|
struct LastMessage;
|
|
|
|
impl Command for LastMessage {
|
|
fn spec(&self) -> &CommandSpec {
|
|
&CommandSpec {
|
|
id: "git.lastMessage",
|
|
label: "Git: Last Commit Message",
|
|
menu_path: None,
|
|
default_shortcut: None,
|
|
params: "none; returns { message: string | null }: the full message of HEAD (trailing line breaks removed), null before the first commit; for prefilling an amend",
|
|
}
|
|
}
|
|
|
|
fn enabled(&self, state: &State) -> bool {
|
|
state.has_project()
|
|
}
|
|
|
|
fn run(&self, state: &mut State, params: Value) -> Result<Outcome, EngineError> {
|
|
let command = self.spec().id;
|
|
let _: serde_json::Map<String, Value> = parse(command, params)?;
|
|
start(state, command, Op::LastMessage, None)
|
|
}
|
|
}
|
|
|
|
/// 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), None)
|
|
}
|
|
}
|
|
|
|
/// `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, None)
|
|
}
|
|
}
|
|
|
|
/// 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), None)
|
|
}
|
|
}
|
|
|
|
/// 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,
|
|
},
|
|
None,
|
|
)
|
|
}
|
|
}
|
|
|
|
/// The ids of the commands this module registers, checked against the
|
|
/// registry by the engine's listing test. Add a new command's id here.
|
|
#[cfg(test)]
|
|
pub(crate) const COMMAND_IDS: &[&str] = &[
|
|
"git.branches",
|
|
"git.checkout",
|
|
"git.commit",
|
|
"git.createBranch",
|
|
"git.lastMessage",
|
|
"git.show",
|
|
"git.stage",
|
|
"git.status",
|
|
"git.unstage",
|
|
];
|
|
|
|
#[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));
|
|
}
|
|
}
|