Skip to main content

amont_runtime/hooks/
commit_msg.rs

1//! commit-msg — validate the summary line and reformat the message.
2//!
3//! Validates: a subject is present and within the subject limit; it carries a
4//! conventional type prefix; a description follows, within the description
5//! budget. Formats: place the type's gitmoji where the repository asked for it,
6//! hard-wrap the body, and group the trailing footers with one blank line
7//! before them.
8//!
9//! Every limit and the emoji placement are [`commit_style`] settings — four
10//! `git config` keys with shipped defaults. What this hook enforces is
11//! configurable; **that** it enforces is not.
12//!
13//! Two invariants hold across all four gitmoji placements:
14//!
15//! * **The limits measure what you wrote.** Decoration this hook added is
16//!   removed before anything is counted, so the emoji can never eat the budget
17//!   — and re-checking an already-decorated subject counts the same characters
18//!   the author was told about the first time.
19//! * **Re-running is a no-op.** `--amend`, a rebase reword and a `--no-verify`
20//!   retry all hand this hook a subject it already wrote. See [`undecorate`].
21//!
22//! Ported from ~190 lines of JS. The one structural simplification is how the
23//! optional leading emoji is recognised — see `split_leading_emoji`.
24
25use crate::check::Verdict;
26use crate::commit_style::{self, Style};
27use crate::ui::{error_sign, highlight, valid_sign};
28
29use crate::vocabulary::{self, COMMIT_TYPES};
30
31pub struct Subject {
32    pub prefix: String,
33    pub scope: String,
34    pub breaking: String,
35    pub description: String,
36}
37
38/// Drop full-line comments, as git itself does.
39pub fn strip_comments(msg: &str) -> String {
40    let mut out: Vec<&str> = Vec::new();
41    for line in msg.split('\n') {
42        if !line.starts_with('#') {
43            out.push(line);
44        }
45    }
46    out.join("\n")
47}
48
49/// Skip a leading emoji cluster.
50///
51/// The JS carried a ~2KB hand-maintained list of emoji codepoints, and had
52/// already been patched once because it matched only the BASE codepoint —
53/// leaving a stray variation selector (U+FE0F) between the emoji and the type,
54/// so a perfectly good `⬆️ chore: …` was rejected as having no prefix.
55///
56/// Inverting the test removes that whole class of bug: a conventional type is
57/// ASCII lowercase letters, so skip anything that is NOT ASCII, plus spaces.
58/// Strictly more permissive than the codepoint list, and permissive in the
59/// harmless direction — the type itself is still required below, so this only
60/// decides how much leading decoration gets stripped before re-adding ours.
61pub fn split_leading_emoji(subject: &str) -> &str {
62    subject.trim_start_matches(|c: char| !c.is_ascii() || c == ' ' || c == '\t')
63}
64
65/// `^\s*(emoji)?\s*(type)(\(scope\))?(!)?:\s*(.*)$` over the FIRST line only.
66///
67/// First line only is load-bearing: the JS once used /ms flags, so `^` matched
68/// any line start and a body quoting a conventional commit (a revert citing the
69/// commit it undid) was picked up as the subject and rewritten into it.
70pub fn parse_subject(subject_line: &str) -> Option<Subject> {
71    let rest = split_leading_emoji(subject_line);
72    let (prefix, rest) = COMMIT_TYPES
73        .iter()
74        .map(|t| t.name)
75        .find(|t| rest.starts_with(t))
76        .map(|t| (t.to_string(), &rest[t.len()..]))?;
77    let (scope, breaking, description) = parse_tail(rest)?;
78    Some(Subject {
79        prefix,
80        scope,
81        breaking,
82        description,
83    })
84}
85
86/// `(\(scope\))?(!)?:\s*(.*)` — everything after the type word.
87///
88/// Split out because the type is not always a word: under the `replace`
89/// gitmoji placement it is an emoji, and re-reading such a subject means
90/// recovering the type from the emoji and then parsing exactly this tail. One
91/// implementation, so a scoped, breaking subject survives an amend the same way
92/// an unscoped one does.
93fn parse_tail(rest: &str) -> Option<(String, String, String)> {
94    let (scope, rest) = if let Some(after) = rest.strip_prefix('(') {
95        let end = after.find(')')?;
96        let inner = &after[..end];
97        if inner.is_empty()
98            || !inner
99                .chars()
100                .all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
101        {
102            return None;
103        }
104        (format!("({inner})"), &after[end + 1..])
105    } else {
106        (String::new(), rest)
107    };
108
109    let (breaking, rest) = match rest.strip_prefix('!') {
110        Some(r) => ("!".to_string(), r),
111        None => (String::new(), rest),
112    };
113
114    let description = rest.strip_prefix(':')?.trim_start_matches(' ').to_string();
115    Some((scope, breaking, description))
116}
117
118/// A subject with the decoration this hook itself applied taken back off.
119pub struct Undecorated<'a> {
120    /// The type recovered from a leading emoji, when that emoji is one of ours.
121    ///
122    /// `Some` only matters for the `replace` placement, where the stored
123    /// subject carries its type nowhere else. Recovering it is what stops the
124    /// hook rejecting its own output on the next `--amend`.
125    pub recovered_type: Option<&'static str>,
126    /// The subject as the author wrote it — what every limit is measured on.
127    pub text: &'a str,
128}
129
130/// Take off a leading gitmoji that this hook wrote.
131///
132/// Only an emoji from `COMMIT_TYPES` counts, matched whole. An emoji the author
133/// chose is theirs: it stays in the text and it counts against the subject
134/// limit, because the limit is about what they wrote. `split_leading_emoji`
135/// remains deliberately more permissive for *parsing* — this is about
136/// *measuring*, and the two questions want different answers.
137pub fn undecorate(subject_line: &str) -> Undecorated<'_> {
138    let trimmed = subject_line.trim_start();
139    for t in COMMIT_TYPES {
140        if let Some(rest) = trimmed.strip_prefix(t.emoji) {
141            return Undecorated {
142                recovered_type: Some(t.name),
143                text: rest.trim_start(),
144            };
145        }
146    }
147    Undecorated {
148        recovered_type: None,
149        text: subject_line,
150    }
151}
152
153/// Take off a trailing gitmoji that this hook wrote — the `suffix` placement's
154/// half of [`undecorate`].
155///
156/// Matched against the emoji for *this* type only, so `feat: ship it 🚀` keeps
157/// the rocket the author chose while `feat: ship it ✨` gives back `ship it`.
158fn undecorate_tail<'a>(description: &'a str, emoji: &str) -> &'a str {
159    if emoji.is_empty() {
160        return description;
161    }
162    match description.trim_end().strip_suffix(emoji) {
163        Some(rest) => rest.trim_end(),
164        None => description,
165    }
166}
167
168/// The subject a `replace`-decorated line describes: type from the emoji,
169/// everything else parsed from what followed it.
170fn recovered_subject(prefix: &'static str, text: &str) -> Subject {
171    let (scope, breaking, description) = parse_tail(text).unwrap_or_else(|| {
172        // No `…:` after the emoji, so there is no scope to find and the whole
173        // remainder is the description — `✨  add a cart`, the common shape.
174        (String::new(), String::new(), text.to_string())
175    });
176    Subject {
177        prefix: prefix.to_string(),
178        scope,
179        breaking,
180        description,
181    }
182}
183
184/// Greedy hard wrap at `width`, breaking on spaces — the JS
185/// `(?![^\n]{1,w}$)([^\n]{1,w})\s` replace. A word longer than `width` is left
186/// intact rather than split.
187pub fn wrap(text: &str, width: usize) -> String {
188    let mut out: Vec<String> = Vec::new();
189    for line in text.split('\n') {
190        if line.chars().count() <= width {
191            out.push(line.to_string());
192            continue;
193        }
194        let mut current = String::new();
195        for word in line.split(' ') {
196            if current.is_empty() {
197                current.push_str(word);
198            } else if current.chars().count() + 1 + word.chars().count() <= width {
199                current.push(' ');
200                current.push_str(word);
201            } else {
202                out.push(std::mem::take(&mut current));
203                current.push_str(word);
204            }
205        }
206        if !current.is_empty() {
207            out.push(current);
208        }
209    }
210    out.join("\n")
211}
212
213/// A trailing footer line: `Key-Word: value`, `BREAKING CHANGE: …`, `Refs: #1`,
214/// or blank.
215pub fn is_footer(line: &str) -> bool {
216    if line.is_empty() {
217        return true;
218    }
219    if let Some(rest) = line
220        .strip_prefix("BREAKING CHANGE:")
221        .or_else(|| line.strip_prefix("BREAKING-CHANGE:"))
222    {
223        return rest.starts_with(' ')
224            && rest
225                .trim_start()
226                .starts_with(|c: char| c.is_alphanumeric() || c == '_');
227    }
228    // The bare (no-colon) form still needs a SEPARATOR after "Refs" — a
229    // space or a '#' — or it also matches prose that merely starts with
230    // those five letters glued to a digit, like "Refs42 was the original
231    // ticket.", sweeping a body line into the footer group.
232    if let Some(rest) = line.strip_prefix("Refs:").or_else(|| {
233        line.strip_prefix("Refs")
234            .filter(|rest| rest.starts_with(' ') || rest.starts_with('#'))
235    }) {
236        let r = rest.trim_start_matches(' ');
237        let r = r.strip_prefix('#').unwrap_or(r);
238        if r.starts_with(|c: char| c.is_ascii_digit()) {
239            return true;
240        }
241    }
242    is_hyphenated_key(line)
243}
244
245/// `^[\w][\w-]*-[\w-]*\w: \w` — a hyphenated trailer key that STARTS the line.
246///
247/// The anchor is the whole point. The rule used to be the JS regex
248/// `/\w-\w{1,}:\s\w/` applied ANYWHERE in the line, and this repo's own commit
249/// subjects match it: the formatted subject
250///
251/// ```text
252/// 🐛  fix: pre-commit: stop hanging
253/// ```
254///
255/// contains the fragment `pre-commit: s`, which satisfied `\w-\w+: \w`. So the
256/// SUBJECT read as a footer, `group_footer` walked the whole message from the
257/// bottom without ever hitting a non-footer line, and split at index 0 — the
258/// emitted message became `["", subject, trailer…]`. git strips the leading
259/// blank, which leaves the subject glued to the trailer block with no blank
260/// line between them, and `%(trailers)` returns EMPTY for a commit that plainly
261/// carries a `Co-Authored-By`. Silent, because the hook still exits 0.
262///
263/// Anchoring at column 0 keeps every real trailer (`Co-Authored-By: x`,
264/// `Signed-off-by: y`) and rejects both `fix: pre-commit: stop hanging` and
265/// prose like `see the pre-commit: docs above`, because in each of those the
266/// leading key run stops at the first space and holds no hyphen.
267fn is_hyphenated_key(line: &str) -> bool {
268    let key: String = line
269        .chars()
270        .take_while(|c| c.is_alphanumeric() || *c == '_' || *c == '-')
271        .collect();
272    // A key starts and ends with a word character — `-foo: x` is a bulleted
273    // list item, and `A-: x` was never a trailer either.
274    if !key.starts_with(|c: char| c.is_alphanumeric() || c == '_')
275        || !key.ends_with(|c: char| c.is_alphanumeric() || c == '_')
276        || !key.contains('-')
277    {
278        return false;
279    }
280    let Some(rest) = line[key.len()..].strip_prefix(": ") else {
281        return false;
282    };
283    rest.starts_with(|c: char| c.is_alphanumeric() || c == '_')
284}
285
286/// Separate the trailing run of footer lines, drop blanks inside it, and put
287/// exactly one blank line before the group.
288///
289/// The run deliberately crosses BLANK lines, which is what merges a
290/// `BREAKING CHANGE:` paragraph and a `Co-Authored-By:` paragraph into one
291/// footer block. That is a feature, not an accident, so this is not a
292/// "last paragraph only" rule.
293///
294/// The scan starts at `lines[1..]`: line 0 is the SUBJECT and can never be a
295/// footer, whatever it happens to look like. Without that anchor a subject
296/// misread as a footer (see `is_hyphenated_key`) let the run consume the entire
297/// message, `split_at` became 0, and the subject was emitted INSIDE the footer
298/// group with a blank line in front of it — destroying every trailer in the
299/// commit. `lines[1..]` makes `split_at >= 1` by construction; `split('\n')`
300/// never yields an empty vector, so the slice is always in range, and a
301/// single-line message falls out of the general path producing exactly what it
302/// produced before (`out = [subject, ""]`).
303pub fn group_footer(text: &str) -> String {
304    let trimmed = text.trim_end_matches('\n');
305    let lines: Vec<&str> = trimmed.split('\n').collect();
306    let mut footer_size = 0;
307    for line in lines[1..].iter().rev() {
308        if is_footer(line) {
309            footer_size += 1;
310        } else {
311            break;
312        }
313    }
314    let split_at = lines.len() - footer_size;
315    let body = &lines[..split_at];
316    let footer: Vec<&str> = lines[split_at..]
317        .iter()
318        .copied()
319        .filter(|l| !l.is_empty())
320        .collect();
321
322    let mut out: Vec<&str> = body.to_vec();
323    out.push("");
324    out.extend(footer);
325    format!("{}\n", out.join("\n"))
326}
327
328fn valid(msg: &str) {
329    println!("  {} {msg}", valid_sign().trim());
330}
331fn error(msg: &str) {
332    eprintln!("  {} {msg}", error_sign().trim());
333}
334fn orange(s: &str) -> String {
335    highlight(s)
336}
337
338pub fn run(args: &[std::ffi::OsString]) -> Verdict {
339    let Some(filename) = args.first().and_then(|a| a.to_str()) else {
340        println!("Usage:\n\n./commit-msg <filename>");
341        return Verdict::Block;
342    };
343    let Ok(raw) = std::fs::read_to_string(filename) else {
344        return Verdict::Block;
345    };
346    let style = Style::resolve();
347    let cleaned = strip_comments(&raw);
348    let mut parts = cleaned.splitn(2, '\n');
349    let subject_line = parts.next().unwrap_or("");
350    // Everything after the subject's own newline — blank separator lines
351    // included. The format string below writes that blank line itself, so
352    // leaving them here means writing one MORE each time.
353    //
354    // That is not hypothetical: it shipped. Re-running the hook over a message
355    // it had already formatted — `--amend`, a rebase reword, a `--no-verify`
356    // retry — grew the gap between subject and body by one line every single
357    // time. Nothing caught it because the idempotence test covered
358    // `group_footer` alone rather than the whole rewrite.
359    let body = parts.next().unwrap_or("").trim_start_matches('\n');
360
361    // Our own decoration comes off before anything is counted or parsed. On a
362    // first commit there is none; on an amend there is, and measuring it would
363    // fail a subject that was accepted five seconds earlier.
364    let undecorated = undecorate(subject_line);
365    let written = undecorated.text;
366
367    if written.is_empty() || written.chars().count() > style.subject_max {
368        error(&format!(
369            "Commit's first line should exist and be at most {} characters.",
370            orange(&style.subject_max.to_string())
371        ));
372        return Verdict::Block;
373    }
374    valid(&format!(
375        "Summary size is at most {} characters",
376        orange(&style.subject_max.to_string())
377    ));
378
379    let types: Vec<String> = COMMIT_TYPES.iter().map(|t| orange(t.name)).collect();
380    let subject = match parse_subject(written) {
381        Some(s) => s,
382        // No type in the text — but if a gitmoji of ours opened the line, the
383        // type IS there, carried by the emoji. That is the `replace` placement
384        // being handed back its own output.
385        None => match undecorated.recovered_type {
386            Some(t) => recovered_subject(t, written),
387            None => {
388                error(&format!(
389                    "Commits MUST be prefixed with a type, which consists of a noun:
390    {}
391    The prefix must be followed by the OPTIONAL scope, OPTIONAL !,
392    and REQUIRED terminal colon and space.
393    A scope MAY be provided after a type. A scope MUST consist of a noun describing
394    a section of the codebase surrounded by parenthesis, e.g., fix(parser)",
395                    types.join(", ")
396                ));
397                return Verdict::Block;
398            }
399        },
400    };
401    valid("A prefix is defined");
402
403    // The `suffix` placement's half of the same round trip.
404    let description = undecorate_tail(&subject.description, vocabulary::emoji_for(&subject.prefix));
405
406    if description.is_empty() {
407        error(&format!(
408            "A description MUST immediately follow the {} and {} after the type/scope prefix.
409    The description is a short summary of the code changes, e.g., fix: array parsing issue when multiple spaces were contained in string.",
410            orange("colon"), orange("space")
411        ));
412        return Verdict::Block;
413    }
414    valid("A description is present in the summary");
415
416    if description.chars().count() > style.description_max {
417        error(&format!(
418            "The description after the {} should be at most {} characters.",
419            orange("colon"),
420            orange(&style.description_max.to_string())
421        ));
422        return Verdict::Block;
423    }
424    valid(&format!(
425        "Description size is at most {} characters",
426        orange(&style.description_max.to_string())
427    ));
428
429    let formatted = format!(
430        "{}\n\n{}\n",
431        commit_style::render_subject(
432            style.gitmoji,
433            &subject.prefix,
434            &subject.scope,
435            &subject.breaking,
436            description,
437        ),
438        wrap_body(&strip_comments(body), style.body_wrap)
439    );
440    if std::fs::write(filename, group_footer(&formatted)).is_err() {
441        return Verdict::Block;
442    }
443    Verdict::Proceed
444}
445
446/// The body, wrapped — or left exactly as written when the wrap column is `0`.
447///
448/// `0` is what keeps a pasted stack trace, a table or a fenced code block
449/// intact. Hard-wrapping those is the one thing this hook does that cannot be
450/// undone by reading the message again.
451fn wrap_body(body: &str, column: usize) -> String {
452    if column == 0 {
453        body.to_string()
454    } else {
455        wrap(body, column)
456    }
457}
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462
463    #[test]
464    fn parses_the_conventional_shapes() {
465        let s = parse_subject("feat: add a thing").unwrap();
466        assert_eq!(
467            (s.prefix.as_str(), s.description.as_str()),
468            ("feat", "add a thing")
469        );
470
471        let s = parse_subject("fix(parser): trim").unwrap();
472        assert_eq!(s.scope, "(parser)");
473
474        let s = parse_subject("fix(my-scope): trim").unwrap();
475        assert_eq!(s.scope, "(my-scope)");
476
477        let s = parse_subject("feat!: breaking").unwrap();
478        assert_eq!(s.breaking, "!");
479    }
480
481    /// The bug the JS was patched for: only the BASE codepoint was consumed, so
482    /// the trailing U+FE0F sat between emoji and type and the subject failed to
483    /// match. Every one of these must parse.
484    #[test]
485    fn accepts_emoji_prefixes_including_multi_codepoint_ones() {
486        for subject in [
487            "✨ feat: x",
488            "⬆️ chore: x",     // variation selector
489            "♻️  refactor: x", // variation selector + two spaces
490            "🔧  chore: x",
491            "👨‍💻 feat: x", // ZWJ sequence
492        ] {
493            assert!(parse_subject(subject).is_some(), "failed: {subject}");
494        }
495    }
496
497    #[test]
498    fn rejects_what_is_not_a_conventional_subject() {
499        assert!(parse_subject("just a message").is_none());
500        assert!(parse_subject("feat add a thing").is_none()); // no colon
501        assert!(parse_subject("feature: x").is_none()); // unknown type
502        assert!(parse_subject("fix(bad scope): x").is_none()); // space in scope
503    }
504
505    #[test]
506    fn description_may_be_empty_and_is_caught_by_the_caller() {
507        assert_eq!(parse_subject("feat:").unwrap().description, "");
508    }
509
510    #[test]
511    fn wraps_on_spaces_without_splitting_long_words() {
512        let wrapped = wrap("aaa bbb ccc ddd", 7);
513        assert_eq!(wrapped, "aaa bbb\nccc ddd");
514        let long = "x".repeat(20);
515        assert_eq!(wrap(&long, 7), long); // never split mid-word
516    }
517
518    #[test]
519    fn recognises_footers() {
520        assert!(is_footer("Co-Authored-By: someone"));
521        assert!(is_footer("BREAKING CHANGE: it broke"));
522        assert!(is_footer("Refs: #123"));
523        assert!(is_footer(""));
524        assert!(!is_footer("just prose"));
525        assert!(!is_footer("a sentence with - a dash"));
526    }
527
528    /// The bare (no-colon) form, `Refs #123` / `Refs 123`, is intentionally
529    /// also accepted — but "Refs" glued straight to a digit with no
530    /// separator is prose, not a reference, and must not be swept into the
531    /// footer group.
532    #[test]
533    fn a_bare_refs_needs_a_separator_not_just_a_leading_digit() {
534        assert!(is_footer("Refs #123"));
535        assert!(is_footer("Refs 123"));
536        assert!(
537            !is_footer("Refs42 was the original ticket."),
538            "prose starting with Refs+digit must not read as a footer"
539        );
540    }
541
542    /// A trailer key is only a trailer key when it STARTS its line.
543    ///
544    /// The formatted subject `fix: pre-commit: stop hanging` contains
545    /// `pre-commit: s`, which the old anywhere-in-the-line rule accepted — and
546    /// a subject read as a footer took the whole message down with it.
547    #[test]
548    fn a_key_must_start_the_line_to_be_a_footer() {
549        // Real trailers, at column 0.
550        assert!(is_footer("Co-Authored-By: someone"));
551        assert!(is_footer("Signed-off-by: someone"));
552        assert!(is_footer("Reviewed-by: a"));
553        // The subject shape this repo writes constantly.
554        assert!(!is_footer("fix: pre-commit: stop hanging"));
555        assert!(!is_footer("🐛  fix: pre-commit: stop hanging"));
556        // Prose that merely mentions a hyphenated word followed by a colon.
557        assert!(!is_footer("see the pre-commit: docs above"));
558        assert!(!is_footer("  Co-Authored-By: indented is not a trailer"));
559        // A bullet is not a key, and neither is a key with nothing after the
560        // hyphen.
561        assert!(!is_footer("-foo: bar"));
562        assert!(!is_footer("A-: bar"));
563        // Neither branch below is anchored by this rule; both still work.
564        assert!(is_footer("BREAKING CHANGE: it broke"));
565        assert!(is_footer("Refs: #123"));
566    }
567
568    #[test]
569    fn groups_the_trailing_footer_with_one_blank_line() {
570        let out = group_footer("subject\n\nbody text\n\nCo-Authored-By: x\n\n");
571        assert_eq!(out, "subject\n\nbody text\n\nCo-Authored-By: x\n");
572    }
573
574    /// The shapes a real message arrives in, for the property tests below.
575    ///
576    /// Every subject here is one that the old anywhere-in-the-line footer rule
577    /// misread as a trailer, crossed with each body/footer arrangement the
578    /// formatter emits.
579    const SHAPES: &[&str] = &[
580        // subject only
581        "fix: pre-commit: stop hanging",
582        "fix: pre-commit: stop hanging\n\n\n",
583        // body only
584        "fix: pre-commit: stop hanging\n\nthe worker thread blocked on a tty\n",
585        // trailers only
586        "fix: pre-commit: stop hanging\n\nCo-Authored-By: a <a@x>\n",
587        // body and trailers
588        "fix: pre-commit: stop hanging\n\nthe worker thread blocked\n\nCo-Authored-By: a <a@x>\n",
589        // body, trailers, trailing blanks
590        "fix: pre-commit: stop hanging\n\nthe worker thread blocked\n\nCo-Authored-By: a <a@x>\n\n\n",
591        // two footer PARAGRAPHS, which the run deliberately merges
592        "feat: x\n\nbody\n\nBREAKING CHANGE: it broke\n\nCo-Authored-By: a <a@x>\n",
593        // an ordinary subject, to prove nothing regressed for the common case
594        "feat: add a thing\n\nbody\n\nCo-Authored-By: a <a@x>\n",
595    ];
596
597    /// PROPERTY: grouping the footer never drops or invents a line, and never
598    /// moves the subject off line 0.
599    ///
600    /// Both halves failed together for the subject `fix: pre-commit: stop
601    /// hanging`: the whole message was swallowed into the footer group, blank
602    /// body lines inside it were filtered away, and the emitted line 0 was the
603    /// inserted blank rather than the subject.
604    #[test]
605    fn group_footer_never_loses_a_line() {
606        for shape in SHAPES {
607            let out = group_footer(shape);
608
609            let mut before: Vec<&str> = shape
610                .trim_end_matches('\n')
611                .split('\n')
612                .filter(|l| !l.is_empty())
613                .collect();
614            let mut after: Vec<&str> = out
615                .trim_end_matches('\n')
616                .split('\n')
617                .filter(|l| !l.is_empty())
618                .collect();
619            before.sort_unstable();
620            after.sort_unstable();
621            assert_eq!(before, after, "lines changed for {shape:?} -> {out:?}");
622
623            assert_eq!(
624                out.split('\n').next(),
625                shape.split('\n').next(),
626                "the subject left line 0 for {shape:?} -> {out:?}"
627            );
628        }
629    }
630
631    /// PROPERTY: grouping is idempotent. A message that has already been
632    /// formatted once — an amend, a rebase reword, a `--no-verify` retry — must
633    /// come back byte for byte.
634    #[test]
635    fn group_footer_is_idempotent() {
636        for shape in SHAPES {
637            let once = group_footer(shape);
638            let twice = group_footer(&once);
639            assert_eq!(once, twice, "not idempotent for {shape:?}");
640        }
641    }
642
643    /// The exact damage the anchor prevents: a blank line must stand between
644    /// the subject and the footer group, and the subject must never appear
645    /// inside it. Without the blank line git reads the trailer as a
646    /// continuation of the subject and `%(trailers)` comes back empty.
647    #[test]
648    fn a_subject_and_its_trailers_stay_separated() {
649        let out = group_footer("fix: pre-commit: stop hanging\n\nCo-Authored-By: a <a@x>\n");
650        assert_eq!(
651            out, "fix: pre-commit: stop hanging\n\nCo-Authored-By: a <a@x>\n",
652            "got: {out:?}"
653        );
654        assert!(
655            !out.starts_with('\n'),
656            "the message must not begin with a blank line: {out:?}"
657        );
658    }
659
660    #[test]
661    fn strips_comment_lines() {
662        assert_eq!(strip_comments("keep\n# drop\nkeep2"), "keep\nkeep2");
663    }
664
665    use crate::commit_style::{render_subject, Gitmoji};
666
667    /// The whole subject, as the hook would store it, for a message the author
668    /// typed conventionally.
669    fn store(placement: Gitmoji, typed: &str) -> String {
670        let s = parse_subject(typed).expect("test subjects parse");
671        render_subject(
672            placement,
673            &s.prefix,
674            &s.scope,
675            &s.breaking,
676            undecorate_tail(&s.description, vocabulary::emoji_for(&s.prefix)),
677        )
678    }
679
680    /// Re-read a stored subject the way `run` does, and store it again.
681    fn restore(placement: Gitmoji, stored: &str) -> String {
682        let u = undecorate(stored);
683        let s = match parse_subject(u.text) {
684            Some(s) => s,
685            None => recovered_subject(u.recovered_type.expect("a type to recover"), u.text),
686        };
687        render_subject(
688            placement,
689            &s.prefix,
690            &s.scope,
691            &s.breaking,
692            undecorate_tail(&s.description, vocabulary::emoji_for(&s.prefix)),
693        )
694    }
695
696    /// PROPERTY: writing a subject twice writes the same subject.
697    ///
698    /// `--amend`, a rebase reword and a `--no-verify` retry all hand this hook
699    /// a line it wrote itself. Without the undecorate step `suffix` grew an
700    /// emoji per amend and `replace` REJECTED its own output — the type it
701    /// demands had been replaced by the emoji it wrote.
702    #[test]
703    fn decorating_a_subject_is_idempotent() {
704        for typed in [
705            "feat: add a cart",
706            "fix(parser): trim",
707            "feat(api)!: drop v1",
708            "docs: explain the trust model",
709        ] {
710            for placement in Gitmoji::ALL {
711                let once = store(placement, typed);
712                let twice = restore(placement, &once);
713                assert_eq!(
714                    once,
715                    twice,
716                    "{} is not idempotent for {typed:?}",
717                    placement.as_str()
718                );
719                // And a third pass, since `suffix` grew by one emoji per run.
720                assert_eq!(twice, restore(placement, &twice));
721            }
722        }
723    }
724
725    /// Each placement puts the emoji where it says it does, and `none` leaves
726    /// the line alone.
727    #[test]
728    fn each_placement_puts_the_emoji_where_it_says() {
729        assert_eq!(store(Gitmoji::None, "feat: add a cart"), "feat: add a cart");
730        assert_eq!(
731            store(Gitmoji::Prefix, "feat: add a cart"),
732            "✨  feat: add a cart"
733        );
734        assert_eq!(
735            store(Gitmoji::Suffix, "feat: add a cart"),
736            "feat: add a cart ✨"
737        );
738        assert_eq!(
739            store(Gitmoji::Replace, "feat: add a cart"),
740            "✨  add a cart"
741        );
742    }
743
744    /// `suffix` keeps a clean conventional subject at the START of the line,
745    /// which is the reason to prefer it: commitlint and changelog generators
746    /// still see the type. `replace` deliberately does not, and the docs say so.
747    #[test]
748    fn suffix_leaves_the_type_where_tooling_looks_for_it() {
749        assert!(store(Gitmoji::Suffix, "fix: a bug").starts_with("fix:"));
750        assert!(!store(Gitmoji::Replace, "fix: a bug").starts_with("fix:"));
751    }
752
753    /// A scope and a breaking marker are not types, so `replace` keeps them.
754    /// They must also survive the round trip, which is why the recovery parses
755    /// the tail rather than treating everything after the emoji as prose.
756    #[test]
757    fn replace_keeps_a_scope_and_a_breaking_marker() {
758        let stored = store(Gitmoji::Replace, "feat(api)!: drop v1");
759        assert_eq!(stored, "✨  (api)!: drop v1");
760        let u = undecorate(&stored);
761        let s = recovered_subject(u.recovered_type.unwrap(), u.text);
762        assert_eq!(
763            (s.prefix.as_str(), s.scope.as_str(), s.breaking.as_str()),
764            ("feat", "(api)", "!")
765        );
766        assert_eq!(s.description, "drop v1");
767    }
768
769    /// The type is recovered from OUR emoji only. One the author chose is
770    /// theirs, and a subject carrying it still needs a real type word.
771    #[test]
772    fn only_our_own_emoji_recovers_a_type() {
773        assert_eq!(undecorate("✨  add a cart").recovered_type, Some("feat"));
774        assert_eq!(undecorate("🐛  fix: x").recovered_type, Some("fix"));
775        assert_eq!(undecorate("🚀 ship it").recovered_type, None);
776        assert_eq!(undecorate("feat: x").recovered_type, None);
777        // The text handed on is what remains once ours is off.
778        assert_eq!(undecorate("✨  add a cart").text, "add a cart");
779        assert_eq!(undecorate("🚀 ship it").text, "🚀 ship it");
780    }
781
782    /// The trailing half: only the emoji for THIS type is ours to remove.
783    #[test]
784    fn a_trailing_emoji_is_only_stripped_when_we_wrote_it() {
785        assert_eq!(undecorate_tail("add a cart ✨", "✨"), "add a cart");
786        assert_eq!(undecorate_tail("ship it 🚀", "✨"), "ship it 🚀");
787        assert_eq!(undecorate_tail("plain", "✨"), "plain");
788        assert_eq!(undecorate_tail("nothing to strip", ""), "nothing to strip");
789    }
790
791    /// PROPERTY: the limits measure what the author wrote.
792    ///
793    /// A subject at exactly the limit must stay acceptable after decoration —
794    /// otherwise the first amend of a maximal subject is rejected for length
795    /// the hook itself added.
796    #[test]
797    fn decoration_never_counts_against_the_limit() {
798        let typed = format!("feat: {}", "x".repeat(60));
799        assert_eq!(typed.chars().count(), 66);
800        for placement in Gitmoji::ALL {
801            let stored = store(placement, &typed);
802            let remeasured = undecorate(&stored);
803            let s = match parse_subject(remeasured.text) {
804                Some(s) => s,
805                None => recovered_subject(remeasured.recovered_type.unwrap(), remeasured.text),
806            };
807            let description = undecorate_tail(&s.description, vocabulary::emoji_for(&s.prefix));
808            assert_eq!(
809                description.chars().count(),
810                60,
811                "{} changed the measured description: {stored:?}",
812                placement.as_str()
813            );
814        }
815    }
816
817    #[test]
818    fn a_zero_wrap_column_leaves_the_body_alone() {
819        let long = "x ".repeat(100);
820        assert_eq!(wrap_body(&long, 0), long);
821        assert!(wrap_body(&long, 72).contains('\n'));
822    }
823}