Skip to content

Commit

Permalink
chore(core): reconcile functions to find project of a path
Browse files Browse the repository at this point in the history
  • Loading branch information
FrozenPandaz committed Nov 23, 2022
1 parent f90fb30 commit 6d768ba
Show file tree
Hide file tree
Showing 20 changed files with 299 additions and 291 deletions.
10 changes: 5 additions & 5 deletions packages/angular/plugins/component-testing.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,7 @@ import {
stripIndents,
workspaceRoot,
} from '@nrwl/devkit';
import { mapProjectGraphFiles } from '@nrwl/workspace/src/utils/runtime-lint-utils';
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 @@ -279,14 +278,15 @@ function withSchemaDefaults(options: any): BrowserBuilderSchema {
* this file should get cleaned up via the cypress executor
*/
function getTempStylesForTailwind(ctExecutorContext: ExecutorContext) {
const mappedGraph = mapProjectGraphFiles(ctExecutorContext.projectGraph);
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 = !!mappedGraph.allFiles[ctProjectTailwindConfig];
const isTailWindInRoot = !!mappedGraph.allFiles['tailwind.config'];
const isTailWindInCtProject = existsSync(ctProjectTailwindConfig);
const isTailWindInRoot = existsSync(
join(ctExecutorContext.root, 'tailwind.config')
);

if (isTailWindInRoot || isTailWindInCtProject) {
const pathToStyle = getTempTailwindPath(ctExecutorContext);
Expand Down
18 changes: 8 additions & 10 deletions packages/angular/src/generators/component/lib/normalize-options.ts
Original file line number Diff line number Diff line change
@@ -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
13 changes: 9 additions & 4 deletions packages/cypress/plugins/cypress-preset.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,13 @@ import {
TargetConfiguration,
workspaceRoot,
} from '@nrwl/devkit';
import { mapProjectGraphFiles } from '@nrwl/workspace/src/utils/runtime-lint-utils';
import { readProjectsConfigurationFromProjectGraph } from 'nx/src/project-graph/project-graph';
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,9 +93,11 @@ export function getProjectConfigByPath(
: configFileFromWorkspaceRoot
);

const mappedGraph = mapProjectGraphFiles(graph);
const componentTestingProjectName =
mappedGraph.allFiles[normalizedPathFromWorkspaceRoot];
const projectRootMappings = createProjectRootMappings(graph.nodes);
const componentTestingProjectName = findProjectForPath(
normalizedPathFromWorkspaceRoot,
projectRootMappings
);
if (
!componentTestingProjectName ||
!graph.nodes[componentTestingProjectName]?.data
Expand Down
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import type { FileData, ProjectGraph } from '@nrwl/devkit';
import { DependencyType } from '@nrwl/devkit';
import { mapProjectGraphFiles } from '../utils/runtime-lint-utils';
import * as parser from '@typescript-eslint/parser';
import { TSESLint } from '@typescript-eslint/utils';
import { vol } from 'memfs';
import { TargetProjectLocator } from 'nx/src/utils/target-project-locator';
import enforceModuleBoundaries, {
RULE_NAME as enforceModuleBoundariesRuleName,
} 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 @@ -1883,7 +1883,10 @@ function runRule(
projectGraph: ProjectGraph
): TSESLint.Linter.LintMessage[] {
(global as any).projectPath = `${process.cwd()}/proj`;
(global as any).projectGraph = mapProjectGraphFiles(projectGraph);
(global as any).projectGraph = projectGraph;
(global as any).projectRootMappings = createProjectRootMappings(
projectGraph.nodes
);
(global as any).targetProjectLocator = new TargetProjectLocator(
projectGraph.nodes,
projectGraph.externalNodes
Expand Down
14 changes: 9 additions & 5 deletions packages/eslint-plugin-nx/src/rules/enforce-module-boundaries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,8 @@ import {
findConstraintsFor,
findDependenciesWithTags,
findProjectUsingImport,
findSourceProject,
findProject,
findTransitiveExternalDependencies,
findTargetProject,
getSourceFilePath,
getTargetProjectBasedOnRelativeImport,
groupImports,
Expand Down Expand Up @@ -154,7 +153,7 @@ export default createESLintRule<Options, MessageIds>({
);
const fileName = normalizePath(context.getFilename());

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

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

const sourceFilePath = getSourceFilePath(fileName, projectPath);

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

if (isAbsoluteImportIntoAnotherProj) {
targetProject = findTargetProject(projectGraph, imp);
targetProject = findProject(projectGraph, projectRootMappings, imp);
} else {
targetProject = getTargetProjectBasedOnRelativeImport(
imp,
projectPath,
projectGraph,
projectRootMappings,
sourceFilePath
);
}
Expand Down
13 changes: 7 additions & 6 deletions packages/eslint-plugin-nx/src/rules/nx-plugin-checks.ts
Original file line number Diff line number Diff line change
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,14 +84,18 @@ export default createESLintRule<Options, MessageIds>({
return {};
}

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

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

const sourceProject = findSourceProject(projectGraph, sourceFilePath);
const sourceProject = findProject(
projectGraph,
projectRootMappings,
sourceFilePath
);
// If source is not part of an nx workspace, return.
if (!sourceProject) {
return {};
Expand Down
27 changes: 17 additions & 10 deletions packages/eslint-plugin-nx/src/utils/project-graph-utils.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import { readCachedProjectGraph, readNxJson } from '@nrwl/devkit';
import {
isTerminalRun,
MappedProjectGraph,
mapProjectGraphFiles,
} from './runtime-lint-utils';
import { ProjectGraph, readCachedProjectGraph, readNxJson } from '@nrwl/devkit';
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) {
/**
Expand All @@ -20,8 +20,9 @@ export function ensureGlobalProjectGraph(ruleName: string) {
* the ProjectGraph may or may not exist by the time the lint rule is invoked for the first time.
*/
try {
(global as any).projectGraph = mapProjectGraphFiles(
readCachedProjectGraph()
(global as any).projectGraph = readCachedProjectGraph();
(global as any).projectRootMappings = createProjectRootMappings(
(global as any).projectGraph
);
} catch {
const WARNING_PREFIX = `${chalk.reset.keyword('orange')('warning')}`;
Expand All @@ -34,7 +35,13 @@ export function ensureGlobalProjectGraph(ruleName: string) {
}
}

export function readProjectGraph(ruleName: string) {
export function readProjectGraph(ruleName: string): {
projectGraph: ProjectGraph;
projectRootMappings: ProjectRootMappings;
} {
ensureGlobalProjectGraph(ruleName);
return (global as any).projectGraph as MappedProjectGraph;
return {
projectGraph: (global as any).projectGraph,
projectRootMappings: (global as any).projectRootMappings,
};
}
90 changes: 20 additions & 70 deletions packages/eslint-plugin-nx/src/utils/runtime-lint-utils.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import * as path from 'path';
import { join } from 'path';
import {
ProjectGraph,
ProjectGraphDependency,
ProjectGraphProjectNode,
normalizePath,
DependencyType,
joinPathFragments,
normalizePath,
parseJson,
ProjectGraph,
ProjectGraphDependency,
ProjectGraphExternalNode,
joinPathFragments,
ProjectGraphProjectNode,
workspaceRoot,
} from '@nrwl/devkit';
import { join } from 'path';
import { getPath, pathExists } from './graph-utils';
import { existsSync } from 'fs';
import { readFileIfExisting } from 'nx/src/project-graph/file-utils';
import { TargetProjectLocator } from 'nx/src/utils/target-project-locator';

export type MappedProjectGraph<T = any> = ProjectGraph<T> & {
allFiles: Record<string, string>;
};
import {
findProjectForPath,
ProjectRootMappings,
} from 'nx/src/project-graph/utils/find-project-for-path';

export type Deps = { [projectName: string]: ProjectGraphDependency[] };
export type DepConstraint = {
Expand Down Expand Up @@ -70,10 +70,6 @@ function hasTag(proj: ProjectGraphProjectNode, tag: string) {
return tag === '*' || (proj.data.tags || []).indexOf(tag) > -1;
}

export function removeExt(file: string): string {
return file.replace(/(?<!(^|\/))\.[^/.]+$/, '');
}

export function matchImportWithWildcard(
// This may or may not contain wildcards ("*")
allowableImport: string,
Expand Down Expand Up @@ -103,7 +99,8 @@ export function isRelative(s: string) {
export function getTargetProjectBasedOnRelativeImport(
imp: string,
projectPath: string,
projectGraph: MappedProjectGraph,
projectGraph: ProjectGraph,
projectRootMappings: ProjectRootMappings,
sourceFilePath: string
): ProjectGraphProjectNode<any> | undefined {
if (!isRelative(imp)) {
Expand All @@ -115,42 +112,17 @@ export function getTargetProjectBasedOnRelativeImport(
projectPath.length + 1
);

return findTargetProject(projectGraph, targetFile);
}

export function findProjectUsingFile<T>(
projectGraph: MappedProjectGraph<T>,
file: string
): ProjectGraphProjectNode {
return projectGraph.nodes[projectGraph.allFiles[file]];
return findProject(projectGraph, projectRootMappings, targetFile);
}

export function findSourceProject(
projectGraph: MappedProjectGraph,
export function findProject(
projectGraph: ProjectGraph,
projectRootMappings: ProjectRootMappings,
sourceFilePath: string
) {
const targetFile = removeExt(sourceFilePath);
return findProjectUsingFile(projectGraph, targetFile);
}

export function findTargetProject(
projectGraph: MappedProjectGraph,
targetFile: string
) {
let targetProject = findProjectUsingFile(projectGraph, targetFile);
if (!targetProject) {
targetProject = findProjectUsingFile(
projectGraph,
normalizePath(path.join(targetFile, 'index'))
);
}
if (!targetProject) {
targetProject = findProjectUsingFile(
projectGraph,
normalizePath(path.join(targetFile, 'src', 'index'))
);
}
return targetProject;
return projectGraph.nodes[
findProjectForPath(sourceFilePath, projectRootMappings)
];
}

export function isAbsoluteImportIntoAnotherProject(
Expand All @@ -166,7 +138,7 @@ export function isAbsoluteImportIntoAnotherProject(
}

export function findProjectUsingImport(
projectGraph: MappedProjectGraph,
projectGraph: ProjectGraph,
targetProjectLocator: TargetProjectLocator,
filePath: string,
imp: string
Expand Down Expand Up @@ -353,28 +325,6 @@ export function hasBuildExecutor(
);
}

export function mapProjectGraphFiles<T>(
projectGraph: ProjectGraph<T>
): MappedProjectGraph | null {
if (!projectGraph) {
return null;
}
const allFiles: Record<string, string> = {};
Object.entries(
projectGraph.nodes as Record<string, ProjectGraphProjectNode>
).forEach(([name, node]) => {
node.data.files.forEach(({ file }) => {
const fileName = removeExt(file);
allFiles[fileName] = name;
});
});

return {
...projectGraph,
allFiles,
};
}

const ESLINT_REGEX = /node_modules.*[\/\\]eslint$/;
const JEST_REGEX = /node_modules\/.bin\/jest$/; // when we run unit tests in jest
const NRWL_CLI_REGEX = /nx[\/\\]bin[\/\\]run-executor\.js$/;
Expand Down
Loading

0 comments on commit 6d768ba

Please sign in to comment.