Lutra/crates/engine/tests/git_merge.rs
danny 68599fa2ac A3: add untracked files to .gitignore from the Changes context menu
git.ignore appends one anchored, escaped literal pattern per path to the
work tree root's .gitignore, skipping patterns already there. The Changes
window gets a row context menu (right click, Shift+F10, context-menu key)
with Open and Add to .gitignore.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 14:33:42 +01:00

249 lines
7.6 KiB
Rust

//! The merge commands through the engine with pending outcomes:
//! `git.merge` up to date, with conflicts and refused; `git.conflictVersions`;
//! `git.markResolved` and `git.mergeAbort`, each followed by `gitChanged`;
//! `git.mergeMessage`; `git.ignore` (C7 A3); bad params. 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 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()
}
/// Commits everything.
fn commit(dir: &Path, file: &str, text: &str, message: &str) {
std::fs::write(dir.join(file), text).unwrap();
git(dir, &["add", "-A"]);
git(dir, &["commit", "-q", "-m", message]);
}
/// A repository where `main` and `feature` changed the same line of
/// `a.php`.
fn conflicting(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]);
}
commit(dir, "a.php", "<?php\nbase\n", "base");
git(dir, &["branch", "feature"]);
commit(dir, "a.php", "<?php\nmain\n", "main side");
git(dir, &["switch", "-q", "feature"]);
commit(dir, "a.php", "<?php\nfeature\n", "feature side");
git(dir, &["switch", "-q", "main"]);
}
/// 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)
}
/// How many `gitChanged` events arrived since the last call.
fn git_changes(&self) -> usize {
let mut events = self.events.lock().unwrap();
let count = events
.iter()
.filter(|e| matches!(e, Event::GitChanged(_)))
.count();
events.clear();
count
}
}
#[test]
fn merge_conflict_versions_resolve_and_abort() {
if !have_git() {
return;
}
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
conflicting(root);
let host = Host::open(root);
host.git_changes();
let merged = host.run("git.merge", json!({"branch": "feature"})).unwrap();
assert_eq!(
merged,
json!({"result": "conflicts", "conflicts": ["a.php"]})
);
assert_eq!(host.git_changes(), 1);
let versions = host
.run("git.conflictVersions", json!({"path": "a.php"}))
.unwrap();
assert_eq!(
versions,
json!({
"base": "<?php\nbase\n",
"ours": "<?php\nmain\n",
"theirs": "<?php\nfeature\n",
"binary": false,
"tooLarge": false,
})
);
assert_eq!(host.git_changes(), 0);
let prepared = host.run("git.mergeMessage", Value::Null).unwrap();
let text = prepared["message"].as_str().unwrap();
assert!(text.starts_with("Merge branch 'feature'"), "{text}");
assert!(!text.contains('#'), "{text}");
assert_eq!(host.git_changes(), 0);
let again = host.run("git.merge", json!({"branch": "feature"}));
assert!(matches!(again, Err(EngineError::Failed(m)) if m.contains("in progress")));
host.run("git.mergeAbort", Value::Null).unwrap();
assert_eq!(host.git_changes(), 1);
assert_eq!(
host.run("git.mergeMessage", Value::Null).unwrap(),
json!({"message": null})
);
assert_eq!(
std::fs::read_to_string(root.join("a.php")).unwrap(),
"<?php\nmain\n"
);
host.run("git.merge", json!({"branch": "feature"})).unwrap();
std::fs::write(root.join("a.php"), "<?php\nboth\n").unwrap();
host.git_changes();
host.run("git.markResolved", json!({"paths": ["a.php"]}))
.unwrap();
assert_eq!(host.git_changes(), 1);
let status = host.run("git.status", Value::Null).unwrap();
assert_eq!(status["files"][0]["index"], "modified");
assert!(
host.run("git.conflictVersions", json!({"path": "a.php"}))
.is_err()
);
host.run("git.commit", json!({"message": "Merge feature"}))
.unwrap();
let up_to_date = host.run("git.merge", json!({"branch": "feature"})).unwrap();
assert_eq!(up_to_date, json!({"result": "upToDate", "conflicts": []}));
}
#[test]
fn bad_params_and_no_project() {
if !have_git() {
return;
}
let dir = tempfile::tempdir().unwrap();
conflicting(dir.path());
let host = Host::open(dir.path());
for (command, params) in [
("git.merge", json!({})),
("git.merge", json!({"branch": "-x"})),
("git.markResolved", json!({"paths": []})),
("git.conflictVersions", json!({"path": 3})),
("git.ignore", json!({"paths": []})),
("git.ignore", json!({"paths": ["../x"]})),
] {
assert!(
matches!(
host.run(command, params.clone()),
Err(EngineError::InvalidParams { .. })
),
"{command} {params}"
);
}
let bare = Host {
engine: Mutex::new(Engine::new().unwrap()),
events: Mutex::new(Vec::new()),
};
assert!(matches!(
bare.run("git.mergeAbort", Value::Null),
Err(EngineError::Disabled(_))
));
}
#[test]
fn ignore_appends_a_literal_pattern_and_refreshes() {
if !have_git() {
return;
}
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
conflicting(root);
std::fs::write(root.join("debug[1].log"), "x").unwrap();
std::fs::write(root.join("debug1.log"), "x").unwrap();
let host = Host::open(root);
host.git_changes();
let out = host
.run("git.ignore", json!({"paths": ["debug[1].log"]}))
.unwrap();
assert_eq!(out["patterns"].as_array().unwrap().len(), 1);
assert_eq!(host.git_changes(), 1);
let status = host.run("git.status", Value::Null).unwrap();
let paths: Vec<&str> = status["files"]
.as_array()
.unwrap()
.iter()
.map(|f| f["path"].as_str().unwrap())
.collect();
assert!(paths.contains(&"debug1.log"), "{paths:?}");
assert!(paths.contains(&".gitignore"), "{paths:?}");
assert!(!paths.contains(&"debug[1].log"), "{paths:?}");
}