[6a3a178] | 1 | "use strict";
|
---|
| 2 | /**
|
---|
| 3 | * @license
|
---|
| 4 | * Copyright Google LLC All Rights Reserved.
|
---|
| 5 | *
|
---|
| 6 | * Use of this source code is governed by an MIT-style license that can be
|
---|
| 7 | * found in the LICENSE file at https://angular.io/license
|
---|
| 8 | */
|
---|
| 9 | var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
---|
| 10 | if (k2 === undefined) k2 = k;
|
---|
| 11 | Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
|
---|
| 12 | }) : (function(o, m, k, k2) {
|
---|
| 13 | if (k2 === undefined) k2 = k;
|
---|
| 14 | o[k2] = m[k];
|
---|
| 15 | }));
|
---|
| 16 | var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
---|
| 17 | Object.defineProperty(o, "default", { enumerable: true, value: v });
|
---|
| 18 | }) : function(o, v) {
|
---|
| 19 | o["default"] = v;
|
---|
| 20 | });
|
---|
| 21 | var __importStar = (this && this.__importStar) || function (mod) {
|
---|
| 22 | if (mod && mod.__esModule) return mod;
|
---|
| 23 | var result = {};
|
---|
| 24 | if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
|
---|
| 25 | __setModuleDefault(result, mod);
|
---|
| 26 | return result;
|
---|
| 27 | };
|
---|
| 28 | var __importDefault = (this && this.__importDefault) || function (mod) {
|
---|
| 29 | return (mod && mod.__esModule) ? mod : { "default": mod };
|
---|
| 30 | };
|
---|
| 31 | Object.defineProperty(exports, "__esModule", { value: true });
|
---|
| 32 | exports.UpdateCommand = void 0;
|
---|
| 33 | const schematics_1 = require("@angular-devkit/schematics");
|
---|
| 34 | const tools_1 = require("@angular-devkit/schematics/tools");
|
---|
| 35 | const child_process_1 = require("child_process");
|
---|
| 36 | const fs = __importStar(require("fs"));
|
---|
| 37 | const npm_package_arg_1 = __importDefault(require("npm-package-arg"));
|
---|
| 38 | const path = __importStar(require("path"));
|
---|
| 39 | const semver = __importStar(require("semver"));
|
---|
| 40 | const workspace_schema_1 = require("../lib/config/workspace-schema");
|
---|
| 41 | const command_1 = require("../models/command");
|
---|
| 42 | const schematic_engine_host_1 = require("../models/schematic-engine-host");
|
---|
| 43 | const version_1 = require("../models/version");
|
---|
| 44 | const color_1 = require("../utilities/color");
|
---|
| 45 | const install_package_1 = require("../utilities/install-package");
|
---|
| 46 | const log_file_1 = require("../utilities/log-file");
|
---|
| 47 | const package_manager_1 = require("../utilities/package-manager");
|
---|
| 48 | const package_metadata_1 = require("../utilities/package-metadata");
|
---|
| 49 | const package_tree_1 = require("../utilities/package-tree");
|
---|
| 50 | const pickManifest = require('npm-pick-manifest');
|
---|
| 51 | const NG_VERSION_9_POST_MSG = color_1.colors.cyan('\nYour project has been updated to Angular version 9!\n' +
|
---|
| 52 | 'For more info, please see: https://v9.angular.io/guide/updating-to-version-9');
|
---|
| 53 | const UPDATE_SCHEMATIC_COLLECTION = path.join(__dirname, '../src/commands/update/schematic/collection.json');
|
---|
| 54 | /**
|
---|
| 55 | * Disable CLI version mismatch checks and forces usage of the invoked CLI
|
---|
| 56 | * instead of invoking the local installed version.
|
---|
| 57 | */
|
---|
| 58 | const disableVersionCheckEnv = process.env['NG_DISABLE_VERSION_CHECK'];
|
---|
| 59 | const disableVersionCheck = disableVersionCheckEnv !== undefined &&
|
---|
| 60 | disableVersionCheckEnv !== '0' &&
|
---|
| 61 | disableVersionCheckEnv.toLowerCase() !== 'false';
|
---|
| 62 | class UpdateCommand extends command_1.Command {
|
---|
| 63 | constructor() {
|
---|
| 64 | super(...arguments);
|
---|
| 65 | this.allowMissingWorkspace = true;
|
---|
| 66 | this.packageManager = workspace_schema_1.PackageManager.Npm;
|
---|
| 67 | }
|
---|
| 68 | async initialize(options) {
|
---|
| 69 | this.packageManager = await package_manager_1.getPackageManager(this.context.root);
|
---|
| 70 | this.workflow = new tools_1.NodeWorkflow(this.context.root, {
|
---|
| 71 | packageManager: this.packageManager,
|
---|
| 72 | packageManagerForce: options.force,
|
---|
| 73 | // __dirname -> favor @schematics/update from this package
|
---|
| 74 | // Otherwise, use packages from the active workspace (migrations)
|
---|
| 75 | resolvePaths: [__dirname, this.context.root],
|
---|
| 76 | schemaValidation: true,
|
---|
| 77 | engineHostCreator: (options) => new schematic_engine_host_1.SchematicEngineHost(options.resolvePaths),
|
---|
| 78 | });
|
---|
| 79 | }
|
---|
| 80 | async executeSchematic(collection, schematic, options = {}) {
|
---|
| 81 | let error = false;
|
---|
| 82 | let logs = [];
|
---|
| 83 | const files = new Set();
|
---|
| 84 | const reporterSubscription = this.workflow.reporter.subscribe((event) => {
|
---|
| 85 | // Strip leading slash to prevent confusion.
|
---|
| 86 | const eventPath = event.path.startsWith('/') ? event.path.substr(1) : event.path;
|
---|
| 87 | switch (event.kind) {
|
---|
| 88 | case 'error':
|
---|
| 89 | error = true;
|
---|
| 90 | const desc = event.description == 'alreadyExist' ? 'already exists' : 'does not exist.';
|
---|
| 91 | this.logger.error(`ERROR! ${eventPath} ${desc}.`);
|
---|
| 92 | break;
|
---|
| 93 | case 'update':
|
---|
| 94 | logs.push(`${color_1.colors.cyan('UPDATE')} ${eventPath} (${event.content.length} bytes)`);
|
---|
| 95 | files.add(eventPath);
|
---|
| 96 | break;
|
---|
| 97 | case 'create':
|
---|
| 98 | logs.push(`${color_1.colors.green('CREATE')} ${eventPath} (${event.content.length} bytes)`);
|
---|
| 99 | files.add(eventPath);
|
---|
| 100 | break;
|
---|
| 101 | case 'delete':
|
---|
| 102 | logs.push(`${color_1.colors.yellow('DELETE')} ${eventPath}`);
|
---|
| 103 | files.add(eventPath);
|
---|
| 104 | break;
|
---|
| 105 | case 'rename':
|
---|
| 106 | const eventToPath = event.to.startsWith('/') ? event.to.substr(1) : event.to;
|
---|
| 107 | logs.push(`${color_1.colors.blue('RENAME')} ${eventPath} => ${eventToPath}`);
|
---|
| 108 | files.add(eventPath);
|
---|
| 109 | break;
|
---|
| 110 | }
|
---|
| 111 | });
|
---|
| 112 | const lifecycleSubscription = this.workflow.lifeCycle.subscribe((event) => {
|
---|
| 113 | if (event.kind == 'end' || event.kind == 'post-tasks-start') {
|
---|
| 114 | if (!error) {
|
---|
| 115 | // Output the logging queue, no error happened.
|
---|
| 116 | logs.forEach((log) => this.logger.info(` ${log}`));
|
---|
| 117 | logs = [];
|
---|
| 118 | }
|
---|
| 119 | }
|
---|
| 120 | });
|
---|
| 121 | // TODO: Allow passing a schematic instance directly
|
---|
| 122 | try {
|
---|
| 123 | await this.workflow
|
---|
| 124 | .execute({
|
---|
| 125 | collection,
|
---|
| 126 | schematic,
|
---|
| 127 | options,
|
---|
| 128 | logger: this.logger,
|
---|
| 129 | })
|
---|
| 130 | .toPromise();
|
---|
| 131 | reporterSubscription.unsubscribe();
|
---|
| 132 | lifecycleSubscription.unsubscribe();
|
---|
| 133 | return { success: !error, files };
|
---|
| 134 | }
|
---|
| 135 | catch (e) {
|
---|
| 136 | if (e instanceof schematics_1.UnsuccessfulWorkflowExecution) {
|
---|
| 137 | this.logger.error(`${color_1.colors.symbols.cross} Migration failed. See above for further details.\n`);
|
---|
| 138 | }
|
---|
| 139 | else {
|
---|
| 140 | const logPath = log_file_1.writeErrorToLogFile(e);
|
---|
| 141 | this.logger.fatal(`${color_1.colors.symbols.cross} Migration failed: ${e.message}\n` +
|
---|
| 142 | ` See "${logPath}" for further details.\n`);
|
---|
| 143 | }
|
---|
| 144 | return { success: false, files };
|
---|
| 145 | }
|
---|
| 146 | }
|
---|
| 147 | /**
|
---|
| 148 | * @return Whether or not the migration was performed successfully.
|
---|
| 149 | */
|
---|
| 150 | async executeMigration(packageName, collectionPath, migrationName, commit) {
|
---|
| 151 | const collection = this.workflow.engine.createCollection(collectionPath);
|
---|
| 152 | const name = collection.listSchematicNames().find((name) => name === migrationName);
|
---|
| 153 | if (!name) {
|
---|
| 154 | this.logger.error(`Cannot find migration '${migrationName}' in '${packageName}'.`);
|
---|
| 155 | return false;
|
---|
| 156 | }
|
---|
| 157 | const schematic = this.workflow.engine.createSchematic(name, collection);
|
---|
| 158 | this.logger.info(color_1.colors.cyan(`** Executing '${migrationName}' of package '${packageName}' **\n`));
|
---|
| 159 | return this.executePackageMigrations([schematic.description], packageName, commit);
|
---|
| 160 | }
|
---|
| 161 | /**
|
---|
| 162 | * @return Whether or not the migrations were performed successfully.
|
---|
| 163 | */
|
---|
| 164 | async executeMigrations(packageName, collectionPath, from, to, commit) {
|
---|
| 165 | const collection = this.workflow.engine.createCollection(collectionPath);
|
---|
| 166 | const migrationRange = new semver.Range('>' + (semver.prerelease(from) ? from.split('-')[0] + '-0' : from) + ' <=' + to);
|
---|
| 167 | const migrations = [];
|
---|
| 168 | for (const name of collection.listSchematicNames()) {
|
---|
| 169 | const schematic = this.workflow.engine.createSchematic(name, collection);
|
---|
| 170 | const description = schematic.description;
|
---|
| 171 | description.version = coerceVersionNumber(description.version) || undefined;
|
---|
| 172 | if (!description.version) {
|
---|
| 173 | continue;
|
---|
| 174 | }
|
---|
| 175 | if (semver.satisfies(description.version, migrationRange, { includePrerelease: true })) {
|
---|
| 176 | migrations.push(description);
|
---|
| 177 | }
|
---|
| 178 | }
|
---|
| 179 | migrations.sort((a, b) => semver.compare(a.version, b.version) || a.name.localeCompare(b.name));
|
---|
| 180 | if (migrations.length === 0) {
|
---|
| 181 | return true;
|
---|
| 182 | }
|
---|
| 183 | this.logger.info(color_1.colors.cyan(`** Executing migrations of package '${packageName}' **\n`));
|
---|
| 184 | return this.executePackageMigrations(migrations, packageName, commit);
|
---|
| 185 | }
|
---|
| 186 | async executePackageMigrations(migrations, packageName, commit = false) {
|
---|
| 187 | for (const migration of migrations) {
|
---|
| 188 | const [title, ...description] = migration.description.split('. ');
|
---|
| 189 | this.logger.info(color_1.colors.cyan(color_1.colors.symbols.pointer) +
|
---|
| 190 | ' ' +
|
---|
| 191 | color_1.colors.bold(title.endsWith('.') ? title : title + '.'));
|
---|
| 192 | if (description.length) {
|
---|
| 193 | this.logger.info(' ' + description.join('.\n '));
|
---|
| 194 | }
|
---|
| 195 | const result = await this.executeSchematic(migration.collection.name, migration.name);
|
---|
| 196 | if (!result.success) {
|
---|
| 197 | return false;
|
---|
| 198 | }
|
---|
| 199 | this.logger.info(' Migration completed.');
|
---|
| 200 | // Commit migration
|
---|
| 201 | if (commit) {
|
---|
| 202 | const commitPrefix = `${packageName} migration - ${migration.name}`;
|
---|
| 203 | const commitMessage = migration.description
|
---|
| 204 | ? `${commitPrefix}\n\n${migration.description}`
|
---|
| 205 | : commitPrefix;
|
---|
| 206 | const committed = this.commit(commitMessage);
|
---|
| 207 | if (!committed) {
|
---|
| 208 | // Failed to commit, something went wrong. Abort the update.
|
---|
| 209 | return false;
|
---|
| 210 | }
|
---|
| 211 | }
|
---|
| 212 | this.logger.info(''); // Extra trailing newline.
|
---|
| 213 | }
|
---|
| 214 | return true;
|
---|
| 215 | }
|
---|
| 216 | // eslint-disable-next-line max-lines-per-function
|
---|
| 217 | async run(options) {
|
---|
| 218 | var _a, _b;
|
---|
| 219 | await package_manager_1.ensureCompatibleNpm(this.context.root);
|
---|
| 220 | // Check if the current installed CLI version is older than the latest version.
|
---|
| 221 | if (!disableVersionCheck && (await this.checkCLILatestVersion(options.verbose, options.next))) {
|
---|
| 222 | this.logger.warn(`The installed local Angular CLI version is older than the latest ${options.next ? 'pre-release' : 'stable'} version.\n` + 'Installing a temporary version to perform the update.');
|
---|
| 223 | return install_package_1.runTempPackageBin(`@angular/cli@${options.next ? 'next' : 'latest'}`, this.packageManager, process.argv.slice(2));
|
---|
| 224 | }
|
---|
| 225 | const logVerbose = (message) => {
|
---|
| 226 | if (options.verbose) {
|
---|
| 227 | this.logger.info(message);
|
---|
| 228 | }
|
---|
| 229 | };
|
---|
| 230 | if (options.all) {
|
---|
| 231 | const updateCmd = this.packageManager === workspace_schema_1.PackageManager.Yarn
|
---|
| 232 | ? `'yarn upgrade-interactive' or 'yarn upgrade'`
|
---|
| 233 | : `'${this.packageManager} update'`;
|
---|
| 234 | this.logger.warn(`
|
---|
| 235 | '--all' functionality has been removed as updating multiple packages at once is not recommended.
|
---|
| 236 | To update packages which don’t provide 'ng update' capabilities in your workspace 'package.json' use ${updateCmd} instead.
|
---|
| 237 | Run the package manager update command after updating packages which provide 'ng update' capabilities.
|
---|
| 238 | `);
|
---|
| 239 | return 0;
|
---|
| 240 | }
|
---|
| 241 | const packages = [];
|
---|
| 242 | for (const request of options['--'] || []) {
|
---|
| 243 | try {
|
---|
| 244 | const packageIdentifier = npm_package_arg_1.default(request);
|
---|
| 245 | // only registry identifiers are supported
|
---|
| 246 | if (!packageIdentifier.registry) {
|
---|
| 247 | this.logger.error(`Package '${request}' is not a registry package identifer.`);
|
---|
| 248 | return 1;
|
---|
| 249 | }
|
---|
| 250 | if (packages.some((v) => v.name === packageIdentifier.name)) {
|
---|
| 251 | this.logger.error(`Duplicate package '${packageIdentifier.name}' specified.`);
|
---|
| 252 | return 1;
|
---|
| 253 | }
|
---|
| 254 | if (options.migrateOnly && packageIdentifier.rawSpec) {
|
---|
| 255 | this.logger.warn('Package specifier has no effect when using "migrate-only" option.');
|
---|
| 256 | }
|
---|
| 257 | // If next option is used and no specifier supplied, use next tag
|
---|
| 258 | if (options.next && !packageIdentifier.rawSpec) {
|
---|
| 259 | packageIdentifier.fetchSpec = 'next';
|
---|
| 260 | }
|
---|
| 261 | packages.push(packageIdentifier);
|
---|
| 262 | }
|
---|
| 263 | catch (e) {
|
---|
| 264 | this.logger.error(e.message);
|
---|
| 265 | return 1;
|
---|
| 266 | }
|
---|
| 267 | }
|
---|
| 268 | if (!options.migrateOnly && (options.from || options.to)) {
|
---|
| 269 | this.logger.error('Can only use "from" or "to" options with "migrate-only" option.');
|
---|
| 270 | return 1;
|
---|
| 271 | }
|
---|
| 272 | // If not asking for status then check for a clean git repository.
|
---|
| 273 | // This allows the user to easily reset any changes from the update.
|
---|
| 274 | if (packages.length && !this.checkCleanGit()) {
|
---|
| 275 | if (options.allowDirty) {
|
---|
| 276 | this.logger.warn('Repository is not clean. Update changes will be mixed with pre-existing changes.');
|
---|
| 277 | }
|
---|
| 278 | else {
|
---|
| 279 | this.logger.error('Repository is not clean. Please commit or stash any changes before updating.');
|
---|
| 280 | return 2;
|
---|
| 281 | }
|
---|
| 282 | }
|
---|
| 283 | this.logger.info(`Using package manager: '${this.packageManager}'`);
|
---|
| 284 | this.logger.info('Collecting installed dependencies...');
|
---|
| 285 | const rootDependencies = await package_tree_1.getProjectDependencies(this.context.root);
|
---|
| 286 | this.logger.info(`Found ${rootDependencies.size} dependencies.`);
|
---|
| 287 | if (packages.length === 0) {
|
---|
| 288 | // Show status
|
---|
| 289 | const { success } = await this.executeSchematic(UPDATE_SCHEMATIC_COLLECTION, 'update', {
|
---|
| 290 | force: options.force || false,
|
---|
| 291 | next: options.next || false,
|
---|
| 292 | verbose: options.verbose || false,
|
---|
| 293 | packageManager: this.packageManager,
|
---|
| 294 | packages: [],
|
---|
| 295 | });
|
---|
| 296 | return success ? 0 : 1;
|
---|
| 297 | }
|
---|
| 298 | if (options.migrateOnly) {
|
---|
| 299 | if (!options.from && typeof options.migrateOnly !== 'string') {
|
---|
| 300 | this.logger.error('"from" option is required when using the "migrate-only" option without a migration name.');
|
---|
| 301 | return 1;
|
---|
| 302 | }
|
---|
| 303 | else if (packages.length !== 1) {
|
---|
| 304 | this.logger.error('A single package must be specified when using the "migrate-only" option.');
|
---|
| 305 | return 1;
|
---|
| 306 | }
|
---|
| 307 | if (options.next) {
|
---|
| 308 | this.logger.warn('"next" option has no effect when using "migrate-only" option.');
|
---|
| 309 | }
|
---|
| 310 | const packageName = packages[0].name;
|
---|
| 311 | const packageDependency = rootDependencies.get(packageName);
|
---|
| 312 | let packagePath = packageDependency === null || packageDependency === void 0 ? void 0 : packageDependency.path;
|
---|
| 313 | let packageNode = packageDependency === null || packageDependency === void 0 ? void 0 : packageDependency.package;
|
---|
| 314 | if (packageDependency && !packageNode) {
|
---|
| 315 | this.logger.error('Package found in package.json but is not installed.');
|
---|
| 316 | return 1;
|
---|
| 317 | }
|
---|
| 318 | else if (!packageDependency) {
|
---|
| 319 | // Allow running migrations on transitively installed dependencies
|
---|
| 320 | // There can technically be nested multiple versions
|
---|
| 321 | // TODO: If multiple, this should find all versions and ask which one to use
|
---|
| 322 | const packageJson = package_tree_1.findPackageJson(this.context.root, packageName);
|
---|
| 323 | if (packageJson) {
|
---|
| 324 | packagePath = path.dirname(packageJson);
|
---|
| 325 | packageNode = await package_tree_1.readPackageJson(packageJson);
|
---|
| 326 | }
|
---|
| 327 | }
|
---|
| 328 | if (!packageNode || !packagePath) {
|
---|
| 329 | this.logger.error('Package is not installed.');
|
---|
| 330 | return 1;
|
---|
| 331 | }
|
---|
| 332 | const updateMetadata = packageNode['ng-update'];
|
---|
| 333 | let migrations = updateMetadata === null || updateMetadata === void 0 ? void 0 : 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(packagePath, 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: [packagePath] });
|
---|
| 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 | success = await this.executeMigrations(packageName, migrations, from, options.to || packageNode.version, options.createCommits);
|
---|
| 385 | }
|
---|
| 386 | if (success) {
|
---|
| 387 | if (packageName === '@angular/core' &&
|
---|
| 388 | options.from &&
|
---|
| 389 | +options.from.split('.')[0] < 9 &&
|
---|
| 390 | (options.to || packageNode.version).split('.')[0] === '9') {
|
---|
| 391 | this.logger.info(NG_VERSION_9_POST_MSG);
|
---|
| 392 | }
|
---|
| 393 | return 0;
|
---|
| 394 | }
|
---|
| 395 | return 1;
|
---|
| 396 | }
|
---|
| 397 | const requests = [];
|
---|
| 398 | // Validate packages actually are part of the workspace
|
---|
| 399 | for (const pkg of packages) {
|
---|
| 400 | const node = rootDependencies.get(pkg.name);
|
---|
| 401 | if (!(node === null || node === void 0 ? void 0 : node.package)) {
|
---|
| 402 | this.logger.error(`Package '${pkg.name}' is not a dependency.`);
|
---|
| 403 | return 1;
|
---|
| 404 | }
|
---|
| 405 | // If a specific version is requested and matches the installed version, skip.
|
---|
| 406 | if (pkg.type === 'version' && node.package.version === pkg.fetchSpec) {
|
---|
| 407 | this.logger.info(`Package '${pkg.name}' is already at '${pkg.fetchSpec}'.`);
|
---|
| 408 | continue;
|
---|
| 409 | }
|
---|
| 410 | requests.push({ identifier: pkg, node });
|
---|
| 411 | }
|
---|
| 412 | if (requests.length === 0) {
|
---|
| 413 | return 0;
|
---|
| 414 | }
|
---|
| 415 | const packagesToUpdate = [];
|
---|
| 416 | this.logger.info('Fetching dependency metadata from registry...');
|
---|
| 417 | for (const { identifier: requestIdentifier, node } of requests) {
|
---|
| 418 | const packageName = requestIdentifier.name;
|
---|
| 419 | let metadata;
|
---|
| 420 | try {
|
---|
| 421 | // Metadata requests are internally cached; multiple requests for same name
|
---|
| 422 | // does not result in additional network traffic
|
---|
| 423 | metadata = await package_metadata_1.fetchPackageMetadata(packageName, this.logger, {
|
---|
| 424 | verbose: options.verbose,
|
---|
| 425 | });
|
---|
| 426 | }
|
---|
| 427 | catch (e) {
|
---|
| 428 | this.logger.error(`Error fetching metadata for '${packageName}': ` + e.message);
|
---|
| 429 | return 1;
|
---|
| 430 | }
|
---|
| 431 | // Try to find a package version based on the user requested package specifier
|
---|
| 432 | // registry specifier types are either version, range, or tag
|
---|
| 433 | let manifest;
|
---|
| 434 | if (requestIdentifier.type === 'version' ||
|
---|
| 435 | requestIdentifier.type === 'range' ||
|
---|
| 436 | requestIdentifier.type === 'tag') {
|
---|
| 437 | try {
|
---|
| 438 | manifest = pickManifest(metadata, requestIdentifier.fetchSpec);
|
---|
| 439 | }
|
---|
| 440 | catch (e) {
|
---|
| 441 | if (e.code === 'ETARGET') {
|
---|
| 442 | // If not found and next was used and user did not provide a specifier, try latest.
|
---|
| 443 | // Package may not have a next tag.
|
---|
| 444 | if (requestIdentifier.type === 'tag' &&
|
---|
| 445 | requestIdentifier.fetchSpec === 'next' &&
|
---|
| 446 | !requestIdentifier.rawSpec) {
|
---|
| 447 | try {
|
---|
| 448 | manifest = pickManifest(metadata, 'latest');
|
---|
| 449 | }
|
---|
| 450 | catch (e) {
|
---|
| 451 | if (e.code !== 'ETARGET' && e.code !== 'ENOVERSIONS') {
|
---|
| 452 | throw e;
|
---|
| 453 | }
|
---|
| 454 | }
|
---|
| 455 | }
|
---|
| 456 | }
|
---|
| 457 | else if (e.code !== 'ENOVERSIONS') {
|
---|
| 458 | throw e;
|
---|
| 459 | }
|
---|
| 460 | }
|
---|
| 461 | }
|
---|
| 462 | if (!manifest) {
|
---|
| 463 | this.logger.error(`Package specified by '${requestIdentifier.raw}' does not exist within the registry.`);
|
---|
| 464 | return 1;
|
---|
| 465 | }
|
---|
| 466 | if (((_a = node.package) === null || _a === void 0 ? void 0 : _a.name) === '@angular/cli') {
|
---|
| 467 | // Migrations for non LTS versions of Angular CLI are no longer included in @schematics/angular v12.
|
---|
| 468 | const toBeInstalledMajorVersion = +manifest.version.split('.')[0];
|
---|
| 469 | const currentMajorVersion = +node.package.version.split('.')[0];
|
---|
| 470 | if (currentMajorVersion < 9 && toBeInstalledMajorVersion >= 12) {
|
---|
| 471 | const updateVersions = {
|
---|
| 472 | 1: 6,
|
---|
| 473 | 6: 7,
|
---|
| 474 | 7: 8,
|
---|
| 475 | 8: 9,
|
---|
| 476 | };
|
---|
| 477 | const updateTo = updateVersions[currentMajorVersion];
|
---|
| 478 | this.logger.error('Updating multiple major versions at once is not recommended. ' +
|
---|
| 479 | `Run 'ng update @angular/cli@${updateTo}' in your workspace directory ` +
|
---|
| 480 | `to update to latest '${updateTo}.x' version of '@angular/cli'.\n\n` +
|
---|
| 481 | 'For more information about the update process, see https://update.angular.io/.');
|
---|
| 482 | return 1;
|
---|
| 483 | }
|
---|
| 484 | }
|
---|
| 485 | if (manifest.version === ((_b = node.package) === null || _b === void 0 ? void 0 : _b.version)) {
|
---|
| 486 | this.logger.info(`Package '${packageName}' is already up to date.`);
|
---|
| 487 | continue;
|
---|
| 488 | }
|
---|
| 489 | packagesToUpdate.push(requestIdentifier.toString());
|
---|
| 490 | }
|
---|
| 491 | if (packagesToUpdate.length === 0) {
|
---|
| 492 | return 0;
|
---|
| 493 | }
|
---|
| 494 | const { success } = await this.executeSchematic(UPDATE_SCHEMATIC_COLLECTION, 'update', {
|
---|
| 495 | verbose: options.verbose || false,
|
---|
| 496 | force: options.force || false,
|
---|
| 497 | next: !!options.next,
|
---|
| 498 | packageManager: this.packageManager,
|
---|
| 499 | packages: packagesToUpdate,
|
---|
| 500 | });
|
---|
| 501 | if (success) {
|
---|
| 502 | try {
|
---|
| 503 | // Remove existing node modules directory to provide a stronger guarantee that packages
|
---|
| 504 | // will be hoisted into the correct locations.
|
---|
| 505 | await fs.promises.rmdir(path.join(this.context.root, 'node_modules'), {
|
---|
| 506 | recursive: true,
|
---|
| 507 | maxRetries: 3,
|
---|
| 508 | });
|
---|
| 509 | }
|
---|
| 510 | catch { }
|
---|
| 511 | const result = await install_package_1.installAllPackages(this.packageManager, options.force ? ['--force'] : [], this.context.root);
|
---|
| 512 | if (result !== 0) {
|
---|
| 513 | return result;
|
---|
| 514 | }
|
---|
| 515 | }
|
---|
| 516 | if (success && options.createCommits) {
|
---|
| 517 | const committed = this.commit(`Angular CLI update for packages - ${packagesToUpdate.join(', ')}`);
|
---|
| 518 | if (!committed) {
|
---|
| 519 | return 1;
|
---|
| 520 | }
|
---|
| 521 | }
|
---|
| 522 | // This is a temporary workaround to allow data to be passed back from the update schematic
|
---|
| 523 | // eslint-disable-next-line @typescript-eslint/no-explicit-any
|
---|
| 524 | const migrations = global.externalMigrations;
|
---|
| 525 | if (success && migrations) {
|
---|
| 526 | for (const migration of migrations) {
|
---|
| 527 | // Resolve the package from the workspace root, as otherwise it will be resolved from the temp
|
---|
| 528 | // installed CLI version.
|
---|
| 529 | let packagePath;
|
---|
| 530 | logVerbose(`Resolving migration package '${migration.package}' from '${this.context.root}'...`);
|
---|
| 531 | try {
|
---|
| 532 | try {
|
---|
| 533 | packagePath = path.dirname(
|
---|
| 534 | // This may fail if the `package.json` is not exported as an entry point
|
---|
| 535 | require.resolve(path.join(migration.package, 'package.json'), {
|
---|
| 536 | paths: [this.context.root],
|
---|
| 537 | }));
|
---|
| 538 | }
|
---|
| 539 | catch (e) {
|
---|
| 540 | if (e.code === 'MODULE_NOT_FOUND') {
|
---|
| 541 | // Fallback to trying to resolve the package's main entry point
|
---|
| 542 | packagePath = require.resolve(migration.package, { paths: [this.context.root] });
|
---|
| 543 | }
|
---|
| 544 | else {
|
---|
| 545 | throw e;
|
---|
| 546 | }
|
---|
| 547 | }
|
---|
| 548 | }
|
---|
| 549 | catch (e) {
|
---|
| 550 | if (e.code === 'MODULE_NOT_FOUND') {
|
---|
| 551 | logVerbose(e.toString());
|
---|
| 552 | this.logger.error(`Migrations for package (${migration.package}) were not found.` +
|
---|
| 553 | ' The package could not be found in the workspace.');
|
---|
| 554 | }
|
---|
| 555 | else {
|
---|
| 556 | this.logger.error(`Unable to resolve migrations for package (${migration.package}). [${e.message}]`);
|
---|
| 557 | }
|
---|
| 558 | return 1;
|
---|
| 559 | }
|
---|
| 560 | let migrations;
|
---|
| 561 | // Check if it is a package-local location
|
---|
| 562 | const localMigrations = path.join(packagePath, migration.collection);
|
---|
| 563 | if (fs.existsSync(localMigrations)) {
|
---|
| 564 | migrations = localMigrations;
|
---|
| 565 | }
|
---|
| 566 | else {
|
---|
| 567 | // Try to resolve from package location.
|
---|
| 568 | // This avoids issues with package hoisting.
|
---|
| 569 | try {
|
---|
| 570 | migrations = require.resolve(migration.collection, { paths: [packagePath] });
|
---|
| 571 | }
|
---|
| 572 | catch (e) {
|
---|
| 573 | if (e.code === 'MODULE_NOT_FOUND') {
|
---|
| 574 | this.logger.error(`Migrations for package (${migration.package}) were not found.`);
|
---|
| 575 | }
|
---|
| 576 | else {
|
---|
| 577 | this.logger.error(`Unable to resolve migrations for package (${migration.package}). [${e.message}]`);
|
---|
| 578 | }
|
---|
| 579 | return 1;
|
---|
| 580 | }
|
---|
| 581 | }
|
---|
| 582 | const result = await this.executeMigrations(migration.package, migrations, migration.from, migration.to, options.createCommits);
|
---|
| 583 | if (!result) {
|
---|
| 584 | return 0;
|
---|
| 585 | }
|
---|
| 586 | }
|
---|
| 587 | if (migrations.some((m) => m.package === '@angular/core' &&
|
---|
| 588 | m.to.split('.')[0] === '9' &&
|
---|
| 589 | +m.from.split('.')[0] < 9)) {
|
---|
| 590 | this.logger.info(NG_VERSION_9_POST_MSG);
|
---|
| 591 | }
|
---|
| 592 | }
|
---|
| 593 | return success ? 0 : 1;
|
---|
| 594 | }
|
---|
| 595 | /**
|
---|
| 596 | * @return Whether or not the commit was successful.
|
---|
| 597 | */
|
---|
| 598 | commit(message) {
|
---|
| 599 | // Check if a commit is needed.
|
---|
| 600 | let commitNeeded;
|
---|
| 601 | try {
|
---|
| 602 | commitNeeded = hasChangesToCommit();
|
---|
| 603 | }
|
---|
| 604 | catch (err) {
|
---|
| 605 | this.logger.error(` Failed to read Git tree:\n${err.stderr}`);
|
---|
| 606 | return false;
|
---|
| 607 | }
|
---|
| 608 | if (!commitNeeded) {
|
---|
| 609 | this.logger.info(' No changes to commit after migration.');
|
---|
| 610 | return true;
|
---|
| 611 | }
|
---|
| 612 | // Commit changes and abort on error.
|
---|
| 613 | try {
|
---|
| 614 | createCommit(message);
|
---|
| 615 | }
|
---|
| 616 | catch (err) {
|
---|
| 617 | this.logger.error(`Failed to commit update (${message}):\n${err.stderr}`);
|
---|
| 618 | return false;
|
---|
| 619 | }
|
---|
| 620 | // Notify user of the commit.
|
---|
| 621 | const hash = findCurrentGitSha();
|
---|
| 622 | const shortMessage = message.split('\n')[0];
|
---|
| 623 | if (hash) {
|
---|
| 624 | this.logger.info(` Committed migration step (${getShortHash(hash)}): ${shortMessage}.`);
|
---|
| 625 | }
|
---|
| 626 | else {
|
---|
| 627 | // Commit was successful, but reading the hash was not. Something weird happened,
|
---|
| 628 | // but nothing that would stop the update. Just log the weirdness and continue.
|
---|
| 629 | this.logger.info(` Committed migration step: ${shortMessage}.`);
|
---|
| 630 | this.logger.warn(' Failed to look up hash of most recent commit, continuing anyways.');
|
---|
| 631 | }
|
---|
| 632 | return true;
|
---|
| 633 | }
|
---|
| 634 | checkCleanGit() {
|
---|
| 635 | try {
|
---|
| 636 | const topLevel = child_process_1.execSync('git rev-parse --show-toplevel', {
|
---|
| 637 | encoding: 'utf8',
|
---|
| 638 | stdio: 'pipe',
|
---|
| 639 | });
|
---|
| 640 | const result = child_process_1.execSync('git status --porcelain', { encoding: 'utf8', stdio: 'pipe' });
|
---|
| 641 | if (result.trim().length === 0) {
|
---|
| 642 | return true;
|
---|
| 643 | }
|
---|
| 644 | // Only files inside the workspace root are relevant
|
---|
| 645 | for (const entry of result.split('\n')) {
|
---|
| 646 | const relativeEntry = path.relative(path.resolve(this.context.root), path.resolve(topLevel.trim(), entry.slice(3).trim()));
|
---|
| 647 | if (!relativeEntry.startsWith('..') && !path.isAbsolute(relativeEntry)) {
|
---|
| 648 | return false;
|
---|
| 649 | }
|
---|
| 650 | }
|
---|
| 651 | }
|
---|
| 652 | catch { }
|
---|
| 653 | return true;
|
---|
| 654 | }
|
---|
| 655 | /**
|
---|
| 656 | * Checks if the current installed CLI version is older than the latest version.
|
---|
| 657 | * @returns `true` when the installed version is older.
|
---|
| 658 | */
|
---|
| 659 | async checkCLILatestVersion(verbose = false, next = false) {
|
---|
| 660 | const installedCLIVersion = version_1.VERSION.full;
|
---|
| 661 | const LatestCLIManifest = await package_metadata_1.fetchPackageManifest(`@angular/cli@${next ? 'next' : 'latest'}`, this.logger, {
|
---|
| 662 | verbose,
|
---|
| 663 | usingYarn: this.packageManager === workspace_schema_1.PackageManager.Yarn,
|
---|
| 664 | });
|
---|
| 665 | return semver.lt(installedCLIVersion, LatestCLIManifest.version);
|
---|
| 666 | }
|
---|
| 667 | }
|
---|
| 668 | exports.UpdateCommand = UpdateCommand;
|
---|
| 669 | /**
|
---|
| 670 | * @return Whether or not the working directory has Git changes to commit.
|
---|
| 671 | */
|
---|
| 672 | function hasChangesToCommit() {
|
---|
| 673 | // List all modified files not covered by .gitignore.
|
---|
| 674 | const files = child_process_1.execSync('git ls-files -m -d -o --exclude-standard').toString();
|
---|
| 675 | // If any files are returned, then there must be something to commit.
|
---|
| 676 | return files !== '';
|
---|
| 677 | }
|
---|
| 678 | /**
|
---|
| 679 | * Precondition: Must have pending changes to commit, they do not need to be staged.
|
---|
| 680 | * Postcondition: The Git working tree is committed and the repo is clean.
|
---|
| 681 | * @param message The commit message to use.
|
---|
| 682 | */
|
---|
| 683 | function createCommit(message) {
|
---|
| 684 | // Stage entire working tree for commit.
|
---|
| 685 | child_process_1.execSync('git add -A', { encoding: 'utf8', stdio: 'pipe' });
|
---|
| 686 | // Commit with the message passed via stdin to avoid bash escaping issues.
|
---|
| 687 | child_process_1.execSync('git commit --no-verify -F -', { encoding: 'utf8', stdio: 'pipe', input: message });
|
---|
| 688 | }
|
---|
| 689 | /**
|
---|
| 690 | * @return The Git SHA hash of the HEAD commit. Returns null if unable to retrieve the hash.
|
---|
| 691 | */
|
---|
| 692 | function findCurrentGitSha() {
|
---|
| 693 | try {
|
---|
| 694 | const hash = child_process_1.execSync('git rev-parse HEAD', { encoding: 'utf8', stdio: 'pipe' });
|
---|
| 695 | return hash.trim();
|
---|
| 696 | }
|
---|
| 697 | catch {
|
---|
| 698 | return null;
|
---|
| 699 | }
|
---|
| 700 | }
|
---|
| 701 | function getShortHash(commitHash) {
|
---|
| 702 | return commitHash.slice(0, 9);
|
---|
| 703 | }
|
---|
| 704 | function coerceVersionNumber(version) {
|
---|
| 705 | if (!version) {
|
---|
| 706 | return null;
|
---|
| 707 | }
|
---|
| 708 | if (!version.match(/^\d{1,30}\.\d{1,30}\.\d{1,30}/)) {
|
---|
| 709 | const match = version.match(/^\d{1,30}(\.\d{1,30})*/);
|
---|
| 710 | if (!match) {
|
---|
| 711 | return null;
|
---|
| 712 | }
|
---|
| 713 | if (!match[1]) {
|
---|
| 714 | version = version.substr(0, match[0].length) + '.0.0' + version.substr(match[0].length);
|
---|
| 715 | }
|
---|
| 716 | else if (!match[2]) {
|
---|
| 717 | version = version.substr(0, match[0].length) + '.0' + version.substr(match[0].length);
|
---|
| 718 | }
|
---|
| 719 | else {
|
---|
| 720 | return null;
|
---|
| 721 | }
|
---|
| 722 | }
|
---|
| 723 | return semver.valid(version);
|
---|
| 724 | }
|
---|