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(devkit): update parseTargetString to allow referencing targets on the current project #19109

Merged
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
24 changes: 24 additions & 0 deletions docs/generated/devkit/parseTargetString.md
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,27 @@ parseTargetString('proj:test:production', graph); // returns { project: "proj",
#### Returns

[`Target`](../../devkit/documents/Target)

▸ **parseTargetString**(`targetString`, `ctx`): [`Target`](../../devkit/documents/Target)

Parses a target string into {project, target, configuration}. Passing a full
[ExecutorContext](../../devkit/documents/ExecutorContext) enables the targetString to reference the current project.

Examples:

```typescript
parseTargetString('test', executorContext); // returns { project: "proj", target: "test" }
parseTargetString('proj:test', executorContext); // returns { project: "proj", target: "test" }
parseTargetString('proj:test:production', executorContext); // returns { project: "proj", target: "test", configuration: "production" }
```

#### Parameters

| Name | Type |
| :------------- | :---------------------------------------------------------- |
| `targetString` | `string` |
| `ctx` | [`ExecutorContext`](../../devkit/documents/ExecutorContext) |

#### Returns

[`Target`](../../devkit/documents/Target)
41 changes: 41 additions & 0 deletions packages/devkit/src/executors/parse-target-string.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { parseTargetString, targetToTargetString } from './parse-target-string';

import * as splitTarget from 'nx/src/utils/split-target';
import { ExecutorContext } from 'nx/src/devkit-exports';

const cases = [
{ input: 'one:two', expected: { project: 'one', target: 'two' } },
Expand All @@ -15,12 +16,52 @@ const cases = [
];

describe('parseTargetString', () => {
const mockContext: ExecutorContext = {
projectName: 'my-project',
cwd: '/virtual',
root: '/virtual',
isVerbose: false,
projectGraph: {
nodes: {
'my-project': {
type: 'lib',
name: 'my-project',
data: { root: '/packages/my-project' },
},
'other-project': {
type: 'lib',
name: 'other-project',
data: { root: '/packages/other-project' },
},
},
dependencies: {},
externalNodes: {},
version: '',
},
};

it.each(cases)('$input -> $expected', ({ input, expected }) => {
jest
.spyOn(splitTarget, 'splitTarget')
.mockReturnValueOnce(Object.values(expected) as [string]);
expect(parseTargetString(input, null)).toEqual(expected);
});

it('should support reading project from ExecutorContext', () => {
expect(parseTargetString('build', mockContext)).toEqual({
project: 'my-project',
target: 'build',
});
expect(parseTargetString('build:production', mockContext)).toEqual({
project: 'my-project',
target: 'build',
configuration: 'production',
});
expect(parseTargetString('other-project:build', mockContext)).toEqual({
project: 'other-project',
target: 'build',
});
});
});

describe('targetToTargetString', () => {
Expand Down
39 changes: 37 additions & 2 deletions packages/devkit/src/executors/parse-target-string.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import type { Target } from 'nx/src/command-line/run/run';
import type { ProjectGraph } from 'nx/src/config/project-graph';
import type { ExecutorContext } from 'nx/src/devkit-exports';

import { requireNx } from '../../nx';

let { readCachedProjectGraph, splitTarget } = requireNx();
let { readCachedProjectGraph, splitTarget, splitByColons } = requireNx();

// TODO: Remove this in Nx 18 when Nx 16.7.0 is no longer supported
splitTarget = splitTarget ?? require('nx/src/utils/split-target').splitTarget;
splitByColons =
splitByColons ?? ((s: string) => s.split(':') as [string, ...string[]]);

/**
* @deprecated(v17) A project graph should be passed to parseTargetString for best accuracy.
Expand All @@ -26,21 +30,52 @@ export function parseTargetString(
targetString: string,
projectGraph: ProjectGraph
): Target;
/**
* Parses a target string into {project, target, configuration}. Passing a full
* {@link ExecutorContext} enables the targetString to reference the current project.
*
* Examples:
* ```typescript
* parseTargetString("test", executorContext) // returns { project: "proj", target: "test" }
* parseTargetString("proj:test", executorContext) // returns { project: "proj", target: "test" }
* parseTargetString("proj:test:production", executorContext) // returns { project: "proj", target: "test", configuration: "production" }
* ```
*/
export function parseTargetString(
targetString: string,
projectGraph?: ProjectGraph
ctx: ExecutorContext
): Target;
export function parseTargetString(
targetString: string,
projectGraphOrCtx?: ProjectGraph | ExecutorContext
): Target {
let projectGraph =
projectGraphOrCtx && 'projectGraph' in projectGraphOrCtx
? projectGraphOrCtx.projectGraph
: (projectGraphOrCtx as ProjectGraph);

if (!projectGraph) {
try {
projectGraph = readCachedProjectGraph();
} catch (e) {
projectGraph = { nodes: {} } as any;
}
}

const [maybeProject] = splitByColons(targetString);
if (
!projectGraph.nodes[maybeProject] &&
projectGraphOrCtx &&
'projectName' in projectGraphOrCtx
) {
targetString = `${projectGraphOrCtx.projectName}:${targetString}`;
}

const [project, target, configuration] = splitTarget(
targetString,
projectGraph
);

if (!project || !target) {
throw new Error(`Invalid Target String: ${targetString}`);
}
Expand Down
1 change: 1 addition & 0 deletions packages/nx/src/devkit-internals.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ export { combineOptionsForExecutor } from './utils/params';
export { sortObjectByKeys } from './utils/object-sort';
export { stripIndent } from './utils/logger';
export { readModulePackageJson } from './utils/package-json';
export { splitByColons } from './utils/split-target';