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

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 17:16:53 +01:00

296 lines
9.3 KiB
Rust

//! The `git.*` commands through the engine, off the lock with pending
//! outcomes: status, stage, commit, show, branches, checkout, branch
//! creation, `gitChanged` after changes and from the `.git` watch, a
//! project outside any repository and a missing git. Skips with a message
//! when git is not installed.
#![allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::indexing_slicing
)]
use std::path::Path;
use std::process::Command;
use std::sync::Mutex;
use std::time::{Duration, Instant};
use lutra_engine::{Engine, EngineError, Event, run_waiting};
use serde_json::{Value, json};
/// Whether git is installed; prints why a test is skipped.
fn have_git() -> bool {
let ok = Command::new("git")
.arg("--version")
.output()
.is_ok_and(|o| o.status.success());
if !ok {
eprintln!("skipped: git is not installed");
}
ok
}
/// Runs git for test setup.
fn git(dir: &Path, args: &[&str]) -> String {
let out = Command::new("git")
.args(args)
.current_dir(dir)
.output()
.unwrap();
assert!(
out.status.success(),
"git {args:?}: {}",
String::from_utf8_lossy(&out.stderr)
);
String::from_utf8_lossy(&out.stdout).trim().to_string()
}
/// A repository with one commit on `main`.
fn repo(dir: &Path) {
git(dir, &["init", "-q", "-b", "main"]);
for (key, value) in [
("user.name", "Lutra Test"),
("user.email", "test@lutra.invalid"),
("commit.gpgsign", "false"),
("core.autocrlf", "false"),
("core.hooksPath", ".git/hooks"),
] {
git(dir, &["config", key, value]);
}
std::fs::write(dir.join("a.php"), "<?php // a\n").unwrap();
git(dir, &["add", "-A"]);
git(dir, &["commit", "-q", "-m", "base"]);
}
/// An engine behind a lock, like a host, recording every event.
struct Host {
/// The engine.
engine: Mutex<Engine>,
/// Events published so far.
events: Mutex<Vec<Event>>,
}
impl Host {
/// An engine with `root` open as the project.
fn open(root: &Path) -> Self {
let host = Self {
engine: Mutex::new(Engine::new().unwrap()),
events: Mutex::new(Vec::new()),
};
host.run("project.open", json!({"path": root})).unwrap();
host
}
/// Runs a command the way hosts do, waiting without the lock.
fn run(&self, command: &str, params: Value) -> Result<Value, EngineError> {
run_waiting(
|| self.engine.lock().unwrap(),
command,
params,
|events| self.events.lock().unwrap().extend_from_slice(events),
)
.map(|o| o.value)
}
/// Takes the `gitChanged` events seen so far.
fn git_changes(&self) -> Vec<Value> {
let mut events = self.events.lock().unwrap();
let taken: Vec<Value> = events
.iter()
.filter(|e| matches!(e, Event::GitChanged(_)))
.map(|e| serde_json::to_value(e).unwrap())
.collect();
events.clear();
taken
}
/// Pumps until a `gitChanged` arrives or `limit` passes.
fn pump_for_change(&self, limit: Duration) -> Option<Value> {
let deadline = Instant::now() + limit;
while Instant::now() < deadline {
let events = self.engine.lock().unwrap().pump_vfs().unwrap();
self.events.lock().unwrap().extend(events);
if let Some(change) = self.git_changes().into_iter().next() {
return Some(change);
}
std::thread::sleep(Duration::from_millis(20));
}
None
}
}
#[test]
fn status_stage_commit_show_and_branches() {
if !have_git() {
return;
}
let dir = tempfile::tempdir().unwrap();
repo(dir.path());
let host = Host::open(dir.path());
let status = host.run("git.status", Value::Null).unwrap();
assert_eq!(status["available"], true);
assert_eq!(status["repo"]["branch"], "main");
assert_eq!(status["repo"]["detached"], false);
assert_eq!(status["files"], json!([]));
std::fs::write(dir.path().join("a.php"), "<?php // changed\n").unwrap();
std::fs::write(dir.path().join("b.php"), "<?php // new\n").unwrap();
let status = host.run("git.status", json!({})).unwrap();
assert_eq!(
status["files"],
json!([
{"path": "a.php", "index": "unmodified", "worktree": "modified"},
{"path": "b.php", "index": "untracked", "worktree": "untracked"},
])
);
host.git_changes();
assert_eq!(
host.run("git.stage", json!({"paths": ["a.php", "b.php"]}))
.unwrap(),
json!({})
);
let changes = host.git_changes();
assert_eq!(changes.len(), 1, "{changes:?}");
assert_eq!(changes[0]["kind"], "gitChanged");
assert_eq!(changes[0]["filesChanged"], true);
assert_eq!(changes[0]["repo"]["branch"], "main");
let show = host
.run("git.show", json!({"path": "a.php", "ref": "index"}))
.unwrap();
assert_eq!(
show,
json!({"text": "<?php // changed\n", "binary": false, "tooLarge": false})
);
let show = host
.run("git.show", json!({"path": "b.php", "ref": "HEAD"}))
.unwrap();
assert_eq!(show["text"], Value::Null);
let err = host
.run("git.commit", json!({"message": " "}))
.unwrap_err();
assert_eq!(err.code(), "invalid_params");
let commit = host
.run("git.commit", json!({"message": "second\n\nbody"}))
.unwrap();
assert_eq!(commit["summary"], "second");
assert_eq!(commit["commit"], git(dir.path(), &["rev-parse", "HEAD"]));
assert_eq!(host.git_changes().len(), 1);
assert_eq!(
host.run("git.lastMessage", Value::Null).unwrap(),
json!({"message": "second\n\nbody"})
);
assert!(host.git_changes().is_empty());
let err = host.run("git.lastMessage", json!([1])).unwrap_err();
assert_eq!(err.code(), "invalid_params");
assert_eq!(
host.run("git.status", Value::Null).unwrap()["files"],
json!([])
);
host.run(
"git.createBranch",
json!({"name": "feature", "checkout": true}),
)
.unwrap();
let branches = host.run("git.branches", Value::Null).unwrap();
assert_eq!(branches["current"], "feature");
assert_eq!(branches["local"].as_array().unwrap().len(), 2);
assert_eq!(branches["remote"], json!([]));
let err = host
.run(
"git.createBranch",
json!({"name": "bad..name", "checkout": false}),
)
.unwrap_err();
assert_eq!(err.code(), "invalid_params");
host.run("git.checkout", json!({"branch": "main"})).unwrap();
assert_eq!(
host.run("git.status", Value::Null).unwrap()["repo"]["branch"],
"main"
);
let err = host
.run("git.stage", json!({"paths": ["../outside.php"]}))
.unwrap_err();
assert_eq!(err.code(), "invalid_params");
let err = host.run("git.stage", json!({"paths": []})).unwrap_err();
assert_eq!(err.code(), "invalid_params");
let err = host
.run("git.show", json!({"path": "a.php", "ref": "main"}))
.unwrap_err();
assert_eq!(err.code(), "invalid_params");
}
#[test]
fn outside_changes_send_git_changed() {
if !have_git() {
return;
}
let dir = tempfile::tempdir().unwrap();
repo(dir.path());
let host = Host::open(dir.path());
host.run("git.status", Value::Null).unwrap();
assert!(host.pump_for_change(Duration::from_millis(600)).is_none());
git(dir.path(), &["branch", "made-outside"]);
let change = host
.pump_for_change(Duration::from_secs(5))
.expect("gitChanged after a new branch");
assert_eq!(change["repo"]["branch"], "main");
git(dir.path(), &["checkout", "-q", "--detach"]);
let change = host
.pump_for_change(Duration::from_secs(5))
.expect("gitChanged after a detach");
assert_eq!(change["repo"]["detached"], true);
assert!(change["repo"].get("branch").is_none());
std::fs::write(dir.path().join("a.php"), "<?php // edited\n").unwrap();
assert!(
host.pump_for_change(Duration::from_secs(5)).is_some(),
"gitChanged after a work tree change"
);
}
#[test]
fn a_project_without_a_repository_and_a_missing_git() {
if !have_git() {
return;
}
let dir = tempfile::tempdir().unwrap();
std::fs::write(dir.path().join("a.php"), "<?php\n").unwrap();
let host = Host::open(dir.path());
let status = host.run("git.status", Value::Null).unwrap();
assert_eq!(
status,
json!({"available": true, "repo": null, "files": []})
);
let err = host
.run("git.stage", json!({"paths": ["a.php"]}))
.unwrap_err();
assert_eq!(err.code(), "failed");
host.run(
"settings.set",
json!({"key": "git.executable", "value": "C:/no/such/git-for-lutra"}),
)
.unwrap();
let status = host.run("git.status", Value::Null).unwrap();
assert_eq!(status["available"], false);
assert!(status["error"].as_str().unwrap().contains("not found"));
assert_eq!(status["repo"], Value::Null);
}
#[test]
fn git_commands_need_a_project() {
let engine = Mutex::new(Engine::new().unwrap());
let err =
run_waiting(|| engine.lock().unwrap(), "git.status", Value::Null, |_| {}).unwrap_err();
assert_eq!(err.code(), "disabled");
}