Skip to content

Commit

Permalink
wip
Browse files Browse the repository at this point in the history
  • Loading branch information
BioPhoton committed Dec 18, 2024
1 parent b240bba commit 15a1bea
Show file tree
Hide file tree
Showing 5 changed files with 99 additions and 65 deletions.
51 changes: 30 additions & 21 deletions e2e/nx-verdaccio-e2e/setup/setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,24 +5,29 @@ import {
objectToCliArgs,
updateJson,
} from '@push-based/test-utils';
import {copyFile, lstat, mkdir, readdir} from 'fs/promises';
import {join} from 'path';
import {dirname, join} from 'node:path';
import {copyFile, mkdir, symlink, readlink} from 'node:fs/promises';
import {logger, NxJsonConfiguration, PluginConfiguration, TargetConfiguration,} from '@nx/devkit';
import {PackageJson} from 'nx/src/utils/package-json';
import { copyFile, lstat, mkdir, readdir } from 'fs/promises';
import { join } from 'path';
import { dirname, join } from 'node:path';
import { copyFile, mkdir, symlink, readlink } from 'node:fs/promises';
import {
logger,
NxJsonConfiguration,
PluginConfiguration,
TargetConfiguration,
} from '@nx/devkit';
import { PackageJson } from 'nx/src/utils/package-json';

export async function setup({
envRoot,
projectName,
repoName,
}: {
envRoot,
projectName,
repoName,
}: {
envRoot: string;
repoName: string;
projectName: string;
}) {
// dedupe packages because symlink copy problems
await mkdir(envRoot, {recursive: true});
await mkdir(envRoot, { recursive: true });
// setup nx environment for e2e tests
logger.info(`Created nx workspace under ${envRoot}`);
await executeProcess({
Expand Down Expand Up @@ -113,7 +118,7 @@ export async function setup({
DEFAULT_TEST_FIXTURE_DIST,
repoName
),
{recursive: true}
{ recursive: true }
);
await copyFile(
join(getTestEnvironmentRoot(projectName), '.npmrc'),
Expand All @@ -123,16 +128,17 @@ export async function setup({
await executeProcess({
command: 'npm',
args: objectToCliArgs({
_: ['dedupe']
_: ['dedupe'],
}),
verbose: true,
cwd: dirname(envRoot),
});


}

export async function registerNxVerdaccioPlugin(envRoot: string, options?: PluginConfiguration) {
export async function registerNxVerdaccioPlugin(
envRoot: string,
options?: PluginConfiguration
) {
logger.info(`register nx-verdaccio plugin`);
await updateJson<NxJsonConfiguration>(join(envRoot, 'nx.json'), (json) =>
registerPluginInNxJson(json, {
Expand All @@ -142,7 +148,7 @@ export async function registerNxVerdaccioPlugin(envRoot: string, options?: Plugi
targetNames: ['e2e'],
},
},
...options
...options,
})
);
}
Expand Down Expand Up @@ -173,17 +179,20 @@ function updatePackageJsonNxTargets(
};
}


/**
* This function avoids issues with symlinks and other edge cases.
*
*/
export async function copyDirectory(src: string, dest: string, exclude: string[] = []) {
export async function copyDirectory(
src: string,
dest: string,
exclude: string[] = []
) {
// Ensure the destination directory exists
await mkdir(dest, {recursive: true});
await mkdir(dest, { recursive: true });

// Read the contents of the source directory
const entries = await readdir(src, {withFileTypes: true});
const entries = await readdir(src, { withFileTypes: true });

for (const entry of entries) {
const srcPath = join(src, entry.name);
Expand Down
40 changes: 20 additions & 20 deletions e2e/nx-verdaccio-e2e/test/plugin-create-nodes.e2e.test.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,41 @@
import type {Tree} from '@nx/devkit';
import {join} from 'node:path';
import {afterEach, beforeAll, expect} from 'vitest';
import {nxShowProjectJson,} from '@push-based/test-nx-utils';
import {copyDirectory, registerNxVerdaccioPlugin} from '../setup/setup';
import {mkdir} from 'node:fs/promises';
import {TARGET_PACKAGE_INSTALL, TARGET_PACKAGE_PUBLISH,} from '@push-based/nx-verdaccio';
import {DEFAULT_TEST_FIXTURE_DIST, getTestEnvironmentRoot} from '@push-based/test-utils';
import type { Tree } from '@nx/devkit';
import { join } from 'node:path';
import { afterEach, beforeAll, expect } from 'vitest';
import { nxShowProjectJson } from '@push-based/test-nx-utils';
import { copyDirectory, registerNxVerdaccioPlugin } from '../setup/setup';
import { mkdir } from 'node:fs/promises';
import {
TARGET_PACKAGE_INSTALL,
TARGET_PACKAGE_PUBLISH,
} from '@push-based/nx-verdaccio';
import {
DEFAULT_TEST_FIXTURE_DIST,
getTestEnvironmentRoot,
} from '@push-based/test-utils';
// eslint-disable-next-line @nx/enforce-module-boundaries
import {REPO_NAME} from "../fixtures/basic-nx-workspace";
import { REPO_NAME } from '../fixtures/basic-nx-workspace';

describe('in a fresh Nx workspace', () => {


const projectName = process.env['NX_TASK_TARGET_PROJECT'];
const envRoot = getTestEnvironmentRoot(projectName);
const basicNxReopPath = join(envRoot, DEFAULT_TEST_FIXTURE_DIST, REPO_NAME);
const baseDir = join(envRoot, DEFAULT_TEST_FIXTURE_DIST, 'create-nodes-v2');

beforeAll(async () => {
await mkdir(baseDir, {recursive: true});
await mkdir(baseDir, { recursive: true });
await copyDirectory(basicNxReopPath, baseDir, []);
})
});

afterEach(async () => {
// await teardownTestFolder(baseDir);
});
describe('with nx-verdaccio plugin installed', () => {

beforeAll(async () => {
await registerNxVerdaccioPlugin(baseDir);
})
});

it('should add package targets to library project', async () => {

const {code, projectJson} = await nxShowProjectJson(baseDir, 'pkg');
const { code, projectJson } = await nxShowProjectJson(baseDir, 'pkg');
expect(code).toBe(0);

expect(projectJson.targets).toStrictEqual({
Expand Down Expand Up @@ -69,7 +71,7 @@ describe('in a fresh Nx workspace', () => {

expect(projectJson.targets).toMatchSnapshot();
});
/*
/*
it('should NOT add package targets to application project', async () => {
const cwd = join(baseDir, 'no-pkg-targets');
registerPluginInWorkspace(tree, {
Expand Down Expand Up @@ -276,7 +278,5 @@ describe('in a fresh Nx workspace', () => {
);
});
*/

});

});
8 changes: 6 additions & 2 deletions projects/nx-verdaccio/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,11 +21,15 @@
"sourceRoot": "packages/pkg/src",
"projectType": "library",
"name": "nx-verdaccio",
"tags": ["publishable"],
"tags": [
"publishable"
],
"targets": {
"build": {
"executor": "@nx/js:tsc",
"outputs": ["{options.outputPath}"],
"outputs": [
"{options.outputPath}"
],
"options": {
"outputPath": "dist/nx-verdaccio",
"main": "src/index.ts",
Expand Down
49 changes: 34 additions & 15 deletions projects/nx-verdaccio/src/plugin/nx-verdaccio.plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,27 @@ import {
type ProjectConfiguration,
readJsonFile,
} from '@nx/devkit';
import {dirname, join} from 'node:path';
import type {NxVerdaccioCreateNodeOptions} from './schema';
import {normalizeCreateNodesOptions, type NormalizedCreateNodeOptions,} from './normalize-create-nodes-options';
import {hashObject} from 'nx/src/hasher/file-hasher';
import {workspaceDataDirectory} from 'nx/src/utils/cache-directory';
import {PLUGIN_NAME} from './constants';
import {getCacheRecord, readTargetsCache, setCacheRecord, writeTargetsToCache,} from './caching';
import {createProjectConfiguration} from './targets/create-targets';
import {getPackageJsonNxConfig, getProjectConfig, getProjectJsonNxConfig} from "./project-config";
import { dirname, join } from 'node:path';
import type { NxVerdaccioCreateNodeOptions } from './schema';
import {
normalizeCreateNodesOptions,
type NormalizedCreateNodeOptions,
} from './normalize-create-nodes-options';
import { hashObject } from 'nx/src/hasher/file-hasher';
import { workspaceDataDirectory } from 'nx/src/utils/cache-directory';
import { PLUGIN_NAME } from './constants';
import {
getCacheRecord,
readTargetsCache,
setCacheRecord,
writeTargetsToCache,
} from './caching';
import { createProjectConfiguration } from './targets/create-targets';
import {
getPackageJsonNxConfig,
getProjectConfig,
getProjectJsonNxConfig,
} from './project-config';

const PROJECT_JSON_FILE_GLOB = '**/project.json';
const PACKAGE_JSON_FILE_GLOB = '**/package.json';
Expand All @@ -24,7 +36,7 @@ const FILE_GLOB = `**/{project,package}.json`;
export const createNodesV2: CreateNodesV2<NxVerdaccioCreateNodeOptions> = [
FILE_GLOB,
async (configFiles, options, context) => {
const optionsHash = hashObject({options: options ?? {}});
const optionsHash = hashObject({ options: options ?? {} });
const nxVerdaccioEnvPluginCachePath = join(
workspaceDataDirectory,
`push-based--${PLUGIN_NAME}-${optionsHash}.hash`
Expand All @@ -34,12 +46,19 @@ export const createNodesV2: CreateNodesV2<NxVerdaccioCreateNodeOptions> = [
return await createNodesFromFiles(
async (projectConfigurationFile, internalOptions) => {
const isPkgJson = projectConfigurationFile.endsWith('package.json');
if(isPkgJson) {
throw new Error('!!!!!!!!!!!!!!!!!!')
if (isPkgJson) {
throw new Error('!!!!!!!!!!!!!!!!!!');
}

const [primaryConfig, fallback] = isPkgJson ? [getPackageJsonNxConfig, getProjectJsonNxConfig] : [getProjectJsonNxConfig, getPackageJsonNxConfig];
const projectConfiguration: ProjectConfiguration = await getProjectConfig(projectConfigurationFile, primaryConfig, fallback);
const [primaryConfig, fallback] = isPkgJson
? [getPackageJsonNxConfig, getProjectJsonNxConfig]
: [getProjectJsonNxConfig, getPackageJsonNxConfig];
const projectConfiguration: ProjectConfiguration =
await getProjectConfig(
projectConfigurationFile,
primaryConfig,
fallback
);
if (
!('name' in projectConfiguration) ||
typeof projectConfiguration.name !== 'string'
Expand Down Expand Up @@ -71,7 +90,7 @@ export const createNodesV2: CreateNodesV2<NxVerdaccioCreateNodeOptions> = [
);
}
}
const {targets, namedInputs = {}} = cachedProjectConfiguration;
const { targets, namedInputs = {} } = cachedProjectConfiguration;
return {
projects: {
[projectRoot]: {
Expand Down
16 changes: 9 additions & 7 deletions projects/nx-verdaccio/src/plugin/project-config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type {ProjectConfiguration} from '@nx/devkit';
import {readFile} from 'node:fs/promises';
import {dirname, join} from 'node:path';
import type { ProjectConfiguration } from '@nx/devkit';
import { readFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';

export async function getProjectJsonNxConfig(packageJsonFile: string) {
const projectConfig: ProjectConfiguration = await readFile(
Expand All @@ -14,20 +14,22 @@ export async function getProjectJsonNxConfig(packageJsonFile: string) {
}

export async function getPackageJsonNxConfig(packageJsonFile: string) {
const {nx: pkgNxConfig = {}} = await readFile(
const { nx: pkgNxConfig = {} } = await readFile(
join(process.cwd(), packageJsonFile),
'utf8'
).then(JSON.parse);
return pkgNxConfig;
}

export async function getProjectConfig(projectConfigFile, getConfig:(projectConfigFile: string) => Promise<ProjectConfiguration>, fallback: (projectConfigFile: string) => Promise<ProjectConfiguration>) {

export async function getProjectConfig(
projectConfigFile,
getConfig: (projectConfigFile: string) => Promise<ProjectConfiguration>,
fallback: (projectConfigFile: string) => Promise<ProjectConfiguration>
) {
const pkgNxConfig = await getConfig(projectConfigFile);

if (!('name' in pkgNxConfig) || typeof pkgNxConfig?.name !== 'string') {
return await fallback(projectConfigFile);
}
return pkgNxConfig;

}

0 comments on commit 15a1bea

Please sign in to comment.