PM: merge A3 follow-ups: registry-derived command lists, MERGE_MSG prefill, gutter fix, git.ignore, BOM
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
commit
83aeec68c0
47 changed files with 1161 additions and 269 deletions
|
|
@ -53,3 +53,8 @@ impl Command for Quit {
|
|||
Ok(Outcome::effect(Effect::Quit))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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] = &["app.about", "app.quit"];
|
||||
|
|
|
|||
|
|
@ -258,3 +258,9 @@ impl Command for List {
|
|||
Ok(Outcome::value(Value::Array(list)))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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] =
|
||||
&["buffer.close", "buffer.edit", "buffer.get", "buffer.list"];
|
||||
|
|
|
|||
|
|
@ -201,3 +201,8 @@ impl Command for SaveAll {
|
|||
))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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] = &["file.open", "file.save", "file.saveAll"];
|
||||
|
|
|
|||
|
|
@ -955,6 +955,21 @@ impl Command for CreateBranch {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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::*;
|
||||
|
|
|
|||
|
|
@ -114,3 +114,8 @@ impl Command for Blame {
|
|||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.blame"];
|
||||
|
|
|
|||
80
crates/engine/src/cmd/git_ignore.rs
Normal file
80
crates/engine/src/cmd/git_ignore.rs
Normal file
|
|
@ -0,0 +1,80 @@
|
|||
//! `git.ignore` (C7 A3): adds literal patterns for chosen files to the
|
||||
//! work tree's `.gitignore`, on top of `lutra_vcs::Repo::ignore`.
|
||||
//!
|
||||
//! It runs through [`super::git::start_with`] like the other `git.*`
|
||||
//! commands and sends `gitChanged` afterwards, since the status changes.
|
||||
|
||||
use serde::Deserialize;
|
||||
use serde_json::{Value, json};
|
||||
|
||||
use super::git::{rel_path, start_with};
|
||||
use super::params::parse;
|
||||
use crate::{Command, CommandSpec, EngineError, Outcome, Registry, State};
|
||||
|
||||
/// Most paths one call takes.
|
||||
const MAX_PATHS: usize = 10_000;
|
||||
|
||||
/// Registers `git.ignore`.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`EngineError::Internal`] if the id is taken.
|
||||
pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
|
||||
registry.register(Box::new(Ignore))
|
||||
}
|
||||
|
||||
/// Params of `git.ignore`.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct IgnoreParams {
|
||||
/// Project-relative or absolute paths inside the project.
|
||||
paths: Vec<String>,
|
||||
}
|
||||
|
||||
/// `git.ignore`.
|
||||
struct Ignore;
|
||||
|
||||
impl Command for Ignore {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "git.ignore",
|
||||
label: "Git: Add to .gitignore",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "{ paths: [path inside the project] } (1 to 10000); appends one literal pattern per path to the .gitignore at the work tree's root (created when missing): anchored with /, with \\ * ? [ and trailing spaces escaped, so it matches exactly that file or folder; returns { patterns: [added pattern] }, leaving out patterns already in the file",
|
||||
}
|
||||
}
|
||||
|
||||
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: IgnoreParams = parse(command, params)?;
|
||||
if p.paths.is_empty() || p.paths.len() > MAX_PATHS {
|
||||
return Err(EngineError::invalid_params(
|
||||
command,
|
||||
format!("paths takes 1 to {MAX_PATHS} entries"),
|
||||
));
|
||||
}
|
||||
let paths = p
|
||||
.paths
|
||||
.iter()
|
||||
.map(|path| rel_path(state, command, path))
|
||||
.collect::<Result<Vec<_>, _>>()?;
|
||||
start_with(
|
||||
state,
|
||||
command,
|
||||
true,
|
||||
Box::new(move |repo| {
|
||||
let patterns = repo.ignore(&paths)?;
|
||||
Ok(json!({ "patterns": patterns }))
|
||||
}),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.ignore"];
|
||||
|
|
@ -449,6 +449,11 @@ impl Command for LineChanges {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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.lineChanges"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
|||
|
|
@ -221,3 +221,8 @@ impl Command for ShowAt {
|
|||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.log", "git.showAt", "git.showCommit"];
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
//! Merge commands (M4.8): `git.merge`, `git.mergeAbort`,
|
||||
//! `git.conflictVersions` and `git.markResolved`, on top of
|
||||
//! `git.conflictVersions`, `git.markResolved` and `git.mergeMessage`, on top of
|
||||
//! `lutra_vcs::Repo`'s merge calls.
|
||||
//!
|
||||
//! Each runs through [`super::git::start_with`]: a pending outcome, git and
|
||||
|
|
@ -25,6 +25,7 @@ pub fn register(registry: &mut Registry) -> Result<(), EngineError> {
|
|||
registry.register(Box::new(MergeAbort))?;
|
||||
registry.register(Box::new(ConflictVersionsCommand))?;
|
||||
registry.register(Box::new(MarkResolved))?;
|
||||
registry.register(Box::new(MergeMessage))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
|
@ -112,6 +113,36 @@ impl Command for MergeAbort {
|
|||
}
|
||||
}
|
||||
|
||||
/// `git.mergeMessage`.
|
||||
struct MergeMessage;
|
||||
|
||||
impl Command for MergeMessage {
|
||||
fn spec(&self) -> &CommandSpec {
|
||||
&CommandSpec {
|
||||
id: "git.mergeMessage",
|
||||
label: "Git: Prepared Merge Message",
|
||||
menu_path: None,
|
||||
default_shortcut: None,
|
||||
params: "none; returns { message: string | null }: the message git prepared for the merge in progress (MERGE_MSG without its # comment lines), null when no merge is in progress; for prefilling the commit box",
|
||||
}
|
||||
}
|
||||
|
||||
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_with(
|
||||
state,
|
||||
command,
|
||||
false,
|
||||
Box::new(|repo| Ok(json!({ "message": repo.merge_message()? }))),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// Params of `git.conflictVersions`.
|
||||
#[derive(Debug, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
|
|
@ -208,3 +239,14 @@ impl Command for MarkResolved {
|
|||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.conflictVersions",
|
||||
"git.markResolved",
|
||||
"git.merge",
|
||||
"git.mergeAbort",
|
||||
"git.mergeMessage",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -699,3 +699,18 @@ impl Command for RemoteRemove {
|
|||
start(state, command, Op::Remove(p.name))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.cancel",
|
||||
"git.clone",
|
||||
"git.fetch",
|
||||
"git.pull",
|
||||
"git.push",
|
||||
"git.remoteAdd",
|
||||
"git.remoteRemove",
|
||||
"git.remoteSetUrl",
|
||||
"git.remotes",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -219,3 +219,13 @@ impl Command for StashDrop {
|
|||
)
|
||||
}
|
||||
}
|
||||
|
||||
/// 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.stash",
|
||||
"git.stashApply",
|
||||
"git.stashDrop",
|
||||
"git.stashList",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -516,3 +516,8 @@ fn symbol_item(hit: &SymbolHit<'_>, container: bool) -> Value {
|
|||
}
|
||||
item
|
||||
}
|
||||
|
||||
/// 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] = &["goto.class", "goto.file", "goto.symbol", "index.status"];
|
||||
|
|
|
|||
|
|
@ -841,6 +841,11 @@ fn cap(text: &str, max: usize) -> String {
|
|||
text.get(..end).unwrap_or("").to_string()
|
||||
}
|
||||
|
||||
/// 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] = &["lsp.completion", "lsp.hover", "lsp.signatureHelp"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
|
|
|||
|
|
@ -135,3 +135,9 @@ impl Command for Log {
|
|||
Ok(Outcome::value(json!({ "lines": state.lsp.log() })))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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] =
|
||||
&["diagnostics.list", "lsp.log", "lsp.restart", "lsp.status"];
|
||||
|
|
|
|||
|
|
@ -781,6 +781,16 @@ fn notify_summary(state: &mut State, new_name: &str, applied: &edit::Applied) {
|
|||
);
|
||||
}
|
||||
|
||||
/// 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] = &[
|
||||
"lsp.definition",
|
||||
"lsp.prepareRename",
|
||||
"lsp.references",
|
||||
"lsp.rename",
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ mod buffer;
|
|||
mod file;
|
||||
pub mod git;
|
||||
pub mod git_blame;
|
||||
pub mod git_ignore;
|
||||
pub mod git_lines;
|
||||
pub mod git_log;
|
||||
pub mod git_merge;
|
||||
|
|
@ -78,5 +79,37 @@ pub fn register_builtins(registry: &mut Registry) -> Result<(), EngineError> {
|
|||
git_remote::register(registry)?;
|
||||
git_merge::register(registry)?;
|
||||
git_stash::register(registry)?;
|
||||
git_ignore::register(registry)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The id lists of every module that registers built-in commands, one entry
|
||||
/// per module. Each module keeps its own list next to its commands, so new
|
||||
/// commands in different modules never touch the same lines.
|
||||
#[cfg(test)]
|
||||
pub(crate) const BUILTIN_COMMAND_IDS: &[&[&str]] = &[
|
||||
app::COMMAND_IDS,
|
||||
buffer::COMMAND_IDS,
|
||||
file::COMMAND_IDS,
|
||||
git::COMMAND_IDS,
|
||||
git_blame::COMMAND_IDS,
|
||||
git_ignore::COMMAND_IDS,
|
||||
git_lines::COMMAND_IDS,
|
||||
git_log::COMMAND_IDS,
|
||||
git_merge::COMMAND_IDS,
|
||||
git_remote::COMMAND_IDS,
|
||||
git_stash::COMMAND_IDS,
|
||||
goto::COMMAND_IDS,
|
||||
lsp_assist::COMMAND_IDS,
|
||||
lsp_diagnostics::COMMAND_IDS,
|
||||
lsp_nav::COMMAND_IDS,
|
||||
project::COMMAND_IDS,
|
||||
recovery::COMMAND_IDS,
|
||||
search::COMMAND_IDS,
|
||||
settings::COMMAND_IDS,
|
||||
syntax::COMMAND_IDS,
|
||||
terminal::COMMAND_IDS,
|
||||
theme::COMMAND_IDS,
|
||||
toolchain::COMMAND_IDS,
|
||||
ui::COMMAND_IDS,
|
||||
];
|
||||
|
|
|
|||
|
|
@ -230,3 +230,13 @@ impl Command for Children {
|
|||
})))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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] = &[
|
||||
"project.children",
|
||||
"project.close",
|
||||
"project.open",
|
||||
"project.openDialog",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -204,3 +204,8 @@ impl Command for Discard {
|
|||
Ok(Outcome::value(json!({ "discarded": discarded })))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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] = &["recovery.discard", "recovery.list", "recovery.restore"];
|
||||
|
|
|
|||
|
|
@ -302,3 +302,8 @@ impl From<lutra_search::Match> for SearchMatch {
|
|||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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] = &["search.cancel", "search.find"];
|
||||
|
|
|
|||
|
|
@ -167,3 +167,13 @@ fn finish(
|
|||
.ok_or_else(|| EngineError::Internal(format!("setting vanished: {key}")))?;
|
||||
Ok(Outcome::value(json!({ "value": value })))
|
||||
}
|
||||
|
||||
/// 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] = &[
|
||||
"settings.get",
|
||||
"settings.list",
|
||||
"settings.reset",
|
||||
"settings.set",
|
||||
];
|
||||
|
|
|
|||
|
|
@ -581,6 +581,11 @@ impl Command for OutlineCommand {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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] = &["syntax.outline"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
|
|
|||
|
|
@ -400,6 +400,16 @@ pub fn pump(state: &mut State) {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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] = &[
|
||||
"terminal.close",
|
||||
"terminal.create",
|
||||
"terminal.input",
|
||||
"terminal.resize",
|
||||
];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use serde_json::json;
|
||||
|
|
|
|||
|
|
@ -100,3 +100,8 @@ impl Command for SystemPreference {
|
|||
Ok(Outcome::value(Value::Object(fields)))
|
||||
}
|
||||
}
|
||||
|
||||
/// 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] = &["theme.list", "theme.systemPreference"];
|
||||
|
|
|
|||
|
|
@ -639,6 +639,11 @@ impl Command for DownloadPhpactor {
|
|||
}
|
||||
}
|
||||
|
||||
/// 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] = &["toolchain.downloadPhpactor", "toolchain.status"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use std::io::{Read, Write};
|
||||
|
|
|
|||
|
|
@ -182,6 +182,11 @@ pub fn dispatch(state: &mut State, id: &str, params: Value) -> Option<Outcome> {
|
|||
Some(Outcome::value(Value::Null))
|
||||
}
|
||||
|
||||
/// 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] = &["ui.registerCommands"];
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::valid_id;
|
||||
|
|
|
|||
|
|
@ -467,91 +467,23 @@ mod tests {
|
|||
let mut engine = Engine::new().unwrap();
|
||||
engine.register(Box::new(Disabled)).unwrap();
|
||||
let list = engine.list_commands();
|
||||
let ids: Vec<_> = list.iter().map(|c| c.id.as_str()).collect();
|
||||
assert_eq!(
|
||||
ids,
|
||||
vec![
|
||||
"app.about",
|
||||
"app.quit",
|
||||
"buffer.close",
|
||||
"buffer.edit",
|
||||
"buffer.get",
|
||||
"buffer.list",
|
||||
"diagnostics.list",
|
||||
"file.open",
|
||||
"file.save",
|
||||
"file.saveAll",
|
||||
"git.blame",
|
||||
"git.branches",
|
||||
"git.cancel",
|
||||
"git.checkout",
|
||||
"git.clone",
|
||||
"git.commit",
|
||||
"git.conflictVersions",
|
||||
"git.createBranch",
|
||||
"git.fetch",
|
||||
"git.lastMessage",
|
||||
"git.lineChanges",
|
||||
"git.log",
|
||||
"git.markResolved",
|
||||
"git.merge",
|
||||
"git.mergeAbort",
|
||||
"git.pull",
|
||||
"git.push",
|
||||
"git.remoteAdd",
|
||||
"git.remoteRemove",
|
||||
"git.remoteSetUrl",
|
||||
"git.remotes",
|
||||
"git.show",
|
||||
"git.showAt",
|
||||
"git.showCommit",
|
||||
"git.stage",
|
||||
"git.stash",
|
||||
"git.stashApply",
|
||||
"git.stashDrop",
|
||||
"git.stashList",
|
||||
"git.status",
|
||||
"git.unstage",
|
||||
"goto.class",
|
||||
"goto.file",
|
||||
"goto.symbol",
|
||||
"index.status",
|
||||
"lsp.completion",
|
||||
"lsp.definition",
|
||||
"lsp.hover",
|
||||
"lsp.log",
|
||||
"lsp.prepareRename",
|
||||
"lsp.references",
|
||||
"lsp.rename",
|
||||
"lsp.restart",
|
||||
"lsp.signatureHelp",
|
||||
"lsp.status",
|
||||
"project.children",
|
||||
"project.close",
|
||||
"project.open",
|
||||
"project.openDialog",
|
||||
"recovery.discard",
|
||||
"recovery.list",
|
||||
"recovery.restore",
|
||||
"search.cancel",
|
||||
"search.find",
|
||||
"settings.get",
|
||||
"settings.list",
|
||||
"settings.reset",
|
||||
"settings.set",
|
||||
"syntax.outline",
|
||||
"terminal.close",
|
||||
"terminal.create",
|
||||
"terminal.input",
|
||||
"terminal.resize",
|
||||
"test.disabled",
|
||||
"theme.list",
|
||||
"theme.systemPreference",
|
||||
"toolchain.downloadPhpactor",
|
||||
"toolchain.status",
|
||||
"ui.registerCommands",
|
||||
]
|
||||
let ids: Vec<&str> = list.iter().map(|c| c.id.as_str()).collect();
|
||||
let mut sorted = ids.clone();
|
||||
sorted.sort_unstable();
|
||||
assert_eq!(ids, sorted, "the listing is sorted by id");
|
||||
let mut expected: Vec<&str> = cmd::BUILTIN_COMMAND_IDS
|
||||
.iter()
|
||||
.flat_map(|ids| ids.iter().copied())
|
||||
.chain(["test.disabled"])
|
||||
.collect();
|
||||
expected.sort_unstable();
|
||||
let missing: Vec<_> = expected.iter().filter(|id| !ids.contains(id)).collect();
|
||||
let extra: Vec<_> = ids.iter().filter(|id| !expected.contains(id)).collect();
|
||||
assert!(
|
||||
missing.is_empty() && extra.is_empty(),
|
||||
"registered but not in a module's COMMAND_IDS: {extra:?}; listed in COMMAND_IDS but not registered: {missing:?}"
|
||||
);
|
||||
assert_eq!(ids, expected, "no id is listed twice");
|
||||
let by_id = |id: &str| list.iter().find(|c| c.id == id).unwrap();
|
||||
let quit = by_id("app.quit");
|
||||
assert_eq!(quit.default_shortcut.as_deref(), Some("Mod+Q"));
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
//! 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`;
|
||||
//! bad params. Skips with a message when git is not installed.
|
||||
//! `git.mergeMessage`; `git.ignore` (C7 A3); bad params. Skips with a message when git is not installed.
|
||||
|
||||
#![allow(
|
||||
clippy::unwrap_used,
|
||||
|
|
@ -147,11 +147,21 @@ fn merge_conflict_versions_resolve_and_abort() {
|
|||
);
|
||||
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"
|
||||
|
|
@ -188,6 +198,8 @@ fn bad_params_and_no_project() {
|
|||
("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!(
|
||||
|
|
@ -206,3 +218,32 @@ fn bad_params_and_no_project() {
|
|||
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:?}");
|
||||
}
|
||||
|
|
|
|||
|
|
@ -53,7 +53,11 @@ pub enum Incoming {
|
|||
/// The error response line to send back: a parse error for invalid
|
||||
/// JSON, invalid request for anything that is not a single JSON-RPC 2.0
|
||||
/// message, invalid params for params that are not an object.
|
||||
///
|
||||
/// A leading byte order mark is dropped first: Windows PowerShell 5.1
|
||||
/// writes one when it pipes text into a native program.
|
||||
pub fn parse(line: &str) -> Result<Incoming, String> {
|
||||
let line = line.strip_prefix('\u{feff}').unwrap_or(line);
|
||||
let value: Value = serde_json::from_str(line)
|
||||
.map_err(|e| error(&Value::Null, codes::PARSE_ERROR, &e.to_string(), None))?;
|
||||
let Value::Object(mut object) = value else {
|
||||
|
|
@ -176,6 +180,10 @@ mod tests {
|
|||
};
|
||||
assert_eq!(id, json!("a"));
|
||||
assert_eq!(params["k"], 1);
|
||||
assert!(matches!(
|
||||
parse("\u{feff}{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"ping\"}"),
|
||||
Ok(Incoming::Request { .. })
|
||||
));
|
||||
assert_eq!(
|
||||
parse(r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#).unwrap(),
|
||||
Incoming::Notification {
|
||||
|
|
|
|||
115
crates/vcs/src/ignore.rs
Normal file
115
crates/vcs/src/ignore.rs
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
//! Ignoring files (C7 A3): appending literal patterns for chosen paths to
|
||||
//! the `.gitignore` at the work tree's root.
|
||||
//!
|
||||
//! Each path becomes one pattern that matches exactly that path: anchored
|
||||
//! with a leading `/`, and with the characters gitignore treats specially
|
||||
//! (`\`, `*`, `?`, `[`, and trailing spaces) escaped with a backslash, so a
|
||||
//! file named `a*.php` ignores only itself. Patterns already in the file
|
||||
//! are not added again.
|
||||
|
||||
use std::fs::OpenOptions;
|
||||
use std::io::{ErrorKind, Write};
|
||||
|
||||
use crate::Repo;
|
||||
use crate::VcsError;
|
||||
use crate::repo::SMALL_CAP;
|
||||
|
||||
/// The literal, root-anchored gitignore pattern of a root-relative path.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `path`: a root-relative path with `/` separators, as
|
||||
/// [`Repo::to_repo_path`] returns it.
|
||||
pub fn ignore_pattern(path: &str) -> String {
|
||||
let kept = path.trim_end_matches(' ');
|
||||
let trailing = path.len() - kept.len();
|
||||
let mut out = String::with_capacity(path.len() + 8);
|
||||
out.push('/');
|
||||
for c in kept.chars() {
|
||||
if matches!(c, '\\' | '*' | '?' | '[') {
|
||||
out.push('\\');
|
||||
}
|
||||
out.push(c);
|
||||
}
|
||||
for _ in 0..trailing {
|
||||
out.push_str("\\ ");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
impl Repo {
|
||||
/// Appends a literal pattern for each path to the root's `.gitignore`
|
||||
/// (created when missing), on a line of its own.
|
||||
///
|
||||
/// # Parameters
|
||||
/// - `paths`: project-relative paths of files or folders.
|
||||
///
|
||||
/// # Returns
|
||||
/// The patterns added, in the order given; patterns already in the
|
||||
/// file are left out.
|
||||
///
|
||||
/// # Errors
|
||||
/// [`VcsError::InvalidPath`] for a bad path (nothing is written);
|
||||
/// [`VcsError::Git`] when `.gitignore` cannot be read or written, or is
|
||||
/// larger than 16 MiB.
|
||||
pub fn ignore(&self, paths: &[String]) -> Result<Vec<String>, VcsError> {
|
||||
let mut patterns = Vec::with_capacity(paths.len());
|
||||
for path in paths {
|
||||
let pattern = ignore_pattern(&self.to_repo_path(path)?);
|
||||
if pattern != "/" && !patterns.contains(&pattern) {
|
||||
patterns.push(pattern);
|
||||
}
|
||||
}
|
||||
if patterns.is_empty() {
|
||||
return Ok(patterns);
|
||||
}
|
||||
let _guard = self.lock();
|
||||
let file = self.root().join(".gitignore");
|
||||
let failed = |e: std::io::Error| VcsError::Git(format!("cannot update .gitignore: {e}"));
|
||||
let existing = match std::fs::read(&file) {
|
||||
Ok(bytes) => bytes,
|
||||
Err(e) if e.kind() == ErrorKind::NotFound => Vec::new(),
|
||||
Err(e) => return Err(failed(e)),
|
||||
};
|
||||
if existing.len() > SMALL_CAP {
|
||||
return Err(VcsError::Git(
|
||||
"cannot update .gitignore: the file is too large".into(),
|
||||
));
|
||||
}
|
||||
let text = String::from_utf8_lossy(&existing);
|
||||
let present: Vec<&str> = text.lines().collect();
|
||||
patterns.retain(|p| !present.contains(&p.as_str()));
|
||||
if patterns.is_empty() {
|
||||
return Ok(patterns);
|
||||
}
|
||||
let mut out = String::new();
|
||||
if !existing.is_empty() && !existing.ends_with(b"\n") {
|
||||
out.push('\n');
|
||||
}
|
||||
for pattern in &patterns {
|
||||
out.push_str(pattern);
|
||||
out.push('\n');
|
||||
}
|
||||
OpenOptions::new()
|
||||
.create(true)
|
||||
.append(true)
|
||||
.open(&file)
|
||||
.and_then(|mut f| f.write_all(out.as_bytes()))
|
||||
.map_err(failed)?;
|
||||
Ok(patterns)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn patterns_are_anchored_and_literal() {
|
||||
assert_eq!(ignore_pattern("tmp.txt"), "/tmp.txt");
|
||||
assert_eq!(ignore_pattern("a/b c.php"), "/a/b c.php");
|
||||
assert_eq!(ignore_pattern("x*?[y].php"), "/x\\*\\?\\[y].php");
|
||||
assert_eq!(ignore_pattern("#note!"), "/#note!");
|
||||
assert_eq!(ignore_pattern("back\\slash"), "/back\\\\slash");
|
||||
assert_eq!(ignore_pattern("end "), "/end\\ \\ ");
|
||||
}
|
||||
}
|
||||
|
|
@ -12,6 +12,8 @@
|
|||
//! git's credential helper and the ssh agent (see `remote.rs`).
|
||||
//! - Blame (M4.7): who last changed each line, of the working copy or an
|
||||
//! editor buffer (`blame.rs`).
|
||||
//! - Ignoring files (C7 A3): literal patterns appended to `.gitignore`
|
||||
//! (`ignore.rs`).
|
||||
//! - [`RepoWatch`] notices changes inside `.git` (HEAD, index, refs).
|
||||
//!
|
||||
//! Every call goes through [`runner::run`]: arguments as an array, never a
|
||||
|
|
@ -25,6 +27,7 @@
|
|||
|
||||
pub mod blame;
|
||||
mod error;
|
||||
mod ignore;
|
||||
pub mod log;
|
||||
pub mod porcelain;
|
||||
mod remote;
|
||||
|
|
@ -35,6 +38,7 @@ mod watch;
|
|||
|
||||
pub use blame::{BlameLine, UNCOMMITTED_AUTHOR, is_uncommitted};
|
||||
pub use error::VcsError;
|
||||
pub use ignore::ignore_pattern;
|
||||
pub use log::{CommitDetails, CommitFile, LOG_LIMIT, LogCommit, LogQuery};
|
||||
pub use porcelain::{FileState, FileStatus, Head, Status, Version};
|
||||
pub use remote::{
|
||||
|
|
|
|||
|
|
@ -12,11 +12,29 @@
|
|||
//! - [`Repo::mark_resolved`] stages the files (`add -A`), which removes the
|
||||
//! unmerged entries; a file deleted in the work tree is staged as deleted.
|
||||
//! - [`Repo::merge_abort`] runs `git merge --abort`.
|
||||
//! - [`Repo::merge_message`] reads the message git prepared for the merge
|
||||
//! in progress (`MERGE_MSG`), for the commit box.
|
||||
|
||||
use std::io::Read;
|
||||
|
||||
use crate::VcsError;
|
||||
use crate::repo::{Contents, FILE_CAP, Repo, SMALL_CAP, check_name, decode};
|
||||
use crate::runner::{Call, HOOK_TIMEOUT};
|
||||
|
||||
/// The most of `MERGE_MSG` [`Repo::merge_message`] reads.
|
||||
const MESSAGE_CAP: u64 = 64 * 1024;
|
||||
|
||||
/// Removes comment lines (starting with `#`) and surrounding blank lines
|
||||
/// from a prepared commit message; line endings become `\n`.
|
||||
fn strip_comments(text: &str) -> String {
|
||||
text.lines()
|
||||
.filter(|line| !line.starts_with('#'))
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
.trim_matches(['\n', ' ', '\t'])
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// How a merge ended.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MergeResult {
|
||||
|
|
@ -209,6 +227,35 @@ impl Repo {
|
|||
})
|
||||
}
|
||||
|
||||
/// The message git prepared for the merge in progress: `MERGE_MSG` in
|
||||
/// the repository directory, without its comment lines (those starting
|
||||
/// with `#`, git's default comment character, such as the list of
|
||||
/// conflicts) and without surrounding blank lines.
|
||||
///
|
||||
/// A missing or unreadable file means there is no message: the box is
|
||||
/// only a convenience, and the commit itself reports real failures.
|
||||
///
|
||||
/// # Returns
|
||||
/// `None` when no merge is in progress or git left no message.
|
||||
///
|
||||
/// # Errors
|
||||
/// The runner's errors.
|
||||
pub fn merge_message(&self) -> Result<Option<String>, VcsError> {
|
||||
if !self.merging()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let Ok(file) = std::fs::File::open(self.git_dir().join("MERGE_MSG")) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let mut bytes = Vec::new();
|
||||
if file.take(MESSAGE_CAP).read_to_end(&mut bytes).is_err() {
|
||||
return Ok(None);
|
||||
}
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
let message = strip_comments(&text);
|
||||
Ok((!message.is_empty()).then_some(message))
|
||||
}
|
||||
|
||||
/// Aborts the merge in progress (`git merge --abort`): the work tree
|
||||
/// and index go back to the state before the merge.
|
||||
///
|
||||
|
|
@ -303,6 +350,16 @@ mod tests {
|
|||
use super::*;
|
||||
use proptest::prelude::*;
|
||||
|
||||
#[test]
|
||||
fn strips_comment_lines_from_a_prepared_message() {
|
||||
assert_eq!(
|
||||
strip_comments("Merge branch 'f'\r\n\r\n# Conflicts:\r\n#\ta.php\r\n"),
|
||||
"Merge branch 'f'"
|
||||
);
|
||||
assert_eq!(strip_comments("\nA\n\nB\n#c\n\n"), "A\n\nB");
|
||||
assert_eq!(strip_comments("# only\n"), "");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_check_lines() {
|
||||
assert_eq!(
|
||||
|
|
|
|||
86
crates/vcs/tests/ignore.rs
Normal file
86
crates/vcs/tests/ignore.rs
Normal file
|
|
@ -0,0 +1,86 @@
|
|||
//! Ignoring files against a real temp repository: literal patterns for
|
||||
//! odd names, a project in a subfolder, no duplicates, a missing final line
|
||||
//! break, and refused paths. Skips with a message when git is not
|
||||
//! installed.
|
||||
|
||||
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
|
||||
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
use lutra_vcs::{Git, VcsError};
|
||||
|
||||
/// The installed git, or `None` (with a message) when there is none.
|
||||
fn installed() -> Option<Git> {
|
||||
match Git::detect("") {
|
||||
Ok(git) => Some(git),
|
||||
Err(e) => {
|
||||
eprintln!("skipped: no usable git installed ({e})");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs git in `dir` and returns its stdout and whether it succeeded.
|
||||
fn git(dir: &Path, args: &[&str]) -> (String, bool) {
|
||||
let out = Command::new("git")
|
||||
.args(args)
|
||||
.current_dir(dir)
|
||||
.env_remove("GIT_DIR")
|
||||
.env_remove("GIT_WORK_TREE")
|
||||
.env_remove("GIT_INDEX_FILE")
|
||||
.output()
|
||||
.unwrap();
|
||||
(
|
||||
String::from_utf8_lossy(&out.stdout).trim().to_string(),
|
||||
out.status.success(),
|
||||
)
|
||||
}
|
||||
|
||||
/// Whether git ignores `path` (root-relative).
|
||||
fn ignored(dir: &Path, path: &str) -> bool {
|
||||
git(dir, &["check-ignore", "-q", "--no-index", "--", path]).1
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ignores_exactly_the_given_paths() {
|
||||
let Some(cli) = installed() else { return };
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
assert!(git(root, &["init", "-q", "-b", "main"]).1);
|
||||
std::fs::create_dir_all(root.join("app/var")).unwrap();
|
||||
std::fs::write(root.join(".gitignore"), "vendor/").unwrap();
|
||||
for name in [
|
||||
"app/a[1].php",
|
||||
"app/a1.php",
|
||||
"app/var/cache.log",
|
||||
"app/b.php",
|
||||
] {
|
||||
std::fs::write(root.join(name), "x").unwrap();
|
||||
}
|
||||
let repo = cli.open(&root.join("app")).unwrap().expect("a repository");
|
||||
|
||||
let added = repo
|
||||
.ignore(&[
|
||||
"a[1].php".to_string(),
|
||||
"var".to_string(),
|
||||
"var/".to_string(),
|
||||
])
|
||||
.unwrap();
|
||||
assert_eq!(added, vec![r"/app/a\[1].php", "/app/var"]);
|
||||
assert_eq!(
|
||||
std::fs::read_to_string(root.join(".gitignore")).unwrap(),
|
||||
"vendor/\n/app/a\\[1].php\n/app/var\n"
|
||||
);
|
||||
assert!(ignored(root, "app/a[1].php"));
|
||||
assert!(!ignored(root, "app/a1.php"));
|
||||
assert!(ignored(root, "app/var/cache.log"));
|
||||
assert!(!ignored(root, "app/b.php"));
|
||||
|
||||
assert!(repo.ignore(&["a[1].php".to_string()]).unwrap().is_empty());
|
||||
assert!(matches!(
|
||||
repo.ignore(&["../outside".to_string(), "b.php".to_string()]),
|
||||
Err(VcsError::InvalidPath(_))
|
||||
));
|
||||
assert!(!ignored(root, "app/b.php"));
|
||||
}
|
||||
|
|
@ -127,10 +127,14 @@ fn a_conflict_its_versions_resolving_and_committing() {
|
|||
init(root);
|
||||
conflicting(root);
|
||||
let repo = open(&cli, root);
|
||||
assert_eq!(repo.merge_message().unwrap(), None);
|
||||
let outcome = repo.merge("feature").unwrap();
|
||||
assert_eq!(outcome.result, MergeResult::Conflicts);
|
||||
assert_eq!(outcome.conflicts, vec!["a.php"]);
|
||||
assert!(repo.merging().unwrap());
|
||||
let prepared = repo.merge_message().unwrap().unwrap();
|
||||
assert!(prepared.starts_with("Merge branch 'feature'"), "{prepared}");
|
||||
assert!(!prepared.contains('#'), "{prepared}");
|
||||
let status = repo.status().unwrap();
|
||||
let file = status.files.iter().find(|f| f.path == "a.php").unwrap();
|
||||
assert_eq!(file.worktree, FileState::Conflicted);
|
||||
|
|
@ -160,6 +164,7 @@ fn a_conflict_its_versions_resolving_and_committing() {
|
|||
));
|
||||
repo.commit("Merge feature", false).unwrap();
|
||||
assert!(!repo.merging().unwrap());
|
||||
assert_eq!(repo.merge_message().unwrap(), None);
|
||||
assert_eq!(git(root, &["rev-list", "--count", "--merges", "HEAD"]), "1");
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue