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>
This commit is contained in:
danny 2026-10-31 14:33:42 +01:00
parent ce681871ad
commit 68599fa2ac
14 changed files with 633 additions and 5 deletions

View 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"];

View file

@ -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,6 +79,7 @@ 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(())
}
@ -91,6 +93,7 @@ pub(crate) const BUILTIN_COMMAND_IDS: &[&[&str]] = &[
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,

View file

@ -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,
@ -198,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!(
@ -216,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:?}");
}