pr_01m47d15m3e54sn21z27rpy5n9/apps/web/app/lib/commit-message.ts
| 1 | /** |
| 2 | * A commit message's parts: its subject, the prose of its body, and the |
| 3 | * trailers git and tools add at the end (`Co-Authored-By: …`), which read |
| 4 | * better as metadata than as prose. |
| 5 | */ |
| 6 | export type CommitMessage = { |
| 7 | subject: string; |
| 8 | body: string; |
| 9 | /** The names in `Co-Authored-By` trailers, without their addresses. */ |
| 10 | coAuthors: string[]; |
| 11 | /** Every other trailer, as written. */ |
| 12 | trailers: { key: string; value: string }[]; |
| 13 | }; |
| 14 | |
| 15 | const TRAILER = /^([A-Za-z][A-Za-z0-9-]*):\s+(.+)$/; |
| 16 | |
| 17 | export function parseCommitMessage(message: string): CommitMessage { |
| 18 | const [subject = "", ...rest] = message.split("\n"); |
| 19 | const lines = rest.join("\n").trim().split("\n"); |
| 20 | // Trailers are the last paragraph, when every line of it is one. |
| 21 | const lastBreak = lines.lastIndexOf(""); |
| 22 | const last = lines.slice(lastBreak + 1); |
| 23 | const isTrailers = last.length > 0 && last.every((line) => TRAILER.test(line.trim())); |
| 24 | const prose = isTrailers ? lines.slice(0, Math.max(lastBreak, 0)) : lines; |
| 25 | const coAuthors: string[] = []; |
| 26 | const trailers: { key: string; value: string }[] = []; |
| 27 | if (isTrailers) { |
| 28 | for (const line of last) { |
| 29 | const [, key, value] = TRAILER.exec(line.trim())!; |
| 30 | if (key.toLowerCase() === "co-authored-by") coAuthors.push(value.replace(/\s*<[^>]*>\s*$/, "").trim()); |
| 31 | else trailers.push({ key, value }); |
| 32 | } |
| 33 | } |
| 34 | return { subject, body: prose.join("\n").trim(), coAuthors, trailers }; |
| 35 | } |