Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add validate command #28

Merged
merged 6 commits into from
Apr 30, 2021
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 36 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ or

## CLI Usage

### Update

To update the 'Unreleased' section of the changelog:

`npx @metamask/auto-changelog update`
Expand All @@ -22,6 +24,16 @@ To update the current release section of the changelog:

`npx @metamask/auto-changelog update --rc`

### Validate

To validate the changelog:

`npx @metamask/auto-changelog validate`

To validate the changelog in a release candidate environment:

`npx @metamask/auto-changelog validate --rc`

## API Usage

Each supported command is a separate named export.
Expand All @@ -46,6 +58,30 @@ const updatedChangelog = updateChangelog({
await fs.writeFile('CHANEGLOG.md', updatedChangelog);
```

### `validateChangelog`

This command validates the changelog

```javascript
const fs = require('fs').promises;
const { validateChangelog } = require('@metamask/auto-changelog');

const oldChangelog = await fs.readFile('CHANEGLOG.md', {
encoding: 'utf8',
});
try {
validateChangelog({
changelogContent: oldChangelog,
currentVersion: '1.0.0',
repoUrl: 'https://github.com/ExampleUsernameOrOrganization/ExampleRepository',
isReleaseCandidate: false,
});
// changelog is valid!
} catch (error) {
// changelog is invalid
}
```

## Testing

Run `yarn test` to run the tests once.
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
},
"dependencies": {
"cross-spawn": "^7.0.3",
"diff": "^5.0.0",
"semver": "^7.3.5",
"yargs": "^16.2.0"
},
Expand Down
147 changes: 116 additions & 31 deletions src/cli.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,12 @@ const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');

const { updateChangelog } = require('./updateChangelog');
const { generateDiff } = require('./generateDiff');
const {
ChangelogFormattingError,
InvalidChangelogError,
validateChangelog,
} = require('./validateChangelog');
const { unreleased } = require('./constants');

const updateEpilog = `New commits will be added to the "${unreleased}" section (or \
Expand All @@ -17,6 +23,10 @@ changelog will be ignored.
If the '--rc' flag is used and the section for the current release does not \
yet exist, it will be created.`;

const validateEpilog = `This does not ensure that the changelog is complete, \
or that each change is in the correct section. It just ensures that the \
formatting is correct. Verification of the contents is left for manual review.`;
rekmarks marked this conversation as resolved.
Show resolved Hide resolved

// eslint-disable-next-line node/no-process-env
const npmPackageVersion = process.env.npm_package_version;
// eslint-disable-next-line node/no-process-env
Expand All @@ -32,36 +42,110 @@ function isValidUrl(proposedUrl) {
}
}

async function readChangelog(changelogFilename) {
return await fs.readFile(changelogFilename, {
encoding: 'utf8',
});
}

async function saveChangelog(changelogFilename, newChangelogContent) {
await fs.writeFile(changelogFilename, newChangelogContent);
}

async function update({
changelogFilename,
currentVersion,
isReleaseCandidate,
repoUrl,
}) {
const changelogContent = await readChangelog(changelogFilename);

const newChangelogContent = await updateChangelog({
changelogContent,
currentVersion,
repoUrl,
isReleaseCandidate,
});

await saveChangelog(changelogFilename, newChangelogContent);
console.log('CHANGELOG updated');
}

async function validate({
changelogFilename,
currentVersion,
isReleaseCandidate,
repoUrl,
}) {
const changelogContent = await readChangelog(changelogFilename);

try {
validateChangelog({
changelogContent,
currentVersion,
repoUrl,
isReleaseCandidate,
});
} catch (error) {
if (error instanceof ChangelogFormattingError) {
const { validChangelog, invalidChangelog } = error.data;
const diff = generateDiff(validChangelog, invalidChangelog);
console.error(`Changelog not well-formatted.\nDiff:\n${diff}`);
Gudahtt marked this conversation as resolved.
Show resolved Hide resolved
process.exit(1);
} else if (error instanceof InvalidChangelogError) {
console.error(`Changelog is invalid: ${error.message}`);
process.exit(1);
}
throw error;
}
}

function configureCommonCommandOptions(_yargs) {
return _yargs
.option('file', {
default: 'CHANGELOG.md',
description: 'The changelog file path',
type: 'string',
})
.option('currentVersion', {
default: npmPackageVersion,
description:
'The current version of the project that the changelog belongs to.',
type: 'string',
})
.option('repo', {
default: npmPackageRepositoryUrl,
description: `The GitHub repository URL`,
type: 'string',
});
}

async function main() {
const { argv } = yargs(hideBin(process.argv))
.command(
'update',
'Update CHANGELOG.md with any changes made since the most recent release.\nUsage: $0 update [options]',
(_yargs) =>
_yargs
configureCommonCommandOptions(_yargs)
.option('rc', {
default: false,
description: `Add new changes to the current release header, rather than to the '${unreleased}' section.`,
type: 'boolean',
})
.option('file', {
default: 'CHANGELOG.md',
description: 'The changelog file path',
type: 'string',
})
.option('currentVersion', {
default: npmPackageVersion,
description:
'The current version of the project that the changelog belongs to.',
type: 'string',
})
.option('repo', {
default: npmPackageRepositoryUrl,
description: `The GitHub repository URL`,
type: 'string',
})
.epilog(updateEpilog),
)
.command(
'validate',
'Validate the changelog, ensuring that it is well-formatted.\nUsage: $0 validate [options]',
(_yargs) =>
configureCommonCommandOptions(_yargs)
.option('rc', {
default: false,
description: `Verify that the current version has a release header in the changelog`,
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I left rc out of the "commonCommandOptions" group because it was helpful to have a separate description for this flag for each command, since it implies something a bit different in each case.

type: 'boolean',
})
.epilog(validateEpilog),
)
.strict()
.demandCommand()
.help('help')
Expand Down Expand Up @@ -106,20 +190,21 @@ async function main() {
process.exit(1);
}

const changelogContent = await fs.readFile(changelogFilename, {
encoding: 'utf8',
});

const newChangelogContent = await updateChangelog({
changelogContent,
currentVersion,
repoUrl,
isReleaseCandidate,
});

await fs.writeFile(changelogFilename, newChangelogContent);

console.log('CHANGELOG updated');
if (argv._ && argv._[0] === 'update') {
await update({
changelogFilename,
currentVersion,
isReleaseCandidate,
repoUrl,
});
} else if (argv._ && argv._[0] === 'validate') {
await validate({
changelogFilename,
currentVersion,
isReleaseCandidate,
repoUrl,
});
}
}

main().catch((error) => {
Expand Down
41 changes: 41 additions & 0 deletions src/generateDiff.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
const diff = require('diff');

/**
* Generates a diff between two multi-line strings. The resulting diff shows
* any changes using '-' and '+' to indicate the "old" and "new" version
* respectively, and includes 2 lines of unchanged content around each changed
* section where possible.
* @param {string} before - The string representing the base for the comparison.
* @param {string} after - The string representing the changes being compared.
* @returns {string} The genereated text diff
*/
function generateDiff(before, after) {
const changes = diff.diffLines(before, after);
const diffLines = [];
const preceedingContext = [];
Gudahtt marked this conversation as resolved.
Show resolved Hide resolved
for (const { added, removed, value } of changes) {
const lines = value.split('\n');
// remove trailing newline
lines.pop();
rekmarks marked this conversation as resolved.
Show resolved Hide resolved
if (added || removed) {
if (preceedingContext.length) {
diffLines.push(...preceedingContext);
preceedingContext.splice(0, preceedingContext.length);
}
diffLines.push(...lines.map((line) => `${added ? '+' : '-'}${line}`));
} else {
// If a changed line has been included already, add up to 2 lines of context
if (diffLines.length) {
diffLines.push(...lines.slice(0, 2).map((line) => ` ${line}`));
lines.splice(0, 2);
}
// stash last 2 lines for context in case there is another change
if (lines.length) {
preceedingContext.push(...lines.slice(-2));
}
rekmarks marked this conversation as resolved.
Show resolved Hide resolved
}
}
return diffLines.join('\n');
}

module.exports = { generateDiff };
6 changes: 6 additions & 0 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
const { updateChangelog } = require('./updateChangelog');
const {
ChangelogFormattingError,
validateChangelog,
} = require('./validateChangelog');

module.exports = {
ChangelogFormattingError,
updateChangelog,
validateChangelog,
};
Loading