update-impl.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. "use strict";
  2. Object.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. */
  10. const child_process_1 = require("child_process");
  11. const fs = require("fs");
  12. const path = require("path");
  13. const semver = require("semver");
  14. const schematic_command_1 = require("../models/schematic-command");
  15. const install_package_1 = require("../tasks/install-package");
  16. const package_manager_1 = require("../utilities/package-manager");
  17. const package_metadata_1 = require("../utilities/package-metadata");
  18. const package_tree_1 = require("../utilities/package-tree");
  19. const npa = require('npm-package-arg');
  20. const pickManifest = require('npm-pick-manifest');
  21. const oldConfigFileNames = ['.angular-cli.json', 'angular-cli.json'];
  22. class UpdateCommand extends schematic_command_1.SchematicCommand {
  23. constructor() {
  24. super(...arguments);
  25. this.allowMissingWorkspace = true;
  26. this.packageManager = package_manager_1.getPackageManager(this.workspace.root);
  27. }
  28. async parseArguments(_schematicOptions, _schema) {
  29. return {};
  30. }
  31. // tslint:disable-next-line:no-big-function
  32. async run(options) {
  33. // Check if the current installed CLI version is older than the latest version.
  34. if (await this.checkCLILatestVersion(options.verbose, options.next)) {
  35. this.logger.warn(`The installed Angular CLI version is older than the latest ${options.next ? 'pre-release' : 'stable'} version.\n` +
  36. 'Installing a temporary version to perform the update.');
  37. return install_package_1.runTempPackageBin(`@angular/cli@${options.next ? 'next' : 'latest'}`, this.logger, this.packageManager, process.argv.slice(2));
  38. }
  39. const packages = [];
  40. for (const request of options['--'] || []) {
  41. try {
  42. const packageIdentifier = npa(request);
  43. // only registry identifiers are supported
  44. if (!packageIdentifier.registry) {
  45. this.logger.error(`Package '${request}' is not a registry package identifer.`);
  46. return 1;
  47. }
  48. if (packages.some(v => v.name === packageIdentifier.name)) {
  49. this.logger.error(`Duplicate package '${packageIdentifier.name}' specified.`);
  50. return 1;
  51. }
  52. // If next option is used and no specifier supplied, use next tag
  53. if (options.next && !packageIdentifier.rawSpec) {
  54. packageIdentifier.fetchSpec = 'next';
  55. }
  56. packages.push(packageIdentifier);
  57. }
  58. catch (e) {
  59. this.logger.error(e.message);
  60. return 1;
  61. }
  62. }
  63. if (options.all && packages.length > 0) {
  64. this.logger.error('Cannot specify packages when using the "all" option.');
  65. return 1;
  66. }
  67. else if (options.all && options.migrateOnly) {
  68. this.logger.error('Cannot use "all" option with "migrate-only" option.');
  69. return 1;
  70. }
  71. else if (!options.migrateOnly && (options.from || options.to)) {
  72. this.logger.error('Can only use "from" or "to" options with "migrate-only" option.');
  73. return 1;
  74. }
  75. // If not asking for status then check for a clean git repository.
  76. // This allows the user to easily reset any changes from the update.
  77. const statusCheck = packages.length === 0 && !options.all;
  78. if (!statusCheck && !this.checkCleanGit()) {
  79. if (options.allowDirty) {
  80. this.logger.warn('Repository is not clean. Update changes will be mixed with pre-existing changes.');
  81. }
  82. else {
  83. this.logger.error('Repository is not clean. Please commit or stash any changes before updating.');
  84. return 2;
  85. }
  86. }
  87. this.logger.info(`Using package manager: '${this.packageManager}'`);
  88. // Special handling for Angular CLI 1.x migrations
  89. if (options.migrateOnly === undefined &&
  90. options.from === undefined &&
  91. !options.all &&
  92. packages.length === 1 &&
  93. packages[0].name === '@angular/cli' &&
  94. this.workspace.configFile &&
  95. oldConfigFileNames.includes(this.workspace.configFile)) {
  96. options.migrateOnly = true;
  97. options.from = '1.0.0';
  98. }
  99. this.logger.info('Collecting installed dependencies...');
  100. const packageTree = await package_tree_1.readPackageTree(this.workspace.root);
  101. const rootDependencies = package_tree_1.findNodeDependencies(packageTree);
  102. this.logger.info(`Found ${Object.keys(rootDependencies).length} dependencies.`);
  103. if (options.all || packages.length === 0) {
  104. // Either update all packages or show status
  105. return this.runSchematic({
  106. collectionName: '@schematics/update',
  107. schematicName: 'update',
  108. dryRun: !!options.dryRun,
  109. showNothingDone: false,
  110. additionalOptions: {
  111. force: options.force || false,
  112. next: options.next || false,
  113. verbose: options.verbose || false,
  114. packageManager: this.packageManager,
  115. packages: options.all ? Object.keys(rootDependencies) : [],
  116. },
  117. });
  118. }
  119. if (options.migrateOnly) {
  120. if (!options.from) {
  121. this.logger.error('"from" option is required when using the "migrate-only" option.');
  122. return 1;
  123. }
  124. else if (packages.length !== 1) {
  125. this.logger.error('A single package must be specified when using the "migrate-only" option.');
  126. return 1;
  127. }
  128. if (options.next) {
  129. this.logger.warn('"next" option has no effect when using "migrate-only" option.');
  130. }
  131. const packageName = packages[0].name;
  132. const packageDependency = rootDependencies[packageName];
  133. let packageNode = packageDependency && packageDependency.node;
  134. if (packageDependency && !packageNode) {
  135. this.logger.error('Package found in package.json but is not installed.');
  136. return 1;
  137. }
  138. else if (!packageDependency) {
  139. // Allow running migrations on transitively installed dependencies
  140. // There can technically be nested multiple versions
  141. // TODO: If multiple, this should find all versions and ask which one to use
  142. const child = packageTree.children.find(c => c.name === packageName);
  143. if (child) {
  144. packageNode = child;
  145. }
  146. }
  147. if (!packageNode) {
  148. this.logger.error('Package is not installed.');
  149. return 1;
  150. }
  151. const updateMetadata = packageNode.package['ng-update'];
  152. let migrations = updateMetadata && updateMetadata.migrations;
  153. if (migrations === undefined) {
  154. this.logger.error('Package does not provide migrations.');
  155. return 1;
  156. }
  157. else if (typeof migrations !== 'string') {
  158. this.logger.error('Package contains a malformed migrations field.');
  159. return 1;
  160. }
  161. else if (path.posix.isAbsolute(migrations) || path.win32.isAbsolute(migrations)) {
  162. this.logger.error('Package contains an invalid migrations field. Absolute paths are not permitted.');
  163. return 1;
  164. }
  165. // Normalize slashes
  166. migrations = migrations.replace(/\\/g, '/');
  167. if (migrations.startsWith('../')) {
  168. this.logger.error('Package contains an invalid migrations field. ' +
  169. 'Paths outside the package root are not permitted.');
  170. return 1;
  171. }
  172. // Check if it is a package-local location
  173. const localMigrations = path.join(packageNode.path, migrations);
  174. if (fs.existsSync(localMigrations)) {
  175. migrations = localMigrations;
  176. }
  177. else {
  178. // Try to resolve from package location.
  179. // This avoids issues with package hoisting.
  180. try {
  181. migrations = require.resolve(migrations, { paths: [packageNode.path] });
  182. }
  183. catch (e) {
  184. if (e.code === 'MODULE_NOT_FOUND') {
  185. this.logger.error('Migrations for package were not found.');
  186. }
  187. else {
  188. this.logger.error(`Unable to resolve migrations for package. [${e.message}]`);
  189. }
  190. return 1;
  191. }
  192. }
  193. return this.runSchematic({
  194. collectionName: '@schematics/update',
  195. schematicName: 'migrate',
  196. dryRun: !!options.dryRun,
  197. force: false,
  198. showNothingDone: false,
  199. additionalOptions: {
  200. package: packageName,
  201. collection: migrations,
  202. from: options.from,
  203. verbose: options.verbose || false,
  204. to: options.to || packageNode.package.version,
  205. },
  206. });
  207. }
  208. const requests = [];
  209. // Validate packages actually are part of the workspace
  210. for (const pkg of packages) {
  211. const node = rootDependencies[pkg.name] && rootDependencies[pkg.name].node;
  212. if (!node) {
  213. this.logger.error(`Package '${pkg.name}' is not a dependency.`);
  214. return 1;
  215. }
  216. // If a specific version is requested and matches the installed version, skip.
  217. if (pkg.type === 'version' && node.package.version === pkg.fetchSpec) {
  218. this.logger.info(`Package '${pkg.name}' is already at '${pkg.fetchSpec}'.`);
  219. continue;
  220. }
  221. requests.push({ identifier: pkg, node });
  222. }
  223. if (requests.length === 0) {
  224. return 0;
  225. }
  226. const packagesToUpdate = [];
  227. this.logger.info('Fetching dependency metadata from registry...');
  228. for (const { identifier: requestIdentifier, node } of requests) {
  229. const packageName = requestIdentifier.name;
  230. let metadata;
  231. try {
  232. // Metadata requests are internally cached; multiple requests for same name
  233. // does not result in additional network traffic
  234. metadata = await package_metadata_1.fetchPackageMetadata(packageName, this.logger, { verbose: options.verbose });
  235. }
  236. catch (e) {
  237. this.logger.error(`Error fetching metadata for '${packageName}': ` + e.message);
  238. return 1;
  239. }
  240. // Try to find a package version based on the user requested package specifier
  241. // registry specifier types are either version, range, or tag
  242. let manifest;
  243. if (requestIdentifier.type === 'version' ||
  244. requestIdentifier.type === 'range' ||
  245. requestIdentifier.type === 'tag') {
  246. try {
  247. manifest = pickManifest(metadata, requestIdentifier.fetchSpec);
  248. }
  249. catch (e) {
  250. if (e.code === 'ETARGET') {
  251. // If not found and next was used and user did not provide a specifier, try latest.
  252. // Package may not have a next tag.
  253. if (requestIdentifier.type === 'tag' &&
  254. requestIdentifier.fetchSpec === 'next' &&
  255. !requestIdentifier.rawSpec) {
  256. try {
  257. manifest = pickManifest(metadata, 'latest');
  258. }
  259. catch (e) {
  260. if (e.code !== 'ETARGET' && e.code !== 'ENOVERSIONS') {
  261. throw e;
  262. }
  263. }
  264. }
  265. }
  266. else if (e.code !== 'ENOVERSIONS') {
  267. throw e;
  268. }
  269. }
  270. }
  271. if (!manifest) {
  272. this.logger.error(`Package specified by '${requestIdentifier.raw}' does not exist within the registry.`);
  273. return 1;
  274. }
  275. if (manifest.version === node.package.version) {
  276. this.logger.info(`Package '${packageName}' is already up to date.`);
  277. continue;
  278. }
  279. packagesToUpdate.push(requestIdentifier.toString());
  280. }
  281. if (packagesToUpdate.length === 0) {
  282. return 0;
  283. }
  284. return this.runSchematic({
  285. collectionName: '@schematics/update',
  286. schematicName: 'update',
  287. dryRun: !!options.dryRun,
  288. showNothingDone: false,
  289. additionalOptions: {
  290. verbose: options.verbose || false,
  291. force: options.force || false,
  292. packageManager: this.packageManager,
  293. packages: packagesToUpdate,
  294. },
  295. });
  296. }
  297. checkCleanGit() {
  298. try {
  299. const topLevel = child_process_1.execSync('git rev-parse --show-toplevel', { encoding: 'utf8', stdio: 'pipe' });
  300. const result = child_process_1.execSync('git status --porcelain', { encoding: 'utf8', stdio: 'pipe' });
  301. if (result.trim().length === 0) {
  302. return true;
  303. }
  304. // Only files inside the workspace root are relevant
  305. for (const entry of result.split('\n')) {
  306. const relativeEntry = path.relative(path.resolve(this.workspace.root), path.resolve(topLevel.trim(), entry.slice(3).trim()));
  307. if (!relativeEntry.startsWith('..') && !path.isAbsolute(relativeEntry)) {
  308. return false;
  309. }
  310. }
  311. }
  312. catch (_a) { }
  313. return true;
  314. }
  315. /**
  316. * Checks if the current installed CLI version is older than the latest version.
  317. * @returns `true` when the installed version is older.
  318. */
  319. async checkCLILatestVersion(verbose = false, next = false) {
  320. const { version: installedCLIVersion } = require('../package.json');
  321. const LatestCLIManifest = await package_metadata_1.fetchPackageMetadata('@angular/cli', this.logger, {
  322. verbose,
  323. usingYarn: this.packageManager === 'yarn',
  324. });
  325. const latest = LatestCLIManifest.tags[next ? 'next' : 'latest'];
  326. if (!latest) {
  327. return false;
  328. }
  329. return semver.lt(installedCLIVersion, latest.version);
  330. }
  331. }
  332. exports.UpdateCommand = UpdateCommand;