forked from angular/flex-layout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
release
executable file
·430 lines (366 loc) · 13.9 KB
/
release
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
#!/usr/bin/env node
(function () {
'use strict';
const REPO_TITLE = 'Angular Flex-Layout';
const SOURCE_REPO = 'flex-layout'; // Source repository with Demo-app and wiki docs
const BUILD_REPO = 'flex-layout-builds'; // Build repository used for npm publish and travis CI
var lineWidth = 80;
var defaultOptions = { encoding: 'utf-8' };
var colors = require('colors');
var strip = require('cli-color/strip');
var fs = require('fs');
var prompt = require('prompt-sync')();
var child_process = require('child_process');
var releases = require('./tools/releases.json');
var oldVersion = require('./package.json').version;
var cleanupCmds = [];
var pushCmds = [ 'rm ./abort ./push' ];
var abortCmds = [ 'rm ./abort ./push', 'git reset --hard', 'git checkout master' ];
var origin = 'git@github.com:angular/flex-layout.git';
var newVersion = "";
var lastMajorVer = releases.latest;
var isYes = matches.bind(this, "yes");
var dryRun = isYes(prompt(`Is this a dry-run? ${"[yes/no]".cyan} `));
let msg = `What would you like the old version to be? (default: ${oldVersion.cyan}) `;
oldVersion = prompt(msg) || oldVersion;
newVersion = getNewVersion();
let validated = dryRun || validate();
if ( validated ) {
build();
}
// ********************************************************
// Scripts and Utils
// ********************************************************
/** start the build script */
function build () {
let hint = "git add CHANGELOG.md; git commit --amend --no-edit;";
line();
checkoutVersionBranch();
updateVersion();
createChangelog();
commitChanges();
tagRelease();
cloneDeployRepo();
generateLatestBuild();
updateMaster();
writeScript('abort', abortCmds.concat(cleanupCmds));
writeScript('push', pushCmds.concat(cleanupCmds));
line();
log(`Your repo is ${"ready".cyan} to be pushed.`);
log(`Please look over ${"CHANGELOG.md".cyan} and make any changes.`);
log(`! ------------ `);
log(`! NOTE: If you make changes to the CHANGELOG, use `);
log(`! ${hint.red} `);
log(`! before proceeding with "${"./push".cyan}"`);
log(`! ------------ `);
log(`If you would like to cancel this release, please run "${"./abort".cyan}"`);
log(`When you are ready, please run "${"./push".cyan}" to finish the process.`);
}
/** confirms that you will be able to perform the release before attempting */
function validate () {
if (exec('npm whoami') !== 'angular') {
err('You must be authenticated with npm as "angular" to perform a release.');
} else if (exec('git rev-parse --abbrev-ref HEAD') !== 'staging') {
err('Releases can only performed from "staging" at this time.');
} else {
return true;
}
function err (msg) {
var str = 'Error: ' + msg;
log(str.red);
}
}
/**
* Confirm case-insensitive prompt() response partially matches
* one of the options.
*/
function matches(options, value) {
value = value.toLowerCase();
if ( typeof options === 'string' ) options = [options];
options = [' '].concat(options);
return options.reduce((prev, curr)=>{
return !prev ? curr.indexOf(value) > -1 : true;
},false);
}
/** creates the version branch and adds abort steps */
function checkoutVersionBranch () {
exec(`git branch -q -D release/${newVersion}`);
exec(`git checkout -q -b release/${newVersion}`);
pushCmds.push(`# build release/${newVersion} branch...`);
abortCmds.push('git checkout staging -q');
}
/** writes the new version to package.json */
function updateVersion() {
start(`Updating ${"package.json".cyan} version from ${oldVersion.cyan} to ${newVersion.cyan}...`);
updatePackageVersions();
done();
}
/** generates the changelog from the commits since the last release */
function createChangelog () {
start(`Generating changelog from ${oldVersion.cyan} to ${newVersion.cyan}...`);
exec(`git fetch --all --tags ${origin}`);
// Use the current CHANGELOG.md (that is on #master and now this brank)
exec(`gulp changelog --sha=$(git rev-list -n 1 v${lastMajorVer})`);
done();
abortCmds.push('git checkout CHANGELOG.md');
}
function updateReleasesJson () {
const RELEASE_PATH = './tools/releases.json';
var config = require( RELEASE_PATH );
config.versions.unshift(newVersion);
config.latest = newVersion;
require('fs').writeFileSync(RELEASE_PATH, JSON.stringify(config, null, 2));
}
/** utility method for clearing the terminal */
function clear () {
write("\u001b[2J\u001b[0;0H");
}
/** prompts the user for the new version */
function getNewVersion () {
var options = getVersionOptions(oldVersion), key, type, version;
header();
log(`The current version is ${oldVersion.cyan}.`);
log('');
log('What should the next version be?');
for (key in options) { log((+key + 1) + ') ' + options[ key ].cyan); }
log('');
type = prompt('Please select a new version: ');
if (options[ type - 1 ]) version = options[ type - 1 ];
else if (type.match(/^\d+\.\d+\.\d+(-rc\.?\d+)?$/)) version = type;
else throw new Error('Your entry was invalid.');
log('');
log('The new version will be ' + version.cyan + '.');
return isYes(prompt(`Is this correct? ${"[yes/no]".cyan} `)) ? version : getNewVersion();
function getVersionOptions (version) {
return version.match(/-alpha\.?\d+$/) ? [ increment(version, 'alpha'), addBeta(increment(version, 'minor')) ] :
version.match(/-beta\.?\d+$/) ? [ increment(version, 'beta'), increment(version, 'rc') ] :
version.match(/-rc\.?\d+$/) ? [ increment(version, 'rc'), increment(version, 'patch') ] :
[ increment(version, 'patch'), increment(version, 'minor') ];
function increment (versionString, type) {
var version = parseVersion(versionString);
switch (type) {
case 'alpha':
case 'beta' :
case 'rc' :
case 'patch':
case 'minor':
++version[type];
break;
}
resetVersionParts(type);
return buildVersionString(version);
function parseVersion (version) {
var hasBeta = version.indexOf("-beta") > -1;
var parts = version.split(/\-beta\.|\-rc\.|\./g);
return {
string: version,
major: parts[ 0 ],
minor: parts[ 1 ],
patch: parts[ 2 ],
rc : hasBeta ? 0 : (parts[ 3 ] || 0),
beta : hasBeta ? (parts[ 3 ] || 0) : 0,
};
}
function buildVersionString (version) {
var str = version.major + '.' + version.minor + '.' + version.patch;
str += version.rc ? `-rc.${version.rc}` :
version.beta ? `-beta.${version.beta}` :
version.alpha ? `-alpha.${version.alpha}` : "";
return str;
}
function resetVersionParts() {
switch (type) {
case 'minor' : version.patch = 0;
case 'patch' : version.rc = 0;
case 'rc' : version.beta = 0;
case 'beta' : version.alpha = 0;
}
}
}
function addRC (str) {
return str + '-rc.1';
}
function addBeta (str) {
return str + '-beta.1';
}
}
}
/** adds git tag for release and pushes to github */
function tagRelease () {
if ( dryRun ) return;
pushCmds.push(
`git tag v${newVersion} -f`,
`git push --tags ${origin}`
// `git push ${origin} HEAD`, // do not push the release branch to origin
);
}
/** amends the commit to include local changes (ie. changelog) */
function commitChanges () {
start('Committing changes...');
exec(`git commit -am "build(release): version ${newVersion}"`);
done();
// Now any other changes (on the release branch will
// be amended to the last commit
// !! NOTE: Typically this is not needed.
//pushCmds.push('git commit --amend --no-edit');
}
/** utility method for cloning github repos */
function cloneDeployRepo () {
let path = "./"+BUILD_REPO;
start(`Cloning ${path.cyan} from Github...`);
exec(`rm -Rf ${path}`);
exec(`git clone git@github.com:angular/${BUILD_REPO}.git --depth=1`);
done();
cleanupCmds.push(
`rm -Rf ${path}`,
'rm -rf dist',
`git branch -D release/${newVersion}`
);
}
/** writes an array of commands to a bash script */
function writeScript (name, cmds) {
fs.writeFileSync(name, '#!/usr/bin/env bash\n\n' + cmds.join('\n'));
exec('chmod +x ' + name);
}
/** updates the version for flex-layout-builds in package.json */
function generateLatestBuild () {
start('Building deployed files...');
exec([
'rm -rf dist',
'gulp build:release'
]);
done();
// Execute the next commands relative to the flex-layout-builds repo
let options = {cwd: "./"+BUILD_REPO};
start(`Copy files into ${options.cwd.cyan} repo...`);
exec([
'cp -Rf ../dist/@angular/flex-layout/* ./', // local build output dir
'cp -f ../tools/scripts/release/npm_assets/package.json ./', // package for the deployed npm build
'cp -f ../CHANGELOG.md .', // always over the CHANGELOG
'git add -A',
`git commit -m "build(deploy): release version ${newVersion}"`
], options);
done();
// These actions occur AFTER pause and the `./push`
pushCmds.push(
comment(`push to angular/${BUILD_REPO} (master and tag) and publish to npm`),
`cd ./${BUILD_REPO}`,
'cp -f ../CHANGELOG.md .', // Copy Changelog from root (if changed)
'git add CHANGELOG.md', // re-add to the commit
'git commit --amend --no-edit',
dryRun ? 'cd ../' : '' // Stay in the BUILD_REPO dir is not dryrun
);
if ( !dryRun ) {
pushCmds.push(
`git tag -f v${newVersion}`, // Tag and update @angular/flex-layout-builds
'git pull --rebase --strategy=ours',
'git push',
'git push --tags',
comment(`publish @angular/flex-layout v${newVersion} to npm`),
'npm publish',
'cd ..'
);
}
}
/**
* When updating the 'master' branch, update both the source repository 'package.json',
* and also the npm version that is used when deploying the releases to npm.
* FYI -
* ./package.json == package for the source repo
* ./tools/scripts/release/npm_assets/package.json == package for the deployed npm build
*/
function updatePackageVersions () {
[
'./package.json',
'./tools/scripts/release/npm_assets/package.json'
].forEach(filePath => {
let json = require(filePath);
json.version = newVersion;
require('fs').writeFileSync(filePath, JSON.stringify(json, null, 2));
});
}
/**
* copies the changelog back over to master branch
* FYI -
* ./package.json == package for the source repo
* ./tools/scripts/release/npm_assets/package.json == package for the deployed npm build
* ./tools/releases.json == version list used by release script getNewVersion()
*/
function updateMaster () {
pushCmds.push(
comment('update package.json in master'),
'git checkout master -q',
`git checkout release/${newVersion} -- CHANGELOG.md`,
`node -e "var newVersion = '${newVersion}'; ${stringifyFunction(updatePackageVersions)}"`,
'git add package.json',
'git add tools/scripts/release/npm_assets/package.json',
`node -e "var newVersion = '${newVersion}'; ${stringifyFunction(updateReleasesJson)}"`,
`git add tools/releases.json`,
`git commit -m "chore(version): update version number in package.json to ${newVersion}"`,
dryRun ? `` : `git push ${origin} master`
);
function stringifyFunction (method) {
return method
.toString()
.split('\n')
.slice(1, -1)
.map((line) => line.trim() )
.join(' ')
.replace(/"/g, '\\"');
}
}
/** utility method to output header */
function header () {
clear();
line();
log(center(`${REPO_TITLE} : NPM Release`));
line();
}
/** outputs a centered message in the terminal */
function center (msg) {
msg = ' ' + msg.trim() + ' ';
var length = msg.length;
var spaces = Math.floor((lineWidth - length) / 2);
return Array(spaces + 1).join('-') + msg.green + Array(lineWidth - msg.length - spaces + 1).join('-');
}
/** outputs done text when a task is completed */
function done () {
log('done'.green);
}
/** utility method for executing terminal commands */
function exec (cmd, userOptions) {
if (cmd instanceof Array) {
return cmd.map( (cmd) => exec(cmd, userOptions) );
}
try {
var options = Object.create(defaultOptions);
for (var key in userOptions) options[ key ] = userOptions[ key ];
return child_process.execSync(cmd + ' 2> /dev/null', options).toString().trim();
} catch (err) {
return err;
}
}
/** returns a commented message for use in bash scripts */
function comment (msg) {
return '\n# ' + msg + '\n';
}
/** prints the left side of a task while it is being performed */
function start (msg) {
var msgLength = strip(msg).length,
diff = lineWidth - 4 - msgLength;
write(msg + Array(diff + 1).join(' '));
}
/** outputs to the terminal with string variable replacement */
function log (msg) {
msg = msg || '';
console.log(msg);
}
/** writes a message without a newline */
function write (msg) {
process.stdout.write(msg);
}
/** prints a horizontal line to the terminal */
function line () {
log(Array(lineWidth + 1).join('-'));
}
})();