|
| 1 | +import fs from 'fs-extra'; |
| 2 | +import { marked } from 'marked'; |
| 3 | +import SemanticReleaseError from '@semantic-release/error'; |
| 4 | +import getError from './get-error.js'; |
| 5 | + |
| 6 | +function stripLink(text: string): string { |
| 7 | + return text.replace(/\[([^\]]+)]\([^)]+\)/g, '$1'); |
| 8 | +} |
| 9 | +function stripEmoji(text: string): string { |
| 10 | + return text.replace(/:\w+:/g, '').trim(); |
| 11 | +} |
| 12 | + |
| 13 | +function stripCommitHash(text: string): string { |
| 14 | + return text.replace(/\(.+\)$/, '').trim(); |
| 15 | +} |
| 16 | + |
| 17 | +export async function prepareChangelog( |
| 18 | + readmePath: string, |
| 19 | + notes: string, |
| 20 | +): Promise<any> { |
| 21 | + const errors: SemanticReleaseError[] = []; |
| 22 | + const renderer = new marked.Renderer(); |
| 23 | + |
| 24 | + renderer.link = ({ text }) => text; |
| 25 | + renderer.heading = ({ text, depth }) => { |
| 26 | + if (depth === 2) { |
| 27 | + return `= ${stripLink(text)} =\n\n`; |
| 28 | + } |
| 29 | + |
| 30 | + if (depth === 3) { |
| 31 | + return `**${stripEmoji(text)}**\n\n`; |
| 32 | + } |
| 33 | + |
| 34 | + return `\n${text}\n\n`; |
| 35 | + }; |
| 36 | + renderer.list = ({ items }) => |
| 37 | + `${items.map((item) => renderer.listitem(item)).join('')}\n`; |
| 38 | + renderer.listitem = ({ text }) => `* ${stripCommitHash(stripLink(text))}\n`; |
| 39 | + |
| 40 | + const output = (await marked(notes, { renderer })) |
| 41 | + .replace(/\n{3,}/g, '\n\n') |
| 42 | + .trim(); |
| 43 | + |
| 44 | + const readmeText = fs |
| 45 | + .readFileSync(readmePath, 'utf-8') |
| 46 | + .replace('== Changelog ==', `== Changelog ==\n\n${output}`); |
| 47 | + |
| 48 | + try { |
| 49 | + fs.writeFileSync(readmePath, readmeText); |
| 50 | + } catch (err) { |
| 51 | + errors.push(getError('EFILECOPY', readmePath)); |
| 52 | + } |
| 53 | + |
| 54 | + return errors; |
| 55 | +} |
0 commit comments