@avleon/cli
Version:
Coming Soon....
241 lines (237 loc) • 9.64 kB
JavaScript
;
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
var ownKeys = function(o) {
ownKeys = Object.getOwnPropertyNames || function (o) {
var ar = [];
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
return ar;
};
return ownKeys(o);
};
return function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
__setModuleDefault(result, mod);
return result;
};
})();
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.iqraCli = iqraCli;
exports.run = run;
const cli_table3_1 = __importDefault(require("cli-table3"));
const path_1 = __importDefault(require("path"));
const promises_1 = __importDefault(require("fs/promises"));
const fs_extra_1 = __importDefault(require("fs-extra"));
const fs_1 = require("fs");
const prettier = __importStar(require("prettier"));
const chalk_1 = __importDefault(require("chalk"));
const controller_1 = require("./controller");
const commands_1 = require("./commands");
const child_process_1 = require("child_process");
const create_1 = require("./create");
function iqraCli() { }
const listedCommands = commands_1.commandList.flatMap(x => x.Command).concat(commands_1.commandList.flatMap(x => x.Alias.split(","))).flatMap(a => a.trim());
/**
* @description Displaying basic info
* @since v0.0.2
* */
async function printLogo() {
try {
const packageInfo = await promises_1.default.readFile(path_1.default.join(__dirname, "../package.json"), "utf8");
const parsedPackInfo = JSON.parse(packageInfo);
console.log(`Name: Avleon CLI`, "\r");
console.log(`Version: ${parsedPackInfo.version}`, "\r");
}
catch (error) {
throw new Error("Can't read packag info");
}
}
async function displayCommandList(info = { logo: true, all: false }) {
if (info.logo) {
await printLogo();
}
console.log("Available commandList:");
if (info.all) {
const table = new cli_table3_1.default({
head: ["Command", "Alias", "Available Options", "Description"],
colWidths: [20, 10, 30, 50],
wrapOnWordBoundary: true,
wordWrap: true,
});
commands_1.commandList.forEach((c) => {
table.push([c.Command, c.Alias, c.Options, c.Description]);
});
console.log(table.toString());
}
else {
const table = new cli_table3_1.default({
head: ["Command", "Alias", "Available Options"],
colWidths: [20, 10, 50],
wrapOnWordBoundary: true,
wordWrap: true,
});
commands_1.commandList.forEach((c) => {
table.push([c.Command, c.Alias, c.Options]);
});
console.log(table.toString());
}
}
async function createModel(name, options = { force: false }) {
if (!name) {
throw new Error("Model name not found . use --name or node artisan make:model ModelName");
}
const modelFolderExists = (0, fs_1.existsSync)(path_1.default.join(process.cwd(), "./src/models"));
if (!modelFolderExists) {
await promises_1.default.mkdir(path_1.default.join(process.cwd(), "./src/models"), {
recursive: true,
});
}
const modelName = name.at(0).toUpperCase() + name.slice(1);
const modelExists = (0, fs_1.existsSync)(path_1.default.join(process.cwd(), `./src/models/${modelName.toLowerCase()}.ts`));
if (modelExists && !options.force) {
console.log(chalk_1.default.bold(chalk_1.default.red("Model already exists!")), chalk_1.default.greenBright("Use -f or --force to overwrite.\r"));
return;
}
const model = `
import {Entity, PrimaryGeneratedColumn, CreateDateColumn, UpdateDateColumn } from 'typeorm';
\t
@Entity({name:'${modelName}'})
export class ${modelName}{
@PrimaryGeneratedColumn()
id:number;
@CreateDateColumn()
createdAt: Date;
@UpdateDateColumn()
updatedAt: Date;
}
`;
const formatModel = await prettier.format(model, {
singleQuote: true,
singleAttributePerLine: true,
parser: "typescript",
});
await promises_1.default.writeFile(path_1.default.join(process.cwd(), "./src/models/" + modelName.toLowerCase() + ".ts"), formatModel);
console.log("Model created succssessfully!");
}
async function createXApplication(fname) {
if ((0, fs_1.existsSync)(process.cwd() + fname)) {
throw new Error("Application already exists");
}
const projectPath = path_1.default.join(process.cwd(), fname);
const templateDir = path_1.default.resolve("D:\\projects\\node\\iqra\\packages\\cli\\src\\stubs");
//await fs.mkdir(projectPath);
//await fsExtra.copy(templateDir, projectPath + '/');
// Define project path
// const projectPath = path.resolve('new_test');
// Clone the repository and move the required folder
const cloneCommand = `
git clone -n --depth=1 --filter=tree:0 https://github.com/xtareq/iqra temp_repo &&
cd temp_repo &&
git sparse-checkout init --no-cone &&
git sparse-checkout set examples/iqra_test &&
git checkout &&
mv examples/iqra_test ${projectPath} &&
cd ..
`;
try {
// Execute the cloning and moving process
console.log('Cloning and setting up the repository...');
(0, child_process_1.exec)(cloneCommand, {});
// Check if the projectPath exists before proceeding
if (!fs_extra_1.default.existsSync(projectPath)) {
throw new Error(`Project path "${projectPath}" was not created.`);
}
// Remove the Git origin from the new project
console.log('Removing Git origin...');
(0, child_process_1.execSync)(`cd ${projectPath} && git remote remove origin`, { stdio: 'inherit' });
// Clean up the temporary repository
console.log('Cleaning up temporary files...');
fs_extra_1.default.removeSync('./temp_repo');
console.log(`Project created successfully in ${projectPath}`);
}
catch (error) {
console.error('An error occurred:', error);
// Cleanup in case of failure
if (fs_extra_1.default.existsSync('./temp_repo')) {
console.log('Cleaning up temporary repository...');
fs_extra_1.default.removeSync('./temp_repo');
}
if (fs_extra_1.default.existsSync(projectPath)) {
console.log('Cleaning up project path...');
fs_extra_1.default.removeSync(projectPath);
}
}
}
async function run() {
try {
const args = process.argv.slice(2);
if (args.length < 1) {
await displayCommandList({ logo: true, all: false });
}
else {
const cmdList = commands_1.commandList
.flatMap((x) => x.Command)
.concat(...commands_1.commandList.flatMap((f) => f.Alias.split(",").map((s) => s.trim())));
if (!listedCommands.includes(args[0].trim())) {
console.error("Invalid command");
await displayCommandList({ logo: false, all: false });
}
else {
let force = false;
if (args.some((x) => x == "-f" || x == "--force")) {
force = true;
}
if (args[0] == "new") {
const fname = args[1];
await (0, create_1.createApplication)(fname);
}
if (args[0] == "make:model") {
await createModel(args[1], { force });
}
if (args[0] == "make:controller" || args[0] == "m:c") {
let resource = false;
if (args.some((x) => x == "-r" || x == "--resource")) {
resource = true;
}
let model = null;
if (args.some((x) => x == "-m" || x == "--model")) {
const index = args.includes("-m")
? args.indexOf("-m")
: args.indexOf("--model");
if (args[index + 1] == undefined) {
throw new Error("Model not defined");
}
const modelName = args[index + 1];
model = modelName;
}
await (0, controller_1.createController)(args[1], { force, resource, model });
}
}
}
}
catch (error) {
console.log("CLI ERROR:", error);
}
}
run();