Skip to content

Commit

Permalink
feat: optimize code
Browse files Browse the repository at this point in the history
  • Loading branch information
kiner-tang committed Jul 8, 2024
1 parent 7362e1f commit 2aa64bb
Showing 1 changed file with 21 additions and 18 deletions.
39 changes: 21 additions & 18 deletions packages/create-mako/src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import fs from 'fs';
import path from 'path';
import path, { resolve } from 'path';
import { globSync } from 'glob';
import type { QuestionCollection } from 'inquirer';
import yargs from 'yargs-parser';
Expand Down Expand Up @@ -64,15 +64,12 @@ type InitQuestion = {
name: string;
template: string;
};
async function main() {
const inquirer = (await import('inquirer')).default;

// Check if the current directory is empty.
async function checkEmptyDir(name: string) {
const inquirer = (await import('inquirer')).default;
const cwd = process.cwd();
const isDirEmpty = fs.readdirSync(cwd).length === 0;

// If the current directory is not empty, prompt the user to confirm whether they want to continue creating the project.
if (!isDirEmpty) {
const exist = fs.existsSync(resolve(cwd, name));
if (exist && fs.readdirSync(resolve(cwd, name)).length > 0) {
const answersContinue = await inquirer.prompt([
{
type: 'confirm',
Expand All @@ -84,21 +81,29 @@ async function main() {
]);

if (!answersContinue.continue) {
return;
process.exit(1);
}
}
}

let name = args._[0];
async function main() {
const inquirer = (await import('inquirer')).default;

let name: string = args._[0] as string;
let { template } = args;
let questions: QuestionCollection[] = [];
if (!name) {
questions.push({
type: 'input',
name: 'name',
message: 'Project name:',
default: 'mako-project',
});
let answers = await inquirer.prompt<InitQuestion>([
{
type: 'input',
name: 'name',
message: 'Project name:',
default: 'mako-project',
},
]);
name = answers.name;
}
await checkEmptyDir(name);
if (!template) {
const templates = globSync('**/', {
cwd: baseTemplatesPath,
Expand All @@ -113,9 +118,7 @@ async function main() {
});
}
if (questions.length > 0) {
const inquirer = (await import('inquirer')).default;
let answers = await inquirer.prompt<InitQuestion>(questions);
name = name || answers.name;
template = template || answers.template;
}
return init({ projectName: String(name), template });
Expand Down

0 comments on commit 2aa64bb

Please sign in to comment.