|
| 1 | +import { promises as fs } from 'node:fs'; |
| 2 | +import path from 'node:path'; |
| 3 | +import * as core from '@actions/core'; |
| 4 | + |
| 5 | +const UNRELEASED_HEADING = `## Unreleased |
| 6 | +
|
| 7 | +- "You miss 100 percent of the chances you don't take. — Wayne Gretzky" — Michael Scott |
| 8 | +`; |
| 9 | + |
| 10 | +const contributorMessageRegex = /Work in this release was contributed by (.+)\. Thank you for your contribution!/; |
| 11 | + |
| 12 | +async function run() { |
| 13 | + const { getInput } = core; |
| 14 | + |
| 15 | + const name = getInput('name'); |
| 16 | + |
| 17 | + if (!name) { |
| 18 | + return; |
| 19 | + } |
| 20 | + |
| 21 | + const ghUserName = name.startsWith('@') ? name : `@${name}`; |
| 22 | + |
| 23 | + const cwd = process.cwd(); |
| 24 | + const changelogFilePath = path.resolve(cwd, 'CHANGELOG.md'); |
| 25 | + |
| 26 | + const changelogStr = await fs.readFile(changelogFilePath, 'utf8'); |
| 27 | + |
| 28 | + // Find the unreleased section |
| 29 | + const start = changelogStr.indexOf(UNRELEASED_HEADING) + UNRELEASED_HEADING.length; |
| 30 | + const end = changelogStr.slice(start).indexOf('## '); |
| 31 | + |
| 32 | + const inBetween = changelogStr.slice(start, start + end); |
| 33 | + |
| 34 | + const existing = contributorMessageRegex.exec(inBetween); |
| 35 | + |
| 36 | + // If the contributor message already exists, add the new contributor to the list |
| 37 | + if (existing) { |
| 38 | + const users = existing[1].split(/(?:,? and )|(?:, )/); |
| 39 | + if (!users.includes(ghUserName)) { |
| 40 | + users.push(ghUserName); |
| 41 | + } |
| 42 | + |
| 43 | + const formatter = new Intl.ListFormat('en', { |
| 44 | + style: 'long', |
| 45 | + type: 'conjunction', |
| 46 | + }); |
| 47 | + |
| 48 | + const newContributors = formatter.format(users); |
| 49 | + const newChangelog = changelogStr.replace( |
| 50 | + contributorMessageRegex, |
| 51 | + `Work in this release was contributed by ${newContributors}. Thank you for your contribution!`, |
| 52 | + ); |
| 53 | + |
| 54 | + fs.writeFile(changelogFilePath, newChangelog); |
| 55 | + |
| 56 | + // eslint-disable-next-line no-console |
| 57 | + console.log('Added contributor to list of existing contributors.'); |
| 58 | + return; |
| 59 | + } |
| 60 | + |
| 61 | + // If the contributor message does not exist, add it |
| 62 | + const newChangelog = changelogStr.replace( |
| 63 | + UNRELEASED_HEADING, |
| 64 | + `${UNRELEASED_HEADING}\nWork in this release was contributed by ${ghUserName}. Thank you for your contribution!\n`, |
| 65 | + ); |
| 66 | + fs.writeFile(changelogFilePath, newChangelog); |
| 67 | + |
| 68 | + // eslint-disable-next-line no-console |
| 69 | + console.log('Added contributor message.'); |
| 70 | +} |
| 71 | + |
| 72 | +run(); |
0 commit comments