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/Cargo.toml b/Cargo.toml index ddf6d76..c5245d1 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,7 +7,7 @@ members = [ ] [workspace.package] -version = "0.2.1" +version = "0.2.2" edition = "2021" license = "Apache-2.0 OR MIT" authors = ["Afsall Inc"] diff --git a/changelogger.toml b/changelogger.toml index 6b0980b..7aee3aa 100644 --- a/changelogger.toml +++ b/changelogger.toml @@ -1,40 +1,3 @@ -# بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيم -# This file is part of forehead. -# -# Copyright (C) 2026-Present Afsall Inc. -# SPDX-License-Identifier: Apache-2.0 OR MIT -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Alternatively, this file is available under the MIT License: -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - version = 1 schema = "prdoc/schema_user.json" output_dir = "prdoc" diff --git a/mise.toml b/mise.toml index a563c08..53f2670 100644 --- a/mise.toml +++ b/mise.toml @@ -1,40 +1,3 @@ -# بِسْمِ اللَّهِ الرَّحْمَنِ الرَّحِيم -# This file is part of forehead. -# -# Copyright (C) 2026-Present Afsall Inc. -# SPDX-License-Identifier: Apache-2.0 OR MIT -# -# Licensed under the Apache License, Version 2.0 (the "License"); -# you may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. -# -# Alternatively, this file is available under the MIT License: -# Permission is hereby granted, free of charge, to any person obtaining a copy -# of this software and associated documentation files (the "Software"), to deal -# in the Software without restriction, including without limitation the rights -# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -# copies of the Software, and to permit persons to whom the Software is -# furnished to do so, subject to the following conditions: -# -# The above copyright notice and this permission notice shall be included in all -# copies or substantial portions of the Software. -# -# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -# SOFTWARE. - [tools] rust = "1.84" @@ -57,4 +20,4 @@ depends = ["fmt", "headers", "clippy", "test", "build"] [tasks.changelogger] description = "Install changelogger-cli v0.2.2" -run = "cargo install changelogger-cli --version 0.2.2" \ No newline at end of file +run = "cargo install changelogger-cli --version 0.2.2" diff --git a/packages/forehead-cli/Cargo.toml b/packages/forehead-cli/Cargo.toml index 36e2a29..cc7f351 100644 --- a/packages/forehead-cli/Cargo.toml +++ b/packages/forehead-cli/Cargo.toml @@ -9,7 +9,7 @@ description.workspace = true readme = "README.md" [dependencies] -forehead-core = { path = "../forehead-core", version = "0.2.1" } +forehead-core = { path = "../forehead-core", version = "0.2.2" } clap.workspace = true anyhow.workspace = true serde.workspace = true 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("