UNPKG

2.6 kBJavaScriptView Raw
1const accessSync = require('fs-access').sync
2const chalk = require('chalk')
3const checkpoint = require('../checkpoint')
4const conventionalChangelog = require('conventional-changelog')
5const fs = require('fs')
6const presetLoader = require('../preset-loader')
7const runLifecycleScript = require('../run-lifecycle-script')
8const writeFile = require('../write-file')
9const START_OF_LAST_RELEASE_PATTERN = /(^#+ \[?[0-9]+\.[0-9]+\.[0-9]+|<a name=)/m
10
11function 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
22Changelog.START_OF_LAST_RELEASE_PATTERN = START_OF_LAST_RELEASE_PATTERN
23
24module.exports = Changelog
25
26function 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 // find the position of the last release and remove header:
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
61function 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}