#!/usr/bin/env node

// Sets the release date of the current release in the changelog.
// This is run automatically when npm version is run.

const fs = require('fs');
const cp = require('child_process');

const suffix = process.env.PRERELEASE_SUFFIX || 'rc';

const changelog = fs.readFileSync('CHANGELOG.md', 'utf8');

// The changelog entry to be updated looks like this:
// ## Unreleased
// We need to add the version and release date in a YYYY-MM-DD format, so that it looks like this:
// ## 2.5.3 (2019-04-25)

const pkg = require('../../package.json');
const version = pkg.version.replace(new RegExp('-' + suffix + '\\..*'), '');

const unreleased = /^## Unreleased$/im;
const released = new RegExp(`^## ${version} \\([-\\d]*\\)$`, 'm');

if (released.test(changelog)) {
  process.exit(0);
}

if (!unreleased.test(changelog)) {
  console.error('Missing changelog entry');
  process.exit(1);
}

fs.writeFileSync('CHANGELOG.md', changelog.replace(
  unreleased,
  `## ${version} (${new Date().toISOString().split('T')[0]})`),
);

cp.execSync('git add CHANGELOG.md', { stdio: 'inherit' });

@@ -641,394 +641,374 @@
 nst 
-unreleased = /%5E## Unreleased$/im;%0Aconst released = new RegExp(%60%5E## $%7Bversion%7D %5C%5C(%5B-%5C%5Cd%5D*%5C%5C)$%60, 'm');%0A%0Aif (released.test(changelog)) %7B%0A  process.exit(0);%0A%7D%0A%0Aif (!unreleased.test(changelog)) %7B%0A  console.error('Missing changelog entry');%0A  process.exit(1);%0A%7D%0A%0Afs.writeFileSync('CHANGELOG.md', changelog.replace(%0A  unreleased,%0A  %60## $%7Bversion%7D ($%7Bnew Date().toISOString().split('T')%5B0%5D%7D)%60),
+header = new RegExp(%60%5E## (Unreleased%7C$%7Bversion%7D)$%60, 'm');%0A%0Aif (!header.test(changelog)) %7B%0A  console.error('Missing changelog entry');%0A  process.exit(1);%0A%7D%0A%0Aconst newHeader = pkg.version.indexOf(suffix) === -1%0A  ? %60## $%7Bversion%7D ($%7Bnew Date().toISOString().split('T')%5B0%5D%7D)%60%0A  : %60## $%7Bversion%7D%60;%0A%0Afs.writeFileSync('CHANGELOG.md',%0A  changelog.replace(header, newHeader)
 %0A);%0A

Fix changelog versioning to include date only after final release