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(cli): Add non-interactive CLI commands #2842

Closed
wants to merge 3 commits into from
Closed
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
64,991 changes: 32,506 additions & 32,485 deletions package-lock.json

Large diffs are not rendered by default.

3 changes: 2 additions & 1 deletion packages/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@
"picocolors": "^1.0.0",
"ts-morph": "^21.0.1",
"ts-node": "^10.9.2",
"tsconfig-paths": "^4.2.0"
"tsconfig-paths": "^4.2.0",
"zod": "^3.23.7"
},
"devDependencies": {
"@vendure/core": "^2.2.4",
Expand Down
4 changes: 4 additions & 0 deletions packages/cli/src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import { Command } from 'commander';
import pc from 'picocolors';

import { registerAddPluginNonInteractiveCommand } from './commands/add/plugin/add-plugin.command.non-interactive';

const program = new Command();

// eslint-disable-next-line @typescript-eslint/no-var-requires
Expand Down Expand Up @@ -33,6 +35,8 @@ program
process.exit(0);
});

registerAddPluginNonInteractiveCommand(program);

program
.command('migrate')
.description('Generate, run or revert a database migration')
Expand Down
4 changes: 2 additions & 2 deletions packages/cli/src/commands/add/add.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { addApiExtensionCommand } from './api-extension/add-api-extension';
import { addCodegenCommand } from './codegen/add-codegen';
import { addEntityCommand } from './entity/add-entity';
import { addJobQueueCommand } from './job-queue/add-job-queue';
import { createNewPluginCommand } from './plugin/create-new-plugin';
import { addPluginCommandInteractive } from './plugin/add-plugin.command.interactive';
import { addServiceCommand } from './service/add-service';
import { addUiExtensionsCommand } from './ui-extensions/add-ui-extensions';

Expand All @@ -20,7 +20,7 @@ export async function addCommand() {
console.log(`\n`);
intro(pc.blue("✨ Let's add a new feature to your Vendure project!"));
const addCommands: Array<CliCommand<any>> = [
createNewPluginCommand,
addPluginCommandInteractive,
addEntityCommand,
addServiceCommand,
addApiExtensionCommand,
Expand Down
103 changes: 103 additions & 0 deletions packages/cli/src/commands/add/plugin/add-plugin.command.interactive.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,103 @@
import { intro, isCancel, log, select, spinner } from '@clack/prompts';

import { CliCommand, CliCommandReturnVal } from '../../../shared/cli-command';
import { runPromptsForInputDefinitions } from '../../../shared/prompter';
import { analyzeProject } from '../../../shared/shared-prompts';
import { VendureConfigRef } from '../../../shared/vendure-config-ref';
import { addImportsToFile } from '../../../utilities/ast-utils';
import { pauseForPromptDisplay } from '../../../utilities/utils';
import { addApiExtensionCommand } from '../api-extension/add-api-extension';
import { addCodegenCommand } from '../codegen/add-codegen';
import { addEntityCommand } from '../entity/add-entity';
import { addJobQueueCommand } from '../job-queue/add-job-queue';
import { addServiceCommand } from '../service/add-service';
import { addUiExtensionsCommand } from '../ui-extensions/add-ui-extensions';

import { inputDefinitions } from './add-plugin.input-definitions';
import { generatePlugin } from './add-plugin.service';
import { GeneratePluginOptions } from './types';

export const addPluginCommandInteractive = new CliCommand({
id: 'plugin',
category: 'Plugin',
description: 'Create a new Vendure plugin',
run: createNewPlugin,
});

const cancelledMessage = 'Plugin setup cancelled.';

export async function createNewPlugin(): Promise<CliCommandReturnVal> {
intro('Adding a new Vendure plugin!');

const { project } = await analyzeProject({ cancelledMessage });

const options = (await runPromptsForInputDefinitions(
inputDefinitions,
project,
cancelledMessage,
)) as GeneratePluginOptions;

const { plugin, modifiedSourceFiles } = await generatePlugin(project, options);

const configSpinner = spinner();
configSpinner.start('Updating VendureConfig...');
await pauseForPromptDisplay();
const vendureConfig = new VendureConfigRef(project);
vendureConfig.addToPluginsArray(`${plugin.name}.init({})`);
addImportsToFile(vendureConfig.sourceFile, {
moduleSpecifier: plugin.getSourceFile(),
namedImports: [plugin.name],
});
await vendureConfig.sourceFile.getProject().save();
configSpinner.stop('Updated VendureConfig');

let done = false;
const followUpCommands = [
addEntityCommand,
addServiceCommand,
addApiExtensionCommand,
addJobQueueCommand,
addUiExtensionsCommand,
addCodegenCommand,
];
let allModifiedSourceFiles = [...modifiedSourceFiles];
while (!done) {
const featureType = await select({
message: `Add features to ${options.name}?`,
options: [
{ value: 'no', label: "[Finish] No, I'm done!" },
...followUpCommands.map(c => ({
value: c.id,
label: `[${c.category}] ${c.description}`,
})),
],
});
if (isCancel(featureType)) {
done = true;
}
if (featureType === 'no') {
done = true;
} else {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const command = followUpCommands.find(c => c.id === featureType)!;
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
try {
const result = await command.run({ plugin });
allModifiedSourceFiles = result.modifiedSourceFiles;
// We format all modified source files and re-load the
// project to avoid issues with the project state
for (const sourceFile of allModifiedSourceFiles) {
sourceFile.organizeImports();
}
} catch (e: any) {
log.error(`Error adding feature "${command.id}"`);
log.error(e.stack);
}
}
}

return {
project,
modifiedSourceFiles: [],
};
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import { Command } from 'commander';

import { enrichProgramWithInputOptions } from '../../../shared/program-builder';
import { analyzeProject } from '../../../shared/shared-prompts';

import { inputDefinitions } from './add-plugin.input-definitions';
import { generatePlugin } from './add-plugin.service';
import { GeneratePluginOptions } from './types';

export const registerAddPluginNonInteractiveCommand = (program: Command) => {
const command = program.command('add:plugin').description('Add a plugin to your Vendure project');

enrichProgramWithInputOptions(command, inputDefinitions);

command.action(async options => {
const { project } = await analyzeProject();
await generatePlugin(project, options as GeneratePluginOptions);
process.exit(0);
});
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { z } from 'zod';

import { InputDefinitions, InputOptionType } from '../../../shared/input-option-definitions';

import { findExistingPluginsDir, getPluginDirName } from './add-plugin.service';

export const inputDefinitions: InputDefinitions = {
options: [
{
name: 'name',
type: InputOptionType.String,
required: true,
shortFlag: 'n',
longName: 'name',
help: 'The name of the plugin',
prompt: 'What is the name of the plugin?',
description: 'The name of the plugin to create',
validate: (input: string) => {
const isValid = z
.string()
.regex(/^[a-z][a-z-0-9]+$/)
.safeParse(input).success;

if (!isValid) {
return 'The plugin name must be lowercase and contain only letters, numbers and dashes';
}
},
transform: (input: string) => input.replace(/-?plugin$/i, ''),
},
{
name: 'pluginDir',
type: InputOptionType.String,
required: true,
shortFlag: 'd',
longName: 'plugin-dir',
help: 'Add a relative path to your current working directory',
prompt: 'What is the directory to create the plugin in?',
description: 'The directory to create the plugin in',
defaultValue: (currentOptions, project) => {
const existingPluginDir = findExistingPluginsDir(project);
return getPluginDirName(currentOptions.name, existingPluginDir);
},
},
],
};
135 changes: 135 additions & 0 deletions packages/cli/src/commands/add/plugin/add-plugin.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,135 @@
import { spinner } from '@clack/prompts';
import { constantCase, paramCase, pascalCase } from 'change-case';
import * as fs from 'fs-extra';
import path from 'path';
import { Project, SourceFile } from 'ts-morph';

import { VendurePluginRef } from '../../../shared/vendure-plugin-ref';
import { createFile, getPluginClasses } from '../../../utilities/ast-utils';
import { pauseForPromptDisplay } from '../../../utilities/utils';

import { GeneratePluginOptions, NewPluginTemplateContext } from './types';

export async function generatePlugin(
project: Project,
options: GeneratePluginOptions,
): Promise<{ plugin: VendurePluginRef; modifiedSourceFiles: SourceFile[] }> {
const nameWithoutPlugin = options.name.replace(/-?plugin$/i, '');
const normalizedName = nameWithoutPlugin + '-plugin';
const templateContext: NewPluginTemplateContext = {
...options,
pluginName: pascalCase(normalizedName),
pluginInitOptionsName: constantCase(normalizedName) + '_OPTIONS',
};

const projectSpinner = spinner();
projectSpinner.start('Generating plugin scaffold...');
await pauseForPromptDisplay();

const pluginFile = createFile(
project,
path.join(__dirname, 'templates/plugin.template.ts'),
path.join(options.pluginDir, paramCase(nameWithoutPlugin) + '.plugin.ts'),
);
const pluginClass = pluginFile.getClass('TemplatePlugin');
if (!pluginClass) {
throw new Error('Could not find the plugin class in the generated file');
}
pluginFile.getImportDeclaration('./constants.template')?.setModuleSpecifier('./constants');
pluginFile.getImportDeclaration('./types.template')?.setModuleSpecifier('./types');
pluginClass.rename(templateContext.pluginName);

const typesFile = createFile(
project,
path.join(__dirname, 'templates/types.template.ts'),
path.join(options.pluginDir, 'types.ts'),
);

const constantsFile = createFile(
project,
path.join(__dirname, 'templates/constants.template.ts'),
path.join(options.pluginDir, 'constants.ts'),
);
constantsFile
.getVariableDeclaration('TEMPLATE_PLUGIN_OPTIONS')
?.rename(templateContext.pluginInitOptionsName)
.set({ initializer: `Symbol('${templateContext.pluginInitOptionsName}')` });
constantsFile
.getVariableDeclaration('loggerCtx')
?.set({ initializer: `'${templateContext.pluginName}'` });

projectSpinner.stop('Generated plugin scaffold');
await project.save();
return {
modifiedSourceFiles: [pluginFile, typesFile, constantsFile],
plugin: new VendurePluginRef(pluginClass),
};
}

export function findExistingPluginsDir(project: Project): { prefix: string; suffix: string } | undefined {
const pluginClasses = getPluginClasses(project);
if (pluginClasses.length === 0) {
return;
}
if (pluginClasses.length === 1) {
return { prefix: path.dirname(pluginClasses[0].getSourceFile().getDirectoryPath()), suffix: '' };
}
const pluginDirs = pluginClasses.map(c => {
return c.getSourceFile().getDirectoryPath();
});
const prefix = findCommonPath(pluginDirs);
const suffixStartIndex = prefix.length;
const rest = pluginDirs[0].substring(suffixStartIndex).replace(/^\//, '').split('/');
const suffix = rest.length > 1 ? rest.slice(1).join('/') : '';
return { prefix, suffix };
}

export function getPluginDirName(
name: string,
existingPluginDirPattern: { prefix: string; suffix: string } | undefined,
) {
const cwd = process.cwd();
const nameWithoutPlugin = name.replace(/-?plugin$/i, '');
if (existingPluginDirPattern) {
return path.join(
existingPluginDirPattern.prefix,
paramCase(nameWithoutPlugin),
existingPluginDirPattern.suffix,
);
} else {
return path.join(cwd, 'src', 'plugins', paramCase(nameWithoutPlugin));
}
}

export function findCommonPath(paths: string[]): string {
if (paths.length === 0) {
return ''; // If no paths provided, return empty string
}

// Split each path into segments
const pathSegmentsList = paths.map(p => p.split('/'));

// Find the minimum length of path segments (to avoid out of bounds)
const minLength = Math.min(...pathSegmentsList.map(segments => segments.length));

// Initialize the common path
const commonPath: string[] = [];

// Loop through each segment index up to the minimum length
for (let i = 0; i < minLength; i++) {
// Get the segment at the current index from the first path
const currentSegment = pathSegmentsList[0][i];
// Check if this segment is common across all paths
const isCommon = pathSegmentsList.every(segments => segments[i] === currentSegment);
if (isCommon) {
// If it's common, add this segment to the common path
commonPath.push(currentSegment);
} else {
// If it's not common, break out of the loop
break;
}
}

// Join the common path segments back into a string
return commonPath.join('/');
}
Loading
Loading