From 220c11b8c898bcbd8856a3b5ca44b26ae0c2d05c Mon Sep 17 00:00:00 2001 From: Muhammad-Jibril Bashir Sharif Date: Sat, 15 Aug 2026 20:08:29 +0800 Subject: [PATCH 1/4] fix: honor configured ignore field, skip toml by default, deduplicate headers The walker now honors the configured \ignore\ field (renamed from \skip\; the legacy \skip\ key still works as an alias). TOML files are skipped by default, while \Cargo.toml\ is still processed for its \license\ field. Applying headers now detects stale license headers anywhere in a file and replaces them instead of stacking a new header, so headers are never duplicated. Closes #18 --- AGENTS.md | 7 + packages/forehead-cli/src/commands.rs | 4 + packages/forehead-core/README.md | 3 + packages/forehead-core/src/config.rs | 7 +- packages/forehead-core/src/header.rs | 315 +++++++++++++++++++++++++- packages/forehead-core/src/lib.rs | 265 +++++++++++++++++++++- prdoc/pr_18.prdoc | 19 ++ 7 files changed, 604 insertions(+), 16 deletions(-) create mode 100644 prdoc/pr_18.prdoc diff --git a/AGENTS.md b/AGENTS.md index fcebec8..c1bb136 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -21,6 +21,13 @@ The `forehead.toml` file defines project metadata, header templates, path-based - `indicators` — extra keywords on top of built-in defaults (`Copyright`, `SPDX`, `License`) for header detection. Set to `["none"]` to disable all built-in defaults. - `greetings` — optional line prepended to every header. Supports template placeholders. +### Top-level `ignore` field + +- `ignore` — list of file/dir names or relative path suffixes to exclude from processing, e.g. `ignore = ["vendor", "generated.rs"]`. Defaults to `[]`. +- The legacy key name `skip` is still accepted as an alias for backward compatibility. +- TOML files are always ignored by default; `Cargo.toml` is still processed for its `license` field. +- Applying headers is idempotent — stale license headers found anywhere in a file are replaced, never duplicated. + ## Invariants - All source files must have a correct license header diff --git a/packages/forehead-cli/src/commands.rs b/packages/forehead-cli/src/commands.rs index 6d30ef5..ff3a0fd 100644 --- a/packages/forehead-cli/src/commands.rs +++ b/packages/forehead-cli/src/commands.rs @@ -206,6 +206,10 @@ template = "mit-apache" # Optional line prepended to every header. Supports template placeholders. # greetings = "بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيم" +# Directories or files to exclude by name or relative path suffix. +# TOML files are always ignored by default (Cargo.toml is still synced). +# ignore = ["vendor", "generated.rs"] + [file_types] "#; diff --git a/packages/forehead-core/README.md b/packages/forehead-core/README.md index 7220cd8..9570a0c 100644 --- a/packages/forehead-core/README.md +++ b/packages/forehead-core/README.md @@ -30,6 +30,9 @@ let report = forehead.remove(false)?; - Template placeholders: `{project}`, `{author}`, `{year}`, `{year_span}`, `{license}`, `{repository}`, `{description}`, `{file}` - Optional greetings line prepended to every header - Headless detection, apply, check, and remove operations +- `ignore` list to exclude files/directories by name or path suffix +- TOML files skipped by default (Cargo.toml still gets its `license` field synced) +- Idempotent header application — stale license headers are replaced, never duplicated ## License diff --git a/packages/forehead-core/src/config.rs b/packages/forehead-core/src/config.rs index eff9108..40a93ba 100644 --- a/packages/forehead-core/src/config.rs +++ b/packages/forehead-core/src/config.rs @@ -61,11 +61,8 @@ pub struct Config { #[serde(default)] pub file_types: HashMap, - #[serde(default)] - pub skip: Vec, - - #[serde(default)] - pub include: Vec, + #[serde(default, alias = "skip")] + pub ignore: Vec, } #[derive(Debug, Clone, Default, Deserialize)] diff --git a/packages/forehead-core/src/header.rs b/packages/forehead-core/src/header.rs index ace863d..5fbc0d0 100644 --- a/packages/forehead-core/src/header.rs +++ b/packages/forehead-core/src/header.rs @@ -72,7 +72,13 @@ pub fn check_header_on_file( Ok(FileStatus::Wrong) } } - None => Ok(FileStatus::Missing), + None => { + if find_stale_header(&content, style, indicators).is_some() { + Ok(FileStatus::Wrong) + } else { + Ok(FileStatus::Missing) + } + } } } @@ -98,7 +104,13 @@ pub fn apply_header_to_file( } replace_header(&content, &existing, &expected, style) } - None => prepend_header(&content, &expected, style), + None => match find_stale_header(&content, style, indicators) { + Some((start, end)) => { + let rest = strip_stale_range(&content, start, end); + prepend_header(&rest, &expected, style) + } + None => prepend_header(&content, &expected, style), + }, }; if new_content == content { @@ -128,7 +140,10 @@ pub fn remove_header_from_file( let after = content[existing.len()..].trim_start(); after.to_string() } - None => return Ok(false), + None => match find_stale_header(&content, style, indicators) { + Some((start, end)) => strip_stale_range(&content, start, end), + None => return Ok(false), + }, }; if new_content == content { @@ -165,10 +180,16 @@ pub fn replace_header_on_file( let after = content[existing.len()..].trim_start(); format!("{}\n\n{}", expected, after) } - None => { - let trimmed = content.trim_start(); - format!("{}\n\n{}", expected, trimmed) - } + None => match find_stale_header(&content, style, indicators) { + Some((start, end)) => { + let rest = strip_stale_range(&content, start, end); + format!("{}\n\n{}", expected, rest.trim_start()) + } + None => { + let trimmed = content.trim_start(); + format!("{}\n\n{}", expected, trimmed) + } + }, }; if new_content == content { @@ -310,6 +331,140 @@ fn extract_header_block( } } +// --------------------------------------------------------------------------- +// Stale-header detection helpers +// --------------------------------------------------------------------------- + +/// A line of file content along with its byte offset in the original string. +struct LineSlice<'a> { + text: &'a str, + start: usize, + end: usize, +} + +/// Collect lines from `content`, recording byte ranges so we can later slice +/// out blocks exactly as they appear (preserving line endings). +fn collect_lines(content: &str) -> Vec> { + let mut lines = Vec::new(); + let mut start = 0usize; + for piece in content.split_terminator('\n') { + let text = piece.strip_suffix('\r').unwrap_or(piece); + let end = content.len().min(start + piece.len() + 1); + lines.push(LineSlice { text, start, end }); + start += piece.len() + 1; + } + lines +} + +/// Extract a contiguous comment block from `lines` starting at index `start`. +/// Returns the inclusive line index range `(start, end)` — the block spans +/// `lines[start..end]`. +fn extract_block_lines( + lines: &[LineSlice<'_>], + start: usize, + style: &CommentStyle, +) -> Option<(usize, usize)> { + match style { + CommentStyle::Line(prefix) => { + if !lines[start].text.trim().starts_with(prefix.as_str()) { + return None; + } + let mut end = start + 1; + while end < lines.len() { + let trimmed = lines[end].text.trim(); + if trimmed.starts_with(prefix.as_str()) || trimmed.is_empty() { + end += 1; + } else { + break; + } + } + Some((start, end)) + } + CommentStyle::Block(open, close) => { + if !lines[start].text.trim().starts_with(open.as_str()) { + return None; + } + let mut end = start + 1; + while end < lines.len() { + if lines[end].text.trim().ends_with(close.as_str()) { + return Some((start, end + 1)); + } + end += 1; + } + None + } + CommentStyle::BlockTriple(_delim) => { + if lines[start].text.trim() != "\"\"\"" && lines[start].text.trim() != "'''" { + return None; + } + let mut end = start + 1; + while end < lines.len() { + let trimmed = lines[end].text.trim(); + if trimmed == "\"\"\"" || trimmed == "'''" { + return Some((start, end + 1)); + } + end += 1; + } + None + } + } +} + +/// Check whether any line in the given block lines contains a header indicator. +fn block_has_indicator(block_lines: &[LineSlice<'_>], indicators: &[String]) -> bool { + if indicators.is_empty() { + return true; + } + block_lines + .iter() + .any(|l| is_header_line(l.text.trim(), indicators)) +} + +/// Find the first comment block anywhere in the file that contains a header +/// indicator. Used to detect stale license headers not located at the top of +/// the file so they can be replaced rather than duplicated. +/// +/// Returns the byte range `[start, end)` of the block in `content`. +fn find_stale_header( + content: &str, + style: &CommentStyle, + indicators: &[String], +) -> Option<(usize, usize)> { + let lines = collect_lines(content); + let mut i = 0; + while i < lines.len() { + let trimmed = lines[i].text.trim(); + let is_comment_start = match style { + CommentStyle::Line(prefix) => trimmed.starts_with(prefix.as_str()), + CommentStyle::Block(open, _) => trimmed.starts_with(open.as_str()), + CommentStyle::BlockTriple(_) => trimmed == "\"\"\"" || trimmed == "'''", + }; + if is_comment_start { + if let Some((li, lj)) = extract_block_lines(&lines, i, style) { + if block_has_indicator(&lines[li..lj], indicators) { + return Some((lines[li].start, lines[lj - 1].end)); + } + i = lj; + continue; + } + } + i += 1; + } + None +} + +/// Remove the stale header located at byte range `[start, end)` and return +/// the remaining content. +fn strip_stale_range(content: &str, start: usize, end: usize) -> String { + let before = content[..start].trim_end(); + let after = content[end..].trim_start(); + if before.is_empty() { + after.to_string() + } else { + format!("{}\n{}", before, after) + } +} + fn is_header_line(line: &str, indicators: &[String]) -> bool { if indicators.is_empty() { return true; @@ -612,4 +767,150 @@ mod tests { check_header_on_file_str_with(content, &template, &style, &subst, &indicators, ""); assert_eq!(status, FileStatus::Wrong); } + + // ----------------------------------------------------------------------- + // Stale-header detection and dedup tests + // ----------------------------------------------------------------------- + + fn with_temp_file(content: &str, f: impl FnOnce(&std::path::Path)) { + let nanos = std::time::SystemTime::now() + .duration_since(std::time::UNIX_EPOCH) + .unwrap() + .as_nanos(); + let dir = + std::env::temp_dir().join(format!("forehead-test-{}-{nanos}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let path = dir.join("sample.rs"); + std::fs::write(&path, content).unwrap(); + f(&path); + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn test_find_stale_header_mid_file_line_style() { + let style = CommentStyle::Line("//".into()); + let indicators = default_indicators(); + let content = "use std::io;\n// Copyright (C) 2020 Old Author.\n// SPDX-License-Identifier: MIT\n\nfn main() {}\n"; + let range = find_stale_header(content, &style, &indicators); + assert!(range.is_some(), "stale header should be detected"); + let (start, end) = range.unwrap(); + let block = &content[start..end]; + assert!(block.contains("Copyright")); + assert!(block.contains("SPDX")); + assert!(start > 0, "stale header is not at the top"); + } + + #[test] + fn test_find_stale_header_absent_when_no_indicator() { + let style = CommentStyle::Line("//".into()); + let indicators = default_indicators(); + let content = "// A generic comment.\n// Without legal text.\n\nfn main() {}\n"; + assert!(find_stale_header(content, &style, &indicators).is_none()); + } + + #[test] + fn test_apply_replaces_stale_header_mid_file() { + let template = HeaderTemplate::new( + "This file is part of {project}.\nCopyright (C) {year_span} {author}.\nSPDX-License-Identifier: {license}.", + ); + let style = CommentStyle::Line("//".into()); + let subst = test_subst(); + let indicators = default_indicators(); + + let content = "use std::io;\n// Copyright (C) 2020 Old Author.\n// SPDX-License-Identifier: MIT\n\nfn main() {}\n"; + + with_temp_file(content, |path| { + // check reports wrong + assert!( + matches!( + check_header_on_file(path, &template, &style, &subst, &indicators, ""), + Ok(FileStatus::Wrong) + ), + "expected Wrong status for stale header" + ); + // apply returns true (modified) + assert!( + apply_header_to_file(path, &template, &style, &subst, false, &indicators, "") + .unwrap() + ); + let result = std::fs::read_to_string(path).unwrap(); + // New header at top, code preserved, old header gone + assert!( + result.starts_with("// This file is part of TestProject."), + "result starts with new header: {result:?}" + ); + assert!( + result.contains("use std::io;"), + "code before stale header is preserved" + ); + assert!(!result.contains("Old Author"), "old header text is removed"); + // Idempotent: second apply does nothing + assert!( + !apply_header_to_file(path, &template, &style, &subst, false, &indicators, "") + .unwrap() + ); + assert_eq!( + std::fs::read_to_string(path).unwrap(), + result, + "second apply is idempotent" + ); + }); + } + + #[test] + fn test_remove_strips_stale_header_mid_file() { + let style = CommentStyle::Line("//".into()); + let indicators = default_indicators(); + let content = "use std::io;\n// Copyright (C) 2020 Old Author.\n// SPDX-License-Identifier: MIT\n\nfn main() {}\n"; + + with_temp_file(content, |path| { + assert!(remove_header_from_file(path, &style, &indicators, false).unwrap()); + let result = std::fs::read_to_string(path).unwrap(); + assert!( + result.starts_with("use std::io;"), + "code before stale header preserved: {result:?}" + ); + assert!(!result.contains("SPDX"), "stale header removed"); + // Idempotent: second remove does nothing + assert!(!remove_header_from_file(path, &style, &indicators, false).unwrap()); + }); + } + + #[test] + fn test_apply_replaces_stale_block_header_after_code() { + let template = HeaderTemplate::new( + "This file is part of {project}.\nCopyright (C) {year_span} {author}.\nSPDX-License-Identifier: {license}.", + ); + let style = CommentStyle::Block("".into()); + let subst = test_subst(); + let indicators = default_indicators(); + let content = "\n\n\n\n"; + + with_temp_file(content, |path| { + // check reports wrong + assert!( + matches!( + check_header_on_file(path, &template, &style, &subst, &indicators, ""), + Ok(FileStatus::Wrong) + ), + "expected Wrong status for stale header" + ); + // apply replaces + assert!( + apply_header_to_file(path, &template, &style, &subst, false, &indicators, "") + .unwrap() + ); + let result = std::fs::read_to_string(path).unwrap(); + // New header at top (block style) + assert!( + result.starts_with("