Skip to content

Commit

Permalink
chore(core): reconcile functions to find project of a path (#13364)
Browse files Browse the repository at this point in the history
  • Loading branch information
FrozenPandaz committed Nov 24, 2022
1 parent 0e54262 commit 6d35fd4
Show file tree
Hide file tree
Showing 28 changed files with 373 additions and 412 deletions.
23 changes: 14 additions & 9 deletions packages/angular/plugins/component-testing.ts
Expand Up @@ -21,8 +21,7 @@ import {
stripIndents,
workspaceRoot,
} from '@nrwl/devkit';
import { createProjectFileMappings } from 'nx/src/utils/target-project-locator';
import { lstatSync, mkdirSync, writeFileSync } from 'fs';
import { existsSync, lstatSync, mkdirSync, writeFileSync } from 'fs';
import { dirname, join, relative } from 'path';
import type { BrowserBuilderSchema } from '../src/builders/webpack-browser/webpack-browser.impl';

Expand Down Expand Up @@ -74,7 +73,7 @@ ${e.stack ? e.stack : e}`
const buildTarget = getBuildableTarget(ctContext);

if (!buildTarget.project && !graph.nodes?.[buildTarget.project]?.data) {
throw new Error(stripIndents`Unable to find project configuration for build target.
throw new Error(stripIndents`Unable to find project configuration for build target.
Project Name? ${buildTarget.project}
Has project config? ${!!graph.nodes?.[buildTarget.project]?.data}`);
}
Expand Down Expand Up @@ -279,16 +278,22 @@ function withSchemaDefaults(options: any): BrowserBuilderSchema {
* this file should get cleaned up via the cypress executor
*/
function getTempStylesForTailwind(ctExecutorContext: ExecutorContext) {
const mappedGraphFiles = createProjectFileMappings(
ctExecutorContext.projectGraph.nodes
);
const ctProjectConfig = ctExecutorContext.projectGraph.nodes[
ctExecutorContext.projectName
].data as ProjectConfiguration;
// angular only supports `tailwind.config.{js,cjs}`
const ctProjectTailwindConfig = join(ctProjectConfig.root, 'tailwind.config');
const isTailWindInCtProject = !!mappedGraphFiles[ctProjectTailwindConfig];
const isTailWindInRoot = !!mappedGraphFiles['tailwind.config'];
const ctProjectTailwindConfig = join(
ctExecutorContext.root,
ctProjectConfig.root,
'tailwind.config'
);
const isTailWindInCtProject =
existsSync(ctProjectTailwindConfig + '.js') ||
existsSync(ctProjectTailwindConfig + '.cjs');
const rootTailwindPath = join(ctExecutorContext.root, 'tailwind.config');
const isTailWindInRoot =
existsSync(rootTailwindPath + '.js') ||
existsSync(rootTailwindPath + '.cjs');

if (isTailWindInRoot || isTailWindInCtProject) {
const pathToStyle = getTempTailwindPath(ctExecutorContext);
Expand Down
18 changes: 8 additions & 10 deletions packages/angular/src/generators/component/lib/normalize-options.ts
@@ -1,27 +1,25 @@
import type { Tree } from '@nrwl/devkit';
import {
joinPathFragments,
readCachedProjectGraph,
readProjectConfiguration,
readWorkspaceConfiguration,
} from '@nrwl/devkit';
import type { NormalizedSchema, Schema } from '../schema';
import { getProjectNameFromDirPath } from 'nx/src/utils/project-graph-utils';

function getProjectFromPath(path: string) {
try {
return getProjectNameFromDirPath(path);
} catch {
return null;
}
}
import {
createProjectRootMappings,
findProjectForPath,
} from 'nx/src/project-graph/utils/find-project-for-path';

export function normalizeOptions(
tree: Tree,
options: Schema
): NormalizedSchema {
const projectGraph = readCachedProjectGraph();
const projectRootMappings = createProjectRootMappings(projectGraph.nodes);
const project =
options.project ??
getProjectFromPath(options.path) ??
findProjectForPath(options.path, projectRootMappings) ??
readWorkspaceConfiguration(tree).defaultProject;
const { projectType, root, sourceRoot } = readProjectConfiguration(
tree,
Expand Down
@@ -1,7 +1,6 @@
import type { Tree } from '@nrwl/devkit';
import { getSourceNodes } from '@nrwl/workspace/src/utilities/typescript';
import { findNodes } from 'nx/src/utils/typescript';

import { getSourceNodes } from '@nrwl/workspace/src/utilities/typescript';
import type { PropertyDeclaration } from 'typescript';
import { SyntaxKind } from 'typescript';
import { getTsSourceFile } from '../../../utils/nx-devkit/ast-utils';
Expand Down
17 changes: 11 additions & 6 deletions packages/cypress/plugins/cypress-preset.ts
Expand Up @@ -9,9 +9,12 @@ import {
workspaceRoot,
} from '@nrwl/devkit';
import { readProjectsConfigurationFromProjectGraph } from 'nx/src/project-graph/project-graph';
import { createProjectFileMappings } from 'nx/src/utils/target-project-locator';
import { dirname, extname, join, relative } from 'path';
import { lstatSync } from 'fs';
import {
createProjectRootMappings,
findProjectForPath,
} from 'nx/src/project-graph/utils/find-project-for-path';

interface BaseCypressPreset {
videosFolder: string;
Expand Down Expand Up @@ -90,16 +93,18 @@ export function getProjectConfigByPath(
: configFileFromWorkspaceRoot
);

const mappedGraphFiles = createProjectFileMappings(graph.nodes);
const componentTestingProjectName =
mappedGraphFiles[normalizedPathFromWorkspaceRoot];
const projectRootMappings = createProjectRootMappings(graph.nodes);
const componentTestingProjectName = findProjectForPath(
normalizedPathFromWorkspaceRoot,
projectRootMappings
);
if (
!componentTestingProjectName ||
!graph.nodes[componentTestingProjectName]?.data
) {
throw new Error(
stripIndents`Unable to find the project configuration that includes ${normalizedPathFromWorkspaceRoot}.
Found project name? ${componentTestingProjectName}.
stripIndents`Unable to find the project configuration that includes ${normalizedPathFromWorkspaceRoot}.
Found project name? ${componentTestingProjectName}.
Graph has data? ${!!graph.nodes[componentTestingProjectName]?.data}`
);
}
Expand Down
1 change: 1 addition & 0 deletions packages/eslint-plugin-nx/.eslintrc.json
Expand Up @@ -3,6 +3,7 @@
"rules": {
"no-restricted-imports": [
"error",
"@nrwl/workspace",
"@angular-devkit/core",
"@angular-devkit/architect",
"@angular-devkit/schematics"
Expand Down
Expand Up @@ -3,13 +3,11 @@ import { DependencyType } from '@nrwl/devkit';
import * as parser from '@typescript-eslint/parser';
import { TSESLint } from '@typescript-eslint/utils';
import { vol } from 'memfs';
import {
TargetProjectLocator,
createProjectFileMappings,
} from 'nx/src/utils/target-project-locator';
import { TargetProjectLocator } from 'nx/src/utils/target-project-locator';
import enforceModuleBoundaries, {
RULE_NAME as enforceModuleBoundariesRuleName,
} from './enforce-module-boundaries';
} from '../../src/rules/enforce-module-boundaries';
import { createProjectRootMappings } from 'nx/src/project-graph/utils/find-project-for-path';

jest.mock('fs', () => require('memfs').fs);

Expand Down Expand Up @@ -1015,7 +1013,7 @@ Violation detected in:
tags: [],
implicitDependencies: [],
architect: {},
files: [createFile(`libs/other/src/index.ts`)],
files: [createFile(`libs/other/index.ts`)],
},
},
},
Expand All @@ -1033,7 +1031,6 @@ Violation detected in:
if (importKind === 'type') {
expect(failures.length).toEqual(0);
} else {
expect(failures.length).toEqual(1);
expect(failures[0].message).toEqual(
'Imports of lazy-loaded libraries are forbidden'
);
Expand Down Expand Up @@ -1145,10 +1142,7 @@ Violation detected in:
tags: [],
implicitDependencies: [],
architect: {},
files: [
createFile(`libs/mylib/src/main.ts`),
createFile(`libs/mylib/src/index.ts`),
],
files: [createFile(`libs/mylib/src/main.ts`)],
},
},
anotherlibName: {
Expand Down Expand Up @@ -1272,10 +1266,7 @@ Violation detected in:
tags: [],
implicitDependencies: [],
architect: {},
files: [
createFile(`libs/mylib/src/main.ts`, ['anotherlibName']),
createFile(`libs/mylib/src/index.ts`),
],
files: [createFile(`libs/mylib/src/main.ts`, ['anotherlibName'])],
},
},
anotherlibName: {
Expand Down Expand Up @@ -1370,7 +1361,6 @@ Circular file chain:
architect: {},
files: [
createFile(`libs/badcirclelib/src/main.ts`, ['anotherlibName']),
createFile(`libs/badcirclelib/src/index.ts`),
],
},
},
Expand Down Expand Up @@ -1894,7 +1884,7 @@ function runRule(
): TSESLint.Linter.LintMessage[] {
(global as any).projectPath = `${process.cwd()}/proj`;
(global as any).projectGraph = projectGraph;
(global as any).projectGraphFileMappings = createProjectFileMappings(
(global as any).projectRootMappings = createProjectRootMappings(
projectGraph.nodes
);
(global as any).targetProjectLocator = new TargetProjectLocator(
Expand Down
18 changes: 6 additions & 12 deletions packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.ts
Expand Up @@ -15,9 +15,8 @@ import {
findConstraintsFor,
findDependenciesWithTags,
findProjectUsingImport,
findSourceProject,
findProject,
findTransitiveExternalDependencies,
findTargetProject,
getSourceFilePath,
getTargetProjectBasedOnRelativeImport,
groupImports,
Expand Down Expand Up @@ -154,8 +153,7 @@ export default createESLintRule<Options, MessageIds>({
);
const fileName = normalizePath(context.getFilename());

const { projectGraph, projectGraphFileMappings } =
readProjectGraph(RULE_NAME);
const { projectGraph, projectRootMappings } = readProjectGraph(RULE_NAME);

if (!projectGraph) {
return {};
Expand Down Expand Up @@ -199,9 +197,9 @@ export default createESLintRule<Options, MessageIds>({

const sourceFilePath = getSourceFilePath(fileName, projectPath);

const sourceProject = findSourceProject(
const sourceProject = findProject(
projectGraph,
projectGraphFileMappings,
projectRootMappings,
sourceFilePath
);
// If source is not part of an nx workspace, return.
Expand All @@ -215,17 +213,13 @@ export default createESLintRule<Options, MessageIds>({
let targetProject: ProjectGraphProjectNode | ProjectGraphExternalNode;

if (isAbsoluteImportIntoAnotherProj) {
targetProject = findTargetProject(
projectGraph,
projectGraphFileMappings,
imp
);
targetProject = findProject(projectGraph, projectRootMappings, imp);
} else {
targetProject = getTargetProjectBasedOnRelativeImport(
imp,
projectPath,
projectGraph,
projectGraphFileMappings,
projectRootMappings,
sourceFilePath
);
}
Expand Down
12 changes: 4 additions & 8 deletions packages/eslint-plugin-nx/src/rules/nx-plugin-checks.ts
Expand Up @@ -6,10 +6,7 @@ import {
readJsonFile,
workspaceRoot,
} from '@nrwl/devkit';
import {
findSourceProject,
getSourceFilePath,
} from '../utils/runtime-lint-utils';
import { findProject, getSourceFilePath } from '../utils/runtime-lint-utils';
import { existsSync } from 'fs';
import { registerTsProject } from 'nx/src/utils/register';
import * as path from 'path';
Expand Down Expand Up @@ -87,17 +84,16 @@ export default createESLintRule<Options, MessageIds>({
return {};
}

const { projectGraph, projectGraphFileMappings } =
readProjectGraph(RULE_NAME);
const { projectGraph, projectRootMappings } = readProjectGraph(RULE_NAME);

const sourceFilePath = getSourceFilePath(
context.getFilename(),
workspaceRoot
);

const sourceProject = findSourceProject(
const sourceProject = findProject(
projectGraph,
projectGraphFileMappings,
projectRootMappings,
sourceFilePath
);
// If source is not part of an nx workspace, return.
Expand Down
17 changes: 8 additions & 9 deletions packages/eslint-plugin-nx/src/utils/project-graph-utils.ts
@@ -1,18 +1,17 @@
import { ProjectGraph, readCachedProjectGraph, readNxJson } from '@nrwl/devkit';
import { createProjectFileMappings } from 'nx/src/utils/target-project-locator';
import { isTerminalRun } from './runtime-lint-utils';
import * as chalk from 'chalk';
import {
createProjectRootMappings,
ProjectRootMappings,
} from 'nx/src/project-graph/utils/find-project-for-path';

export function ensureGlobalProjectGraph(ruleName: string) {
/**
* Only reuse graph when running from terminal
* Enforce every IDE change to get a fresh nxdeps.json
*/
if (
!(global as any).projectGraph ||
!(global as any).projectGraphFileMappings ||
!isTerminalRun()
) {
if (!(global as any).projectGraph || !isTerminalRun()) {
const nxJson = readNxJson();
(global as any).workspaceLayout = nxJson.workspaceLayout;

Expand All @@ -22,7 +21,7 @@ export function ensureGlobalProjectGraph(ruleName: string) {
*/
try {
(global as any).projectGraph = readCachedProjectGraph();
(global as any).projectGraphFileMappings = createProjectFileMappings(
(global as any).projectRootMappings = createProjectRootMappings(
(global as any).projectGraph.nodes
);
} catch {
Expand All @@ -38,11 +37,11 @@ export function ensureGlobalProjectGraph(ruleName: string) {

export function readProjectGraph(ruleName: string): {
projectGraph: ProjectGraph;
projectGraphFileMappings: Record<string, string>;
projectRootMappings: ProjectRootMappings;
} {
ensureGlobalProjectGraph(ruleName);
return {
projectGraph: (global as any).projectGraph,
projectGraphFileMappings: (global as any).projectGraphFileMappings,
projectRootMappings: (global as any).projectRootMappings,
};
}

0 comments on commit 6d35fd4

Please sign in to comment.