1 | const accessSync = require('fs-access').sync
|
2 | const chalk = require('chalk')
|
3 | const checkpoint = require('../checkpoint')
|
4 | const conventionalChangelog = require('conventional-changelog')
|
5 | const fs = require('fs')
|
6 | const presetLoader = require('../preset-loader')
|
7 | const runLifecycleScript = require('../run-lifecycle-script')
|
8 | const writeFile = require('../write-file')
|
9 | const START_OF_LAST_RELEASE_PATTERN = /(^#+ \[?[0-9]+\.[0-9]+\.[0-9]+|<a name=)/m
|
10 |
|
11 | function Changelog (args, newVersion) {
|
12 | if (args.skip.changelog) return Promise.resolve()
|
13 | return runLifecycleScript(args, 'prechangelog')
|
14 | .then(() => {
|
15 | return outputChangelog(args, newVersion)
|
16 | })
|
17 | .then(() => {
|
18 | return runLifecycleScript(args, 'postchangelog')
|
19 | })
|
20 | }
|
21 |
|
22 | Changelog.START_OF_LAST_RELEASE_PATTERN = START_OF_LAST_RELEASE_PATTERN
|
23 |
|
24 | module.exports = Changelog
|
25 |
|
26 | function outputChangelog (args, newVersion) {
|
27 | return new Promise((resolve, reject) => {
|
28 | createIfMissing(args)
|
29 | const header = args.changelogHeader || '# Changelog\n\nAll notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.\n'
|
30 |
|
31 | let oldContent = args.dryRun ? '' : fs.readFileSync(args.infile, 'utf-8')
|
32 | let oldContentStart = oldContent.search(START_OF_LAST_RELEASE_PATTERN)
|
33 |
|
34 | if (oldContentStart !== -1) {
|
35 | oldContent = oldContent.substring(oldContentStart)
|
36 | }
|
37 | let content = ''
|
38 | const context = { version: newVersion }
|
39 | let changelogStream = conventionalChangelog({
|
40 | debug: args.verbose && console.info.bind(console, 'conventional-changelog'),
|
41 | preset: presetLoader(args),
|
42 | tagPrefix: args.tagPrefix
|
43 | }, context, { merges: null, path: args.path })
|
44 | .on('error', function (err) {
|
45 | return reject(err)
|
46 | })
|
47 |
|
48 | changelogStream.on('data', function (buffer) {
|
49 | content += buffer.toString()
|
50 | })
|
51 |
|
52 | changelogStream.on('end', function () {
|
53 | checkpoint(args, 'outputting changes to %s', [args.infile])
|
54 | if (args.dryRun) console.info(`\n---\n${chalk.gray(content.trim())}\n---\n`)
|
55 | else writeFile(args, args.infile, header + '\n' + (content + oldContent).replace(/\n+$/, '\n'))
|
56 | return resolve()
|
57 | })
|
58 | })
|
59 | }
|
60 |
|
61 | function createIfMissing (args) {
|
62 | try {
|
63 | accessSync(args.infile, fs.F_OK)
|
64 | } catch (err) {
|
65 | if (err.code === 'ENOENT') {
|
66 | checkpoint(args, 'created %s', [args.infile])
|
67 | args.outputUnreleased = true
|
68 | writeFile(args, args.infile, '\n')
|
69 | }
|
70 | }
|
71 | }
|