-
Notifications
You must be signed in to change notification settings - Fork 34
/
bump.ts
287 lines (242 loc) · 9 KB
/
bump.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import { aws_cloudwatch as cloudwatch, aws_codebuild as cbuild, aws_events as events, aws_events_targets as events_targets, core as cdk, } from "monocdk-experiment";
import { createBuildEnvironment } from "../build-env";
import permissions = require("../permissions");
import { WritableGitHubRepo } from "../repo";
// tslint:disable:max-line-length
export interface AutoBumpOptions {
/**
* The command to execute in order to bump the repo.
*
* The bump command is responsible to bump any version metadata, update
* CHANGELOG and commit this to the repository.
*
* @default "/bin/bash ./bump.sh"
*/
bumpCommand?: string;
/**
* The command to determine the current version.
* @default "git describe" by default the latest git tag will be used to determine the current version
*/
versionCommand?: string;
/**
* The schedule to produce an automatic bump.
*
* The expression can be one of:
*
* - cron expression, such as "cron(0 12 * * ? *)" will trigger every day at 12pm UTC
* - rate expression, such as "rate(1 day)" will trigger every 24 hours from the time of deployment
*
* To disable, use the string `disable`.
*
* @see https://docs.aws.amazon.com/AmazonCloudWatch/latest/events/ScheduledEvents.html
* @default "cron(0 12 * * ? *)" (12pm UTC daily)
*/
scheduleExpression?: string;
/**
* The image used for the builds.
*
* @default jsii/superchain (see docs)
*/
buildImage?: cbuild.IBuildImage;
/**
* The type of compute to use for this build.
* See the {@link ComputeType} enum for the possible values.
*
* @default taken from {@link #buildImage#defaultComputeType}
*/
computeType?: cbuild.ComputeType;
/**
* Indicates how the project builds Docker images. Specify true to enable
* running the Docker daemon inside a Docker container. This value must be
* set to true only if this build project will be used to build Docker
* images, and the specified build environment image is not one provided by
* AWS CodeBuild with Docker support. Otherwise, all associated builds that
* attempt to interact with the Docker daemon will fail.
*
* @default false
*/
privileged?: boolean;
/**
* Environment variables to pass to build
*/
env?: { [key: string]: string };
/**
* The name of the branch to push the bump commit (e.g. "master")
* This branch has to exist.
*
* @default - the commit will be pushed to the branch `bump/$VERSION`
*/
branch?: string;
/**
* Create a pull request after the branch is pushed.
*
* @default false
*/
pullRequest?: boolean;
/**
* Options for pull request
*
* @default - default options
*/
pullRequestOptions?: PullRequestOptions;
/**
* Git clone depth
*
* @default 0 clones the entire repository
*/
cloneDepth?: number;
}
export interface AutoBumpProps extends AutoBumpOptions {
/**
* The repository to bump.
*/
repo: WritableGitHubRepo;
}
export interface PullRequestOptions {
/**
* The title of the pull request.
*
* $VERSION will be substituted by the current version (obtained by executing `versionCommand`).
*
* @default "chore(release): $VERSION"
*/
title?: string;
/**
* The PR body.
* @default "see CHANGELOG"
*/
body?: string;
/**
* Base branch
* @default "master"
*/
base?: string;
}
export class AutoBump extends cdk.Construct {
/**
* CloudWatch alarm that will be triggered if bump fails.
*/
public readonly alarm: cloudwatch.Alarm;
constructor(parent: cdk.Construct, id: string, props: AutoBumpProps) {
super(parent, id);
const bumpCommand = props.bumpCommand || '/bin/sh ./bump.sh';
const sshKeySecret = props.repo.sshKeySecret;
if (!sshKeySecret) {
throw new Error(`Cannot install auto-bump on a repo without an SSH key secret`);
}
const commitEmail = props.repo.commitEmail;
if (!commitEmail) {
throw new Error(`Cannot install auto-bump on a repo without "commitEmail"`);
}
const commitUsername = props.repo.commitUsername;
if (!commitUsername) {
throw new Error(`Cannot install auto-bump on a repo without "commitUsername"`);
}
const pushCommands = new Array<string>();
const versionCommand = props.versionCommand ?? "git describe";
pushCommands.push(...[
`export VERSION=$(${versionCommand})`,
`export BRANCH=bump/$VERSION`,
`git branch -D $BRANCH || true`, // force delete the branch if it already exists
`git checkout -b $BRANCH`, // create a new branch from HEAD
]);
// if we want to merge this to a branch automatically, then check out the branch and merge
if (props.branch) {
pushCommands.push(...[
`git checkout ${props.branch}`,
`git merge $BRANCH`
]);
}
// add "origin" remote
pushCommands.push(`git remote add origin_ssh ${props.repo.repositoryUrlSsh}`);
// now push either to our bump branch or the destination branch
const targetBranch = props.branch || '$BRANCH';
pushCommands.push(`git push --follow-tags origin_ssh ${targetBranch }`);
const pullRequestEnabled = props.pullRequest || props.pullRequestOptions;
if (pullRequestEnabled) {
// we can't create a pull request if base=head
if (props.branch) {
const base = props.pullRequestOptions?.base ?? 'master';
if (props.branch === base) {
throw new Error(`cannot enable pull requests since the head branch ("${props.branch}") is the same as the base branch ("${base}")`);
}
}
pushCommands.push(...createPullRequestCommands(props.repo, props.pullRequestOptions));
}
// by default, clone the entire repo (cloneDepth: 0)
const cloneDepth = props.cloneDepth === undefined ? 0 : props.cloneDepth;
const project = new cbuild.Project(this, 'Bump', {
source: props.repo.createBuildSource(this, false, { cloneDepth }),
environment: createBuildEnvironment(props),
buildSpec: cbuild.BuildSpec.fromObject({
version: '0.2',
phases: {
pre_build: {
commands: [
`git config --global user.email "${commitEmail}"`,
`git config --global user.name "${commitUsername}"`,
]
},
build: {
commands: [
// We would like to do the equivalent of "if (!changes) { return success; }" here, but we can't because
// there's no way to stop a BuildSpec execution halfway through without throwing an error. Believe me, I
// checked the code. Instead we define a variable that we will switch all other lines on.
`git describe --exact-match HEAD && { echo "No new commits."; export SKIP=true; } || { echo "Changes to release."; export SKIP=false; }`,
`$SKIP || { ${bumpCommand}; }`,
`$SKIP || aws secretsmanager get-secret-value --secret-id "${sshKeySecret.secretArn}" --output=text --query=SecretString > ~/.ssh/id_rsa`,
`$SKIP || mkdir -p ~/.ssh`,
`$SKIP || chmod 0600 ~/.ssh/id_rsa`,
`$SKIP || chmod 0600 ~/.ssh/config`,
`$SKIP || ssh-keyscan -t rsa github.com >> ~/.ssh/known_hosts`,
...pushCommands.map(c => `$SKIP || { ${c} ; }`)
]
},
}
}),
});
if (project.role) {
permissions.grantSecretRead(sshKeySecret, project.role);
// if pull request is enabled, we also need access to the github token
if (pullRequestEnabled) {
permissions.grantSecretRead({ secretArn: props.repo.tokenSecretArn }, project.role);
}
}
if (props.scheduleExpression !== 'disable') {
// set up the schedule
const schedule = events.Schedule.expression(props.scheduleExpression === undefined
? 'cron(0 12 * * ? *)'
: props.scheduleExpression);
new events.Rule(this, 'Scheduler', {
description: 'Schedules an automatic bump for this repository',
schedule,
targets: [new events_targets.CodeBuildProject(project)],
});
}
this.alarm = project.metricFailedBuilds({ period: cdk.Duration.seconds(300) }).createAlarm(this, 'BumpFailedAlarm', {
threshold: 1,
evaluationPeriods: 1,
treatMissingData: cloudwatch.TreatMissingData.IGNORE,
});
}
}
function createPullRequestCommands(repo: WritableGitHubRepo, options: PullRequestOptions = { }): string[] {
const request = {
title: options.title ?? `chore(release): $VERSION`,
body: options.body ?? `see CHANGELOG`,
base: options.base ?? `master`,
head: `$BRANCH`
};
const curl = [
`curl`,
`-X POST`,
`--header "Authorization: token $GITHUB_TOKEN"`,
`--header "Content-Type: application/json"`,
`-d ${JSON.stringify(JSON.stringify(request))}`, // to escape quotes
`https://api.github.com/repos/${repo.owner}/${repo.repo}/pulls`
];
return [
`GITHUB_TOKEN=$(aws secretsmanager get-secret-value --secret-id "${repo.tokenSecretArn}" --output=text --query=SecretString)`,
curl.join(' ')
];
}