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

Add inferred target #1153

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
5 changes: 5 additions & 0 deletions plugins/nx-container/generators.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@
"factory": "./src/generators/configuration/generator",
"schema": "./src/generators/configuration/schema.json",
"description": "Configure Container builds for your application"
},
"init": {
"factory": "./src/generators/init/init",
"schema": "./src/generators/init/schema.json",
"description": "Init Container settings for your workspace"
}
}
}
52 changes: 31 additions & 21 deletions plugins/nx-container/src/generators/configuration/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import {
formatFiles,
generateFiles,
ProjectConfiguration,
readNxJson,
readProjectConfiguration,
Tree,
updateProjectConfiguration,
Expand All @@ -21,30 +22,32 @@ function addFiles(tree: Tree, project: ProjectConfiguration, template) {
export async function configurationGenerator(tree: Tree, options: ConfigurationGeneratorSchema) {
const project = readProjectConfiguration(tree, options.project);

updateProjectConfiguration(tree, options.project, {
...project,
targets: {
...project.targets,
container: {
executor: `@nx-tools/nx-container:build`,
dependsOn: ['build'],
options: {
engine: options.engine ?? DEFAULT_ENGINE,
metadata: {
images: [project.name],
load: true,
tags: [
'type=schedule',
'type=ref,event=branch',
'type=ref,event=tag',
'type=ref,event=pr',
'type=sha,prefix=sha-',
],
if (!hasContainerPlugin(tree)) {
updateProjectConfiguration(tree, options.project, {
...project,
targets: {
...project.targets,
container: {
executor: `@nx-tools/nx-container:build`,
dependsOn: ['build'],
options: {
engine: options.engine ?? DEFAULT_ENGINE,
metadata: {
images: [project.name],
load: true,
tags: [
'type=schedule',
'type=ref,event=branch',
'type=ref,event=tag',
'type=ref,event=pr',
'type=sha,prefix=sha-',
],
},
},
},
},
},
});
});
}

addFiles(tree, project, options.template ?? DEFAULT_TEMPLATE);

Expand All @@ -53,4 +56,11 @@ export async function configurationGenerator(tree: Tree, options: ConfigurationG
}
}

export function hasContainerPlugin(tree: Tree): boolean {
const nxJson = readNxJson(tree);
return !!nxJson.plugins?.some((p) =>
typeof p === 'string' ? p === '@nx-tools/nx-container' : p.plugin === '@nx-tools/nx-container'
);
}

export default configurationGenerator;
41 changes: 41 additions & 0 deletions plugins/nx-container/src/generators/init/init.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import { Tree, readJson } from '@nx/devkit';
import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';
import { initGenerator, hasContainerPlugin } from './init';

describe('init generator', () => {
let tree: Tree;

beforeEach(() => {
tree = createTreeWithEmptyWorkspace();
});

it('should add @nx-tools/nx-container plugin to nx.json', async () => {
// Run the generator
await initGenerator(tree, {});

// Read the nx.json file
const nxJson = readJson(tree, 'nx.json');

// Check that the plugin has been added
expect(nxJson.plugins).toBeDefined();
expect(
nxJson.plugins.some((p) =>
typeof p === 'string' ? p === '@nx-tools/nx-container' : p.plugin === '@nx-tools/nx-container'
)
).toBe(true);
});

it('should not add the plugin if it already exists', async () => {
// Simulate the plugin already being added
const nxJson = readJson(tree, 'nx.json');
nxJson.plugins = [{ plugin: '@nx-tools/nx-container', options: {} }];
tree.write('nx.json', JSON.stringify(nxJson));

// Run the generator
await initGenerator(tree, {});

// Ensure the plugin was not added again
const updatedNxJson = readJson(tree, 'nx.json');
expect(updatedNxJson.plugins.length).toBe(1);
});
});
32 changes: 32 additions & 0 deletions plugins/nx-container/src/generators/init/init.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import { GeneratorCallback, readNxJson, runTasksInSerial, Tree, updateNxJson } from '@nx/devkit';
import { Schema } from './schema';

export async function initGenerator(tree: Tree, options: Schema) {
const tasks: GeneratorCallback[] = [];

addPlugin(tree);

return runTasksInSerial(...tasks);
}

function addPlugin(tree: Tree) {
const nxJson = readNxJson(tree);

if (!hasContainerPlugin(tree)) {
nxJson.plugins ??= [];
nxJson.plugins.push({
plugin: '@nx-tools/nx-container',
options: {},
});
updateNxJson(tree, nxJson);
}
}

export function hasContainerPlugin(tree: Tree): boolean {
const nxJson = readNxJson(tree);
return !!nxJson.plugins?.some((p) =>
typeof p === 'string' ? p === '@nx-tools/nx-container' : p.plugin === '@nx-tools/nx-container'
);
}

export default initGenerator;
1 change: 1 addition & 0 deletions plugins/nx-container/src/generators/init/schema.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export interface Schema {}
8 changes: 8 additions & 0 deletions plugins/nx-container/src/generators/init/schema.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"$schema": "https://json-schema.org/schema",
"$id": "Configuration",
"title": "",
"type": "object",
"properties": {},
"required": []
}
2 changes: 2 additions & 0 deletions plugins/nx-container/src/index.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
export { default as run } from './executors/build/executor';

export * from './plugins';
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`@nx/container/plugin non-root project with Dockerfile should create nodes for non-root project with Dockerfile 1`] = `
{
"projects": {
"apps/your-docker-app": {
"targets": {
"build": {
"dependsOn": [
"build",
],
"executor": "@nx-tools/nx-container:build",
"options": {
"engine": "docker",
"metadata": {
"images": [
"my-docker-app",
],
"load": true,
"tags": [
"type=schedule",
"type=ref,event=branch",
"type=ref,event=tag",
"type=ref,event=pr",
"type=sha,prefix=sha-",
],
},
},
},
},
},
},
}
`;

exports[`@nx/container/plugin root project should create nodes with correct targets 1`] = `
{
"projects": {
".": {
"targets": {
"build": {
"dependsOn": [
"build",
],
"executor": "@nx-tools/nx-container:build",
"options": {
"engine": "docker",
"metadata": {
"images": [
"my-docker-app",
],
"load": true,
"tags": [
"type=schedule",
"type=ref,event=branch",
"type=ref,event=tag",
"type=ref,event=pr",
"type=sha,prefix=sha-",
],
},
},
},
},
},
},
}
`;
1 change: 1 addition & 0 deletions plugins/nx-container/src/plugins/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './nodes';
110 changes: 110 additions & 0 deletions plugins/nx-container/src/plugins/nodes.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
import { type CreateNodesContext, readNxJson, Tree } from '@nx/devkit';
import { createNodes } from './nodes';
import { calculateHashForCreateNodes } from '@nx/devkit/src/utils/calculate-hash-for-create-nodes';
import { createTreeWithEmptyWorkspace } from '@nx/devkit/testing';
import { readdirSync, existsSync, readFileSync } from 'fs';

jest.mock('fs', () => ({
...jest.requireActual('fs'),
readdirSync: jest.fn(),
existsSync: jest.fn(),
readFileSync: jest.fn(),
}));

jest.mock('@nx/devkit/src/utils/calculate-hash-for-create-nodes', () => {
return {
calculateHashForCreateNodes: jest.fn().mockResolvedValue('mock-hash'),
};
});

describe('@nx/container/plugin', () => {
let tree: Tree;
const createNodesFunction = createNodes[1];
let context: CreateNodesContext;

beforeEach(() => {
tree = createTreeWithEmptyWorkspace();
context = {
nxJsonConfiguration: readNxJson(tree),
workspaceRoot: '/',
configFiles: [],
};

(existsSync as jest.Mock).mockImplementation((path: string) => {
return tree.exists(path);
});

(readdirSync as jest.Mock).mockImplementation((path: string) => {
return tree.children(path.replace(/\*/g, ''));
});

(readFileSync as jest.Mock).mockImplementation((path: string) => {
return tree.read(path);
});
});

describe('root project', () => {
beforeEach(() => {
tree.write('Dockerfile', '');
tree.write('package.json', JSON.stringify({ name: 'my-docker-app' }));
tree.write('project.json', JSON.stringify({ name: 'my-docker-app' }));
});

it('should create nodes with correct targets', async () => {
const nodes = await createNodesFunction(
'Dockerfile',
{
buildTargetName: 'build',
defaultEngine: 'docker',
},
context
);

expect(nodes).toMatchSnapshot();
expect(calculateHashForCreateNodes).toHaveBeenCalled();
});
});

describe('non-root project with Dockerfile', () => {
beforeEach(() => {
tree.write('apps/your-docker-app/Dockerfile', '');
tree.write('apps/your-docker-app/package.json', JSON.stringify({ name: 'my-docker-app' }));
tree.write('apps/your-docker-app/project.json', JSON.stringify({ name: 'my-docker-app' }));
});

it('should create nodes for non-root project with Dockerfile', async () => {
const nodes = await createNodesFunction(
'apps/your-docker-app/Dockerfile',
{
buildTargetName: 'build',
defaultEngine: 'docker',
},
context
);

expect(nodes).toMatchSnapshot();
expect(calculateHashForCreateNodes).toHaveBeenCalled();
});
});

describe('non-root project without project.json', () => {
beforeEach(() => {
tree.write('apps/no-project/Dockerfile', '');
tree.write('apps/no-project/package.json', JSON.stringify({ name: 'no-project-app' }));
});

it('should not create nodes if project.json is missing', async () => {
const nodes = await createNodesFunction(
'apps/no-project/Dockerfile',
{
buildTargetName: 'build',
defaultEngine: 'docker',
},
context
);

expect(nodes).toEqual({});
expect(calculateHashForCreateNodes).not.toHaveBeenCalled();
});
});
});
Loading