forked from angular/flex-layout
-
Notifications
You must be signed in to change notification settings - Fork 0
/
release
executable file
·540 lines (466 loc) · 17.3 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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
#!/usr/bin/env node
(function () {
'use strict';
const strip = require('cli-color/strip');
const prompt = require('prompt-sync')();
const {mkdirSync} = require('temp');
const {writeFileSync, readdirSync, statSync, readFile, writeFile} = require('fs');
const {execSync} = require('child_process');
const {relative, sep, join} = require('path');
const isYes = matches.bind(this, 'yes');
const colors = require('colors');
const REPO_TITLE = 'Angular Flex-Layout';
const SOURCE_REPO = 'flex-layout'; // Source repository with Demo-app and wiki docs
const SOURCE_WIKI = 'flex-layout.wiki'; // Source repository with Demo-app and wiki docs
const DEPLOY_REPO = `${SOURCE_REPO}-builds`; // Build repository used for npm publish and travis CI
const NPM_RELEASES = 'scripts/release/releases.json';
const ORIGIN_SOURCE = `[email protected]:angular/${SOURCE_REPO}.git`;
const ORIGIN_WIKI = `[email protected]:angular/${SOURCE_WIKI}.git`;
const ORIGIN_DEPLOY = `[email protected]:angular/${DEPLOY_REPO}.git`;
const LINE_WIDTH = 80;
const DEFAULT_OPTIONS = { encoding: 'utf-8' };
const WIKI_PATH = 'docs/documentation';
const WIKI_LOCAL = mkdirSync(`${SOURCE_REPO}.wiki`);
const IS_DRY_RUN = isYes(prompt(`Is this a dry-run? ${'[yes/no]'.cyan} `));
const OLD_VERSION_PACKAGE = require('./package.json').version;
const MSG = `What would you like the old version to be? (default: ${OLD_VERSION_PACKAGE.cyan}) `;
const OLD_VERSION = prompt(MSG) || OLD_VERSION_PACKAGE;
const NEW_VERSION = getNewVersion();
const SKIP_ON_DRY_RUN = IS_DRY_RUN ? '## -- ' : '';
let cleanupCmds = ['rm -rf flex-layout-builds'];
let pushCmds = ['rm ./abort ./push'];
let abortCmds = ['rm ./abort ./push', 'git reset --hard', 'git checkout master'];
const validated = IS_DRY_RUN || validate();
if (validated) {
build();
}
function stringifyFunction (method) {
return method
.toString()
.split('\n')
.slice(1, -1)
.map(line => line.trim() )
.join(' ')
.replace(/"/g, '\\"');
}
// ********************************************************
// Scripts and Utils
// ********************************************************
/** start the build script */
function build () {
const hint = 'git add CHANGELOG.md; git commit --amend --no-edit;';
line();
checkoutVersionBranch();
updateVersion();
createChangelog();
commitChanges();
tagRelease();
cloneDeployRepo();
generateLatestBuild();
updateMaster();
addWikiDocs();
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 () {
const err = (msg) => {
let str = 'Error: ' + msg;
log(str.red);
};
if (process.argv[2] === '--force' || process.argv[3] === '--force') {
return true;
} else 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 must be performed from a 'staging' branch.`);
err('Please checkout the lastest source: `git checkout -B staging`.');
} else {
return true;
}
}
/**
* 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/${NEW_VERSION}`);
exec(`git checkout -q -b release/${NEW_VERSION}`);
pushCmds.push(`# build release/${NEW_VERSION} branch...`);
abortCmds.push('git checkout staging -q');
}
/** writes the new version to package.json */
function updateVersion() {
start(`Updating ${'package.json'.cyan} version from ${OLD_VERSION.cyan} to ${NEW_VERSION.cyan}...`);
updatePackageVersions();
done();
}
/** generates the changelog from the commits since the last release */
function createChangelog () {
start(`Generating changelog from ${OLD_VERSION.cyan} to ${NEW_VERSION.cyan}...`);
// Use the current CHANGELOG.md (that is on #master and now this branch)
exec(`git fetch origin --tags`);
exec(`./scripts/release/changelog.js`);
done();
abortCmds.push('git checkout CHANGELOG.md');
}
function updateReleasesJson () {
const RELEASE_PATH = './scripts/release/releases.json';
const config = require(RELEASE_PATH);
config.versions.unshift(NEW_VERSION);
config.latest = NEW_VERSION;
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 () {
let options = getVersionOptions(OLD_VERSION), key, type, version;
header();
log(`The current version is ${OLD_VERSION.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: ');
version = options[type - 1] ? options[type - 1] : type;
// 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) {
let 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) {
let hasBeta = version.indexOf('-beta') > -1;
let 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) {
let 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;
break;
case 'patch':
version.rc = 0;
break;
case 'rc':
version.beta = 0;
break;
case 'beta':
version.alpha = 0;
break;
}
}
}
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 () {
pushCmds.push(
`git tag v${NEW_VERSION} -f`,
`${SKIP_ON_DRY_RUN} git push --tags ${ORIGIN_SOURCE}`
);
}
/** amends the commit to include local changes (ie. changelog) */
function commitChanges () {
start('Committing changes...');
exec(`git commit -am "build(release): version ${NEW_VERSION}"`);
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 () {
const deployPath = `./${DEPLOY_REPO}`;
start(`Cloning ${deployPath.cyan} from Github...`);
exec(`rm -Rf ${deployPath}`);
exec(`git clone [email protected]:angular/${DEPLOY_REPO}.git --depth=1`);
done();
cleanupCmds.push(
'rm -rf dist',
`${SKIP_ON_DRY_RUN} rm -Rf ${deployPath}`,
`${SKIP_ON_DRY_RUN} git branch -D release/${NEW_VERSION}`
);
}
/** writes an array of commands to a bash script */
function writeScript (name, cmds) {
writeFileSync(name, '#!/usr/bin/env bash\n\n' + cmds.join('\n'));
exec('chmod +x ' + name);
}
/** updates the version for nightly builds in package.json */
function generateLatestBuild () {
start('Building deployed files...');
exec([
'rm -rf dist',
'gulp flex-layout:build-release:clean'
]);
done();
// Execute the next commands relative to the nightly builds repo
let options = {cwd: `./${DEPLOY_REPO}`};
start(`Copy files into ${options.cwd.cyan} repo...`);
exec([
`cp -Rf ../dist/@angular/${SOURCE_REPO}/* ./`, // local build output dir
'cp -f ../CHANGELOG.md .', // always over the CHANGELOG
'git add -A',
`git commit -m "build(deploy): release version ${NEW_VERSION}"`
], options);
done();
// These actions occur AFTER pause and the `./push`
pushCmds.push(
comment(`push to angular/${DEPLOY_REPO} (master and tag) and publish to npm`),
`cd ./${DEPLOY_REPO}`,
`node -e "const NEW_VERSION = '${NEW_VERSION}'; ${stringifyFunction(updatePackageVersions)}"`,
'git add package.json',
'cp -f ../CHANGELOG.md .', // Copy Changelog from root (if changed)
'git add CHANGELOG.md', // re-add to the commit
'git commit --amend --no-edit',
`git tag -f v${NEW_VERSION}`, // Tag and update nightly builds
'git pull --rebase --strategy=ours',
comment(!IS_DRY_RUN ? '' : `Updating deploy repo @angular/${DEPLOY_REPO} with tag ${NEW_VERSION}`),
`${SKIP_ON_DRY_RUN} git push ${ORIGIN_DEPLOY} master`,
`${SKIP_ON_DRY_RUN} git push --tags ${ORIGIN_DEPLOY} master`,
comment(!IS_DRY_RUN ? '' : `Publishing @angular/${SOURCE_REPO} ${NEW_VERSION} to npm`),
`${SKIP_ON_DRY_RUN} npm publish${(process.argv[2] === '--next' || process.argv[3] === '--next') ? ' --tag next' : ''}`,
'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
* ./scripts/release/package.json == package for the deployed npm build
*/
function updatePackageVersions () {
['./package.json'].forEach(filePath => {
let json = require(filePath);
json.version = NEW_VERSION;
writeFileSync(filePath, JSON.stringify(json, null, 2));
});
}
/**
* copies the changelog back over to master branch
* FYI -
* ./package.json == package for the source repo
* ./src/lib/package.json == package for the deployed npm build
* ./scripts/release/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/${NEW_VERSION} -- CHANGELOG.md`,
`node -e "const NEW_VERSION = '${NEW_VERSION}'; ${stringifyFunction(updatePackageVersions)}"`,
'git add package.json',
`node -e "const NEW_VERSION = '${NEW_VERSION}'; ${stringifyFunction(updateReleasesJson)}"`,
`git add ${NPM_RELEASES}`,
`git commit -m "chore(version): update version number in package.json to ${NEW_VERSION}"`,
`${SKIP_ON_DRY_RUN} git push ${ORIGIN_SOURCE} master`
);
}
/**
* adds the documentation stored in the repo to the GitHub wiki
*/
function addWikiDocs () {
exec(`git clone "https://github.com/angular/${SOURCE_WIKI}" "${WIKI_LOCAL}"`);
createWikiFiles();
pushCmds.push(
comment('push docs to Wiki'),
`cd ${WIKI_LOCAL}`,
'git add .',
`git commit -m "docs(wiki): update to version ${NEW_VERSION}"`,
`${SKIP_ON_DRY_RUN} git push ${ORIGIN_WIKI} master`
)
}
/**
* reads the list of files in the documentation path to
* be copied
*/
function readDocFiles(directory, filelist) {
if (directory[directory.length - 1] !== `${sep}`) {
directory = directory.concat(`${sep}`);
}
const files = readdirSync(directory);
filelist = filelist || [];
files.forEach((file) => {
if (statSync(directory + file).isDirectory()) {
filelist = readDocFiles(directory + file + `${sep}`, filelist);
} else {
const originalPath = directory + file;
const newPath = join(WIKI_LOCAL, originalPath
.replace(WIKI_PATH + `${sep}`, '')
.replace(`${sep}`, '-'));
filelist.push({ originalPath, newPath });
}
});
return filelist;
}
function createWikiFiles() {
const files = readDocFiles(WIKI_PATH) || [];
const linksToReplace = checkNameLinks(files);
const copies = files.map(({ originalPath, newPath }) => {
return copyDocFile(originalPath, newPath, linksToReplace)
});
return Promise.all(copies);
}
function checkNameLinks(files) {
return files.reduce((pValue, cValue) => {
const oldName = cValue.originalPath
.replace(WIKI_PATH + `${sep}`, '')
.replace('.md', '')
.replace(`${sep}`, '/');
const newName = '(' + cValue.newPath.split(`${sep}`).slice(-1).pop().replace('.md', '') + ')';
if (oldName !== newName) {
pValue.push({
oldName,
newName
});
}
return pValue;
}, []);
}
function copyDocFile(from, to, linksToReplace) {
from = relative(process.cwd(), from);
to = relative(process.cwd(), to);
const replaceHyphen = new RegExp('-', 'gi');
return new Promise((resolve, reject) => {
readFile(from, (error, data) => {
if (error) {
reject(error);
}
let fileData = data.toString();
linksToReplace.forEach((link) => {
const str = '\\(' + link.oldName.replace(replaceHyphen, '\\-') + '\\)';
const r = new RegExp(str, 'gi');
fileData = fileData.replace(r, link.newName);
});
writeFile(to, fileData, (error2) => {
if (error2) {
reject(error2);
}
resolve();
})
})
});
}
/** 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()} `;
let length = msg.length;
let spaces = Math.floor((LINE_WIDTH - length) / 2);
return Array(spaces + 1).join('-') + msg.green + Array(LINE_WIDTH - 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 {
let options = Object.create(DEFAULT_OPTIONS);
for (let key in userOptions) {
options[key] = userOptions[key];
}
return 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) {
let msgLength = strip(msg).length,
diff = LINE_WIDTH - 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(LINE_WIDTH + 1).join('-'));
}
})();