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:
parent
ce681871ad
commit
68599fa2ac
14 changed files with 633 additions and 5 deletions
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::{
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue