use crate::git::{self, Opts};
use crate::policy::{self, Op};
use crate::{explain, model::Config, screen, ui};
use anyhow::{bail, Context, Result};
use std::path::PathBuf;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PatternKind {
Exact,
Extension,
Folder,
}
pub fn pattern_for(path: &str, kind: PatternKind) -> String {
let mut p = path.trim().replace('\\', "/");
while let Some(rest) = p.strip_prefix("./") {
p = rest.to_string();
}
let p = p.trim_start_matches('/');
let is_dir = p.ends_with('/');
let p = p.trim_end_matches('/');
let exact = || format!("/{p}{}", if is_dir { "/" } else { "" });
let name = p.rsplit('/').next().unwrap_or(p);
match kind {
PatternKind::Exact => exact(),
PatternKind::Extension => match name.rfind('.') {
Some(dot) if dot > 0 && dot + 1 < name.len() && !is_dir => {
format!("*{}", &name[dot..])
}
_ if is_dir => format!("{p}/"),
_ => exact(),
},
PatternKind::Folder => {
if is_dir {
format!("{p}/")
} else {
match p.rfind('/') {
Some(slash) => format!("{}/", &p[..slash]),
None => exact(),
}
}
}
}
}
fn is_pattern(line: &str) -> bool {
let t = line.trim();
!t.is_empty() && !t.starts_with('#')
}
pub fn merge_gitignore(existing: &str, new: &[String]) -> String {
let eol = if existing.contains("\r\n") {
"\r\n"
} else {
"\n"
};
let mut seen: Vec<&str> = existing
.lines()
.filter(|l| is_pattern(l))
.map(str::trim)
.collect();
let mut kept: Vec<&str> = Vec::new();
for line in new {
let line = line.trim_end_matches(['\r', '\n']);
if is_pattern(line) {
if seen.contains(&line.trim()) {
continue;
}
seen.push(line.trim());
}
kept.push(line);
}
while kept.last().is_some_and(|l| l.trim().is_empty()) {
kept.pop();
}
while kept.first().is_some_and(|l| l.trim().is_empty()) {
kept.remove(0);
}
let mut out = existing.to_string();
if !out.is_empty() && !out.ends_with('\n') {
out.push_str(eol);
}
if !kept.iter().any(|l| is_pattern(l)) {
return out;
}
let last_blank = out.lines().last().is_none_or(|l| l.trim().is_empty());
if !last_blank
&& kept
.first()
.is_some_and(|l| l.trim_start().starts_with('#'))
{
out.push_str(eol);
}
for line in kept {
out.push_str(line);
out.push_str(eol);
}
out
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IgnoreMatch {
pub source: String,
pub line: u32,
pub pattern: String,
pub path: String,
}
pub fn parse_check_ignore(output: &str) -> Option<IgnoreMatch> {
let first = output.lines().find(|l| !l.trim().is_empty())?;
let (left, path) = first.split_once('\t')?;
let bytes = left.as_bytes();
let mut i = 0;
while i < bytes.len() {
if bytes[i] == b':' {
let digits = bytes[i + 1..]
.iter()
.take_while(|b| b.is_ascii_digit())
.count();
if digits > 0 && bytes.get(i + 1 + digits) == Some(&b':') {
let line = left[i + 1..i + 1 + digits].parse().ok()?;
return Some(IgnoreMatch {
source: left[..i].to_string(),
line,
pattern: left[i + 2 + digits..].to_string(),
path: path.trim_end_matches('\r').to_string(),
});
}
}
i += 1;
}
None
}
const RUST: &str = "/target/\n**/*.rs.bk\n";
const NODE: &str = "node_modules/\nnpm-debug.log*\nyarn-error.log*\n.npm/\ndist/\n.next/\ncoverage/\n*.tsbuildinfo\n";
const PYTHON: &str = "__pycache__/\n*.py[cod]\n.venv/\nvenv/\n*.egg-info/\n.pytest_cache/\n.mypy_cache/\nbuild/\ndist/\n";
const VSCODE: &str = ".vscode/*\n!.vscode/settings.json\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/extensions.json\n*.code-workspace\n";
const VISUALSTUDIO: &str =
".vs/\nbin/\nobj/\n*.user\n*.suo\n*.userprefs\n*.rsuser\n[Dd]ebug/\n[Rr]elease/\n";
const JETBRAINS: &str = ".idea/\n*.iml\n*.iws\ncmake-build-*/\n";
const MACOS: &str = ".DS_Store\n.AppleDouble\n.LSOverride\n._*\n.Trashes\n";
const WINDOWS: &str = "Thumbs.db\nehthumbs.db\nDesktop.ini\n$RECYCLE.BIN/\n*.lnk\n";
const SECRETS: &str = ".env\n.env.*\n!.env.example\n*.pem\n*.key\nsecrets.*\ncredentials.json\n";
const TEMPLATES: &[(&str, &str)] = &[
("Rust", RUST),
("Node", NODE),
("Python", PYTHON),
("VSCode", VSCODE),
("VisualStudio", VISUALSTUDIO),
("JetBrains", JETBRAINS),
("macOS", MACOS),
("Windows", WINDOWS),
("Secrets (.env)", SECRETS),
];
pub fn template_names() -> Vec<&'static str> {
TEMPLATES.iter().map(|(name, _)| *name).collect()
}
pub fn template(name: &str) -> Option<&'static str> {
let name = name.trim();
let name = if name.eq_ignore_ascii_case(".env") || name.eq_ignore_ascii_case("secrets") {
"Secrets (.env)"
} else {
name
};
TEMPLATES
.iter()
.find(|(n, _)| n.eq_ignore_ascii_case(name))
.map(|(_, body)| *body)
}
fn parse_untracked(raw: &[u8]) -> Vec<String> {
raw.split(|b| *b == 0)
.filter_map(|entry| entry.strip_prefix(b"?? "))
.map(|p| String::from_utf8_lossy(p).into_owned())
.collect()
}
fn wrap(text: &str, width: usize) -> Vec<String> {
let mut lines = Vec::new();
let mut cur = String::new();
for word in text.split_whitespace() {
if !cur.is_empty() && cur.chars().count() + 1 + word.chars().count() > width {
lines.push(std::mem::take(&mut cur));
}
if !cur.is_empty() {
cur.push(' ');
}
cur.push_str(word);
}
if !cur.is_empty() {
lines.push(cur);
}
lines
}
const LITERAL: &[(&str, &str)] = &[("GIT_LITERAL_PATHSPECS", "1")];
fn repo_root() -> Result<String> {
Ok(
git::git_ok(&["rev-parse", "--show-toplevel"], &Opts::default())?
.trim()
.to_string(),
)
}
fn in_root(args: &[&str], literal: bool) -> Result<git::Out> {
let root = repo_root()?;
let mut full = vec!["-C", root.as_str()];
full.extend_from_slice(args);
git::git_raw(
&full,
&Opts {
env: if literal { LITERAL } else { &[] },
..Opts::default()
},
)
}
fn gitignore_path() -> Result<PathBuf> {
Ok(PathBuf::from(repo_root()?).join(".gitignore"))
}
fn read_gitignore() -> Result<(PathBuf, String)> {
let path = gitignore_path()?;
let text = match std::fs::read(&path) {
Ok(bytes) => {
String::from_utf8(bytes).context(".gitignore is not valid UTF-8; edit it by hand")?
}
Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
Err(e) => return Err(e).context("could not read .gitignore"),
};
Ok((path, text))
}
pub fn add_lines(lines: &[String]) -> Result<Vec<String>> {
let (path, existing) = read_gitignore()?;
let merged = merge_gitignore(&existing, lines);
let before: Vec<&str> = existing.lines().collect();
let added: Vec<String> = merged
.lines()
.skip(before.len())
.filter(|l| is_pattern(l))
.map(str::to_string)
.collect();
if merged != existing {
std::fs::write(&path, merged).context("could not write .gitignore")?;
}
Ok(added)
}
pub fn ignore_exact(path: &str) -> Result<Option<String>> {
let pattern = pattern_for(path, PatternKind::Exact);
Ok(add_lines(std::slice::from_ref(&pattern))?.pop())
}
pub fn untrack(path: &str) -> Result<Option<String>> {
if path.starts_with('-') {
bail!("path cannot start with '-'");
}
let out = in_root(&["rm", "--cached", "-q", "--", path], true)?;
if !out.ok() {
bail!("{}", out.stderr.trim());
}
ignore_exact(path)
}
fn tracked_files() -> Result<Vec<String>> {
let out = in_root(&["ls-files", "-z"], false)?;
Ok(out
.stdout
.split(|b| *b == 0)
.filter(|p| !p.is_empty())
.map(|p| String::from_utf8_lossy(p).into_owned())
.collect())
}
fn untracked_files() -> Result<Vec<String>> {
let out = in_root(&["status", "--porcelain=v1", "-z", "-unormal"], false)?;
Ok(parse_untracked(&out.stdout))
}
fn check_ignored(path: &str) -> Result<Option<IgnoreMatch>> {
if path.starts_with('-') {
bail!("path cannot start with '-'");
}
let out = in_root(&["check-ignore", "-v", "--", path], false)?;
Ok(parse_check_ignore(&out.text()).filter(|m| !m.pattern.starts_with('!')))
}
pub fn run(config: &mut Config) -> Result<()> {
let options = [
"Ignore untracked files",
"Add a template (Rust, Node, Python, ...)",
"Stop tracking a committed file",
"Why is this file ignored?",
"View .gitignore",
"Git glossary (what do these words mean?)",
];
let context = vec![screen::muted("Tell git which files to leave alone")];
while let Some(choice) = ui::choose("Ignore", &context, &options)? {
match choice {
0 => ignore_untracked(config)?,
1 => add_template(config)?,
2 => untrack_flow(config)?,
3 => why_ignored(config)?,
4 => view_gitignore()?,
_ => glossary()?,
}
}
Ok(())
}
pub fn ignore_path(cfg: &mut Config, path: &str) -> Result<()> {
let mut lines = match ignore_exact(path)? {
Some(p) => vec![format!("Added to .gitignore: {p}")],
None => vec!["That path is already in .gitignore.".to_string()],
};
lines.push(
"Files git already tracks stay tracked: use 'Stop tracking a committed file'.".into(),
);
lines.extend(ui::explain(
cfg,
&["A .gitignore line tells git to leave matching files alone."],
));
ui::notice("Ignore", &lines)
}
fn ignore_untracked(cfg: &Config) -> Result<()> {
let files = untracked_files()?;
if files.is_empty() {
return ui::notice(
"Ignore",
&["No untracked files. Nothing to ignore right now.".into()],
);
}
let mut checked = vec![false; files.len()];
if !ui::check_list(
"Untracked files to ignore (Space ticks, Enter confirms)",
&files,
&mut checked,
)? {
return Ok(());
}
let mut patterns = Vec::new();
for file in files
.iter()
.zip(&checked)
.filter(|(_, c)| **c)
.map(|(f, _)| f)
{
let ctx = vec![format!("Ignore: {file}")];
let kinds = [
PatternKind::Exact,
PatternKind::Extension,
PatternKind::Folder,
];
let labels: Vec<String> = kinds
.iter()
.map(|k| {
let p = pattern_for(file, *k);
match k {
PatternKind::Exact => format!("Exactly this file ({p})"),
PatternKind::Extension => format!("All files with this extension ({p})"),
PatternKind::Folder => format!("The whole folder ({p})"),
}
})
.collect();
let refs: Vec<&str> = labels.iter().map(String::as_str).collect();
if let Some(i) = ui::choose("Ignore how?", &ctx, &refs)? {
patterns.push(pattern_for(file, kinds[i]));
}
}
if patterns.is_empty() {
return Ok(());
}
let added = add_lines(&patterns)?;
let mut lines = if added.is_empty() {
vec!["Those patterns were already in .gitignore.".to_string()]
} else {
added.iter().map(|p| format!("Added: {p}")).collect()
};
lines.extend(ui::explain(
cfg,
&["Ignored files no longer show up as untracked."],
));
ui::notice("Ignore", &lines)
}
fn add_template(cfg: &Config) -> Result<()> {
let names = template_names();
let items: Vec<String> = names.iter().map(|n| n.to_string()).collect();
let mut index = 0;
let Some(i) = ui::pick_list("Add a .gitignore template", &items, &mut index, "")? else {
return Ok(());
};
let Some(body) = template(names[i]) else {
return Ok(());
};
let mut lines = vec![String::new(), format!("# {} (added by gct)", names[i])];
lines.extend(body.lines().map(str::to_string));
let added = add_lines(&lines)?;
let mut out = if added.is_empty() {
vec![format!(
"The {} template was already fully in .gitignore.",
names[i]
)]
} else {
vec![format!(
"Added {} line(s) from the {} template.",
added.len(),
names[i]
)]
};
out.extend(ui::explain(
cfg,
&["Existing lines are never duplicated or removed."],
));
ui::notice("Ignore", &out)
}
fn untrack_flow(cfg: &Config) -> Result<()> {
let files = tracked_files()?;
if files.is_empty() {
return ui::notice("Ignore", &["No tracked files in this repository.".into()]);
}
let filter = ui::ask("Filter files (empty = all)", "")?
.unwrap_or_default()
.to_lowercase();
let shown: Vec<String> = files
.into_iter()
.filter(|f| f.to_lowercase().contains(&filter))
.collect();
if shown.is_empty() {
return ui::notice("Ignore", &["No tracked file matches that filter.".into()]);
}
let mut index = 0;
let Some(i) = ui::pick_list("Stop tracking which file?", &shown, &mut index, "")? else {
return Ok(());
};
let path = &shown[i];
let command = format!("git rm --cached -- {path}");
let what = format!(
"Stop tracking {path}? The file stays on your disk but is removed from the repository on your next commit, and teammates lose it when they pull."
);
if !ui::gate(
cfg,
&policy::check(cfg, &Op::CreatesCommit),
&what,
&command,
)? {
return Ok(());
}
let added = untrack(path)?;
let mut lines = vec![
format!("$ {command}"),
format!("{path} is no longer tracked (still on disk)."),
];
match added {
Some(p) => lines.push(format!("Added to .gitignore: {p}")),
None => lines.push("It was already listed in .gitignore.".into()),
}
lines.push("Commit the change to finish removing it from the repository.".into());
lines.extend(ui::explain(
cfg,
&["The removal only becomes official once you commit."],
));
ui::notice("Ignore", &lines)
}
fn why_ignored(cfg: &mut Config) -> Result<()> {
let Some(path) = ui::ask("Path to check (from the repo root)", "")? else {
return Ok(());
};
let path = path.trim().to_string();
if path.is_empty() {
return Ok(());
}
let lines = match check_ignored(&path)? {
Some(m) => vec![
format!("{} is ignored.", m.path),
format!("Rule: {}", m.pattern),
format!("From: {} line {}", m.source, m.line),
],
None => {
let tracked = in_root(&["ls-files", "--", &path], true)?;
let mut l = vec![format!("{path} is not ignored.")];
if !tracked.stdout.is_empty() {
l.push("It is tracked, and ignore rules never apply to tracked files.".into());
l.push("Use 'Stop tracking a committed file' to change that.".into());
} else {
ui::notice("Why is this file ignored?", &l)?;
let ctx = vec![format!("Add {path} to .gitignore?")];
return match ui::choose("Ignore it now?", &ctx, &["Yes, ignore this path", "No"])? {
Some(0) => ignore_path(cfg, &path),
_ => Ok(()),
};
}
l
}
};
ui::notice("Why is this file ignored?", &lines)
}
fn view_gitignore() -> Result<()> {
let (path, text) = read_gitignore()?;
if text.is_empty() {
return ui::notice(
".gitignore",
&[
format!("{} is empty or missing.", path.display()),
"Add a template or ignore some files first.".into(),
],
);
}
let lines: Vec<String> = text.lines().map(str::to_string).collect();
ui::pager(".gitignore", &lines, "")
}
fn glossary() -> Result<()> {
let query = ui::ask("Search the glossary (empty = all)", "")?;
let Some(query) = query else {
return Ok(());
};
let hits = explain::search(&query);
if hits.is_empty() {
return ui::notice(
"Glossary",
&[format!("No term matches '{}'.", query.trim())],
);
}
let items: Vec<String> = hits.iter().map(|(t, _)| t.to_string()).collect();
let mut index = 0;
while let Some(i) = ui::pick_list("Git glossary", &items, &mut index, "")? {
let (term, def) = hits[i];
let mut lines = wrap(def, 70);
lines.insert(0, String::new());
ui::notice(term, &lines)?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testutil::TempRepo;
#[test]
fn pattern_table() {
use PatternKind::*;
let cases = [
("a.txt", Exact, "/a.txt"),
("src\\gen\\x.log", Exact, "/src/gen/x.log"),
("./a.txt", Exact, "/a.txt"),
("build/", Exact, "/build/"),
("src/x.log", Extension, "*.log"),
("archive.tar.gz", Extension, "*.gz"),
("Makefile", Extension, "/Makefile"),
(".env", Extension, "/.env"),
("target/", Extension, "target/"),
("src/gen/x.log", Folder, "src/gen/"),
("build/", Folder, "build/"),
("x.log", Folder, "/x.log"),
("dir\\sub\\f.rs", Folder, "dir/sub/"),
];
for (path, kind, want) in cases {
assert_eq!(pattern_for(path, kind), want, "{path} {kind:?}");
}
}
fn s(v: &[&str]) -> Vec<String> {
v.iter().map(|x| x.to_string()).collect()
}
#[test]
fn merge_basics() {
assert_eq!(merge_gitignore("", &s(&["/a"])), "/a\n");
assert_eq!(merge_gitignore("/a", &s(&["/b"])), "/a\n/b\n");
assert_eq!(merge_gitignore("/a\n", &s(&["/a", "/b", "/b"])), "/a\n/b\n");
assert_eq!(merge_gitignore("/a", &s(&["/a"])), "/a\n");
assert_eq!(merge_gitignore("", &s(&[])), "");
}
#[test]
fn merge_keeps_crlf() {
assert_eq!(
merge_gitignore("/a\r\n/b\r\n", &s(&["/c"])),
"/a\r\n/b\r\n/c\r\n"
);
assert_eq!(
merge_gitignore("/a\r\n/b", &s(&["/c"])),
"/a\r\n/b\r\n/c\r\n"
);
}
#[test]
fn merge_section_comment_gets_blank_line() {
let out = merge_gitignore("/a\n", &s(&["# Rust", "/target/"]));
assert_eq!(out, "/a\n\n# Rust\n/target/\n");
assert_eq!(
merge_gitignore("/target/\n", &s(&["# Rust", "/target/"])),
"/target/\n"
);
assert_eq!(
merge_gitignore("/a\n\n", &s(&["# T", "/b"])),
"/a\n\n# T\n/b\n"
);
}
#[test]
fn check_ignore_parsing() {
let m = parse_check_ignore(".gitignore:3:*.log\tsrc/x.log\n").unwrap();
assert_eq!(
(
m.source.as_str(),
m.line,
m.pattern.as_str(),
m.path.as_str()
),
(".gitignore", 3, "*.log", "src/x.log")
);
let m = parse_check_ignore("C:/Users/me/.config/git/ignore:12:/a:b\tz\r\n").unwrap();
assert_eq!(
(m.source.as_str(), m.line, m.pattern.as_str()),
("C:/Users/me/.config/git/ignore", 12, "/a:b")
);
assert_eq!(parse_check_ignore(""), None);
assert_eq!(parse_check_ignore("garbage"), None);
}
#[test]
fn templates_are_valid() {
assert!(template_names().len() >= 8);
for name in template_names() {
let body = template(name).unwrap();
assert!(!body.trim().is_empty() && body.ends_with('\n'), "{name}");
}
assert!(template("rust").is_some() && template(".env").is_some());
assert!(template("cobol").is_none());
}
#[test]
fn untracked_parsing() {
let raw = b"?? new file.txt\0 M a.txt\0?? dir/\0";
assert_eq!(parse_untracked(raw), ["new file.txt", "dir/"]);
}
#[test]
fn ignore_path_hides_file_from_status() {
let repo = TempRepo::new(1);
repo.write("junk.log", "x");
assert!(repo.git(&["status", "--porcelain"]).contains("junk.log"));
let added = repo.run(|| ignore_exact("junk.log")).unwrap();
assert_eq!(added.as_deref(), Some("/junk.log"));
assert!(!repo.git(&["status", "--porcelain"]).contains("junk.log"));
assert_eq!(repo.run(|| ignore_exact("junk.log")).unwrap(), None);
let hit = repo.run(|| check_ignored("junk.log")).unwrap().unwrap();
assert_eq!(hit.pattern, "/junk.log");
}
#[test]
fn untrack_keeps_disk_file() {
let repo = TempRepo::new(2);
let added = repo.run(|| untrack("f1.txt")).unwrap();
assert_eq!(added.as_deref(), Some("/f1.txt"));
assert!(repo.path().join("f1.txt").exists());
assert!(!repo.git(&["ls-files"]).contains("f1.txt"));
assert!(repo.git(&["ls-files"]).contains("f2.txt"));
assert!(repo.run(|| untrack("-bad")).is_err());
}
#[test]
fn merge_into_existing_crlf_file() {
let repo = TempRepo::new(1);
repo.write(".gitignore", "/old\r\n");
let lines = s(&["", "# Rust (added by gct)", "/target/"]);
let added = repo.run(|| add_lines(&lines)).unwrap();
assert_eq!(added, ["/target/"]);
let text = std::fs::read_to_string(repo.path().join(".gitignore")).unwrap();
assert_eq!(text, "/old\r\n\r\n# Rust (added by gct)\r\n/target/\r\n");
assert!(!text.replace("\r\n", "").contains('\n'));
}
#[test]
fn ignore_and_untrack_from_a_subfolder_use_root_paths() {
let repo = TempRepo::new(1);
repo.write("same.log", "root");
repo.write("sub/same.log", "sub");
repo.write("sub/keep.txt", "k");
repo.git(&["add", "f1.txt"]);
let in_sub = |f: &dyn Fn()| crate::git::with_ctx(&repo.path().join("sub"), repo.env(), f);
in_sub(&|| {
assert_eq!(
ignore_exact("same.log").unwrap().as_deref(),
Some("/same.log")
)
});
let text = std::fs::read_to_string(repo.path().join(".gitignore")).unwrap();
assert_eq!(text, "/same.log\n");
assert!(!repo.path().join("sub/.gitignore").exists());
let status = repo.git(&["status", "--porcelain", "-uall"]);
assert!(
status.contains("sub/same.log") && !status.contains("?? same.log"),
"{status}"
);
in_sub(&|| {
assert!(untracked_files().unwrap().contains(&"sub/".to_string()));
assert!(tracked_files().unwrap().contains(&"f1.txt".to_string()));
assert!(check_ignored("same.log").unwrap().is_some());
assert!(check_ignored("sub/same.log").unwrap().is_none());
assert_eq!(untrack("f1.txt").unwrap().as_deref(), Some("/f1.txt"));
});
assert!(!repo.git(&["ls-files"]).contains("f1.txt"));
assert!(repo.path().join("sub/same.log").exists());
}
#[test]
fn wraps_text() {
assert_eq!(wrap("aa bb cc", 5), ["aa bb", "cc"]);
assert!(wrap("", 10).is_empty());
}
}