Skip to content

Commit

Permalink
templates
Browse files Browse the repository at this point in the history
  • Loading branch information
catplvsplus committed May 29, 2024
1 parent a43ca5a commit a8a1c49
Show file tree
Hide file tree
Showing 23 changed files with 25 additions and 473 deletions.
27 changes: 6 additions & 21 deletions packages/create-reciple/src/bin.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
#!/usr/bin/env node

import { confirm, intro, isCancel, multiselect, outro, password, select, text } from '@clack/prompts';
import { packageJson, packageManagers, templatesFolder } from './utils/constants.js';
import { cancelPrompts, create, getTemplates, isDirEmpty } from './utils/helpers.js';
import { PackageManager, resolvePackageManager } from '@reciple/utils';
import availableAddons from './utils/addons.js';
import { existsSync, statSync } from 'node:fs';
import { CliOptions } from './utils/types.js';
import { confirm, intro, isCancel, multiselect, outro, password, select, text } from '@clack/prompts';
import { kleur } from 'fallout-utility';
import { Command } from 'commander';
import path from 'node:path';
import { existsSync, statSync } from 'node:fs';
import { kleur } from 'fallout-utility';
import availableAddons from './utils/addons.js';

const command = new Command()
.name(packageJson.name!)
Expand All @@ -18,8 +18,6 @@ const command = new Command()
.argument('[dir]', 'Create template in this folder')
.option('--force', 'Force override existing files in directory', false)
.option('--typescript', 'Use typescript templates', 'null')
.option('--esm', 'Use commonjs templates', 'null')
.option('--commonjs', 'Use commonjs templates', 'null')
.option('--package-manager <npm,yarn,pnpm>', 'Set package manager', 'null')
.option('-t, --token <DiscordToken>', 'Add token to created .env')
.option('--no-addons', 'Disable addons prompt', false)
Expand All @@ -32,13 +30,12 @@ const templates = await getTemplates(templatesFolder);

let dir: string|null = command.args[0] ?? null;
let typescript: boolean|null = options.typescript !== 'null' ? options.typescript : null;
let commonjs: boolean|null = options.esm === true ? false : options.commonjs !== 'null' ? options.commonjs : null;
let packageManager: PackageManager|null = options.packageManager !== 'null' ? options.packageManager : null;
let token: string|null = options.token ?? null;
let addons: string[]|false = Array.isArray(options.addons) ? options.addons : false;
let setup: boolean = false;

if (dir === null || typescript === null || commonjs === null || packageManager === null) {
if (dir === null || typescript === null || packageManager === null) {
setup = true;
intro(kleur.cyan().bold(`${packageJson.name} v${packageJson.version}`));
}
Expand Down Expand Up @@ -85,18 +82,6 @@ if (typescript === null) {
typescript = isTypescript;
}

if (commonjs === null) {
const isESM = await confirm({
message: `Would you like to use ES Modules? (uses import() instead of require())`,
initialValue: true,
active: `Yes`,
inactive: `No`
});

if (isCancel(isESM)) cancelPrompts();
commonjs = !isESM;
}

if (addons && !addons.length) {
const selectedAddons = await multiselect<{ label?: string; hint?: string; value: string; }[], string>({
message: `Select a addons from Reciple ${kleur.gray('(Press space to select, and enter to submit)')}`,
Expand Down Expand Up @@ -139,7 +124,7 @@ if (token === null) {
token = newToken;
}

const template = templates.find(p => p.type === (commonjs ? 'commonjs' : 'module') && p.language === (typescript ? 'Typescript' : 'Javascript'));
const template = templates.find(p => p.language === (typescript ? 'Typescript' : 'Javascript'));
if (!template) cancelPrompts({ reason: `Template not found` });
if (packageManager && !packageManagers.some(p => p.value === packageManager)) cancelPrompts({ reason: `Invalid package manager` });
if (setup) outro(`Setup Done! Creating from ${kleur.cyan().bold(template.name)} template`);
Expand Down
21 changes: 8 additions & 13 deletions packages/create-reciple/src/utils/addons.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { writeFile } from 'node:fs/promises';
import { runScript } from './helpers.js';
import path from 'node:path';

export type AddonModuleType = 'cjs'|'cts'|'mjs'|'mts';
export type AddonModuleType = 'js'|'ts';

export const addonCreators = {
'reciple-interaction-events': addRecipleInteractionEvents,
Expand All @@ -15,47 +15,42 @@ export function createAddonModuleFileContent(pkg: string, imports: string[]|stri
let importStatement: string;
let exportStatement: string;

if (type === 'cjs') {
importStatement = `const ${typeof imports === 'string' ? imports : ('{ ' + imports.join(', ') + ' }')} = require('${pkg}');`;
exportStatement = `module.exports = new ${classExport}(${params ?? ''});`;
} else {
importStatement = `import ${typeof imports === 'string' ? imports : ('{ ' + imports.join(', ') + ' }')} from '${pkg}';`;
exportStatement = `export default new ${classExport}(${params ?? ''});`;
}
importStatement = `import ${typeof imports === 'string' ? imports : ('{ ' + imports.join(', ') + ' }')} from '${pkg}';`;
exportStatement = `export default new ${classExport}(${params ?? ''});`;

return importStatement + '\n\n' + exportStatement;
}

export async function addRecipleInteractionEvents(dir: string, type: AddonModuleType): Promise<void> {
await writeFile(
path.join(dir, type.endsWith('js') ? 'modules' : 'src', `RecipleInteractionEvents.${type}`),
path.join(dir, type === 'js' ? 'modules' : 'src', `RecipleInteractionEvents.${type}`),
createAddonModuleFileContent('reciple-interaction-events', ['InteractionEventManager'], 'InteractionEventManager', type)
);
}

export async function addRecipleAnticrash(dir: string, type: AddonModuleType): Promise<void> {
await writeFile(
path.join(dir, type.endsWith('js') ? 'modules' : 'src', `RecipleAnticrash.${type}`),
path.join(dir, type === 'js' ? 'modules' : 'src', `RecipleAnticrash.${type}`),
createAddonModuleFileContent('reciple-anticrash', ['RecipleAnticrash'], 'RecipleAnticrash', type)
);
}

export async function addRecipleDevCommands(dir: string, type: AddonModuleType): Promise<void> {
await writeFile(
path.join(dir, type.endsWith('js') ? 'modules' : 'src', `RecipleDevCommands.${type}`),
path.join(dir, type === 'js' ? 'modules' : 'src', `RecipleDevCommands.${type}`),
createAddonModuleFileContent('reciple-dev-commands', ['DevCommandManager'], 'DevCommandManager', type, `{\n devGuilds: [],\n devUsers: []\n}`)
);
}

export async function addRecipleRegistryCache(dir: string, type: AddonModuleType): Promise<void> {
await writeFile(
path.join(dir, type.endsWith('js') ? 'modules' : 'src', `RecipleRegistryCache.${type}`),
path.join(dir, type === 'js' ? 'modules' : 'src', `RecipleRegistryCache.${type}`),
createAddonModuleFileContent('reciple-registry-cache', ['RegistryCacheManager'], 'RegistryCacheManager', type)
);
}

export async function installAddons(dir: string, type: AddonModuleType, addons: string[], installPackage?: string): Promise<void> {
await runScript((installPackage ?? 'npm i') + ' ' + addons.map(a => a + '@2').join(' '), dir);
await runScript((installPackage ?? 'npm i') + ' ' + addons.map(a => a + '@3').join(' '), dir);

Check warning

Code scanning / CodeQL

Unsafe shell command constructed from library input Medium

This string concatenation which depends on
library input
is later used in a
shell command
.

for (const addon of addons) {
await addonCreators[addon as keyof typeof addonCreators](dir, type);
Expand Down
6 changes: 3 additions & 3 deletions packages/create-reciple/src/utils/constants.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import { fileURLToPath } from 'node:url';
import path from 'node:path';
import { readFile } from 'node:fs/promises';
import { PackageJson } from 'fallout-utility/types';
import { PackageManager } from '@reciple/utils';
import { readFile } from 'node:fs/promises';
import { fileURLToPath } from 'node:url';
import path from 'node:path';

export const root = path.join(path.dirname(fileURLToPath(import.meta.url)), '../../');
export const templatesFolder = path.join(root, 'templates');
Expand Down
23 changes: 7 additions & 16 deletions packages/create-reciple/src/utils/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import { TemplateJson, TemplateMetadata } from './types.js';
import { copyFile, mkdir, readFile, readdir, stat, writeFile } from 'node:fs/promises';
import { PackageJson } from 'fallout-utility/types';
import { kleur } from 'fallout-utility/strings';
import path from 'node:path';
import { cancel } from '@clack/prompts';
import { exit } from 'node:process';
import { packageManagerPlaceholders, packages, root } from './constants.js';
import { PackageManager, existsAsync } from '@reciple/utils';
import { TemplateJson, TemplateMetadata } from './types.js';
import { kleur } from 'fallout-utility/strings';
import { execSync } from 'node:child_process';
import { installAddons } from './addons.js';
import { cancel } from '@clack/prompts';
import { exit } from 'node:process';
import path from 'node:path';

export async function getTemplates(dir: string): Promise<TemplateMetadata[]> {
if (!await existsAsync(dir)) {
Expand All @@ -28,13 +27,11 @@ export async function getTemplates(dir: string): Promise<TemplateMetadata[]> {
if (!files.includes(path.join(file, 'template.json')) || !files.includes(path.join(file, 'package.json'))) continue;

const metadata: TemplateJson = JSON.parse(await readFile(path.join(file, 'template.json'), 'utf-8'));
const packageJson: PackageJson = JSON.parse(await readFile(path.join(file, 'package.json'), 'utf-8'));

const data: TemplateMetadata = {
id,
name: metadata.name,
language: metadata.language,
type: packageJson.type ?? "commonjs",
files: files.filter(f => !f.endsWith('template.json')),
path: file
};
Expand Down Expand Up @@ -90,18 +87,12 @@ export async function create(template: TemplateMetadata, dir: string, packageMan

if (packageManager) await runScript(placeholders['INSTALL_ALL'], dir);

await runScript(`${packageManagerPlaceholders['npm']['BIN_EXEC']} reciple@${packages['RECIPLE']?.substring(1)} "${dir}" --setup -c reciple.${template.type === 'commonjs' ? 'cjs' : 'mjs'}`, dir);
await runScript(`${packageManagerPlaceholders['npm']['BIN_EXEC']} reciple@${packages['RECIPLE']?.substring(1)} "${dir}" --setup -c reciple.js`, dir);

Check warning

Code scanning / CodeQL

Unsafe shell command constructed from library input Medium

This string concatenation which depends on
library input
is later used in a
shell command
.
await createDotEnv(dir, token);

if (addons?.length) await installAddons(
dir,
template.type === 'commonjs'
? template.language === 'Javascript'
? 'cjs'
: 'cts'
: template.language === 'Typescript'
? 'mts'
: 'mjs',
template.language === 'Typescript' ? 'ts' : 'js',
addons,
placeholders['INSTALL_PKG']
);
Expand Down
3 changes: 1 addition & 2 deletions packages/create-reciple/src/utils/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ModuleType, PackageManager } from '@reciple/utils';
import { PackageManager } from '@reciple/utils';

export interface CliOptions {
force: boolean;
Expand All @@ -13,7 +13,6 @@ export interface CliOptions {

export interface TemplateMetadata extends TemplateJson {
id: string;
type: ModuleType;
path: string;
files: string[];
}
Expand Down
49 changes: 0 additions & 49 deletions packages/create-reciple/templates/cjs/modules/example.js

This file was deleted.

18 changes: 0 additions & 18 deletions packages/create-reciple/templates/cjs/package.json

This file was deleted.

4 changes: 0 additions & 4 deletions packages/create-reciple/templates/cjs/template.json

This file was deleted.

22 changes: 0 additions & 22 deletions packages/create-reciple/templates/cts/package.json

This file was deleted.

4 changes: 0 additions & 4 deletions packages/create-reciple/templates/cts/template.json

This file was deleted.

Loading

0 comments on commit a8a1c49

Please sign in to comment.