diff --git a/docs/shared/migration/adding-to-monorepo.md b/docs/shared/migration/adding-to-monorepo.md index 0b9c9c5cc2ed4..96092b1775fb6 100644 --- a/docs/shared/migration/adding-to-monorepo.md +++ b/docs/shared/migration/adding-to-monorepo.md @@ -148,7 +148,7 @@ Nx + Lerna: "devDependencies": { "lerna": "*", "@nrwl/workspace": "*", - "@nrwl/tao": "*" + "nx": "*" } } ``` diff --git a/docs/shared/migration/migration-angularjs.md b/docs/shared/migration/migration-angularjs.md index ade8ec1b0e54e..1dcbb88bb03f6 100644 --- a/docs/shared/migration/migration-angularjs.md +++ b/docs/shared/migration/migration-angularjs.md @@ -107,7 +107,6 @@ Your `package.json` should now look like this: "@nrwl/cli": "13.4.6", "@nrwl/eslint-plugin-nx": "13.4.6", "@nrwl/linter": "13.4.6", - "@nrwl/tao": "13.4.6", "@nrwl/workspace": "13.4.6", "@types/jasmine": "~3.5.0", "@types/jasminewd2": "~2.0.3", diff --git a/docs/shared/nx-core.md b/docs/shared/nx-core.md index 33354ef14bf92..3a7df8a73ef2a 100644 --- a/docs/shared/nx-core.md +++ b/docs/shared/nx-core.md @@ -32,8 +32,7 @@ package.json "scripts": {}, "private": true, "devDependencies": { - "@nrwl/cli": "12.8.0", - "@nrwl/tao": "12.8.0", + "nx": "12.8.0", "@nrwl/workspace": "12.8.0", "@types/node": "14.14.33", "typescript": "~4.3.5" diff --git a/e2e/add-nx-to-monorepo/src/add-nx-to-monorepo.test.ts b/e2e/add-nx-to-monorepo/src/add-nx-to-monorepo.test.ts index fb1009af06519..a24dee6776464 100644 --- a/e2e/add-nx-to-monorepo/src/add-nx-to-monorepo.test.ts +++ b/e2e/add-nx-to-monorepo/src/add-nx-to-monorepo.test.ts @@ -1,11 +1,10 @@ import { createNonNxProjectDirectory, - readProjectConfig, runCommand, tmpProjPath, updateFile, } from '@nrwl/e2e/utils'; -import { Workspaces } from '@nrwl/tao/src/shared/workspace'; +import { Workspaces } from 'nx/src/shared/workspace'; describe('add-nx-to-monorepo', () => { it('should not throw', () => { diff --git a/e2e/angular-core/src/ng-add.test.ts b/e2e/angular-core/src/ng-add.test.ts index b31a8cc289c90..a4c8e8e0b03c0 100644 --- a/e2e/angular-core/src/ng-add.test.ts +++ b/e2e/angular-core/src/ng-add.test.ts @@ -1,3 +1,5 @@ +import { PackageManager } from 'nx/src/shared/package-manager'; + process.env.SELECTED_CLI = 'angular'; import { @@ -13,7 +15,6 @@ import { uniq, updateFile, } from '@nrwl/e2e/utils'; -import { PackageManager } from '@nrwl/tao/src/shared/package-manager'; describe('convert Angular CLI workspace to an Nx workspace', () => { let project: string; diff --git a/e2e/cli/project.json b/e2e/cli/project.json index 02a8b9876b891..935525eadacb4 100644 --- a/e2e/cli/project.json +++ b/e2e/cli/project.json @@ -30,5 +30,5 @@ "outputs": ["coverage/e2e/cli"] } }, - "implicitDependencies": ["cli", "js"] + "implicitDependencies": ["js"] } diff --git a/e2e/cli/src/cli.test.ts b/e2e/cli/src/cli.test.ts index d26f37d8861f7..e95663b9adc62 100644 --- a/e2e/cli/src/cli.test.ts +++ b/e2e/cli/src/cli.test.ts @@ -15,7 +15,7 @@ import { describe('Cli', () => { beforeEach(() => newProject()); - it('vvvshould execute long running tasks', () => { + it('vvvshould execute long running tasks', async () => { const myapp = uniq('myapp'); runCLI(`generate @nrwl/web:app ${myapp}`); updateProjectConfig(myapp, (c) => { @@ -210,15 +210,13 @@ describe('migrate', () => { }) ); - updateFile( - './node_modules/@nrwl/tao/src/commands/migrate.js', - (content) => { - const start = content.indexOf('// testing-fetch-start'); - const end = content.indexOf('// testing-fetch-end'); - - const before = content.substring(0, start); - const after = content.substring(end); - const newFetch = ` + updateFile('./node_modules/nx/src/commands/migrate.js', (content) => { + const start = content.indexOf('// testing-fetch-start'); + const end = content.indexOf('// testing-fetch-end'); + + const before = content.substring(0, start); + const after = content.substring(end); + const newFetch = ` function createFetcher(logger) { return function fetch(packageName) { if (packageName === 'migrate-parent-package') { @@ -250,9 +248,8 @@ describe('migrate', () => { } `; - return `${before}${newFetch}${after}`; - } - ); + return `${before}${newFetch}${after}`; + }); runCLI( 'migrate migrate-parent-package@2.0.0 --from="migrate-parent-package@1.0.0"', diff --git a/e2e/utils/index.ts b/e2e/utils/index.ts index 3a496998d6fb4..5fe0e8b99f9ea 100644 --- a/e2e/utils/index.ts +++ b/e2e/utils/index.ts @@ -4,8 +4,6 @@ import { ProjectConfiguration, WorkspaceJsonConfiguration, } from '@nrwl/devkit'; -import { detectPackageManager } from '@nrwl/tao/src/shared/package-manager'; -import { Workspaces } from '@nrwl/tao/src/shared/workspace'; import { angularCliVersion } from '@nrwl/workspace/src/utils/versions'; import { ChildProcess, exec, execSync } from 'child_process'; import { @@ -29,6 +27,8 @@ import { promisify } from 'util'; import chalk = require('chalk'); import isCI = require('is-ci'); import treeKill = require('tree-kill'); +import { Workspaces } from '../../packages/nx/src/shared/workspace'; +import { detectPackageManager } from '../../packages/create-nx-workspace/bin/package-manager'; const kill = require('kill-port'); export const isWindows = require('is-windows'); diff --git a/packages/angular/src/builders/webpack-server/webpack-server.impl.ts b/packages/angular/src/builders/webpack-server/webpack-server.impl.ts index 3f3f7adeb90b6..1ae772c0dc436 100644 --- a/packages/angular/src/builders/webpack-server/webpack-server.impl.ts +++ b/packages/angular/src/builders/webpack-server/webpack-server.impl.ts @@ -5,7 +5,7 @@ import { } from '@angular-devkit/build-angular/src/builders/dev-server'; import { JsonObject } from '@angular-devkit/core'; import { joinPathFragments, parseTargetString } from '@nrwl/devkit'; -import { Workspaces } from '@nrwl/tao/src/shared/workspace'; +import { Workspaces } from 'nx/src/shared/workspace'; import { existsSync } from 'fs'; import { merge } from 'webpack-merge'; import { resolveCustomWebpackConfig } from '../utilities/webpack'; diff --git a/packages/angular/src/executors/utilities/tailwindcss.ts b/packages/angular/src/executors/utilities/tailwindcss.ts index cd712fa624d58..2562b9766920e 100644 --- a/packages/angular/src/executors/utilities/tailwindcss.ts +++ b/packages/angular/src/executors/utilities/tailwindcss.ts @@ -1,5 +1,5 @@ import { logger } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { existsSync } from 'fs'; import { join, relative } from 'path'; import * as postcssImport from 'postcss-import'; diff --git a/packages/angular/src/generators/library/library.spec.ts b/packages/angular/src/generators/library/library.spec.ts index 285d09e1d50b7..2e08cd3088d20 100644 --- a/packages/angular/src/generators/library/library.spec.ts +++ b/packages/angular/src/generators/library/library.spec.ts @@ -9,7 +9,7 @@ import { } from '@nrwl/devkit'; import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing'; import { Linter } from '@nrwl/linter'; -import { toNewFormat } from '@nrwl/tao/src/shared/workspace'; +import { toNewFormat } from 'nx/src/shared/workspace'; import { createApp } from '../../utils/nx-devkit/testing'; import { UnitTestRunner } from '../../utils/test-runners'; import { diff --git a/packages/angular/src/generators/move/lib/update-ng-package.ts b/packages/angular/src/generators/move/lib/update-ng-package.ts index a08232140aaa2..6b9486df1545a 100644 --- a/packages/angular/src/generators/move/lib/update-ng-package.ts +++ b/packages/angular/src/generators/move/lib/update-ng-package.ts @@ -1,5 +1,5 @@ import { readProjectConfiguration, Tree, updateJson } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { getNewProjectName } from '@nrwl/workspace/src/generators/move/lib/utils'; import { join, relative } from 'path'; import { Schema } from '../schema'; diff --git a/packages/angular/src/generators/storybook-migrate-stories-to-6-2/migrate-stories-to-6-2.spec.ts b/packages/angular/src/generators/storybook-migrate-stories-to-6-2/migrate-stories-to-6-2.spec.ts index f7132d3fd9eb3..956acf4740581 100644 --- a/packages/angular/src/generators/storybook-migrate-stories-to-6-2/migrate-stories-to-6-2.spec.ts +++ b/packages/angular/src/generators/storybook-migrate-stories-to-6-2/migrate-stories-to-6-2.spec.ts @@ -6,7 +6,7 @@ import { storybookVersion } from '@nrwl/storybook'; import { overrideCollectionResolutionForTesting, wrapAngularDevkitSchematic, -} from '@nrwl/tao/src/commands/ngcli-adapter'; +} from 'nx/src/commands/ngcli-adapter'; import { findNodes } from '@nrwl/workspace/src/utils/ast-utils'; import * as ts from 'typescript'; import { SyntaxKind } from 'typescript'; diff --git a/packages/angular/src/migrations/update-13-2-0/opt-out-testbed-teardown.spec.ts b/packages/angular/src/migrations/update-13-2-0/opt-out-testbed-teardown.spec.ts index 60331d4588d29..41c4d5bd6f457 100644 --- a/packages/angular/src/migrations/update-13-2-0/opt-out-testbed-teardown.spec.ts +++ b/packages/angular/src/migrations/update-13-2-0/opt-out-testbed-teardown.spec.ts @@ -7,7 +7,7 @@ describe('opt-out-testbed-teardown migration', () => { beforeEach(() => { tree = createTreeWithEmptyWorkspace(2); - jest.doMock('@nrwl/tao/src/utils/app-root', () => ({ appRootPath: '' })); + jest.doMock('nx/src/utils/app-root', () => ({ appRootPath: '' })); }); it('should warn when the jestConfig property is not configured', async () => { diff --git a/packages/angular/src/utils/mfe-webpack.ts b/packages/angular/src/utils/mfe-webpack.ts index 57a6ecdd1dfa2..cf0c7f9bf2fa5 100644 --- a/packages/angular/src/utils/mfe-webpack.ts +++ b/packages/angular/src/utils/mfe-webpack.ts @@ -1,7 +1,7 @@ import { readTsConfig } from '@nrwl/workspace'; import { existsSync, readFileSync } from 'fs'; import { NormalModuleReplacementPlugin } from 'webpack'; -import { appRootPath as rootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath as rootPath } from 'nx/src/utils/app-root'; import { normalizePath, joinPathFragments } from '@nrwl/devkit'; import { dirname } from 'path'; import { ParsedCommandLine } from 'typescript'; diff --git a/packages/cli/bin/nx.ts b/packages/cli/bin/nx.ts index b6ee9152ecf3c..c4a549e1a9e5c 100644 --- a/packages/cli/bin/nx.ts +++ b/packages/cli/bin/nx.ts @@ -1,68 +1,2 @@ #!/usr/bin/env node -import { findWorkspaceRoot } from '../lib/find-workspace-root'; -const workspace = findWorkspaceRoot(process.cwd()); -if (workspace && workspace.type === 'nx') { - require('v8-compile-cache'); -} -// polyfill rxjs observable to avoid issues with multiple version fo Observable installed in node_modules -// https://twitter.com/BenLesh/status/1192478226385428483?s=20 -if (!(Symbol as any).observable) - (Symbol as any).observable = Symbol('observable polyfill'); -import * as chalk from 'chalk'; -import { initLocal } from '../lib/init-local'; -import { output } from '../lib/output'; -import { detectPackageManager } from '@nrwl/tao/src/shared/package-manager'; - -if (!workspace) { - output.log({ - title: `The current directory isn't part of an Nx workspace.`, - bodyLines: [ - `To create a workspace run:`, - chalk.bold.white(`npx create-nx-workspace@latest `), - ], - }); - - output.note({ - title: `For more information please visit https://nx.dev/`, - }); - process.exit(1); -} - -// Make sure that a local copy of Nx exists in workspace -let localNx: string; -try { - localNx = require.resolve('@nrwl/cli/bin/nx.js', { - paths: [workspace.dir], - }); -} catch { - output.error({ - title: `Could not find Nx modules in this workspace.`, - bodyLines: [`Have you run ${chalk.bold.white(`npm/yarn install`)}?`], - }); - process.exit(1); -} - -if (localNx === require.resolve('@nrwl/cli/bin/nx.js')) { - initLocal(workspace); -} else { - const packageManager = detectPackageManager(); - if (packageManager === 'pnpm') { - const tip = - process.platform === 'win32' - ? 'doskey pnx=pnpm nx -- $*' - : `alias pnx="pnpm nx --"`; - output.warn({ - title: `Running global Nx CLI with PNPM may have issues.`, - bodyLines: [ - `Prefer to use "pnpm" (https://pnpm.io/cli/exec) to execute commands in this workspace.`, - `${chalk.reset.inverse.bold.cyan( - ' TIP ' - )} create a shortcut such as: ${chalk.bold.white(tip)}`, - ``, - ], - }); - } - - // Nx is being run from globally installed CLI - hand off to the local - require(localNx); -} +require('nx/bin/nx'); diff --git a/packages/cli/lib/decorate-cli.ts b/packages/cli/lib/decorate-cli.ts index 18fabe7876553..8eae01e58f1fa 100644 --- a/packages/cli/lib/decorate-cli.ts +++ b/packages/cli/lib/decorate-cli.ts @@ -1,16 +1 @@ -import { readFileSync, writeFileSync } from 'fs'; - -export function decorateCli() { - const path = 'node_modules/@angular/cli/lib/cli/index.js'; - const angularCLIInit = readFileSync(path, 'utf-8'); - const start = angularCLIInit.indexOf(`(options) {`) + 11; - - const newContent = `${angularCLIInit.substr(0, start)} - if (!process.env['NX_CLI_SET']) { - require('@nrwl/cli/bin/nx'); - return new Promise(function(res, rej) {}); - } - ${angularCLIInit.substring(start)} -`; - writeFileSync(path, newContent); -} +require('nx/src/cli/decorate-cli'); diff --git a/packages/cli/package.json b/packages/cli/package.json index 21af888f05f89..d6f01db183a85 100644 --- a/packages/cli/package.json +++ b/packages/cli/package.json @@ -28,10 +28,6 @@ }, "homepage": "https://nx.dev", "dependencies": { - "yargs-parser": "20.0.0", - "@nrwl/tao": "*", - "chalk": "4.1.0", - "enquirer": "~2.3.6", - "v8-compile-cache": "2.3.0" + "nx": "*" } } diff --git a/packages/create-nx-plugin/bin/create-nx-plugin.ts b/packages/create-nx-plugin/bin/create-nx-plugin.ts index 7bc4a70abba6c..6d5bb3809b66a 100644 --- a/packages/create-nx-plugin/bin/create-nx-plugin.ts +++ b/packages/create-nx-plugin/bin/create-nx-plugin.ts @@ -1,9 +1,9 @@ #!/usr/bin/env node // we can't import from '@nrwl/workspace' because it will require typescript -import { getPackageManagerCommand } from '@nrwl/tao/src/shared/package-manager'; -import type { NxJsonConfiguration } from '@nrwl/tao/src/shared/nx'; -import { readJsonFile, writeJsonFile } from '@nrwl/tao/src/utils/fileutils'; +import { getPackageManagerCommand } from 'nx/src/shared/package-manager'; +import type { NxJsonConfiguration } from 'nx/src/shared/nx'; +import { readJsonFile, writeJsonFile } from 'nx/src/utils/fileutils'; import { output } from '@nrwl/workspace/src/utilities/output'; import { execSync } from 'child_process'; import { removeSync } from 'fs-extra'; @@ -38,7 +38,7 @@ function createSandbox(packageManager: string) { writeJsonFile(path.join(tmpDir, 'package.json'), { dependencies: { '@nrwl/workspace': nxVersion, - '@nrwl/tao': cliVersion, + nx: cliVersion, typescript: tsVersion, prettier: prettierVersion, }, @@ -77,7 +77,7 @@ function createWorkspace( execSync( `${ pmc.exec - } tao ${command}/generators.json --nxWorkspaceRoot="${process.cwd()}"`, + } nx ${command}/generators.json --nxWorkspaceRoot="${process.cwd()}"`, { stdio: [0, 1, 2], cwd: tmpDir, diff --git a/packages/create-nx-workspace/bin/create-nx-workspace.ts b/packages/create-nx-workspace/bin/create-nx-workspace.ts index 7a14f90d595eb..3255148d876a0 100644 --- a/packages/create-nx-workspace/bin/create-nx-workspace.ts +++ b/packages/create-nx-workspace/bin/create-nx-workspace.ts @@ -481,7 +481,7 @@ async function createSandbox(packageManager: string) { JSON.stringify({ dependencies: { '@nrwl/workspace': nxVersion, - '@nrwl/tao': cliVersion, + nx: cliVersion, typescript: tsVersion, prettier: prettierVersion, }, @@ -540,8 +540,7 @@ async function createApp( nxWorkspaceRoot = `\\"${nxWorkspaceRoot.slice(1, -1)}\\"`; } } - const fullCommandWithoutWorkspaceRoot = `${pmc.exec} tao ${command}/generators.json --cli=${cli}`; - + const fullCommandWithoutWorkspaceRoot = `${pmc.exec} nx ${command}/generators.json --cli=${cli}`; let workspaceSetupSpinner = ora('Creating your workspace').start(); try { diff --git a/packages/devkit/index.ts b/packages/devkit/index.ts index a31bec3982877..f09064bdd67c1 100644 --- a/packages/devkit/index.ts +++ b/packages/devkit/index.ts @@ -12,7 +12,7 @@ /** * @category Tree */ -export type { Tree, FileChange } from '@nrwl/tao/src/shared/tree'; +export type { Tree, FileChange } from 'nx/src/shared/tree'; /** * @category Workspace @@ -29,17 +29,17 @@ export type { ExecutorContext, TaskGraphExecutor, Workspace, -} from '@nrwl/tao/src/shared/workspace'; +} from 'nx/src/shared/workspace'; export type { NxPlugin, ProjectTargetConfigurator, -} from '@nrwl/tao/src/shared/nx-plugin'; +} from 'nx/src/shared/nx-plugin'; /** * @category Workspace */ -export type { Task, TaskGraph } from '@nrwl/tao/src/shared/tasks'; +export type { Task, TaskGraph } from 'nx/src/shared/tasks'; /** * @category Workspace @@ -50,17 +50,17 @@ export type { NxJsonConfiguration, NxJsonProjectConfiguration, NxAffectedConfig, -} from '@nrwl/tao/src/shared/nx'; +} from 'nx/src/shared/nx'; /** * @category Logger */ -export { logger } from '@nrwl/tao/src/shared/logger'; +export { logger } from 'nx/src/shared/logger'; /** * @category Package Manager */ -export type { PackageManager } from '@nrwl/tao/src/shared/package-manager'; +export type { PackageManager } from 'nx/src/shared/package-manager'; /** * @category Package Manager @@ -69,16 +69,16 @@ export { getPackageManagerCommand, detectPackageManager, getPackageManagerVersion, -} from '@nrwl/tao/src/shared/package-manager'; +} from 'nx/src/shared/package-manager'; /** * @category Commands */ -export type { Target } from '@nrwl/tao/src/commands/run'; +export type { Target } from 'nx/src/commands/run'; /** * @category Commands */ -export { runExecutor } from '@nrwl/tao/src/commands/run'; +export { runExecutor } from 'nx/src/commands/run'; /** * @category Generators @@ -170,24 +170,17 @@ export { readJson, writeJson, updateJson } from './src/utils/json'; /** * @category Utils */ -export { - parseJson, - serializeJson, - stripJsonComments, -} from '@nrwl/tao/src/utils/json'; +export { parseJson, serializeJson, stripJsonComments } from 'nx/src/utils/json'; /** * @category Utils */ -export type { - JsonParseOptions, - JsonSerializeOptions, -} from '@nrwl/tao/src/utils/json'; +export type { JsonParseOptions, JsonSerializeOptions } from 'nx/src/utils/json'; /** * @category Utils */ -export { readJsonFile, writeJsonFile } from '@nrwl/tao/src/utils/fileutils'; +export { readJsonFile, writeJsonFile } from 'nx/src/utils/fileutils'; /** * @category Utils diff --git a/packages/devkit/ngcli-adapter.ts b/packages/devkit/ngcli-adapter.ts index bcb76dcf493cd..f80514a43996d 100644 --- a/packages/devkit/ngcli-adapter.ts +++ b/packages/devkit/ngcli-adapter.ts @@ -6,4 +6,4 @@ export { overrideCollectionResolutionForTesting, mockSchematicsForTesting, NxScopedHost, -} from '@nrwl/tao/src/commands/ngcli-adapter'; +} from 'nx/src/commands/ngcli-adapter'; diff --git a/packages/devkit/package.json b/packages/devkit/package.json index 3974ed1443fc5..e48dfd25efa0e 100644 --- a/packages/devkit/package.json +++ b/packages/devkit/package.json @@ -27,7 +27,7 @@ }, "homepage": "https://nx.dev", "dependencies": { - "@nrwl/tao": "*", + "nx": "*", "ejs": "^3.1.5", "ignore": "^5.0.4", "rxjs": "^6.5.4", diff --git a/packages/devkit/src/executors/parse-target-string.ts b/packages/devkit/src/executors/parse-target-string.ts index fa97fc76ad470..2695d580c0732 100644 --- a/packages/devkit/src/executors/parse-target-string.ts +++ b/packages/devkit/src/executors/parse-target-string.ts @@ -1,4 +1,4 @@ -import type { Target } from '@nrwl/tao/src/commands/run'; +import type { Target } from 'nx/src/commands/run'; /** * Parses a target string into {project, target, configuration} diff --git a/packages/devkit/src/executors/read-target-options.ts b/packages/devkit/src/executors/read-target-options.ts index 0710a9d99d7d3..df19243bae21c 100644 --- a/packages/devkit/src/executors/read-target-options.ts +++ b/packages/devkit/src/executors/read-target-options.ts @@ -1,7 +1,7 @@ -import type { Target } from '@nrwl/tao/src/commands/run'; -import type { ExecutorContext } from '@nrwl/tao/src/shared/workspace'; -import { Workspaces } from '@nrwl/tao/src/shared/workspace'; -import { combineOptionsForExecutor } from '@nrwl/tao/src/shared/params'; +import type { Target } from 'nx/src/commands/run'; +import type { ExecutorContext } from 'nx/src/shared/workspace'; +import { Workspaces } from 'nx/src/shared/workspace'; +import { combineOptionsForExecutor } from 'nx/src/shared/params'; /** * Reads and combines options for a given target. diff --git a/packages/devkit/src/generators/format-files.ts b/packages/devkit/src/generators/format-files.ts index 5808e42f34a88..6788a015d7bca 100644 --- a/packages/devkit/src/generators/format-files.ts +++ b/packages/devkit/src/generators/format-files.ts @@ -1,9 +1,9 @@ -import type { Tree } from '@nrwl/tao/src/shared/tree'; +import type { Tree } from 'nx/src/shared/tree'; import * as path from 'path'; import type * as Prettier from 'prettier'; import { getWorkspacePath } from '../utils/get-workspace-layout'; import { readJson, updateJson, writeJson } from '../utils/json'; -import { sortObjectByKeys } from '@nrwl/tao/src/utils/object-sort'; +import { sortObjectByKeys } from 'nx/src/utils/object-sort'; import { readWorkspaceConfiguration, updateWorkspaceConfiguration, diff --git a/packages/devkit/src/generators/generate-files.spec.ts b/packages/devkit/src/generators/generate-files.spec.ts index 5f07e12574fc9..1eaf23fe000f8 100644 --- a/packages/devkit/src/generators/generate-files.spec.ts +++ b/packages/devkit/src/generators/generate-files.spec.ts @@ -1,4 +1,4 @@ -import type { Tree } from '@nrwl/tao/src/shared/tree'; +import type { Tree } from 'nx/src/shared/tree'; import { createTree } from '../tests/create-tree'; import { generateFiles } from './generate-files'; import { join } from 'path'; diff --git a/packages/devkit/src/generators/generate-files.ts b/packages/devkit/src/generators/generate-files.ts index e29ba1f97641b..cc76c5f42d9af 100644 --- a/packages/devkit/src/generators/generate-files.ts +++ b/packages/devkit/src/generators/generate-files.ts @@ -1,7 +1,7 @@ import { readFileSync, readdirSync, statSync } from 'fs'; import * as path from 'path'; -import type { Tree } from '@nrwl/tao/src/shared/tree'; -import { logger } from '@nrwl/tao/src/shared/logger'; +import type { Tree } from 'nx/src/shared/tree'; +import { logger } from 'nx/src/shared/logger'; const binaryExts = new Set([ // // Image types originally from https://github.com/sindresorhus/image-type/blob/5541b6a/index.js diff --git a/packages/devkit/src/generators/project-configuration.spec.ts b/packages/devkit/src/generators/project-configuration.spec.ts index aadb1b90d1f27..01ec38ed7f80f 100644 --- a/packages/devkit/src/generators/project-configuration.spec.ts +++ b/packages/devkit/src/generators/project-configuration.spec.ts @@ -1,5 +1,5 @@ -import { Tree } from '@nrwl/tao/src/shared/tree'; -import { ProjectConfiguration } from '@nrwl/tao/src/shared/workspace'; +import { Tree } from 'nx/src/shared/tree'; +import { ProjectConfiguration } from 'nx/src/shared/workspace'; import { createTreeWithEmptyWorkspace } from '../tests/create-tree-with-empty-workspace'; import { readJson, updateJson } from '../utils/json'; diff --git a/packages/devkit/src/generators/project-configuration.ts b/packages/devkit/src/generators/project-configuration.ts index dc517ba38727b..6cf9a6419682c 100644 --- a/packages/devkit/src/generators/project-configuration.ts +++ b/packages/devkit/src/generators/project-configuration.ts @@ -7,7 +7,7 @@ import { reformattedWorkspaceJsonOrNull, toNewFormat, WorkspaceJsonConfiguration, -} from '@nrwl/tao/src/shared/workspace'; +} from 'nx/src/shared/workspace'; import { basename, dirname, relative } from 'path'; import { @@ -17,8 +17,8 @@ import { import { readJson, updateJson, writeJson } from '../utils/json'; import { joinPathFragments } from '../utils/path'; -import type { Tree } from '@nrwl/tao/src/shared/tree'; -import type { NxJsonConfiguration } from '@nrwl/tao/src/shared/nx'; +import type { Tree } from 'nx/src/shared/tree'; +import type { NxJsonConfiguration } from 'nx/src/shared/nx'; export type WorkspaceConfiguration = Omit< WorkspaceJsonConfiguration, @@ -385,8 +385,8 @@ export function readWorkspace(tree: Tree): WorkspaceJsonConfiguration { } /** - * This has to be separate from the inline functionality inside tao, - * as the functionality in tao does not use a Tree. Changes made during + * This has to be separate from the inline functionality inside nx, + * as the functionality in nx does not use a Tree. Changes made during * a generator would not be present during runtime execution. * @returns */ diff --git a/packages/devkit/src/generators/to-js.ts b/packages/devkit/src/generators/to-js.ts index 417d5f45e35a9..b12376800d05c 100644 --- a/packages/devkit/src/generators/to-js.ts +++ b/packages/devkit/src/generators/to-js.ts @@ -1,4 +1,4 @@ -import type { Tree } from '@nrwl/tao/src/shared/tree'; +import type { Tree } from 'nx/src/shared/tree'; /** * Rename and transpile any new typescript files created to javascript files diff --git a/packages/devkit/src/generators/update-ts-configs-to-js.ts b/packages/devkit/src/generators/update-ts-configs-to-js.ts index 40940eefa425e..6ff888d7301f2 100644 --- a/packages/devkit/src/generators/update-ts-configs-to-js.ts +++ b/packages/devkit/src/generators/update-ts-configs-to-js.ts @@ -1,4 +1,4 @@ -import type { Tree } from '@nrwl/tao/src/shared/tree'; +import type { Tree } from 'nx/src/shared/tree'; import { updateJson } from '../utils/json'; export function updateTsConfigsToJs( diff --git a/packages/devkit/src/generators/visit-not-ignored-files.spec.ts b/packages/devkit/src/generators/visit-not-ignored-files.spec.ts index c35ef4fd8b5cb..0fdaf4ea12111 100644 --- a/packages/devkit/src/generators/visit-not-ignored-files.spec.ts +++ b/packages/devkit/src/generators/visit-not-ignored-files.spec.ts @@ -1,5 +1,5 @@ import { createTree } from '../tests/create-tree'; -import type { Tree } from '@nrwl/tao/src/shared/tree'; +import type { Tree } from 'nx/src/shared/tree'; import { visitNotIgnoredFiles } from './visit-not-ignored-files'; describe('visitNotIgnoredFiles', () => { diff --git a/packages/devkit/src/generators/visit-not-ignored-files.ts b/packages/devkit/src/generators/visit-not-ignored-files.ts index f937a5773c517..2d7bf166f2799 100644 --- a/packages/devkit/src/generators/visit-not-ignored-files.ts +++ b/packages/devkit/src/generators/visit-not-ignored-files.ts @@ -1,4 +1,4 @@ -import type { Tree } from '@nrwl/tao/src/shared/tree'; +import type { Tree } from 'nx/src/shared/tree'; import ignore, { Ignore } from 'ignore'; import { join, relative, sep } from 'path'; diff --git a/packages/devkit/src/project-graph/interfaces.ts b/packages/devkit/src/project-graph/interfaces.ts index 7633c4a4c7fe4..aa56155eefae2 100644 --- a/packages/devkit/src/project-graph/interfaces.ts +++ b/packages/devkit/src/project-graph/interfaces.ts @@ -1 +1 @@ -export * from '@nrwl/tao/src/shared/project-graph'; +export * from 'nx/src/shared/project-graph'; diff --git a/packages/devkit/src/tasks/install-packages-task.ts b/packages/devkit/src/tasks/install-packages-task.ts index 164f4c0941dba..8945fb9b35cfa 100644 --- a/packages/devkit/src/tasks/install-packages-task.ts +++ b/packages/devkit/src/tasks/install-packages-task.ts @@ -1,11 +1,11 @@ -import type { Tree } from '@nrwl/tao/src/shared/tree'; +import type { Tree } from 'nx/src/shared/tree'; import { execSync } from 'child_process'; import { join } from 'path'; import { detectPackageManager, getPackageManagerCommand, -} from '@nrwl/tao/src/shared/package-manager'; -import type { PackageManager } from '@nrwl/tao/src/shared/package-manager'; +} from 'nx/src/shared/package-manager'; +import type { PackageManager } from 'nx/src/shared/package-manager'; import { joinPathFragments } from '../utils/path'; let storedPackageJsonValue: string; diff --git a/packages/devkit/src/tests/create-tree-with-empty-workspace.ts b/packages/devkit/src/tests/create-tree-with-empty-workspace.ts index f8ee6fb76bd2e..7ace5a1a65523 100644 --- a/packages/devkit/src/tests/create-tree-with-empty-workspace.ts +++ b/packages/devkit/src/tests/create-tree-with-empty-workspace.ts @@ -1,5 +1,5 @@ -import { FsTree } from '@nrwl/tao/src/shared/tree'; -import type { Tree } from '@nrwl/tao/src/shared/tree'; +import { FsTree } from 'nx/src/shared/tree'; +import type { Tree } from 'nx/src/shared/tree'; /** * Creates a host for testing. diff --git a/packages/devkit/src/tests/create-tree.ts b/packages/devkit/src/tests/create-tree.ts index d100a289635c9..9e8de78992356 100644 --- a/packages/devkit/src/tests/create-tree.ts +++ b/packages/devkit/src/tests/create-tree.ts @@ -1,5 +1,5 @@ -import { FsTree } from '@nrwl/tao/src/shared/tree'; -import type { Tree } from '@nrwl/tao/src/shared/tree'; +import { FsTree } from 'nx/src/shared/tree'; +import type { Tree } from 'nx/src/shared/tree'; /** * Creates a host for testing. diff --git a/packages/devkit/src/utils/convert-nx-executor.ts b/packages/devkit/src/utils/convert-nx-executor.ts index e61972252d441..266bb3a162734 100644 --- a/packages/devkit/src/utils/convert-nx-executor.ts +++ b/packages/devkit/src/utils/convert-nx-executor.ts @@ -1,6 +1,6 @@ import type { Observable } from 'rxjs'; -import type { Executor, ExecutorContext } from '@nrwl/tao/src/shared/workspace'; -import { Workspaces } from '@nrwl/tao/src/shared/workspace'; +import type { Executor, ExecutorContext } from 'nx/src/shared/workspace'; +import { Workspaces } from 'nx/src/shared/workspace'; /** * Convert an Nx Executor into an Angular Devkit Builder diff --git a/packages/devkit/src/utils/get-workspace-layout.ts b/packages/devkit/src/utils/get-workspace-layout.ts index 44456e803e24e..6ed46078aedc0 100644 --- a/packages/devkit/src/utils/get-workspace-layout.ts +++ b/packages/devkit/src/utils/get-workspace-layout.ts @@ -1,9 +1,9 @@ -import { RawWorkspaceJsonConfiguration } from '@nrwl/tao/src/shared/workspace'; +import { RawWorkspaceJsonConfiguration } from 'nx/src/shared/workspace'; import { readNxJson } from '../generators/project-configuration'; import { readJson } from './json'; -import type { Tree } from '@nrwl/tao/src/shared/tree'; +import type { Tree } from 'nx/src/shared/tree'; /** * Returns workspace defaults. It includes defaults folders for apps and libs, diff --git a/packages/devkit/src/utils/invoke-nx-generator.ts b/packages/devkit/src/utils/invoke-nx-generator.ts index b55ddb63cc232..48ee2027232ca 100644 --- a/packages/devkit/src/utils/invoke-nx-generator.ts +++ b/packages/devkit/src/utils/invoke-nx-generator.ts @@ -1,16 +1,12 @@ -import { logger, stripIndent } from '@nrwl/tao/src/shared/logger'; -import type { - FileChange, - Tree, - TreeWriteOptions, -} from '@nrwl/tao/src/shared/tree'; +import { logger, stripIndent } from 'nx/src/shared/logger'; +import type { FileChange, Tree, TreeWriteOptions } from 'nx/src/shared/tree'; import { Generator, GeneratorCallback, toNewFormat, toOldFormatOrNull, -} from '@nrwl/tao/src/shared/workspace'; -import { parseJson, serializeJson } from '@nrwl/tao/src/utils/json'; +} from 'nx/src/shared/workspace'; +import { parseJson, serializeJson } from 'nx/src/utils/json'; import { join, relative } from 'path'; class RunCallbackTask { diff --git a/packages/devkit/src/utils/json.ts b/packages/devkit/src/utils/json.ts index 1dab73fdae0a6..b5068bcfd6e0a 100644 --- a/packages/devkit/src/utils/json.ts +++ b/packages/devkit/src/utils/json.ts @@ -1,9 +1,6 @@ -import type { Tree } from '@nrwl/tao/src/shared/tree'; -import { parseJson, serializeJson } from '@nrwl/tao/src/utils/json'; -import type { - JsonParseOptions, - JsonSerializeOptions, -} from '@nrwl/tao/src/utils/json'; +import type { Tree } from 'nx/src/shared/tree'; +import { parseJson, serializeJson } from 'nx/src/utils/json'; +import type { JsonParseOptions, JsonSerializeOptions } from 'nx/src/utils/json'; /** * Reads a json file, removes all comments and parses JSON. diff --git a/packages/devkit/src/utils/move-dir.ts b/packages/devkit/src/utils/move-dir.ts index 1148bce3d7426..18ddfe32af6bb 100644 --- a/packages/devkit/src/utils/move-dir.ts +++ b/packages/devkit/src/utils/move-dir.ts @@ -1,4 +1,4 @@ -import { Tree } from '@nrwl/tao/src/shared/tree'; +import { Tree } from 'nx/src/shared/tree'; import { relative } from 'path'; import { visitNotIgnoredFiles } from '../generators/visit-not-ignored-files'; import { normalizePath } from './path'; diff --git a/packages/devkit/src/utils/package-json.spec.ts b/packages/devkit/src/utils/package-json.spec.ts index 2c7a606efa03c..fc9596ca776d6 100644 --- a/packages/devkit/src/utils/package-json.spec.ts +++ b/packages/devkit/src/utils/package-json.spec.ts @@ -1,4 +1,4 @@ -import type { Tree } from '@nrwl/tao/src/shared/tree'; +import type { Tree } from 'nx/src/shared/tree'; import { readJson, writeJson } from './json'; import { addDependenciesToPackageJson } from './package-json'; import { createTree } from '../tests/create-tree'; diff --git a/packages/devkit/src/utils/package-json.ts b/packages/devkit/src/utils/package-json.ts index 698c2db204e69..b0acc82b50871 100644 --- a/packages/devkit/src/utils/package-json.ts +++ b/packages/devkit/src/utils/package-json.ts @@ -1,7 +1,7 @@ import { readJson, updateJson } from './json'; import { installPackagesTask } from '../tasks/install-packages-task'; -import type { Tree } from '@nrwl/tao/src/shared/tree'; -import type { GeneratorCallback } from '@nrwl/tao/src/shared/workspace'; +import type { Tree } from 'nx/src/shared/tree'; +import type { GeneratorCallback } from 'nx/src/shared/workspace'; /** * Add Dependencies and Dev Dependencies to package.json diff --git a/packages/eslint-plugin-nx/src/configs/typescript.ts b/packages/eslint-plugin-nx/src/configs/typescript.ts index 7758f69f7040b..a5ffeced0a9ac 100644 --- a/packages/eslint-plugin-nx/src/configs/typescript.ts +++ b/packages/eslint-plugin-nx/src/configs/typescript.ts @@ -1,4 +1,4 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; /** * This configuration is intended to be applied to ALL .ts and .tsx files diff --git a/packages/eslint-plugin-nx/src/constants.ts b/packages/eslint-plugin-nx/src/constants.ts index c1c83d2918f0f..9dd323c2d3b68 100644 --- a/packages/eslint-plugin-nx/src/constants.ts +++ b/packages/eslint-plugin-nx/src/constants.ts @@ -1,4 +1,4 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { join } from 'path'; export const WORKSPACE_PLUGIN_DIR = join(appRootPath, 'tools/eslint-rules'); diff --git a/packages/eslint-plugin-nx/src/resolve-workspace-rules.ts b/packages/eslint-plugin-nx/src/resolve-workspace-rules.ts index a55330aa7fa09..4c508efde5fdc 100644 --- a/packages/eslint-plugin-nx/src/resolve-workspace-rules.ts +++ b/packages/eslint-plugin-nx/src/resolve-workspace-rules.ts @@ -1,7 +1,7 @@ import type { TSESLint } from '@typescript-eslint/experimental-utils'; import { existsSync } from 'fs'; import { WORKSPACE_PLUGIN_DIR, WORKSPACE_RULE_NAMESPACE } from './constants'; -import { registerTsProject } from '@nrwl/tao/src/utils/register'; +import { registerTsProject } from 'nx/src/utils/register'; type ESLintRules = Record>; diff --git a/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.spec.ts b/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.spec.ts index 4624fb50e59fb..1f74217eb2ae0 100644 --- a/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.spec.ts +++ b/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.spec.ts @@ -12,7 +12,7 @@ import enforceModuleBoundaries, { import { TargetProjectLocator } from '@nrwl/workspace/src/core/target-project-locator'; import { mapProjectGraphFiles } from '@nrwl/workspace/src/utils/runtime-lint-utils'; jest.mock('fs', () => require('memfs').fs); -jest.mock('@nrwl/tao/src/utils/app-root', () => ({ +jest.mock('nx/src/utils/app-root', () => ({ appRootPath: '/root', })); diff --git a/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.ts b/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.ts index f0dbb8a409b5d..1e3a63da26082 100644 --- a/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.ts +++ b/packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.ts @@ -1,4 +1,4 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { DepConstraint, findConstraintsFor, diff --git a/packages/eslint-plugin-nx/src/utils/ast-utils.ts b/packages/eslint-plugin-nx/src/utils/ast-utils.ts index 5c0ba7c1fc814..e31d771aa6603 100644 --- a/packages/eslint-plugin-nx/src/utils/ast-utils.ts +++ b/packages/eslint-plugin-nx/src/utils/ast-utils.ts @@ -5,7 +5,7 @@ import { existsSync, readFileSync } from 'fs'; import { dirname } from 'path'; import ts = require('typescript'); import { logger } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; function tryReadBaseJson() { try { diff --git a/packages/jest/migrations.json b/packages/jest/migrations.json index 50e7cf5b607ab..ddd9e1a8e55b7 100644 --- a/packages/jest/migrations.json +++ b/packages/jest/migrations.json @@ -1,65 +1,5 @@ { "schematics": { - "update-8.3.0": { - "version": "8.3.0", - "description": "Update jest.config.js", - "factory": "./src/migrations/update-8-3-0/update-8-3-0" - }, - "update-8.7.0": { - "version": "8.7.0", - "description": "Update Jest testPathPattern option", - "factory": "./src/migrations/update-8-7-0/update-8-7-0" - }, - "update-9.0.0": { - "version": "9.0.0-beta.1", - "description": "Upgrades jest-preset-angular to 8.0.0", - "factory": "./src/migrations/update-9-0-0/update-9-0-0" - }, - "update-9.0.1": { - "version": "9.0.1-beta.1", - "description": "Correctly sets passWithNoTests option", - "factory": "./src/migrations/update-9-0-1/update-9-0-1" - }, - "update-9.2.0": { - "version": "9.2.0-beta.3", - "description": "Update jest to v25", - "factory": "./src/migrations/update-9-2-0/update-9-2-0" - }, - "update-10.0.0": { - "version": "10.0.0-beta.2", - "description": "update jest configs to include setup env files", - "factory": "./src/migrations/update-10-0-0/update-jest-configs" - }, - "update-10.1.0": { - "version": "10.1.0-beta.4", - "description": "Update jest to v26", - "factory": "./src/migrations/update-10-1-0/update-10-1-0" - }, - "update-10.2.0": { - "version": "10.2.0", - "description": "Remove deprecated jest builder options", - "factory": "./src/migrations/update-10-2-0/update-10-2-0" - }, - "update-projects-property": { - "version": "10.3.0-beta.1", - "description": "Adds all jest projects into the root jest config", - "factory": "./src/migrations/update-10-3-0/update-projects-property" - }, - "update-ts-jest": { - "version": "10.3.0-beta.1", - "description": "Update ts-jest to v26.4", - "factory": "./src/migrations/update-10-3-0/update-ts-jest" - }, - "add-jest-extension": { - "version": "10.3.0-beta.1", - "description": "Adds a jest extension to the recommended extensions for vscode", - "factory": "./src/migrations/update-10-3-0/add-jest-extension" - }, - "update-ts-jest": { - "version": "10.3.1-beta.1", - "description": "Fix ts-jest migration", - "factory": "./src/migrations/update-10-3-0/update-ts-jest" - }, "update-jest-preset-angular-8-4-0": { "version": "12.1.0-beta.1", "cli": "nx", @@ -104,70 +44,6 @@ } }, "packageJsonUpdates": { - "9.0.0": { - "version": "9.0.0-beta.1", - "packages": { - "jest-preset-angular": { - "version": "8.0.0", - "alwaysAddToPackageJson": false - } - } - }, - "9.2.0": { - "version": "9.2.0-beta.3", - "packages": { - "jest": { - "version": "25.2.4", - "alwaysAddToPackageJson": false - }, - "ts-jest": { - "version": "25.2.1", - "alwaysAddToPackageJson": false - }, - "@types/jest": { - "version": "25.1.4", - "alwaysAddToPackageJson": false - }, - "jest-preset-angular": { - "version": "8.1.3", - "alwaysAddToPackageJson": false - } - } - }, - "10.1.0": { - "version": "10.1.0-beta.0", - "packages": { - "jest": { - "version": "26.2.2", - "alwaysAddToPackageJson": false - }, - "ts-jest": { - "version": "26.1.4", - "alwaysAddToPackageJson": false - }, - "@types/jest": { - "version": "26.0.8", - "alwaysAddToPackageJson": false - }, - "jest-preset-angular": { - "version": "8.2.1", - "alwaysAddToPackageJson": false - }, - "babel-jest": { - "version": "26.2.2", - "alwaysAddToPackageJson": false - } - } - }, - "10.3.0": { - "version": "10.3.0-beta.1", - "packages": { - "ts-jest": { - "version": "26.4.0", - "alwaysAddToPackageJson": false - } - } - }, "12.1.0": { "version": "12.1.0-beta.1", "packages": { diff --git a/packages/jest/src/executors/jest/jest.impl.spec.ts b/packages/jest/src/executors/jest/jest.impl.spec.ts index ae893f75c255d..3c4413ff9e70c 100644 --- a/packages/jest/src/executors/jest/jest.impl.spec.ts +++ b/packages/jest/src/executors/jest/jest.impl.spec.ts @@ -1,4 +1,4 @@ -import { ExecutorContext } from '@nrwl/tao/src/shared/workspace'; +import { ExecutorContext } from 'nx/src/shared/workspace'; let runCLI = jest.fn(); let readConfig = jest.fn(() => diff --git a/packages/jest/src/migrations/update-10-0-0/require-jest-config.ts b/packages/jest/src/migrations/update-10-0-0/require-jest-config.ts deleted file mode 100644 index b96f903f8ccdf..0000000000000 --- a/packages/jest/src/migrations/update-10-0-0/require-jest-config.ts +++ /dev/null @@ -1,4 +0,0 @@ -// export so that we can mock this return value -export function getJestObject(path: string) { - return require(path); -} diff --git a/packages/jest/src/migrations/update-10-0-0/update-jest-configs.spec.ts b/packages/jest/src/migrations/update-10-0-0/update-jest-configs.spec.ts deleted file mode 100644 index b54135cb325e6..0000000000000 --- a/packages/jest/src/migrations/update-10-0-0/update-jest-configs.spec.ts +++ /dev/null @@ -1,165 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; -import { createEmptyWorkspace } from '@nrwl/workspace/testing'; -import * as path from 'path'; -import { jestConfigObject } from '../utils/config/legacy/functions'; - -import { getJestObject } from './require-jest-config'; - -jest.mock('./require-jest-config'); -const getJestObjectMock = getJestObject as jest.Mock; - -const ngJestObject = { - name: 'test-jest', - preset: '../../jest.config.js', - coverageDirectory: '../../coverage/libs/test-jest', - globals: { - 'existing-global': 'test', - }, - snapshotSerializers: [ - 'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js', - 'jest-preset-angular/build/AngularSnapshotSerializer.js', - 'jest-preset-angular/build/HTMLCommentSerializer.js', - ], -}; - -const reactJestObject = { - name: 'my-react-app', - preset: '../../jest.config.js', - transform: { - '^(?!.*\\\\.(js|jsx|ts|tsx|css|json)$)': '@nrwl/react/plugins/jest', - '^.+\\\\.[tj]sx?$': ['babel-jest', { cwd: __dirname }], - }, - moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'html'], - coverageDirectory: '../../coverage/apps/my-react-app', -}; - -describe('update 10.0.0', () => { - let initialTree: Tree; - let schematicRunner: SchematicTestRunner; - const jestConfig = String.raw` - module.exports = ${JSON.stringify(ngJestObject)} - `; - - const jestConfigReact = String.raw` - module.exports = ${JSON.stringify(reactJestObject)} - `; - - beforeEach(() => { - getJestObjectMock.mockImplementation((path: string): any => { - if (path.includes('apps/products')) { - return ngJestObject; - } else if (path.includes('apps/cart')) { - return reactJestObject; - } - }); - - initialTree = createEmptyWorkspace(Tree.empty()); - - initialTree.create('apps/products/jest.config.js', jestConfig); - initialTree.create( - 'apps/products/src/test-setup.ts', - `import 'jest-preset-angular'` - ); - initialTree.create('apps/cart/jest.config.js', jestConfigReact); - initialTree.overwrite( - 'workspace.json', - JSON.stringify({ - version: 1, - projects: { - products: { - root: 'apps/products', - sourceRoot: 'apps/products/src', - architect: { - build: { - builder: '@angular-devkit/build-angular:browser', - }, - test: { - builder: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/products/jest.config.js', - tsConfig: 'apps/products/tsconfig.spec.json', - setupFile: 'apps/products/src/test-setup.ts', - passWithNoTests: true, - }, - }, - }, - }, - cart: { - root: 'apps/cart', - sourceRoot: 'apps/cart/src', - architect: { - build: { - builder: '@nrwl/web:webpack', - }, - test: { - builder: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/cart/jest.config.js', - passWithNoTests: true, - }, - }, - }, - }, - }, - }) - ); - schematicRunner = new SchematicTestRunner( - '@nrwl/jest', - path.join(__dirname, '../../../migrations.json') - ); - }); - - it('should remove setupFile and tsconfig in test architect from workspace.json', async () => { - const result = await schematicRunner - .runSchematicAsync('update-10.0.0', {}, initialTree) - .toPromise(); - - const updatedWorkspace = JSON.parse(result.readContent('workspace.json')); - expect(updatedWorkspace.projects.products.architect.test.options).toEqual({ - jestConfig: expect.anything(), - passWithNoTests: expect.anything(), - }); - expect(updatedWorkspace.projects.cart.architect.test.options).toEqual({ - jestConfig: expect.anything(), - passWithNoTests: expect.anything(), - }); - }); - - it('should update the jest.config files', async () => { - await schematicRunner - .runSchematicAsync('update-10.0.0', {}, initialTree) - .toPromise(); - - const jestObject = jestConfigObject( - initialTree, - 'apps/products/jest.config.js' - ); - - const angularSetupFiles = jestObject.setupFilesAfterEnv; - const angularGlobals = jestObject.globals; - - expect(angularSetupFiles).toEqual(['/src/test-setup.ts']); - expect(angularGlobals).toEqual({ - 'existing-global': 'test', - 'ts-jest': { - tsConfig: '/tsconfig.spec.json', - stringifyContentPathRegex: '\\.(html|svg)$', - astTransformers: [ - 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer', - ], - }, - }); - - const reactJestObject = jestConfigObject( - initialTree, - 'apps/cart/jest.config.js' - ); - - const reactSetupFiles = reactJestObject.setupFilesAfterEnv; - const reactGlobals = reactJestObject.globals; - expect(reactSetupFiles).toBeUndefined(); - expect(reactGlobals).toBeUndefined(); - }); -}); diff --git a/packages/jest/src/migrations/update-10-0-0/update-jest-configs.ts b/packages/jest/src/migrations/update-10-0-0/update-jest-configs.ts deleted file mode 100644 index 9c926a6e90fc0..0000000000000 --- a/packages/jest/src/migrations/update-10-0-0/update-jest-configs.ts +++ /dev/null @@ -1,173 +0,0 @@ -import { - chain, - Rule, - SchematicContext, - Tree, -} from '@angular-devkit/schematics'; -import { - formatFiles, - getWorkspace, - getWorkspacePath, - updateWorkspace, -} from '@nrwl/workspace'; -import { addPropertyToJestConfig } from '../utils/config/legacy/update-config'; -import { getJestObject } from './require-jest-config'; -import { appRootPath } from '@nrwl/workspace/src/utilities/app-root'; -import { serializeJson } from '@nrwl/devkit'; - -function checkJestPropertyObject(object: unknown): object is object { - return object !== null && object !== undefined; -} - -function modifyJestConfig( - host: Tree, - context: SchematicContext, - project: string, - setupFile: string, - jestConfig: string, - tsConfig: string, - isAngular: boolean -) { - let globalTsJest: any = { - tsConfig, - }; - - if (isAngular) { - globalTsJest = { - ...globalTsJest, - stringifyContentPathRegex: '\\.(html|svg)$', - astTransformers: [ - 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer', - ], - }; - } - - try { - const jestObject = getJestObject(`${appRootPath}/${jestConfig}`); - - if (setupFile !== '') { - // add set up env file - // setupFilesAfterEnv - const existingSetupFiles = jestObject.setupFilesAfterEnv; - - let setupFilesAfterEnv: string | string[] = [setupFile]; - if (Array.isArray(existingSetupFiles)) { - setupFilesAfterEnv = setupFile; - } - - addPropertyToJestConfig( - host, - jestConfig, - 'setupFilesAfterEnv', - setupFilesAfterEnv - ); - } - - // check if jest config has babel transform - const transformProperty = jestObject.transform; - - let hasBabelTransform = false; - if (transformProperty) { - for (const prop in transformProperty) { - const transformPropValue = transformProperty[prop]; - if (Array.isArray(transformPropValue)) { - hasBabelTransform = transformPropValue.some( - (value) => typeof value === 'string' && value.includes('babel') - ); - } else if (typeof transformPropValue === 'string') { - transformPropValue.includes('babel'); - } - } - } - - if (hasBabelTransform) { - return; - } - - // Add ts-jest configurations - const existingGlobals = jestObject.globals; - if (!existingGlobals) { - addPropertyToJestConfig(host, jestConfig, 'globals', { - 'ts-jest': globalTsJest, - }); - } else { - const existingGlobalTsJest = existingGlobals['ts-jest']; - if (!checkJestPropertyObject(existingGlobalTsJest)) { - addPropertyToJestConfig( - host, - jestConfig, - 'globals.ts-jest', - globalTsJest - ); - } - } - } catch { - context.logger.warn(` - Cannot update jest config for the ${project} project. - This is most likely caused because the jest config at ${jestConfig} it not in a expected configuration format (ie. module.exports = {}). - - Since this migration could not be ran on this project, please make sure to modify the Jest config file to have the following configured: - * setupFilesAfterEnv with: "${setupFile}" - * globals.ts-jest with: - "${serializeJson(globalTsJest)}" - `); - } -} - -function updateJestConfigForProjects() { - return async (host: Tree, context: SchematicContext) => { - const workspace = await getWorkspace(host, getWorkspacePath(host)); - - for (const [projectName, projectDefinition] of workspace.projects) { - for (const [, testTarget] of projectDefinition.targets) { - if (testTarget.builder !== '@nrwl/jest:jest') { - continue; - } - - const setupfile = testTarget.options?.setupFile; - const jestConfig = (testTarget.options?.jestConfig as string) ?? ''; - const tsConfig = (testTarget.options?.tsConfig as string) ?? ''; - const tsConfigWithRootDir = tsConfig.replace( - projectDefinition.root, - '' - ); - - let isAngular = false; - let setupFileWithRootDir = ''; - if (typeof setupfile === 'string') { - isAngular = host - .read(setupfile) - ?.toString() - .includes('jest-preset-angular'); - setupFileWithRootDir = setupfile.replace( - projectDefinition.root, - '' - ); - } - - modifyJestConfig( - host, - context, - projectName, - setupFileWithRootDir, - jestConfig, - tsConfigWithRootDir, - isAngular - ); - - const updatedOptions = { ...testTarget.options }; - delete updatedOptions.setupFile; - delete updatedOptions.tsConfig; - - testTarget.options = updatedOptions; - } - } - - return updateWorkspace(workspace); - }; -} - -export default function update(): Rule { - return chain([updateJestConfigForProjects(), formatFiles()]); -} diff --git a/packages/jest/src/migrations/update-10-1-0/update-10-1-0.ts b/packages/jest/src/migrations/update-10-1-0/update-10-1-0.ts deleted file mode 100644 index 9e18196a45cb1..0000000000000 --- a/packages/jest/src/migrations/update-10-1-0/update-10-1-0.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { chain, Rule } from '@angular-devkit/schematics'; -import { formatFiles, updatePackagesInPackageJson } from '@nrwl/workspace'; -import * as path from 'path'; - -export default function update(): Rule { - return chain([ - updatePackagesInPackageJson( - path.join(__dirname, '../../../', 'migrations.json'), - '10.1.0' - ), - formatFiles(), - ]); -} diff --git a/packages/jest/src/migrations/update-10-2-0/update-10-2-0.spec.ts b/packages/jest/src/migrations/update-10-2-0/update-10-2-0.spec.ts deleted file mode 100644 index 4cd1e740ecc49..0000000000000 --- a/packages/jest/src/migrations/update-10-2-0/update-10-2-0.spec.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; -import { createEmptyWorkspace } from '@nrwl/workspace/testing'; -import * as path from 'path'; - -describe('update 10.2.0', () => { - let initialTree: Tree; - let schematicRunner: SchematicTestRunner; - - beforeEach(() => { - initialTree = createEmptyWorkspace(Tree.empty()); - - initialTree.overwrite( - 'workspace.json', - JSON.stringify({ - version: 1, - projects: { - products: { - root: 'apps/products', - sourceRoot: 'apps/products/src', - architect: { - build: { - builder: '@angular-devkit/build-angular:browser', - }, - test: { - builder: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/products/jest.config.js', - tsConfig: 'apps/products/tsconfig.spec.json', - setupFile: 'apps/products/src/test-setup.ts', - passWithNoTests: true, - }, - }, - }, - }, - cart: { - root: 'apps/cart', - sourceRoot: 'apps/cart/src', - architect: { - build: { - builder: '@nrwl/web:build', - }, - test: { - builder: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/cart/jest.config.js', - passWithNoTests: true, - }, - }, - }, - }, - }, - }) - ); - schematicRunner = new SchematicTestRunner( - '@nrwl/jest', - path.join(__dirname, '../../../migrations.json') - ); - }); - - it('should remove setupFile and tsconfig in test architect from workspace.json', async () => { - const result = await schematicRunner - .runSchematicAsync('update-10.2.0', {}, initialTree) - .toPromise(); - - const updatedWorkspace = JSON.parse(result.readContent('workspace.json')); - expect(updatedWorkspace.projects.products.architect.test.options).toEqual({ - jestConfig: expect.anything(), - passWithNoTests: expect.anything(), - }); - expect(updatedWorkspace.projects.cart.architect.test.options).toEqual({ - jestConfig: expect.anything(), - passWithNoTests: expect.anything(), - }); - }); -}); diff --git a/packages/jest/src/migrations/update-10-2-0/update-10-2-0.ts b/packages/jest/src/migrations/update-10-2-0/update-10-2-0.ts deleted file mode 100644 index 7ba77212088a4..0000000000000 --- a/packages/jest/src/migrations/update-10-2-0/update-10-2-0.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { chain, Rule, Tree } from '@angular-devkit/schematics'; -import { - formatFiles, - getWorkspace, - getWorkspacePath, - updateWorkspace, -} from '@nrwl/workspace'; - -function removeDeprecatedJestBuilderOptions() { - return async (host: Tree) => { - const workspace = await getWorkspace(host, getWorkspacePath(host)); - - for (const [, projectDefinition] of workspace.projects) { - for (const [, testTarget] of projectDefinition.targets) { - if (testTarget.builder !== '@nrwl/jest:jest') { - continue; - } - - const updatedOptions = { ...testTarget.options }; - delete updatedOptions.setupFile; - delete updatedOptions.tsConfig; - - testTarget.options = updatedOptions; - } - } - - return updateWorkspace(workspace); - }; -} - -export default function update(): Rule { - return chain([removeDeprecatedJestBuilderOptions(), formatFiles()]); -} diff --git a/packages/jest/src/migrations/update-10-3-0/add-jest-extension.spec.ts b/packages/jest/src/migrations/update-10-3-0/add-jest-extension.spec.ts deleted file mode 100644 index 23adee0e08d55..0000000000000 --- a/packages/jest/src/migrations/update-10-3-0/add-jest-extension.spec.ts +++ /dev/null @@ -1,31 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { callRule, runMigration } from '../../utils/testing'; -import { readJsonInTree, updateJsonInTree } from '@nrwl/workspace'; -import { createEmptyWorkspace } from '@nrwl/workspace/testing'; - -describe('add VsCode extensions file', () => { - let tree: Tree; - - beforeEach(async () => { - tree = createEmptyWorkspace(Tree.empty()); - tree = await callRule( - updateJsonInTree('.vscode/extensions.json', () => ({ - recommendations: ['alreadyhere.something'], - })), - tree - ); - }); - - it('add a jest extension', async () => { - const result = await runMigration('add-jest-extension', {}, tree); - const extensions = readJsonInTree(result, '.vscode/extensions.json'); - expect(extensions).toMatchInlineSnapshot(` - Object { - "recommendations": Array [ - "alreadyhere.something", - "firsttris.vscode-jest-runner", - ], - } - `); - }); -}); diff --git a/packages/jest/src/migrations/update-10-3-0/add-jest-extension.ts b/packages/jest/src/migrations/update-10-3-0/add-jest-extension.ts deleted file mode 100644 index e84d2a9791692..0000000000000 --- a/packages/jest/src/migrations/update-10-3-0/add-jest-extension.ts +++ /dev/null @@ -1,19 +0,0 @@ -import { Rule, Tree } from '@angular-devkit/schematics'; -import { updateJsonInTree } from '@nrwl/workspace'; - -export default function (): Rule { - return (host: Tree) => { - if (!host.exists('.vscode/extensions.json')) { - return; - } - - return updateJsonInTree('.vscode/extensions.json', (json) => { - json.recommendations = json.recommendations || []; - const extension = 'firsttris.vscode-jest-runner'; - if (!json.recommendations.includes(extension)) { - json.recommendations.push(extension); - } - return json; - }); - }; -} diff --git a/packages/jest/src/migrations/update-10-3-0/update-projects-property.spec.ts b/packages/jest/src/migrations/update-10-3-0/update-projects-property.spec.ts deleted file mode 100644 index 80e43e98e86b3..0000000000000 --- a/packages/jest/src/migrations/update-10-3-0/update-projects-property.spec.ts +++ /dev/null @@ -1,159 +0,0 @@ -import { tags } from '@angular-devkit/core'; -import { Tree } from '@angular-devkit/schematics'; -import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; -import { createEmptyWorkspace } from '@nrwl/workspace/testing'; -import * as path from 'path'; - -describe('update projects property', () => { - let initialTree: Tree; - let schematicRunner: SchematicTestRunner; - - beforeEach(() => { - initialTree = createEmptyWorkspace(Tree.empty()); - - initialTree.create( - 'jest.config.js', - tags.stripIndents` - module.exports = { - testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'], - transform: { - '^.+\\\\.(ts|js|html)$': 'ts-jest', - }, - maxWorkers: 2, - }; - ` - ); - - initialTree.create( - 'apps/products/jest.config.js', - tags.stripIndents` - module.exports = { - name: 'products', - preset: '../../jest.config.js', - coverageDirectory: '../../coverage/apps/products', - snapshotSerializers: [ - 'jest-preset-angular/build/AngularSnapshotSerializer.js', - 'jest-preset-angular/build/HTMLCommentSerializer.js' - ], - setupFilesAfterEnv: ['/src/test-setup.ts'], - globals: { - 'ts-jest': { - tsConfig: '/tsconfig.spec.json', - stringifyContentPathRegex: '\\.(html|svg)$', - astTransformers: [ - 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer' - ] - } - } - }; - ` - ); - - initialTree.overwrite( - 'workspace.json', - JSON.stringify({ - version: 1, - projects: { - products: { - root: 'apps/products', - sourceRoot: 'apps/products/src', - architect: { - build: { - builder: '@angular-devkit/build-angular:browser', - }, - test: { - builder: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/products/jest.config.js', - tsConfig: 'apps/products/tsconfig.spec.json', - setupFile: 'apps/products/src/test-setup.ts', - passWithNoTests: true, - }, - }, - }, - }, - cart: { - root: 'apps/cart', - sourceRoot: 'apps/cart/src', - architect: { - build: { - builder: '@nrwl/web:build', - }, - test: { - builder: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/cart/jest.config.js', - passWithNoTests: true, - }, - }, - }, - }, - basket: { - root: 'apps/basket', - sourceRoot: 'apps/basket/src', - architect: { - build: { - builder: '@nrwl/web:build', - }, - }, - }, - }, - }) - ); - schematicRunner = new SchematicTestRunner( - '@nrwl/jest', - path.join(__dirname, '../../../migrations.json') - ); - }); - - it('should remove setupFile and tsconfig in test architect from workspace.json', async () => { - const result = await schematicRunner - .runSchematicAsync('update-projects-property', {}, initialTree) - .toPromise(); - - const updatedJestConfig = result.readContent('jest.config.js'); - expect(tags.stripIndents`${updatedJestConfig}`).toEqual(tags.stripIndents` - module.exports = { - projects: ['/apps/products', '/apps/cart'], - }; - `); - - const jestPreset = result.readContent('jest.preset.js'); - expect(tags.stripIndents`${jestPreset}`).toEqual(tags.stripIndents` - const nxPreset = require('@nrwl/jest/preset'); - module.exports = { - ...nxPreset, - testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'], - transform: { - '^.+\\\\.(ts|js|html)$': 'ts-jest', - }, - maxWorkers: 2, - }; - `); - - const projectConfig = result.readContent('apps/products/jest.config.js'); - expect(tags.stripIndents`${projectConfig}`).toEqual(tags.stripIndents` - module.exports = { - preset: '../../jest.preset.js', - coverageDirectory: '../../coverage/apps/products', - snapshotSerializers: [ - 'jest-preset-angular/build/AngularSnapshotSerializer.js', - 'jest-preset-angular/build/HTMLCommentSerializer.js', - ], - setupFilesAfterEnv: ['/src/test-setup.ts'], - globals: { - 'ts-jest': { - tsConfig: '/tsconfig.spec.json', - stringifyContentPathRegex: '\\.(html|svg)$', - astTransformers: [ - 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer', - ], - }, - }, - displayName: 'products', - }; - `); - }); -}); diff --git a/packages/jest/src/migrations/update-10-3-0/update-projects-property.ts b/packages/jest/src/migrations/update-10-3-0/update-projects-property.ts deleted file mode 100644 index d521dab37d152..0000000000000 --- a/packages/jest/src/migrations/update-10-3-0/update-projects-property.ts +++ /dev/null @@ -1,105 +0,0 @@ -import { - chain, - Rule, - SchematicContext, - Tree, -} from '@angular-devkit/schematics'; -import { - formatFiles, - getWorkspace, - insert, - InsertChange, -} from '@nrwl/workspace'; -import { - addPropertyToJestConfig, - removePropertyFromJestConfig, -} from '../utils/config/legacy/update-config'; -import { jestConfigObjectAst } from '../utils/config/legacy/functions'; -import { offsetFromRoot, serializeJson } from '@nrwl/devkit'; - -function updateRootJestConfig(): Rule { - return async (host: Tree, context: SchematicContext) => { - const workspace = await getWorkspace(host); - - const rootDirs = []; - for (const [projectName, project] of workspace.projects) { - for (const [, target] of project.targets) { - if (target.builder !== '@nrwl/jest:jest') { - continue; - } - - rootDirs.push(`/${project.root}`); - - try { - addPropertyToJestConfig( - host, - target.options.jestConfig as string, - 'preset', - `${offsetFromRoot(project.root)}jest.preset.js` - ); - addPropertyToJestConfig( - host, - target.options.jestConfig as string, - 'displayName', - projectName - ); - removePropertyFromJestConfig( - host, - target.options.jestConfig as string, - 'name' - ); - } catch { - context.logger.error( - `Unable to update the jest preset for project ${projectName}. Please manually add "@nrwl/jest/preset" as the preset.` - ); - } - } - } - - if (rootDirs.length == 0) { - return; - } else { - try { - context.logger.info(` -The root jest.config.js file will be updated to include all references to each individual project's jest config. -A new jest.preset.js file will be created that would have your existing configuration. All projects will now have this preset. - `); - - let existingRootConfig = host.read('jest.config.js').toString('utf-8'); - - existingRootConfig = `const nxPreset = require('@nrwl/jest/preset'); -${existingRootConfig}`; - - const presetPath = 'jest.preset.js'; - - host.create(presetPath, existingRootConfig); - const configObject = jestConfigObjectAst(host, presetPath); - insert(host, presetPath, [ - new InsertChange( - presetPath, - configObject.getStart() + 1, - '\n...nxPreset,' - ), - ]); - - host.overwrite( - 'jest.config.js', - ` - module.exports = { - projects: ${serializeJson(rootDirs)} - } - ` - ); - } catch { - context.logger.error(` -Unable to update the root jest.config.js with projects. Please add the "projects" property to the exported jest config with the following: -${serializeJson(rootDirs)} - `); - } - } - }; -} - -export default function update(): Rule { - return chain([updateRootJestConfig(), formatFiles()]); -} diff --git a/packages/jest/src/migrations/update-10-3-0/update-ts-jest.spec.ts b/packages/jest/src/migrations/update-10-3-0/update-ts-jest.spec.ts deleted file mode 100644 index 04a8c6863a482..0000000000000 --- a/packages/jest/src/migrations/update-10-3-0/update-ts-jest.spec.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; -import { createEmptyWorkspace } from '@nrwl/workspace/testing'; -import * as path from 'path'; -import { jestConfigObject } from '../utils/config/legacy/functions'; -import { getJestObject } from '../update-10-0-0/require-jest-config'; - -jest.mock('../update-10-0-0/require-jest-config'); -const getJestObjectMock = getJestObject as jest.Mock; - -const jestObject = { - name: 'test-jest', - preset: '../../jest.config.js', - coverageDirectory: '../../coverage/libs/test-jest', - globals: { - 'existing-global': 'test', - 'ts-jest': { - astTransformers: [ - 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer', - ], - }, - }, - snapshotSerializers: [ - 'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js', - 'jest-preset-angular/build/AngularSnapshotSerializer.js', - 'jest-preset-angular/build/HTMLCommentSerializer.js', - ], -}; - -describe('update ts-jest', () => { - let initialTree: Tree; - let schematicRunner: SchematicTestRunner; - const jestConfig = String.raw` - module.exports = ${JSON.stringify(jestObject, null, 2)} - `; - - beforeEach(() => { - getJestObjectMock.mockImplementation(() => jestObject as any); - - initialTree = createEmptyWorkspace(Tree.empty()); - - initialTree.create('apps/products/jest.config.js', jestConfig); - initialTree.create( - 'apps/products/src/test-setup.ts', - `import 'jest-preset-angular'` - ); - initialTree.overwrite( - 'workspace.json', - JSON.stringify({ - version: 1, - projects: { - products: { - root: 'apps/products', - sourceRoot: 'apps/products/src', - architect: { - build: { - builder: '@angular-devkit/build-angular:browser', - }, - test: { - builder: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/products/jest.config.js', - tsConfig: 'apps/products/tsconfig.spec.json', - setupFile: 'apps/products/src/test-setup.ts', - passWithNoTests: true, - }, - }, - }, - }, - }, - }) - ); - schematicRunner = new SchematicTestRunner( - '@nrwl/jest', - path.join(__dirname, '../../../migrations.json') - ); - }); - - it('should update the jest.config files', async () => { - const result = await schematicRunner - .runSchematicAsync('update-ts-jest', {}, initialTree) - .toPromise(); - - const jestObject = jestConfigObject(result, 'apps/products/jest.config.js'); - - expect((jestObject.globals['ts-jest'] as any).astTransformers).toEqual({ - before: [ - 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer', - ], - }); - }); -}); diff --git a/packages/jest/src/migrations/update-10-3-0/update-ts-jest.ts b/packages/jest/src/migrations/update-10-3-0/update-ts-jest.ts deleted file mode 100644 index 78d332ae08039..0000000000000 --- a/packages/jest/src/migrations/update-10-3-0/update-ts-jest.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { - chain, - Rule, - SchematicContext, - Tree, -} from '@angular-devkit/schematics'; -import { - formatFiles, - getWorkspace, - updatePackagesInPackageJson, -} from '@nrwl/workspace'; -import { join } from 'path'; -import { - addPropertyToJestConfig, - removePropertyFromJestConfig, -} from '../utils/config/legacy/update-config'; -import { getJestObject } from '../update-10-0-0/require-jest-config'; -import { stripIndents } from '@angular-devkit/core/src/utils/literals'; -import { appRootPath } from '@nrwl/workspace/src/utilities/app-root'; - -function updateAstTransformers(): Rule { - return async (host: Tree, context: SchematicContext) => { - const workspace = await getWorkspace(host); - - for (const [projectName, project] of workspace.projects) { - for (const [, target] of project.targets) { - if (target.builder !== '@nrwl/jest:jest') { - continue; - } - - const config = getJestObject( - join(appRootPath, target.options.jestConfig as string) - ); - - if ( - !config.globals?.['ts-jest']?.astTransformers || - !Array.isArray(config.globals?.['ts-jest']?.astTransformers) - ) { - continue; - } - - try { - removePropertyFromJestConfig( - host, - target.options.jestConfig as string, - 'globals.ts-jest.astTransformers' - ); - addPropertyToJestConfig( - host, - target.options.jestConfig as string, - 'globals.ts-jest.astTransformers', - { - before: config.globals['ts-jest'].astTransformers, - } - ); - } catch { - context.logger.error( - stripIndents`Unable to update the AST transformers for project ${projectName}. - Please define your custom AST transformers in a form of an object. - More information you can check online documentation https://kulshekhar.github.io/ts-jest/user/config/astTransformers` - ); - } - } - } - }; -} - -export default function update(): Rule { - return chain([ - updatePackagesInPackageJson( - join(__dirname, '../../../migrations.json'), - '10.3.0' - ), - updateAstTransformers(), - formatFiles(), - ]); -} diff --git a/packages/jest/src/migrations/update-12-1-2/update-jest-preset-angular.spec.ts b/packages/jest/src/migrations/update-12-1-2/update-jest-preset-angular.spec.ts deleted file mode 100644 index 52bc9a58acbf2..0000000000000 --- a/packages/jest/src/migrations/update-12-1-2/update-jest-preset-angular.spec.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { addProjectConfiguration, Tree } from '@nrwl/devkit'; -import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing'; - -import update from './update-jest-preset-angular'; - -import { getJestObject } from '../update-10-0-0/require-jest-config'; -import { jestConfigObject } from '../../utils/config/functions'; - -jest.mock('../update-10-0-0/require-jest-config'); -const getJestObjectMock = getJestObject as jest.Mock; - -const jestObject = { - snapshotSerializers: [ - 'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js', - 'jest-preset-angular/build/AngularSnapshotSerializer.js', - 'jest-preset-angular/build/HTMLCommentSerializer.js', - ], -}; - -describe('update 12.1.2', () => { - let tree: Tree; - const jestConfig = String.raw` - module.exports = ${JSON.stringify(jestObject, null, 2)} - `; - - beforeEach(() => { - getJestObjectMock.mockImplementation((path: string): any => { - if (path.includes('apps/products')) { - return jestObject; - } - }); - - tree = createTreeWithEmptyWorkspace(); - - tree.write('apps/products/jest.config.js', jestConfig); - tree.write( - 'apps/products/src/test-setup.ts', - `import 'jest-preset-angular';` - ); - addProjectConfiguration(tree, 'products', { - root: 'apps/products', - sourceRoot: 'apps/products/src', - targets: { - build: { - executor: '@angular-devkit/build-angular:browser', - }, - test: { - executor: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/products/jest.config.js', - passWithNoTests: true, - }, - }, - }, - }); - }); - - it('should update the jest.config files', async () => { - await update(tree); - - const jestObject = jestConfigObject(tree, 'apps/products/jest.config.js'); - - expect(jestObject.snapshotSerializers).toEqual([ - 'jest-preset-angular/build/serializers/no-ng-attributes', - 'jest-preset-angular/build/serializers/ng-snapshot', - 'jest-preset-angular/build/serializers/html-comment', - ]); - }); - - it('should update the test-setup files', async () => { - await update(tree); - - const testSetup = tree - .read('apps/products/src/test-setup.ts') - .toString('utf-8') - .trim(); - - expect(testSetup).toEqual(`import 'jest-preset-angular/setup-jest';`); - }); -}); diff --git a/packages/jest/src/migrations/update-12-1-2/update-jest-preset-angular.ts b/packages/jest/src/migrations/update-12-1-2/update-jest-preset-angular.ts index 716d472d4d8d7..6bfdaaa6102df 100644 --- a/packages/jest/src/migrations/update-12-1-2/update-jest-preset-angular.ts +++ b/packages/jest/src/migrations/update-12-1-2/update-jest-preset-angular.ts @@ -7,7 +7,6 @@ import { } from '@nrwl/devkit'; import { join } from 'path'; -import { getJestObject } from '../update-10-0-0/require-jest-config'; import { addPropertyToJestConfig, removePropertyFromJestConfig, @@ -20,9 +19,7 @@ function updateJestConfig(tree: Tree) { tree, '@nrwl/jest:jest', (options, projectName) => { - const config = getJestObject( - join(tree.root, options.jestConfig as string) - ); + const config = require(join(tree.root, options.jestConfig as string)); // migrate serializers if ( diff --git a/packages/jest/src/migrations/update-12-1-2/update-ts-jest.spec.ts b/packages/jest/src/migrations/update-12-1-2/update-ts-jest.spec.ts deleted file mode 100644 index 1ab457c5cfdde..0000000000000 --- a/packages/jest/src/migrations/update-12-1-2/update-ts-jest.spec.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { addProjectConfiguration, Tree } from '@nrwl/devkit'; -import { getJestObject } from '../update-10-0-0/require-jest-config'; -import { jestConfigObject } from '../../utils/config/functions'; -import update from './update-ts-jest'; -import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing'; - -jest.mock('../update-10-0-0/require-jest-config'); -const getJestObjectMock = getJestObject as jest.Mock; - -const jestObject = { - globals: { 'ts-jest': { tsConfig: '/tsconfig.spec.json' } }, -}; - -describe('update 12.1.2', () => { - let tree: Tree; - const jestConfig = String.raw` - module.exports = ${JSON.stringify(jestObject, null, 2)} - `; - - beforeEach(() => { - getJestObjectMock.mockImplementation((path: string): any => { - if (path.includes('apps/products')) { - return jestObject; - } - }); - - tree = createTreeWithEmptyWorkspace(); - - tree.write('apps/products/jest.config.js', jestConfig); - tree.write( - 'apps/products/src/test-setup.ts', - `import 'jest-preset-angular';` - ); - addProjectConfiguration(tree, 'products', { - root: 'apps/products', - sourceRoot: 'apps/products/src', - targets: { - build: { - executor: '@angular-devkit/build-angular:browser', - }, - test: { - executor: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/products/jest.config.js', - passWithNoTests: true, - }, - }, - }, - }); - }); - - it('should update the jest.config files by renaming tsConfig', async () => { - await update(tree); - - const jestObject = jestConfigObject(tree, 'apps/products/jest.config.js'); - - expect(jestObject.globals['ts-jest']['tsconfig']).toEqual( - '/tsconfig.spec.json' - ); - expect(jestObject.globals['ts-jest']['tsConfig']).toBeUndefined(); - }); - - it('should ignore migration if the jest config does not have a globals prop', async () => { - getJestObjectMock.mockImplementation((path: string): any => { - if (path.includes('apps/products')) { - // return empty jest config without globals - return {}; - } - }); - - await expect(update(tree)).resolves.not.toThrowError(); - }); - - it('should ignore migration if the jest config does not have a tsconfig prop', async () => { - getJestObjectMock.mockImplementation((path: string): any => { - if (path.includes('apps/products')) { - // return empty jest config without tsconfig - return { globals: { 'ts-jest': {} } }; - } - }); - - await expect(update(tree)).resolves.not.toThrowError(); - }); -}); diff --git a/packages/jest/src/migrations/update-12-1-2/update-ts-jest.ts b/packages/jest/src/migrations/update-12-1-2/update-ts-jest.ts index 99b1464a21087..370f968a256c0 100644 --- a/packages/jest/src/migrations/update-12-1-2/update-ts-jest.ts +++ b/packages/jest/src/migrations/update-12-1-2/update-ts-jest.ts @@ -3,7 +3,6 @@ import { join } from 'path'; import { forEachExecutorOptions } from '@nrwl/workspace/src/utilities/executor-options-utils'; import { JestExecutorOptions } from '../../executors/jest/schema'; -import { getJestObject } from '../update-10-0-0/require-jest-config'; import { addPropertyToJestConfig, removePropertyFromJestConfig, @@ -19,7 +18,7 @@ function updateJestConfig(tree: Tree) { } const jestConfigPath = options.jestConfig; - const config = getJestObject(join(tree.root, jestConfigPath)); + const config = require(join(tree.root, jestConfigPath)); const tsJestConfig = config.globals?.['ts-jest']; if (!(tsJestConfig && tsJestConfig.tsConfig)) { return; diff --git a/packages/jest/src/migrations/update-12-4-0/add-test-environment-for-node.spec.ts b/packages/jest/src/migrations/update-12-4-0/add-test-environment-for-node.spec.ts deleted file mode 100644 index 0cf55fc71a7b9..0000000000000 --- a/packages/jest/src/migrations/update-12-4-0/add-test-environment-for-node.spec.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { addProjectConfiguration, Tree } from '@nrwl/devkit'; -import { getJestObject } from '../update-10-0-0/require-jest-config'; -import { jestConfigObject } from '../../utils/config/functions'; -import update from './add-test-environment-for-node'; -import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing'; - -jest.mock('../update-10-0-0/require-jest-config'); -const getJestObjectMock = getJestObject as jest.Mock; - -const jestObject = {}; - -describe('update 12.4.0', () => { - let tree: Tree; - const jestConfig = String.raw` - module.exports = ${JSON.stringify(jestObject, null, 2)} - `; - - beforeEach(() => { - getJestObjectMock.mockImplementation((path: string): any => { - return jestObject; - }); - - tree = createTreeWithEmptyWorkspace(); - - tree.write('apps/products/jest.config.js', jestConfig); - tree.write('apps/products-2/jest.config.js', jestConfig); - - addProjectConfiguration(tree, 'products', { - root: 'apps/products', - sourceRoot: 'apps/products/src', - targets: { - build: { - executor: '@nrwl/node:package', - }, - test: { - executor: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/products/jest.config.js', - passWithNoTests: true, - }, - }, - }, - }); - - addProjectConfiguration(tree, 'products-2', { - root: 'apps/products-2', - sourceRoot: 'apps/products-2/src', - targets: { - build: { - executor: '@nrwl/angular:build', - }, - test: { - executor: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/products-2/jest.config.js', - passWithNoTests: true, - }, - }, - }, - }); - }); - - it('should update the jest.config files by adding testEnvironment for node projects', async () => { - await update(tree); - - const jestObject = jestConfigObject(tree, 'apps/products/jest.config.js'); - - expect(jestObject.testEnvironment).toEqual('node'); - }); - - it('should not change the testEnvironment for angular apps', async () => { - await update(tree); - - const jestObject = jestConfigObject(tree, 'apps/products-2/jest.config.js'); - - expect(jestObject.testEnvironment).toBeUndefined(); - }); -}); diff --git a/packages/jest/src/migrations/update-12-4-0/add-test-environment-for-node.ts b/packages/jest/src/migrations/update-12-4-0/add-test-environment-for-node.ts index d253c91870b2a..eb0c723f067e0 100644 --- a/packages/jest/src/migrations/update-12-4-0/add-test-environment-for-node.ts +++ b/packages/jest/src/migrations/update-12-4-0/add-test-environment-for-node.ts @@ -10,7 +10,6 @@ import { join } from 'path'; import { forEachExecutorOptions } from '@nrwl/workspace/src/utilities/executor-options-utils'; import { JestExecutorOptions } from '../../executors/jest/schema'; -import { getJestObject } from '../update-10-0-0/require-jest-config'; import { addPropertyToJestConfig } from '../../utils/config/update-config'; function updateJestConfig(tree: Tree) { @@ -23,7 +22,7 @@ function updateJestConfig(tree: Tree) { } const jestConfigPath = options.jestConfig; - const jestConfig = getJestObject(join(tree.root, jestConfigPath)); + const jestConfig = require(join(tree.root, jestConfigPath)); const projectConfig = readProjectConfiguration(tree, project); const testEnvironment = jestConfig.testEnvironment; diff --git a/packages/jest/src/migrations/update-12-4-0/update-jest-preset-angular.spec.ts b/packages/jest/src/migrations/update-12-4-0/update-jest-preset-angular.spec.ts deleted file mode 100644 index 880ec221eab11..0000000000000 --- a/packages/jest/src/migrations/update-12-4-0/update-jest-preset-angular.spec.ts +++ /dev/null @@ -1,171 +0,0 @@ -import { addProjectConfiguration, Tree } from '@nrwl/devkit'; -import { getJestObject } from '../update-10-0-0/require-jest-config'; -import { jestConfigObject } from '../../utils/config/functions'; -import update from './update-jest-preset-angular'; -import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing'; - -jest.mock('../update-10-0-0/require-jest-config'); -const getJestObjectMock = getJestObject as jest.Mock; - -const jestExampleConfig1 = { - globals: { - 'ts-jest': { - astTransformers: { - before: [ - 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer', - ], - }, - }, - }, -}; - -const jestExampleConfig2 = { - preset: '../../../../../../jest.preset.js', - transform: { - '^.+\\.[tj]sx?$': 'ts-jest', - }, - moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'html'], - setupFilesAfterEnv: ['/src/test-setup.ts'], - globals: { - 'ts-jest': { - tsConfig: '/tsconfig.spec.json', - stringifyContentPathRegex: '\\.(html|svg)$', - astTransformers: { - before: [ - 'jest-preset-angular/build/InlineFilesTransformer', - 'jest-preset-angular/build/StripStylesTransformer', - ], - }, - }, - }, -}; - -const jestExampleConfig3 = { - testMatch: ['**/+(*.)+(spec|test).[tj]s?(x)'], - globals: { - 'ts-jest': { - tsConfig: 'lib/somepath/tsconfig.spec.json', - stringifyContentPathRegex: '\\.(html|svg)$', - astTransformers: { - before: [ - // concatenated via "path.join(..)" in the real project - 'node_modules/jest-preset-angular/build/InlineFilesTransformer', - 'node_modules/jest-preset-angular/build/StripStylesTransformer', - ], - }, - }, - }, - resolver: '@nrwl/jest/plugins/resolver', - moduleFileExtensions: ['ts', 'js', 'html'], - coverageReporters: ['html', 'lcov', 'json'], - coverageThreshold: { - global: { - branches: 90, - lines: 80, - statements: 80, - }, - }, -}; - -[ - { name: 'jest config example 1', jestObject: jestExampleConfig1 }, - { name: 'jest example config 2', jestObject: jestExampleConfig2 }, - { - name: 'testing when jest-preset-angular astTransform path is composed of node_modules etc..', - jestObject: jestExampleConfig3, - }, -].forEach(({ name, jestObject }) => { - describe(`Jest migration: ${name}`, () => { - let tree: Tree; - const jestConfig = String.raw` - module.exports = ${JSON.stringify(jestObject, null, 2)} - `; - - beforeEach(() => { - getJestObjectMock.mockImplementation((path: string): any => { - return jestObject; - }); - - tree = createTreeWithEmptyWorkspace(); - - tree.write('apps/products/jest.config.js', jestConfig); - tree.write('apps/products-2/jest.config.js', jestConfig); - - addProjectConfiguration(tree, 'products', { - root: 'apps/products', - sourceRoot: 'apps/products/src', - targets: { - build: { - executor: '@nrwl/node:package', - }, - test: { - executor: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/products/jest.config.js', - passWithNoTests: true, - }, - }, - }, - }); - - addProjectConfiguration(tree, 'products-2', { - root: 'apps/products-2', - sourceRoot: 'apps/products-2/src', - targets: { - build: { - executor: '@nrwl/angular:build', - }, - test: { - executor: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/products-2/jest.config.js', - passWithNoTests: true, - }, - }, - }, - }); - }); - - it('should update the jest.config files by removing astTransformers if using only jest-preset-angular', async () => { - await update(tree); - - const jestObject = jestConfigObject(tree, 'apps/products/jest.config.js'); - - expect( - (jestObject.globals['ts-jest'] as { astTransformers: unknown }) - .astTransformers - ).toBeUndefined(); - }); - - it('should add transform if angular app', async () => { - await update(tree); - - const jestObject = jestConfigObject( - tree, - 'apps/products-2/jest.config.js' - ); - - expect(jestObject.transform).toEqual({ - ...jestObject.transform, - '^.+\\.(ts|js|html)$': 'jest-preset-angular', - }); - }); - - it('should not add transform if non-angular app', async () => { - getJestObjectMock.mockImplementation((path: string): any => { - if (path.includes('apps/products')) { - // return empty jest config without tsconfig - return { globals: { 'ts-jest': {} } }; - } - }); - - await update(tree); - - const jestObject = jestConfigObject(tree, 'apps/products/jest.config.js'); - - // should be the same as before - expect(jestObject.transform).toEqual(jestObject.transform); - }); - }); -}); diff --git a/packages/jest/src/migrations/update-12-4-0/update-jest-preset-angular.ts b/packages/jest/src/migrations/update-12-4-0/update-jest-preset-angular.ts index 68af098a279c1..bc5e7bc917805 100644 --- a/packages/jest/src/migrations/update-12-4-0/update-jest-preset-angular.ts +++ b/packages/jest/src/migrations/update-12-4-0/update-jest-preset-angular.ts @@ -3,7 +3,6 @@ import { join } from 'path'; import { forEachExecutorOptions } from '@nrwl/workspace/src/utilities/executor-options-utils'; import { JestExecutorOptions } from '../../executors/jest/schema'; -import { getJestObject } from '../update-10-0-0/require-jest-config'; import { addPropertyToJestConfig, removePropertyFromJestConfig, @@ -19,9 +18,10 @@ function updateJestConfig(tree: Tree) { } const jestConfigPath = options.jestConfig; - const jestConfig = getJestObject( - join(tree.root, jestConfigPath) - ) as PartialJestConfig; + const jestConfig = require(join( + tree.root, + jestConfigPath + )) as PartialJestConfig; if (!usesJestPresetAngular(jestConfig)) { return; diff --git a/packages/jest/src/migrations/update-8-3-0/test-files/jest.config.js b/packages/jest/src/migrations/update-8-3-0/test-files/jest.config.js deleted file mode 100644 index 9b08aea993436..0000000000000 --- a/packages/jest/src/migrations/update-8-3-0/test-files/jest.config.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'], - transform: { - '^.+\\.(ts|js|html)$': 'ts-jest', - }, - resolver: '@nrwl/jest/plugins/resolver', - moduleFileExtensions: ['ts', 'js', 'html'], - collectCoverage: true, - coverageReporters: ['html'], -}; diff --git a/packages/jest/src/migrations/update-8-3-0/update-8-3-0.spec.ts b/packages/jest/src/migrations/update-8-3-0/update-8-3-0.spec.ts deleted file mode 100644 index 87a651cd020d3..0000000000000 --- a/packages/jest/src/migrations/update-8-3-0/update-8-3-0.spec.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { Tree, mergeWith, url } from '@angular-devkit/schematics'; -import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; - -import * as path from 'path'; -import { readFileSync } from 'fs'; - -describe('Update 8.3.0', () => { - let initialTree: Tree; - let schematicRunner: SchematicTestRunner; - - beforeEach(async () => { - initialTree = Tree.empty(); - schematicRunner = new SchematicTestRunner( - '@nrwl/jest', - path.join(__dirname, '../../../migrations.json') - ); - }); - - it('should collectCoverage to false in the jest.config.js', async () => { - initialTree.create( - 'jest.config.js', - readFileSync( - path.join(__dirname, './test-files/jest.config.js') - ).toString() - ); - - const result = await schematicRunner - .runSchematicAsync('update-8.3.0', {}, initialTree) - .toPromise(); - - const updatedJestConfigFile = result.readContent('jest.config.js'); - - expect(updatedJestConfigFile).not.toContain('collectCoverage: true'); - - //check if the file is still valid - expect(updatedJestConfigFile.match(/,/g) || []).toHaveLength(8); - expect(updatedJestConfigFile).toContain('}'); - expect(updatedJestConfigFile).toContain('{'); - }); -}); diff --git a/packages/jest/src/migrations/update-8-3-0/update-8-3-0.ts b/packages/jest/src/migrations/update-8-3-0/update-8-3-0.ts deleted file mode 100644 index 4775f1820aded..0000000000000 --- a/packages/jest/src/migrations/update-8-3-0/update-8-3-0.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { Rule, Tree, chain } from '@angular-devkit/schematics'; -import { insert, formatFiles } from '@nrwl/workspace'; -import * as ts from 'typescript'; -import { - getSourceNodes, - RemoveChange, -} from '@nrwl/workspace/src/utils/ast-utils'; - -function updateJestConfig(host: Tree) { - if (host.exists('jest.config.js')) { - const contents = host.read('jest.config.js').toString(); - const sourceFile = ts.createSourceFile( - 'jest.config.js', - contents, - ts.ScriptTarget.Latest - ); - const changes: RemoveChange[] = []; - const sourceNodes = getSourceNodes(sourceFile); - sourceNodes.forEach((node, index) => { - if ( - ts.isPropertyAssignment(node) && - ts.isIdentifier(node.name) && - node.name.text === 'collectCoverage' - ) { - const expectedCommaNode = sourceNodes[index + 4]; - const isFollowedByComma = - expectedCommaNode.kind === ts.SyntaxKind.CommaToken; - changes.push( - new RemoveChange( - 'jest.config.js', - node.getStart(sourceFile), - isFollowedByComma - ? node.getFullText(sourceFile) - : node.getText(sourceFile) - ) - ); - } - }); - insert(host, 'jest.config.js', changes); - } -} - -export default function (): Rule { - return chain([updateJestConfig, formatFiles()]); -} diff --git a/packages/jest/src/migrations/update-8-7-0/update-8-7-0.spec.ts b/packages/jest/src/migrations/update-8-7-0/update-8-7-0.spec.ts deleted file mode 100644 index 659d95f1f0b0f..0000000000000 --- a/packages/jest/src/migrations/update-8-7-0/update-8-7-0.spec.ts +++ /dev/null @@ -1,60 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { readJsonInTree } from '@nrwl/workspace/src/utils/ast-utils'; -import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; -import * as path from 'path'; - -describe('Update 8.7.0', () => { - let tree: Tree; - let schematicRunner: SchematicTestRunner; - - beforeEach(async () => { - tree = Tree.empty(); - schematicRunner = new SchematicTestRunner( - '@nrwl/jest', - path.join(__dirname, '../../../migrations.json') - ); - }); - - it('should convert testPathPattern option to an array', async () => { - tree.create( - 'angular.json', - JSON.stringify({ - version: 1, - projects: { - test: { - architect: { - jest1: { - builder: '@nrwl/jest:jest', - options: { - testPathPattern: 'some/test/path', - }, - }, - jest2: { - builder: '@nrwl/jest:jest', - options: { - foo: 'bar', - }, - }, - jest3: { - builder: '@nrwl/jest:jest', - }, - }, - }, - }, - }) - ); - - await schematicRunner - .runSchematicAsync('update-8.7.0', {}, tree) - .toPromise(); - - const angularJson = readJsonInTree(tree, 'angular.json'); - - expect( - angularJson.projects.test.architect.jest1.options.testPathPattern - ).toEqual(['some/test/path']); - expect( - angularJson.projects.test.architect.jest2.options.testPathPattern - ).toBeUndefined(); - }); -}); diff --git a/packages/jest/src/migrations/update-8-7-0/update-8-7-0.ts b/packages/jest/src/migrations/update-8-7-0/update-8-7-0.ts deleted file mode 100644 index b7dcd893099f6..0000000000000 --- a/packages/jest/src/migrations/update-8-7-0/update-8-7-0.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { chain, Rule } from '@angular-devkit/schematics'; -import { updateWorkspace } from '@nrwl/workspace/src/utils/workspace'; -import { formatFiles } from '@nrwl/workspace'; - -const convertToArray = updateWorkspace((workspace) => { - workspace.projects.forEach((project) => { - project.targets.forEach((target) => { - if ( - target.builder === '@nrwl/jest:jest' && - target.options && - target.options.testPathPattern - ) { - target.options.testPathPattern = [target.options.testPathPattern]; - } - }); - }); -}); - -export default function (): Rule { - return chain([convertToArray, formatFiles()]); -} diff --git a/packages/jest/src/migrations/update-9-0-0/update-9-0-0.spec.ts b/packages/jest/src/migrations/update-9-0-0/update-9-0-0.spec.ts deleted file mode 100644 index bd5a627bbdb7a..0000000000000 --- a/packages/jest/src/migrations/update-9-0-0/update-9-0-0.spec.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { readJsonInTree } from '@nrwl/workspace/src/utils/ast-utils'; -import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; -import * as path from 'path'; -import { createEmptyWorkspace } from '@nrwl/workspace/testing'; - -describe('Update 9.0.0', () => { - let initialTree: Tree; - let schematicRunner: SchematicTestRunner; - - beforeEach(async () => { - initialTree = createEmptyWorkspace(Tree.empty()); - - schematicRunner = new SchematicTestRunner( - '@nrwl/jest', - path.join(__dirname, '../../../migrations.json') - ); - - initialTree.overwrite( - 'package.json', - JSON.stringify({ devDependencies: { 'jest-preset-angular': '7.0.0' } }) - ); - - initialTree.overwrite( - 'workspace.json', - JSON.stringify({ - projects: { - 'angular-one': { - root: 'apps/angular-one/', - architect: { - test: { - builder: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/angular-one/jest.config.js', - }, - }, - }, - }, - 'angular-two': { - root: 'apps/angular-two/', - architect: { - test: { - builder: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/angular-two/jest.config.js', - }, - }, - }, - }, - 'non-angular-one': { - root: 'apps/non-angular-one/', - architect: { - test: { - builder: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/non-angular-one/jest.config.js', - }, - }, - }, - }, - }, - }) - ); - - initialTree.create( - 'apps/angular-one/jest.config.js', - `module.exports = { - name: 'angular-one', - preset: '../../jest.config.js', - coverageDirectory: - '../../coverage/apps/angular-one', - snapshotSerializers: [ - 'jest-preset-angular/AngularSnapshotSerializer.js', - 'jest-preset-angular/HTMLCommentSerializer.js' - ] - };` - ); - - initialTree.create( - 'apps/angular-two/jest.config.js', - `module.exports = { - name: 'angular-two', - preset: '../../jest.config.js', - coverageDirectory: - '../../coverage/apps/angular-two', - snapshotSerializers: [ - 'jest-preset-angular/AngularSnapshotSerializer.js', - 'jest-preset-angular/HTMLCommentSerializer.js' - ] - };` - ); - - initialTree.create( - 'apps/non-angular-one/jest.config.js', - `module.exports = { - name: 'non-angular-one', - preset: '../../jest.config.js', - coverageDirectory: - '../../coverage/apps/non-angular-one', - moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'html'] - };` - ); - }); - - it('should update jest-preset-angular to 8.0.0', async () => { - const result = await schematicRunner - .runSchematicAsync('update-9.0.0', {}, initialTree) - .toPromise(); - - const { devDependencies } = readJsonInTree(result, 'package.json'); - expect(devDependencies['jest-preset-angular']).toEqual('8.0.0'); - }); - - it(`it should add '/build' into jest-preset-angular snapshotSerializers in any jest.config.js where it exists`, async () => { - const result = await schematicRunner - .runSchematicAsync('update-9.0.0', {}, initialTree) - .toPromise(); - - const updateJestAngularOne = result.readContent( - 'apps/angular-one/jest.config.js' - ); - const updateJestAngularTwo = result.readContent( - 'apps/angular-two/jest.config.js' - ); - const updateJestNonAngularOne = result.readContent( - 'apps/non-angular-one/jest.config.js' - ); - - expect(updateJestAngularOne).not.toContain( - 'jest-preset-angular/AngularSnapshotSerializer.js' - ); - expect(updateJestAngularOne).not.toContain( - 'jest-preset-angular/HTMLCommentSerializer.js' - ); - expect(updateJestAngularTwo).not.toContain( - 'jest-preset-angular/AngularSnapshotSerializer.js' - ); - expect(updateJestAngularTwo).not.toContain( - 'jest-preset-angular/HTMLCommentSerializer.js' - ); - - expect(updateJestAngularOne).toContain( - 'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js' - ); - expect(updateJestAngularOne).toContain( - 'jest-preset-angular/build/AngularSnapshotSerializer.js' - ); - expect(updateJestAngularOne).toContain( - 'jest-preset-angular/build/HTMLCommentSerializer.js' - ); - - expect(updateJestAngularTwo).toContain( - 'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js' - ); - expect(updateJestAngularTwo).toContain( - 'jest-preset-angular/build/AngularSnapshotSerializer.js' - ); - expect(updateJestAngularTwo).toContain( - 'jest-preset-angular/build/HTMLCommentSerializer.js' - ); - - expect(updateJestNonAngularOne).not.toContain( - 'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js' - ); - expect(updateJestNonAngularOne).not.toContain( - 'jest-preset-angular/build/AngularSnapshotSerializer.js' - ); - expect(updateJestNonAngularOne).not.toContain( - 'jest-preset-angular/build/HTMLCommentSerializer.js' - ); - }); -}); diff --git a/packages/jest/src/migrations/update-9-0-0/update-9-0-0.ts b/packages/jest/src/migrations/update-9-0-0/update-9-0-0.ts deleted file mode 100644 index 245aae9f9f938..0000000000000 --- a/packages/jest/src/migrations/update-9-0-0/update-9-0-0.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { - chain, - Rule, - SchematicContext, - Tree, -} from '@angular-devkit/schematics'; -import { - formatFiles, - insert, - readWorkspace, - updatePackagesInPackageJson, -} from '@nrwl/workspace'; -import * as ts from 'typescript'; -import * as path from 'path'; -import { - Change, - getSourceNodes, - InsertChange, - readJsonInTree, - ReplaceChange, -} from '@nrwl/workspace/src/utils/ast-utils'; -import { stripIndents } from '@angular-devkit/core/src/utils/literals'; - -export default function update(): Rule { - return chain([ - displayInformation, - updatePackagesInPackageJson( - path.join(__dirname, '../../../', 'migrations.json'), - '9.0.0' - ), - updateJestConfigs, - formatFiles(), - ]); -} - -function displayInformation(host: Tree, context: SchematicContext) { - const config = readJsonInTree(host, 'package.json'); - if (config.devDependencies && config.devDependencies['jest-preset-angular']) { - context.logger.info(stripIndents` - \`jest-preset-angular\` 8.0.0 has restructured folders, introducing breaking changes to - jest.config.js files. - - We are updating snapshotSerializers in each Angular project to include appropriate paths. - - See: https://github.com/thymikee/jest-preset-angular/releases/tag/v8.0.0 - `); - } -} - -function updateJestConfigs(host: Tree) { - const config = readJsonInTree(host, 'package.json'); - - if (config.devDependencies && config.devDependencies['jest-preset-angular']) { - const workspaceConfig = readWorkspace(host); - const jestConfigsToUpdate = []; - - Object.values(workspaceConfig.projects).forEach((project) => { - if (!project.architect) { - return; - } - - Object.values(project.architect).forEach((target) => { - if (target.builder !== '@nrwl/jest:jest') { - return; - } - - if (target.options.jestConfig) { - jestConfigsToUpdate.push(target.options.jestConfig); - } - - if (target.configurations) { - Object.values(target.configurations).forEach((config) => { - if (config.jestConfig) { - jestConfigsToUpdate.push(config.jestConfig); - } - }); - } - }); - }); - - jestConfigsToUpdate.forEach((configPath) => { - if (host.exists(configPath)) { - const contents = host.read(configPath).toString(); - const sourceFile = ts.createSourceFile( - configPath, - contents, - ts.ScriptTarget.Latest - ); - - const changes: Change[] = []; - - getSourceNodes(sourceFile).forEach((node) => { - if (node && ts.isStringLiteral(node)) { - const nodeText = node.text; - - if ( - nodeText === 'jest-preset-angular/AngularSnapshotSerializer.js' - ) { - // add new serializer from v8 of jest-preset-angular - changes.push( - new InsertChange( - configPath, - node.getStart(sourceFile), - `'jest-preset-angular/build/AngularNoNgAttributesSnapshotSerializer.js',\n` - ) - ); - - changes.push( - new ReplaceChange( - configPath, - node.getStart(sourceFile) + 1, - nodeText, - 'jest-preset-angular/build/AngularSnapshotSerializer.js' - ) - ); - } - - if (nodeText === 'jest-preset-angular/HTMLCommentSerializer.js') { - changes.push( - new ReplaceChange( - configPath, - node.getStart(sourceFile) + 1, - nodeText, - 'jest-preset-angular/build/HTMLCommentSerializer.js' - ) - ); - } - } - }); - - insert( - host, - configPath, - changes.sort((a, b) => (a.order > b.order ? -1 : 1)) - ); - } - }); - } -} diff --git a/packages/jest/src/migrations/update-9-0-1/test-files/jest.config.js b/packages/jest/src/migrations/update-9-0-1/test-files/jest.config.js deleted file mode 100644 index e4ee1a2b33936..0000000000000 --- a/packages/jest/src/migrations/update-9-0-1/test-files/jest.config.js +++ /dev/null @@ -1,10 +0,0 @@ -module.exports = { - testMatch: ['**/+(*.)+(spec|test).+(ts|js)?(x)'], - transform: { - '^.+\\.(ts|js|html)$': 'ts-jest', - }, - resolver: '@nrwl/jest/plugins/resolver', - moduleFileExtensions: ['ts', 'js', 'html'], - coverageReporters: ['html'], - passWithNoTests: true, -}; diff --git a/packages/jest/src/migrations/update-9-0-1/update-9-0-1.spec.ts b/packages/jest/src/migrations/update-9-0-1/update-9-0-1.spec.ts deleted file mode 100644 index cd1394adcc023..0000000000000 --- a/packages/jest/src/migrations/update-9-0-1/update-9-0-1.spec.ts +++ /dev/null @@ -1,157 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { readJsonInTree } from '@nrwl/workspace/src/utils/ast-utils'; -import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; -import * as path from 'path'; -import { createEmptyWorkspace } from '@nrwl/workspace/testing'; -import { readFileSync } from 'fs'; - -describe('Update 9.0.1', () => { - let initialTree: Tree; - let schematicRunner: SchematicTestRunner; - - beforeEach(async () => { - initialTree = createEmptyWorkspace(Tree.empty()); - - schematicRunner = new SchematicTestRunner( - '@nrwl/jest', - path.join(__dirname, '../../../migrations.json') - ); - }); - it('should remove passWithNoTests in jest.config.js', async () => { - initialTree.create( - 'jest.config.js', - readFileSync( - path.join(__dirname, './test-files/jest.config.js') - ).toString() - ); - const initialJestConfigFile = initialTree.read('jest.config.js').toString(); - expect(initialJestConfigFile).toContain('passWithNoTests: true'); - - const result = await schematicRunner - .runSchematicAsync('update-9.0.1', {}, initialTree) - .toPromise(); - - const updatedJestConfigFile = result.readContent('jest.config.js'); - expect(updatedJestConfigFile).not.toContain('passWithNoTests: true'); - - //check if the file is still valid - expect(updatedJestConfigFile.match(/,/g) || []).toHaveLength(8); - expect(updatedJestConfigFile).toContain('}'); - expect(updatedJestConfigFile).toContain('{'); - }); - - it('should add passWithNoTests to workspace.json where it does not exist', async () => { - initialTree.overwrite( - 'workspace.json', - JSON.stringify({ - version: 1, - projects: { - 'angular-one': { - architect: { - test: { - builder: '@nrwl/jest:jest', - options: { - jestConfig: 'apps/angular-one/jest.config.js', - }, - }, - }, - }, - 'angular-two': { - architect: { - test: { - builder: '@nrwl/jest:jest', - options: { - passWithNoTests: false, - }, - }, - }, - }, - other1: { - architect: { - 'other-architect': { - builder: 'other', - options: { - foo: 'bar', - }, - }, - test: { - builder: '@nrwl/jest:jest', - options: {}, - }, - }, - }, - }, - }) - ); - - await schematicRunner - .runSchematicAsync('update-9.0.1', {}, initialTree) - .toPromise(); - - const workspaceJson = readJsonInTree(initialTree, 'workspace.json'); - expect( - workspaceJson.projects['angular-one'].architect.test.options - .passWithNoTests - ).toBeTruthy(); - expect( - workspaceJson.projects['angular-two'].architect.test.options - .passWithNoTests - ).toBeFalsy(); - expect( - workspaceJson.projects.other1.architect['other-architect'].options - .passWithNoTests - ).toBeUndefined(); - expect( - workspaceJson.projects.other1.architect.test.options.passWithNoTests - ).toBeTruthy(); - }); - - it('should add passWithNoTests to angular.json where it does not exist', async () => { - initialTree.create( - 'angular.json', - JSON.stringify({ - version: 1, - projects: { - frontend: { - architect: { - jest1: { - builder: '@nrwl/jest:jest', - options: { - foo: 'bar', - }, - }, - jest2: { - builder: '@nrwl/jest:jest', - options: { - foo: 'bar', - passWithNoTests: false, - }, - }, - other1: { - options: { - foo: 'bar', - }, - }, - }, - }, - }, - }) - ); - - await schematicRunner - .runSchematicAsync('update-9.0.1', {}, initialTree) - .toPromise(); - - const angularJson = readJsonInTree(initialTree, 'angular.json'); - - expect( - angularJson.projects.frontend.architect.jest1.options.passWithNoTests - ).toBeTruthy(); - expect( - angularJson.projects.frontend.architect.jest2.options.passWithNoTests - ).toBeFalsy(); - expect( - angularJson.projects.frontend.architect.other1.options.passWithNoTests - ).toBeUndefined(); - }); -}); diff --git a/packages/jest/src/migrations/update-9-0-1/update-9-0-1.ts b/packages/jest/src/migrations/update-9-0-1/update-9-0-1.ts deleted file mode 100644 index 2c6b466fee13c..0000000000000 --- a/packages/jest/src/migrations/update-9-0-1/update-9-0-1.ts +++ /dev/null @@ -1,64 +0,0 @@ -import { chain, Rule, Tree } from '@angular-devkit/schematics'; -import { formatFiles, insert } from '@nrwl/workspace'; -import * as ts from 'typescript'; -import { - getSourceNodes, - RemoveChange, -} from '@nrwl/workspace/src/utils/ast-utils'; -import { updateWorkspace } from '@nrwl/workspace/src/utils/workspace'; - -export default function update(): Rule { - return chain([ - addPassWithNoTestsToWorkspace, - removePassWithNoTestsFromJestConfig, - formatFiles(), - ]); -} - -const addPassWithNoTestsToWorkspace = updateWorkspace((workspace) => { - workspace.projects.forEach((project) => { - project.targets.forEach((target) => { - if ( - target.builder === '@nrwl/jest:jest' && - target.options && - target.options.passWithNoTests === undefined - ) { - target.options.passWithNoTests = true; - } - }); - }); -}); - -function removePassWithNoTestsFromJestConfig(host: Tree) { - if (host.exists('jest.config.js')) { - const contents = host.read('jest.config.js').toString(); - const sourceFile = ts.createSourceFile( - 'jest.config.js', - contents, - ts.ScriptTarget.Latest - ); - const changes: RemoveChange[] = []; - const sourceNodes = getSourceNodes(sourceFile); - sourceNodes.forEach((node, index) => { - if ( - ts.isPropertyAssignment(node) && - ts.isIdentifier(node.name) && - node.name.text === 'passWithNoTests' - ) { - const expectedCommaNode = sourceNodes[index + 4]; - const isFollowedByComma = - expectedCommaNode.kind === ts.SyntaxKind.CommaToken; - changes.push( - new RemoveChange( - 'jest.config.js', - node.getStart(sourceFile), - isFollowedByComma - ? node.getFullText(sourceFile) - : node.getText(sourceFile) - ) - ); - } - }); - insert(host, 'jest.config.js', changes); - } -} diff --git a/packages/jest/src/migrations/update-9-2-0/update-9-2-0.ts b/packages/jest/src/migrations/update-9-2-0/update-9-2-0.ts deleted file mode 100644 index 4c6be6484ebd9..0000000000000 --- a/packages/jest/src/migrations/update-9-2-0/update-9-2-0.ts +++ /dev/null @@ -1,13 +0,0 @@ -import { chain, Rule } from '@angular-devkit/schematics'; -import { formatFiles, updatePackagesInPackageJson } from '@nrwl/workspace'; -import * as path from 'path'; - -export default function update(): Rule { - return chain([ - updatePackagesInPackageJson( - path.join(__dirname, '../../../', 'migrations.json'), - '9.2.0' - ), - formatFiles(), - ]); -} diff --git a/packages/js/src/utils/copy-assets-handler.ts b/packages/js/src/utils/copy-assets-handler.ts index 8db9af268a080..3d9c7ba141ca6 100644 --- a/packages/js/src/utils/copy-assets-handler.ts +++ b/packages/js/src/utils/copy-assets-handler.ts @@ -5,7 +5,7 @@ import * as fse from 'fs-extra'; import ignore, { Ignore } from 'ignore'; import * as fg from 'fast-glob'; import { AssetGlob } from '@nrwl/workspace/src/utilities/assets'; -import { logger } from '@nrwl/tao/src/shared/logger'; +import { logger } from 'nx/src/shared/logger'; export type FileEventType = 'create' | 'update' | 'delete'; diff --git a/packages/js/src/utils/update-package-json.ts b/packages/js/src/utils/update-package-json.ts index af12d5e09bc62..5f63eac841523 100644 --- a/packages/js/src/utils/update-package-json.ts +++ b/packages/js/src/utils/update-package-json.ts @@ -3,7 +3,7 @@ import { normalizePath, ProjectGraphProjectNode, } from '@nrwl/devkit'; -import { readJsonFile, writeJsonFile } from '@nrwl/tao/src/utils/fileutils'; +import { readJsonFile, writeJsonFile } from 'nx/src/utils/fileutils'; import { DependentBuildableProjectNode, updateBuildableProjectPackageJsonDependencies, diff --git a/packages/js/src/utils/watch-for-single-file-changes.ts b/packages/js/src/utils/watch-for-single-file-changes.ts index 7dacfe658e201..184959a4bad4d 100644 --- a/packages/js/src/utils/watch-for-single-file-changes.ts +++ b/packages/js/src/utils/watch-for-single-file-changes.ts @@ -1,4 +1,4 @@ -import { logger } from '@nrwl/tao/src/shared/logger'; +import { logger } from 'nx/src/shared/logger'; import { join } from 'path'; export async function watchForSingleFileChanges( diff --git a/packages/nest/src/generators/utils/run-nest-schematic.ts b/packages/nest/src/generators/utils/run-nest-schematic.ts index 7b2e605be7003..39e1559347477 100644 --- a/packages/nest/src/generators/utils/run-nest-schematic.ts +++ b/packages/nest/src/generators/utils/run-nest-schematic.ts @@ -1,6 +1,6 @@ import type { Tree } from '@nrwl/devkit'; import { formatFiles } from '@nrwl/devkit'; -import { wrapAngularDevkitSchematic } from '@nrwl/tao/src/commands/ngcli-adapter'; +import { wrapAngularDevkitSchematic } from 'nx/src/commands/ngcli-adapter'; import type { NestSchematic, NormalizedOptions } from './types'; export async function runNestSchematic( diff --git a/packages/nest/src/migrations/update-13-2-0/update-to-nest-8.ts b/packages/nest/src/migrations/update-13-2-0/update-to-nest-8.ts index b3f84537c920c..e634b71e8744c 100644 --- a/packages/nest/src/migrations/update-13-2-0/update-to-nest-8.ts +++ b/packages/nest/src/migrations/update-13-2-0/update-to-nest-8.ts @@ -1,5 +1,5 @@ import { formatFiles, logger, readJson, Tree, updateJson } from '@nrwl/devkit'; -import { sortObjectByKeys } from '@nrwl/tao/src/utils/object-sort'; +import { sortObjectByKeys } from 'nx/src/utils/object-sort'; import { checkAndCleanWithSemver } from '@nrwl/workspace'; import { satisfies } from 'semver'; import { diff --git a/packages/next/plugins/with-nx.ts b/packages/next/plugins/with-nx.ts index 83713802af151..c4f31126876dd 100644 --- a/packages/next/plugins/with-nx.ts +++ b/packages/next/plugins/with-nx.ts @@ -4,7 +4,7 @@ import type { NextConfig } from 'next/dist/server/config'; import type { WebpackConfigOptions } from '../src/utils/types'; const { join } = require('path'); -const { appRootPath } = require('@nrwl/tao/src/utils/app-root'); +const { appRootPath } = require('nx/src/utils/app-root'); const { workspaceLayout } = require('@nrwl/workspace/src/core/file-utils'); export interface WithNxOptions extends NextConfig { diff --git a/packages/next/src/utils/generate-globs.ts b/packages/next/src/utils/generate-globs.ts index f3dbab27f50f9..e311c3e74c097 100644 --- a/packages/next/src/utils/generate-globs.ts +++ b/packages/next/src/utils/generate-globs.ts @@ -1,5 +1,5 @@ import { joinPathFragments, logger } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { getSourceDirOfDependentProjects } from '@nrwl/workspace/src/utilities/project-graph-utils'; import { resolve } from 'path'; diff --git a/packages/node/src/utils/node.config.spec.ts b/packages/node/src/utils/node.config.spec.ts index 834e27ae0ab24..e5ece26a305e0 100644 --- a/packages/node/src/utils/node.config.spec.ts +++ b/packages/node/src/utils/node.config.spec.ts @@ -4,7 +4,7 @@ import { TsconfigPathsPlugin } from 'tsconfig-paths-webpack-plugin'; import { BuildNodeBuilderOptions } from './types'; jest.mock('tsconfig-paths-webpack-plugin'); -jest.mock('@nrwl/tao/src/utils/app-root', () => ({ +jest.mock('nx/src/utils/app-root', () => ({ get appRootPath() { return join(__dirname, '../../../..'); }, diff --git a/packages/node/src/utils/node.config.ts b/packages/node/src/utils/node.config.ts index f86d379d292fc..0252c01a08857 100644 --- a/packages/node/src/utils/node.config.ts +++ b/packages/node/src/utils/node.config.ts @@ -1,4 +1,4 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { Configuration } from 'webpack'; import { merge } from 'webpack-merge'; diff --git a/packages/nx-plugin/src/utils/testing-utils/async-commands.ts b/packages/nx-plugin/src/utils/testing-utils/async-commands.ts index 4e9a7efa595fa..8e7a568a37513 100644 --- a/packages/nx-plugin/src/utils/testing-utils/async-commands.ts +++ b/packages/nx-plugin/src/utils/testing-utils/async-commands.ts @@ -1,6 +1,6 @@ import { exec } from 'child_process'; import { tmpProjPath } from './paths'; -import { getPackageManagerCommand } from '@nrwl/tao/src/shared/package-manager'; +import { getPackageManagerCommand } from 'nx/src/shared/package-manager'; /** * Run a command asynchronously inside the e2e directory. diff --git a/packages/nx-plugin/src/utils/testing-utils/commands.ts b/packages/nx-plugin/src/utils/testing-utils/commands.ts index 61945c86e853c..956e8617508c5 100644 --- a/packages/nx-plugin/src/utils/testing-utils/commands.ts +++ b/packages/nx-plugin/src/utils/testing-utils/commands.ts @@ -1,6 +1,6 @@ import { execSync } from 'child_process'; import { tmpProjPath } from './paths'; -import { getPackageManagerCommand } from '@nrwl/tao/src/shared/package-manager'; +import { getPackageManagerCommand } from 'nx/src/shared/package-manager'; /** * Run a nx command inside the e2e directory diff --git a/packages/nx-plugin/src/utils/testing-utils/nx-project.ts b/packages/nx-plugin/src/utils/testing-utils/nx-project.ts index dbe2fd2947e16..ef39022a3624d 100644 --- a/packages/nx-plugin/src/utils/testing-utils/nx-project.ts +++ b/packages/nx-plugin/src/utils/testing-utils/nx-project.ts @@ -1,4 +1,4 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { getPackageManagerCommand, readJsonFile, @@ -14,7 +14,7 @@ function runNxNewCommand(args?: string, silent?: boolean) { const localTmpDir = dirname(tmpProjPath()); return execSync( `node ${require.resolve( - '@nrwl/tao' + 'nx' )} new proj --nx-workspace-root=${localTmpDir} --no-interactive --skip-install --collection=@nrwl/workspace --npmScope=proj --preset=empty ${ args || '' }`, diff --git a/packages/nx/bin/nx.ts b/packages/nx/bin/nx.ts index 31869bd706e4b..455f3bdc759ac 100644 --- a/packages/nx/bin/nx.ts +++ b/packages/nx/bin/nx.ts @@ -1,2 +1,73 @@ #!/usr/bin/env node -require('@nrwl/cli/bin/nx'); +import { findWorkspaceRoot } from '../src/cli/find-workspace-root'; +import * as chalk from 'chalk'; +import { initLocal } from '../src/cli/init-local'; +import { output } from '../src/cli/output'; +import { detectPackageManager } from '../src/shared/package-manager'; + +if (process.argv[2] === 'new' || process.argv[2] === '_migrate') { + require('../src/cli/index'); +} else { + const workspace = findWorkspaceRoot(process.cwd()); + if (workspace && workspace.type === 'nx') { + require('v8-compile-cache'); + } + // polyfill rxjs observable to avoid issues with multiple version fo Observable installed in node_modules + // https://twitter.com/BenLesh/status/1192478226385428483?s=20 + if (!(Symbol as any).observable) + (Symbol as any).observable = Symbol('observable polyfill'); + + if (!workspace) { + output.log({ + title: `The current directory isn't part of an Nx workspace.`, + bodyLines: [ + `To create a workspace run:`, + chalk.bold.white(`npx create-nx-workspace@latest `), + ], + }); + + output.note({ + title: `For more information please visit https://nx.dev/`, + }); + process.exit(1); + } + + // Make sure that a local copy of Nx exists in workspace + let localNx: string; + try { + localNx = require.resolve('nx/bin/nx.js', { + paths: [workspace.dir], + }); + } catch { + output.error({ + title: `Could not find Nx modules in this workspace.`, + bodyLines: [`Have you run ${chalk.bold.white(`npm/yarn install`)}?`], + }); + process.exit(1); + } + + if (localNx === require.resolve('nx/bin/nx.js')) { + initLocal(workspace); + } else { + const packageManager = detectPackageManager(); + if (packageManager === 'pnpm') { + const tip = + process.platform === 'win32' + ? 'doskey pnx=pnpm nx -- $*' + : `alias pnx="pnpm nx --"`; + output.warn({ + title: `Running global Nx CLI with PNPM may have issues.`, + bodyLines: [ + `Prefer to use "pnpm" (https://pnpm.io/cli/exec) to execute commands in this workspace.`, + `${chalk.reset.inverse.bold.cyan( + ' TIP ' + )} create a shortcut such as: ${chalk.bold.white(tip)}`, + ``, + ], + }); + } + + // Nx is being run from globally installed CLI - hand off to the local + require(localNx); + } +} diff --git a/packages/nx/package.json b/packages/nx/package.json index c26455aea9d08..52ba3612ed59c 100644 --- a/packages/nx/package.json +++ b/packages/nx/package.json @@ -28,6 +28,21 @@ }, "homepage": "https://nx.dev", "dependencies": { - "@nrwl/cli": "*" + "@swc/core": "^1.2.146", + "@swc-node/register": "^1.4.2", + "chalk": "4.1.0", + "enquirer": "~2.3.6", + "fast-glob": "3.2.7", + "fs-extra": "^9.1.0", + "ignore": "^5.0.4", + "jsonc-parser": "3.0.0", + "rxjs-for-await": "0.0.2", + "rxjs": "^6.5.4", + "semver": "7.3.4", + "tmp": "~0.2.1", + "tslib": "^2.3.0", + "tsconfig-paths": "^3.9.0", + "yargs-parser": "20.0.0", + "v8-compile-cache": "2.3.0" } } diff --git a/packages/nx/project.json b/packages/nx/project.json index cd896bbabf011..498351f51d290 100644 --- a/packages/nx/project.json +++ b/packages/nx/project.json @@ -48,6 +48,9 @@ "outputs": ["build/packages/nx"], "options": { "commands": [ + { + "command": "node ./scripts/chmod build/packages/nx/bin/nx.js" + }, { "command": "node ./scripts/copy-readme.js nx" } diff --git a/packages/nx/src/cli/decorate-cli.ts b/packages/nx/src/cli/decorate-cli.ts new file mode 100644 index 0000000000000..5375f7b6ca221 --- /dev/null +++ b/packages/nx/src/cli/decorate-cli.ts @@ -0,0 +1,16 @@ +import { readFileSync, writeFileSync } from 'fs'; + +export function decorateCli() { + const path = 'node_modules/@angular/cli/lib/cli/index.js'; + const angularCLIInit = readFileSync(path, 'utf-8'); + const start = angularCLIInit.indexOf(`(options) {`) + 11; + + const newContent = `${angularCLIInit.substr(0, start)} + if (!process.env['NX_CLI_SET']) { + require('nx/bin/nx'); + return new Promise(function(res, rej) {}); + } + ${angularCLIInit.substring(start)} +`; + writeFileSync(path, newContent); +} diff --git a/packages/cli/lib/find-workspace-root.ts b/packages/nx/src/cli/find-workspace-root.ts similarity index 100% rename from packages/cli/lib/find-workspace-root.ts rename to packages/nx/src/cli/find-workspace-root.ts diff --git a/packages/nx/src/cli/index.ts b/packages/nx/src/cli/index.ts new file mode 100644 index 0000000000000..38a95e24a5cad --- /dev/null +++ b/packages/nx/src/cli/index.ts @@ -0,0 +1,104 @@ +#!/usr/bin/env node +import { dirname, join } from 'path'; +import { existsSync } from 'fs-extra'; +import * as yargsParser from 'yargs-parser'; + +const argv = yargsParser(process.argv.slice(2), { + configuration: { + 'strip-dashed': true, + 'dot-notation': false, + }, +}); + +export async function invokeCommand( + command: string, + root: string, + commandArgs: string[] = [] +) { + if (!command) { + command = 'help'; + } + + let verboseFlagIndex = commandArgs.indexOf('--verbose'); + if (verboseFlagIndex < 0) { + verboseFlagIndex = commandArgs.indexOf('-v'); + } + const isVerbose = verboseFlagIndex >= 0; + if (isVerbose) { + commandArgs.splice(verboseFlagIndex, 1); + } + + switch (command) { + case 'new': + return (await import('../commands/generate')).newWorkspace( + root, + commandArgs, + isVerbose + ); + case 'generate': + case 'g': + return (await import('../commands/generate')).generate( + process.cwd(), + root, + commandArgs, + isVerbose + ); + case 'run': + case 'r': + return (await import('../commands/run')).run( + process.cwd(), + root, + commandArgs, + isVerbose + ); + case '_migrate': + return (await import('../commands/migrate')).migrate( + root, + commandArgs, + isVerbose + ); + case 'help': + case '--help': + return (await import('../commands/help')).help(); + + default: { + const projectNameIncluded = + commandArgs[0] && !commandArgs[0].startsWith('-'); + const projectName = projectNameIncluded ? commandArgs[0] : ''; + // this is to make `nx test mylib` same as `nx run mylib:test` + return (await import('../commands/run')).run( + process.cwd(), + root, + [ + `${projectName}:${command}`, + ...(projectNameIncluded ? commandArgs.slice(1) : commandArgs), + ], + isVerbose + ); + } + } +} + +function findWorkspaceRoot(dir: string): string { + if (dirname(dir) === dir) { + throw new Error(`The cwd isn't part of an Nx workspace`); + } + if ( + existsSync(join(dir, 'angular.json')) || + existsSync(join(dir, 'workspace.json')) || + existsSync(join(dir, 'nx.json')) + ) { + return dir; + } + return findWorkspaceRoot(dirname(dir)); +} + +export async function invokeCli(root: string, args: string[]) { + const [command, ...commandArgs] = args; + process.exit(await invokeCommand(command, root, commandArgs)); +} + +invokeCli( + argv.nxWorkspaceRoot || findWorkspaceRoot(process.cwd()), + process.argv.slice(2) +); diff --git a/packages/cli/lib/init-local.ts b/packages/nx/src/cli/init-local.ts similarity index 93% rename from packages/cli/lib/init-local.ts rename to packages/nx/src/cli/init-local.ts index 29eefb5a94f1c..b51ac4d13e287 100644 --- a/packages/cli/lib/init-local.ts +++ b/packages/nx/src/cli/init-local.ts @@ -1,5 +1,5 @@ -import { Workspaces } from '@nrwl/tao/src/shared/workspace'; -import { getPackageManagerCommand } from '@nrwl/tao/src/shared/package-manager'; +import { Workspaces } from '../shared/workspace'; +import { getPackageManagerCommand } from '../shared/package-manager'; import { performance } from 'perf_hooks'; import { execSync } from 'child_process'; @@ -33,7 +33,7 @@ export function initLocal(workspace: Workspace) { } if (generating()) { - loadCli(workspace, '@nrwl/tao/index.js'); + loadCli(workspace, 'nx/src/cli/index.js'); return; } @@ -46,7 +46,7 @@ export function initLocal(workspace: Workspace) { } if (workspace.type === 'nx') { - loadCli(workspace, '@nrwl/tao/index.js'); + loadCli(workspace, 'nx/src/cli/index.js'); } else { if ( process.argv[2] === 'update' && @@ -100,7 +100,7 @@ export function initLocal(workspace: Workspace) { }) ); } else { - require('@nrwl/tao/src/compat/compat'); + require('nx/src/compat/compat'); loadCli(workspace, '@angular/cli/lib/init.js'); } } diff --git a/packages/cli/lib/is_ci.ts b/packages/nx/src/cli/is_ci.ts similarity index 100% rename from packages/cli/lib/is_ci.ts rename to packages/nx/src/cli/is_ci.ts diff --git a/packages/cli/lib/output.ts b/packages/nx/src/cli/output.ts similarity index 100% rename from packages/cli/lib/output.ts rename to packages/nx/src/cli/output.ts diff --git a/packages/cli/lib/parse-run-one-options.spec.ts b/packages/nx/src/cli/parse-run-one-options.spec.ts similarity index 100% rename from packages/cli/lib/parse-run-one-options.spec.ts rename to packages/nx/src/cli/parse-run-one-options.spec.ts diff --git a/packages/cli/lib/parse-run-one-options.ts b/packages/nx/src/cli/parse-run-one-options.ts similarity index 95% rename from packages/cli/lib/parse-run-one-options.ts rename to packages/nx/src/cli/parse-run-one-options.ts index f6d46679409ab..47960883d532c 100644 --- a/packages/cli/lib/parse-run-one-options.ts +++ b/packages/nx/src/cli/parse-run-one-options.ts @@ -1,9 +1,7 @@ import yargsParser = require('yargs-parser'); -import type { - WorkspaceJsonConfiguration, - NxJsonConfiguration, -} from '@nrwl/devkit'; -import { readJsonFile } from '@nrwl/tao/src/utils/fileutils'; +import { readJsonFile } from '../utils/fileutils'; +import { WorkspaceJsonConfiguration } from '../shared/workspace'; +import { NxJsonConfiguration } from '../shared/nx'; function calculateDefaultProjectName( cwd: string, diff --git a/packages/cli/lib/run-cli.ts b/packages/nx/src/cli/run-cli.ts similarity index 94% rename from packages/cli/lib/run-cli.ts rename to packages/nx/src/cli/run-cli.ts index 6d82f19c77fe6..1648c123afbe1 100644 --- a/packages/cli/lib/run-cli.ts +++ b/packages/nx/src/cli/run-cli.ts @@ -16,12 +16,12 @@ requireCli(); function requireCli() { process.env.NX_CLI_SET = 'true'; try { - const cli = require.resolve('@nrwl/tao/index.js', { + const cli = require.resolve('nx/src/cli/index.js', { paths: [process.env.NX_WORKSPACE_ROOT], }); require(cli); } catch (e) { - console.error(`Could not find @nrwl/tao module in this workspace.`, e); + console.error(`Could not find 'nx' module in this workspace.`, e); process.exit(1); } } diff --git a/packages/cli/lib/workspace.ts b/packages/nx/src/cli/workspace.ts similarity index 100% rename from packages/cli/lib/workspace.ts rename to packages/nx/src/cli/workspace.ts diff --git a/packages/tao/src/commands/generate.ts b/packages/nx/src/commands/generate.ts similarity index 98% rename from packages/tao/src/commands/generate.ts rename to packages/nx/src/commands/generate.ts index d422528b9272e..43c0b72b87f1a 100644 --- a/packages/tao/src/commands/generate.ts +++ b/packages/nx/src/commands/generate.ts @@ -142,7 +142,11 @@ function printChanges(fileChanges: FileChange[]) { }); } -export async function taoNew(cwd: string, args: string[], isVerbose = false) { +export async function newWorkspace( + cwd: string, + args: string[], + isVerbose = false +) { const ws = new Workspaces(null); return handleErrors(isVerbose, async () => { const opts = parseGenerateOpts(args, 'new', null); diff --git a/packages/tao/src/commands/help.ts b/packages/nx/src/commands/help.ts similarity index 100% rename from packages/tao/src/commands/help.ts rename to packages/nx/src/commands/help.ts diff --git a/packages/tao/src/commands/migrate.spec.ts b/packages/nx/src/commands/migrate.spec.ts similarity index 99% rename from packages/tao/src/commands/migrate.spec.ts rename to packages/nx/src/commands/migrate.spec.ts index 85cdfced7b3bc..5c45007a1b70c 100644 --- a/packages/tao/src/commands/migrate.spec.ts +++ b/packages/nx/src/commands/migrate.spec.ts @@ -331,7 +331,7 @@ describe('Migration', () => { }); }); - // this is temporary. if tao gets used by other projects, + // this is temporary. if nx gets used by other projects, // we will extract the special casing it('should special case @nrwl/workspace', async () => { const migrator = new Migrator({ @@ -354,7 +354,6 @@ describe('Migration', () => { '@nrwl/nx-plugin': '0.9.0', '@nrwl/react': '0.9.0', '@nrwl/storybook': '0.9.0', - '@nrwl/tao': '0.9.0', '@nrwl/web': '0.9.0', }, }, @@ -389,7 +388,6 @@ describe('Migration', () => { '@nrwl/nx-plugin': { version: '2.0.0', addToPackageJson: false }, '@nrwl/react': { version: '2.0.0', addToPackageJson: false }, '@nrwl/storybook': { version: '2.0.0', addToPackageJson: false }, - '@nrwl/tao': { version: '2.0.0', addToPackageJson: false }, '@nrwl/web': { version: '2.0.0', addToPackageJson: false }, }, }); diff --git a/packages/tao/src/commands/migrate.ts b/packages/nx/src/commands/migrate.ts similarity index 99% rename from packages/tao/src/commands/migrate.ts rename to packages/nx/src/commands/migrate.ts index 4c10e220a18e2..e65bf923aa263 100644 --- a/packages/tao/src/commands/migrate.ts +++ b/packages/nx/src/commands/migrate.ts @@ -222,8 +222,8 @@ export class Migrator { m.packageJsonUpdates[`${targetVersion}-defaultPackages`] = { version: targetVersion, packages: [ + 'nx', '@nrwl/angular', - '@nrwl/cli', '@nrwl/cypress', '@nrwl/devkit', '@nrwl/eslint-plugin-nx', @@ -238,7 +238,6 @@ export class Migrator { '@nrwl/nx-plugin', '@nrwl/react', '@nrwl/storybook', - '@nrwl/tao', '@nrwl/web', '@nrwl/react-native', '@nrwl/detox', diff --git a/packages/tao/src/commands/ngcli-adapter.ts b/packages/nx/src/commands/ngcli-adapter.ts similarity index 99% rename from packages/tao/src/commands/ngcli-adapter.ts rename to packages/nx/src/commands/ngcli-adapter.ts index 0f48a0e57e9f6..651432d7f6a67 100644 --- a/packages/tao/src/commands/ngcli-adapter.ts +++ b/packages/nx/src/commands/ngcli-adapter.ts @@ -616,7 +616,7 @@ export class NxScopeHostUsedForWrappedSchematics extends NxScopedHost { } else if (!this.__nxInMemoryWorkspace) { // if we've already dealt with this, let NxScopedHost read the cache... // projects created inside a generator will not be visible - // to glob when it runs in @nrwl/tao/shared/workspace, so + // to glob when it runs in nx/shared/workspace, so // we have to add them into the file. const createdProjectFiles = findCreatedProjects(this.host); const deletedProjectFiles = findDeletedProjects(this.host); diff --git a/packages/tao/src/commands/run.ts b/packages/nx/src/commands/run.ts similarity index 100% rename from packages/tao/src/commands/run.ts rename to packages/nx/src/commands/run.ts diff --git a/packages/tao/src/compat/compat.ts b/packages/nx/src/compat/compat.ts similarity index 100% rename from packages/tao/src/compat/compat.ts rename to packages/nx/src/compat/compat.ts diff --git a/packages/tao/src/shared/__snapshots__/logger.spec.ts.snap b/packages/nx/src/shared/__snapshots__/logger.spec.ts.snap similarity index 100% rename from packages/tao/src/shared/__snapshots__/logger.spec.ts.snap rename to packages/nx/src/shared/__snapshots__/logger.spec.ts.snap diff --git a/packages/tao/src/shared/logger.spec.ts b/packages/nx/src/shared/logger.spec.ts similarity index 97% rename from packages/tao/src/shared/logger.spec.ts rename to packages/nx/src/shared/logger.spec.ts index 922fc0167d6d6..5b2d402b20000 100644 --- a/packages/tao/src/shared/logger.spec.ts +++ b/packages/nx/src/shared/logger.spec.ts @@ -1,6 +1,6 @@ import { logger } from './logger'; -describe('Tao Logger', () => { +describe('Logger', () => { it('should color the NX prefix', () => { let logObject; jest.spyOn(console, 'info').mockImplementation((message) => { diff --git a/packages/nx/src/shared/logger.ts b/packages/nx/src/shared/logger.ts new file mode 100644 index 0000000000000..ba6e18dbc3ba3 --- /dev/null +++ b/packages/nx/src/shared/logger.ts @@ -0,0 +1,46 @@ +import * as chalk from 'chalk'; + +export const NX_PREFIX = `${chalk.cyan('>')} ${chalk.inverse( + chalk.bold(chalk.cyan(' NX ')) +)}`; + +export const NX_ERROR = chalk.inverse(chalk.bold(chalk.red(' ERROR '))); + +export const logger = { + warn: (s) => console.warn(chalk.bold(chalk.yellow(s))), + error: (s) => { + if (typeof s === 'string' && s.startsWith('NX ')) { + console.error(`\n${NX_ERROR} ${chalk.bold(chalk.red(s.substr(3)))}\n`); + } else if (s instanceof Error && s.stack) { + console.error(chalk.bold(chalk.red(s.stack))); + } else { + console.error(chalk.bold(chalk.red(s))); + } + }, + info: (s) => { + if (typeof s === 'string' && s.startsWith('NX ')) { + console.info(`\n${NX_PREFIX} ${chalk.bold(s.substr(3))}\n`); + } else { + console.info(s); + } + }, + log: (...s) => { + console.log(...s); + }, + debug: (...s) => { + console.debug(...s); + }, + fatal: (...s) => { + console.error(...s); + }, +}; + +export function stripIndent(str: string): string { + const match = str.match(/^[ \t]*(?=\S)/gm); + if (!match) { + return str; + } + const indent = match.reduce((r, a) => Math.min(r, a.length), Infinity); + const regex = new RegExp(`^[ \\t]{${indent}}`, 'gm'); + return str.replace(regex, ''); +} diff --git a/packages/tao/src/shared/nx-plugin.ts b/packages/nx/src/shared/nx-plugin.ts similarity index 100% rename from packages/tao/src/shared/nx-plugin.ts rename to packages/nx/src/shared/nx-plugin.ts diff --git a/packages/tao/src/shared/nx.ts b/packages/nx/src/shared/nx.ts similarity index 100% rename from packages/tao/src/shared/nx.ts rename to packages/nx/src/shared/nx.ts diff --git a/packages/tao/src/shared/package-json.spec.ts b/packages/nx/src/shared/package-json.spec.ts similarity index 100% rename from packages/tao/src/shared/package-json.spec.ts rename to packages/nx/src/shared/package-json.spec.ts diff --git a/packages/tao/src/shared/package-json.ts b/packages/nx/src/shared/package-json.ts similarity index 100% rename from packages/tao/src/shared/package-json.ts rename to packages/nx/src/shared/package-json.ts diff --git a/packages/tao/src/shared/package-manager.ts b/packages/nx/src/shared/package-manager.ts similarity index 100% rename from packages/tao/src/shared/package-manager.ts rename to packages/nx/src/shared/package-manager.ts diff --git a/packages/tao/src/shared/params.spec.ts b/packages/nx/src/shared/params.spec.ts similarity index 100% rename from packages/tao/src/shared/params.spec.ts rename to packages/nx/src/shared/params.spec.ts diff --git a/packages/tao/src/shared/params.ts b/packages/nx/src/shared/params.ts similarity index 100% rename from packages/tao/src/shared/params.ts rename to packages/nx/src/shared/params.ts diff --git a/packages/tao/src/shared/print-help.ts b/packages/nx/src/shared/print-help.ts similarity index 100% rename from packages/tao/src/shared/print-help.ts rename to packages/nx/src/shared/print-help.ts diff --git a/packages/tao/src/shared/project-graph.ts b/packages/nx/src/shared/project-graph.ts similarity index 97% rename from packages/tao/src/shared/project-graph.ts rename to packages/nx/src/shared/project-graph.ts index 75618ceeeb96b..39c9df666734e 100644 --- a/packages/tao/src/shared/project-graph.ts +++ b/packages/nx/src/shared/project-graph.ts @@ -1,7 +1,4 @@ -import type { - TargetConfiguration, - Workspace, -} from '@nrwl/tao/src/shared/workspace'; +import type { TargetConfiguration, Workspace } from './workspace'; /** * Some metadata about a file diff --git a/packages/tao/src/shared/tasks.ts b/packages/nx/src/shared/tasks.ts similarity index 100% rename from packages/tao/src/shared/tasks.ts rename to packages/nx/src/shared/tasks.ts diff --git a/packages/tao/src/shared/tree.spec.ts b/packages/nx/src/shared/tree.spec.ts similarity index 100% rename from packages/tao/src/shared/tree.spec.ts rename to packages/nx/src/shared/tree.spec.ts diff --git a/packages/tao/src/shared/tree.ts b/packages/nx/src/shared/tree.ts similarity index 100% rename from packages/tao/src/shared/tree.ts rename to packages/nx/src/shared/tree.ts diff --git a/packages/tao/src/shared/workspace.spec.ts b/packages/nx/src/shared/workspace.spec.ts similarity index 100% rename from packages/tao/src/shared/workspace.spec.ts rename to packages/nx/src/shared/workspace.spec.ts diff --git a/packages/nx/src/shared/workspace.ts b/packages/nx/src/shared/workspace.ts new file mode 100644 index 0000000000000..7ceb7a869d11a --- /dev/null +++ b/packages/nx/src/shared/workspace.ts @@ -0,0 +1,909 @@ +import { existsSync, readFileSync } from 'fs'; +import * as path from 'path'; +import { appRootPath } from '../utils/app-root'; +import { readJsonFile } from '../utils/fileutils'; +import type { NxJsonConfiguration } from './nx'; +import { TaskGraph } from './tasks'; +import { logger } from './logger'; +import { sync as globSync } from 'fast-glob'; +import ignore, { Ignore } from 'ignore'; +import { basename, dirname, join } from 'path'; +import { performance } from 'perf_hooks'; +import { loadNxPlugins } from './nx-plugin'; + +export interface Workspace + extends WorkspaceJsonConfiguration, + NxJsonConfiguration { + projects: Record; +} + +/** + * Workspace configuration + */ +export interface WorkspaceJsonConfiguration { + /** + * Version of the configuration format + */ + version: number; + /** + * Projects' projects + */ + projects: { + [projectName: string]: ProjectConfiguration; + }; +} + +export interface RawWorkspaceJsonConfiguration + extends Omit { + projects: { [projectName: string]: ProjectConfiguration | string }; +} + +/** + * Type of project supported + */ +export type ProjectType = 'library' | 'application'; + +/** + * Project configuration + */ +export interface ProjectConfiguration { + /** + * Project's name. Optional if specified in workspace.json + */ + name?: string; + + /** + * Project's targets + */ + targets?: { [targetName: string]: TargetConfiguration }; + + /** + * Project's location relative to the root of the workspace + */ + root: string; + + /** + * The location of project's sources relative to the root of the workspace + */ + sourceRoot?: string; + + /** + * Project type + */ + projectType?: ProjectType; + + /** + * List of default values used by generators. + * + * These defaults are project specific. + * + * Example: + * + * ``` + * { + * "@nrwl/react": { + * "library": { + * "style": "scss" + * } + * } + * } + * ``` + */ + generators?: { [collectionName: string]: { [generatorName: string]: any } }; + + /** + * List of projects which are added as a dependency + */ + implicitDependencies?: string[]; + + /** + * List of tags used by nx-enforce-module-boundaries / project graph + */ + tags?: string[]; +} + +export interface TargetDependencyConfig { + /** + * This the projects that the targets belong to + * + * 'self': This target depends on another target of the same project + * 'deps': This target depends on targets of the projects of it's deps. + */ + projects: 'self' | 'dependencies'; + + /** + * The name of the target + */ + target: string; +} + +/** + * Target's configuration + */ +export interface TargetConfiguration { + /** + * The executor/builder used to implement the target. + * + * Example: '@nrwl/web:rollup' + */ + executor: string; + + /** + * List of the target's outputs. The outputs will be cached by the Nx computation + * caching engine. + */ + outputs?: string[]; + + /** + * This describes other targets that a target depends on. + */ + dependsOn?: TargetDependencyConfig[]; + + /** + * Target's options. They are passed in to the executor. + */ + options?: any; + + /** + * Sets of options + */ + configurations?: { [config: string]: any }; + + /** + * A default named configuration to use when a target configuration is not provided. + */ + defaultConfiguration?: string; +} + +export function workspaceConfigName(root: string) { + if (existsSync(path.join(root, 'angular.json'))) { + return 'angular.json'; + } else if (existsSync(path.join(root, 'workspace.json'))) { + return 'workspace.json'; + } else { + return null; + } +} + +/** + * A callback function that is executed after changes are made to the file system + */ +export type GeneratorCallback = () => void | Promise; + +/** + * A function that schedules updates to the filesystem to be done atomically + */ +export type Generator = ( + tree, + schema: T +) => void | GeneratorCallback | Promise; + +export interface ExecutorConfig { + schema: any; + hasherFactory?: () => any; + implementationFactory: () => Executor; + batchImplementationFactory?: () => TaskGraphExecutor; +} + +/** + * Implementation of a target of a project + */ +export type Executor = ( + /** + * Options that users configure or pass via the command line + */ + options: T, + context: ExecutorContext +) => + | Promise<{ success: boolean }> + | AsyncIterableIterator<{ success: boolean }>; + +/** + * Implementation of a target of a project that handles multiple projects to be batched + */ +export type TaskGraphExecutor = ( + /** + * Graph of Tasks to be executed + */ + taskGraph: TaskGraph, + /** + * Map of Task IDs to options for the task + */ + options: Record, + /** + * Set of overrides for the overall execution + */ + overrides: T, + context: ExecutorContext +) => Promise>; + +/** + * Context that is passed into an executor + */ +export interface ExecutorContext { + /** + * The root of the workspace + */ + root: string; + + /** + * The name of the project being executed on + */ + projectName?: string; + + /** + * The name of the target being executed + */ + targetName?: string; + + /** + * The name of the configuration being executed + */ + configurationName?: string; + + /** + * The configuration of the target being executed + */ + target?: TargetConfiguration; + + /** + * The full workspace configuration + */ + workspace: WorkspaceJsonConfiguration & NxJsonConfiguration; + + /** + * The current working directory + */ + cwd: string; + + /** + * Enable verbose logging + */ + isVerbose: boolean; +} + +export class Workspaces { + private cachedWorkspaceConfig: WorkspaceJsonConfiguration & + NxJsonConfiguration; + + constructor(private root: string) {} + + relativeCwd(cwd: string) { + return path.relative(this.root, cwd).replace(/\\/g, '/') || null; + } + + calculateDefaultProjectName( + cwd: string, + wc: WorkspaceJsonConfiguration & NxJsonConfiguration + ) { + const relativeCwd = this.relativeCwd(cwd); + if (relativeCwd) { + const matchingProject = Object.keys(wc.projects).find((p) => { + const projectRoot = wc.projects[p].root; + return ( + relativeCwd == projectRoot || + relativeCwd.startsWith(`${projectRoot}/`) + ); + }); + if (matchingProject) return matchingProject; + } + return wc.defaultProject; + } + + readWorkspaceConfiguration(): WorkspaceJsonConfiguration & + NxJsonConfiguration { + if (this.cachedWorkspaceConfig) return this.cachedWorkspaceConfig; + const nxJsonPath = path.join(this.root, 'nx.json'); + const nxJson = readNxJson(nxJsonPath); + const workspaceFile = workspaceConfigName(this.root); + const workspacePath = workspaceFile + ? path.join(this.root, workspaceFile) + : null; + const workspace = + workspacePath && existsSync(workspacePath) + ? this.readFromWorkspaceJson() + : buildWorkspaceConfigurationFromGlobs( + nxJson, + globForProjectFiles(this.root, nxJson), + (path) => readJsonFile(join(this.root, path)) + ); + + assertValidWorkspaceConfiguration(nxJson); + this.cachedWorkspaceConfig = { ...workspace, ...nxJson }; + return this.cachedWorkspaceConfig; + } + + isNxExecutor(nodeModule: string, executor: string) { + const schema = this.readExecutor(nodeModule, executor).schema; + return schema['cli'] === 'nx'; + } + + isNxGenerator(collectionName: string, generatorName: string) { + const schema = this.readGenerator(collectionName, generatorName).schema; + return schema['cli'] === 'nx'; + } + + readExecutor(nodeModule: string, executor: string): ExecutorConfig { + try { + const { executorsFilePath, executorConfig } = this.readExecutorsJson( + nodeModule, + executor + ); + const executorsDir = path.dirname(executorsFilePath); + const schemaPath = path.join(executorsDir, executorConfig.schema || ''); + const schema = readJsonFile(schemaPath); + if (!schema.properties || typeof schema.properties !== 'object') { + schema.properties = {}; + } + const implementationFactory = this.getImplementationFactory( + executorConfig.implementation, + executorsDir + ); + + const batchImplementationFactory = executorConfig.batchImplementation + ? this.getImplementationFactory( + executorConfig.batchImplementation, + executorsDir + ) + : null; + + const hasherFactory = executorConfig.hasher + ? this.getImplementationFactory( + executorConfig.hasher, + executorsDir + ) + : null; + + return { + schema, + implementationFactory, + batchImplementationFactory, + hasherFactory, + }; + } catch (e) { + throw new Error( + `Unable to resolve ${nodeModule}:${executor}.\n${e.message}` + ); + } + } + + readGenerator(collectionName: string, generatorName: string) { + try { + const { generatorsFilePath, generatorsJson, normalizedGeneratorName } = + this.readGeneratorsJson(collectionName, generatorName); + const generatorsDir = path.dirname(generatorsFilePath); + const generatorConfig = + generatorsJson.generators?.[normalizedGeneratorName] || + generatorsJson.schematics?.[normalizedGeneratorName]; + const schemaPath = path.join(generatorsDir, generatorConfig.schema || ''); + const schema = readJsonFile(schemaPath); + if (!schema.properties || typeof schema.properties !== 'object') { + schema.properties = {}; + } + generatorConfig.implementation = + generatorConfig.implementation || generatorConfig.factory; + const implementationFactory = this.getImplementationFactory( + generatorConfig.implementation, + generatorsDir + ); + return { normalizedGeneratorName, schema, implementationFactory }; + } catch (e) { + throw new Error( + `Unable to resolve ${collectionName}:${generatorName}.\n${e.message}` + ); + } + } + + private getImplementationFactory( + implementation: string, + directory: string + ): () => T { + const [implementationModulePath, implementationExportName] = + implementation.split('#'); + return () => { + const module = require(path.join(directory, implementationModulePath)); + return module[implementationExportName || 'default'] as T; + }; + } + + private readExecutorsJson(nodeModule: string, executor: string) { + const packageJsonPath = require.resolve(`${nodeModule}/package.json`, { + paths: this.resolvePaths(), + }); + const packageJson = readJsonFile(packageJsonPath); + const executorsFile = packageJson.executors ?? packageJson.builders; + + if (!executorsFile) { + throw new Error( + `The "${nodeModule}" package does not support Nx executors.` + ); + } + + const executorsFilePath = require.resolve( + path.join(path.dirname(packageJsonPath), executorsFile) + ); + const executorsJson = readJsonFile(executorsFilePath); + const executorConfig: { + implementation: string; + batchImplementation?: string; + schema: string; + hasher?: string; + } = + executorsJson.executors?.[executor] || executorsJson.builders?.[executor]; + if (!executorConfig) { + throw new Error( + `Cannot find executor '${executor}' in ${executorsFilePath}.` + ); + } + return { executorsFilePath, executorConfig }; + } + + private readGeneratorsJson(collectionName: string, generator: string) { + let generatorsFilePath; + if (collectionName.endsWith('.json')) { + generatorsFilePath = require.resolve(collectionName, { + paths: this.resolvePaths(), + }); + } else { + const packageJsonPath = require.resolve( + `${collectionName}/package.json`, + { + paths: this.resolvePaths(), + } + ); + const packageJson = readJsonFile(packageJsonPath); + const generatorsFile = packageJson.generators ?? packageJson.schematics; + + if (!generatorsFile) { + throw new Error( + `The "${collectionName}" package does not support Nx generators.` + ); + } + + generatorsFilePath = require.resolve( + path.join(path.dirname(packageJsonPath), generatorsFile) + ); + } + const generatorsJson = readJsonFile(generatorsFilePath); + + let normalizedGeneratorName = + findFullGeneratorName(generator, generatorsJson.generators) || + findFullGeneratorName(generator, generatorsJson.schematics); + + if (!normalizedGeneratorName) { + for (let parent of generatorsJson.extends || []) { + try { + return this.readGeneratorsJson(parent, generator); + } catch (e) {} + } + + throw new Error( + `Cannot find generator '${generator}' in ${generatorsFilePath}.` + ); + } + return { generatorsFilePath, generatorsJson, normalizedGeneratorName }; + } + + private resolvePaths() { + return this.root ? [this.root, __dirname] : [__dirname]; + } + + private readFromWorkspaceJson() { + const rawWorkspace = readJsonFile( + path.join(this.root, workspaceConfigName(this.root)) + ); + return resolveNewFormatWithInlineProjects(rawWorkspace, this.root); + } +} + +function assertValidWorkspaceConfiguration( + nxJson: NxJsonConfiguration & { projects?: any } +) { + // Assert valid workspace configuration + if (nxJson.projects) { + logger.warn( + 'NX As of Nx 13, project configuration should be moved from nx.json to workspace.json/project.json. Please run "nx format" to fix this.' + ); + } +} + +function findFullGeneratorName( + name: string, + generators: { + [name: string]: { aliases?: string[] }; + } +) { + if (generators) { + for (let [key, data] of Object.entries<{ aliases?: string[] }>( + generators + )) { + if ( + key === name || + (data.aliases && (data.aliases as string[]).includes(name)) + ) { + return key; + } + } + } +} + +export function reformattedWorkspaceJsonOrNull(w: any) { + return w.version === 2 ? toNewFormatOrNull(w) : toOldFormatOrNull(w); +} + +export function toNewFormat(w: any): WorkspaceJsonConfiguration { + const f = toNewFormatOrNull(w); + return f ?? w; +} + +export function toNewFormatOrNull(w: any) { + let formatted = false; + Object.values(w.projects || {}).forEach((projectConfig: any) => { + if (projectConfig.architect) { + renamePropertyWithStableKeys(projectConfig, 'architect', 'targets'); + formatted = true; + } + if (projectConfig.schematics) { + renamePropertyWithStableKeys(projectConfig, 'schematics', 'generators'); + formatted = true; + } + Object.values(projectConfig.targets || {}).forEach((target: any) => { + if (target.builder !== undefined) { + renamePropertyWithStableKeys(target, 'builder', 'executor'); + formatted = true; + } + }); + }); + if (w.schematics) { + renamePropertyWithStableKeys(w, 'schematics', 'generators'); + formatted = true; + } + if (w.version !== 2) { + w.version = 2; + formatted = true; + } + return formatted ? w : null; +} + +export function toOldFormatOrNull(w: any) { + let formatted = false; + + Object.values(w.projects || {}).forEach((projectConfig: any) => { + if (typeof projectConfig === 'string') { + throw new Error( + "'project.json' files are incompatible with version 1 workspace schemas." + ); + } + if (projectConfig.targets) { + renamePropertyWithStableKeys(projectConfig, 'targets', 'architect'); + formatted = true; + } + if (projectConfig.generators) { + renamePropertyWithStableKeys(projectConfig, 'generators', 'schematics'); + formatted = true; + } + Object.values(projectConfig.architect || {}).forEach((target: any) => { + if (target.executor !== undefined) { + renamePropertyWithStableKeys(target, 'executor', 'builder'); + formatted = true; + } + }); + }); + + if (w.generators) { + renamePropertyWithStableKeys(w, 'generators', 'schematics'); + formatted = true; + } + if (w.version !== 1) { + w.version = 1; + formatted = true; + } + return formatted ? w : null; +} + +export function resolveOldFormatWithInlineProjects( + w: any, + root: string = appRootPath +) { + const inlined = inlineProjectConfigurations(w, root); + const formatted = toOldFormatOrNull(inlined); + return formatted ? formatted : inlined; +} + +export function resolveNewFormatWithInlineProjects( + w: any, + root: string = appRootPath +) { + return toNewFormat(inlineProjectConfigurations(w, root)); +} + +function inlineProjectConfigurations(w: any, root: string = appRootPath) { + Object.entries(w.projects || {}).forEach( + ([project, config]: [string, any]) => { + if (typeof config === 'string') { + const configFilePath = path.join(root, config, 'project.json'); + const fileConfig = readJsonFile(configFilePath); + w.projects[project] = fileConfig; + } + } + ); + return w; +} + +/** + * Reads an nx.json file from a given path or extends a local nx.json config. + */ +function readNxJson(nxJson: string): NxJsonConfiguration { + let nxJsonConfig: NxJsonConfiguration; + if (existsSync(nxJson)) { + nxJsonConfig = readJsonFile(nxJson); + } else { + nxJsonConfig = {} as NxJsonConfiguration; + } + if (nxJsonConfig.extends) { + const extendedNxJsonPath = require.resolve(nxJsonConfig.extends, { + paths: [dirname(nxJson)], + }); + const baseNxJson = readJsonFile(extendedNxJsonPath); + nxJsonConfig = { ...baseNxJson, ...nxJsonConfig }; + } + return nxJsonConfig; +} + +/** + * Pulled from toFileName in names from @nrwl/devkit. + * Todo: Should refactor, not duplicate. + */ +export function toProjectName( + fileName: string, + nxJson: NxJsonConfiguration +): string { + const directory = dirname(fileName); + let { appsDir, libsDir } = nxJson?.workspaceLayout || {}; + appsDir ??= 'apps'; + libsDir ??= 'libs'; + const parts = directory.split(/[\/\\]/g); + if ([appsDir, libsDir].includes(parts[0])) { + parts.splice(0, 1); + } + return parts.join('-').toLowerCase(); +} + +let projectGlobCache: string[]; +let projectGlobCacheKey: string; + +function getGlobPatternsFromPlugins(nxJson: NxJsonConfiguration): string[] { + const plugins = loadNxPlugins(nxJson?.plugins); + + const patterns = []; + for (const plugin of plugins) { + if (!plugin.projectFilePatterns) { + continue; + } + for (const filePattern of plugin.projectFilePatterns) { + patterns.push('**/' + filePattern); + } + } + + return patterns; +} + +/** + * Get the package.json globs from package manager workspaces + */ +function getGlobPatternsFromPackageManagerWorkspaces(root: string): string[] { + // TODO: add support for pnpm + try { + const { workspaces } = readJsonFile(join(root, 'package.json')); + + return ( + workspaces?.map((pattern) => pattern + '/package.json') ?? [ + '**/package.json', + ] + ); + } catch { + return ['**/package.json']; + } +} + +export function globForProjectFiles( + root: string, + nxJson?: NxJsonConfiguration +) { + // Deal w/ Caching + const cacheKey = [root, ...(nxJson?.plugins || [])].join(','); + if (projectGlobCache && cacheKey === projectGlobCacheKey) + return projectGlobCache; + projectGlobCacheKey = cacheKey; + + const projectGlobPatterns: string[] = [ + '**/project.json', + ...getGlobPatternsFromPackageManagerWorkspaces(root), + ...getGlobPatternsFromPlugins(nxJson), + ]; + + const combinedProjectGlobPattern = '{' + projectGlobPatterns.join(',') + '}'; + + performance.mark('start-glob-for-projects'); + /** + * This configures the files and directories which we always want to ignore as part of file watching + * and which we know the location of statically (meaning irrespective of user configuration files). + * This has the advantage of being ignored directly within globSync + * + * Other ignored entries will need to be determined dynamically by reading and evaluating the user's + * .gitignore and .nxignore files below. + */ + const ALWAYS_IGNORE = [ + join(root, 'node_modules'), + '**/node_modules', + join(root, 'dist'), + join(root, '.git'), + ]; + + /** + * TODO: This utility has been implemented multiple times across the Nx codebase, + * discuss whether it should be moved to a shared location. + */ + const ig = ignore(); + try { + ig.add(readFileSync(`${root}/.gitignore`, 'utf-8')); + } catch {} + try { + ig.add(readFileSync(`${root}/.nxignore`, 'utf-8')); + } catch {} + + const globResults = globSync(combinedProjectGlobPattern, { + ignore: ALWAYS_IGNORE, + absolute: false, + cwd: root, + }); + projectGlobCache = deduplicateProjectFiles(globResults, ig); + performance.mark('finish-glob-for-projects'); + performance.measure( + 'glob-for-project-files', + 'start-glob-for-projects', + 'finish-glob-for-projects' + ); + return projectGlobCache; +} + +export function deduplicateProjectFiles(files: string[], ig?: Ignore) { + const filtered = new Map(); + files.forEach((file) => { + const projectFolder = dirname(file); + const projectFile = basename(file); + if ( + ig?.ignores(file) || // file is in .gitignore or .nxignore + file === 'package.json' || // file is workspace root package json + // project.json or equivallent inferred project file has been found + (filtered.has(projectFolder) && projectFile !== 'project.json') + ) { + return; + } + + filtered.set(projectFolder, projectFile); + }); + return Array.from(filtered.entries()).map(([folder, file]) => + join(folder, file) + ); +} + +function buildProjectConfigurationFromPackageJson( + path: string, + packageJson: { name: string }, + nxJson: NxJsonConfiguration +): ProjectConfiguration & { name: string } { + const directory = dirname(path).split('\\').join('/'); + const npmPrefix = `@${nxJson.npmScope}/`; + let name = packageJson.name ?? toProjectName(directory, nxJson); + if (name.startsWith(npmPrefix)) { + name = name.replace(npmPrefix, ''); + } + return { + root: directory, + sourceRoot: directory, + name, + }; +} + +export function inferProjectFromNonStandardFile( + file: string, + nxJson: NxJsonConfiguration +): ProjectConfiguration & { name: string } { + const directory = dirname(file).split('\\').join('/'); + + return { + name: toProjectName(file, nxJson), + root: directory, + }; +} + +export function buildWorkspaceConfigurationFromGlobs( + nxJson: NxJsonConfiguration, + projectFiles: string[] = globForProjectFiles(appRootPath, nxJson), // making this parameter allows devkit to pick up newly created projects + readJson: (string) => any = readJsonFile // making this an arg allows us to reuse in devkit +): WorkspaceJsonConfiguration { + const projects: Record = {}; + + for (const file of projectFiles) { + const directory = dirname(file).split('\\').join('/'); + const fileName = basename(file); + + if (fileName === 'project.json') { + // Nx specific project configuration (`project.json` files) in the same + // directory as a package.json should overwrite the inferred package.json + // project configuration. + const configuration = readJson(file); + let name = configuration.name; + if (!configuration.name) { + name = toProjectName(file, nxJson); + } + if (!projects[name]) { + projects[name] = configuration; + } else { + logger.warn( + `Skipping project found at ${directory} since project ${name} already exists at ${projects[name].root}! Specify a unique name for the project to allow Nx to differentiate between the two projects.` + ); + } + } else { + // We can infer projects from package.json files, + // if a package.json file is in a directory w/o a `project.json` file. + // this results in targets being inferred by Nx from package scripts, + // and the root / sourceRoot both being the directory. + if (fileName === 'package.json') { + const { name, ...config } = buildProjectConfigurationFromPackageJson( + file, + readJson(file), + nxJson + ); + if (!projects[name]) { + projects[name] = config; + } else { + logger.warn( + `Skipping project found at ${directory} since project ${name} already exists at ${projects[name].root}! Specify a unique name for the project to allow Nx to differentiate between the two projects.` + ); + } + } else { + // This project was created from an nx plugin. + // The only thing we know about the file is its location + const { name, ...config } = inferProjectFromNonStandardFile( + file, + nxJson + ); + if (!projects[name]) { + projects[name] = config; + } else { + logger.error( + `Skipping project inferred from ${file} since project ${name} already exists.` + ); + throw new Error(); + } + } + } + } + + return { + version: 2, + projects: projects, + }; +} + +// we have to do it this way to preserve the order of properties +// not to screw up the formatting +export function renamePropertyWithStableKeys( + obj: any, + from: string, + to: string +) { + const copy = { ...obj }; + Object.keys(obj).forEach((k) => { + delete obj[k]; + }); + Object.keys(copy).forEach((k) => { + if (k === from) { + obj[to] = copy[k]; + } else { + obj[k] = copy[k]; + } + }); +} diff --git a/packages/workspace/src/utilities/app-root.ts b/packages/nx/src/utils/app-root.ts similarity index 67% rename from packages/workspace/src/utilities/app-root.ts rename to packages/nx/src/utils/app-root.ts index fdc26b036c13e..5557648f37b98 100644 --- a/packages/workspace/src/utilities/app-root.ts +++ b/packages/nx/src/utils/app-root.ts @@ -1,9 +1,6 @@ -import { fileExists } from './fileutils'; import * as path from 'path'; +import { statSync } from 'fs'; -/** - * @deprecated Use appRootPath in tao instead! Will be removed in v13. - */ export const appRootPath = pathInner(__dirname); function pathInner(dir: string): string { @@ -12,6 +9,7 @@ function pathInner(dir: string): string { if (path.dirname(dir) === dir) return process.cwd(); if ( fileExists(path.join(dir, 'workspace.json')) || + fileExists(path.join(dir, 'nx.json')) || fileExists(path.join(dir, 'angular.json')) ) { return dir; @@ -19,3 +17,11 @@ function pathInner(dir: string): string { return pathInner(path.dirname(dir)); } } + +export function fileExists(filePath: string): boolean { + try { + return statSync(filePath).isFile(); + } catch (err) { + return false; + } +} diff --git a/packages/tao/src/utils/fileutils.ts b/packages/nx/src/utils/fileutils.ts similarity index 100% rename from packages/tao/src/utils/fileutils.ts rename to packages/nx/src/utils/fileutils.ts diff --git a/packages/tao/src/utils/json.spec.ts b/packages/nx/src/utils/json.spec.ts similarity index 100% rename from packages/tao/src/utils/json.spec.ts rename to packages/nx/src/utils/json.spec.ts diff --git a/packages/tao/src/utils/json.ts b/packages/nx/src/utils/json.ts similarity index 100% rename from packages/tao/src/utils/json.ts rename to packages/nx/src/utils/json.ts diff --git a/packages/tao/src/utils/object-sort.ts b/packages/nx/src/utils/object-sort.ts similarity index 100% rename from packages/tao/src/utils/object-sort.ts rename to packages/nx/src/utils/object-sort.ts diff --git a/packages/tao/src/utils/register.ts b/packages/nx/src/utils/register.ts similarity index 100% rename from packages/tao/src/utils/register.ts rename to packages/nx/src/utils/register.ts diff --git a/packages/tao/src/utils/split-target.spec.ts b/packages/nx/src/utils/split-target.spec.ts similarity index 100% rename from packages/tao/src/utils/split-target.spec.ts rename to packages/nx/src/utils/split-target.spec.ts diff --git a/packages/tao/src/utils/split-target.ts b/packages/nx/src/utils/split-target.ts similarity index 100% rename from packages/tao/src/utils/split-target.ts rename to packages/nx/src/utils/split-target.ts diff --git a/packages/react-native/plugins/metro-resolver.ts b/packages/react-native/plugins/metro-resolver.ts index b88301791398a..78e6602380af2 100644 --- a/packages/react-native/plugins/metro-resolver.ts +++ b/packages/react-native/plugins/metro-resolver.ts @@ -6,7 +6,7 @@ import { detectPackageManager } from '@nrwl/devkit'; import { CachedInputFileSystem, ResolverFactory } from 'enhanced-resolve'; import { dirname, join } from 'path'; import * as fs from 'fs'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; /* * Use tsconfig to resolve additional workspace libs. diff --git a/packages/react/plugins/storybook/index.spec.ts b/packages/react/plugins/storybook/index.spec.ts index 3c08fb7e90e13..753f728b04c44 100644 --- a/packages/react/plugins/storybook/index.spec.ts +++ b/packages/react/plugins/storybook/index.spec.ts @@ -1,7 +1,7 @@ import { webpack } from './index'; import { join } from 'path'; -import { writeJsonFile } from '@nrwl/tao/src/utils/fileutils'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { writeJsonFile } from 'nx/src/utils/fileutils'; +import { appRootPath } from 'nx/src/utils/app-root'; jest.mock('@nrwl/web/src/utils/web.config', () => { return { getStylesPartial: () => ({}), diff --git a/packages/react/plugins/storybook/index.ts b/packages/react/plugins/storybook/index.ts index 8bfa7fa86f725..4a31211d0bac7 100644 --- a/packages/react/plugins/storybook/index.ts +++ b/packages/react/plugins/storybook/index.ts @@ -1,5 +1,5 @@ import { joinPathFragments, readJsonFile } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { getBaseWebpackPartial } from '@nrwl/web/src/utils/config'; import { getStylesPartial } from '@nrwl/web/src/utils/web.config'; import { checkAndCleanWithSemver } from '@nrwl/workspace/src/utilities/version-utils'; diff --git a/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.spec.ts b/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.spec.ts index 82fea02c5d381..7d1926157078c 100644 --- a/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.spec.ts +++ b/packages/react/src/migrations/update-8-5-0/update-workspace-8-5-0.spec.ts @@ -2,7 +2,7 @@ import { Tree } from '@angular-devkit/schematics'; import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; import { readWorkspace } from '@nrwl/workspace'; -import * as taoWorkspace from '@nrwl/tao/src/shared/workspace'; +import * as nxWorkspace from 'nx/src/shared/workspace'; import * as path from 'path'; @@ -12,7 +12,7 @@ describe('Update 8-5-0', () => { beforeAll(() => { jest - .spyOn(taoWorkspace, 'workspaceConfigName') + .spyOn(nxWorkspace, 'workspaceConfigName') .mockReturnValue('workspace.json'); }); diff --git a/packages/storybook/src/executors/utils.ts b/packages/storybook/src/executors/utils.ts index 726ef94afbaf1..baedebf526ab5 100644 --- a/packages/storybook/src/executors/utils.ts +++ b/packages/storybook/src/executors/utils.ts @@ -5,10 +5,7 @@ import { parseTargetString, readTargetOptions, } from '@nrwl/devkit'; -import { - TargetConfiguration, - Workspaces, -} from '@nrwl/tao/src/shared/workspace'; +import { TargetConfiguration, Workspaces } from 'nx/src/shared/workspace'; import { checkAndCleanWithSemver } from '@nrwl/workspace/src/utilities/version-utils'; import 'dotenv/config'; import { existsSync, readFileSync } from 'fs'; diff --git a/packages/tao/index.ts b/packages/tao/index.ts index 9ab5bef09392d..c4a549e1a9e5c 100644 --- a/packages/tao/index.ts +++ b/packages/tao/index.ts @@ -1,104 +1,2 @@ #!/usr/bin/env node -import { dirname, join } from 'path'; -import { existsSync } from 'fs-extra'; -import * as yargsParser from 'yargs-parser'; - -const argv = yargsParser(process.argv.slice(2), { - configuration: { - 'strip-dashed': true, - 'dot-notation': false, - }, -}); - -export async function invokeCommand( - command: string, - root: string, - commandArgs: string[] = [] -) { - if (!command) { - command = 'help'; - } - - let verboseFlagIndex = commandArgs.indexOf('--verbose'); - if (verboseFlagIndex < 0) { - verboseFlagIndex = commandArgs.indexOf('-v'); - } - const isVerbose = verboseFlagIndex >= 0; - if (isVerbose) { - commandArgs.splice(verboseFlagIndex, 1); - } - - switch (command) { - case 'new': - return (await import('./src/commands/generate')).taoNew( - root, - commandArgs, - isVerbose - ); - case 'generate': - case 'g': - return (await import('./src/commands/generate')).generate( - process.cwd(), - root, - commandArgs, - isVerbose - ); - case 'run': - case 'r': - return (await import('./src/commands/run')).run( - process.cwd(), - root, - commandArgs, - isVerbose - ); - case 'migrate': - return (await import('./src/commands/migrate')).migrate( - root, - commandArgs, - isVerbose - ); - case 'help': - case '--help': - return (await import('./src/commands/help')).help(); - - default: { - const projectNameIncluded = - commandArgs[0] && !commandArgs[0].startsWith('-'); - const projectName = projectNameIncluded ? commandArgs[0] : ''; - // this is to make `tao test mylib` same as `tao run mylib:test` - return (await import('./src/commands/run')).run( - process.cwd(), - root, - [ - `${projectName}:${command}`, - ...(projectNameIncluded ? commandArgs.slice(1) : commandArgs), - ], - isVerbose - ); - } - } -} - -function findWorkspaceRoot(dir: string): string { - if (dirname(dir) === dir) { - throw new Error(`The cwd isn't part of an Nx workspace`); - } - if ( - existsSync(join(dir, 'angular.json')) || - existsSync(join(dir, 'workspace.json')) || - existsSync(join(dir, 'nx.json')) - ) { - return dir; - } - return findWorkspaceRoot(dirname(dir)); -} - -export async function invokeCli(root: string, args: string[]) { - const [command, ...commandArgs] = args; - process.exit(await invokeCommand(command, root, commandArgs)); -} - -invokeCli( - argv.nxWorkspaceRoot || findWorkspaceRoot(process.cwd()), - process.argv.slice(2) -); +require('nx/bin/nx'); diff --git a/packages/tao/package.json b/packages/tao/package.json index 3798c71a5888d..70081c6ba3876 100644 --- a/packages/tao/package.json +++ b/packages/tao/package.json @@ -30,20 +30,6 @@ }, "homepage": "https://nx.dev", "dependencies": { - "@swc/core": "^1.2.146", - "@swc-node/register": "^1.4.2", - "chalk": "4.1.0", - "enquirer": "~2.3.6", - "fast-glob": "3.2.7", - "fs-extra": "^9.1.0", - "ignore": "^5.0.4", - "jsonc-parser": "3.0.0", - "rxjs-for-await": "0.0.2", - "rxjs": "^6.5.4", - "semver": "7.3.4", - "tmp": "~0.2.1", - "tslib": "^2.3.0", - "tsconfig-paths": "^3.9.0", - "yargs-parser": "20.0.0" + "nx": "*" } } diff --git a/packages/tao/project.json b/packages/tao/project.json index ba578c26c7a9f..12515968929bb 100644 --- a/packages/tao/project.json +++ b/packages/tao/project.json @@ -61,9 +61,6 @@ }, { "command": "node ./scripts/copy-readme.js tao" - }, - { - "command": "node ./scripts/add-dependency-to-build.js tao nx" } ], "parallel": false diff --git a/packages/tao/src/shared/logger.ts b/packages/tao/src/shared/logger.ts index ba6e18dbc3ba3..f6e4e47d1d84b 100644 --- a/packages/tao/src/shared/logger.ts +++ b/packages/tao/src/shared/logger.ts @@ -1,46 +1 @@ -import * as chalk from 'chalk'; - -export const NX_PREFIX = `${chalk.cyan('>')} ${chalk.inverse( - chalk.bold(chalk.cyan(' NX ')) -)}`; - -export const NX_ERROR = chalk.inverse(chalk.bold(chalk.red(' ERROR '))); - -export const logger = { - warn: (s) => console.warn(chalk.bold(chalk.yellow(s))), - error: (s) => { - if (typeof s === 'string' && s.startsWith('NX ')) { - console.error(`\n${NX_ERROR} ${chalk.bold(chalk.red(s.substr(3)))}\n`); - } else if (s instanceof Error && s.stack) { - console.error(chalk.bold(chalk.red(s.stack))); - } else { - console.error(chalk.bold(chalk.red(s))); - } - }, - info: (s) => { - if (typeof s === 'string' && s.startsWith('NX ')) { - console.info(`\n${NX_PREFIX} ${chalk.bold(s.substr(3))}\n`); - } else { - console.info(s); - } - }, - log: (...s) => { - console.log(...s); - }, - debug: (...s) => { - console.debug(...s); - }, - fatal: (...s) => { - console.error(...s); - }, -}; - -export function stripIndent(str: string): string { - const match = str.match(/^[ \t]*(?=\S)/gm); - if (!match) { - return str; - } - const indent = match.reduce((r, a) => Math.min(r, a.length), Infinity); - const regex = new RegExp(`^[ \\t]{${indent}}`, 'gm'); - return str.replace(regex, ''); -} +require('nx/src/shared/logger'); diff --git a/packages/tao/src/shared/workspace.ts b/packages/tao/src/shared/workspace.ts index 7ceb7a869d11a..8f8d03af0650c 100644 --- a/packages/tao/src/shared/workspace.ts +++ b/packages/tao/src/shared/workspace.ts @@ -1,909 +1 @@ -import { existsSync, readFileSync } from 'fs'; -import * as path from 'path'; -import { appRootPath } from '../utils/app-root'; -import { readJsonFile } from '../utils/fileutils'; -import type { NxJsonConfiguration } from './nx'; -import { TaskGraph } from './tasks'; -import { logger } from './logger'; -import { sync as globSync } from 'fast-glob'; -import ignore, { Ignore } from 'ignore'; -import { basename, dirname, join } from 'path'; -import { performance } from 'perf_hooks'; -import { loadNxPlugins } from './nx-plugin'; - -export interface Workspace - extends WorkspaceJsonConfiguration, - NxJsonConfiguration { - projects: Record; -} - -/** - * Workspace configuration - */ -export interface WorkspaceJsonConfiguration { - /** - * Version of the configuration format - */ - version: number; - /** - * Projects' projects - */ - projects: { - [projectName: string]: ProjectConfiguration; - }; -} - -export interface RawWorkspaceJsonConfiguration - extends Omit { - projects: { [projectName: string]: ProjectConfiguration | string }; -} - -/** - * Type of project supported - */ -export type ProjectType = 'library' | 'application'; - -/** - * Project configuration - */ -export interface ProjectConfiguration { - /** - * Project's name. Optional if specified in workspace.json - */ - name?: string; - - /** - * Project's targets - */ - targets?: { [targetName: string]: TargetConfiguration }; - - /** - * Project's location relative to the root of the workspace - */ - root: string; - - /** - * The location of project's sources relative to the root of the workspace - */ - sourceRoot?: string; - - /** - * Project type - */ - projectType?: ProjectType; - - /** - * List of default values used by generators. - * - * These defaults are project specific. - * - * Example: - * - * ``` - * { - * "@nrwl/react": { - * "library": { - * "style": "scss" - * } - * } - * } - * ``` - */ - generators?: { [collectionName: string]: { [generatorName: string]: any } }; - - /** - * List of projects which are added as a dependency - */ - implicitDependencies?: string[]; - - /** - * List of tags used by nx-enforce-module-boundaries / project graph - */ - tags?: string[]; -} - -export interface TargetDependencyConfig { - /** - * This the projects that the targets belong to - * - * 'self': This target depends on another target of the same project - * 'deps': This target depends on targets of the projects of it's deps. - */ - projects: 'self' | 'dependencies'; - - /** - * The name of the target - */ - target: string; -} - -/** - * Target's configuration - */ -export interface TargetConfiguration { - /** - * The executor/builder used to implement the target. - * - * Example: '@nrwl/web:rollup' - */ - executor: string; - - /** - * List of the target's outputs. The outputs will be cached by the Nx computation - * caching engine. - */ - outputs?: string[]; - - /** - * This describes other targets that a target depends on. - */ - dependsOn?: TargetDependencyConfig[]; - - /** - * Target's options. They are passed in to the executor. - */ - options?: any; - - /** - * Sets of options - */ - configurations?: { [config: string]: any }; - - /** - * A default named configuration to use when a target configuration is not provided. - */ - defaultConfiguration?: string; -} - -export function workspaceConfigName(root: string) { - if (existsSync(path.join(root, 'angular.json'))) { - return 'angular.json'; - } else if (existsSync(path.join(root, 'workspace.json'))) { - return 'workspace.json'; - } else { - return null; - } -} - -/** - * A callback function that is executed after changes are made to the file system - */ -export type GeneratorCallback = () => void | Promise; - -/** - * A function that schedules updates to the filesystem to be done atomically - */ -export type Generator = ( - tree, - schema: T -) => void | GeneratorCallback | Promise; - -export interface ExecutorConfig { - schema: any; - hasherFactory?: () => any; - implementationFactory: () => Executor; - batchImplementationFactory?: () => TaskGraphExecutor; -} - -/** - * Implementation of a target of a project - */ -export type Executor = ( - /** - * Options that users configure or pass via the command line - */ - options: T, - context: ExecutorContext -) => - | Promise<{ success: boolean }> - | AsyncIterableIterator<{ success: boolean }>; - -/** - * Implementation of a target of a project that handles multiple projects to be batched - */ -export type TaskGraphExecutor = ( - /** - * Graph of Tasks to be executed - */ - taskGraph: TaskGraph, - /** - * Map of Task IDs to options for the task - */ - options: Record, - /** - * Set of overrides for the overall execution - */ - overrides: T, - context: ExecutorContext -) => Promise>; - -/** - * Context that is passed into an executor - */ -export interface ExecutorContext { - /** - * The root of the workspace - */ - root: string; - - /** - * The name of the project being executed on - */ - projectName?: string; - - /** - * The name of the target being executed - */ - targetName?: string; - - /** - * The name of the configuration being executed - */ - configurationName?: string; - - /** - * The configuration of the target being executed - */ - target?: TargetConfiguration; - - /** - * The full workspace configuration - */ - workspace: WorkspaceJsonConfiguration & NxJsonConfiguration; - - /** - * The current working directory - */ - cwd: string; - - /** - * Enable verbose logging - */ - isVerbose: boolean; -} - -export class Workspaces { - private cachedWorkspaceConfig: WorkspaceJsonConfiguration & - NxJsonConfiguration; - - constructor(private root: string) {} - - relativeCwd(cwd: string) { - return path.relative(this.root, cwd).replace(/\\/g, '/') || null; - } - - calculateDefaultProjectName( - cwd: string, - wc: WorkspaceJsonConfiguration & NxJsonConfiguration - ) { - const relativeCwd = this.relativeCwd(cwd); - if (relativeCwd) { - const matchingProject = Object.keys(wc.projects).find((p) => { - const projectRoot = wc.projects[p].root; - return ( - relativeCwd == projectRoot || - relativeCwd.startsWith(`${projectRoot}/`) - ); - }); - if (matchingProject) return matchingProject; - } - return wc.defaultProject; - } - - readWorkspaceConfiguration(): WorkspaceJsonConfiguration & - NxJsonConfiguration { - if (this.cachedWorkspaceConfig) return this.cachedWorkspaceConfig; - const nxJsonPath = path.join(this.root, 'nx.json'); - const nxJson = readNxJson(nxJsonPath); - const workspaceFile = workspaceConfigName(this.root); - const workspacePath = workspaceFile - ? path.join(this.root, workspaceFile) - : null; - const workspace = - workspacePath && existsSync(workspacePath) - ? this.readFromWorkspaceJson() - : buildWorkspaceConfigurationFromGlobs( - nxJson, - globForProjectFiles(this.root, nxJson), - (path) => readJsonFile(join(this.root, path)) - ); - - assertValidWorkspaceConfiguration(nxJson); - this.cachedWorkspaceConfig = { ...workspace, ...nxJson }; - return this.cachedWorkspaceConfig; - } - - isNxExecutor(nodeModule: string, executor: string) { - const schema = this.readExecutor(nodeModule, executor).schema; - return schema['cli'] === 'nx'; - } - - isNxGenerator(collectionName: string, generatorName: string) { - const schema = this.readGenerator(collectionName, generatorName).schema; - return schema['cli'] === 'nx'; - } - - readExecutor(nodeModule: string, executor: string): ExecutorConfig { - try { - const { executorsFilePath, executorConfig } = this.readExecutorsJson( - nodeModule, - executor - ); - const executorsDir = path.dirname(executorsFilePath); - const schemaPath = path.join(executorsDir, executorConfig.schema || ''); - const schema = readJsonFile(schemaPath); - if (!schema.properties || typeof schema.properties !== 'object') { - schema.properties = {}; - } - const implementationFactory = this.getImplementationFactory( - executorConfig.implementation, - executorsDir - ); - - const batchImplementationFactory = executorConfig.batchImplementation - ? this.getImplementationFactory( - executorConfig.batchImplementation, - executorsDir - ) - : null; - - const hasherFactory = executorConfig.hasher - ? this.getImplementationFactory( - executorConfig.hasher, - executorsDir - ) - : null; - - return { - schema, - implementationFactory, - batchImplementationFactory, - hasherFactory, - }; - } catch (e) { - throw new Error( - `Unable to resolve ${nodeModule}:${executor}.\n${e.message}` - ); - } - } - - readGenerator(collectionName: string, generatorName: string) { - try { - const { generatorsFilePath, generatorsJson, normalizedGeneratorName } = - this.readGeneratorsJson(collectionName, generatorName); - const generatorsDir = path.dirname(generatorsFilePath); - const generatorConfig = - generatorsJson.generators?.[normalizedGeneratorName] || - generatorsJson.schematics?.[normalizedGeneratorName]; - const schemaPath = path.join(generatorsDir, generatorConfig.schema || ''); - const schema = readJsonFile(schemaPath); - if (!schema.properties || typeof schema.properties !== 'object') { - schema.properties = {}; - } - generatorConfig.implementation = - generatorConfig.implementation || generatorConfig.factory; - const implementationFactory = this.getImplementationFactory( - generatorConfig.implementation, - generatorsDir - ); - return { normalizedGeneratorName, schema, implementationFactory }; - } catch (e) { - throw new Error( - `Unable to resolve ${collectionName}:${generatorName}.\n${e.message}` - ); - } - } - - private getImplementationFactory( - implementation: string, - directory: string - ): () => T { - const [implementationModulePath, implementationExportName] = - implementation.split('#'); - return () => { - const module = require(path.join(directory, implementationModulePath)); - return module[implementationExportName || 'default'] as T; - }; - } - - private readExecutorsJson(nodeModule: string, executor: string) { - const packageJsonPath = require.resolve(`${nodeModule}/package.json`, { - paths: this.resolvePaths(), - }); - const packageJson = readJsonFile(packageJsonPath); - const executorsFile = packageJson.executors ?? packageJson.builders; - - if (!executorsFile) { - throw new Error( - `The "${nodeModule}" package does not support Nx executors.` - ); - } - - const executorsFilePath = require.resolve( - path.join(path.dirname(packageJsonPath), executorsFile) - ); - const executorsJson = readJsonFile(executorsFilePath); - const executorConfig: { - implementation: string; - batchImplementation?: string; - schema: string; - hasher?: string; - } = - executorsJson.executors?.[executor] || executorsJson.builders?.[executor]; - if (!executorConfig) { - throw new Error( - `Cannot find executor '${executor}' in ${executorsFilePath}.` - ); - } - return { executorsFilePath, executorConfig }; - } - - private readGeneratorsJson(collectionName: string, generator: string) { - let generatorsFilePath; - if (collectionName.endsWith('.json')) { - generatorsFilePath = require.resolve(collectionName, { - paths: this.resolvePaths(), - }); - } else { - const packageJsonPath = require.resolve( - `${collectionName}/package.json`, - { - paths: this.resolvePaths(), - } - ); - const packageJson = readJsonFile(packageJsonPath); - const generatorsFile = packageJson.generators ?? packageJson.schematics; - - if (!generatorsFile) { - throw new Error( - `The "${collectionName}" package does not support Nx generators.` - ); - } - - generatorsFilePath = require.resolve( - path.join(path.dirname(packageJsonPath), generatorsFile) - ); - } - const generatorsJson = readJsonFile(generatorsFilePath); - - let normalizedGeneratorName = - findFullGeneratorName(generator, generatorsJson.generators) || - findFullGeneratorName(generator, generatorsJson.schematics); - - if (!normalizedGeneratorName) { - for (let parent of generatorsJson.extends || []) { - try { - return this.readGeneratorsJson(parent, generator); - } catch (e) {} - } - - throw new Error( - `Cannot find generator '${generator}' in ${generatorsFilePath}.` - ); - } - return { generatorsFilePath, generatorsJson, normalizedGeneratorName }; - } - - private resolvePaths() { - return this.root ? [this.root, __dirname] : [__dirname]; - } - - private readFromWorkspaceJson() { - const rawWorkspace = readJsonFile( - path.join(this.root, workspaceConfigName(this.root)) - ); - return resolveNewFormatWithInlineProjects(rawWorkspace, this.root); - } -} - -function assertValidWorkspaceConfiguration( - nxJson: NxJsonConfiguration & { projects?: any } -) { - // Assert valid workspace configuration - if (nxJson.projects) { - logger.warn( - 'NX As of Nx 13, project configuration should be moved from nx.json to workspace.json/project.json. Please run "nx format" to fix this.' - ); - } -} - -function findFullGeneratorName( - name: string, - generators: { - [name: string]: { aliases?: string[] }; - } -) { - if (generators) { - for (let [key, data] of Object.entries<{ aliases?: string[] }>( - generators - )) { - if ( - key === name || - (data.aliases && (data.aliases as string[]).includes(name)) - ) { - return key; - } - } - } -} - -export function reformattedWorkspaceJsonOrNull(w: any) { - return w.version === 2 ? toNewFormatOrNull(w) : toOldFormatOrNull(w); -} - -export function toNewFormat(w: any): WorkspaceJsonConfiguration { - const f = toNewFormatOrNull(w); - return f ?? w; -} - -export function toNewFormatOrNull(w: any) { - let formatted = false; - Object.values(w.projects || {}).forEach((projectConfig: any) => { - if (projectConfig.architect) { - renamePropertyWithStableKeys(projectConfig, 'architect', 'targets'); - formatted = true; - } - if (projectConfig.schematics) { - renamePropertyWithStableKeys(projectConfig, 'schematics', 'generators'); - formatted = true; - } - Object.values(projectConfig.targets || {}).forEach((target: any) => { - if (target.builder !== undefined) { - renamePropertyWithStableKeys(target, 'builder', 'executor'); - formatted = true; - } - }); - }); - if (w.schematics) { - renamePropertyWithStableKeys(w, 'schematics', 'generators'); - formatted = true; - } - if (w.version !== 2) { - w.version = 2; - formatted = true; - } - return formatted ? w : null; -} - -export function toOldFormatOrNull(w: any) { - let formatted = false; - - Object.values(w.projects || {}).forEach((projectConfig: any) => { - if (typeof projectConfig === 'string') { - throw new Error( - "'project.json' files are incompatible with version 1 workspace schemas." - ); - } - if (projectConfig.targets) { - renamePropertyWithStableKeys(projectConfig, 'targets', 'architect'); - formatted = true; - } - if (projectConfig.generators) { - renamePropertyWithStableKeys(projectConfig, 'generators', 'schematics'); - formatted = true; - } - Object.values(projectConfig.architect || {}).forEach((target: any) => { - if (target.executor !== undefined) { - renamePropertyWithStableKeys(target, 'executor', 'builder'); - formatted = true; - } - }); - }); - - if (w.generators) { - renamePropertyWithStableKeys(w, 'generators', 'schematics'); - formatted = true; - } - if (w.version !== 1) { - w.version = 1; - formatted = true; - } - return formatted ? w : null; -} - -export function resolveOldFormatWithInlineProjects( - w: any, - root: string = appRootPath -) { - const inlined = inlineProjectConfigurations(w, root); - const formatted = toOldFormatOrNull(inlined); - return formatted ? formatted : inlined; -} - -export function resolveNewFormatWithInlineProjects( - w: any, - root: string = appRootPath -) { - return toNewFormat(inlineProjectConfigurations(w, root)); -} - -function inlineProjectConfigurations(w: any, root: string = appRootPath) { - Object.entries(w.projects || {}).forEach( - ([project, config]: [string, any]) => { - if (typeof config === 'string') { - const configFilePath = path.join(root, config, 'project.json'); - const fileConfig = readJsonFile(configFilePath); - w.projects[project] = fileConfig; - } - } - ); - return w; -} - -/** - * Reads an nx.json file from a given path or extends a local nx.json config. - */ -function readNxJson(nxJson: string): NxJsonConfiguration { - let nxJsonConfig: NxJsonConfiguration; - if (existsSync(nxJson)) { - nxJsonConfig = readJsonFile(nxJson); - } else { - nxJsonConfig = {} as NxJsonConfiguration; - } - if (nxJsonConfig.extends) { - const extendedNxJsonPath = require.resolve(nxJsonConfig.extends, { - paths: [dirname(nxJson)], - }); - const baseNxJson = readJsonFile(extendedNxJsonPath); - nxJsonConfig = { ...baseNxJson, ...nxJsonConfig }; - } - return nxJsonConfig; -} - -/** - * Pulled from toFileName in names from @nrwl/devkit. - * Todo: Should refactor, not duplicate. - */ -export function toProjectName( - fileName: string, - nxJson: NxJsonConfiguration -): string { - const directory = dirname(fileName); - let { appsDir, libsDir } = nxJson?.workspaceLayout || {}; - appsDir ??= 'apps'; - libsDir ??= 'libs'; - const parts = directory.split(/[\/\\]/g); - if ([appsDir, libsDir].includes(parts[0])) { - parts.splice(0, 1); - } - return parts.join('-').toLowerCase(); -} - -let projectGlobCache: string[]; -let projectGlobCacheKey: string; - -function getGlobPatternsFromPlugins(nxJson: NxJsonConfiguration): string[] { - const plugins = loadNxPlugins(nxJson?.plugins); - - const patterns = []; - for (const plugin of plugins) { - if (!plugin.projectFilePatterns) { - continue; - } - for (const filePattern of plugin.projectFilePatterns) { - patterns.push('**/' + filePattern); - } - } - - return patterns; -} - -/** - * Get the package.json globs from package manager workspaces - */ -function getGlobPatternsFromPackageManagerWorkspaces(root: string): string[] { - // TODO: add support for pnpm - try { - const { workspaces } = readJsonFile(join(root, 'package.json')); - - return ( - workspaces?.map((pattern) => pattern + '/package.json') ?? [ - '**/package.json', - ] - ); - } catch { - return ['**/package.json']; - } -} - -export function globForProjectFiles( - root: string, - nxJson?: NxJsonConfiguration -) { - // Deal w/ Caching - const cacheKey = [root, ...(nxJson?.plugins || [])].join(','); - if (projectGlobCache && cacheKey === projectGlobCacheKey) - return projectGlobCache; - projectGlobCacheKey = cacheKey; - - const projectGlobPatterns: string[] = [ - '**/project.json', - ...getGlobPatternsFromPackageManagerWorkspaces(root), - ...getGlobPatternsFromPlugins(nxJson), - ]; - - const combinedProjectGlobPattern = '{' + projectGlobPatterns.join(',') + '}'; - - performance.mark('start-glob-for-projects'); - /** - * This configures the files and directories which we always want to ignore as part of file watching - * and which we know the location of statically (meaning irrespective of user configuration files). - * This has the advantage of being ignored directly within globSync - * - * Other ignored entries will need to be determined dynamically by reading and evaluating the user's - * .gitignore and .nxignore files below. - */ - const ALWAYS_IGNORE = [ - join(root, 'node_modules'), - '**/node_modules', - join(root, 'dist'), - join(root, '.git'), - ]; - - /** - * TODO: This utility has been implemented multiple times across the Nx codebase, - * discuss whether it should be moved to a shared location. - */ - const ig = ignore(); - try { - ig.add(readFileSync(`${root}/.gitignore`, 'utf-8')); - } catch {} - try { - ig.add(readFileSync(`${root}/.nxignore`, 'utf-8')); - } catch {} - - const globResults = globSync(combinedProjectGlobPattern, { - ignore: ALWAYS_IGNORE, - absolute: false, - cwd: root, - }); - projectGlobCache = deduplicateProjectFiles(globResults, ig); - performance.mark('finish-glob-for-projects'); - performance.measure( - 'glob-for-project-files', - 'start-glob-for-projects', - 'finish-glob-for-projects' - ); - return projectGlobCache; -} - -export function deduplicateProjectFiles(files: string[], ig?: Ignore) { - const filtered = new Map(); - files.forEach((file) => { - const projectFolder = dirname(file); - const projectFile = basename(file); - if ( - ig?.ignores(file) || // file is in .gitignore or .nxignore - file === 'package.json' || // file is workspace root package json - // project.json or equivallent inferred project file has been found - (filtered.has(projectFolder) && projectFile !== 'project.json') - ) { - return; - } - - filtered.set(projectFolder, projectFile); - }); - return Array.from(filtered.entries()).map(([folder, file]) => - join(folder, file) - ); -} - -function buildProjectConfigurationFromPackageJson( - path: string, - packageJson: { name: string }, - nxJson: NxJsonConfiguration -): ProjectConfiguration & { name: string } { - const directory = dirname(path).split('\\').join('/'); - const npmPrefix = `@${nxJson.npmScope}/`; - let name = packageJson.name ?? toProjectName(directory, nxJson); - if (name.startsWith(npmPrefix)) { - name = name.replace(npmPrefix, ''); - } - return { - root: directory, - sourceRoot: directory, - name, - }; -} - -export function inferProjectFromNonStandardFile( - file: string, - nxJson: NxJsonConfiguration -): ProjectConfiguration & { name: string } { - const directory = dirname(file).split('\\').join('/'); - - return { - name: toProjectName(file, nxJson), - root: directory, - }; -} - -export function buildWorkspaceConfigurationFromGlobs( - nxJson: NxJsonConfiguration, - projectFiles: string[] = globForProjectFiles(appRootPath, nxJson), // making this parameter allows devkit to pick up newly created projects - readJson: (string) => any = readJsonFile // making this an arg allows us to reuse in devkit -): WorkspaceJsonConfiguration { - const projects: Record = {}; - - for (const file of projectFiles) { - const directory = dirname(file).split('\\').join('/'); - const fileName = basename(file); - - if (fileName === 'project.json') { - // Nx specific project configuration (`project.json` files) in the same - // directory as a package.json should overwrite the inferred package.json - // project configuration. - const configuration = readJson(file); - let name = configuration.name; - if (!configuration.name) { - name = toProjectName(file, nxJson); - } - if (!projects[name]) { - projects[name] = configuration; - } else { - logger.warn( - `Skipping project found at ${directory} since project ${name} already exists at ${projects[name].root}! Specify a unique name for the project to allow Nx to differentiate between the two projects.` - ); - } - } else { - // We can infer projects from package.json files, - // if a package.json file is in a directory w/o a `project.json` file. - // this results in targets being inferred by Nx from package scripts, - // and the root / sourceRoot both being the directory. - if (fileName === 'package.json') { - const { name, ...config } = buildProjectConfigurationFromPackageJson( - file, - readJson(file), - nxJson - ); - if (!projects[name]) { - projects[name] = config; - } else { - logger.warn( - `Skipping project found at ${directory} since project ${name} already exists at ${projects[name].root}! Specify a unique name for the project to allow Nx to differentiate between the two projects.` - ); - } - } else { - // This project was created from an nx plugin. - // The only thing we know about the file is its location - const { name, ...config } = inferProjectFromNonStandardFile( - file, - nxJson - ); - if (!projects[name]) { - projects[name] = config; - } else { - logger.error( - `Skipping project inferred from ${file} since project ${name} already exists.` - ); - throw new Error(); - } - } - } - } - - return { - version: 2, - projects: projects, - }; -} - -// we have to do it this way to preserve the order of properties -// not to screw up the formatting -export function renamePropertyWithStableKeys( - obj: any, - from: string, - to: string -) { - const copy = { ...obj }; - Object.keys(obj).forEach((k) => { - delete obj[k]; - }); - Object.keys(copy).forEach((k) => { - if (k === from) { - obj[to] = copy[k]; - } else { - obj[k] = copy[k]; - } - }); -} +require('nx/src/shared/workspace'); diff --git a/packages/tao/src/utils/app-root.ts b/packages/tao/src/utils/app-root.ts index 5557648f37b98..eb6e40477ac5d 100644 --- a/packages/tao/src/utils/app-root.ts +++ b/packages/tao/src/utils/app-root.ts @@ -1,27 +1 @@ -import * as path from 'path'; -import { statSync } from 'fs'; - -export const appRootPath = pathInner(__dirname); - -function pathInner(dir: string): string { - if (process.env.NX_WORKSPACE_ROOT_PATH) - return process.env.NX_WORKSPACE_ROOT_PATH; - if (path.dirname(dir) === dir) return process.cwd(); - if ( - fileExists(path.join(dir, 'workspace.json')) || - fileExists(path.join(dir, 'nx.json')) || - fileExists(path.join(dir, 'angular.json')) - ) { - return dir; - } else { - return pathInner(path.dirname(dir)); - } -} - -export function fileExists(filePath: string): boolean { - try { - return statSync(filePath).isFile(); - } catch (err) { - return false; - } -} +require('nx/src/utils/app-root'); diff --git a/packages/workspace/migrations.json b/packages/workspace/migrations.json index 0c64d1edc4dfb..6520785a9ef2a 100644 --- a/packages/workspace/migrations.json +++ b/packages/workspace/migrations.json @@ -1,85 +1,5 @@ { "schematics": { - "add-default-branch-to-nx-json": { - "version": "10.0.0-beta.0", - "description": "Add default branch to nx.json", - "factory": "./src/migrations/update-10-0-0/update-10-0-0" - }, - "solution-tsconfigs": { - "version": "10.0.0-beta.0", - "description": "Migrate tsconfigs to solution style tsconfigs", - "factory": "./src/migrations/update-10-0-0/solution-tsconfigs" - }, - "migrate-eslintrc-tsconfig": { - "version": "10.0.1-beta.0", - "description": "Migrate .eslintrc files to reference new tsconfig", - "factory": "./src/migrations/update-10-0-1/migrate-eslintrc" - }, - "migrate-eslintrc-tsconfig-wildcard": { - "version": "10.1.0-beta.0", - "description": "Migrate .eslintrc files to use tsconfig with a wildcard", - "factory": "./src/migrations/update-10-1-0/migrate-eslintrc-tsconfig-wildcard" - }, - "add-cli-dependency": { - "version": "10.3.0-beta.0", - "description": "Add @nrwl/cli as dependency", - "factory": "./src/migrations/update-10-3-0/add-cli-dependency" - }, - "update-10-3-0": { - "version": "10.3.0-beta.0", - "description": "Update typescript to v4", - "factory": "./src/migrations/update-10-3-0/update-typescript" - }, - "add-vscode-extensions": { - "version": "10.3.0-beta.1", - "description": "Adds .vscode/extensions.json to a workspace", - "factory": "./src/migrations/update-10-3-0/add-vscode-extensions" - }, - "add-buildable-project-deps-in-package-json-type": { - "version": "10.3.0-beta.0", - "description": "Adds `buildableProjectDepsInPackageJsonType` for web and angular package builders", - "factory": "./src/migrations/update-10-3-0/add-buildable-project-deps-in-package-json-type" - }, - "add-explicit-dep-on-tao": { - "version": "10.4.0-beta.5", - "description": "Add an explicit dependency on @nrwl/tao", - "factory": "./src/migrations/update-10-4-0/add-explicit-dep-on-tao" - }, - "update-script-to-invoke-nx-migrate": { - "version": "10.4.5", - "description": "Update the 'update' npm script to invoke nx migrate", - "factory": "./src/migrations/update-10-4-0/update-script-to-invoke-nx-migrate" - }, - "update-decorate-angular-cli": { - "version": "11.0.0-beta.3", - "description": "Update the decoration script when using Angular CLI", - "factory": "./src/migrations/update-11-0-0/update-decorate-angular-cli" - }, - "update-node-types": { - "version": "11.0.0-beta.3", - "description": "Update the @types/node package", - "factory": "./src/migrations/update-11-0-0/update-node-types" - }, - "rename-workspace-schematics": { - "version": "11.0.0-beta.3", - "description": "Rename tools/schematics into tools/generators", - "factory": "./src/migrations/update-11-0-0/rename-workspace-schematics" - }, - "add-outputs-in-workspace": { - "version": "11.0.0-beta.15", - "description": "Adds `outputs` based on builders", - "factory": "./src/migrations/update-11-0-0/add-outputs-in-workspace" - }, - "update-command-check": { - "version": "11.0.0", - "description": "Check that the right update command is used", - "factory": "./src/migrations/update-11-0-0/update-command-check" - }, - "rename-workspace-schematic-script": { - "version": "11.0.2", - "description": "Rename the workspace-schematic script into workspace-generator script", - "factory": "./src/migrations/update-11-0-0/rename-workspace-schematic-script" - }, "add-target-dependencies": { "version": "12.5.0-beta.1", "description": "Rename the workspace-schematic script into workspace-generator script", @@ -115,216 +35,15 @@ "description": "Remove old options that are no longer used", "cli": "nx", "implementation": "./src/migrations/update-13-6-0/remove-old-task-runner-options" + }, + "13-9-0-update-decorate-cli": { + "version": "13.9.0-beta.0", + "description": "Update the decorate-angular-cli script to require nx instead of @nrwl/cli", + "cli": "nx", + "implementation": "./src/migrations/update-13-9-0/update-decorate-cli" } }, "packageJsonUpdates": { - "10.0.0": { - "version": "10.0.0-beta.1", - "packages": { - "@angular/cli": { - "version": "~10.0.0", - "alwaysAddToPackageJson": false - }, - "typescript": { - "version": "~3.9.3", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/architect": { - "version": "~0.1000.0", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/build-angular": { - "version": "~0.1000.0", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/build-ng-packagr": { - "version": "~0.1000.0", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/build-webpack": { - "version": "~0.1000.0", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/build-optimizer": { - "version": "~0.1000.0", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/core": { - "version": "~10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/schematics": { - "version": "~10.0.0", - "alwaysAddToPackageJson": false - }, - "@schematics/angular": { - "version": "~10.0.0", - "alwaysAddToPackageJson": false - }, - "rxjs": { - "version": "~6.5.4", - "alwaysAddToPackageJson": false - }, - "@angular/core": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular/common": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular/forms": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular/compiler": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular/compiler-cli": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular/platform-browser": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular/platform-browser-dynamic": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular/router": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular/upgrade": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular/language-service": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular/animations": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - }, - "@angular/service-worker": { - "version": "^10.0.0", - "alwaysAddToPackageJson": false - } - } - }, - "10.3.0": { - "version": "10.3.0-beta.1", - "packages": { - "typescript": { - "version": "~4.0.3", - "alwaysAddToPackageJson": false - }, - "@typescript-eslint/parser": { - "version": "4.3.0", - "alwaysAddToPackageJson": false - }, - "@typescript-eslint/eslint-plugin": { - "version": "4.3.0", - "alwaysAddToPackageJson": false - }, - "@angular/cli": { - "version": "~10.1.3", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/architect": { - "version": "~0.1001.3", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/build-angular": { - "version": "~0.1001.3", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/build-ng-packagr": { - "version": "~0.1001.3", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/build-webpack": { - "version": "~0.1001.3", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/build-optimizer": { - "version": "~0.1001.3", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/core": { - "version": "~10.1.3", - "alwaysAddToPackageJson": false - }, - "@angular-devkit/schematics": { - "version": "~10.1.3", - "alwaysAddToPackageJson": false - }, - "@schematics/angular": { - "version": "~10.1.3", - "alwaysAddToPackageJson": false - } - } - }, - "10.4.0": { - "version": "10.4.0-beta.1", - "packages": { - "prettier": { - "version": "2.1.2", - "alwaysAddToPackageJson": false - } - } - }, - "11.0.0": { - "version": "11.0.0-beta.3", - "packages": { - "@types/node": { - "version": "12.12.38", - "alwaysAddToPackageJson": false - } - } - }, - "11.0.9": { - "version": "11.0.9", - "packages": { - "tslint": { - "version": "~6.1.0", - "alwaysAddToPackageJson": false - }, - "ts-node": { - "version": "~9.1.1", - "alwaysAddToPackageJson": false - } - } - }, - "11.1.2": { - "version": "11.1.2", - "packages": { - "prettier": { - "version": "2.2.1", - "alwaysAddToPackageJson": false - } - } - }, - "11.6.0": { - "version": "11.6.0-beta.0", - "packages": { - "dotenv": { - "version": "8.2.0", - "alwaysAddToPackageJson": false - }, - "typescript": { - "version": "4.1.4", - "alwaysAddToPackageJson": false - }, - "@types/node": { - "version": "14.14.33", - "alwaysAddToPackageJson": false - } - } - }, "12.5.0": { "version": "12.5.0", "packages": { diff --git a/packages/workspace/package.json b/packages/workspace/package.json index 64dda344701a7..eafa2a6d5ecda 100644 --- a/packages/workspace/package.json +++ b/packages/workspace/package.json @@ -37,7 +37,7 @@ "packageGroup": [ "@nrwl/workspace", "@nrwl/angular", - "@nrwl/cli", + "nx", "@nrwl/cypress", "@nrwl/devkit", "@nrwl/eslint-plugin-nx", @@ -50,7 +50,6 @@ "@nrwl/nx-plugin", "@nrwl/react", "@nrwl/storybook", - "@nrwl/tao", "@nrwl/web" ] }, diff --git a/packages/workspace/project.json b/packages/workspace/project.json index 8e2dcff02c952..6ac6fc9a07a4a 100644 --- a/packages/workspace/project.json +++ b/packages/workspace/project.json @@ -70,7 +70,7 @@ "command": "node ./scripts/copy-readme.js workspace" }, { - "command": "node ./scripts/add-dependency-to-build.js workspace @nrwl/cli" + "command": "node ./scripts/add-dependency-to-build.js workspace nx" }, { "command": "node ./scripts/add-dependency-to-build.js workspace @nrwl/devkit" diff --git a/packages/workspace/src/command-line/dep-graph.ts b/packages/workspace/src/command-line/dep-graph.ts index 659fa309be046..76fb8090e97e8 100644 --- a/packages/workspace/src/command-line/dep-graph.ts +++ b/packages/workspace/src/command-line/dep-graph.ts @@ -1,5 +1,5 @@ import { joinPathFragments } from '@nrwl/devkit/src/utils/path'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { watch } from 'chokidar'; import { createHash } from 'crypto'; import { existsSync, readFileSync, statSync, writeFileSync } from 'fs'; diff --git a/packages/workspace/src/command-line/format.ts b/packages/workspace/src/command-line/format.ts index e04fc94c37167..f217ac9cc9bf1 100644 --- a/packages/workspace/src/command-line/format.ts +++ b/packages/workspace/src/command-line/format.ts @@ -11,8 +11,8 @@ import { reformattedWorkspaceJsonOrNull, workspaceConfigName, WorkspaceJsonConfiguration, -} from '@nrwl/tao/src/shared/workspace'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +} from 'nx/src/shared/workspace'; +import { appRootPath } from 'nx/src/utils/app-root'; import * as prettier from 'prettier'; import { NxJsonConfiguration, @@ -20,7 +20,7 @@ import { readJsonFile, writeJsonFile, } from '@nrwl/devkit'; -import { sortObjectByKeys } from '@nrwl/tao/src/utils/object-sort'; +import { sortObjectByKeys } from 'nx/src/utils/object-sort'; import { getRootTsConfigFileName, getRootTsConfigPath, diff --git a/packages/workspace/src/command-line/list.ts b/packages/workspace/src/command-line/list.ts index aee3a09b29f36..258be160c40bd 100644 --- a/packages/workspace/src/command-line/list.ts +++ b/packages/workspace/src/command-line/list.ts @@ -1,4 +1,4 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { output } from '../utilities/output'; import { fetchCommunityPlugins, diff --git a/packages/workspace/src/command-line/nx-commands.ts b/packages/workspace/src/command-line/nx-commands.ts index a88f5380e3985..3ea1470fb8b38 100644 --- a/packages/workspace/src/command-line/nx-commands.ts +++ b/packages/workspace/src/command-line/nx-commands.ts @@ -10,7 +10,7 @@ import * as yargs from 'yargs'; import { generateDaemonHelpOutput } from '../core/project-graph/daemon/client/generate-help-output'; import { nxVersion } from '../utils/versions'; import { examples } from './examples'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import type { ListArgs } from './list'; const noop = (yargs: yargs.Argv): yargs.Argv => yargs; @@ -280,16 +280,16 @@ npx nx daemon () => { const runLocalMigrate = () => { const pmc = getPackageManagerCommand(); - execSync(`${pmc.exec} tao migrate ${process.argv.slice(3).join(' ')}`, { + execSync(`${pmc.exec} nx _migrate ${process.argv.slice(3).join(' ')}`, { stdio: ['inherit', 'inherit', 'inherit'], }); }; if (process.env.NX_MIGRATE_USE_LOCAL === undefined) { - const p = taoPath(); + const p = nxCliPath(); if (p === null) { runLocalMigrate(); } else { - execSync(`${p} migrate ${process.argv.slice(3).join(' ')}`, { + execSync(`${p} _migrate ${process.argv.slice(3).join(' ')}`, { stdio: ['inherit', 'inherit', 'inherit'], }); } @@ -586,7 +586,7 @@ function withTarget(yargs: yargs.Argv): yargs.Argv { }); } -function taoPath() { +function nxCliPath() { try { const packageManager = getPackageManagerCommand(); @@ -594,7 +594,7 @@ function taoPath() { const tmpDir = dirSync().name; writeJsonFile(path.join(tmpDir, 'package.json'), { dependencies: { - '@nrwl/tao': 'latest', + nx: 'latest', }, license: 'MIT', }); @@ -608,7 +608,7 @@ function taoPath() { addToNodePath(path.join(tmpDir, 'node_modules')); addToNodePath(path.join(appRootPath, 'node_modules')); - return path.join(tmpDir, `node_modules`, '.bin', 'tao'); + return path.join(tmpDir, `node_modules`, '.bin', 'nx'); } catch (e) { console.error( 'Failed to install the latest version of the migration script. Using the current version.' diff --git a/packages/workspace/src/command-line/report.spec.ts b/packages/workspace/src/command-line/report.spec.ts index 1b85c7ae642af..399311ce3e1f6 100644 --- a/packages/workspace/src/command-line/report.spec.ts +++ b/packages/workspace/src/command-line/report.spec.ts @@ -3,7 +3,7 @@ import * as devkit from '@nrwl/devkit'; import * as fileUtils from '../utilities/fileutils'; import { join } from 'path'; -jest.mock('@nrwl/tao/src/utils/app-root', () => ({ +jest.mock('nx/src/utils/app-root', () => ({ appRootPath: '', })); diff --git a/packages/workspace/src/command-line/report.ts b/packages/workspace/src/command-line/report.ts index 9f67c74a4105b..f01794b18be57 100644 --- a/packages/workspace/src/command-line/report.ts +++ b/packages/workspace/src/command-line/report.ts @@ -1,5 +1,5 @@ import * as chalk from 'chalk'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { detectPackageManager, getPackageManagerVersion, @@ -12,7 +12,6 @@ import { resolve } from '../utilities/fileutils'; export const packagesWeCareAbout = [ 'nx', '@nrwl/angular', - '@nrwl/cli', '@nrwl/cypress', '@nrwl/detox', '@nrwl/devkit', @@ -29,7 +28,6 @@ export const packagesWeCareAbout = [ '@nrwl/react-native', '@nrwl/schematics', '@nrwl/storybook', - '@nrwl/tao', '@nrwl/web', '@nrwl/workspace', 'typescript', diff --git a/packages/workspace/src/command-line/workspace-generators.ts b/packages/workspace/src/command-line/workspace-generators.ts index db20b2cab2afb..d0e452e6cef9f 100644 --- a/packages/workspace/src/command-line/workspace-generators.ts +++ b/packages/workspace/src/command-line/workspace-generators.ts @@ -4,7 +4,7 @@ import { readdirSync, existsSync } from 'fs'; import { copySync, removeSync } from 'fs-extra'; import * as path from 'path'; import * as yargsParser from 'yargs-parser'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { fileExists } from '../utilities/fileutils'; import { output } from '../utilities/output'; import type { CompilerOptions } from 'typescript'; @@ -15,7 +15,7 @@ import { readJsonFile, writeJsonFile, } from '@nrwl/devkit'; -import { generate } from '@nrwl/tao/src/commands/generate'; +import { generate } from 'nx/src/commands/generate'; const rootDirectory = appRootPath; const toolsDir = path.join(rootDirectory, 'tools'); diff --git a/packages/workspace/src/core/affected-project-graph/affected-project-graph.spec.ts b/packages/workspace/src/core/affected-project-graph/affected-project-graph.spec.ts index 7d4c9b9519a19..d9805861b60ac 100644 --- a/packages/workspace/src/core/affected-project-graph/affected-project-graph.spec.ts +++ b/packages/workspace/src/core/affected-project-graph/affected-project-graph.spec.ts @@ -11,7 +11,7 @@ import type { import { defaultFileHasher } from '../hasher/file-hasher'; jest.mock('fs', () => require('memfs').fs); -jest.mock('@nrwl/tao/src/utils/app-root', () => ({ +jest.mock('nx/src/utils/app-root', () => ({ appRootPath: '/root', })); diff --git a/packages/workspace/src/core/file-utils.ts b/packages/workspace/src/core/file-utils.ts index 670ef2d084e52..47d344bcce049 100644 --- a/packages/workspace/src/core/file-utils.ts +++ b/packages/workspace/src/core/file-utils.ts @@ -2,14 +2,14 @@ import { toOldFormatOrNull, WorkspaceJsonConfiguration, Workspaces, -} from '@nrwl/tao/src/shared/workspace'; +} from 'nx/src/shared/workspace'; import type { FileData, NxJsonConfiguration } from '@nrwl/devkit'; import { readJsonFile } from '@nrwl/devkit'; import { execSync } from 'child_process'; import { existsSync, readFileSync } from 'fs'; import { extname, join, relative, sep } from 'path'; import type { NxArgs } from '../command-line/utils'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { fileExists } from '../utilities/fileutils'; import { jsonDiff } from '../utilities/json-diff'; import type { Environment } from './shared-interfaces'; diff --git a/packages/workspace/src/core/hasher/file-hasher-base.ts b/packages/workspace/src/core/hasher/file-hasher-base.ts index da75402ec5128..f65b6dc7e37ff 100644 --- a/packages/workspace/src/core/hasher/file-hasher-base.ts +++ b/packages/workspace/src/core/hasher/file-hasher-base.ts @@ -1,7 +1,7 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { performance } from 'perf_hooks'; import { defaultHashing } from './hashing-impl'; -import { FileData } from '@nrwl/tao/src/shared/project-graph'; +import { FileData } from 'nx/src/shared/project-graph'; import { joinPathFragments } from '@nrwl/devkit'; export abstract class FileHasherBase { diff --git a/packages/workspace/src/core/hasher/file-hasher.ts b/packages/workspace/src/core/hasher/file-hasher.ts index bf743ae3c328f..dea93c02f7fb8 100644 --- a/packages/workspace/src/core/hasher/file-hasher.ts +++ b/packages/workspace/src/core/hasher/file-hasher.ts @@ -1,5 +1,5 @@ import { GitBasedFileHasher } from './git-based-file-hasher'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { NodeBasedFileHasher } from './node-based-file-hasher'; import { FileHasherBase } from './file-hasher-base'; import { execSync } from 'child_process'; diff --git a/packages/workspace/src/core/hasher/git-based-file-hasher.ts b/packages/workspace/src/core/hasher/git-based-file-hasher.ts index 392cbb7b7f154..5d9f0744556f4 100644 --- a/packages/workspace/src/core/hasher/git-based-file-hasher.ts +++ b/packages/workspace/src/core/hasher/git-based-file-hasher.ts @@ -1,4 +1,4 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { performance } from 'perf_hooks'; import { getFileHashes, getGitHashForFiles } from './git-hasher'; import { existsSync, readFileSync } from 'fs'; diff --git a/packages/workspace/src/core/hasher/hasher.ts b/packages/workspace/src/core/hasher/hasher.ts index 66204e217e63d..13bc9e48bc76b 100644 --- a/packages/workspace/src/core/hasher/hasher.ts +++ b/packages/workspace/src/core/hasher/hasher.ts @@ -5,7 +5,7 @@ import { Task, WorkspaceJsonConfiguration, } from '@nrwl/devkit'; -import { resolveNewFormatWithInlineProjects } from '@nrwl/tao/src/shared/workspace'; +import { resolveNewFormatWithInlineProjects } from 'nx/src/shared/workspace'; import { exec } from 'child_process'; import { existsSync } from 'fs'; import * as minimatch from 'minimatch'; diff --git a/packages/workspace/src/core/hasher/node-based-file-hasher.ts b/packages/workspace/src/core/hasher/node-based-file-hasher.ts index 7de0757b9e6f0..60ec6f9688911 100644 --- a/packages/workspace/src/core/hasher/node-based-file-hasher.ts +++ b/packages/workspace/src/core/hasher/node-based-file-hasher.ts @@ -1,6 +1,6 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { performance } from 'perf_hooks'; -import { FileData } from '@nrwl/tao/src/shared/project-graph'; +import { FileData } from 'nx/src/shared/project-graph'; import { join, relative } from 'path'; import { existsSync, readdirSync, readFileSync, statSync } from 'fs'; import { FileHasherBase } from './file-hasher-base'; diff --git a/packages/workspace/src/core/project-graph/build-dependencies/explicit-package-json-dependencies.spec.ts b/packages/workspace/src/core/project-graph/build-dependencies/explicit-package-json-dependencies.spec.ts index 0ad9778d562a9..6a5e1a66a958e 100644 --- a/packages/workspace/src/core/project-graph/build-dependencies/explicit-package-json-dependencies.spec.ts +++ b/packages/workspace/src/core/project-graph/build-dependencies/explicit-package-json-dependencies.spec.ts @@ -9,7 +9,7 @@ import { createProjectFileMap } from '../../file-map-utils'; import { defaultFileHasher } from '@nrwl/workspace/src/core/hasher/file-hasher'; jest.mock('fs', () => require('memfs').fs); -jest.mock('@nrwl/tao/src/utils/app-root', () => ({ +jest.mock('nx/src/utils/app-root', () => ({ appRootPath: '/root', })); diff --git a/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.spec.ts b/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.spec.ts index a6dac1acc7cac..717d94712ae79 100644 --- a/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.spec.ts +++ b/packages/workspace/src/core/project-graph/build-dependencies/explicit-project-dependencies.spec.ts @@ -1,7 +1,7 @@ import { createProjectFileMap } from '@nrwl/workspace/src/core/file-map-utils'; jest.mock('fs', () => require('memfs').fs); -jest.mock('@nrwl/tao/src/utils/app-root', () => ({ +jest.mock('nx/src/utils/app-root', () => ({ appRootPath: '/root', })); diff --git a/packages/workspace/src/core/project-graph/build-dependencies/implict-project-dependencies.spec.ts b/packages/workspace/src/core/project-graph/build-dependencies/implict-project-dependencies.spec.ts index d6b4db10323b8..a77075020546a 100644 --- a/packages/workspace/src/core/project-graph/build-dependencies/implict-project-dependencies.spec.ts +++ b/packages/workspace/src/core/project-graph/build-dependencies/implict-project-dependencies.spec.ts @@ -5,7 +5,7 @@ import { import { buildImplicitProjectDependencies } from './implicit-project-dependencies'; jest.mock('fs', () => require('memfs').fs); -jest.mock('@nrwl/tao/src/utils/app-root', () => ({ +jest.mock('nx/src/utils/app-root', () => ({ appRootPath: '/root', })); diff --git a/packages/workspace/src/core/project-graph/build-nodes/npm-packages.ts b/packages/workspace/src/core/project-graph/build-nodes/npm-packages.ts index 632305ae32051..f43628f6bd6e9 100644 --- a/packages/workspace/src/core/project-graph/build-nodes/npm-packages.ts +++ b/packages/workspace/src/core/project-graph/build-nodes/npm-packages.ts @@ -1,6 +1,6 @@ import { ProjectGraphBuilder, readJsonFile } from '@nrwl/devkit'; import { join } from 'path'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; export function buildNpmPackageNodes(builder: ProjectGraphBuilder) { const packageJson = readJsonFile(join(appRootPath, 'package.json')); diff --git a/packages/workspace/src/core/project-graph/build-nodes/workspace-projects.ts b/packages/workspace/src/core/project-graph/build-nodes/workspace-projects.ts index 554518189457d..a462d42f8d791 100644 --- a/packages/workspace/src/core/project-graph/build-nodes/workspace-projects.ts +++ b/packages/workspace/src/core/project-graph/build-nodes/workspace-projects.ts @@ -5,11 +5,11 @@ import { import { join } from 'path'; import { existsSync } from 'fs'; import { mergeNpmScriptsWithTargets } from '../../../utilities/project-graph-utils'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { loadNxPlugins, mergePluginTargetsWithNxTargets, -} from '@nrwl/tao/src/shared/nx-plugin'; +} from 'nx/src/shared/nx-plugin'; export function buildWorkspaceProjectNodes( ctx: ProjectGraphProcessorContext, diff --git a/packages/workspace/src/core/project-graph/build-project-graph.spec.ts b/packages/workspace/src/core/project-graph/build-project-graph.spec.ts index b0cdbcb16f56c..19b8804a7d86b 100644 --- a/packages/workspace/src/core/project-graph/build-project-graph.spec.ts +++ b/packages/workspace/src/core/project-graph/build-project-graph.spec.ts @@ -1,7 +1,7 @@ import { vol, fs } from 'memfs'; jest.mock('fs', () => require('memfs').fs); -jest.mock('@nrwl/tao/src/utils/app-root', () => ({ +jest.mock('nx/src/utils/app-root', () => ({ appRootPath: '/root', })); import { buildProjectGraph } from './build-project-graph'; diff --git a/packages/workspace/src/core/project-graph/build-project-graph.ts b/packages/workspace/src/core/project-graph/build-project-graph.ts index 2a3799304699c..e75b5991ba5f0 100644 --- a/packages/workspace/src/core/project-graph/build-project-graph.ts +++ b/packages/workspace/src/core/project-graph/build-project-graph.ts @@ -11,7 +11,7 @@ import { readJsonFile, WorkspaceJsonConfiguration, } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { join } from 'path'; import { performance } from 'perf_hooks'; import { assertWorkspaceValidity } from '../assert-workspace-validity'; @@ -32,7 +32,7 @@ import { } from './build-nodes'; import * as os from 'os'; import { buildExplicitTypescriptAndPackageJsonDependencies } from './build-dependencies/build-explicit-typescript-and-package-json-dependencies'; -import { loadNxPlugins } from '@nrwl/tao/src/shared/nx-plugin'; +import { loadNxPlugins } from 'nx/src/shared/nx-plugin'; import { defaultFileHasher } from '../hasher/file-hasher'; import { createProjectFileMap } from '../file-map-utils'; import { getRootTsConfigPath } from '../../utilities/typescript'; diff --git a/packages/workspace/src/core/project-graph/daemon/client/client.ts b/packages/workspace/src/core/project-graph/daemon/client/client.ts index 4e09e226333e1..695ed991835dc 100644 --- a/packages/workspace/src/core/project-graph/daemon/client/client.ts +++ b/packages/workspace/src/core/project-graph/daemon/client/client.ts @@ -1,5 +1,5 @@ import { ProjectGraph } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { ChildProcess, spawn, spawnSync } from 'child_process'; import { openSync, readFileSync } from 'fs'; import { ensureDirSync, ensureFileSync } from 'fs-extra'; diff --git a/packages/workspace/src/core/project-graph/daemon/server/server.ts b/packages/workspace/src/core/project-graph/daemon/server/server.ts index 5e2d596927821..238349076dabf 100644 --- a/packages/workspace/src/core/project-graph/daemon/server/server.ts +++ b/packages/workspace/src/core/project-graph/daemon/server/server.ts @@ -1,4 +1,4 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { createServer, Server, Socket } from 'net'; import { join } from 'path'; import { performance, PerformanceObserver } from 'perf_hooks'; diff --git a/packages/workspace/src/core/project-graph/daemon/server/shutdown-utils.ts b/packages/workspace/src/core/project-graph/daemon/server/shutdown-utils.ts index 16a455a1f598c..1379fd6e51489 100644 --- a/packages/workspace/src/core/project-graph/daemon/server/shutdown-utils.ts +++ b/packages/workspace/src/core/project-graph/daemon/server/shutdown-utils.ts @@ -1,4 +1,4 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import type { Server } from 'net'; import { serverLogger } from './logger'; import type { WatcherSubscription } from './watcher'; diff --git a/packages/workspace/src/core/project-graph/daemon/server/watcher.ts b/packages/workspace/src/core/project-graph/daemon/server/watcher.ts index 4c7a11e108d77..318aecc2c1ad1 100644 --- a/packages/workspace/src/core/project-graph/daemon/server/watcher.ts +++ b/packages/workspace/src/core/project-graph/daemon/server/watcher.ts @@ -6,7 +6,7 @@ * See https://github.com/parcel-bundler/watcher for more details. */ import { normalizePath } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import type { AsyncSubscription, Event } from '@parcel/watcher'; import { readFileSync } from 'fs'; import { join, relative } from 'path'; diff --git a/packages/workspace/src/core/target-project-locator.spec.ts b/packages/workspace/src/core/target-project-locator.spec.ts index 9d11babb1ff46..4423801e3a9d5 100644 --- a/packages/workspace/src/core/target-project-locator.spec.ts +++ b/packages/workspace/src/core/target-project-locator.spec.ts @@ -6,7 +6,7 @@ import type { } from '@nrwl/devkit'; import { TargetProjectLocator } from './target-project-locator'; -jest.mock('@nrwl/tao/src/utils/app-root', () => ({ +jest.mock('nx/src/utils/app-root', () => ({ appRootPath: '/root', })); jest.mock('fs', () => require('memfs').fs); diff --git a/packages/workspace/src/core/target-project-locator.ts b/packages/workspace/src/core/target-project-locator.ts index 631c2d30346b3..3f6ca0c271338 100644 --- a/packages/workspace/src/core/target-project-locator.ts +++ b/packages/workspace/src/core/target-project-locator.ts @@ -9,7 +9,7 @@ import { } from '@nrwl/devkit'; import { isRelativePath } from '../utilities/fileutils'; import { dirname, join, posix } from 'path'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { readFileSync } from 'fs'; export class TargetProjectLocator { diff --git a/packages/workspace/src/executors/run-commands/run-commands.impl.spec.ts b/packages/workspace/src/executors/run-commands/run-commands.impl.spec.ts index 1210af3149516..c3c4da47a7e1e 100644 --- a/packages/workspace/src/executors/run-commands/run-commands.impl.spec.ts +++ b/packages/workspace/src/executors/run-commands/run-commands.impl.spec.ts @@ -350,43 +350,6 @@ describe('Command Runner Builder', () => { }); describe('cwd', () => { - it('should use local installed package when cwd is specified', async () => { - const root = dirSync().name; - const childFolder = dirSync({ dir: root }).name; - const cwd = relative(root, childFolder); - const f = fileSync().name; - - const result = await runCommands( - { - commands: [ - { - command: `yarn init -y`, - }, - { - command: `yarn add nx@12.0.0 @nrwl/workspace@12.0.0 @nrwl/cli@12.0.0 --save --registry=https://registry.yarnpkg.com/`, - }, - { - command: `echo '{"name":"tmp","scripts":{"nx":"nx"}}' >> package.json`, - }, - { - command: `echo '{}' >> nx.json`, - }, - { - command: `echo '{}' >> workspace.json`, - }, - { - command: `nx --version >> ${f}`, - }, - ], - parallel: false, - cwd, - }, - { root } as any - ); - expect(result).toEqual(expect.objectContaining({ success: true })); - // expect(normalize(readFile(f))).toBe('12.0.0'); - }); - it('should use workspace root package when cwd is not specified', async () => { const root = dirSync().name; const f = fileSync().name; diff --git a/packages/workspace/src/generators/library/library.spec.ts b/packages/workspace/src/generators/library/library.spec.ts index 603ead8ad1672..41f4d6ba44a05 100644 --- a/packages/workspace/src/generators/library/library.spec.ts +++ b/packages/workspace/src/generators/library/library.spec.ts @@ -9,7 +9,7 @@ import { createTreeWithEmptyWorkspace } from '@nrwl/devkit/testing'; import { libraryGenerator } from './library'; import { Schema } from './schema.d'; -import { toNewFormat } from '@nrwl/tao/src/shared/workspace'; +import { toNewFormat } from 'nx/src/shared/workspace'; describe('lib', () => { let tree: Tree; diff --git a/packages/workspace/src/generators/move/lib/update-cypress-json.ts b/packages/workspace/src/generators/move/lib/update-cypress-json.ts index 3622324260898..07a7d6faa54e8 100644 --- a/packages/workspace/src/generators/move/lib/update-cypress-json.ts +++ b/packages/workspace/src/generators/move/lib/update-cypress-json.ts @@ -1,5 +1,5 @@ import { Tree } from '@nrwl/devkit'; -import { ProjectConfiguration } from '@nrwl/tao/src/shared/workspace'; +import { ProjectConfiguration } from 'nx/src/shared/workspace'; import * as path from 'path'; import { NormalizedSchema } from '../schema'; diff --git a/packages/workspace/src/generators/move/lib/update-project-root-files.ts b/packages/workspace/src/generators/move/lib/update-project-root-files.ts index d879bf53f53ad..c280319b3d717 100644 --- a/packages/workspace/src/generators/move/lib/update-project-root-files.ts +++ b/packages/workspace/src/generators/move/lib/update-project-root-files.ts @@ -1,5 +1,5 @@ import { ProjectConfiguration, Tree } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import * as path from 'path'; import { extname, join } from 'path'; import { NormalizedSchema } from '../schema'; diff --git a/packages/workspace/src/generators/move/lib/update-storybook-config.ts b/packages/workspace/src/generators/move/lib/update-storybook-config.ts index c4f0459386ac3..9ccb872897396 100644 --- a/packages/workspace/src/generators/move/lib/update-storybook-config.ts +++ b/packages/workspace/src/generators/move/lib/update-storybook-config.ts @@ -1,5 +1,5 @@ import { ProjectConfiguration, Tree } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import * as path from 'path'; import { join } from 'path'; import { NormalizedSchema } from '../schema'; diff --git a/packages/workspace/src/generators/new/__snapshots__/new.spec.ts.snap b/packages/workspace/src/generators/new/__snapshots__/new.spec.ts.snap index 3b411a1cf9ed0..ae8d783e16da1 100644 --- a/packages/workspace/src/generators/new/__snapshots__/new.spec.ts.snap +++ b/packages/workspace/src/generators/new/__snapshots__/new.spec.ts.snap @@ -6,10 +6,9 @@ Object { "@nrwl/angular": "*", }, "devDependencies": Object { - "@nrwl/cli": "*", - "@nrwl/tao": "*", "@nrwl/workspace": "*", "@types/node": "16.11.7", + "nx": "*", "prettier": "^2.5.1", "typescript": "~4.5.2", }, @@ -29,10 +28,9 @@ exports[`new --preset empty should generate necessary npm dependencies 1`] = ` Object { "dependencies": Object {}, "devDependencies": Object { - "@nrwl/cli": "*", - "@nrwl/tao": "*", "@nrwl/workspace": "*", "@types/node": "16.11.7", + "nx": "*", "prettier": "^2.5.1", "typescript": "~4.5.2", }, @@ -52,11 +50,10 @@ exports[`new --preset react should generate necessary npm dependencies 1`] = ` Object { "dependencies": Object {}, "devDependencies": Object { - "@nrwl/cli": "*", "@nrwl/react": "*", - "@nrwl/tao": "*", "@nrwl/workspace": "*", "@types/node": "16.11.7", + "nx": "*", "prettier": "^2.5.1", "typescript": "~4.5.2", }, diff --git a/packages/workspace/src/generators/new/new.ts b/packages/workspace/src/generators/new/new.ts index b9cb5e1862504..011de17294344 100644 --- a/packages/workspace/src/generators/new/new.ts +++ b/packages/workspace/src/generators/new/new.ts @@ -102,7 +102,7 @@ function generatePreset(host: Tree, opts: NormalizedSchema) { acc.push(`--${key}`); } else if (value === false) { acc.push(`--no-${key}`); - // nxWorkspaceRoot breaks Tao CLI if incorrectly set, so need to exclude it. + // nxWorkspaceRoot breaks CLI if incorrectly set, so need to exclude it. // TODO(jack): Should read in the preset schema and only pass the options specified. } else if (key !== 'nxWorkspaceRoot') { // string, number (don't handle arrays or nested objects) diff --git a/packages/workspace/src/generators/utils/decorate-angular-cli.js__tmpl__ b/packages/workspace/src/generators/utils/decorate-angular-cli.js__tmpl__ index bc81a83788969..7857473732c19 100644 --- a/packages/workspace/src/generators/utils/decorate-angular-cli.js__tmpl__ +++ b/packages/workspace/src/generators/utils/decorate-angular-cli.js__tmpl__ @@ -62,7 +62,7 @@ function symlinkNgCLItoNxCLI() { try { symlinkNgCLItoNxCLI(); - require('@nrwl/cli/lib/decorate-cli').decorateCli(); + require('nx/src/cli/decorate-cli').decorateCli(); output.log({ title: 'Angular CLI has been decorated to enable computation caching.' }); } catch(e) { output.error({ title: 'Decoration of the Angular CLI did not complete successfully' }); diff --git a/packages/workspace/src/generators/workspace/files/package.json__tmpl__ b/packages/workspace/src/generators/workspace/files/package.json__tmpl__ index a0ebe35ad6b9e..039552c859b74 100644 --- a/packages/workspace/src/generators/workspace/files/package.json__tmpl__ +++ b/packages/workspace/src/generators/workspace/files/package.json__tmpl__ @@ -9,8 +9,7 @@ }, "devDependencies": { <% if(cli === 'angular') { %>"@angular/cli": "<%= angularCliVersion %>",<% } %> - "@nrwl/tao": "<%= nxVersion %>", - "@nrwl/cli": "<%= nxVersion %>", + "nx": "<%= nxVersion %>", "@nrwl/workspace": "<%= nxVersion %>", "@types/node": "16.11.7", "typescript": "<%= typescriptVersion %>", diff --git a/packages/workspace/src/generators/workspace/workspace.ts b/packages/workspace/src/generators/workspace/workspace.ts index 28a110e316991..d8b1638192e47 100644 --- a/packages/workspace/src/generators/workspace/workspace.ts +++ b/packages/workspace/src/generators/workspace/workspace.ts @@ -16,7 +16,7 @@ import { } from '../../utils/versions'; import { readFileSync } from 'fs'; import { join, join as pathJoin } from 'path'; -import { reformattedWorkspaceJsonOrNull } from '@nrwl/tao/src/shared/workspace'; +import { reformattedWorkspaceJsonOrNull } from 'nx/src/shared/workspace'; import { Preset } from '../utils/presets'; import { deduceDefaultBase } from '../../utilities/default-base'; diff --git a/packages/workspace/src/migrations/update-10-0-0/solution-tsconfigs.spec.ts b/packages/workspace/src/migrations/update-10-0-0/solution-tsconfigs.spec.ts deleted file mode 100644 index a51129bd91ded..0000000000000 --- a/packages/workspace/src/migrations/update-10-0-0/solution-tsconfigs.spec.ts +++ /dev/null @@ -1,132 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { callRule, runMigration } from '../../utils/testing'; -import { readJsonInTree, updateJsonInTree } from '@nrwl/workspace'; - -describe('Solution Tsconfigs Migration', () => { - let tree: Tree; - - beforeEach(async () => { - tree = Tree.empty(); - tree = await callRule( - updateJsonInTree('nx.json', () => ({ - implicitDependencies: { - 'tsconfig.json': '*', - }, - })), - tree - ); - tree = await callRule( - updateJsonInTree('tsconfig.json', () => ({ - compilerOptions: { - target: 'es2015', - }, - })), - tree - ); - tree = await callRule( - updateJsonInTree('apps/app1/tsconfig.json', () => ({ - extends: '../../tsconfig.json', - compilerOptions: { - module: 'commonjs', - }, - files: ['src/index.ts'], - include: ['**/*.ts'], - })), - tree - ); - tree = await callRule( - updateJsonInTree('apps/app1/tsconfig.app.json', () => ({ - extends: './tsconfig.json', - compilerOptions: { - module: 'esnext', - types: [], - }, - })), - tree - ); - tree = await callRule( - updateJsonInTree('apps/app1/tsconfig.spec.json', () => ({ - extends: './tsconfig.json', - compilerOptions: { - module: 'esnext', - }, - include: ['**/*.spec.ts'], - })), - tree - ); - }); - - it('should rename tsconfig.json', async () => { - const result = await runMigration('solution-tsconfigs', {}, tree); - expect(result.exists('tsconfig.base.json')).toEqual(true); - expect(result.exists('tsconfig.json')).toEqual(false); - }); - - it('should update implicit dependencies on tsconfig.json', async () => { - const result = await runMigration('solution-tsconfigs', {}, tree); - const json = readJsonInTree(result, 'nx.json'); - expect(json).toEqual({ - implicitDependencies: { - 'tsconfig.base.json': '*', - }, - }); - }); - - it('should update tsconfig.base.json', async () => { - const result = await runMigration('solution-tsconfigs', {}, tree); - const json = readJsonInTree(result, 'tsconfig.base.json'); - expect(json).toEqual({ - compilerOptions: { - target: 'es2015', - }, - }); - }); - - it('should extend tsconfig.base.json in tsconfigs that extended tsconfig.json', async () => { - const result = await runMigration('solution-tsconfigs', {}, tree); - const json = readJsonInTree(result, 'apps/app1/tsconfig.json'); - expect(json).toEqual({ - extends: '../../tsconfig.base.json', - compilerOptions: { - module: 'commonjs', - }, - files: [], - include: [], - references: [ - { - path: './tsconfig.app.json', - }, - { - path: './tsconfig.spec.json', - }, - ], - }); - }); - - it('should update tsconfig.app.json', async () => { - const result = await runMigration('solution-tsconfigs', {}, tree); - const json = readJsonInTree(result, 'apps/app1/tsconfig.app.json'); - expect(json).toEqual({ - extends: './tsconfig.json', - compilerOptions: { - module: 'esnext', - types: [], - }, - files: ['src/index.ts'], - include: ['**/*.ts'], - }); - }); - - it('should update tsconfig.spec.json', async () => { - const result = await runMigration('solution-tsconfigs', {}, tree); - const json = readJsonInTree(result, 'apps/app1/tsconfig.spec.json'); - expect(json).toEqual({ - extends: './tsconfig.json', - compilerOptions: { - module: 'esnext', - }, - files: ['src/index.ts'], - include: ['**/*.spec.ts'], - }); - }); -}); diff --git a/packages/workspace/src/migrations/update-10-0-0/solution-tsconfigs.ts b/packages/workspace/src/migrations/update-10-0-0/solution-tsconfigs.ts deleted file mode 100644 index 32ba5361f6fd3..0000000000000 --- a/packages/workspace/src/migrations/update-10-0-0/solution-tsconfigs.ts +++ /dev/null @@ -1,134 +0,0 @@ -import { basename, dirname, join, normalize, Path } from '@angular-devkit/core'; -import { chain, Rule, Tree } from '@angular-devkit/schematics'; -import type { NxJsonConfiguration } from '@nrwl/devkit'; -import { formatFiles, readJsonInTree, updateJsonInTree } from '@nrwl/workspace'; -import { relative } from 'path'; -import { visitNotIgnoredFiles } from '../../utils/rules/visit-not-ignored-files'; - -function renameRootTsconfig(host: Tree) { - if (!host.exists('tsconfig.json')) { - throw new Error('Root tsconfig.json does not exist'); - } - - host.rename('tsconfig.json', 'tsconfig.base.json'); -} - -function moveIncludesToProjectTsconfig( - file: Path, - extendedTsconfigPath: Path, - extendedTsconfig: any -) { - return updateJsonInTree(file, (json) => { - json.files = - json.files || - extendedTsconfig.files?.map((p: string) => - relative(dirname(file), join(dirname(extendedTsconfigPath), p)) - ); - json.include = - json.include || - extendedTsconfig.include?.map((p: string) => - relative(dirname(file), join(dirname(extendedTsconfigPath), p)) - ); - return json; - }); -} - -function convertToSolutionTsconfig(tsconfigPath: Path): Rule { - return updateJsonInTree(tsconfigPath, (json) => { - json.files = []; - json.include = []; - return json; - }); -} - -function addReference( - extendedTsconfigPath: string & { __PRIVATE_DEVKIT_PATH: void }, - file: Path -): Rule { - return updateJsonInTree(extendedTsconfigPath, (json, context) => { - json.references = json.references || []; - const relativePath = `${ - relative(dirname(extendedTsconfigPath), file).startsWith('../') - ? '' - : './' - }${relative(dirname(extendedTsconfigPath), file)}`; - context.logger.info(`Referencing ${file} in ${extendedTsconfigPath}`); - json.references.push({ - path: relativePath, - }); - return json; - }); -} - -function updateExtend(file: Path): Rule { - return updateJsonInTree(file, (json) => { - json.extends = json.extends.replace(/tsconfig.json$/, 'tsconfig.base.json'); - return json; - }); -} - -const originalExtendedTsconfigMap = new Map(); - -const changeImplicitDependency = updateJsonInTree( - 'nx.json', - (json) => { - if ( - !json.implicitDependencies || - !json.implicitDependencies['tsconfig.json'] - ) { - return json; - } - json.implicitDependencies['tsconfig.base.json'] = - json.implicitDependencies['tsconfig.json']; - delete json.implicitDependencies['tsconfig.json']; - return json; - } -); - -export default function (schema: any): Rule { - return chain([ - renameRootTsconfig, - changeImplicitDependency, - visitNotIgnoredFiles((file, host, context) => { - if (!file.endsWith('.json')) { - return; - } - - try { - const json = readJsonInTree(host, file); - if (!json.extends) { - return; - } - const extendedTsconfigPath = join(dirname(file), json.extends); - if (extendedTsconfigPath === normalize('tsconfig.json')) { - return updateExtend(file); - } else if (basename(json.extends) === 'tsconfig.json') { - let extendedTsconfig = - originalExtendedTsconfigMap.get(extendedTsconfigPath); - - if (!extendedTsconfig) { - extendedTsconfig = readJsonInTree(host, extendedTsconfigPath); - originalExtendedTsconfigMap.set( - extendedTsconfigPath, - extendedTsconfig - ); - } - return chain([ - moveIncludesToProjectTsconfig( - file, - extendedTsconfigPath, - extendedTsconfig - ), - convertToSolutionTsconfig(extendedTsconfigPath), - addReference(extendedTsconfigPath, file), - ]); - } else { - return; - } - } catch (e) { - context.logger.warn(`Could not update ${file}: Invalid JSON`); - } - }), - formatFiles(), - ]); -} diff --git a/packages/workspace/src/migrations/update-10-0-0/update-10-0-0.ts b/packages/workspace/src/migrations/update-10-0-0/update-10-0-0.ts deleted file mode 100644 index 3b6c4ec9efc39..0000000000000 --- a/packages/workspace/src/migrations/update-10-0-0/update-10-0-0.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { chain } from '@angular-devkit/schematics'; -import { updateJsonInTree } from '../../utils/ast-utils'; -import type { NxJsonConfiguration } from '@nrwl/devkit'; -import { updatePackagesInPackageJson } from '../../utils/update-packages-in-package-json'; -import { join } from 'path'; - -const updatePackages = updatePackagesInPackageJson( - join(__dirname, '../../..', 'migrations.json'), - '10.0.0' -); - -const addNxJsonAffectedConfig = updateJsonInTree( - 'nx.json', - (json: NxJsonConfiguration) => { - json.affected = { - defaultBase: 'main', - }; - - return json; - } -); - -export default function () { - return chain([updatePackages, addNxJsonAffectedConfig]); -} diff --git a/packages/workspace/src/migrations/update-10-0-1/migrate-eslintrc.spec.ts b/packages/workspace/src/migrations/update-10-0-1/migrate-eslintrc.spec.ts deleted file mode 100644 index 92781b894ebce..0000000000000 --- a/packages/workspace/src/migrations/update-10-0-1/migrate-eslintrc.spec.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { callRule, runMigration } from '../../utils/testing'; -import { readJsonInTree, updateJsonInTree } from '@nrwl/workspace'; - -describe('Eslintrc Migration', () => { - let tree: Tree; - - beforeEach(async () => { - tree = Tree.empty(); - tree = await callRule( - updateJsonInTree('.eslintrc', () => ({ - parserOptions: { - project: './tsconfig.json', - }, - })), - tree - ); - tree = await callRule( - updateJsonInTree('project1/.eslintrc', () => ({ - parserOptions: { - project: '../tsconfig.json', - }, - })), - tree - ); - tree = await callRule( - updateJsonInTree('project2/.eslintrc', () => ({ - parserOptions: { - project: './tsconfig.json', - }, - })), - tree - ); - }); - - it('should reference tsconfig.base.json', async () => { - const result = await runMigration('migrate-eslintrc-tsconfig', {}, tree); - const eslintrc = readJsonInTree(result, '.eslintrc'); - expect(eslintrc.parserOptions.project).toEqual('./tsconfig.base.json'); - }); - - it('should reference tsconfig.base.json from .eslintrc files not in the root', async () => { - const result = await runMigration('migrate-eslintrc-tsconfig', {}, tree); - const eslintrc = readJsonInTree(result, 'project1/.eslintrc'); - expect(eslintrc.parserOptions.project).toEqual('../tsconfig.base.json'); - }); - - it("should reference tsconfig.base.json in .eslintrc that don't reference the root tsconfig.json", async () => { - const result = await runMigration('migrate-eslintrc-tsconfig', {}, tree); - const eslintrc = readJsonInTree(result, 'project2/.eslintrc'); - expect(eslintrc.parserOptions.project).toEqual('./tsconfig.json'); - }); - - it('should not fail for a non-json eslintrc', async () => { - tree.overwrite('project2/.eslintrc', 'not-json'); - await runMigration('migrate-eslintrc-tsconfig', {}, tree); - }); -}); diff --git a/packages/workspace/src/migrations/update-10-0-1/migrate-eslintrc.ts b/packages/workspace/src/migrations/update-10-0-1/migrate-eslintrc.ts deleted file mode 100644 index 24ffad375c43b..0000000000000 --- a/packages/workspace/src/migrations/update-10-0-1/migrate-eslintrc.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { basename, dirname, join } from '@angular-devkit/core'; -import { chain, Rule } from '@angular-devkit/schematics'; -import { formatFiles, updateJsonInTree } from '@nrwl/workspace'; -import { visitNotIgnoredFiles } from '../../utils/rules/visit-not-ignored-files'; - -export default function (schema: any): Rule { - return chain([ - visitNotIgnoredFiles((file, host, context) => { - if (basename(file) !== '.eslintrc') { - return; - } - - return (host, context) => { - try { - updateJsonInTree(file, (json) => { - const tsconfig = json?.parserOptions?.project; - if (tsconfig) { - const tsconfigPath = join(dirname(file), tsconfig); - if (tsconfigPath === 'tsconfig.json') { - json.parserOptions.project = json.parserOptions.project.replace( - /tsconfig.json$/, - 'tsconfig.base.json' - ); - } - return json; - } else { - return json; - } - })(host, context); - } catch (e) { - context.logger.warn( - `${file} could not be migrated because it is not valid JSON` - ); - context.logger.error(e); - } - }; - }), - formatFiles(), - ]); -} diff --git a/packages/workspace/src/migrations/update-10-1-0/migrate-eslintrc-tsconfig-wildcard.spec.ts b/packages/workspace/src/migrations/update-10-1-0/migrate-eslintrc-tsconfig-wildcard.spec.ts deleted file mode 100644 index 82ec9daee5865..0000000000000 --- a/packages/workspace/src/migrations/update-10-1-0/migrate-eslintrc-tsconfig-wildcard.spec.ts +++ /dev/null @@ -1,29 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { callRule, runMigration } from '../../utils/testing'; -import { readJsonInTree, updateJsonInTree } from '@nrwl/workspace'; - -describe('Eslintrc Migration', () => { - let tree: Tree; - - beforeEach(async () => { - tree = Tree.empty(); - tree = await callRule( - updateJsonInTree('.eslintrc', () => ({ - parserOptions: { - project: './tsconfig.base.json', - }, - })), - tree - ); - }); - - it('should reference tsconfig.*.json', async () => { - const result = await runMigration( - 'migrate-eslintrc-tsconfig-wildcard', - {}, - tree - ); - const eslintrc = readJsonInTree(result, '.eslintrc'); - expect(eslintrc.parserOptions.project).toEqual('./tsconfig.*?.json'); - }); -}); diff --git a/packages/workspace/src/migrations/update-10-1-0/migrate-eslintrc-tsconfig-wildcard.ts b/packages/workspace/src/migrations/update-10-1-0/migrate-eslintrc-tsconfig-wildcard.ts deleted file mode 100644 index 7f7c8a87b3a5c..0000000000000 --- a/packages/workspace/src/migrations/update-10-1-0/migrate-eslintrc-tsconfig-wildcard.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { chain, noop, Rule, Tree } from '@angular-devkit/schematics'; -import { formatFiles, updateJsonInTree } from '@nrwl/workspace'; - -export default function (): Rule { - return (host: Tree) => { - if (!host.exists('.eslintrc')) { - return noop(); - } else { - return chain([ - updateJsonInTree('.eslintrc', (json) => { - const tsconfig = json?.parserOptions?.project; - if (tsconfig && tsconfig === './tsconfig.base.json') { - json.parserOptions.project = json.parserOptions.project.replace( - /tsconfig.base.json$/, - 'tsconfig.*?.json' - ); - return json; - } else { - return json; - } - }), - formatFiles(), - ]); - } - }; -} diff --git a/packages/workspace/src/migrations/update-10-3-0/add-buildable-project-deps-in-package-json-type.spec.ts b/packages/workspace/src/migrations/update-10-3-0/add-buildable-project-deps-in-package-json-type.spec.ts deleted file mode 100644 index 97547b95b7020..0000000000000 --- a/packages/workspace/src/migrations/update-10-3-0/add-buildable-project-deps-in-package-json-type.spec.ts +++ /dev/null @@ -1,88 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { SchematicTestRunner } from '@angular-devkit/schematics/testing'; -import { createEmptyWorkspace } from '@nrwl/workspace/testing'; -import * as path from 'path'; - -describe('update workspace that have web and angular lib builders', () => { - let initialTree: Tree; - let schematicRunner: SchematicTestRunner; - - beforeEach(() => { - initialTree = createEmptyWorkspace(Tree.empty()); - - initialTree.overwrite( - 'workspace.json', - JSON.stringify({ - version: 1, - projects: { - products: { - root: 'apps/products', - sourceRoot: 'apps/products/src', - architect: { - build: { - builder: '@nrwl/angular:package', - }, - }, - }, - cart: { - root: 'apps/cart', - sourceRoot: 'apps/cart/src', - architect: { - build: { - builder: '@nrwl/web:package', - }, - }, - }, - basket: { - root: 'apps/basket', - sourceRoot: 'apps/basket/src', - architect: { - build: { - builder: '@nrwl/node:package', - }, - }, - }, - }, - }) - ); - schematicRunner = new SchematicTestRunner( - '@nrwl/workspace', - path.join(__dirname, '../../../migrations.json') - ); - }); - - it('should add `buildableProjectDepsInPackageJsonType` to specific builders', async () => { - const result = await schematicRunner - .runSchematicAsync( - 'add-buildable-project-deps-in-package-json-type', - {}, - initialTree - ) - .toPromise(); - - const workspace = JSON.parse(result.readContent('workspace.json')); - - expect(workspace.projects['products'].architect.build) - .toMatchInlineSnapshot(` - Object { - "builder": "@nrwl/angular:package", - "options": Object { - "buildableProjectDepsInPackageJsonType": "dependencies", - }, - } - `); - expect(workspace.projects['cart'].architect.build).toMatchInlineSnapshot(` - Object { - "builder": "@nrwl/web:package", - "options": Object { - "buildableProjectDepsInPackageJsonType": "dependencies", - }, - } - `); - expect(workspace.projects['basket'].architect.build).toMatchInlineSnapshot(` - Object { - "builder": "@nrwl/node:package", - } - `); - }); -}); diff --git a/packages/workspace/src/migrations/update-10-3-0/add-buildable-project-deps-in-package-json-type.ts b/packages/workspace/src/migrations/update-10-3-0/add-buildable-project-deps-in-package-json-type.ts deleted file mode 100644 index 26da497a5e2c7..0000000000000 --- a/packages/workspace/src/migrations/update-10-3-0/add-buildable-project-deps-in-package-json-type.ts +++ /dev/null @@ -1,26 +0,0 @@ -import { Rule, Tree } from '@angular-devkit/schematics'; -import { getWorkspace, updateWorkspace } from '@nrwl/workspace'; - -export default function (): Rule { - return async (host: Tree) => { - const workspace = await getWorkspace(host); - - for (let [, projectTarget] of workspace.projects) { - for (let [, buildTarget] of projectTarget.targets) { - if ( - buildTarget.builder === '@nrwl/web:package' || - buildTarget.builder === '@nrwl/angular:package' - ) { - if (!buildTarget.options) { - buildTarget.options = {}; - } - - buildTarget.options['buildableProjectDepsInPackageJsonType'] = - 'dependencies'; - } - } - } - - return updateWorkspace(workspace); - }; -} diff --git a/packages/workspace/src/migrations/update-10-3-0/add-cli-dependency.spec.ts b/packages/workspace/src/migrations/update-10-3-0/add-cli-dependency.spec.ts deleted file mode 100644 index 7cb74543376f7..0000000000000 --- a/packages/workspace/src/migrations/update-10-3-0/add-cli-dependency.spec.ts +++ /dev/null @@ -1,24 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { callRule, runMigration } from '../../utils/testing'; -import { readJsonInTree } from '@nrwl/workspace'; -import { nxVersion } from '../../utils/versions'; - -describe('CLI dependency migration', () => { - let tree: Tree; - - beforeEach(async () => { - tree = Tree.empty(); - tree.create( - 'package.json', - JSON.stringify({ - devDependencies: {}, - }) - ); - }); - - it('should add @nrwl/cli to package.json', async () => { - const result = await runMigration('add-cli-dependency', {}, tree); - const packageJson = readJsonInTree(result, 'package.json'); - expect(packageJson.devDependencies['@nrwl/cli']).toEqual(nxVersion); - }); -}); diff --git a/packages/workspace/src/migrations/update-10-3-0/add-cli-dependency.ts b/packages/workspace/src/migrations/update-10-3-0/add-cli-dependency.ts deleted file mode 100644 index b6a88f0d21f32..0000000000000 --- a/packages/workspace/src/migrations/update-10-3-0/add-cli-dependency.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { chain, Rule } from '@angular-devkit/schematics'; -import { formatFiles } from '../../utils/rules/format-files'; -import { nxVersion } from '../../utils/versions'; -import { sortObjectByKeys, updateJsonInTree } from '../../utils/ast-utils'; - -export default function update(): Rule { - return chain([ - updateJsonInTree('package.json', (json) => { - json.dependencies = json.dependencies || {}; - - json.devDependencies = json.devDependencies || {}; - - delete json.dependencies['@nrwl/cli']; - json.devDependencies['@nrwl/cli'] = nxVersion; - - json.dependencies = sortObjectByKeys(json.dependencies); - json.devDependencies = sortObjectByKeys(json.devDependencies); - - return json; - }), - formatFiles(), - ]); -} diff --git a/packages/workspace/src/migrations/update-10-3-0/add-vscode-extensions.spec.ts b/packages/workspace/src/migrations/update-10-3-0/add-vscode-extensions.spec.ts deleted file mode 100644 index d44d8c7c25963..0000000000000 --- a/packages/workspace/src/migrations/update-10-3-0/add-vscode-extensions.spec.ts +++ /dev/null @@ -1,74 +0,0 @@ -import { chain, Tree } from '@angular-devkit/schematics'; -import { callRule, runMigration } from '../../utils/testing'; -import { readJsonInTree, updateWorkspace } from '@nrwl/workspace'; -import { createEmptyWorkspace } from '@nrwl/workspace/testing'; - -describe('add VsCode extensions file', () => { - let tree: Tree; - - beforeEach(async () => { - tree = createEmptyWorkspace(Tree.empty()); - }); - - it('add a extensions.json file', async () => { - const result = await runMigration('add-vscode-extensions', {}, tree); - const extensions = readJsonInTree(result, '.vscode/extensions.json'); - expect(extensions).toMatchInlineSnapshot(` - Object { - "recommendations": Array [ - "nrwl.angular-console", - "ms-vscode.vscode-typescript-tslint-plugin", - "esbenp.prettier-vscode", - ], - } - `); - }); - - describe('angular builders', () => { - beforeEach(async () => { - tree = await callRule( - chain([ - updateWorkspace((workspace) => { - workspace.projects - .add({ - name: 'project', - root: 'apps/project', - sourceRoot: 'apps/project/src', - }) - .targets.add({ - builder: '@nrwl/node:builder', - name: 'builder', - }); - - workspace.projects - .add({ - name: 'angular-project', - root: 'apps/angular-project', - sourceRoot: 'apps/angular-project/src', - }) - .targets.add({ - builder: '@angular-devkit/build-angular:browser', - name: 'builder', - }); - }), - ]), - tree - ); - }); - - it('add a extensions.json file with the angular extension', async () => { - const result = await runMigration('add-vscode-extensions', {}, tree); - const extensions = readJsonInTree(result, '.vscode/extensions.json'); - expect(extensions).toMatchInlineSnapshot(` - Object { - "recommendations": Array [ - "nrwl.angular-console", - "ms-vscode.vscode-typescript-tslint-plugin", - "esbenp.prettier-vscode", - "angular.ng-template", - ], - } - `); - }); - }); -}); diff --git a/packages/workspace/src/migrations/update-10-3-0/add-vscode-extensions.ts b/packages/workspace/src/migrations/update-10-3-0/add-vscode-extensions.ts deleted file mode 100644 index e6685ae4beaa9..0000000000000 --- a/packages/workspace/src/migrations/update-10-3-0/add-vscode-extensions.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { Rule, Tree } from '@angular-devkit/schematics'; -import { serializeJson } from '@nrwl/devkit'; -import { getWorkspace } from '@nrwl/workspace'; - -export default function (): Rule { - return async (host: Tree) => { - if (host.exists('.vscode/extensions.json')) { - return; - } - - const workspace = await getWorkspace(host); - - let needsAngularExtension = false; - - for (let [, project] of workspace.projects) { - needsAngularExtension = Array.from(project.targets).some( - ([, targetDefinition]) => - targetDefinition.builder.startsWith('@angular-devkit') - ); - - if (needsAngularExtension) break; - } - - const extensions = [ - 'nrwl.angular-console', - 'ms-vscode.vscode-typescript-tslint-plugin', - 'esbenp.prettier-vscode', - ]; - - if (needsAngularExtension) { - extensions.push('angular.ng-template'); - } - - host.create( - '.vscode/extensions.json', - serializeJson({ - recommendations: extensions, - }) - ); - }; -} diff --git a/packages/workspace/src/migrations/update-10-3-0/update-typescript.ts b/packages/workspace/src/migrations/update-10-3-0/update-typescript.ts deleted file mode 100644 index 7fe517d0b50cb..0000000000000 --- a/packages/workspace/src/migrations/update-10-3-0/update-typescript.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { chain } from '@angular-devkit/schematics'; -import { updatePackagesInPackageJson } from '../../utils/update-packages-in-package-json'; -import { join } from 'path'; - -import { formatFiles } from '../../utils/rules/format-files'; - -const updatePackages = updatePackagesInPackageJson( - join(__dirname, '../../..', 'migrations.json'), - '10.3.0' -); - -export default function () { - return chain([updatePackages, formatFiles()]); -} diff --git a/packages/workspace/src/migrations/update-10-4-0/add-explicit-dep-on-tao.ts b/packages/workspace/src/migrations/update-10-4-0/add-explicit-dep-on-tao.ts deleted file mode 100644 index 3a8fae96ceacd..0000000000000 --- a/packages/workspace/src/migrations/update-10-4-0/add-explicit-dep-on-tao.ts +++ /dev/null @@ -1,25 +0,0 @@ -import { chain, Rule } from '@angular-devkit/schematics'; -import { formatFiles } from '../../utils/rules/format-files'; -import { nxVersion } from '../../utils/versions'; -import { sortObjectByKeys, updateJsonInTree } from '../../utils/ast-utils'; - -export default function update(): Rule { - return chain([ - updateJsonInTree('package.json', (json) => { - json.dependencies = json.dependencies || {}; - - json.devDependencies = json.devDependencies || {}; - - delete json.dependencies['@nrwl/cli']; - json.devDependencies['@nrwl/cli'] = nxVersion; - delete json.dependencies['@nrwl/tao']; - json.devDependencies['@nrwl/tao'] = nxVersion; - - json.dependencies = sortObjectByKeys(json.dependencies); - json.devDependencies = sortObjectByKeys(json.devDependencies); - - return json; - }), - formatFiles(), - ]); -} diff --git a/packages/workspace/src/migrations/update-10-4-0/update-script-to-invoke-nx-migrate.ts b/packages/workspace/src/migrations/update-10-4-0/update-script-to-invoke-nx-migrate.ts deleted file mode 100644 index 5ab00ae715b87..0000000000000 --- a/packages/workspace/src/migrations/update-10-4-0/update-script-to-invoke-nx-migrate.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Rule } from '@angular-devkit/schematics'; -import { updateJsonInTree } from '@nrwl/workspace'; - -export default function update(): Rule { - return updateJsonInTree('package.json', (json) => { - if (json.scripts && json.scripts.update) { - json.scripts.update = 'nx migrate latest'; - } - return json; - }); -} diff --git a/packages/workspace/src/migrations/update-11-0-0/add-outputs-in-workspace.spec.ts b/packages/workspace/src/migrations/update-11-0-0/add-outputs-in-workspace.spec.ts deleted file mode 100644 index 36db196cdaeac..0000000000000 --- a/packages/workspace/src/migrations/update-11-0-0/add-outputs-in-workspace.spec.ts +++ /dev/null @@ -1,76 +0,0 @@ -import { Tree } from '@angular-devkit/schematics'; -import { readWorkspace } from '@nrwl/workspace'; -import { - SchematicTestRunner, - UnitTestTree, -} from '@angular-devkit/schematics/testing'; -import { join } from 'path'; - -describe('add `outputs` in workspace', () => { - let tree: Tree; - let schematicRunner: SchematicTestRunner; - - beforeEach(async () => { - tree = new UnitTestTree(Tree.empty()); - - schematicRunner = new SchematicTestRunner( - '@nrwl/workspace', - join(__dirname, '../../../migrations.json') - ); - }); - - it('based on the builder', async () => { - tree.create( - 'workspace.json', - JSON.stringify({ - projects: { - products: { - root: 'apps/products', - architect: { - build: { - builder: '@nrwl/jest:jest', - }, - serve: { - builder: 'whatever', - }, - }, - }, - cart: { - architect: { - build: { - builder: '@nrwl/web:build', - }, - buildWithOutputsDefined: { - builder: '@nrwl/web:build', - outputs: ['test/dir'], - }, - }, - }, - noArchitect: { - projectType: 'library', - }, - }, - }) - ); - - await schematicRunner - .runSchematicAsync('add-outputs-in-workspace', {}, tree) - .toPromise(); - - const config = readWorkspace(tree); - const { products, cart, noArchitect } = config.projects; - expect(products.architect.build.outputs).toEqual([ - 'coverage/apps/products', - ]); - expect(products.architect.serve.outputs).toBeUndefined(); - - expect(cart.architect.build.outputs).toEqual(['{options.outputPath}']); - expect(cart.architect.buildWithOutputsDefined.outputs).toEqual([ - 'test/dir', - ]); - - expect(noArchitect).toEqual({ - projectType: 'library', - }); - }); -}); diff --git a/packages/workspace/src/migrations/update-11-0-0/add-outputs-in-workspace.ts b/packages/workspace/src/migrations/update-11-0-0/add-outputs-in-workspace.ts deleted file mode 100644 index 9871d5f41d682..0000000000000 --- a/packages/workspace/src/migrations/update-11-0-0/add-outputs-in-workspace.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { chain, Rule } from '@angular-devkit/schematics'; -import { updateWorkspaceInTree } from '@nrwl/workspace'; - -const addOutputs = () => - updateWorkspaceInTree((workspace) => { - for (const [, project] of Object.entries(workspace.projects)) { - for (const [, target] of Object.entries(project.architect || {})) { - const builder = target?.builder; - - if (!builder || target.outputs) { - continue; // Do not mess with already defined outputs from user - } - - if ( - ['@nrwl/jest:jest', '@angular-devkit/build-angular:karma'].includes( - builder - ) - ) { - target.outputs = [`coverage/${project.root}`]; - } else if ( - [ - '@angular-devkit/build-angular:browser', - '@nrwl/next:build', - '@nrwl/node:build', - '@nrwl/node:package', - '@nrwl/web:build', - '@nrwl/web:package', - '@nrwl/storybook:build', - ].includes(builder) - ) { - target.outputs = ['{options.outputPath}']; - } - } - } - - return workspace; - }); - -export default function update(): Rule { - return chain([addOutputs()]); -} diff --git a/packages/workspace/src/migrations/update-11-0-0/rename-workspace-schematic-script.ts b/packages/workspace/src/migrations/update-11-0-0/rename-workspace-schematic-script.ts deleted file mode 100644 index 80a8d0042acde..0000000000000 --- a/packages/workspace/src/migrations/update-11-0-0/rename-workspace-schematic-script.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { updateJsonInTree } from '@nrwl/workspace'; - -export default function renameWorkspaceSchematicScript() { - return updateJsonInTree('package.json', (json) => { - if (json.scripts && json.scripts['workspace-schematic']) { - delete json.scripts['workspace-schematic']; - json.scripts['workspace-generator'] = 'nx workspace-generator'; - } - return json; - }); -} diff --git a/packages/workspace/src/migrations/update-11-0-0/rename-workspace-schematics.ts b/packages/workspace/src/migrations/update-11-0-0/rename-workspace-schematics.ts deleted file mode 100644 index 1bebaada87499..0000000000000 --- a/packages/workspace/src/migrations/update-11-0-0/rename-workspace-schematics.ts +++ /dev/null @@ -1,11 +0,0 @@ -import { Rule } from '@angular-devkit/schematics'; -import { existsSync } from 'fs'; -import { moveSync } from 'fs-extra'; - -export default function update(): Rule { - return () => { - if (existsSync('tools/schematics')) { - moveSync('tools/schematics', 'tools/generators'); - } - }; -} diff --git a/packages/workspace/src/migrations/update-11-0-0/update-command-check.ts b/packages/workspace/src/migrations/update-11-0-0/update-command-check.ts deleted file mode 100644 index 7466c8554ec69..0000000000000 --- a/packages/workspace/src/migrations/update-11-0-0/update-command-check.ts +++ /dev/null @@ -1,42 +0,0 @@ -export default function update() { - return () => { - if (process.argv[2] === 'update') { - console.log( - '-------------------------------------------------------------' - ); - console.log( - '-------------------------------------------------------------' - ); - console.log( - '-------------------------------------------------------------' - ); - console.log( - `Nx provides a much improved version of "ng update". It runs the same migrations, but allows you to:` - ); - console.log(`- rerun the same migration multiple times`); - console.log(`- reorder migrations`); - console.log(`- skip migrations`); - console.log(`- fix migrations that "almost work"`); - console.log(`- commit a partially migrated state`); - console.log(`- change versions of packages to match org requirements`); - console.log( - `And, in general, it is lot more reliable for non-trivial workspaces. Read more at: https://nx.dev/latest/angular/workspace/update` - ); - console.log( - `Run "nx migrate latest" to update to the latest version of Nx.` - ); - console.log( - '-------------------------------------------------------------' - ); - console.log( - '-------------------------------------------------------------' - ); - console.log( - '-------------------------------------------------------------' - ); - throw new Error( - `Use "nx migrate" instead of "ng update". Read more at: Read more at: https://nx.dev/latest/angular/workspace/update` - ); - } - }; -} diff --git a/packages/workspace/src/migrations/update-11-0-0/update-decorate-angular-cli.ts b/packages/workspace/src/migrations/update-11-0-0/update-decorate-angular-cli.ts deleted file mode 100644 index 44b0584f0dece..0000000000000 --- a/packages/workspace/src/migrations/update-11-0-0/update-decorate-angular-cli.ts +++ /dev/null @@ -1,21 +0,0 @@ -import { join as pathJoin } from 'path'; -import { readFileSync } from 'fs'; -import { Tree } from '@angular-devkit/schematics'; - -export default function update() { - return (host: Tree) => { - const decorateCli = readFileSync( - pathJoin( - __dirname as any, - '..', - '..', - 'generators', - 'utils', - 'decorate-angular-cli.js__tmpl__' - ) - ).toString(); - if (host.exists('/decorate-angular-cli.js')) { - host.overwrite('/decorate-angular-cli.js', decorateCli); - } - }; -} diff --git a/packages/workspace/src/migrations/update-11-0-0/update-node-types.ts b/packages/workspace/src/migrations/update-11-0-0/update-node-types.ts deleted file mode 100644 index bd7b7484ffe5f..0000000000000 --- a/packages/workspace/src/migrations/update-11-0-0/update-node-types.ts +++ /dev/null @@ -1,14 +0,0 @@ -import { chain } from '@angular-devkit/schematics'; -import { updatePackagesInPackageJson } from '../../utils/update-packages-in-package-json'; -import { join } from 'path'; - -import { formatFiles } from '../../utils/rules/format-files'; - -const updatePackages = updatePackagesInPackageJson( - join(__dirname, '../../..', 'migrations.json'), - '11.0.0' -); - -export default function () { - return chain([updatePackages, formatFiles()]); -} diff --git a/packages/workspace/src/migrations/update-11-1-2/update-11-1-2.ts b/packages/workspace/src/migrations/update-11-1-2/update-11-1-2.ts deleted file mode 100644 index 2d290e898c131..0000000000000 --- a/packages/workspace/src/migrations/update-11-1-2/update-11-1-2.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { chain } from '@angular-devkit/schematics'; -import { formatFiles, updatePackagesInPackageJson } from '@nrwl/workspace'; -import { join } from 'path'; - -const updatePackages = updatePackagesInPackageJson( - join(__dirname, '../../../', 'migrations.json'), - '11.1.2' -); - -export default function () { - return chain([updatePackages, formatFiles()]); -} diff --git a/packages/workspace/src/migrations/update-13-9-0/update-decorate-cli.ts b/packages/workspace/src/migrations/update-13-9-0/update-decorate-cli.ts new file mode 100644 index 0000000000000..d5fca075a9213 --- /dev/null +++ b/packages/workspace/src/migrations/update-13-9-0/update-decorate-cli.ts @@ -0,0 +1,13 @@ +import { Tree } from '@nrwl/devkit'; + +export function updateDecorateAngularCLI(host: Tree) { + const decorate = host.read('decorate-angular-cli.js').toString(); + if (decorate) { + host.write( + 'decorate-angular-cli.js', + decorate.replace('@nrwl/cli/lib/decorate-cli', 'nx/src/cli/decorate-cli') + ); + } +} + +export default updateDecorateAngularCLI; diff --git a/packages/workspace/src/tasks-runner/batch/run-batch.ts b/packages/workspace/src/tasks-runner/batch/run-batch.ts index 854f719891ba6..917d081af862b 100644 --- a/packages/workspace/src/tasks-runner/batch/run-batch.ts +++ b/packages/workspace/src/tasks-runner/batch/run-batch.ts @@ -4,9 +4,9 @@ import { BatchMessageType, } from './batch-messages'; import { TaskGraph } from '@nrwl/devkit'; -import { ExecutorContext, Workspaces } from '@nrwl/tao/src/shared/workspace'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; -import { combineOptionsForExecutor } from '@nrwl/tao/src/shared/params'; +import { ExecutorContext, Workspaces } from 'nx/src/shared/workspace'; +import { appRootPath } from 'nx/src/utils/app-root'; +import { combineOptionsForExecutor } from 'nx/src/shared/params'; function getBatchExecutor(executorName: string) { const workspace = new Workspaces(appRootPath); diff --git a/packages/workspace/src/tasks-runner/cache.ts b/packages/workspace/src/tasks-runner/cache.ts index e2f2f4c9af939..4fd1edc61343c 100644 --- a/packages/workspace/src/tasks-runner/cache.ts +++ b/packages/workspace/src/tasks-runner/cache.ts @@ -1,4 +1,4 @@ -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { Task } from '@nrwl/devkit'; import { copy, diff --git a/packages/workspace/src/tasks-runner/forked-process-task-runner.ts b/packages/workspace/src/tasks-runner/forked-process-task-runner.ts index 0863385a37cff..a004a246870c4 100644 --- a/packages/workspace/src/tasks-runner/forked-process-task-runner.ts +++ b/packages/workspace/src/tasks-runner/forked-process-task-runner.ts @@ -1,7 +1,7 @@ import { readFileSync, writeFileSync } from 'fs'; import * as dotenv from 'dotenv'; import { ChildProcess, fork } from 'child_process'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { DefaultTasksRunnerOptions } from './default-tasks-runner'; import { Task } from './tasks-runner'; import { output } from '../utilities/output'; diff --git a/packages/workspace/src/tasks-runner/run-command.ts b/packages/workspace/src/tasks-runner/run-command.ts index b99532c15cc73..6c893af477695 100644 --- a/packages/workspace/src/tasks-runner/run-command.ts +++ b/packages/workspace/src/tasks-runner/run-command.ts @@ -1,6 +1,6 @@ import { TasksRunner, TaskStatus } from './tasks-runner'; import { join } from 'path'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import type { NxJsonConfiguration, ProjectGraph, @@ -9,7 +9,7 @@ import type { Task, } from '@nrwl/devkit'; import { logger } from '@nrwl/devkit'; -import { stripIndent } from '@nrwl/tao/src/shared/logger'; +import { stripIndent } from 'nx/src/shared/logger'; import { Environment } from '../core/shared-interfaces'; import { NxArgs } from '../command-line/utils'; import { isRelativePath } from '../utilities/fileutils'; diff --git a/packages/workspace/src/tasks-runner/task-orchestrator.ts b/packages/workspace/src/tasks-runner/task-orchestrator.ts index 4021812a1821b..ef2563ff9eff6 100644 --- a/packages/workspace/src/tasks-runner/task-orchestrator.ts +++ b/packages/workspace/src/tasks-runner/task-orchestrator.ts @@ -1,9 +1,9 @@ -import { Workspaces } from '@nrwl/tao/src/shared/workspace'; +import { Workspaces } from 'nx/src/shared/workspace'; import type { ProjectGraph, Task, TaskGraph } from '@nrwl/devkit'; import { performance } from 'perf_hooks'; import { Hasher } from '../core/hasher/hasher'; import { ForkedProcessTaskRunner } from './forked-process-task-runner'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { Cache } from './cache'; import { DefaultTasksRunnerOptions } from './default-tasks-runner'; import { TaskStatus } from './tasks-runner'; diff --git a/packages/workspace/src/tasks-runner/tasks-schedule.spec.ts b/packages/workspace/src/tasks-runner/tasks-schedule.spec.ts index d522d9c7a4ab7..baa7306af780e 100644 --- a/packages/workspace/src/tasks-runner/tasks-schedule.spec.ts +++ b/packages/workspace/src/tasks-runner/tasks-schedule.spec.ts @@ -1,6 +1,6 @@ import { TasksSchedule } from './tasks-schedule'; import { Task, TaskGraph } from '@nrwl/devkit'; -import { Workspaces } from '@nrwl/tao/src/shared/workspace'; +import { Workspaces } from 'nx/src/shared/workspace'; import { removeTasksFromTaskGraph } from '@nrwl/workspace/src/tasks-runner/utils'; function createMockTask(id: string): Task { diff --git a/packages/workspace/src/tasks-runner/tasks-schedule.ts b/packages/workspace/src/tasks-runner/tasks-schedule.ts index 375cfc462bab9..9ca8851a6c08e 100644 --- a/packages/workspace/src/tasks-runner/tasks-schedule.ts +++ b/packages/workspace/src/tasks-runner/tasks-schedule.ts @@ -5,7 +5,7 @@ import { WorkspaceConfiguration, } from '@nrwl/devkit'; -import { Workspaces } from '@nrwl/tao/src/shared/workspace'; +import { Workspaces } from 'nx/src/shared/workspace'; import { calculateReverseDeps, diff --git a/packages/workspace/src/tasks-runner/utils.ts b/packages/workspace/src/tasks-runner/utils.ts index 763e050ebd35d..26e215628d97a 100644 --- a/packages/workspace/src/tasks-runner/utils.ts +++ b/packages/workspace/src/tasks-runner/utils.ts @@ -8,14 +8,14 @@ import { } from '@nrwl/devkit'; import { flatten } from 'flat'; import { output } from '../utilities/output'; -import { Workspaces } from '@nrwl/tao/src/shared/workspace'; +import { Workspaces } from 'nx/src/shared/workspace'; import { mergeNpmScriptsWithTargets } from '../utilities/project-graph-utils'; import { existsSync } from 'fs'; import { join } from 'path'; import { loadNxPlugins, mergePluginTargetsWithNxTargets, -} from '@nrwl/tao/src/shared/nx-plugin'; +} from 'nx/src/shared/nx-plugin'; export function getCommandAsString(task: Task) { const execCommand = getPackageManagerCommand().exec; @@ -232,7 +232,7 @@ export function calculateReverseDeps( } export function getCliPath(workspaceRoot: string) { - const cli = require.resolve(`@nrwl/cli/lib/run-cli.js`, { + const cli = require.resolve(`nx/src/cli/run-cli.js`, { paths: [workspaceRoot], }); return `${cli}`; diff --git a/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.spec.ts b/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.spec.ts index a52355944219c..241a9faba49e1 100644 --- a/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.spec.ts +++ b/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.spec.ts @@ -12,7 +12,7 @@ import { mapProjectGraphFiles } from '../utils/runtime-lint-utils'; import { FileData } from '@nrwl/devkit'; jest.mock('fs', () => require('memfs').fs); -jest.mock('@nrwl/tao/src/utils/app-root', () => ({ appRootPath: '/root' })); +jest.mock('nx/src/utils/app-root', () => ({ appRootPath: '/root' })); const tsconfig = { compilerOptions: { diff --git a/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.ts b/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.ts index c8995cf481e0e..e57a56b5917af 100644 --- a/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.ts +++ b/packages/workspace/src/tslint/nxEnforceModuleBoundariesRule.ts @@ -6,7 +6,7 @@ import type { ProjectGraphExternalNode, } from '@nrwl/devkit'; import { ProjectType, readCachedProjectGraph } from '../core/project-graph'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { DepConstraint, findConstraintsFor, diff --git a/packages/workspace/src/utilities/cache-directory.ts b/packages/workspace/src/utilities/cache-directory.ts index 96cd576df568b..052ff20913d0b 100644 --- a/packages/workspace/src/utilities/cache-directory.ts +++ b/packages/workspace/src/utilities/cache-directory.ts @@ -1,6 +1,6 @@ import { NxJsonConfiguration, readJsonFile } from '@nrwl/devkit'; import { join, isAbsolute } from 'path'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; function readCacheDirectoryProperty(root: string): string | undefined { try { diff --git a/packages/workspace/src/utilities/fileutils.spec.ts b/packages/workspace/src/utilities/fileutils.spec.ts index 4c8b8a02f1e86..d78f7c2994bb5 100644 --- a/packages/workspace/src/utilities/fileutils.spec.ts +++ b/packages/workspace/src/utilities/fileutils.spec.ts @@ -3,7 +3,6 @@ import { stripIndents } from '@angular-devkit/core/src/utils/literals'; import { createDirectory, isRelativePath } from './fileutils'; jest.mock('fs', () => require('memfs').fs); -jest.mock('./app-root', () => ({ appRootPath: '/root' })); describe('fileutils', () => { beforeEach(() => { diff --git a/packages/workspace/src/utilities/generate-globs.ts b/packages/workspace/src/utilities/generate-globs.ts index 4b6b2b54fbbdd..5dd44e424ed0a 100644 --- a/packages/workspace/src/utilities/generate-globs.ts +++ b/packages/workspace/src/utilities/generate-globs.ts @@ -1,5 +1,5 @@ import { joinPathFragments } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { relative, resolve } from 'path'; import { readCachedProjectGraph } from '../core/project-graph'; import { diff --git a/packages/workspace/src/utilities/plugins/plugin-capabilities.ts b/packages/workspace/src/utilities/plugins/plugin-capabilities.ts index e56b9acdd22ce..97426e5286eef 100644 --- a/packages/workspace/src/utilities/plugins/plugin-capabilities.ts +++ b/packages/workspace/src/utilities/plugins/plugin-capabilities.ts @@ -1,5 +1,5 @@ import { getPackageManagerCommand, readJsonFile } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import * as chalk from 'chalk'; import { dirname, join } from 'path'; import { output } from '../output'; diff --git a/packages/workspace/src/utilities/project-graph-utils.spec.ts b/packages/workspace/src/utilities/project-graph-utils.spec.ts index f3a252e5d0895..9e787c027a88e 100644 --- a/packages/workspace/src/utilities/project-graph-utils.spec.ts +++ b/packages/workspace/src/utilities/project-graph-utils.spec.ts @@ -1,4 +1,4 @@ -import { PackageJson } from '@nrwl/tao/src/shared/package-json'; +import { PackageJson } from 'nx/src/shared/package-json'; import { ProjectGraph } from '../core/project-graph'; import { getProjectNameFromDirPath, diff --git a/packages/workspace/src/utilities/project-graph-utils.ts b/packages/workspace/src/utilities/project-graph-utils.ts index 790e5e2e84107..aea8fe322b05d 100644 --- a/packages/workspace/src/utilities/project-graph-utils.ts +++ b/packages/workspace/src/utilities/project-graph-utils.ts @@ -5,10 +5,7 @@ import { readJsonFile, TargetConfiguration, } from '@nrwl/devkit'; -import { - buildTargetFromScript, - PackageJson, -} from '@nrwl/tao/src/shared/package-json'; +import { buildTargetFromScript, PackageJson } from 'nx/src/shared/package-json'; import { join, relative } from 'path'; import { readCachedProjectGraph } from '../core/project-graph'; diff --git a/packages/workspace/src/utilities/typescript.ts b/packages/workspace/src/utilities/typescript.ts index f3218cd9b502e..ea170c21091df 100644 --- a/packages/workspace/src/utilities/typescript.ts +++ b/packages/workspace/src/utilities/typescript.ts @@ -1,5 +1,5 @@ import { offsetFromRoot, Tree } from '@nrwl/devkit'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { existsSync } from 'fs'; import { dirname, join } from 'path'; import type * as ts from 'typescript'; diff --git a/packages/workspace/src/utils/app-root.ts b/packages/workspace/src/utils/app-root.ts index a99e95e2f478a..2889f75f59298 100644 --- a/packages/workspace/src/utils/app-root.ts +++ b/packages/workspace/src/utils/app-root.ts @@ -1 +1 @@ -export { appRootPath } from '@nrwl/tao/src/utils/app-root'; +export { appRootPath } from 'nx/src/utils/app-root'; diff --git a/packages/workspace/src/utils/rules/format-files.spec.ts b/packages/workspace/src/utils/rules/format-files.spec.ts index a819e92a4b67b..0af7ed0d1675d 100644 --- a/packages/workspace/src/utils/rules/format-files.spec.ts +++ b/packages/workspace/src/utils/rules/format-files.spec.ts @@ -3,10 +3,10 @@ import { Tree } from '@angular-devkit/schematics'; import * as prettier from 'prettier'; import * as path from 'path'; -import * as taoWorkspace from '@nrwl/tao/src/shared/workspace'; +import * as nxWorkspace from 'nx/src/shared/workspace'; import { formatFiles } from './format-files'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; describe('formatFiles', () => { let tree: Tree; @@ -14,7 +14,7 @@ describe('formatFiles', () => { beforeAll(() => { jest - .spyOn(taoWorkspace, 'workspaceConfigName') + .spyOn(nxWorkspace, 'workspaceConfigName') .mockReturnValue('workspace.json'); }); diff --git a/packages/workspace/src/utils/rules/format-files.ts b/packages/workspace/src/utils/rules/format-files.ts index ae7980e300964..27c76a3aff103 100644 --- a/packages/workspace/src/utils/rules/format-files.ts +++ b/packages/workspace/src/utils/rules/format-files.ts @@ -9,11 +9,11 @@ import { import { from } from 'rxjs'; import { filter, map, mergeMap } from 'rxjs/operators'; import * as path from 'path'; -import { appRootPath } from '@nrwl/tao/src/utils/app-root'; +import { appRootPath } from 'nx/src/utils/app-root'; import { reformattedWorkspaceJsonOrNull, workspaceConfigName, -} from '@nrwl/tao/src/shared/workspace'; +} from 'nx/src/shared/workspace'; import { parseJson, serializeJson } from '@nrwl/devkit'; export function formatFiles( diff --git a/scripts/depcheck/missing.ts b/scripts/depcheck/missing.ts index 2914af86b39c2..dfa0d461de732 100644 --- a/scripts/depcheck/missing.ts +++ b/scripts/depcheck/missing.ts @@ -2,7 +2,7 @@ import * as depcheck from 'depcheck'; // Ignore packages that are defined here per package const IGNORE_MATCHES = { - '*': ['@nrwl/tao', '@nrwl/workspace', 'prettier', 'typescript', 'dotenv'], + '*': ['nx', '@nrwl/workspace', 'prettier', 'typescript', 'dotenv'], angular: [ '@angular-devkit/architect', '@angular-devkit/build-angular', @@ -82,7 +82,7 @@ const IGNORE_MATCHES = { '@storybook/core', 'rxjs', ], - tao: [ + nx: [ '@angular-devkit/build-angular', '@angular-devkit/schematics', '@angular-devkit/core', diff --git a/tsconfig.base.json b/tsconfig.base.json index 404b585ad8d6e..5fd1a64a53393 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -75,7 +75,9 @@ "@nrwl/web/*": ["./packages/web/*"], "@nrwl/workspace": ["./packages/workspace"], "@nrwl/workspace/*": ["./packages/workspace/*"], - "@nrwl/workspace/testing": ["./packages/workspace/testing"] + "@nrwl/workspace/testing": ["./packages/workspace/testing"], + "nx": ["./packages/nx"], + "nx/*": ["./packages/nx/*"] } } }