PHP WebShell
Текущая директория: /opt/BitGoJS/node_modules/nx/src/command-line
Просмотр файла: migrate.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.migrate = exports.executeMigrations = exports.parseMigrationsOptions = exports.Migrator = exports.normalizeVersion = void 0;
const tslib_1 = require("tslib");
const chalk = require("chalk");
const child_process_1 = require("child_process");
const enquirer_1 = require("enquirer");
const path_1 = require("path");
const semver_1 = require("semver");
const util_1 = require("util");
const tree_1 = require("../generators/tree");
const fileutils_1 = require("../utils/fileutils");
const logger_1 = require("../utils/logger");
const package_json_1 = require("../utils/package-json");
const package_manager_1 = require("../utils/package-manager");
const params_1 = require("../utils/params");
const connect_1 = require("./connect");
const output_1 = require("../utils/output");
const ab_testing_1 = require("../utils/ab-testing");
const versions_1 = require("../utils/versions");
const fs_1 = require("fs");
const workspace_root_1 = require("../utils/workspace-root");
const is_ci_1 = require("../utils/is-ci");
const installation_directory_1 = require("../utils/installation-directory");
const configuration_1 = require("../config/configuration");
const child_process_2 = require("../utils/child-process");
const client_1 = require("../daemon/client/client");
const nx_cloud_utils_1 = require("../utils/nx-cloud-utils");
const execAsync = (0, util_1.promisify)(child_process_1.exec);
function normalizeVersion(version) {
const [semver, ...prereleaseTagParts] = version.split('-');
// Handle versions like 1.0.0-beta-next.2
const prereleaseTag = prereleaseTagParts.join('-');
const [major, minor, patch] = semver.split('.');
const newSemver = `${major || 0}.${minor || 0}.${patch || 0}`;
const newVersion = prereleaseTag
? `${newSemver}-${prereleaseTag}`
: newSemver;
const withoutPatch = `${major || 0}.${minor || 0}.0`;
const withoutPatchAndMinor = `${major || 0}.0.0`;
const variationsToCheck = [
newVersion,
newSemver,
withoutPatch,
withoutPatchAndMinor,
];
for (const variation of variationsToCheck) {
try {
if ((0, semver_1.gt)(variation, '0.0.0')) {
return variation;
}
}
catch (_a) { }
}
return '0.0.0';
}
exports.normalizeVersion = normalizeVersion;
function cleanSemver(version) {
var _a;
return (_a = (0, semver_1.clean)(version)) !== null && _a !== void 0 ? _a : (0, semver_1.coerce)(version);
}
function normalizeSlashes(packageName) {
return packageName.replace(/\\/g, '/');
}
class Migrator {
constructor(opts) {
this.packageUpdates = {};
this.collectedVersions = {};
this.promptAnswers = {};
this.packageJson = opts.packageJson;
this.nxInstallation = opts.nxInstallation;
this.getInstalledPackageVersion = opts.getInstalledPackageVersion;
this.fetch = opts.fetch;
this.installedPkgVersionOverrides = opts.from;
this.to = opts.to;
this.interactive = opts.interactive;
this.excludeAppliedMigrations = opts.excludeAppliedMigrations;
}
migrate(targetPackage, targetVersion) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
yield this.buildPackageJsonUpdates(targetPackage, {
version: targetVersion,
addToPackageJson: false,
});
const migrations = yield this.createMigrateJson();
return { packageUpdates: this.packageUpdates, migrations };
});
}
createMigrateJson() {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const migrations = yield Promise.all(Object.keys(this.packageUpdates).map((packageName) => tslib_1.__awaiter(this, void 0, void 0, function* () {
const currentVersion = this.getPkgVersion(packageName);
if (currentVersion === null)
return [];
const { version } = this.packageUpdates[packageName];
const { generators } = yield this.fetch(packageName, version);
if (!generators)
return [];
return Object.entries(generators)
.filter(([, migration]) => migration.version &&
this.gt(migration.version, currentVersion) &&
this.lte(migration.version, version) &&
this.areMigrationRequirementsMet(packageName, migration))
.map(([migrationName, migration]) => (Object.assign(Object.assign({}, migration), { package: packageName, name: migrationName })));
})));
return migrations.flat();
});
}
buildPackageJsonUpdates(targetPackage, target) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const packagesToCheck = yield this.populatePackageJsonUpdatesAndGetPackagesToCheck(targetPackage, target);
for (const packageToCheck of packagesToCheck) {
const filteredUpdates = {};
for (const packageUpdate of packageToCheck.updates) {
if (this.areRequirementsMet(packageUpdate.requires) &&
(!this.interactive ||
(yield this.runPackageJsonUpdatesConfirmationPrompt(packageUpdate)))) {
Object.entries(packageUpdate.packages).forEach(([name, update]) => {
filteredUpdates[name] = update;
this.packageUpdates[name] = update;
});
}
}
yield Promise.all(Object.entries(filteredUpdates).map(([name, update]) => this.buildPackageJsonUpdates(name, update)));
}
});
}
populatePackageJsonUpdatesAndGetPackagesToCheck(targetPackage, target) {
var _a;
return tslib_1.__awaiter(this, void 0, void 0, function* () {
let targetVersion = target.version;
if (this.to[targetPackage]) {
targetVersion = this.to[targetPackage];
}
if (!this.getPkgVersion(targetPackage)) {
this.addPackageUpdate(targetPackage, {
version: target.version,
addToPackageJson: target.addToPackageJson || false,
});
return [];
}
let migrationConfig;
try {
migrationConfig = yield this.fetch(targetPackage, targetVersion);
}
catch (e) {
if ((_a = e === null || e === void 0 ? void 0 : e.message) === null || _a === void 0 ? void 0 : _a.includes('No matching version')) {
throw new Error(`${e.message}\nRun migrate with --to="package1@version1,package2@version2"`);
}
else {
throw e;
}
}
targetVersion = migrationConfig.version;
if (this.collectedVersions[targetPackage] &&
(0, semver_1.gte)(this.collectedVersions[targetPackage], targetVersion)) {
return [];
}
this.collectedVersions[targetPackage] = targetVersion;
this.addPackageUpdate(targetPackage, {
version: migrationConfig.version,
addToPackageJson: target.addToPackageJson || false,
});
const { packageJsonUpdates, packageGroupOrder } = this.getPackageJsonUpdatesFromMigrationConfig(targetPackage, targetVersion, migrationConfig);
if (!packageJsonUpdates.length) {
return [];
}
const shouldCheckUpdates = packageJsonUpdates.some((packageJsonUpdate) => {
var _a;
return (this.interactive && packageJsonUpdate['x-prompt']) ||
Object.keys((_a = packageJsonUpdate.requires) !== null && _a !== void 0 ? _a : {}).length;
});
if (shouldCheckUpdates) {
return [{ package: targetPackage, updates: packageJsonUpdates }];
}
const packageUpdatesToApply = packageJsonUpdates.reduce((m, c) => (Object.assign(Object.assign({}, m), c.packages)), {});
return (yield Promise.all(Object.entries(packageUpdatesToApply).map(([packageName, packageUpdate]) => this.populatePackageJsonUpdatesAndGetPackagesToCheck(packageName, packageUpdate))))
.filter((pkgs) => pkgs.length)
.flat()
.sort((pkgUpdate1, pkgUpdate2) => packageGroupOrder.indexOf(pkgUpdate1.package) -
packageGroupOrder.indexOf(pkgUpdate2.package));
});
}
getPackageJsonUpdatesFromMigrationConfig(packageName, targetVersion, migrationConfig) {
const packageGroupOrder = this.getPackageJsonUpdatesFromPackageGroup(packageName, targetVersion, migrationConfig);
if (!migrationConfig.packageJsonUpdates ||
!this.getPkgVersion(packageName)) {
return { packageJsonUpdates: [], packageGroupOrder };
}
const packageJsonUpdates = this.filterPackageJsonUpdates(migrationConfig.packageJsonUpdates, packageName, targetVersion);
return { packageJsonUpdates, packageGroupOrder };
}
/**
* Mutates migrationConfig, adding package group updates into packageJsonUpdates section
*
* @param packageName Package which is being migrated
* @param targetVersion Version which is being migrated to
* @param migrationConfig Configuration which is mutated to contain package json updates
* @returns Order of package groups
*/
getPackageJsonUpdatesFromPackageGroup(packageName, targetVersion, migrationConfig) {
var _a, _b, _c;
var _d, _e;
const packageGroup = packageName === '@nrwl/workspace' && (0, semver_1.lt)(targetVersion, '14.0.0-beta.0')
? LEGACY_NRWL_PACKAGE_GROUP
: (_a = migrationConfig.packageGroup) !== null && _a !== void 0 ? _a : [];
let packageGroupOrder = [];
if (packageGroup.length) {
packageGroupOrder = packageGroup.map((packageConfig) => packageConfig.package);
(_b = migrationConfig.packageJsonUpdates) !== null && _b !== void 0 ? _b : (migrationConfig.packageJsonUpdates = {});
const packages = {};
migrationConfig.packageJsonUpdates[targetVersion + '--PackageGroup'] = {
version: targetVersion,
packages,
};
for (const packageConfig of packageGroup) {
packages[packageConfig.package] = {
version: packageConfig.version === '*'
? targetVersion
: packageConfig.version,
alwaysAddToPackageJson: false,
};
if (packageConfig.version === '*' &&
this.installedPkgVersionOverrides[packageName]) {
(_c = (_d = this.installedPkgVersionOverrides)[_e = packageConfig.package]) !== null && _c !== void 0 ? _c : (_d[_e] = this.installedPkgVersionOverrides[packageName]);
}
}
}
return packageGroupOrder;
}
filterPackageJsonUpdates(packageJsonUpdates, packageName, targetVersion) {
var _a, _b, _c;
const filteredPackageJsonUpdates = [];
for (const packageJsonUpdate of Object.values(packageJsonUpdates)) {
if (!packageJsonUpdate.packages ||
this.lte(packageJsonUpdate.version, this.getPkgVersion(packageName)) ||
this.gt(packageJsonUpdate.version, targetVersion)) {
continue;
}
const dependencies = Object.assign(Object.assign(Object.assign(Object.assign({}, (_a = this.packageJson) === null || _a === void 0 ? void 0 : _a.dependencies), (_b = this.packageJson) === null || _b === void 0 ? void 0 : _b.devDependencies), (_c = this.nxInstallation) === null || _c === void 0 ? void 0 : _c.plugins), (this.nxInstallation && { nx: this.nxInstallation.version }));
const filtered = {};
for (const [packageName, packageUpdate] of Object.entries(packageJsonUpdate.packages)) {
if (this.shouldApplyPackageUpdate(packageUpdate, packageName, dependencies)) {
filtered[packageName] = {
version: packageUpdate.version,
addToPackageJson: packageUpdate.alwaysAddToPackageJson
? 'dependencies'
: packageUpdate.addToPackageJson || false,
};
}
}
if (Object.keys(filtered).length) {
packageJsonUpdate.packages = filtered;
filteredPackageJsonUpdates.push(packageJsonUpdate);
}
}
return filteredPackageJsonUpdates;
}
shouldApplyPackageUpdate(packageUpdate, packageName, dependencies) {
return ((!packageUpdate.ifPackageInstalled ||
this.getPkgVersion(packageUpdate.ifPackageInstalled)) &&
(packageUpdate.alwaysAddToPackageJson ||
packageUpdate.addToPackageJson ||
!!(dependencies === null || dependencies === void 0 ? void 0 : dependencies[packageName])) &&
(!this.collectedVersions[packageName] ||
this.gt(packageUpdate.version, this.collectedVersions[packageName])));
}
addPackageUpdate(name, packageUpdate) {
if (!this.packageUpdates[name] ||
this.gt(packageUpdate.version, this.packageUpdates[name].version)) {
this.packageUpdates[name] = packageUpdate;
}
}
areRequirementsMet(requirements) {
if (!requirements || !Object.keys(requirements).length) {
return true;
}
return Object.entries(requirements).every(([pkgName, versionRange]) => {
if (this.packageUpdates[pkgName]) {
return (0, semver_1.satisfies)(cleanSemver(this.packageUpdates[pkgName].version), versionRange, { includePrerelease: true });
}
return (this.getPkgVersion(pkgName) &&
(0, semver_1.satisfies)(this.getPkgVersion(pkgName), versionRange, {
includePrerelease: true,
}));
});
}
areMigrationRequirementsMet(packageName, migration) {
if (!this.excludeAppliedMigrations) {
return this.areRequirementsMet(migration.requires);
}
return ((this.wasMigrationSkipped(migration.requires) ||
this.isMigrationForHigherVersionThanWhatIsInstalled(packageName, migration)) &&
this.areRequirementsMet(migration.requires));
}
isMigrationForHigherVersionThanWhatIsInstalled(packageName, migration) {
const installedVersion = this.getInstalledPackageVersion(packageName);
return (migration.version &&
(!installedVersion || this.gt(migration.version, installedVersion)) &&
this.lte(migration.version, this.packageUpdates[packageName].version));
}
wasMigrationSkipped(requirements) {
// no requiremets, so it ran before
if (!requirements || !Object.keys(requirements).length) {
return false;
}
// at least a requirement was not met, it was skipped
return Object.entries(requirements).some(([pkgName, versionRange]) => !this.getInstalledPackageVersion(pkgName) ||
!(0, semver_1.satisfies)(this.getInstalledPackageVersion(pkgName), versionRange, {
includePrerelease: true,
}));
}
runPackageJsonUpdatesConfirmationPrompt(packageUpdate) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (!packageUpdate['x-prompt']) {
return Promise.resolve(true);
}
const promptKey = this.getPackageUpdatePromptKey(packageUpdate);
if (this.promptAnswers[promptKey] !== undefined) {
// a same prompt was already answered, skip
return Promise.resolve(false);
}
return yield (0, enquirer_1.prompt)([
{
name: 'shouldApply',
type: 'confirm',
message: packageUpdate['x-prompt'],
initial: true,
},
]).then(({ shouldApply }) => {
this.promptAnswers[promptKey] = shouldApply;
return shouldApply;
});
});
}
getPackageUpdatePromptKey(packageUpdate) {
return Object.entries(packageUpdate.packages)
.map(([name, update]) => `${name}:${JSON.stringify(update)}`)
.join('|');
}
getPkgVersion(pkg) {
return this.getInstalledPackageVersion(pkg, this.installedPkgVersionOverrides);
}
gt(v1, v2) {
return (0, semver_1.gt)(normalizeVersion(v1), normalizeVersion(v2));
}
lte(v1, v2) {
return (0, semver_1.lte)(normalizeVersion(v1), normalizeVersion(v2));
}
}
exports.Migrator = Migrator;
const LEGACY_NRWL_PACKAGE_GROUP = [
{ package: '@nrwl/workspace', version: '*' },
{ package: '@nrwl/angular', version: '*' },
{ package: '@nrwl/cypress', version: '*' },
{ package: '@nrwl/devkit', version: '*' },
{ package: '@nrwl/eslint-plugin-nx', version: '*' },
{ package: '@nrwl/express', version: '*' },
{ package: '@nrwl/jest', version: '*' },
{ package: '@nrwl/linter', version: '*' },
{ package: '@nrwl/nest', version: '*' },
{ package: '@nrwl/next', version: '*' },
{ package: '@nrwl/node', version: '*' },
{ package: '@nrwl/nx-plugin', version: '*' },
{ package: '@nrwl/react', version: '*' },
{ package: '@nrwl/storybook', version: '*' },
{ package: '@nrwl/web', version: '*' },
{ package: '@nrwl/js', version: '*' },
{ package: '@nrwl/cli', version: '*' },
{ package: '@nrwl/nx-cloud', version: 'latest' },
{ package: '@nrwl/react-native', version: '*' },
{ package: '@nrwl/detox', version: '*' },
{ package: '@nrwl/expo', version: '*' },
{ package: '@nrwl/tao', version: '*' },
];
function normalizeVersionWithTagCheck(pkg, version) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
// This doesn't seem like a valid version, lets check if its a tag on the registry.
if (version && !(0, semver_1.coerce)(version)) {
try {
return (0, package_manager_1.packageRegistryView)(pkg, version, 'version');
}
catch (_a) {
// fall through to old logic
}
}
return normalizeVersion(version);
});
}
function versionOverrides(overrides, param) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const res = {};
const promises = overrides.split(',').map((p) => {
const split = p.lastIndexOf('@');
if (split === -1 || split === 0) {
throw new Error(`Incorrect '${param}' section. Use --${param}="package@version"`);
}
const selectedPackage = p.substring(0, split).trim();
const selectedVersion = p.substring(split + 1).trim();
if (!selectedPackage || !selectedVersion) {
throw new Error(`Incorrect '${param}' section. Use --${param}="package@version"`);
}
return normalizeVersionWithTagCheck(selectedPackage, selectedVersion).then((version) => {
res[normalizeSlashes(selectedPackage)] = version;
});
});
yield Promise.all(promises);
return res;
});
}
function parseTargetPackageAndVersion(args) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (!args) {
throw new Error(`Provide the correct package name and version. E.g., my-package@9.0.0.`);
}
if (args.indexOf('@') > -1) {
const i = args.lastIndexOf('@');
if (i === 0) {
const targetPackage = args.trim();
const targetVersion = 'latest';
return { targetPackage, targetVersion };
}
else {
const targetPackage = args.substring(0, i);
const maybeVersion = args.substring(i + 1);
if (!targetPackage || !maybeVersion) {
throw new Error(`Provide the correct package name and version. E.g., my-package@9.0.0.`);
}
const targetVersion = yield normalizeVersionWithTagCheck(targetPackage, maybeVersion);
return { targetPackage, targetVersion };
}
}
else {
if (args === 'latest' ||
args === 'next' ||
(0, semver_1.valid)(args) ||
args.match(/^\d+(?:\.\d+)?(?:\.\d+)?$/)) {
// Passing `nx` here may seem wrong, but nx and @nrwl/workspace are synced in version.
// We could duplicate the ternary below, but its not necessary since they are equivalent
// on the registry
const targetVersion = yield normalizeVersionWithTagCheck('nx', args);
const targetPackage = !['latest', 'next'].includes(args) && (0, semver_1.lt)(targetVersion, '14.0.0-beta.0')
? '@nrwl/workspace'
: 'nx';
return {
targetPackage,
targetVersion,
};
}
else {
return {
targetPackage: args,
targetVersion: 'latest',
};
}
}
});
}
function parseMigrationsOptions(options) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (options.runMigrations === '') {
options.runMigrations = 'migrations.json';
}
if (!options.runMigrations) {
const [from, to] = yield Promise.all([
options.from
? versionOverrides(options.from, 'from')
: Promise.resolve({}),
options.to
? yield versionOverrides(options.to, 'to')
: Promise.resolve({}),
]);
const { targetPackage, targetVersion } = yield parseTargetPackageAndVersion(options['packageAndVersion']);
return {
type: 'generateMigrations',
targetPackage: normalizeSlashes(targetPackage),
targetVersion,
from,
to,
interactive: options.interactive,
excludeAppliedMigrations: options.excludeAppliedMigrations,
};
}
else {
return {
type: 'runMigrations',
runMigrations: options.runMigrations,
ifExists: options.ifExists,
};
}
});
}
exports.parseMigrationsOptions = parseMigrationsOptions;
function createInstalledPackageVersionsResolver(root) {
const cache = {};
function getInstalledPackageVersion(packageName, overrides) {
try {
if (overrides === null || overrides === void 0 ? void 0 : overrides[packageName]) {
return overrides[packageName];
}
if (!cache[packageName]) {
const { packageJson, path } = (0, package_json_1.readModulePackageJson)(packageName, (0, installation_directory_1.getNxRequirePaths)());
// old workspaces would have the temp installation of nx in the cache,
// so the resolved package is not the one we need
if (!path.startsWith(workspace_root_1.workspaceRoot)) {
throw new Error('Resolved a package outside the workspace root.');
}
cache[packageName] = packageJson.version;
}
return cache[packageName];
}
catch (_a) {
// Support migrating old workspaces without nx package
if (packageName === 'nx') {
cache[packageName] = getInstalledPackageVersion('@nrwl/workspace', overrides);
return cache[packageName];
}
return null;
}
}
return getInstalledPackageVersion;
}
// testing-fetch-start
function createFetcher() {
const migrationsCache = {};
const resolvedVersionCache = {};
function fetchMigrations(packageName, packageVersion, setCache) {
const cacheKey = packageName + '-' + packageVersion;
return Promise.resolve(resolvedVersionCache[cacheKey])
.then((cachedResolvedVersion) => {
if (cachedResolvedVersion) {
return cachedResolvedVersion;
}
resolvedVersionCache[cacheKey] = (0, package_manager_1.resolvePackageVersionUsingRegistry)(packageName, packageVersion);
return resolvedVersionCache[cacheKey];
})
.then((resolvedVersion) => {
if (resolvedVersion !== packageVersion &&
migrationsCache[`${packageName}-${resolvedVersion}`]) {
return migrationsCache[`${packageName}-${resolvedVersion}`];
}
setCache(packageName, resolvedVersion);
return getPackageMigrationsUsingRegistry(packageName, resolvedVersion);
})
.catch(() => {
logger_1.logger.info(`Fetching ${packageName}@${packageVersion}`);
return getPackageMigrationsUsingInstall(packageName, packageVersion);
});
}
return function nxMigrateFetcher(packageName, packageVersion) {
if (migrationsCache[`${packageName}-${packageVersion}`]) {
return migrationsCache[`${packageName}-${packageVersion}`];
}
let resolvedVersion = packageVersion;
let migrations;
function setCache(packageName, packageVersion) {
migrationsCache[packageName + '-' + packageVersion] = migrations;
}
migrations = fetchMigrations(packageName, packageVersion, setCache).then((result) => {
if (result.schematics) {
result.generators = result.schematics;
delete result.schematics;
}
resolvedVersion = result.version;
return result;
});
setCache(packageName, packageVersion);
return migrations;
};
}
// testing-fetch-end
function getPackageMigrationsUsingRegistry(packageName, packageVersion) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
// check if there are migrations in the packages by looking at the
// registry directly
const migrationsConfig = yield getPackageMigrationsConfigFromRegistry(packageName, packageVersion);
if (!migrationsConfig) {
return {
version: packageVersion,
};
}
if (!migrationsConfig.migrations) {
return {
version: packageVersion,
packageGroup: migrationsConfig.packageGroup,
};
}
logger_1.logger.info(`Fetching ${packageName}@${packageVersion}`);
// try to obtain the migrations from the registry directly
return yield downloadPackageMigrationsFromRegistry(packageName, packageVersion, migrationsConfig);
});
}
function getPackageMigrationsConfigFromRegistry(packageName, packageVersion) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const result = yield (0, package_manager_1.packageRegistryView)(packageName, packageVersion, 'nx-migrations ng-update --json');
if (!result) {
return null;
}
return (0, package_json_1.readNxMigrateConfig)(JSON.parse(result));
});
}
function downloadPackageMigrationsFromRegistry(packageName, packageVersion, { migrations: migrationsFilePath, packageGroup, }) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const { dir, cleanup } = (0, package_manager_1.createTempNpmDirectory)();
let result;
try {
const { tarballPath } = yield (0, package_manager_1.packageRegistryPack)(dir, packageName, packageVersion);
const migrations = yield (0, fileutils_1.extractFileFromTarball)((0, path_1.join)(dir, tarballPath), (0, path_1.join)('package', migrationsFilePath), (0, path_1.join)(dir, migrationsFilePath)).then((path) => (0, fileutils_1.readJsonFile)(path));
result = Object.assign(Object.assign({}, migrations), { packageGroup, version: packageVersion });
}
catch (_a) {
throw new Error(`Failed to find migrations file "${migrationsFilePath}" in package "${packageName}@${packageVersion}".`);
}
finally {
yield cleanup();
}
return result;
});
}
function getPackageMigrationsUsingInstall(packageName, packageVersion) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const { dir, cleanup } = (0, package_manager_1.createTempNpmDirectory)();
let result;
try {
const pmc = (0, package_manager_1.getPackageManagerCommand)((0, package_manager_1.detectPackageManager)(dir));
yield execAsync(`${pmc.add} ${packageName}@${packageVersion}`, {
cwd: dir,
});
const { migrations: migrationsFilePath, packageGroup, packageJson, } = readPackageMigrationConfig(packageName, dir);
let migrations = undefined;
if (migrationsFilePath) {
migrations = (0, fileutils_1.readJsonFile)(migrationsFilePath);
}
result = Object.assign(Object.assign({}, migrations), { packageGroup, version: packageJson.version });
}
finally {
yield cleanup();
}
return result;
});
}
function readPackageMigrationConfig(packageName, dir) {
const { path: packageJsonPath, packageJson: json } = (0, package_json_1.readModulePackageJson)(packageName, (0, installation_directory_1.getNxRequirePaths)(dir));
const config = (0, package_json_1.readNxMigrateConfig)(json);
if (!config) {
return { packageJson: json, migrations: null, packageGroup: [] };
}
try {
const migrationFile = require.resolve(config.migrations, {
paths: [(0, path_1.dirname)(packageJsonPath)],
});
return {
packageJson: json,
migrations: migrationFile,
packageGroup: config.packageGroup,
};
}
catch (_a) {
return {
packageJson: json,
migrations: null,
packageGroup: config.packageGroup,
};
}
}
function createMigrationsFile(root, migrations) {
(0, fileutils_1.writeJsonFile)((0, path_1.join)(root, 'migrations.json'), { migrations });
}
function updatePackageJson(root, updatedPackages) {
const packageJsonPath = (0, path_1.join)(root, 'package.json');
if (!(0, fs_1.existsSync)(packageJsonPath)) {
return;
}
const parseOptions = {};
const json = (0, fileutils_1.readJsonFile)(packageJsonPath, parseOptions);
Object.keys(updatedPackages).forEach((p) => {
var _a, _b, _c;
if ((_a = json.devDependencies) === null || _a === void 0 ? void 0 : _a[p]) {
json.devDependencies[p] = updatedPackages[p].version;
return;
}
if ((_b = json.dependencies) === null || _b === void 0 ? void 0 : _b[p]) {
json.dependencies[p] = updatedPackages[p].version;
return;
}
const dependencyType = updatedPackages[p].addToPackageJson;
if (typeof dependencyType === 'string') {
(_c = json[dependencyType]) !== null && _c !== void 0 ? _c : (json[dependencyType] = {});
json[dependencyType][p] = updatedPackages[p].version;
}
});
(0, fileutils_1.writeJsonFile)(packageJsonPath, json, {
appendNewLine: parseOptions.endsWithNewline,
});
}
function updateInstallationDetails(root, updatedPackages) {
var _a;
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const nxJsonPath = (0, path_1.join)(root, 'nx.json');
const parseOptions = {};
const nxJson = (0, fileutils_1.readJsonFile)(nxJsonPath, parseOptions);
if (!nxJson.installation) {
return;
}
const nxVersion = (_a = updatedPackages.nx) === null || _a === void 0 ? void 0 : _a.version;
if (nxVersion) {
nxJson.installation.version = nxVersion;
}
if (nxJson.installation.plugins) {
for (const dep in nxJson.installation.plugins) {
const update = updatedPackages[dep];
if (update) {
nxJson.installation.plugins[dep] = (0, semver_1.valid)(update.version)
? update.version
: yield (0, package_manager_1.resolvePackageVersionUsingRegistry)(dep, update.version);
}
}
}
(0, fileutils_1.writeJsonFile)(nxJsonPath, nxJson, {
appendNewLine: parseOptions.endsWithNewline,
});
});
}
function isMigratingToNewMajor(from, to) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
from = normalizeVersion(from);
to = ['latest', 'next'].includes(to) ? to : normalizeVersion(to);
if (!(0, semver_1.valid)(from)) {
from = yield (0, package_manager_1.resolvePackageVersionUsingRegistry)('nx', from);
}
if (!(0, semver_1.valid)(to)) {
to = yield (0, package_manager_1.resolvePackageVersionUsingRegistry)('nx', to);
}
return (0, semver_1.major)(from) < (0, semver_1.major)(to);
});
}
function readNxVersion(packageJson) {
var _a, _b, _c, _d, _e, _f, _g;
return ((_f = (_d = (_b = (_a = packageJson === null || packageJson === void 0 ? void 0 : packageJson.devDependencies) === null || _a === void 0 ? void 0 : _a['nx']) !== null && _b !== void 0 ? _b : (_c = packageJson === null || packageJson === void 0 ? void 0 : packageJson.dependencies) === null || _c === void 0 ? void 0 : _c['nx']) !== null && _d !== void 0 ? _d : (_e = packageJson === null || packageJson === void 0 ? void 0 : packageJson.devDependencies) === null || _e === void 0 ? void 0 : _e['@nrwl/workspace']) !== null && _f !== void 0 ? _f : (_g = packageJson === null || packageJson === void 0 ? void 0 : packageJson.dependencies) === null || _g === void 0 ? void 0 : _g['@nrwl/workspace']);
}
function generateMigrationsJsonAndUpdatePackageJson(root, opts) {
var _a;
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const pmc = (0, package_manager_1.getPackageManagerCommand)();
try {
const rootPkgJsonPath = (0, path_1.join)(root, 'package.json');
let originalPackageJson = (0, fs_1.existsSync)(rootPkgJsonPath)
? (0, fileutils_1.readJsonFile)(rootPkgJsonPath)
: null;
const originalNxInstallation = (0, configuration_1.readNxJson)().installation;
const from = (_a = originalNxInstallation === null || originalNxInstallation === void 0 ? void 0 : originalNxInstallation.version) !== null && _a !== void 0 ? _a : readNxVersion(originalPackageJson);
try {
if (['nx', '@nrwl/workspace'].includes(opts.targetPackage) &&
(yield isMigratingToNewMajor(from, opts.targetVersion)) &&
!(0, is_ci_1.isCI)() &&
!(0, nx_cloud_utils_1.isNxCloudUsed)()) {
const useCloud = yield (0, connect_1.connectToNxCloudCommand)(ab_testing_1.messages.getPromptMessage('nxCloudMigration'));
yield (0, ab_testing_1.recordStat)({
command: 'migrate',
nxVersion: versions_1.nxVersion,
useCloud,
meta: ab_testing_1.messages.codeOfSelectedPromptMessage('nxCloudMigration'),
});
originalPackageJson = (0, fileutils_1.readJsonFile)((0, path_1.join)(root, 'package.json'));
}
}
catch (_b) {
// The above code is to remind folks when updating to a new major and not currently using Nx cloud.
// If for some reason it fails, it shouldn't affect the overall migration process
}
logger_1.logger.info(`Fetching meta data about packages.`);
logger_1.logger.info(`It may take a few minutes.`);
const migrator = new Migrator({
packageJson: originalPackageJson,
nxInstallation: originalNxInstallation,
getInstalledPackageVersion: createInstalledPackageVersionsResolver(root),
fetch: createFetcher(),
from: opts.from,
to: opts.to,
interactive: opts.interactive && !(0, is_ci_1.isCI)(),
excludeAppliedMigrations: opts.excludeAppliedMigrations,
});
const { migrations, packageUpdates } = yield migrator.migrate(opts.targetPackage, opts.targetVersion);
updatePackageJson(root, packageUpdates);
yield updateInstallationDetails(root, packageUpdates);
if (migrations.length > 0) {
createMigrationsFile(root, [
...addSplitConfigurationMigrationIfAvailable(from, packageUpdates),
...migrations,
]);
}
output_1.output.success({
title: `The migrate command has run successfully.`,
bodyLines: [
`- package.json has been updated.`,
migrations.length > 0
? `- migrations.json has been generated.`
: `- There are no migrations to run, so migrations.json has not been created.`,
],
});
output_1.output.log({
title: 'Next steps:',
bodyLines: [
`- Make sure package.json changes make sense and then run '${pmc.install}',`,
...(migrations.length > 0
? [`- Run '${pmc.exec} nx migrate --run-migrations'`]
: []),
`- To learn more go to https://nx.dev/core-features/automate-updating-dependencies`,
...(showConnectToCloudMessage()
? [
`- You may run '${pmc.run('nx', 'connect-to-nx-cloud')}' to get faster builds, GitHub integration, and more. Check out https://nx.app`,
]
: []),
],
});
}
catch (e) {
output_1.output.error({
title: `The migrate command failed.`,
});
throw e;
}
});
}
function addSplitConfigurationMigrationIfAvailable(from, packageJson) {
if (!packageJson['@nrwl/workspace'])
return [];
if ((0, semver_1.gte)(packageJson['@nrwl/workspace'].version, '15.7.0-beta.0') &&
(0, semver_1.lt)(from, '15.7.0-beta.0')) {
return [
{
version: '15.7.0-beta.0',
description: 'Split global configuration files into individual project.json files. This migration has been added automatically to the beginning of your migration set to retroactively make them work with the new version of Nx.',
cli: 'nx',
implementation: './src/migrations/update-15-7-0/split-configuration-into-project-json-files',
package: '@nrwl/workspace',
name: '15-7-0-split-configuration-into-project-json-files',
},
];
}
else {
return [];
}
}
function showConnectToCloudMessage() {
try {
const nxJson = (0, fileutils_1.readJsonFile)('nx.json');
const defaultRunnerIsUsed = !nxJson.tasksRunnerOptions ||
Object.values(nxJson.tasksRunnerOptions).find((r) => r.runner == '@nrwl/workspace/tasks-runners/default' ||
r.runner == 'nx/tasks-runners/default');
return !!defaultRunnerIsUsed;
}
catch (_a) {
return false;
}
}
function runInstall() {
const pmCommands = (0, package_manager_1.getPackageManagerCommand)();
output_1.output.log({
title: `Running '${pmCommands.install}' to make sure necessary packages are installed`,
});
(0, child_process_1.execSync)(pmCommands.install, { stdio: [0, 1, 2] });
}
function executeMigrations(root, migrations, isVerbose, shouldCreateCommits, commitPrefix) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const depsBeforeMigrations = getStringifiedPackageJsonDeps(root);
const migrationsWithNoChanges = [];
let ngCliAdapter;
if (migrations.some((m) => m.cli !== 'nx')) {
ngCliAdapter = yield Promise.resolve().then(() => require('../adapter/ngcli-adapter'));
require('../adapter/compat');
}
for (const m of migrations) {
try {
if (m.cli === 'nx') {
const changes = yield runNxMigration(root, m.package, m.name);
if (changes.length < 1) {
migrationsWithNoChanges.push(m);
// If no changes are made, continue on without printing anything
continue;
}
logger_1.logger.info(`Ran ${m.name} from ${m.package}`);
logger_1.logger.info(` ${m.description}\n`);
(0, tree_1.printChanges)(changes, ' ');
}
else {
const { madeChanges, loggingQueue } = yield ngCliAdapter.runMigration(root, m.package, m.name, isVerbose);
if (!madeChanges) {
migrationsWithNoChanges.push(m);
// If no changes are made, continue on without printing anything
continue;
}
logger_1.logger.info(`Ran ${m.name} from ${m.package}`);
logger_1.logger.info(` ${m.description}\n`);
loggingQueue.forEach((log) => logger_1.logger.info(' ' + log));
}
if (shouldCreateCommits) {
const commitMessage = `${commitPrefix}${m.name}`;
try {
const committedSha = commitChanges(commitMessage);
if (committedSha) {
logger_1.logger.info(chalk.dim(`- Commit created for changes: ${committedSha}`));
}
else {
logger_1.logger.info(chalk.red(`- A commit could not be created/retrieved for an unknown reason`));
}
}
catch (e) {
logger_1.logger.info(chalk.red(`- ${e.message}`));
}
}
logger_1.logger.info(`---------------------------------------------------------`);
}
catch (e) {
output_1.output.error({
title: `Failed to run ${m.name} from ${m.package}. This workspace is NOT up to date!`,
});
throw e;
}
}
const depsAfterMigrations = getStringifiedPackageJsonDeps(root);
if (depsBeforeMigrations !== depsAfterMigrations) {
runInstall();
}
return migrationsWithNoChanges;
});
}
exports.executeMigrations = executeMigrations;
function runMigrations(root, opts, args, isVerbose, shouldCreateCommits = false, commitPrefix) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (!process.env.NX_MIGRATE_SKIP_INSTALL) {
runInstall();
}
if (!__dirname.startsWith(workspace_root_1.workspaceRoot)) {
// we are running from a temp installation with nx latest, switch to running
// from local installation
(0, child_process_2.runNxSync)(`migrate ${args.join(' ')}`, {
stdio: ['inherit', 'inherit', 'inherit'],
env: Object.assign(Object.assign({}, process.env), { NX_MIGRATE_SKIP_INSTALL: 'true', NX_MIGRATE_USE_LOCAL: 'true' }),
});
return;
}
const migrationsExists = (0, fileutils_1.fileExists)(opts.runMigrations);
if (opts.ifExists && !migrationsExists) {
output_1.output.log({
title: `Migrations file '${opts.runMigrations}' doesn't exist`,
});
return;
}
else if (!opts.ifExists && !migrationsExists) {
throw new Error(`File '${opts.runMigrations}' doesn't exist, can't run migrations. Use flag --if-exists to run migrations only if the file exists`);
}
output_1.output.log({
title: `Running migrations from '${opts.runMigrations}'` +
(shouldCreateCommits ? ', with each applied in a dedicated commit' : ''),
});
const migrations = (0, fileutils_1.readJsonFile)((0, path_1.join)(root, opts.runMigrations)).migrations;
const migrationsWithNoChanges = yield executeMigrations(root, migrations, isVerbose, shouldCreateCommits, commitPrefix);
if (migrationsWithNoChanges.length < migrations.length) {
output_1.output.success({
title: `Successfully finished running migrations from '${opts.runMigrations}'. This workspace is up to date!`,
});
}
else {
output_1.output.success({
title: `No changes were made from running '${opts.runMigrations}'. This workspace is up to date!`,
});
}
});
}
function getStringifiedPackageJsonDeps(root) {
try {
const { dependencies, devDependencies } = (0, fileutils_1.readJsonFile)((0, path_1.join)(root, 'package.json'));
return JSON.stringify([dependencies, devDependencies]);
}
catch (_a) {
// We don't really care if the .nx/installation property changes,
// whenever nxw is invoked it will handle the dep updates.
return '';
}
}
function commitChanges(commitMessage) {
try {
(0, child_process_1.execSync)('git add -A', { encoding: 'utf8', stdio: 'pipe' });
(0, child_process_1.execSync)('git commit --no-verify -F -', {
encoding: 'utf8',
stdio: 'pipe',
input: commitMessage,
});
}
catch (err) {
throw new Error(`Error committing changes:\n${err.stderr}`);
}
return getLatestCommitSha();
}
function getLatestCommitSha() {
try {
return (0, child_process_1.execSync)('git rev-parse HEAD', {
encoding: 'utf8',
stdio: 'pipe',
}).trim();
}
catch (_a) {
return null;
}
}
function runNxMigration(root, packageName, name) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
const collectionPath = readPackageMigrationConfig(packageName, root).migrations;
const collection = (0, fileutils_1.readJsonFile)(collectionPath);
const g = collection.generators || collection.schematics;
if (!g[name]) {
const source = collection.generators ? 'generators' : 'schematics';
throw new Error(`Unable to determine implementation path for "${collectionPath}:${name}" using collection.${source}`);
}
const implRelativePath = g[name].implementation || g[name].factory;
let implPath;
try {
implPath = require.resolve(implRelativePath, {
paths: [(0, path_1.dirname)(collectionPath)],
});
}
catch (e) {
// workaround for a bug in node 12
implPath = require.resolve(`${(0, path_1.dirname)(collectionPath)}/${implRelativePath}`);
}
const fn = require(implPath).default;
const host = new tree_1.FsTree(root, false);
yield fn(host, {});
host.lock();
const changes = host.listChanges();
(0, tree_1.flushChanges)(root, changes);
return changes;
});
}
function migrate(root, args, rawArgs) {
return tslib_1.__awaiter(this, void 0, void 0, function* () {
if (args['verbose']) {
process.env.NX_VERBOSE_LOGGING = 'true';
}
yield client_1.daemonClient.stop();
return (0, params_1.handleErrors)(process.env.NX_VERBOSE_LOGGING === 'true', () => tslib_1.__awaiter(this, void 0, void 0, function* () {
const opts = yield parseMigrationsOptions(args);
if (opts.type === 'generateMigrations') {
yield generateMigrationsJsonAndUpdatePackageJson(root, opts);
}
else {
yield runMigrations(root, opts, rawArgs, args['verbose'], args['createCommits'], args['commitPrefix']);
}
}));
});
}
exports.migrate = migrate;
//# sourceMappingURL=migrate.js.mapВыполнить команду
Для локальной разработки. Не используйте в интернете!