Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: implement Nx createNodes V2 #882

Draft
wants to merge 7 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -47,4 +47,5 @@ Thumbs.db
**/.code-pushup

# Nx workspace cache
.nx
.nx/cache
.nx/workspace-data
12 changes: 12 additions & 0 deletions e2e/nx-plugin-nx18-e2e/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"extends": ["../../.eslintrc.json"],
"ignorePatterns": ["!**/*", "code-pushup.config*.ts"],
"overrides": [
{
"files": ["*.ts", "*.tsx"],
"parserOptions": {
"project": ["e2e/nx-plugin-nx18-e2e/tsconfig.*?.json"]
}
}
]
}
23 changes: 23 additions & 0 deletions e2e/nx-plugin-nx18-e2e/project.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
{
"name": "nx-plugin-nx18-e2e",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "e2e/nx-plugin-nx18-e2e/src",
"projectType": "application",
"targets": {
"lint": {
"executor": "@nx/linter:eslint",
"outputs": ["{options.outputFile}"],
"options": {
"lintFilePatterns": ["e2e/nx-plugin-nx18-e2e/**/*.ts"]
}
},
"e2e": {
"executor": "@nx/vite:test",
"options": {
"configFile": "e2e/nx-plugin-nx18-e2e/vite.config.e2e.ts"
}
}
},
"implicitDependencies": ["test-utils", "nx-plugin"],
"tags": ["scope:tooling", "type:e2e"]
}
57 changes: 57 additions & 0 deletions e2e/nx-plugin-nx18-e2e/tests/plugin-create-nodes.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import { join } from 'node:path';
import { afterEach, expect } from 'vitest';
import {
nxShowProjectJson,
registerPluginInNxJson,
} from '@code-pushup/test-nx-utils';
import { teardownTestFolder } from '@code-pushup/test-setup';
import { executeProcess } from '@code-pushup/utils';

describe('nx-plugin-nx18', () => {
const project = 'my-lib';
const envRoot = 'tmp/e2e/nx-plugin-nx18-e2e';
const baseDir = join(envRoot, '__test__/plugin/create-nodes');

beforeEach(async () => {
await executeProcess({
command: 'npx',
args: [
'--yes',
'create-nx-workspace@18.3.5',
'__test__/plugin/create-nodes/nxv18',
'--preset=apps',
'--appName=my-app',
'--style=none',
'--packageManager=npm',
'--interactive=false',
'--ci=skip',
],
cwd: envRoot,
});
await registerPluginInNxJson(
join(envRoot, 'code-pushup.config.ts'),
'@code-pushup/nx-plugin',
);
});

afterEach(async () => {
await teardownTestFolder(baseDir);
});

it('should add configuration target dynamically in nx18', async () => {
const { code, projectJson } = await nxShowProjectJson(envRoot, project);
expect(code).toBe(0);

expect(projectJson.targets).toStrictEqual({
['code-pushup--configuration']: {
configurations: {},
executor: 'nx:run-commands',
options: {
command: `nx g @code-pushup/nx-plugin:configuration --skipTarget --targetName="code-pushup" --project="${project}"`,
},
},
});

expect(projectJson.targets).toMatchSnapshot();
});
}, 300000);
20 changes: 20 additions & 0 deletions e2e/nx-plugin-nx18-e2e/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"extends": "../../tsconfig.base.json",
"compilerOptions": {
"module": "ESNext",
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"types": ["vitest"]
},
"files": [],
"include": [],
"references": [
{
"path": "./tsconfig.test.json"
}
]
}
13 changes: 13 additions & 0 deletions e2e/nx-plugin-nx18-e2e/tsconfig.test.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "../../dist/out-tsc",
"types": ["vitest/globals", "vitest/importMeta", "vite/client", "node"]
},
"include": [
"vite.config.e2e.ts",
"tests/**/*.e2e.test.ts",
"tests/**/*.d.ts",
"mocks/**/*.ts"
]
}
21 changes: 21 additions & 0 deletions e2e/nx-plugin-nx18-e2e/vite.config.e2e.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
/// <reference types="vitest" />
import { defineConfig } from 'vite';
import { tsconfigPathAliases } from '../../tools/vitest-tsconfig-path-aliases';

export default defineConfig({
cacheDir: '../../node_modules/.vite/nx-plugin-nx18-e2e',
test: {
reporters: ['basic'],
testTimeout: 160_000,
globals: true,
alias: tsconfigPathAliases(),
pool: 'threads',
poolOptions: { threads: { singleThread: true } },
cache: {
dir: '../../node_modules/.vitest',
},
environment: 'node',
include: ['tests/**/*.e2e.test.{js,mjs,cjs,ts,mts,cts,jsx,tsx}'],
setupFiles: ['../../testing/test-setup/src/lib/reset.mocks.ts'],
},
});
2 changes: 1 addition & 1 deletion packages/nx-plugin/src/executors/cli/utils.unit.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ describe('parseAutorunExecutorOptions', () => {
}),
);

expect(osAgnosticPath(executorOptions.persist?.outputDir)).toBe(
expect(osAgnosticPath(executorOptions?.persist?.outputDir)).toBe(
osAgnosticPath('workspaceRoot/.code-pushup/my-app'),
);
});
Expand Down
50 changes: 50 additions & 0 deletions packages/nx-plugin/src/plugin/caching.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import {
type ProjectConfiguration,
readJsonFile,
writeJsonFile,
} from '@nx/devkit';
import { existsSync } from 'node:fs';
import { hashObject } from 'nx/src/hasher/file-hasher';

export function cacheKey(prefix: string, hashData: Record<string, unknown>) {
return `${prefix}-${hashObject(hashData)}`;
}

export function getCacheRecord<T>(
targetsCache: Record<string, T>,
prefix: string,
hashData: Record<string, unknown>,
) {
const targetCacheKey = cacheKey(prefix, hashData);

if (targetsCache[targetCacheKey]) {
return targetsCache[targetCacheKey];
}
return undefined;
}

export function setCacheRecord<T>(
targetsCache: Record<string, T>,
prefix: string,
hashData: Record<string, unknown>,
cacheData: T,
) {
const targetCacheKey = cacheKey(prefix, hashData);

return (targetsCache[targetCacheKey] = cacheData);
}

export function readTargetsCache(
cachePath: string,
): Record<string, Partial<ProjectConfiguration>> {
return process.env.NX_CACHE_PROJECT_GRAPH !== 'false' && existsSync(cachePath)
? readJsonFile(cachePath)
: {};
}

export function writeTargetsToCache(
cachePath: string,
results: Record<string, Partial<ProjectConfiguration>>,
) {
writeJsonFile(cachePath, results);
}
119 changes: 119 additions & 0 deletions packages/nx-plugin/src/plugin/caching.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
import * as hasher from 'nx/src/hasher/file-hasher';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { cacheKey, getCacheRecord, setCacheRecord } from './caching';

describe('cacheKey', () => {
let hashObjectSpy;

beforeEach(() => {
hashObjectSpy = vi
.spyOn(hasher, 'hashObject')
.mockImplementation(() => '42');
});

afterEach(() => {
hashObjectSpy.mockClear();
});

it('should start with provided prefix', () => {
expect(cacheKey('verdaccio', {} as Record<string, unknown>)).toMatch(
/^verdaccio-/,
);
});

it('should use hashObject to generate hash', () => {
expect(cacheKey('x', { prop: 42 } as Record<string, unknown>)).toMatch(
/[0-9]*$/,
);
expect(hashObjectSpy).toHaveBeenCalledTimes(1);
expect(hashObjectSpy).toHaveBeenCalledWith({ prop: 42 });
});

it('should generate correct hash for empty object', () => {
expect(cacheKey('x', { prop: 42 } as Record<string, unknown>)).toBe('x-42');
expect(hashObjectSpy).toHaveBeenCalledTimes(1);
expect(hashObjectSpy).toHaveBeenCalledWith({ prop: 42 });
});
});

describe('getCacheRecord', () => {
let hashObjectSpy;

beforeEach(() => {
hashObjectSpy = vi
.spyOn(hasher, 'hashObject')
.mockImplementation(() => '42');
});

afterEach(() => {
hashObjectSpy.mockClear();
});

it('should get cached data if given', () => {
const prefix = 'verdaccio';
const targetsCache = {
'verdaccio-42': 'cacheData',
};
const hashData = { prop: 42 };

expect(getCacheRecord(targetsCache, prefix, hashData)).toBe('cacheData');
});

it('should return undefined if no cache hit', () => {
const targetsCache = {};
const prefix = 'verdaccio';
const hashData = { prop: 43 };
expect(getCacheRecord(targetsCache, prefix, hashData)).toBe(undefined);
});

it('should call cacheKey and hashObject', () => {
const targetsCache = {
'verdaccio-42': 'cacheData',
};
const prefix = 'verdaccio';
const hashData = { prop: 42 };
const hashObjectSpy = vi.spyOn(hasher, 'hashObject');
getCacheRecord(targetsCache, prefix, hashData);
expect(hashObjectSpy).toHaveBeenCalledTimes(1);
expect(hashObjectSpy).toHaveBeenCalledWith({ prop: 42 });
});
});

describe('setCacheRecord', () => {
let hashObjectSpy;

beforeEach(() => {
hashObjectSpy = vi
.spyOn(hasher, 'hashObject')
.mockImplementation(() => '42');
});

afterEach(() => {
hashObjectSpy.mockClear();
});

it('should set cached data if given', () => {
const prefix = 'verdaccio';
const targetsCache = {};
const hashData = { prop: 42 };
expect(getCacheRecord(targetsCache, prefix, hashData)).toStrictEqual(
undefined,
);
expect(
setCacheRecord(targetsCache, prefix, hashData, { test: 41 }),
).not.toThrowError();
expect(getCacheRecord(targetsCache, prefix, hashData)).toStrictEqual({
test: 41,
});
});

it('should return cached data after setting', () => {
const prefix = 'verdaccio';
const targetsCache = {};
const hashData = { prop: 42 };

expect(
setCacheRecord(targetsCache, prefix, hashData, { test: 41 }),
).toStrictEqual({ test: 41 });
});
});
1 change: 1 addition & 0 deletions packages/nx-plugin/src/plugin/constants.ts
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
export const PLUGIN_NAME = '@code-pushup/nx-plugin';
export const CP_TARGET_NAME = 'code-pushup';
Loading
Loading