Skip to main content

jouet_git/
conventional.rs

1//! Conventional-commit subjects: whether a repository asks for them, and
2//! what is wrong with a subject that is not one.
3//!
4//! A repository asks for them when a workflow checks them (a file under
5//! `.github/workflows/` that mentions conventional commits, commitlint or
6//! `action-semantic-pull-request`) or when it carries a commitlint,
7//! cocogitto or commitizen config. The rules are commitlint's
8//! `config-conventional` ones that matter for a subject: a known type, an
9//! optional `(scope)` and `!`, a description that does not start with a
10//! capitalised word (an acronym such as `CLI` is fine) or end with a period,
11//! and at most 100 characters.
12
13use std::path::Path;
14
15/// commitlint's `config-conventional` types, plus `security`.
16pub const DEFAULT_TYPES: &[&str] = &[
17    "build", "chore", "ci", "docs", "feat", "fix", "perf", "refactor", "revert", "security",
18    "style", "test",
19];
20
21const CONFIG_FILES: &[&str] = &[
22    ".commitlintrc",
23    ".commitlintrc.cjs",
24    ".commitlintrc.js",
25    ".commitlintrc.json",
26    ".commitlintrc.mjs",
27    ".commitlintrc.ts",
28    ".commitlintrc.yaml",
29    ".commitlintrc.yml",
30    "commitlint.config.cjs",
31    "commitlint.config.cts",
32    "commitlint.config.js",
33    "commitlint.config.mjs",
34    "commitlint.config.mts",
35    "commitlint.config.ts",
36    "cog.toml",
37    ".cz.json",
38    ".cz.toml",
39    ".czrc",
40    "cz.json",
41];
42
43const WORKFLOW_MARKERS: &[&str] = &[
44    "conventional-commit",
45    "conventional commit",
46    "conventionalcommits",
47    "action-semantic-pull-request",
48    "commitlint",
49];
50
51const MAX_HEADER: usize = 100;
52
53/// What `jouet commit` does with a subject that breaks the rules.
54#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
55pub enum Policy {
56    Off,
57    /// Commit anyway, with a warning.
58    #[default]
59    Warn,
60    /// Refuse to commit.
61    Refuse,
62}
63
64impl Policy {
65    pub fn parse(name: &str) -> Option<Self> {
66        match name {
67            "off" => Some(Self::Off),
68            "warn" => Some(Self::Warn),
69            "refuse" => Some(Self::Refuse),
70            _ => None,
71        }
72    }
73}
74
75/// The file that shows a repository wants conventional commits, relative to
76/// its top, or `None` when nothing does.
77pub fn detect(top: &Path) -> Option<String> {
78    if let Some(file) = CONFIG_FILES.iter().find(|f| top.join(f).is_file()) {
79        return Some((*file).to_string());
80    }
81    let workflows = top.join(".github").join("workflows");
82    let mut names: Vec<_> = std::fs::read_dir(&workflows)
83        .ok()?
84        .flatten()
85        .map(|e| e.file_name().to_string_lossy().into_owned())
86        .filter(|n| n.ends_with(".yml") || n.ends_with(".yaml"))
87        .collect();
88    names.sort();
89    names.into_iter().find_map(|name| {
90        let lower_name = name.to_ascii_lowercase();
91        let text = std::fs::read_to_string(workflows.join(&name))
92            .unwrap_or_default()
93            .to_ascii_lowercase();
94        let marked = lower_name.contains("conventional")
95            || WORKFLOW_MARKERS.iter().any(|m| text.contains(m));
96        marked.then(|| format!(".github/workflows/{name}"))
97    })
98}
99
100/// What is wrong with a commit message's subject (and the line after it),
101/// in the order a reader would fix them; empty when nothing is.
102pub fn lint(message: &str, types: &[String]) -> Vec<String> {
103    let mut problems = Vec::new();
104    let mut lines = message.lines();
105    let subject = lines.next().unwrap_or_default();
106    if lines.next().is_some_and(|l| !l.trim().is_empty()) {
107        problems.push("leave a blank line between the subject and the body".into());
108    }
109    let Some(caps) = header().captures(subject) else {
110        problems.insert(
111            0,
112            "the subject is not `type(scope): description` (the scope and a `!` are optional)"
113                .into(),
114        );
115        return problems;
116    };
117    let kind = &caps["type"];
118    if !types.iter().any(|t| t == kind) {
119        problems.push(format!(
120            "unknown type `{kind}`; use one of {}",
121            types.join(", ")
122        ));
123    }
124    let description = &caps["description"];
125    if starts_capitalised(description) {
126        problems
127            .push("start the description lowercase, or with an acronym such as CLI or PGO".into());
128    }
129    if description.ends_with('.') {
130        problems.push("do not end the subject with a period".into());
131    }
132    let length = subject.chars().count();
133    if length > MAX_HEADER {
134        problems.push(format!(
135            "the subject is {length} characters; keep it to {MAX_HEADER}"
136        ));
137    }
138    problems
139}
140
141fn header() -> &'static regex::Regex {
142    static HEADER: std::sync::OnceLock<regex::Regex> = std::sync::OnceLock::new();
143    HEADER.get_or_init(|| {
144        regex::Regex::new(r"^(?<type>[a-z]+)(\([^()\s][^()]*\))?!?: (?<description>\S.*)$")
145            .expect("the header pattern compiles")
146    })
147}
148
149/// Whether the description starts with a capitalised word that is not an
150/// acronym: `Add` is, `CLI` and `add` are not.
151fn starts_capitalised(description: &str) -> bool {
152    let word: String = description
153        .chars()
154        .take_while(|c| c.is_alphanumeric())
155        .collect();
156    let mut chars = word.chars();
157    match chars.next() {
158        Some(first) if first.is_uppercase() => {
159            let rest: Vec<char> = chars.collect();
160            rest.is_empty() || !rest.iter().all(|c| c.is_uppercase() || c.is_ascii_digit())
161        }
162        _ => false,
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    fn types() -> Vec<String> {
171        DEFAULT_TYPES.iter().map(|t| (*t).to_string()).collect()
172    }
173
174    #[test]
175    fn good_subjects_pass() {
176        for subject in [
177            "feat: add jouet commit",
178            "feat(git): add jouet commit, review-package and handoff",
179            "fix(wait)!: stop following a closed PR",
180            "docs: describe the CLI",
181            "perf: cut PGO build time",
182            "chore: release 0.1.0\n\nThe body is fine.",
183        ] {
184            assert_eq!(lint(subject, &types()), Vec::<String>::new(), "{subject}");
185        }
186    }
187
188    #[test]
189    fn bad_subjects_say_why() {
190        let problems = |s: &str| lint(s, &types());
191        assert!(problems("Add a thing")[0].contains("not `type(scope): description`"));
192        assert!(problems("feature: add")[0].contains("unknown type `feature`"));
193        assert!(problems("feat: Add commit")[0].contains("lowercase"));
194        assert!(problems("feat: A thing")[0].contains("lowercase"));
195        assert!(problems("feat: add commit.")[0].contains("period"));
196        assert!(problems(&format!("feat: {}", "x".repeat(100)))[0].contains("characters"));
197        assert!(problems("feat: add\nbody right away")[0].contains("blank line"));
198        assert!(problems("feat:add")[0].contains("not `type"));
199        assert!(problems("feat(): add")[0].contains("not `type"));
200    }
201
202    #[test]
203    fn configured_types_replace_the_defaults() {
204        let types = vec!["registry".to_string()];
205        assert!(lint("registry: add jouet", &types).is_empty());
206        assert!(!lint("feat: add jouet", &types).is_empty());
207    }
208
209    #[test]
210    fn detection_reads_configs_and_workflows() {
211        let dir = tempfile::tempdir().unwrap();
212        assert_eq!(detect(dir.path()), None);
213        let workflows = dir.path().join(".github/workflows");
214        std::fs::create_dir_all(&workflows).unwrap();
215        std::fs::write(workflows.join("ci.yml"), "on: push\n").unwrap();
216        assert_eq!(detect(dir.path()), None);
217        std::fs::write(
218            workflows.join("title.yaml"),
219            "steps:\n  - uses: amannn/action-semantic-pull-request@v5\n",
220        )
221        .unwrap();
222        assert_eq!(
223            detect(dir.path()).as_deref(),
224            Some(".github/workflows/title.yaml")
225        );
226        std::fs::write(dir.path().join("cog.toml"), "").unwrap();
227        assert_eq!(detect(dir.path()).as_deref(), Some("cog.toml"));
228    }
229}