Skip to content

Commit

Permalink
wip build executor
Browse files Browse the repository at this point in the history
  • Loading branch information
BioPhoton committed Sep 3, 2024
1 parent 9422a8b commit aee4445
Show file tree
Hide file tree
Showing 20 changed files with 1,035 additions and 33 deletions.
6 changes: 6 additions & 0 deletions e2e/cli-e2e/project.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,12 @@
"workspaceRoot": "tmp/cli-e2e"
}
},
"kill-process": {
"executor": "@org/build-env:kill-process",
"options": {
"workspaceRoot": "tmp/cli-e2e"
}
},
"e2e": {
"dependsOn": [
{
Expand Down
66 changes: 51 additions & 15 deletions nx.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,10 @@
"libsDir": "projects"
},
"namedInputs": {
"default": ["{projectRoot}/**/*", "sharedGlobals"],
"default": [
"{projectRoot}/**/*",
"sharedGlobals"
],
"production": [
"default",
"!{projectRoot}/.eslintrc.json",
Expand All @@ -22,36 +25,60 @@
"targetDefaults": {
"@nx/esbuild:esbuild": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["production", "^production"]
"dependsOn": [
"^build"
],
"inputs": [
"production",
"^production"
]
},
"@nx/vite:test": {
"cache": true,
"inputs": ["default", "^production"]
"inputs": [
"default",
"^production"
]
},
"nx-release-publish": {
"dependsOn": [
{
"projects": ["self"],
"projects": [
"self"
],
"target": "build"
},
{
"projects": ["dependencies"],
"projects": [
"dependencies"
],
"target": "nx-release-publish"
}
]
},
"build": {
"inputs": ["production", "^production"]
"inputs": [
"production",
"^production"
]
},
"@nx/js:tsc": {
"cache": true,
"dependsOn": ["^build"],
"inputs": ["production", "^production"]
"dependsOn": [
"^build"
],
"inputs": [
"production",
"^production"
]
},
"@nx/jest:jest": {
"cache": true,
"inputs": ["default", "^production", "{workspaceRoot}/jest.preset.js"],
"inputs": [
"default",
"^production",
"{workspaceRoot}/jest.preset.js"
],
"options": {
"passWithNoTests": true
},
Expand All @@ -70,11 +97,20 @@
"targetName": "lint"
}
},
"./tools/e2e-example-plugins/original.plugin.ts",
"./tools/e2e-example-plugins/env.plugin.ts",
"./tools/e2e-example-plugins/graph.plugin.ts",
"./tools/e2e-example-plugins/pretarget.plugin.ts",
"./tools/plugins/verdaccio-test-env.plugin.ts"
{
"plugin": "@nx/jest/plugin",
"options": {
"jestConfig": "{projectRoot}/jest.config.js",
"tsConfig": "{projectRoot}/tsconfig.spec.json",
"babelConfig": "{projectRoot}/babel.config.js"
}
},
{
"plugin": "@nx/esbuild/plugin",
"options": {
"config": "{projectRoot}/esbuild.config.js"
}
}
],
"release": {
"version": {
Expand Down
5 changes: 5 additions & 0 deletions tools/build-env/executors.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
"implementation": "./src/executors/build/executor",
"schema": "./src/executors/build/schema.json",
"description": "Generate test environments in your workspace. Cached and ready for use."
},
"kill-process": {
"implementation": "./src/executors/kill-process/executor",
"schema": "./src/executors/kill-process/schema.json",
"description": "´Kills process by PID, command or file path."
}
}
}
14 changes: 0 additions & 14 deletions tools/build-env/generators.json

This file was deleted.

18 changes: 15 additions & 3 deletions tools/build-env/src/executors/build/executor.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,32 @@
import {type ExecutorContext, logger} from '@nx/devkit';
// eslint-disable-next-line n/no-sync
import type {BuildExecutorOptions} from './schema';
import {setupNpmEnv} from "../../internal/verdaccio/verdaccio-npm-env";
import {join} from "node:path";

export type ExecutorOutput = {
success: boolean;
command?: string;
error?: Error;
};

export default function runBuildExecutor(
export default async function runBuildExecutor(
terminalAndExecutorOptions: BuildExecutorOptions,
context: ExecutorContext,
) {

logger.info(`Execute @org/build-env:build with options: ${JSON.stringify(terminalAndExecutorOptions)}`)

const {projectName} = context;
const normalizedOptions = {
...terminalAndExecutorOptions,
workspaceRoot: join('tmp', 'environments', projectName)
};
logger.info(`Execute @org/build-env:build with options: ${JSON.stringify(terminalAndExecutorOptions, null, 2)}`);
try {
const envResult = await setupNpmEnv(normalizedOptions)
logger.info(`envResult: ${JSON.stringify(envResult, null, 2)}`);
} catch (error) {
logger.error(error);
}
return Promise.resolve({
success: true,
command: '????????',
Expand Down
53 changes: 53 additions & 0 deletions tools/build-env/src/executors/kill-process/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
# Kill Process Executor

This executor is used to kill a process by PID, command of file.

#### @org/build-env:kill-process

## Usage

// project.json

```json
{
"name": "my-project",
"targets": {
"stop-verdaccio-env": {
"executor": "@org/build-env:kill-process"
}
}
}
```

By default, the Nx plugin will derive the options from the executor config.

The following things happen:

- ???

```jsonc
{
"name": "my-project",
"targets": {
"stop-verdaccio-env": {
"executor": "@org/build-env:kill-process",
"options": {
"filePath": "verdaccio-pid.json",
"verbose": true,
"progress": false
}
}
}
}
```

Show what will be executed without actually executing it:

`nx run my-project:stop-verdaccio-env --dryRun`

## Options

| Name | type | description |
|--------------| --------- |--------------------------------------------------------------------|
| **filePath** | `string` | Path to the file containing the PID of the process |
| **dryRun** | `boolean` | To debug the executor, dry run the command without real execution. |
35 changes: 35 additions & 0 deletions tools/build-env/src/executors/kill-process/executor.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import {type ExecutorContext, logger} from '@nx/devkit';
// eslint-disable-next-line n/no-sync
import type {KillProcessExecutorOptions} from './schema';
import {join} from "node:path";
import {killProcessFromPid} from "../../internal/utils/process";

export type ExecutorOutput = {
success: boolean;
command?: string;
error?: Error;
};

export default async function runKillProcessExecutor(
terminalAndExecutorOptions: KillProcessExecutorOptions,
context: ExecutorContext,
) {

const {projectName} = context;
const {workspaceRoot} = {
...terminalAndExecutorOptions,
workspaceRoot: join('tmp', 'environments', projectName)
};

logger.info(`Execute @org/stop-verdaccio-env:kill-process with options: ${JSON.stringify(terminalAndExecutorOptions, null, 2)}`);
try {
const envResult = await killProcessFromPid(join(workspaceRoot, 'verdaccio-registry.json'));
logger.info(`envResult: ${JSON.stringify(['envResult'], null, 2)}`);
} catch (error) {
logger.error(error);
}
return Promise.resolve({
success: true,
command: '????????',
} satisfies ExecutorOutput);
}
114 changes: 114 additions & 0 deletions tools/build-env/src/executors/kill-process/executor.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
import {ExecutorContext, logger} from '@nx/devkit';
// eslint-disable-next-line n/no-sync
import {execSync} from 'node:child_process';
import {afterEach, beforeEach, expect, vi} from 'vitest';
import runKillProcessExecutor from './executor';

vi.mock('node:child_process', async () => {
const actual = await vi.importActual('node:child_process');

return {
...actual,
// eslint-disable-next-line n/no-sync
execSync: vi.fn((command: string) => {
if (command.includes('THROW_ERROR')) {
throw new Error(command);
}
}),
};
});

describe('runAutorunExecutor', () => {
const envSpy = vi.spyOn(process, 'env', 'get');
const loggerInfoSpy = vi.spyOn(logger, 'info');
const loggerWarnSpy = vi.spyOn(logger, 'warn');

beforeEach(() => {
envSpy.mockReturnValue({});
});
afterEach(() => {
loggerWarnSpy.mockReset();
loggerInfoSpy.mockReset();
envSpy.mockReset().mockReturnValue({});
});

it('should call execSync with stop-verdaccio command and return result', async () => {
const output = await runKillProcessExecutor({}, {} as ExecutorContext);
expect(output.success).toBe(true);
expect(output.command).toMatch('npx @org/cli stop-verdaccio');
// eslint-disable-next-line n/no-sync
expect(execSync).toHaveBeenCalledWith(
expect.stringContaining('npx @org/cli stop-verdaccio'),
{ cwd: '/test' },
);
});

it('should normalize context', async () => {
const output = await runKillProcessExecutor(
{},
{
...{} as ExecutorContext,
cwd: 'cwd-form-context',
},
);
expect(output.success).toBe(true);
expect(output.command).toMatch('utils');
// eslint-disable-next-line n/no-sync
expect(execSync).toHaveBeenCalledWith(expect.stringContaining('utils'), {
cwd: 'cwd-form-context',
});
});

it('should process executorOptions', async () => {
const output = await runKillProcessExecutor(
{ workspaceRoot: '.' },
{} as ExecutorContext,
);
expect(output.success).toBe(true);
expect(output.command).toMatch('--persist.filename="REPORT"');
});

it('should create command from context, options and arguments', async () => {
envSpy.mockReturnValue({ CP_PROJECT: 'CLI' });
const output = await runKillProcessExecutor(
{ workspaceRoot: '.' },
{} as ExecutorContext
);
expect(output.command).toMatch('--persist.filename="REPORT"');
expect(output.command).toMatch(
'--persist.format="md" --persist.format="json"',
);
expect(output.command).toMatch('--upload.project="CLI"');
});

it('should log information if verbose is set', async () => {
const output = await runKillProcessExecutor(
{ verbose: true },
{ ...{} as ExecutorContext, cwd: '<CWD>' },
);
// eslint-disable-next-line n/no-sync
expect(execSync).toHaveBeenCalledTimes(1);

expect(output.command).toMatch('--verbose');
expect(loggerWarnSpy).toHaveBeenCalledTimes(0);
expect(loggerInfoSpy).toHaveBeenCalledTimes(2);
expect(loggerInfoSpy).toHaveBeenCalledWith(
expect.stringContaining('Run stop-verdaccio executor'),
);
expect(loggerInfoSpy).toHaveBeenCalledWith(
expect.stringContaining('Command: npx @org/cli stop-verdaccio'),
);
});

it('should log command if dryRun is set', async () => {
await runKillProcessExecutor({ dryRun: true }, {} as ExecutorContext);

expect(loggerInfoSpy).toHaveBeenCalledTimes(0);
expect(loggerWarnSpy).toHaveBeenCalledTimes(1);
expect(loggerWarnSpy).toHaveBeenCalledWith(
expect.stringContaining(
'DryRun execution of: npx @org/cli stop-verdaccio --dryRun',
),
);
});
});
Loading

0 comments on commit aee4445

Please sign in to comment.