Skip to content

Commit d779be0

Browse files
authoredJul 6, 2021
chore: new private 'cdk-release' tool for performing releases (aws#15331)
Introduce a new repo-private tool called `cdk-release` that replaces `standard-version` in our 'bump' process. It's responsible for updating the version file with the new version, generating the Changelog based on on the commit history, and performing the commit that includes the two above files. It allows us to correctly handle edge cases that we had to work around previously with `standard-version`: * For patch releases, `standard-version` always generated the main header as H3, while we want H2. We always had to correct that manually, and we sometimes forgot. This tool does the correct thing for patch releases too. * We had to hack around when we wanted to change the heading 'BREAKING CHANGES' to 'BREAKING CHANGES TO EXPERIMENTAL FEATURES'. This tool now does it natively, no hacks needed. * In V2, `standard-version` couldn't figure out the tag to compare to, because we have tags for 2 major versions present in the repo. This tool handles this without the hacks of locally removing and then re-fetching the tags. * Also in V2, we want to strip the changes to experimental packages (as those are not included in `aws-cdk-lib`). With `standard-version`, we had to grep in the resulting Changelog, which was very fragile (for example, in `2.0.0-rc.7`, our Changelog includes breaking changes to `appmesh`, which is an experimental module). This tool handles this case natively, by filtering out commits, without the need for fragile Changelog grepping. To make sure we don't break our release process, allow passing the environment variable `LEGACY_BUMP` as truthy to fall back on `standard-version`. Once we make at least one successful release, in both major versions, using this new tool, I'll remove the old `standard-version` based code in a separate PR. In a subsequent PR, the tool will be enhanced with the capability to generate separate version bumps and Changelogs for experimental packages in V2. ---- *By submitting this pull request, I confirm that my contribution is made under the terms of the Apache-2.0 license*
1 parent 647acfa commit d779be0

25 files changed

+1239
-18
lines changed
 

‎bump.sh

+5-1
Original file line numberDiff line numberDiff line change
@@ -15,5 +15,9 @@
1515
set -euo pipefail
1616
scriptdir=$(cd $(dirname $0) && pwd)
1717
cd ${scriptdir}
18-
yarn --frozen-lockfile
18+
yarn install --frozen-lockfile
19+
if [[ "${LEGACY_BUMP:-}" == "" ]]; then
20+
# if we're using 'cdk-release' for the bump, build that package, including all of its dependencies
21+
npx lerna run build --include-dependencies --scope cdk-release
22+
fi
1923
${scriptdir}/scripts/bump.js ${1:-minor}

‎scripts/bump.js

+34-17
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,21 @@
11
#!/usr/bin/env node
2+
23
const fs = require('fs');
34
const path = require('path');
45
const semver = require('semver');
56
const ver = require('./resolve-version');
67
const { exec } = require('child_process');
7-
const repoRoot = path.join(__dirname, '..');
8-
9-
const releaseAs = process.argv[2] || 'minor';
10-
const forTesting = process.env.BUMP_CANDIDATE || false;
118

129
async function main() {
10+
const releaseAs = process.argv[2] || 'minor';
1311
if (releaseAs !== 'minor' && releaseAs !== 'patch') {
1412
throw new Error(`invalid bump type "${releaseAs}". only "minor" (the default) and "patch" are allowed. major version bumps require *slightly* more intention`);
1513
}
1614

1715
console.error(`Starting ${releaseAs} version bump`);
1816
console.error('Current version information:', JSON.stringify(ver, undefined, 2));
1917

18+
const repoRoot = path.join(__dirname, '..');
2019
const changelogPath = path.join(repoRoot, ver.changelogFile);
2120
const opts = {
2221
releaseAs: releaseAs,
@@ -30,31 +29,49 @@ async function main() {
3029
}
3130
};
3231

32+
const majorVersion = semver.major(ver.version);
33+
if (majorVersion > 1) {
34+
opts.stripExperimentalChanges = true;
35+
}
36+
37+
const forTesting = process.env.BUMP_CANDIDATE || false;
3338
if (forTesting) {
3439
opts.skip.commit = true;
3540
opts.skip.changelog = true;
3641

3742
// if we are on a "stable" branch, add a pre-release tag ("rc") to the
3843
// version number as a safety in case this version will accidentally be
3944
// published.
40-
opts.prerelease = ver.prerelease || 'rc'
45+
opts.prerelease = ver.prerelease || 'rc';
4146
console.error(`BUMP_CANDIDATE is set, so bumping version for testing (with the "${opts.prerelease}" prerelease tag)`);
4247
}
4348

44-
// `standard-release` will -- among other things -- create the changelog.
45-
// However, on the v2 branch, `conventional-changelog` (which `standard-release` uses) gets confused
46-
// and creates really muddled changelogs with both v1 and v2 releases intermingled, and lots of missing data.
47-
// A super HACK here is to locally remove all version tags that don't match this major version prior
48-
// to doing the bump, and then later fetching to restore those tags.
49-
const majorVersion = semver.major(ver.version);
50-
await exec(`git tag -d $(git tag -l | grep -v '^v${majorVersion}.')`);
49+
const useLegacyBump = process.env.LEGACY_BUMP || false;
50+
if (useLegacyBump) {
51+
console.error("ℹ️ Using the third-party 'standard-version' package to perform the bump");
5152

52-
// Delay loading standard-version until the git tags have been pruned.
53-
const standardVersion = require('standard-version');
54-
await standardVersion(opts);
53+
// `standard-release` will -- among other things -- create the changelog.
54+
// However, on the v2 branch, `conventional-changelog` (which `standard-release` uses) gets confused
55+
// and creates really muddled changelogs with both v1 and v2 releases intermingled, and lots of missing data.
56+
// A super HACK here is to locally remove all version tags that don't match this major version prior
57+
// to doing the bump, and then later fetching to restore those tags.
58+
await exec(`git tag -d $(git tag -l | grep -v '^v${majorVersion}.')`);
5559

56-
// fetch back the tags, and only the tags, removed locally above
57-
await exec('git fetch origin "refs/tags/*:refs/tags/*"');
60+
// Delay loading standard-version until the git tags have been pruned.
61+
const standardVersion = require('standard-version');
62+
await standardVersion(opts);
63+
64+
// fetch back the tags, and only the tags, removed locally above
65+
await exec('git fetch origin "refs/tags/*:refs/tags/*"');
66+
} else {
67+
// this is incredible, but passing this option to standard-version actually makes it crash!
68+
// good thing we're getting rid of it...
69+
opts.verbose = !!process.env.VERBOSE;
70+
console.error("🎉 Calling our 'cdk-release' package to make the bump");
71+
console.error("ℹ️ Set the LEGACY_BUMP env variable to use the old 'standard-version' bump instead");
72+
const cdkRelease = require('cdk-release');
73+
cdkRelease(opts);
74+
}
5875
}
5976

6077
main().catch(err => {

‎tools/cdk-release/.eslintrc.js

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
const baseConfig = require('cdk-build-tools/config/eslintrc');
2+
baseConfig.parserOptions.project = __dirname + '/tsconfig.json';
3+
module.exports = baseConfig;

‎tools/cdk-release/.gitignore

+15
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
*.js
2+
node_modules
3+
*.js.map
4+
*.d.ts
5+
6+
.LAST_BUILD
7+
.nyc_output
8+
coverage
9+
nyc.config.js
10+
*.snk
11+
!.eslintrc.js
12+
13+
junit.xml
14+
15+
!jest.config.js

‎tools/cdk-release/.npmignore

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
# Don't include original .ts files when doing `npm pack`
2+
*.ts
3+
!*.d.ts
4+
coverage
5+
.nyc_output
6+
*.tgz
7+
8+
.LAST_BUILD
9+
*.snk
10+
.eslintrc.js
11+
12+
# exclude cdk artifacts
13+
**/cdk.out
14+
junit.xml
15+
16+
jest.config.js

‎tools/cdk-release/LICENSE

+201
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,201 @@
1+
Apache License
2+
Version 2.0, January 2004
3+
http://www.apache.org/licenses/
4+
5+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6+
7+
1. Definitions.
8+
9+
"License" shall mean the terms and conditions for use, reproduction,
10+
and distribution as defined by Sections 1 through 9 of this document.
11+
12+
"Licensor" shall mean the copyright owner or entity authorized by
13+
the copyright owner that is granting the License.
14+
15+
"Legal Entity" shall mean the union of the acting entity and all
16+
other entities that control, are controlled by, or are under common
17+
control with that entity. For the purposes of this definition,
18+
"control" means (i) the power, direct or indirect, to cause the
19+
direction or management of such entity, whether by contract or
20+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
21+
outstanding shares, or (iii) beneficial ownership of such entity.
22+
23+
"You" (or "Your") shall mean an individual or Legal Entity
24+
exercising permissions granted by this License.
25+
26+
"Source" form shall mean the preferred form for making modifications,
27+
including but not limited to software source code, documentation
28+
source, and configuration files.
29+
30+
"Object" form shall mean any form resulting from mechanical
31+
transformation or translation of a Source form, including but
32+
not limited to compiled object code, generated documentation,
33+
and conversions to other media types.
34+
35+
"Work" shall mean the work of authorship, whether in Source or
36+
Object form, made available under the License, as indicated by a
37+
copyright notice that is included in or attached to the work
38+
(an example is provided in the Appendix below).
39+
40+
"Derivative Works" shall mean any work, whether in Source or Object
41+
form, that is based on (or derived from) the Work and for which the
42+
editorial revisions, annotations, elaborations, or other modifications
43+
represent, as a whole, an original work of authorship. For the purposes
44+
of this License, Derivative Works shall not include works that remain
45+
separable from, or merely link (or bind by name) to the interfaces of,
46+
the Work and Derivative Works thereof.
47+
48+
"Contribution" shall mean any work of authorship, including
49+
the original version of the Work and any modifications or additions
50+
to that Work or Derivative Works thereof, that is intentionally
51+
submitted to Licensor for inclusion in the Work by the copyright owner
52+
or by an individual or Legal Entity authorized to submit on behalf of
53+
the copyright owner. For the purposes of this definition, "submitted"
54+
means any form of electronic, verbal, or written communication sent
55+
to the Licensor or its representatives, including but not limited to
56+
communication on electronic mailing lists, source code control systems,
57+
and issue tracking systems that are managed by, or on behalf of, the
58+
Licensor for the purpose of discussing and improving the Work, but
59+
excluding communication that is conspicuously marked or otherwise
60+
designated in writing by the copyright owner as "Not a Contribution."
61+
62+
"Contributor" shall mean Licensor and any individual or Legal Entity
63+
on behalf of whom a Contribution has been received by Licensor and
64+
subsequently incorporated within the Work.
65+
66+
2. Grant of Copyright License. Subject to the terms and conditions of
67+
this License, each Contributor hereby grants to You a perpetual,
68+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69+
copyright license to reproduce, prepare Derivative Works of,
70+
publicly display, publicly perform, sublicense, and distribute the
71+
Work and such Derivative Works in Source or Object form.
72+
73+
3. Grant of Patent License. Subject to the terms and conditions of
74+
this License, each Contributor hereby grants to You a perpetual,
75+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76+
(except as stated in this section) patent license to make, have made,
77+
use, offer to sell, sell, import, and otherwise transfer the Work,
78+
where such license applies only to those patent claims licensable
79+
by such Contributor that are necessarily infringed by their
80+
Contribution(s) alone or by combination of their Contribution(s)
81+
with the Work to which such Contribution(s) was submitted. If You
82+
institute patent litigation against any entity (including a
83+
cross-claim or counterclaim in a lawsuit) alleging that the Work
84+
or a Contribution incorporated within the Work constitutes direct
85+
or contributory patent infringement, then any patent licenses
86+
granted to You under this License for that Work shall terminate
87+
as of the date such litigation is filed.
88+
89+
4. Redistribution. You may reproduce and distribute copies of the
90+
Work or Derivative Works thereof in any medium, with or without
91+
modifications, and in Source or Object form, provided that You
92+
meet the following conditions:
93+
94+
(a) You must give any other recipients of the Work or
95+
Derivative Works a copy of this License; and
96+
97+
(b) You must cause any modified files to carry prominent notices
98+
stating that You changed the files; and
99+
100+
(c) You must retain, in the Source form of any Derivative Works
101+
that You distribute, all copyright, patent, trademark, and
102+
attribution notices from the Source form of the Work,
103+
excluding those notices that do not pertain to any part of
104+
the Derivative Works; and
105+
106+
(d) If the Work includes a "NOTICE" text file as part of its
107+
distribution, then any Derivative Works that You distribute must
108+
include a readable copy of the attribution notices contained
109+
within such NOTICE file, excluding those notices that do not
110+
pertain to any part of the Derivative Works, in at least one
111+
of the following places: within a NOTICE text file distributed
112+
as part of the Derivative Works; within the Source form or
113+
documentation, if provided along with the Derivative Works; or,
114+
within a display generated by the Derivative Works, if and
115+
wherever such third-party notices normally appear. The contents
116+
of the NOTICE file are for informational purposes only and
117+
do not modify the License. You may add Your own attribution
118+
notices within Derivative Works that You distribute, alongside
119+
or as an addendum to the NOTICE text from the Work, provided
120+
that such additional attribution notices cannot be construed
121+
as modifying the License.
122+
123+
You may add Your own copyright statement to Your modifications and
124+
may provide additional or different license terms and conditions
125+
for use, reproduction, or distribution of Your modifications, or
126+
for any such Derivative Works as a whole, provided Your use,
127+
reproduction, and distribution of the Work otherwise complies with
128+
the conditions stated in this License.
129+
130+
5. Submission of Contributions. Unless You explicitly state otherwise,
131+
any Contribution intentionally submitted for inclusion in the Work
132+
by You to the Licensor shall be under the terms and conditions of
133+
this License, without any additional terms or conditions.
134+
Notwithstanding the above, nothing herein shall supersede or modify
135+
the terms of any separate license agreement you may have executed
136+
with Licensor regarding such Contributions.
137+
138+
6. Trademarks. This License does not grant permission to use the trade
139+
names, trademarks, service marks, or product names of the Licensor,
140+
except as required for reasonable and customary use in describing the
141+
origin of the Work and reproducing the content of the NOTICE file.
142+
143+
7. Disclaimer of Warranty. Unless required by applicable law or
144+
agreed to in writing, Licensor provides the Work (and each
145+
Contributor provides its Contributions) on an "AS IS" BASIS,
146+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147+
implied, including, without limitation, any warranties or conditions
148+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149+
PARTICULAR PURPOSE. You are solely responsible for determining the
150+
appropriateness of using or redistributing the Work and assume any
151+
risks associated with Your exercise of permissions under this License.
152+
153+
8. Limitation of Liability. In no event and under no legal theory,
154+
whether in tort (including negligence), contract, or otherwise,
155+
unless required by applicable law (such as deliberate and grossly
156+
negligent acts) or agreed to in writing, shall any Contributor be
157+
liable to You for damages, including any direct, indirect, special,
158+
incidental, or consequential damages of any character arising as a
159+
result of this License or out of the use or inability to use the
160+
Work (including but not limited to damages for loss of goodwill,
161+
work stoppage, computer failure or malfunction, or any and all
162+
other commercial damages or losses), even if such Contributor
163+
has been advised of the possibility of such damages.
164+
165+
9. Accepting Warranty or Additional Liability. While redistributing
166+
the Work or Derivative Works thereof, You may choose to offer,
167+
and charge a fee for, acceptance of support, warranty, indemnity,
168+
or other liability obligations and/or rights consistent with this
169+
License. However, in accepting such obligations, You may act only
170+
on Your own behalf and on Your sole responsibility, not on behalf
171+
of any other Contributor, and only if You agree to indemnify,
172+
defend, and hold each Contributor harmless for any liability
173+
incurred by, or claims asserted against, such Contributor by reason
174+
of your accepting any such warranty or additional liability.
175+
176+
END OF TERMS AND CONDITIONS
177+
178+
APPENDIX: How to apply the Apache License to your work.
179+
180+
To apply the Apache License to your work, attach the following
181+
boilerplate notice, with the fields enclosed by brackets "[]"
182+
replaced with your own identifying information. (Don't include
183+
the brackets!) The text should be enclosed in the appropriate
184+
comment syntax for the file format. We also recommend that a
185+
file or class name and description of purpose be included on the
186+
same "printed page" as the copyright notice for easier
187+
identification within third-party archives.
188+
189+
Copyright 2018-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.
190+
191+
Licensed under the Apache License, Version 2.0 (the "License");
192+
you may not use this file except in compliance with the License.
193+
You may obtain a copy of the License at
194+
195+
http://www.apache.org/licenses/LICENSE-2.0
196+
197+
Unless required by applicable law or agreed to in writing, software
198+
distributed under the License is distributed on an "AS IS" BASIS,
199+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200+
See the License for the specific language governing permissions and
201+
limitations under the License.

‎tools/cdk-release/NOTICE

+2
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
AWS Cloud Development Kit (AWS CDK)
2+
Copyright 2018-2021 Amazon.com, Inc. or its affiliates. All Rights Reserved.

‎tools/cdk-release/README.md

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
# cdk-release
2+
3+
This is a repo-private tool that we use for performing a release:
4+
bumping the version of the package(s),
5+
generating the Changelog file(s),
6+
creating a commit, etc.
7+
8+
We used to rely on [standard-version](https://www.npmjs.com/package/standard-version)
9+
for this purpose, but our case is so (haha) non-standard,
10+
with `aws-cdk-lib` excluding experimental modules,
11+
and the need for separate Changelog files for V2 experimental modules,
12+
that we decided we need a tool that we have full control over
13+
(plus, `standard-version` has some problems too,
14+
like messing up the headings,
15+
and having problems with both V1 and V2 tags in the same repo).
16+
17+
This library is called from the
18+
[`bump.js` file](../../scripts/bump.js),
19+
which is called from the [`bump.sh` script](../../bump.sh),
20+
which is called by a CodeBuild job that creates the 'bump'
21+
PR every time we perform a CDK release.

‎tools/cdk-release/jest.config.js

+10
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
const baseConfig = require('../../tools/cdk-build-tools/config/jest.config');
2+
module.exports = {
3+
...baseConfig,
4+
coverageThreshold: {
5+
global: {
6+
...baseConfig.coverageThreshold.global,
7+
branches: 60,
8+
},
9+
},
10+
};
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,138 @@
1+
import * as fs from 'fs-extra';
2+
import { ReleaseOptions } from './types';
3+
// eslint-disable-next-line @typescript-eslint/no-require-imports
4+
const lerna_project = require('@lerna/project');
5+
// eslint-disable-next-line @typescript-eslint/no-require-imports
6+
const conventionalCommitsParser = require('conventional-commits-parser');
7+
// eslint-disable-next-line @typescript-eslint/no-require-imports
8+
const gitRawCommits = require('git-raw-commits');
9+
10+
/**
11+
* The optional notes in the commit message.
12+
* Today, the only notes are 'BREAKING CHANGES'.
13+
*/
14+
export interface ConventionalCommitNote {
15+
/** Today, always 'BREAKING CHANGE'. */
16+
readonly title: string;
17+
18+
/** The body of the note. */
19+
readonly text: string;
20+
}
21+
22+
/** For now, only needed for unit tests. */
23+
export interface ConventionalCommitReference {
24+
}
25+
26+
export interface ConventionalCommit {
27+
/** The type of the commit ('feat', 'fix', etc.). */
28+
readonly type: string;
29+
30+
/** The optional scope of the change ('core', 'aws-s3', 's3', etc.). */
31+
readonly scope?: string;
32+
33+
/** The subject is the remaining part of the first line without 'type' and 'scope'. */
34+
readonly subject: string;
35+
36+
/**
37+
* The header is the entire first line of the commit
38+
* (<type>(<scope>): <subject>).
39+
*/
40+
readonly header: string;
41+
42+
/**
43+
* The optional notes in the commit message.
44+
* Today, the only notes are 'BREAKING CHANGES'.
45+
*/
46+
readonly notes: ConventionalCommitNote[];
47+
48+
/**
49+
* References inside the commit body
50+
* (for example, to issues or Pull Requests that this commit is linked to).
51+
*/
52+
readonly references: ConventionalCommitReference[];
53+
}
54+
55+
/**
56+
* Returns a list of all Conventional Commits in the Git repository since the tag `gitTag`.
57+
* The commits will be sorted in chronologically descending order
58+
* (that is, later/newer commits will be earlier in the array).
59+
*
60+
* @param gitTag the string representing the Git tag,
61+
* will be used to limit the returned commits to only those added after that tag
62+
*/
63+
export async function getConventionalCommitsFromGitHistory(gitTag: string): Promise<ConventionalCommit[]> {
64+
const ret = new Array<any>();
65+
return new Promise((resolve, reject) => {
66+
const conventionalCommitsStream = gitRawCommits({
67+
format: '%B%n-hash-%n%H',
68+
// our tags have the 'v' prefix
69+
from: gitTag,
70+
// path: options.path,
71+
}).pipe(conventionalCommitsParser());
72+
73+
conventionalCommitsStream.on('data', function (data: any) {
74+
// filter out all commits that don't conform to the Conventional Commits standard
75+
// (they will have an empty 'type' property)
76+
if (data.type) {
77+
ret.push(data);
78+
}
79+
});
80+
conventionalCommitsStream.on('end', function () {
81+
resolve(ret);
82+
});
83+
conventionalCommitsStream.on('error', function (err: any) {
84+
reject(err);
85+
});
86+
});
87+
}
88+
89+
/**
90+
* Filters commits based on the criteria in `args`
91+
* (right now, the only criteria is whether to remove commits that relate to experimental packages).
92+
*
93+
* @param args configuration
94+
* @param commits the array of Conventional Commits to filter
95+
* @returns an array of ConventionalCommit objects which is a subset of `commits`
96+
* (possibly exactly equal to `commits`)
97+
*/
98+
export function filterCommits(args: ReleaseOptions, commits: ConventionalCommit[]): ConventionalCommit[] {
99+
if (!args.stripExperimentalChanges) {
100+
return commits;
101+
}
102+
103+
// a get a list of packages from our monorepo
104+
const project = new lerna_project.Project();
105+
const packages = project.getPackagesSync();
106+
const experimentalPackageNames: string[] = packages
107+
.filter((pkg: any) => {
108+
const pkgJson = fs.readJsonSync(pkg.manifestLocation);
109+
return pkgJson.name.startsWith('@aws-cdk/')
110+
&& (pkgJson.maturity === 'experimental' || pkgJson.maturity === 'developer-preview');
111+
})
112+
.map((pkg: any) => pkg.name.substr('@aws-cdk/'.length));
113+
114+
const experimentalScopes = flatMap(experimentalPackageNames, (pkgName) => [
115+
pkgName,
116+
...(pkgName.startsWith('aws-')
117+
? [
118+
// if the package name starts with 'aws', like 'aws-s3',
119+
// also include in the scopes variants without the prefix,
120+
// and without the '-' in the prefix
121+
// (so, 's3' and 'awss3')
122+
pkgName.substr('aws-'.length),
123+
pkgName.replace(/^aws-/, 'aws'),
124+
]
125+
: []
126+
),
127+
]);
128+
129+
return commits.filter(commit => !commit.scope || !experimentalScopes.includes(commit.scope));
130+
}
131+
132+
function flatMap<T, U>(xs: T[], fn: (x: T) => U[]): U[] {
133+
const ret = new Array<U>();
134+
for (const x of xs) {
135+
ret.push(...fn(x));
136+
}
137+
return ret;
138+
}

‎tools/cdk-release/lib/defaults.ts

+32
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { ReleaseOptions } from './types';
2+
3+
const defaultPackageFiles = [
4+
'package.json',
5+
'bower.json',
6+
'manifest.json',
7+
];
8+
9+
export const defaultBumpFiles = defaultPackageFiles.concat([
10+
'package-lock.json',
11+
'npm-shrinkwrap.json',
12+
]);
13+
14+
export const defaults: Partial<ReleaseOptions> = {
15+
infile: 'CHANGELOG.md',
16+
// firstRelease: false,
17+
sign: false,
18+
// noVerify: false,
19+
// commitAll: false,
20+
silent: false,
21+
scripts: {},
22+
skip: {
23+
tag: true,
24+
},
25+
packageFiles: defaultPackageFiles,
26+
bumpFiles: defaultBumpFiles,
27+
dryRun: false,
28+
// gitTagFallback: true,
29+
releaseCommitMessageFormat: 'chore(release): {{currentTag}}',
30+
changeLogHeader: '# Changelog\n\nAll notable changes to this project will be documented in this file. ' +
31+
'See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.\n',
32+
};

‎tools/cdk-release/lib/index.ts

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import * as fs from 'fs';
2+
import * as path from 'path';
3+
import { filterCommits, getConventionalCommitsFromGitHistory } from './conventional-commits';
4+
import { defaults } from './defaults';
5+
import { bump } from './lifecycles/bump';
6+
import { changelog } from './lifecycles/changelog';
7+
import { commit } from './lifecycles/commit';
8+
import { debug, debugObject } from './private/print';
9+
import { ReleaseOptions } from './types';
10+
import { resolveUpdaterObjectFromArgument } from './updaters';
11+
12+
module.exports = async function main(opts: ReleaseOptions): Promise<void> {
13+
// handle the default options
14+
const args: ReleaseOptions = {
15+
...defaults,
16+
...opts,
17+
};
18+
debugObject(args, 'options are (including defaults)', args);
19+
20+
const packageInfo = determinePackageInfo(args);
21+
debugObject(args, 'packageInfo is', packageInfo);
22+
23+
const currentVersion = packageInfo.version;
24+
debug(args, 'Current version is: ' + currentVersion);
25+
26+
const commits = await getConventionalCommitsFromGitHistory(`v${currentVersion}`);
27+
const filteredCommits = filterCommits(args, commits);
28+
debugObject(args, 'Found and filtered commits', filteredCommits);
29+
30+
const bumpResult = await bump(args, currentVersion);
31+
const newVersion = bumpResult.newVersion;
32+
debug(args, 'New version is: ' + newVersion);
33+
34+
const changelogResult = await changelog(args, currentVersion, newVersion, filteredCommits);
35+
36+
await commit(args, newVersion, [...bumpResult.changedFiles, ...changelogResult.changedFiles]);
37+
};
38+
39+
interface PackageInfo {
40+
version: string;
41+
private: string | boolean | null | undefined;
42+
}
43+
44+
function determinePackageInfo(args: ReleaseOptions): PackageInfo {
45+
for (const packageFile of args.packageFiles ?? []) {
46+
const updater = resolveUpdaterObjectFromArgument(packageFile);
47+
const pkgPath = path.resolve(process.cwd(), updater.filename);
48+
const contents = fs.readFileSync(pkgPath, 'utf8');
49+
// we stop on the first (successful) option
50+
return {
51+
version: updater.updater.readVersion(contents),
52+
private: typeof updater.updater.isPrivate === 'function' ? updater.updater.isPrivate(contents) : false,
53+
};
54+
}
55+
56+
throw new Error('Could not establish the version to bump!');
57+
}
+122
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,122 @@
1+
import * as fs from 'fs';
2+
import * as path from 'path';
3+
import * as semver from 'semver';
4+
import { writeFile } from '../private/files';
5+
import { notify } from '../private/print';
6+
import { ReleaseOptions, ReleaseType } from '../types';
7+
import { resolveUpdaterObjectFromArgument } from '../updaters/index';
8+
9+
export interface BumpResult {
10+
readonly newVersion: string;
11+
readonly changedFiles: string[];
12+
}
13+
14+
export async function bump(args: ReleaseOptions, currentVersion: string): Promise<BumpResult> {
15+
if (args.skip?.bump) {
16+
return {
17+
newVersion: currentVersion,
18+
changedFiles: [],
19+
};
20+
}
21+
22+
const releaseType = getReleaseType(args.prerelease, args.releaseAs, currentVersion);
23+
const newVersion = semver.inc(currentVersion, releaseType, args.prerelease);
24+
if (!newVersion) {
25+
throw new Error('Could not increment version: ' + currentVersion);
26+
}
27+
const changedFiles = updateBumpFiles(args, newVersion);
28+
return { newVersion, changedFiles };
29+
}
30+
31+
function getReleaseType(prerelease: string | undefined, expectedReleaseType: ReleaseType, currentVersion: string): semver.ReleaseType {
32+
if (typeof prerelease === 'string') {
33+
if (isInPrerelease(currentVersion)) {
34+
if (shouldContinuePrerelease(currentVersion, expectedReleaseType) ||
35+
getTypePriority(getCurrentActiveType(currentVersion)) > getTypePriority(expectedReleaseType)
36+
) {
37+
return 'prerelease';
38+
}
39+
}
40+
41+
return 'pre' + expectedReleaseType as semver.ReleaseType;
42+
} else {
43+
return expectedReleaseType;
44+
}
45+
}
46+
47+
function isInPrerelease(version: string): boolean {
48+
return Array.isArray(semver.prerelease(version));
49+
}
50+
51+
/**
52+
* if a version is currently in pre-release state,
53+
* and if it current in-pre-release type is same as expect type,
54+
* it should continue the pre-release with the same type
55+
*
56+
* @param version
57+
* @param expectType
58+
* @return {boolean}
59+
*/
60+
function shouldContinuePrerelease(version: string, expectType: ReleaseType): boolean {
61+
return getCurrentActiveType(version) === expectType;
62+
}
63+
64+
const TypeList = ['major', 'minor', 'patch'].reverse();
65+
/**
66+
* extract the in-pre-release type in target version
67+
*
68+
* @param version
69+
* @return {string}
70+
*/
71+
function getCurrentActiveType(version: string): string {
72+
for (const item of TypeList) {
73+
if ((semver as any)[item](version)) {
74+
return item;
75+
}
76+
}
77+
throw new Error('unreachable');
78+
}
79+
80+
/**
81+
* calculate the priority of release type,
82+
* major - 2, minor - 1, patch - 0
83+
*
84+
* @param type
85+
* @return {number}
86+
*/
87+
function getTypePriority(type: string): number {
88+
return TypeList.indexOf(type);
89+
}
90+
91+
/**
92+
* attempt to update the version number in provided `bumpFiles`
93+
* @param args config object
94+
* @param newVersion version number to update to.
95+
* @return the collection of file paths that were actually changed
96+
*/
97+
function updateBumpFiles(args: ReleaseOptions, newVersion: string): string[] {
98+
const ret = new Array<string>();
99+
100+
for (const bumpFile of (args.bumpFiles ?? [])) {
101+
const updater = resolveUpdaterObjectFromArgument(bumpFile);
102+
if (!updater) {
103+
continue;
104+
}
105+
const configPath = path.resolve(process.cwd(), updater.filename);
106+
const stat = fs.lstatSync(configPath);
107+
if (!stat.isFile()) {
108+
continue;
109+
}
110+
const contents = fs.readFileSync(configPath, 'utf8');
111+
notify(args,
112+
'bumping version in ' + updater.filename + ' from %s to %s',
113+
[updater.updater.readVersion(contents), newVersion],
114+
);
115+
writeFile(args, configPath,
116+
updater.updater.writeVersion(contents, newVersion),
117+
);
118+
ret.push(updater.filename);
119+
}
120+
121+
return ret;
122+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
import * as stream from 'stream';
2+
import * as fs from 'fs-extra';
3+
import { ConventionalCommit } from '../conventional-commits';
4+
import { writeFile } from '../private/files';
5+
import { notify, debug, debugObject } from '../private/print';
6+
import { ReleaseOptions } from '../types';
7+
// eslint-disable-next-line @typescript-eslint/no-require-imports
8+
const conventionalChangelogPresetLoader = require('conventional-changelog-preset-loader');
9+
// eslint-disable-next-line @typescript-eslint/no-require-imports
10+
const conventionalChangelogWriter = require('conventional-changelog-writer');
11+
12+
const START_OF_LAST_RELEASE_PATTERN = /(^#+ \[?[0-9]+\.[0-9]+\.[0-9]+|<a name=)/m;
13+
14+
export interface ChangelogResult {
15+
readonly contents: string;
16+
readonly changedFiles: string[];
17+
}
18+
19+
export async function changelog(
20+
args: ReleaseOptions, currentVersion: string, newVersion: string, commits: ConventionalCommit[],
21+
): Promise<ChangelogResult> {
22+
if (args.skip?.changelog) {
23+
return {
24+
contents: '',
25+
changedFiles: [],
26+
};
27+
}
28+
createChangelogIfMissing(args);
29+
30+
// find the position of the last release and remove header
31+
let oldContent = args.dryRun ? '' : fs.readFileSync(args.infile!, 'utf-8');
32+
const oldContentStart = oldContent.search(START_OF_LAST_RELEASE_PATTERN);
33+
if (oldContentStart !== -1) {
34+
oldContent = oldContent.substring(oldContentStart);
35+
}
36+
37+
// load the default configuration that we use for the Changelog generation
38+
const presetConfig = await conventionalChangelogPresetLoader({
39+
name: 'conventional-changelog-conventionalcommits',
40+
});
41+
debugObject(args, 'conventionalChangelogPresetLoader returned', presetConfig);
42+
43+
return new Promise((resolve, reject) => {
44+
// convert an array of commits into a Stream,
45+
// which conventionalChangelogWriter expects
46+
const commitsStream = new stream.Stream.Readable({
47+
objectMode: true,
48+
});
49+
commits.forEach(commit => commitsStream.push(commit));
50+
// mark the end of the stream
51+
commitsStream.push(null);
52+
53+
const host = 'https://github.com', owner = 'aws', repository = 'aws-cdk';
54+
const context = {
55+
issue: 'issues',
56+
commit: 'commit',
57+
version: newVersion,
58+
host,
59+
owner,
60+
repository,
61+
repoUrl: `${host}/${owner}/${repository}`,
62+
linkCompare: true,
63+
previousTag: `v${currentVersion}`,
64+
currentTag: `v${newVersion}`,
65+
// when isPatch is 'true', the default template used for the header renders an H3 instead of an H2
66+
// (see: https://github.com/conventional-changelog/conventional-changelog/blob/f1f50f56626099e92efe31d2f8c5477abd90f1b7/packages/conventional-changelog-conventionalcommits/templates/header.hbs#L1-L5)
67+
isPatch: false,
68+
};
69+
// invoke the conventionalChangelogWriter package that will perform the actual Changelog rendering
70+
const changelogStream = commitsStream
71+
.pipe(conventionalChangelogWriter(context,
72+
{
73+
// CDK uses the settings from 'conventional-changelog-conventionalcommits'
74+
// (by way of 'standard-version'),
75+
// which are different than the 'conventionalChangelogWriter' defaults
76+
...presetConfig.writerOpts,
77+
finalizeContext: (ctx: { noteGroups?: { title: string }[], date?: string }) => {
78+
// the heading of the "BREAKING CHANGES" section is governed by this Handlebars template:
79+
// https://github.com/conventional-changelog/conventional-changelog/blob/f1f50f56626099e92efe31d2f8c5477abd90f1b7/packages/conventional-changelog-conventionalcommits/templates/template.hbs#L3-L12
80+
// to change the heading from 'BREAKING CHANGES' to 'BREAKING CHANGES TO EXPERIMENTAL FEATURES',
81+
// we have to change the title of the 'BREAKING CHANGES' noteGroup
82+
ctx.noteGroups?.forEach(noteGroup => {
83+
if (noteGroup.title === 'BREAKING CHANGES') {
84+
noteGroup.title = 'BREAKING CHANGES TO EXPERIMENTAL FEATURES';
85+
}
86+
});
87+
// in unit tests, we don't want to have the date in the Changelog
88+
if (args.includeDateInChangelog === false) {
89+
ctx.date = undefined;
90+
}
91+
return ctx;
92+
},
93+
}));
94+
95+
changelogStream.on('error', function (err: any) {
96+
reject(err);
97+
});
98+
let content = '';
99+
changelogStream.on('data', function (buffer: any) {
100+
content += buffer.toString();
101+
});
102+
changelogStream.on('end', function () {
103+
notify(args, 'outputting changes to %s', [args.infile]);
104+
if (args.dryRun) {
105+
debug(args, `\n---\n${content.trim()}\n---\n`);
106+
} else {
107+
writeFile(args, args.infile!, args.changeLogHeader + '\n' + (content + oldContent).replace(/\n+$/, '\n'));
108+
}
109+
return resolve({
110+
contents: content,
111+
changedFiles: [args.infile!],
112+
});
113+
});
114+
});
115+
}
116+
117+
function createChangelogIfMissing(args: ReleaseOptions) {
118+
if (!fs.existsSync(args.infile!)) {
119+
notify(args, 'created %s', [args.infile]);
120+
// args.outputUnreleased = true
121+
writeFile(args, args.infile!, '\n');
122+
}
123+
}
+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import * as path from 'path';
2+
import { notify } from '../private/print';
3+
import { runExecFile } from '../private/run-exec-file';
4+
import { ReleaseOptions } from '../types';
5+
6+
export async function commit(args: ReleaseOptions, newVersion: string, modifiedFiles: string[]): Promise<void> {
7+
if (args.skip?.commit) {
8+
return;
9+
}
10+
11+
let msg = 'committing %s';
12+
const paths = new Array<string>();
13+
const toAdd = new Array<string>();
14+
// commit any of the config files that we've updated
15+
// the version # for.
16+
for (const modifiedFile of modifiedFiles) {
17+
paths.unshift(modifiedFile);
18+
toAdd.push(path.relative(process.cwd(), modifiedFile));
19+
20+
// account for multiple files in the output message
21+
if (paths.length > 1) {
22+
msg += ' and %s';
23+
}
24+
}
25+
// nothing to do, exit without commit anything
26+
if (toAdd.length === 0) {
27+
return;
28+
}
29+
30+
notify(args, msg, paths);
31+
32+
await runExecFile(args, 'git', ['add'].concat(toAdd));
33+
const sign = args.sign ? ['-S'] : [];
34+
await runExecFile(args, 'git', ['commit'].concat(
35+
sign,
36+
[
37+
'-m',
38+
`${formatCommitMessage(args.releaseCommitMessageFormat!, newVersion)}`,
39+
]),
40+
);
41+
}
42+
43+
function formatCommitMessage(rawMsg: string, newVersion: string): string {
44+
return rawMsg.replace(/{{currentTag}}/g, newVersion);
45+
}
+9
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
import * as fs from 'fs';
2+
import { ReleaseOptions } from '../types';
3+
4+
export function writeFile(args: ReleaseOptions, filePath: string, content: string): void {
5+
if (args.dryRun) {
6+
return;
7+
}
8+
fs.writeFileSync(filePath, content, 'utf8');
9+
}
+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import * as util from 'util';
2+
import { ReleaseOptions } from '../types';
3+
4+
export function debug(opts: ReleaseOptions, message: string): void {
5+
if (opts.verbose) {
6+
// eslint-disable-next-line no-console
7+
console.log(`[cdk-release] ${message}`);
8+
}
9+
}
10+
11+
export function debugObject(opts: ReleaseOptions, message: string, object: any): void {
12+
if (opts.verbose) {
13+
// eslint-disable-next-line no-console
14+
console.log(`[cdk-release] ${message}:\n`, object);
15+
}
16+
}
17+
18+
export function notify(opts: ReleaseOptions, msg: string, args: any[]) {
19+
if (!opts.silent) {
20+
// eslint-disable-next-line no-console
21+
console.info('✔ ' + util.format(msg, ...args));
22+
}
23+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
import { execFile as childProcessExecFile } from 'child_process';
2+
import { promisify } from 'util';
3+
import { ReleaseOptions } from '../types';
4+
import { notify } from './print';
5+
6+
const execFile = promisify(childProcessExecFile);
7+
8+
export async function runExecFile(args: ReleaseOptions, cmd: string, cmdArgs: string[]): Promise<string | undefined> {
9+
if (args.dryRun) {
10+
notify(args, "would execute command: '%s %s'", [cmd, cmdArgs
11+
// quote arguments with spaces, for a more realistic printing experience
12+
.map(cmdArg => cmdArg.match(/\s/) ? `"${cmdArg}"` : cmdArg)
13+
.join(' ')],
14+
);
15+
return;
16+
}
17+
const streams = await execFile(cmd, cmdArgs);
18+
return streams.stdout;
19+
}

‎tools/cdk-release/lib/types.ts

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
export interface Lifecycles {
2+
bump?: string;
3+
changelog?: string;
4+
postchangelog?: string;
5+
commit?: string;
6+
7+
// we don't actually do tagging at all, but still support passing it as an option,
8+
// for conformance with standard-version (CDK doesn't use its tagging capabilities anyway)
9+
tag?: string;
10+
}
11+
12+
type LifecyclesSkip = {
13+
[key in keyof Lifecycles]: boolean;
14+
}
15+
16+
/* ****** Updaters ******** */
17+
18+
export interface UpdaterModule {
19+
isPrivate?: (contents: string) => string | boolean | null | undefined;
20+
readVersion(contents: string): string;
21+
writeVersion(contents: string, version: string): string;
22+
}
23+
24+
export interface ArgUpdater {
25+
filename: string;
26+
type?: string;
27+
updater?: UpdaterModule | string;
28+
}
29+
30+
export type ArgFile = string | ArgUpdater;
31+
32+
export interface Updater {
33+
filename: string;
34+
updater: UpdaterModule;
35+
}
36+
37+
export type ReleaseType = 'major' | 'minor' | 'patch';
38+
39+
export interface ConventionalCommitType {
40+
type: string;
41+
section?: string;
42+
hidden?: boolean;
43+
}
44+
45+
/* ****** main options ******** */
46+
47+
export interface ReleaseOptions {
48+
releaseAs: ReleaseType;
49+
skip?: LifecyclesSkip;
50+
packageFiles?: ArgFile[];
51+
bumpFiles?: ArgFile[];
52+
infile?: string;
53+
prerelease?: string;
54+
scripts?: Lifecycles;
55+
dryRun?: boolean;
56+
verbose?: boolean;
57+
silent?: boolean;
58+
sign?: boolean;
59+
stripExperimentalChanges?: boolean;
60+
61+
changeLogHeader?: string;
62+
includeDateInChangelog?: boolean;
63+
releaseCommitMessageFormat?: string;
64+
}
+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import * as path from 'path';
2+
import { defaultBumpFiles } from '../defaults';
3+
import { UpdaterModule, ArgFile, Updater } from '../types';
4+
import jsonUpdaterModule from './types/json';
5+
import plainTextUpdaterModule from './types/plain-text';
6+
7+
export function resolveUpdaterObjectFromArgument(arg: ArgFile): Updater {
8+
arg = typeof arg === 'string' ? { filename: arg } : arg;
9+
let updaterModule: UpdaterModule;
10+
11+
if (arg.updater) {
12+
updaterModule = getCustomUpdater(arg.updater);
13+
} else if (arg.type) {
14+
updaterModule = getUpdaterByType(arg.type);
15+
} else {
16+
updaterModule = getUpdaterByFilename(arg.filename);
17+
}
18+
19+
return {
20+
updater: updaterModule,
21+
filename: arg.filename,
22+
};
23+
}
24+
25+
function getCustomUpdater(updater: string | UpdaterModule): UpdaterModule {
26+
if (typeof updater === 'string') {
27+
// eslint-disable-next-line @typescript-eslint/no-require-imports
28+
return require(path.resolve(process.cwd(), updater));
29+
}
30+
if (
31+
typeof updater.readVersion === 'function' &&
32+
typeof updater.writeVersion === 'function'
33+
) {
34+
return updater;
35+
}
36+
throw new Error('Updater must be a string path or an object with readVersion and writeVersion methods');
37+
}
38+
39+
const JSON_BUMP_FILES = defaultBumpFiles;
40+
function getUpdaterByFilename(filename: any): UpdaterModule {
41+
if (JSON_BUMP_FILES.includes(path.basename(filename))) {
42+
return getUpdaterByType('json');
43+
}
44+
throw Error(
45+
`Unsupported file (${filename}) provided for bumping.\n Please specify the updater \`type\` or use a custom \`updater\`.`,
46+
);
47+
}
48+
49+
const updatersByType: { [key: string]: UpdaterModule } = {
50+
'json': jsonUpdaterModule,
51+
'plain-text': plainTextUpdaterModule,
52+
};
53+
function getUpdaterByType(type: string): UpdaterModule {
54+
const updater = updatersByType[type];
55+
if (!updater) {
56+
throw Error(`Unable to locate updater for provided type (${type}).`);
57+
}
58+
return updater;
59+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { UpdaterModule } from '../../types';
2+
3+
// eslint-disable-next-line @typescript-eslint/no-require-imports
4+
const detectIndent = require('detect-indent');
5+
// eslint-disable-next-line @typescript-eslint/no-require-imports
6+
const detectNewline = require('detect-newline');
7+
// eslint-disable-next-line @typescript-eslint/no-require-imports
8+
const stringifyPackage = require('stringify-package');
9+
10+
class JsonUpdaterModule implements UpdaterModule {
11+
public readVersion(contents: string): string {
12+
return JSON.parse(contents).version;
13+
};
14+
15+
public writeVersion(contents: string, version: string): string {
16+
const json = JSON.parse(contents);
17+
const indent = detectIndent(contents).indent;
18+
const newline = detectNewline(contents);
19+
json.version = version;
20+
return stringifyPackage(json, indent, newline);
21+
};
22+
23+
public isPrivate(contents: string): string | boolean | null | undefined {
24+
return JSON.parse(contents).private;
25+
};
26+
}
27+
const jsonUpdaterModule = new JsonUpdaterModule();
28+
export default jsonUpdaterModule;
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { UpdaterModule } from '../../types';
2+
3+
const plainTextUpdaterModule: UpdaterModule = {
4+
readVersion(contents: string): string {
5+
return contents;
6+
},
7+
8+
writeVersion(_contents: string, version: string): string {
9+
return version;
10+
},
11+
};
12+
export default plainTextUpdaterModule;

‎tools/cdk-release/package.json

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
{
2+
"name": "cdk-release",
3+
"private": true,
4+
"version": "0.0.0",
5+
"description": "A tool for performing release-related tasks like version bumps, Changelog generation, etc.",
6+
"repository": {
7+
"type": "git",
8+
"url": "https://github.com/aws/aws-cdk.git",
9+
"directory": "tools/cdk-release"
10+
},
11+
"main": "lib/index.js",
12+
"types": "lib/index.d.ts",
13+
"scripts": {
14+
"build": "cdk-build",
15+
"watch": "cdk-watch",
16+
"lint": "cdk-lint",
17+
"test": "cdk-test",
18+
"pkglint": "pkglint -f",
19+
"build+test+package": "yarn build+test",
20+
"build+test": "yarn build && yarn test",
21+
"build+extract": "yarn build",
22+
"build+test+extract": "yarn build+test"
23+
},
24+
"author": {
25+
"name": "Amazon Web Services",
26+
"url": "https://aws.amazon.com",
27+
"organization": true
28+
},
29+
"license": "Apache-2.0",
30+
"devDependencies": {
31+
"@types/fs-extra": "^8.1.1",
32+
"@types/jest": "^26.0.23",
33+
"@types/yargs": "^15.0.13",
34+
"cdk-build-tools": "0.0.0",
35+
"jest": "^26.6.3",
36+
"pkglint": "0.0.0"
37+
},
38+
"dependencies": {
39+
"@lerna/project": "^4.0.0",
40+
"conventional-changelog": "^3.1.24",
41+
"conventional-changelog-config-spec": "^2.1.0",
42+
"conventional-changelog-preset-loader": "^2.3.4",
43+
"conventional-commits-parser": "^3.2.1",
44+
"conventional-changelog-writer": "^4.1.0",
45+
"fs-extra": "^9.1.0",
46+
"git-raw-commits": "^2.0.10",
47+
"semver": "^7.3.5",
48+
"stringify-package": "^1.0.1",
49+
"detect-indent": "^6.1.0",
50+
"detect-newline": "^3.1.0"
51+
},
52+
"keywords": [
53+
"aws",
54+
"cdk",
55+
"changelog",
56+
"bump",
57+
"release",
58+
"version"
59+
],
60+
"homepage": "https://github.com/aws/aws-cdk",
61+
"engines": {
62+
"node": ">= 10.13.0 <13 || >=13.7.0"
63+
},
64+
"cdk-build": {
65+
"jest": true
66+
},
67+
"ubergen": {
68+
"exclude": true
69+
}
70+
}
+110
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
import { ConventionalCommit, filterCommits } from '../lib/conventional-commits';
2+
import { changelog } from '../lib/lifecycles/changelog';
3+
import { ReleaseOptions } from '../lib/types';
4+
5+
describe('Changelog generation', () => {
6+
const args: ReleaseOptions = {
7+
releaseAs: 'minor',
8+
dryRun: true,
9+
silent: true,
10+
includeDateInChangelog: false,
11+
};
12+
13+
test("correctly handles 'BREAKING CHANGES'", async () => {
14+
const commits: ConventionalCommit[] = [
15+
buildCommit({
16+
type: 'feat',
17+
subject: 'super important feature',
18+
notes: [
19+
{
20+
title: 'BREAKING CHANGE',
21+
text: 'this is a breaking change',
22+
},
23+
],
24+
}),
25+
buildCommit({
26+
type: 'fix',
27+
scope: 'scope',
28+
subject: 'hairy bugfix',
29+
}),
30+
buildCommit({
31+
type: 'chore',
32+
subject: 'this commit should not be rendered in the Changelog',
33+
}),
34+
];
35+
36+
const changelogContents = await invokeChangelogFrom1_23_0to1_24_0(args, commits);
37+
38+
expect(changelogContents).toBe(
39+
`## [1.24.0](https://github.com/aws/aws-cdk/compare/v1.23.0...v1.24.0)
40+
41+
### ⚠ BREAKING CHANGES TO EXPERIMENTAL FEATURES
42+
43+
* this is a breaking change
44+
45+
### Features
46+
47+
* super important feature
48+
49+
50+
### Bug Fixes
51+
52+
* **scope:** hairy bugfix
53+
54+
`);
55+
});
56+
57+
test("correctly skips experimental modules, even with 'BREAKING CHANGES'", async () => {
58+
const commits: ConventionalCommit[] = [
59+
buildCommit({
60+
type: 'feat',
61+
scope: 'scope',
62+
subject: 'super important feature',
63+
}),
64+
buildCommit({
65+
type: 'fix',
66+
scope: 'example-construct-library', // really hope we don't stabilize this one
67+
subject: 'hairy bugfix',
68+
notes: [
69+
{
70+
title: 'BREAKING CHANGE',
71+
text: 'this is a breaking change',
72+
},
73+
],
74+
}),
75+
];
76+
77+
const changelogContents = await invokeChangelogFrom1_23_0to1_24_0({
78+
...args,
79+
stripExperimentalChanges: true,
80+
}, commits);
81+
82+
expect(changelogContents).toBe(
83+
`## [1.24.0](https://github.com/aws/aws-cdk/compare/v1.23.0...v1.24.0)
84+
85+
### Features
86+
87+
* **scope:** super important feature
88+
89+
`);
90+
});
91+
});
92+
93+
interface PartialCommit extends Partial<ConventionalCommit> {
94+
readonly type: string;
95+
readonly subject: string;
96+
}
97+
98+
function buildCommit(commit: PartialCommit): ConventionalCommit {
99+
return {
100+
notes: [],
101+
references: [],
102+
header: `${commit.type}${commit.scope ? '(' + commit.scope + ')' : ''}: ${commit.subject}`,
103+
...commit,
104+
};
105+
}
106+
107+
async function invokeChangelogFrom1_23_0to1_24_0(args: ReleaseOptions, commits: ConventionalCommit[]): Promise<string> {
108+
const changelogResult = await changelog(args, '1.23.0', '1.24.0', filterCommits(args, commits));
109+
return changelogResult.contents;
110+
}

‎tools/cdk-release/tsconfig.json

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
{
2+
"compilerOptions": {
3+
"target": "ES2018",
4+
"module": "commonjs",
5+
"lib": ["es2018"],
6+
"strict": true,
7+
"alwaysStrict": true,
8+
"declaration": true,
9+
"inlineSourceMap": true,
10+
"inlineSources": true,
11+
"noUnusedLocals": true,
12+
"noUnusedParameters": true,
13+
"noImplicitReturns": true,
14+
"noFallthroughCasesInSwitch": true,
15+
"resolveJsonModule": true,
16+
"composite": true,
17+
"incremental": true
18+
},
19+
"exclude": ["test/enrichments/**"],
20+
"include": ["**/*.ts"]
21+
}

0 commit comments

Comments
 (0)
Please sign in to comment.