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
338/// A subject git itself wrote, or one that exists only to be autosquashed
339/// away.
340///
341/// Exact prefixes, space and quote included, so a HUMAN subject like
342/// "Merges: cleanup" or "fixup the parser" is still judged — only the shapes
343/// git's own porcelain emits stand aside. The trade is that a hand-written
344/// "Merge the two configs" passes unjudged; commitlint draws the same line,
345/// and the alternative blocks `git merge` itself.
346fn git_generated(subject: &str) -> bool {
347 [
348 "Merge ",
349 "Revert \"",
350 "Reapply \"",
351 "fixup! ",
352 "squash! ",
353 "amend! ",
354 ]
355 .iter()
356 .any(|p| subject.starts_with(p))
357}
358
359pub fn run(args: &[std::ffi::OsString]) -> Verdict {
360 let Some(filename) = args.first().and_then(|a| a.to_str()) else {
361 println!("Usage:\n\n./commit-msg <filename>");
362 return Verdict::Block;
363 };
364 let Ok(raw) = std::fs::read_to_string(filename) else {
365 return Verdict::Block;
366 };
367 let style = Style::resolve();
368 let cleaned = strip_comments(&raw);
369 let mut parts = cleaned.splitn(2, '\n');
370 let subject_line = parts.next().unwrap_or("");
371
372 // Messages GIT writes are passed through, not judged. `git merge` invokes
373 // this hook (githooks(5)) with "Merge branch '…'"; `git revert` writes
374 // `Revert "…"` (and `Reapply "…"` for a revert of a revert); `--fixup`
375 // and `--squash` write `fixup!`/`squash!`/`amend!` subjects that exist
376 // only to be autosquashed away before anyone reads them. None of these
377 // can carry a conventional type — blocking them blocks the porcelain
378 // that produced them, and the workaround people reach for is
379 // `--no-verify`, which turns off the checks that DO apply to them.
380 // Said out loud, because a check that stands aside silently is the
381 // invisibility this project refuses everywhere else.
382 if git_generated(subject_line) {
383 valid("A message git itself wrote — the convention is not applied");
384 return Verdict::Proceed;
385 }
386 // Everything after the subject's own newline — blank separator lines
387 // included. The format string below writes that blank line itself, so
388 // leaving them here means writing one MORE each time.
389 //
390 // That is not hypothetical: it shipped. Re-running the hook over a message
391 // it had already formatted — `--amend`, a rebase reword, a `--no-verify`
392 // retry — grew the gap between subject and body by one line every single
393 // time. Nothing caught it because the idempotence test covered
394 // `group_footer` alone rather than the whole rewrite.
395 let body = parts.next().unwrap_or("").trim_start_matches('\n');
396
397 // Our own decoration comes off before anything is counted or parsed. On a
398 // first commit there is none; on an amend there is, and measuring it would
399 // fail a subject that was accepted five seconds earlier.
400 let undecorated = undecorate(subject_line);
401 let written = undecorated.text;
402
403 if written.is_empty() || written.chars().count() > style.subject_max {
404 error(&format!(
405 "Commit's first line should exist and be at most {} characters.",
406 orange(&style.subject_max.to_string())
407 ));
408 return Verdict::Block;
409 }
410 valid(&format!(
411 "Summary size is at most {} characters",
412 orange(&style.subject_max.to_string())
413 ));
414
415 let types: Vec<String> = COMMIT_TYPES.iter().map(|t| orange(t.name)).collect();
416 let subject = match parse_subject(written) {
417 Some(s) => s,
418 // No type in the text — but if a gitmoji of ours opened the line, the
419 // type IS there, carried by the emoji. That is the `replace` placement
420 // being handed back its own output.
421 None => match undecorated.recovered_type {
422 Some(t) => recovered_subject(t, written),
423 None => {
424 error(&format!(
425 "Commits MUST be prefixed with a type, which consists of a noun:
426 {}
427 The prefix must be followed by the OPTIONAL scope, OPTIONAL !,
428 and REQUIRED terminal colon and space.
429 A scope MAY be provided after a type. A scope MUST consist of a noun describing
430 a section of the codebase surrounded by parenthesis, e.g., fix(parser)",
431 types.join(", ")
432 ));
433 return Verdict::Block;
434 }
435 },
436 };
437 valid("A prefix is defined");
438
439 // The `suffix` placement's half of the same round trip.
440 let description = undecorate_tail(&subject.description, vocabulary::emoji_for(&subject.prefix));
441
442 if description.is_empty() {
443 error(&format!(
444 "A description MUST immediately follow the {} and {} after the type/scope prefix.
445 The description is a short summary of the code changes, e.g., fix: array parsing issue when multiple spaces were contained in string.",
446 orange("colon"), orange("space")
447 ));
448 return Verdict::Block;
449 }
450 valid("A description is present in the summary");
451
452 if description.chars().count() > style.description_max {
453 error(&format!(
454 "The description after the {} should be at most {} characters.",
455 orange("colon"),
456 orange(&style.description_max.to_string())
457 ));
458 return Verdict::Block;
459 }
460 valid(&format!(
461 "Description size is at most {} characters",
462 orange(&style.description_max.to_string())
463 ));
464
465 let formatted = format!(
466 "{}\n\n{}\n",
467 commit_style::render_subject(
468 style.gitmoji,
469 &subject.prefix,
470 &subject.scope,
471 &subject.breaking,
472 description,
473 ),
474 wrap_body(&strip_comments(body), style.body_wrap)
475 );
476 if std::fs::write(filename, group_footer(&formatted)).is_err() {
477 return Verdict::Block;
478 }
479 Verdict::Proceed
480}
481
482/// The body, wrapped — or left exactly as written when the wrap column is `0`.
483///
484/// `0` is what keeps a pasted stack trace, a table or a fenced code block
485/// intact. Hard-wrapping those is the one thing this hook does that cannot be
486/// undone by reading the message again.
487fn wrap_body(body: &str, column: usize) -> String {
488 if column == 0 {
489 body.to_string()
490 } else {
491 wrap(body, column)
492 }
493}
494
495#[cfg(test)]
496mod tests {
497 use super::*;
498
499 #[test]
500 fn parses_the_conventional_shapes() {
501 let s = parse_subject("feat: add a thing").unwrap();
502 assert_eq!(
503 (s.prefix.as_str(), s.description.as_str()),
504 ("feat", "add a thing")
505 );
506
507 let s = parse_subject("fix(parser): trim").unwrap();
508 assert_eq!(s.scope, "(parser)");
509
510 let s = parse_subject("fix(my-scope): trim").unwrap();
511 assert_eq!(s.scope, "(my-scope)");
512
513 let s = parse_subject("feat!: breaking").unwrap();
514 assert_eq!(s.breaking, "!");
515 }
516
517 /// The bug the JS was patched for: only the BASE codepoint was consumed, so
518 /// the trailing U+FE0F sat between emoji and type and the subject failed to
519 /// match. Every one of these must parse.
520 #[test]
521 fn accepts_emoji_prefixes_including_multi_codepoint_ones() {
522 for subject in [
523 "✨ feat: x",
524 "⬆️ chore: x", // variation selector
525 "♻️ refactor: x", // variation selector + two spaces
526 "🔧 chore: x",
527 "👨💻 feat: x", // ZWJ sequence
528 ] {
529 assert!(parse_subject(subject).is_some(), "failed: {subject}");
530 }
531 }
532
533 #[test]
534 fn rejects_what_is_not_a_conventional_subject() {
535 assert!(parse_subject("just a message").is_none());
536 assert!(parse_subject("feat add a thing").is_none()); // no colon
537 assert!(parse_subject("feature: x").is_none()); // unknown type
538 assert!(parse_subject("fix(bad scope): x").is_none()); // space in scope
539 }
540
541 #[test]
542 fn description_may_be_empty_and_is_caught_by_the_caller() {
543 assert_eq!(parse_subject("feat:").unwrap().description, "");
544 }
545
546 #[test]
547 fn wraps_on_spaces_without_splitting_long_words() {
548 let wrapped = wrap("aaa bbb ccc ddd", 7);
549 assert_eq!(wrapped, "aaa bbb\nccc ddd");
550 let long = "x".repeat(20);
551 assert_eq!(wrap(&long, 7), long); // never split mid-word
552 }
553
554 #[test]
555 fn recognises_footers() {
556 assert!(is_footer("Co-Authored-By: someone"));
557 assert!(is_footer("BREAKING CHANGE: it broke"));
558 assert!(is_footer("Refs: #123"));
559 assert!(is_footer(""));
560 assert!(!is_footer("just prose"));
561 assert!(!is_footer("a sentence with - a dash"));
562 }
563
564 /// The bare (no-colon) form, `Refs #123` / `Refs 123`, is intentionally
565 /// also accepted — but "Refs" glued straight to a digit with no
566 /// separator is prose, not a reference, and must not be swept into the
567 /// footer group.
568 #[test]
569 fn a_bare_refs_needs_a_separator_not_just_a_leading_digit() {
570 assert!(is_footer("Refs #123"));
571 assert!(is_footer("Refs 123"));
572 assert!(
573 !is_footer("Refs42 was the original ticket."),
574 "prose starting with Refs+digit must not read as a footer"
575 );
576 }
577
578 /// A trailer key is only a trailer key when it STARTS its line.
579 ///
580 /// The formatted subject `fix: pre-commit: stop hanging` contains
581 /// `pre-commit: s`, which the old anywhere-in-the-line rule accepted — and
582 /// a subject read as a footer took the whole message down with it.
583 #[test]
584 fn a_key_must_start_the_line_to_be_a_footer() {
585 // Real trailers, at column 0.
586 assert!(is_footer("Co-Authored-By: someone"));
587 assert!(is_footer("Signed-off-by: someone"));
588 assert!(is_footer("Reviewed-by: a"));
589 // The subject shape this repo writes constantly.
590 assert!(!is_footer("fix: pre-commit: stop hanging"));
591 assert!(!is_footer("🐛 fix: pre-commit: stop hanging"));
592 // Prose that merely mentions a hyphenated word followed by a colon.
593 assert!(!is_footer("see the pre-commit: docs above"));
594 assert!(!is_footer(" Co-Authored-By: indented is not a trailer"));
595 // A bullet is not a key, and neither is a key with nothing after the
596 // hyphen.
597 assert!(!is_footer("-foo: bar"));
598 assert!(!is_footer("A-: bar"));
599 // Neither branch below is anchored by this rule; both still work.
600 assert!(is_footer("BREAKING CHANGE: it broke"));
601 assert!(is_footer("Refs: #123"));
602 }
603
604 #[test]
605 fn groups_the_trailing_footer_with_one_blank_line() {
606 let out = group_footer("subject\n\nbody text\n\nCo-Authored-By: x\n\n");
607 assert_eq!(out, "subject\n\nbody text\n\nCo-Authored-By: x\n");
608 }
609
610 /// The shapes a real message arrives in, for the property tests below.
611 ///
612 /// Every subject here is one that the old anywhere-in-the-line footer rule
613 /// misread as a trailer, crossed with each body/footer arrangement the
614 /// formatter emits.
615 const SHAPES: &[&str] = &[
616 // subject only
617 "fix: pre-commit: stop hanging",
618 "fix: pre-commit: stop hanging\n\n\n",
619 // body only
620 "fix: pre-commit: stop hanging\n\nthe worker thread blocked on a tty\n",
621 // trailers only
622 "fix: pre-commit: stop hanging\n\nCo-Authored-By: a <a@x>\n",
623 // body and trailers
624 "fix: pre-commit: stop hanging\n\nthe worker thread blocked\n\nCo-Authored-By: a <a@x>\n",
625 // body, trailers, trailing blanks
626 "fix: pre-commit: stop hanging\n\nthe worker thread blocked\n\nCo-Authored-By: a <a@x>\n\n\n",
627 // two footer PARAGRAPHS, which the run deliberately merges
628 "feat: x\n\nbody\n\nBREAKING CHANGE: it broke\n\nCo-Authored-By: a <a@x>\n",
629 // an ordinary subject, to prove nothing regressed for the common case
630 "feat: add a thing\n\nbody\n\nCo-Authored-By: a <a@x>\n",
631 ];
632
633 /// PROPERTY: grouping the footer never drops or invents a line, and never
634 /// moves the subject off line 0.
635 ///
636 /// Both halves failed together for the subject `fix: pre-commit: stop
637 /// hanging`: the whole message was swallowed into the footer group, blank
638 /// body lines inside it were filtered away, and the emitted line 0 was the
639 /// inserted blank rather than the subject.
640 #[test]
641 fn group_footer_never_loses_a_line() {
642 for shape in SHAPES {
643 let out = group_footer(shape);
644
645 let mut before: Vec<&str> = shape
646 .trim_end_matches('\n')
647 .split('\n')
648 .filter(|l| !l.is_empty())
649 .collect();
650 let mut after: Vec<&str> = out
651 .trim_end_matches('\n')
652 .split('\n')
653 .filter(|l| !l.is_empty())
654 .collect();
655 before.sort_unstable();
656 after.sort_unstable();
657 assert_eq!(before, after, "lines changed for {shape:?} -> {out:?}");
658
659 assert_eq!(
660 out.split('\n').next(),
661 shape.split('\n').next(),
662 "the subject left line 0 for {shape:?} -> {out:?}"
663 );
664 }
665 }
666
667 /// PROPERTY: grouping is idempotent. A message that has already been
668 /// formatted once — an amend, a rebase reword, a `--no-verify` retry — must
669 /// come back byte for byte.
670 #[test]
671 fn group_footer_is_idempotent() {
672 for shape in SHAPES {
673 let once = group_footer(shape);
674 let twice = group_footer(&once);
675 assert_eq!(once, twice, "not idempotent for {shape:?}");
676 }
677 }
678
679 /// The exact damage the anchor prevents: a blank line must stand between
680 /// the subject and the footer group, and the subject must never appear
681 /// inside it. Without the blank line git reads the trailer as a
682 /// continuation of the subject and `%(trailers)` comes back empty.
683 #[test]
684 fn a_subject_and_its_trailers_stay_separated() {
685 let out = group_footer("fix: pre-commit: stop hanging\n\nCo-Authored-By: a <a@x>\n");
686 assert_eq!(
687 out, "fix: pre-commit: stop hanging\n\nCo-Authored-By: a <a@x>\n",
688 "got: {out:?}"
689 );
690 assert!(
691 !out.starts_with('\n'),
692 "the message must not begin with a blank line: {out:?}"
693 );
694 }
695
696 #[test]
697 fn strips_comment_lines() {
698 assert_eq!(strip_comments("keep\n# drop\nkeep2"), "keep\nkeep2");
699 }
700
701 use crate::commit_style::{render_subject, Gitmoji};
702
703 /// The whole subject, as the hook would store it, for a message the author
704 /// typed conventionally.
705 fn store(placement: Gitmoji, typed: &str) -> String {
706 let s = parse_subject(typed).expect("test subjects parse");
707 render_subject(
708 placement,
709 &s.prefix,
710 &s.scope,
711 &s.breaking,
712 undecorate_tail(&s.description, vocabulary::emoji_for(&s.prefix)),
713 )
714 }
715
716 /// Re-read a stored subject the way `run` does, and store it again.
717 fn restore(placement: Gitmoji, stored: &str) -> String {
718 let u = undecorate(stored);
719 let s = match parse_subject(u.text) {
720 Some(s) => s,
721 None => recovered_subject(u.recovered_type.expect("a type to recover"), u.text),
722 };
723 render_subject(
724 placement,
725 &s.prefix,
726 &s.scope,
727 &s.breaking,
728 undecorate_tail(&s.description, vocabulary::emoji_for(&s.prefix)),
729 )
730 }
731
732 /// PROPERTY: writing a subject twice writes the same subject.
733 ///
734 /// `--amend`, a rebase reword and a `--no-verify` retry all hand this hook
735 /// a line it wrote itself. Without the undecorate step `suffix` grew an
736 /// emoji per amend and `replace` REJECTED its own output — the type it
737 /// demands had been replaced by the emoji it wrote.
738 #[test]
739 fn decorating_a_subject_is_idempotent() {
740 for typed in [
741 "feat: add a cart",
742 "fix(parser): trim",
743 "feat(api)!: drop v1",
744 "docs: explain the trust model",
745 ] {
746 for placement in Gitmoji::ALL {
747 let once = store(placement, typed);
748 let twice = restore(placement, &once);
749 assert_eq!(
750 once,
751 twice,
752 "{} is not idempotent for {typed:?}",
753 placement.as_str()
754 );
755 // And a third pass, since `suffix` grew by one emoji per run.
756 assert_eq!(twice, restore(placement, &twice));
757 }
758 }
759 }
760
761 /// Each placement puts the emoji where it says it does, and `none` leaves
762 /// the line alone.
763 #[test]
764 fn each_placement_puts_the_emoji_where_it_says() {
765 assert_eq!(store(Gitmoji::None, "feat: add a cart"), "feat: add a cart");
766 assert_eq!(
767 store(Gitmoji::Prefix, "feat: add a cart"),
768 "✨ feat: add a cart"
769 );
770 assert_eq!(
771 store(Gitmoji::Suffix, "feat: add a cart"),
772 "feat: add a cart ✨"
773 );
774 assert_eq!(
775 store(Gitmoji::Replace, "feat: add a cart"),
776 "✨ add a cart"
777 );
778 }
779
780 /// `suffix` keeps a clean conventional subject at the START of the line,
781 /// which is the reason to prefer it: commitlint and changelog generators
782 /// still see the type. `replace` deliberately does not, and the docs say so.
783 #[test]
784 fn suffix_leaves_the_type_where_tooling_looks_for_it() {
785 assert!(store(Gitmoji::Suffix, "fix: a bug").starts_with("fix:"));
786 assert!(!store(Gitmoji::Replace, "fix: a bug").starts_with("fix:"));
787 }
788
789 /// A scope and a breaking marker are not types, so `replace` keeps them.
790 /// They must also survive the round trip, which is why the recovery parses
791 /// the tail rather than treating everything after the emoji as prose.
792 #[test]
793 fn replace_keeps_a_scope_and_a_breaking_marker() {
794 let stored = store(Gitmoji::Replace, "feat(api)!: drop v1");
795 assert_eq!(stored, "✨ (api)!: drop v1");
796 let u = undecorate(&stored);
797 let s = recovered_subject(u.recovered_type.unwrap(), u.text);
798 assert_eq!(
799 (s.prefix.as_str(), s.scope.as_str(), s.breaking.as_str()),
800 ("feat", "(api)", "!")
801 );
802 assert_eq!(s.description, "drop v1");
803 }
804
805 /// The type is recovered from OUR emoji only. One the author chose is
806 /// theirs, and a subject carrying it still needs a real type word.
807 #[test]
808 fn only_our_own_emoji_recovers_a_type() {
809 assert_eq!(undecorate("✨ add a cart").recovered_type, Some("feat"));
810 assert_eq!(undecorate("🐛 fix: x").recovered_type, Some("fix"));
811 assert_eq!(undecorate("🚀 ship it").recovered_type, None);
812 assert_eq!(undecorate("feat: x").recovered_type, None);
813 // The text handed on is what remains once ours is off.
814 assert_eq!(undecorate("✨ add a cart").text, "add a cart");
815 assert_eq!(undecorate("🚀 ship it").text, "🚀 ship it");
816 }
817
818 /// The trailing half: only the emoji for THIS type is ours to remove.
819 #[test]
820 fn a_trailing_emoji_is_only_stripped_when_we_wrote_it() {
821 assert_eq!(undecorate_tail("add a cart ✨", "✨"), "add a cart");
822 assert_eq!(undecorate_tail("ship it 🚀", "✨"), "ship it 🚀");
823 assert_eq!(undecorate_tail("plain", "✨"), "plain");
824 assert_eq!(undecorate_tail("nothing to strip", ""), "nothing to strip");
825 }
826
827 /// PROPERTY: the limits measure what the author wrote.
828 ///
829 /// A subject at exactly the limit must stay acceptable after decoration —
830 /// otherwise the first amend of a maximal subject is rejected for length
831 /// the hook itself added.
832 #[test]
833 fn decoration_never_counts_against_the_limit() {
834 let typed = format!("feat: {}", "x".repeat(60));
835 assert_eq!(typed.chars().count(), 66);
836 for placement in Gitmoji::ALL {
837 let stored = store(placement, &typed);
838 let remeasured = undecorate(&stored);
839 let s = match parse_subject(remeasured.text) {
840 Some(s) => s,
841 None => recovered_subject(remeasured.recovered_type.unwrap(), remeasured.text),
842 };
843 let description = undecorate_tail(&s.description, vocabulary::emoji_for(&s.prefix));
844 assert_eq!(
845 description.chars().count(),
846 60,
847 "{} changed the measured description: {stored:?}",
848 placement.as_str()
849 );
850 }
851 }
852
853 #[test]
854 fn a_zero_wrap_column_leaves_the_body_alone() {
855 let long = "x ".repeat(100);
856 assert_eq!(wrap_body(&long, 0), long);
857 assert!(wrap_body(&long, 72).contains('\n'));
858 }
859}