@lcap/create-plugin
Version:
create lcap ide plugin
105 lines (80 loc) • 2.65 kB
JavaScript
;
import fs from 'fs';
import url from 'url';
import path from 'path';
import { program } from 'commander';
import * as ChangeCase from 'change-case';
const __filename = url.fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const ROOT_PATH = path.resolve(__dirname, '../');
const templates = (() => {
const options = { withFileTypes: true };
const folder = path.resolve(ROOT_PATH, './templates');
const list = fs.readdirSync(folder, options);
const filter = (item) => item.isDirectory();
const map = (item) => item.name;
return list
.filter(filter)
.map(map);
})();
const missions = [
(options = {}) => {
const file = path.resolve(ROOT_PATH, './package.json');
const json = fs.readFileSync(file, 'utf8');
const { version } = JSON.parse(json);
options?.version && console.log(version);
},
(options = {}) => {
const { name, port, template = 'vue-render' } = options;
if (!name) {
return;
}
const templateFolder = `./templates/${template}`;
const source = path.resolve(ROOT_PATH, templateFolder);
const target = path.resolve(name);
if (fs.existsSync(target)) {
console.log(
'\x1b[41m',
`create-lcap-ide-plugin: ${name} plugin already exists.`,
);
}
const context = { name, port };
const cpOptions = { recursive: true };
const readOptions = { ...cpOptions, withFileTypes: true };
const filter = (file) => file.isFile();
const replace = (source, matched) => context[matched];
const forEach = (file) => {
const encoding = 'utf8';
const filePath = path.resolve(file.parentPath, file.name);
const source = fs.readFileSync(filePath, { encoding });
const result = source.replace(/{{{([^{}]+)}}}/g, replace);
fs.writeFileSync(filePath, result, encoding);
};
fs.cpSync(source, target, cpOptions);
const files = fs.readdirSync(target, readOptions);
files
.filter(filter)
.forEach(forEach);
},
];
const run = (name, options = {}) => {
const merged = { name, ...options };
const forEach = (mission) => {
try {
mission?.(merged);
} catch (error) {
console.error(error);
}
};
missions.forEach(forEach);
};
program
.name('create-lcap-ide-plugin')
.arguments('[name]')
.allowUnknownOption()
.option('-t, --template <name>', 'choice template to create plugin', 'vue-render', templates)
.option('-p, --port <number>', 'choice port for dev server', '1613')
.option('-v, --version', 'display version for command')
.action(run)
.parse(process.argv);