UNPKG

29.5 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3/**
4 * @license
5 * Copyright Google Inc. All Rights Reserved.
6 *
7 * Use of this source code is governed by an MIT-style license that can be
8 * found in the LICENSE file at https://angular.io/license
9 */
10const core_1 = require("@angular-devkit/core");
11const node_1 = require("@angular-devkit/core/node");
12const schematics_1 = require("@angular-devkit/schematics");
13const tools_1 = require("@angular-devkit/schematics/tools");
14const child_process_1 = require("child_process");
15const fs = require("fs");
16const path = require("path");
17const semver = require("semver");
18const schema_1 = require("../lib/config/schema");
19const command_1 = require("../models/command");
20const install_package_1 = require("../tasks/install-package");
21const color_1 = require("../utilities/color");
22const log_file_1 = require("../utilities/log-file");
23const package_manager_1 = require("../utilities/package-manager");
24const package_metadata_1 = require("../utilities/package-metadata");
25const package_tree_1 = require("../utilities/package-tree");
26const npa = require('npm-package-arg');
27const pickManifest = require('npm-pick-manifest');
28const oldConfigFileNames = ['.angular-cli.json', 'angular-cli.json'];
29const NG_VERSION_9_POST_MSG = color_1.colors.cyan('\nYour project has been updated to Angular version 9!\n' +
30 'For more info, please see: https://v9.angular.io/guide/updating-to-version-9');
31/**
32 * Disable CLI version mismatch checks and forces usage of the invoked CLI
33 * instead of invoking the local installed version.
34 */
35const disableVersionCheckEnv = process.env['NG_DISABLE_VERSION_CHECK'];
36const disableVersionCheck = disableVersionCheckEnv !== undefined &&
37 disableVersionCheckEnv !== '0' &&
38 disableVersionCheckEnv.toLowerCase() !== 'false';
39class UpdateCommand extends command_1.Command {
40 constructor() {
41 super(...arguments);
42 this.allowMissingWorkspace = true;
43 }
44 async initialize() {
45 this.packageManager = await package_manager_1.getPackageManager(this.workspace.root);
46 this.workflow = new tools_1.NodeWorkflow(new core_1.virtualFs.ScopedHost(new node_1.NodeJsSyncHost(), core_1.normalize(this.workspace.root)), {
47 packageManager: this.packageManager,
48 root: core_1.normalize(this.workspace.root),
49 // __dirname -> favor @schematics/update from this package
50 // Otherwise, use packages from the active workspace (migrations)
51 resolvePaths: [__dirname, this.workspace.root],
52 });
53 this.workflow.engineHost.registerOptionsTransform(tools_1.validateOptionsWithSchema(this.workflow.registry));
54 }
55 async executeSchematic(collection, schematic, options = {}) {
56 let error = false;
57 let logs = [];
58 const files = new Set();
59 const reporterSubscription = this.workflow.reporter.subscribe(event => {
60 // Strip leading slash to prevent confusion.
61 const eventPath = event.path.startsWith('/') ? event.path.substr(1) : event.path;
62 switch (event.kind) {
63 case 'error':
64 error = true;
65 const desc = event.description == 'alreadyExist' ? 'already exists' : 'does not exist.';
66 this.logger.error(`ERROR! ${eventPath} ${desc}.`);
67 break;
68 case 'update':
69 logs.push(`${color_1.colors.whiteBright('UPDATE')} ${eventPath} (${event.content.length} bytes)`);
70 files.add(eventPath);
71 break;
72 case 'create':
73 logs.push(`${color_1.colors.green('CREATE')} ${eventPath} (${event.content.length} bytes)`);
74 files.add(eventPath);
75 break;
76 case 'delete':
77 logs.push(`${color_1.colors.yellow('DELETE')} ${eventPath}`);
78 files.add(eventPath);
79 break;
80 case 'rename':
81 const eventToPath = event.to.startsWith('/') ? event.to.substr(1) : event.to;
82 logs.push(`${color_1.colors.blue('RENAME')} ${eventPath} => ${eventToPath}`);
83 files.add(eventPath);
84 break;
85 }
86 });
87 const lifecycleSubscription = this.workflow.lifeCycle.subscribe(event => {
88 if (event.kind == 'end' || event.kind == 'post-tasks-start') {
89 if (!error) {
90 // Output the logging queue, no error happened.
91 logs.forEach(log => this.logger.info(log));
92 logs = [];
93 }
94 }
95 });
96 // TODO: Allow passing a schematic instance directly
97 try {
98 await this.workflow
99 .execute({
100 collection,
101 schematic,
102 options,
103 logger: this.logger,
104 })
105 .toPromise();
106 reporterSubscription.unsubscribe();
107 lifecycleSubscription.unsubscribe();
108 return { success: !error, files };
109 }
110 catch (e) {
111 if (e instanceof schematics_1.UnsuccessfulWorkflowExecution) {
112 this.logger.error(`${color_1.colors.symbols.cross} Migration failed. See above for further details.\n`);
113 }
114 else {
115 const logPath = log_file_1.writeErrorToLogFile(e);
116 this.logger.fatal(`${color_1.colors.symbols.cross} Migration failed: ${e.message}\n` +
117 ` See "${logPath}" for further details.\n`);
118 }
119 return { success: false, files };
120 }
121 }
122 /**
123 * @return Whether or not the migration was performed successfully.
124 */
125 async executeMigration(packageName, collectionPath, migrationName, commit) {
126 const collection = this.workflow.engine.createCollection(collectionPath);
127 const name = collection.listSchematicNames().find(name => name === migrationName);
128 if (!name) {
129 this.logger.error(`Cannot find migration '${migrationName}' in '${packageName}'.`);
130 return false;
131 }
132 const schematic = this.workflow.engine.createSchematic(name, collection);
133 this.logger.info(color_1.colors.cyan(`** Executing '${migrationName}' of package '${packageName}' **\n`));
134 return this.executePackageMigrations([schematic.description], packageName, commit);
135 }
136 /**
137 * @return Whether or not the migrations were performed successfully.
138 */
139 async executeMigrations(packageName, collectionPath, range, commit) {
140 const collection = this.workflow.engine.createCollection(collectionPath);
141 const migrations = [];
142 for (const name of collection.listSchematicNames()) {
143 const schematic = this.workflow.engine.createSchematic(name, collection);
144 const description = schematic.description;
145 description.version = coerceVersionNumber(description.version) || undefined;
146 if (!description.version) {
147 continue;
148 }
149 if (semver.satisfies(description.version, range, { includePrerelease: true })) {
150 migrations.push(description);
151 }
152 }
153 migrations.sort((a, b) => semver.compare(a.version, b.version) || a.name.localeCompare(b.name));
154 if (migrations.length === 0) {
155 return true;
156 }
157 this.logger.info(color_1.colors.cyan(`** Executing migrations of package '${packageName}' **\n`));
158 return this.executePackageMigrations(migrations, packageName, commit);
159 }
160 // tslint:disable-next-line: no-any
161 async executePackageMigrations(migrations, packageName, commit = false) {
162 for (const migration of migrations) {
163 this.logger.info(`${color_1.colors.symbols.pointer} ${migration.description.replace(/\. /g, '.\n ')}`);
164 const result = await this.executeSchematic(migration.collection.name, migration.name);
165 if (!result.success) {
166 return false;
167 }
168 this.logger.info(' Migration completed.');
169 // Commit migration
170 if (commit) {
171 const commitPrefix = `${packageName} migration - ${migration.name}`;
172 const commitMessage = migration.description
173 ? `${commitPrefix}\n${migration.description}`
174 : commitPrefix;
175 const committed = this.commit(commitMessage);
176 if (!committed) {
177 // Failed to commit, something went wrong. Abort the update.
178 return false;
179 }
180 }
181 this.logger.info(''); // Extra trailing newline.
182 }
183 return true;
184 }
185 // tslint:disable-next-line:no-big-function
186 async run(options) {
187 // Check if the @angular-devkit/schematics package can be resolved from the workspace root
188 // This works around issues with packages containing migrations that cannot directly depend on the package
189 // This check can be removed once the schematic runtime handles this situation
190 try {
191 require.resolve('@angular-devkit/schematics', { paths: [this.workspace.root] });
192 }
193 catch (e) {
194 if (e.code === 'MODULE_NOT_FOUND') {
195 this.logger.fatal('The "@angular-devkit/schematics" package cannot be resolved from the workspace root directory. ' +
196 'This may be due to an unsupported node modules structure.\n' +
197 'Please remove both the "node_modules" directory and the package lock file; and then reinstall.\n' +
198 'If this does not correct the problem, ' +
199 'please temporarily install the "@angular-devkit/schematics" package within the workspace. ' +
200 'It can be removed once the update is complete.');
201 return 1;
202 }
203 throw e;
204 }
205 // Check if the current installed CLI version is older than the latest version.
206 if (!disableVersionCheck && await this.checkCLILatestVersion(options.verbose, options.next)) {
207 this.logger.warn(`The installed local Angular CLI version is older than the latest ${options.next ? 'pre-release' : 'stable'} version.\n` +
208 'Installing a temporary version to perform the update.');
209 return install_package_1.runTempPackageBin(`@angular/cli@${options.next ? 'next' : 'latest'}`, this.logger, this.packageManager, process.argv.slice(2));
210 }
211 const packages = [];
212 for (const request of options['--'] || []) {
213 try {
214 const packageIdentifier = npa(request);
215 // only registry identifiers are supported
216 if (!packageIdentifier.registry) {
217 this.logger.error(`Package '${request}' is not a registry package identifer.`);
218 return 1;
219 }
220 if (packages.some(v => v.name === packageIdentifier.name)) {
221 this.logger.error(`Duplicate package '${packageIdentifier.name}' specified.`);
222 return 1;
223 }
224 if (options.migrateOnly && packageIdentifier.rawSpec) {
225 this.logger.warn('Package specifier has no effect when using "migrate-only" option.');
226 }
227 // If next option is used and no specifier supplied, use next tag
228 if (options.next && !packageIdentifier.rawSpec) {
229 packageIdentifier.fetchSpec = 'next';
230 }
231 packages.push(packageIdentifier);
232 }
233 catch (e) {
234 this.logger.error(e.message);
235 return 1;
236 }
237 }
238 if (options.all && packages.length > 0) {
239 this.logger.error('Cannot specify packages when using the "all" option.');
240 return 1;
241 }
242 else if (options.all && options.migrateOnly) {
243 this.logger.error('Cannot use "all" option with "migrate-only" option.');
244 return 1;
245 }
246 else if (!options.migrateOnly && (options.from || options.to)) {
247 this.logger.error('Can only use "from" or "to" options with "migrate-only" option.');
248 return 1;
249 }
250 // If not asking for status then check for a clean git repository.
251 // This allows the user to easily reset any changes from the update.
252 const statusCheck = packages.length === 0 && !options.all;
253 if (!statusCheck && !this.checkCleanGit()) {
254 if (options.allowDirty) {
255 this.logger.warn('Repository is not clean. Update changes will be mixed with pre-existing changes.');
256 }
257 else {
258 this.logger.error('Repository is not clean. Please commit or stash any changes before updating.');
259 return 2;
260 }
261 }
262 this.logger.info(`Using package manager: '${this.packageManager}'`);
263 // Special handling for Angular CLI 1.x migrations
264 if (options.migrateOnly === undefined &&
265 options.from === undefined &&
266 !options.all &&
267 packages.length === 1 &&
268 packages[0].name === '@angular/cli' &&
269 this.workspace.configFile &&
270 oldConfigFileNames.includes(this.workspace.configFile)) {
271 options.migrateOnly = true;
272 options.from = '1.0.0';
273 }
274 this.logger.info('Collecting installed dependencies...');
275 const packageTree = await package_tree_1.readPackageTree(this.workspace.root);
276 const rootDependencies = package_tree_1.findNodeDependencies(packageTree);
277 this.logger.info(`Found ${Object.keys(rootDependencies).length} dependencies.`);
278 if (options.all) {
279 // 'all' option and a zero length packages have already been checked.
280 // Add all direct dependencies to be updated
281 for (const dep of Object.keys(rootDependencies)) {
282 const packageIdentifier = npa(dep);
283 if (options.next) {
284 packageIdentifier.fetchSpec = 'next';
285 }
286 packages.push(packageIdentifier);
287 }
288 }
289 else if (packages.length === 0) {
290 // Show status
291 const { success } = await this.executeSchematic('@schematics/update', 'update', {
292 force: options.force || false,
293 next: options.next || false,
294 verbose: options.verbose || false,
295 packageManager: this.packageManager,
296 packages: options.all ? Object.keys(rootDependencies) : [],
297 });
298 return success ? 0 : 1;
299 }
300 if (options.migrateOnly) {
301 if (!options.from && typeof options.migrateOnly !== 'string') {
302 this.logger.error('"from" option is required when using the "migrate-only" option without a migration name.');
303 return 1;
304 }
305 else if (packages.length !== 1) {
306 this.logger.error('A single package must be specified when using the "migrate-only" option.');
307 return 1;
308 }
309 if (options.next) {
310 this.logger.warn('"next" option has no effect when using "migrate-only" option.');
311 }
312 const packageName = packages[0].name;
313 const packageDependency = rootDependencies[packageName];
314 let packageNode = packageDependency && packageDependency.node;
315 if (packageDependency && !packageNode) {
316 this.logger.error('Package found in package.json but is not installed.');
317 return 1;
318 }
319 else if (!packageDependency) {
320 // Allow running migrations on transitively installed dependencies
321 // There can technically be nested multiple versions
322 // TODO: If multiple, this should find all versions and ask which one to use
323 const child = packageTree.children.find(c => c.name === packageName);
324 if (child) {
325 packageNode = child;
326 }
327 }
328 if (!packageNode) {
329 this.logger.error('Package is not installed.');
330 return 1;
331 }
332 const updateMetadata = packageNode.package['ng-update'];
333 let migrations = updateMetadata && updateMetadata.migrations;
334 if (migrations === undefined) {
335 this.logger.error('Package does not provide migrations.');
336 return 1;
337 }
338 else if (typeof migrations !== 'string') {
339 this.logger.error('Package contains a malformed migrations field.');
340 return 1;
341 }
342 else if (path.posix.isAbsolute(migrations) || path.win32.isAbsolute(migrations)) {
343 this.logger.error('Package contains an invalid migrations field. Absolute paths are not permitted.');
344 return 1;
345 }
346 // Normalize slashes
347 migrations = migrations.replace(/\\/g, '/');
348 if (migrations.startsWith('../')) {
349 this.logger.error('Package contains an invalid migrations field. ' +
350 'Paths outside the package root are not permitted.');
351 return 1;
352 }
353 // Check if it is a package-local location
354 const localMigrations = path.join(packageNode.path, migrations);
355 if (fs.existsSync(localMigrations)) {
356 migrations = localMigrations;
357 }
358 else {
359 // Try to resolve from package location.
360 // This avoids issues with package hoisting.
361 try {
362 migrations = require.resolve(migrations, { paths: [packageNode.path] });
363 }
364 catch (e) {
365 if (e.code === 'MODULE_NOT_FOUND') {
366 this.logger.error('Migrations for package were not found.');
367 }
368 else {
369 this.logger.error(`Unable to resolve migrations for package. [${e.message}]`);
370 }
371 return 1;
372 }
373 }
374 let success = false;
375 if (typeof options.migrateOnly == 'string') {
376 success = await this.executeMigration(packageName, migrations, options.migrateOnly, options.createCommits);
377 }
378 else {
379 const from = coerceVersionNumber(options.from);
380 if (!from) {
381 this.logger.error(`"from" value [${options.from}] is not a valid version.`);
382 return 1;
383 }
384 const migrationRange = new semver.Range('>' + from + ' <=' + (options.to || packageNode.package.version));
385 success = await this.executeMigrations(packageName, migrations, migrationRange, options.createCommits);
386 }
387 if (success) {
388 if (packageName === '@angular/core'
389 && (options.to || packageNode.package.version).split('.')[0] === '9') {
390 this.logger.info(NG_VERSION_9_POST_MSG);
391 }
392 return 0;
393 }
394 return 1;
395 }
396 const requests = [];
397 // Validate packages actually are part of the workspace
398 for (const pkg of packages) {
399 const node = rootDependencies[pkg.name] && rootDependencies[pkg.name].node;
400 if (!node) {
401 this.logger.error(`Package '${pkg.name}' is not a dependency.`);
402 return 1;
403 }
404 // If a specific version is requested and matches the installed version, skip.
405 if (pkg.type === 'version' && node.package.version === pkg.fetchSpec) {
406 this.logger.info(`Package '${pkg.name}' is already at '${pkg.fetchSpec}'.`);
407 continue;
408 }
409 requests.push({ identifier: pkg, node });
410 }
411 if (requests.length === 0) {
412 return 0;
413 }
414 const packagesToUpdate = [];
415 this.logger.info('Fetching dependency metadata from registry...');
416 for (const { identifier: requestIdentifier, node } of requests) {
417 const packageName = requestIdentifier.name;
418 let metadata;
419 try {
420 // Metadata requests are internally cached; multiple requests for same name
421 // does not result in additional network traffic
422 metadata = await package_metadata_1.fetchPackageMetadata(packageName, this.logger, {
423 verbose: options.verbose,
424 });
425 }
426 catch (e) {
427 this.logger.error(`Error fetching metadata for '${packageName}': ` + e.message);
428 return 1;
429 }
430 // Try to find a package version based on the user requested package specifier
431 // registry specifier types are either version, range, or tag
432 let manifest;
433 if (requestIdentifier.type === 'version' ||
434 requestIdentifier.type === 'range' ||
435 requestIdentifier.type === 'tag') {
436 try {
437 manifest = pickManifest(metadata, requestIdentifier.fetchSpec);
438 }
439 catch (e) {
440 if (e.code === 'ETARGET') {
441 // If not found and next was used and user did not provide a specifier, try latest.
442 // Package may not have a next tag.
443 if (requestIdentifier.type === 'tag' &&
444 requestIdentifier.fetchSpec === 'next' &&
445 !requestIdentifier.rawSpec) {
446 try {
447 manifest = pickManifest(metadata, 'latest');
448 }
449 catch (e) {
450 if (e.code !== 'ETARGET' && e.code !== 'ENOVERSIONS') {
451 throw e;
452 }
453 }
454 }
455 }
456 else if (e.code !== 'ENOVERSIONS') {
457 throw e;
458 }
459 }
460 }
461 if (!manifest) {
462 this.logger.error(`Package specified by '${requestIdentifier.raw}' does not exist within the registry.`);
463 return 1;
464 }
465 if (manifest.version === node.package.version) {
466 this.logger.info(`Package '${packageName}' is already up to date.`);
467 continue;
468 }
469 packagesToUpdate.push(requestIdentifier.toString());
470 }
471 if (packagesToUpdate.length === 0) {
472 return 0;
473 }
474 const { success } = await this.executeSchematic('@schematics/update', 'update', {
475 verbose: options.verbose || false,
476 force: options.force || false,
477 next: !!options.next,
478 packageManager: this.packageManager,
479 packages: packagesToUpdate,
480 migrateExternal: true,
481 });
482 if (success && options.createCommits) {
483 const committed = this.commit(`Angular CLI update for packages - ${packagesToUpdate.join(', ')}`);
484 if (!committed) {
485 return 1;
486 }
487 }
488 // This is a temporary workaround to allow data to be passed back from the update schematic
489 // tslint:disable-next-line: no-any
490 const migrations = global.externalMigrations;
491 if (success && migrations) {
492 for (const migration of migrations) {
493 const result = await this.executeMigrations(migration.package, migration.collection, new semver.Range('>' + migration.from + ' <=' + migration.to), options.createCommits);
494 if (!result) {
495 return 0;
496 }
497 }
498 if (migrations.some(m => m.package === '@angular/core' && m.to.split('.')[0] === '9')) {
499 this.logger.info(NG_VERSION_9_POST_MSG);
500 }
501 }
502 return success ? 0 : 1;
503 }
504 /**
505 * @return Whether or not the commit was successful.
506 */
507 commit(message) {
508 // Check if a commit is needed.
509 let commitNeeded;
510 try {
511 commitNeeded = hasChangesToCommit();
512 }
513 catch (err) {
514 this.logger.error(` Failed to read Git tree:\n${err.stderr}`);
515 return false;
516 }
517 if (!commitNeeded) {
518 this.logger.info(' No changes to commit after migration.');
519 return true;
520 }
521 // Commit changes and abort on error.
522 try {
523 createCommit(message);
524 }
525 catch (err) {
526 this.logger.error(`Failed to commit update (${message}):\n${err.stderr}`);
527 return false;
528 }
529 // Notify user of the commit.
530 const hash = findCurrentGitSha();
531 const shortMessage = message.split('\n')[0];
532 if (hash) {
533 this.logger.info(` Committed migration step (${getShortHash(hash)}): ${shortMessage}.`);
534 }
535 else {
536 // Commit was successful, but reading the hash was not. Something weird happened,
537 // but nothing that would stop the update. Just log the weirdness and continue.
538 this.logger.info(` Committed migration step: ${shortMessage}.`);
539 this.logger.warn(' Failed to look up hash of most recent commit, continuing anyways.');
540 }
541 return true;
542 }
543 checkCleanGit() {
544 try {
545 const topLevel = child_process_1.execSync('git rev-parse --show-toplevel', { encoding: 'utf8', stdio: 'pipe' });
546 const result = child_process_1.execSync('git status --porcelain', { encoding: 'utf8', stdio: 'pipe' });
547 if (result.trim().length === 0) {
548 return true;
549 }
550 // Only files inside the workspace root are relevant
551 for (const entry of result.split('\n')) {
552 const relativeEntry = path.relative(path.resolve(this.workspace.root), path.resolve(topLevel.trim(), entry.slice(3).trim()));
553 if (!relativeEntry.startsWith('..') && !path.isAbsolute(relativeEntry)) {
554 return false;
555 }
556 }
557 }
558 catch (_a) { }
559 return true;
560 }
561 /**
562 * Checks if the current installed CLI version is older than the latest version.
563 * @returns `true` when the installed version is older.
564 */
565 async checkCLILatestVersion(verbose = false, next = false) {
566 const { version: installedCLIVersion } = require('../package.json');
567 const LatestCLIManifest = await package_metadata_1.fetchPackageManifest(`@angular/cli@${next ? 'next' : 'latest'}`, this.logger, {
568 verbose,
569 usingYarn: this.packageManager === schema_1.PackageManager.Yarn,
570 });
571 return semver.lt(installedCLIVersion, LatestCLIManifest.version);
572 }
573}
574exports.UpdateCommand = UpdateCommand;
575/**
576 * @return Whether or not the working directory has Git changes to commit.
577 */
578function hasChangesToCommit() {
579 // List all modified files not covered by .gitignore.
580 const files = child_process_1.execSync('git ls-files -m -d -o --exclude-standard').toString();
581 // If any files are returned, then there must be something to commit.
582 return files !== '';
583}
584/**
585 * Precondition: Must have pending changes to commit, they do not need to be staged.
586 * Postcondition: The Git working tree is committed and the repo is clean.
587 * @param message The commit message to use.
588 */
589function createCommit(message) {
590 // Stage entire working tree for commit.
591 child_process_1.execSync('git add -A', { encoding: 'utf8', stdio: 'pipe' });
592 // Commit with the message passed via stdin to avoid bash escaping issues.
593 child_process_1.execSync('git commit --no-verify -F -', { encoding: 'utf8', stdio: 'pipe', input: message });
594}
595/**
596 * @return The Git SHA hash of the HEAD commit. Returns null if unable to retrieve the hash.
597 */
598function findCurrentGitSha() {
599 try {
600 const hash = child_process_1.execSync('git rev-parse HEAD', { encoding: 'utf8', stdio: 'pipe' });
601 return hash.trim();
602 }
603 catch (_a) {
604 return null;
605 }
606}
607function getShortHash(commitHash) {
608 return commitHash.slice(0, 9);
609}
610function coerceVersionNumber(version) {
611 if (!version) {
612 return null;
613 }
614 if (!version.match(/^\d{1,30}\.\d{1,30}\.\d{1,30}/)) {
615 const match = version.match(/^\d{1,30}(\.\d{1,30})*/);
616 if (!match) {
617 return null;
618 }
619 if (!match[1]) {
620 version = version.substr(0, match[0].length) + '.0.0' + version.substr(match[0].length);
621 }
622 else if (!match[2]) {
623 version = version.substr(0, match[0].length) + '.0' + version.substr(match[0].length);
624 }
625 else {
626 return null;
627 }
628 }
629 return semver.valid(version);
630}