All files / tasks release.ts

99.47% Statements 187/188
98.73% Branches 78/79
100% Functions 43/43
99.47% Lines 186/187
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    42x 42x 42x 42x 42x   42x 42x 42x 42x 42x 42x 42x 42x 42x   42x 42x 42x 42x 42x 42x 42x 42x   42x 42x     4x 4x       2x       3x 2x 2x 2x   3x 3x       2x 2x 2x 2x       2x 2x 2x 2x 1x   2x       3x 3x   3x 1x     3x 3x       36x 1x     36x 36x   36x 35x   1x     42x 4x 4x 2x 2x     4x 1x   3x 3x 1x     4x 2x 2x 2x 2x 1x         42x 3x 3x   3x 1x     2x   2x 1x             18x 18x 5x   13x 13x 14x 13x 13x 4x 4x       13x     42x 6x 6x   6x 4x   6x 4x   6x 5x     6x 6x 6x   6x 4x 4x 4x   3x 3x 3x   1x 1x   3x     2x     42x 3x 3x 3x 1x   3x 3x 3x 1x   3x     42x 4x 4x 4x 2x   2x 2x 1x 1x 4x   1x   1x           42x 2x 2x 2x 1x   2x 2x     42x 4x 4x 4x 1x   4x 4x 4x   4x 2x   2x 2x 1x 1x   1x     4x       42x 2x 2x 2x 2x   2x         2x   2x 2x 1x     2x     42x 5x 5x   5x       5x 1x     4x 3x     4x 2x 2x 1x   1x   3x 3x 3x      
import ITask = grunt.task.ITask;
 
export = function(grunt: IGrunt, packageJson: any) {
	const execa = require('execa');
	const path = require('path');
	const pkgDir = require('pkg-dir');
	const parse = require('parse-git-config');
 
	const packagePath = pkgDir.sync(process.cwd());
	const npmBin = 'npm';
	const gitBin = 'git';
	const temp = 'temp/';
	const defaultBranch = 'master';
	const preReleaseTags = ['alpha', 'beta', 'beta1', 'beta2', 'beta3', 'rc'];
	const gitBaseRemote = 'git@github.com:dojo/';
	const defaultMaintainers = ['sitepen', 'dojotoolkit', 'dojo'];
	const extraToCopy = ['README.md'];
 
	const releaseVersion = grunt.option<string>('release-version');
	const nextVersion = grunt.option<string>('next-version');
	const preReleaseTag = grunt.option<string>('pre-release-tag');
	const dryRun = grunt.option<boolean>('dry-run');
	const tag = grunt.option<string>('tag');
	const pushBack = grunt.option<boolean>('push-back');
	const initial = grunt.option<boolean>('initial');
	const skipChecks = grunt.option<boolean>('skip-checks');
 
	let initialPackageJson = grunt.file.readJSON(path.join(packagePath, 'package.json'));
	const commitMsg = '"Update package metadata"';
 
	function matchesPreReleaseTag(preReleaseTag: string, version: string): string[] {
		const regexp = new RegExp(`(.*)-(${preReleaseTag})\\.(\\d+)`);
		return regexp.exec(version) || [];
	}
 
	function matchesVersion(version1: string, version2: string): boolean {
		return version2.indexOf(version1) === 0;
	}
 
	function getNextPreReleaseTagVersion(versionInPackage: string, existingVersions: string[]): string {
		const filteredVersions = existingVersions
			.filter((v) => matchesVersion(versionInPackage, v))
			.filter((v) => matchesPreReleaseTag(preReleaseTag, v))
			.map((v) => parseInt(matchesPreReleaseTag(preReleaseTag, v)[3], 10) || 0);
 
		const nextVersion = filteredVersions.length ? Math.max(...filteredVersions) + 1 : 1;
		return `${versionInPackage}-${preReleaseTag}.${nextVersion}`;
	}
 
	function preparePackageJson(packageJson: any): any {
		packageJson.private = undefined;
		packageJson.scripts = undefined;
		packageJson.files = undefined;
		return packageJson;
	}
 
	function getGitRemote(): string|boolean {
		const gitConfig = parse.sync();
		const remotes = Object.keys(gitConfig)
			.filter((key) => key.indexOf('remote') === 0)
			.filter((key) => gitConfig[key].url.indexOf(gitBaseRemote) === 0)
			.map((key) => gitConfig[key].url);
 
		return remotes.length ? remotes[0] : false;
	}
 
	function npmPreReleaseVersion(versionInPackage: string, versions: string[]): Promise<any> {
		const versionToRelease = getNextPreReleaseTagVersion(versionInPackage, versions);
		const args = ['version', versionToRelease];
 
		if (dryRun) {
			args.unshift('--no-git-tag-version');
		}
 
		grunt.log.subhead(`version to release: ${versionToRelease}`);
		return command(npmBin, args, {}, true);
	}
 
	function command(bin: string, args: string[], options: any, executeOnDryRun?: boolean): Promise<any> {
		if (dryRun && !executeOnDryRun) {
			grunt.log.subhead('dry-run (not running)');
		}
 
		bin = `${bin} ${args.join(' ')}`;
		grunt.log.ok(`${bin} - ${JSON.stringify(options)}`);
 
		if (!dryRun || executeOnDryRun) {
			return execa.shell(bin, options);
		}
		return Promise.resolve({});
	}
 
	grunt.registerTask('can-publish-check', 'check whether author can publish', function (this: ITask) {
		const done = this.async();
		const whoamiPromise = command(npmBin, ['whoami'], {}, true).then(
			(result: any) => result.stdout,
			(err: any) => grunt.fail.fatal('not logged into npm')
		);
		let maintainersPromise: Promise<string[]>;
		if (initial) {
			maintainersPromise = Promise.resolve(defaultMaintainers);
		} else {
			maintainersPromise = command(npmBin, ['view', '.', '--json'], {}, true)
				.then((result: any) => <string[]> JSON.parse(result.stdout).maintainers)
				.then((maintainers: string[]) => maintainers.map((maintainer) => maintainer.replace(/\s<.*/, '')));
		}
 
		return Promise.all([whoamiPromise, maintainersPromise]).then((results) => {
			const user = results[0];
			const maintainers = results[1];
			const isMaintainer = maintainers.indexOf(user) > -1;
			if (!isMaintainer) {
				grunt.fail.fatal(`cannot publish this package with user ${user}`);
			}
		}).then(done);
	});
 
	grunt.registerTask('repo-is-clean-check', 'check whether the repo is clean', function (this: ITask) {
		const done = this.async();
		return command(gitBin, ['status', '--porcelain'], {}, true)
			.then((result: any) => {
				if (result.stdout) {
					grunt.fail.fatal('there are changes in the working tree');
				}
			})
			.then(() => command(gitBin, ['rev-parse', '--abbrev-ref', 'HEAD'], {}, true))
			.then((result: any) => {
				if (result.stdout !== defaultBranch) {
					grunt.fail.fatal(`not on ${defaultBranch} branch`);
				}
			})
			.then(done);
	});
 
	function updateDojoDependency(dependencies: any): boolean {
		let updatedDependency = false;
		if (!dependencies) {
			return updatedDependency;
		}
		let regExp = new RegExp('@dojo\/.*');
		Object.keys(dependencies).forEach((dependency) => {
			if (regExp.test(dependency)) {
				const version = dependencies[dependency];
				if (version !== tag && dependency !== initialPackageJson.name) {
					dependencies[dependency] = tag;
					updatedDependency = true;
				}
			}
		});
		return updatedDependency;
	}
 
	grunt.registerTask('update-dojo-dependency-tags', 'Update @dojo dependencies to the tag', function (this: ITask) {
		const done = this.async();
		const packageJson = { ...initialPackageJson };
 
		if (initialPackageJson.peerDependencies) {
			packageJson.peerDependencies = { ...initialPackageJson.peerDependencies };
		}
		if (initialPackageJson.dependencies) {
			packageJson.dependencies = { ...initialPackageJson.dependencies };
		}
		if (initialPackageJson.devDependencies) {
			packageJson.devDependencies = { ...initialPackageJson.devDependencies };
		}
 
		const updatedPeerDependency = updateDojoDependency(packageJson.peerDependencies);
		const updatedDependency = updateDojoDependency(packageJson.dependencies);
		const updatedDevDependency = updateDojoDependency(packageJson.devDependencies);
 
		if (updatedPeerDependency || updatedDependency || updatedDevDependency) {
			grunt.log.subhead(`Outdated @dojo dependencies detected updating to ${tag} version`);
			grunt.file.write('package.json', JSON.stringify(packageJson, null, '  ') + '\n');
			return command(npmBin, [ 'install' ], { cwd: packagePath }, true)
				.then(() => {
					initialPackageJson = packageJson;
					grunt.log.subhead(`Committing update to ${tag} for @dojo dependencies`);
					return command(gitBin, [ 'commit', '-am', '"Update tag for @dojo dependencies"' ], {}, false);
				}, () => {
					grunt.file.write('package.json', JSON.stringify(initialPackageJson, null, '  ') + '\n');
					grunt.fail.fatal(`${tag} is not available for one or more @dojo dependencies`);
				})
				.then(() => grunt.log.subhead('@dojo dependencies updated successfully to target tag'))
				.then(done);
		}
		return Promise.resolve().then(done);
	});
 
	grunt.registerTask('release-publish', 'publish the package to npm', function (this: ITask) {
		const done = this.async();
		const args = ['publish', '.'];
		if (tag) {
			args.push('--tag', tag);
		}
		const promises = [command(npmBin, args, { cwd: temp }, false)];
		grunt.log.subhead('publishing to npm...');
		if (dryRun) {
			promises.push(command(npmBin, ['pack', '../' + temp], { cwd: 'dist' }, true));
		}
		return Promise.all(promises).then(done);
	});
 
	grunt.registerTask('release-version-pre-release-tag', 'auto version based on pre release tag', function (this: ITask) {
		const done = this.async();
		const versionInPackage = initialPackageJson.version.replace(/-.*/g, '');
		if (initial) {
			return npmPreReleaseVersion(versionInPackage, []).then(done);
		} else {
			return command(npmBin, ['view', '.', '--json'], {}, true).then((result: any) => {
				if (result.stdout) {
					const time = JSON.parse(result.stdout).time;
					const versions = Object.keys(time).filter((key) => {
						return ['created', 'modified'].indexOf(key) < 0;
					});
					npmPreReleaseVersion(versionInPackage, versions).then(done);
				} else {
					grunt.fail.fatal('failed to fetch versions from npm');
				}
			});
		}
	});
 
	grunt.registerTask('release-version-specific', 'set the version manually', function (this: ITask) {
		const done = this.async();
		const args = ['version', releaseVersion];
		if (dryRun) {
			args.unshift('--no-git-tag-version');
		}
		grunt.log.subhead(`version to release: ${releaseVersion}`);
		return command(npmBin, args, {}, true).then(done);
	});
 
	grunt.registerTask('post-release-version', 'update the version post release', function (this: ITask) {
		const done = this.async();
		const packageJson = Object.assign({}, initialPackageJson);
		if (nextVersion) {
			packageJson.version = nextVersion;
		}
		grunt.file.write('package.json', JSON.stringify(packageJson, null, '  ') + '\n');
		grunt.log.subhead(`version of package.json to commit: ${packageJson.version}`);
		return command(gitBin, ['commit', '-am', commitMsg], {}, false)
			.then(() => {
				if (!pushBack) {
					return;
				}
				const remote = getGitRemote();
				if (remote) {
					return command(gitBin, ['push', <string> remote, defaultBranch], {}, false)
						.then(() => command(gitBin, ['push', <string> remote, '--tags'], {}, false));
				} else {
					grunt.log.subhead('could not find remote to push back to. please push with tags back to remote');
				}
			})
			.then(() => grunt.log.subhead('release completed. please push with tags back to remote'))
			.then(done);
	});
 
	grunt.registerTask('release-publish-flat', 'publish the flat package', function () {
		grunt.log.subhead('making flat package...');
		const pkg = grunt.file.readJSON(path.join(packagePath, 'package.json'));
		const dist = grunt.config('copy.staticDefinitionFiles-dist.dest');
		const tasks = ['copy:temp', 'release-publish', 'clean:temp'];
 
		grunt.config.merge({
			copy: { temp: { expand: true, cwd: dist, src: '**', dest: temp } },
			clean: { temp: [ temp ] }
		});
 
		grunt.file.write(path.join(temp, 'package.json'), JSON.stringify(preparePackageJson(pkg), null, '  ') + '\n');
 
		extraToCopy.forEach((fileName) => {
			if (grunt.file.exists(fileName)) {
				grunt.file.copy(fileName, temp + '/' + fileName);
			}
		});
		grunt.task.run(tasks);
	});
 
	grunt.registerTask('release', 'release', function () {
		grunt.option('remove-links', true);
		const tasks = ['dist'];
 
		Iif (tag) {
			tasks.unshift('update-dojo-dependency-tags');
		}
 
		if (skipChecks && !dryRun) {
			grunt.fail.fatal('you can only skip-checks on a dry-run!');
		}
 
		if (!skipChecks) {
			tasks.unshift('can-publish-check', 'repo-is-clean-check');
		}
 
		if (preReleaseTag && preReleaseTags.indexOf(preReleaseTag) > -1) {
			tasks.push('release-version-pre-release-tag');
		} else if (releaseVersion && nextVersion) {
			tasks.push('release-version-specific');
		} else {
			grunt.fail.fatal('please specify --pre-release-tag or --release-version and --next-version');
		}
		tasks.push('release-publish-flat');
		tasks.push('post-release-version');
		grunt.task.run(tasks);
	});
};