Skip to content

Commit b14a965

Browse files
committed
feat: add command: generate
1 parent 40ce3fd commit b14a965

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

src/commands/generate.ts

+59
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import { CreateFileFromTemplate } from '#functions';
2+
import { Command, flags } from '@oclif/command';
3+
import { blueBright, red } from 'chalk';
4+
import FindUp from 'find-up';
5+
import { existsSync } from 'fs';
6+
import { readFile } from 'fs/promises';
7+
import ora from 'ora';
8+
import { join } from 'path';
9+
10+
export default class Generate extends Command {
11+
public async run() {
12+
const { args } = this.parse(Generate);
13+
14+
const spinner = ora(`Creating a ${args.component.toLowerCase()}`).start();
15+
16+
const configLoc = await FindUp('.sapphirerc.json', { cwd: '.' });
17+
if (!configLoc) return;
18+
const config = JSON.parse(await readFile(configLoc, 'utf8'));
19+
if (!config) return;
20+
21+
await this.createComponent(args.component, args.name, config, configLoc.replace('.sapphirerc.json', '')).catch((err) => {
22+
spinner.fail();
23+
console.log(red(err.message));
24+
process.exit(1);
25+
});
26+
spinner.succeed();
27+
return console.log(blueBright('Done!'));
28+
}
29+
30+
private createComponent(component: string, name: string, config: any, configLoc: string) {
31+
return new Promise(async (resolve, reject) => {
32+
const { projectLanguage } = config;
33+
if (!projectLanguage) return reject(new Error("There is no 'projectLanguage' field in .sapphirerc.json"));
34+
const template = `${component.toLowerCase()}.${projectLanguage}.sapphire`;
35+
36+
const corePath = `${__dirname}/../../templates/components/${template}`;
37+
const userPath = config.customFileTemplates.enabled ? join(configLoc, config.customFileTemplates.location, template) : null;
38+
const target = join(configLoc, config.locations.base, '%L%', `${name}.${projectLanguage}`);
39+
40+
if (userPath && existsSync(userPath)) {
41+
return CreateFileFromTemplate(userPath, target, config, { name }, true, true).then(resolve).catch(reject);
42+
} else if (existsSync(corePath)) {
43+
return CreateFileFromTemplate(`components/${template}`, target, config, { name }, false, true).then(resolve).catch(reject);
44+
}
45+
return reject(new Error("Can't find the template."));
46+
});
47+
}
48+
49+
public static description = 'generate a component (command, listener, etc.)';
50+
51+
public static flags = {
52+
help: flags.help({ char: 'h' })
53+
};
54+
55+
public static args = [
56+
{ name: 'component', required: true },
57+
{ name: 'name', required: true }
58+
];
59+
}

0 commit comments

Comments
 (0)