@sern/cli
Version:
Official CLI for @sern/handler
291 lines (288 loc) • 8.83 kB
JavaScript
import { parseTsConfig } from '../chunk-LLD33MCO.js';
import { fromCwd } from '../chunk-H6QGMA6W.js';
import { blueBright, yellowBright, greenBright, redBright, underline } from 'colorette';
import { execa } from 'execa';
import { findUp } from 'find-up';
import ora from 'ora';
import prompt from 'prompts';
import { writeFile, readFile as readFile$1 } from 'fs/promises';
import { readFile, writeFile as writeFile$1, rename } from 'node:fs/promises';
import fs from 'fs';
import path from 'path';
var lang = {
message: "What language do you want the project to be in?",
name: "lang",
type: "select",
choices: [
{
title: "JavaScript",
description: "JS",
value: "javascript"
},
{
title: "JavaScript (ESM)",
description: "JS",
value: "javascript-esm"
},
{
title: "TypeScript",
description: "TS - (Recommended)",
value: "typescript"
}
]
};
var main_dir = {
message: "What is the main directory of your project?",
name: "main_dir",
type: "text",
initial: "src"
};
var cmds_dir = {
message: "What is the directory of your commands?",
name: "cmds_dir",
type: "text",
initial: "commands",
validate: (dir) => dir === "src" ? "You can not use src as a directory" : true
};
({
name: "npm_init",
type: "confirm",
message: `Do you want ${blueBright("me")} to initialize npm?`,
initial: true
});
var gitInit = {
name: "gitinit",
type: "confirm",
message: `Do you want to ${blueBright("me")} to initialize git?`,
initial: true
};
var which_manager = {
message: `Which manager do you want to use?`,
name: "manager",
type: "select",
choices: [
{
title: "NPM",
description: "Default Package Manager",
selected: true,
value: "npm"
},
{
title: "Yarn",
description: "Yarn Package Manager",
value: "yarn"
},
{
title: "Skip",
description: "Skip selection",
value: "skip"
}
]
};
var skip_install_dep = {
name: "skip_install_dep",
type: "confirm",
message: `Do you want ${blueBright("me")} to install dependencies?`,
initial: false
};
var name = {
message: "What is your project name?",
name: "name",
type: "text",
validate: (name2) => name2.match("^(?:@[a-z0-9-*~][a-z0-9-*._~]*/)?[a-z0-9-~][a-z0-9-._~]*$") ? true : "Invalid name"
};
async function editMain(name2) {
const pjLocation = await findUp("package.json", {
cwd: fromCwd("/" + name2)
});
const output = JSON.parse(await readFile(pjLocation, "utf8"));
if (!output)
throw new Error("Can't read your package.json.");
output.name = name2;
return writeFile$1(pjLocation, JSON.stringify(output, null, 2));
}
async function editDirs(srcName, cmds_dirName, name2, lang2 = "typescript") {
const path2 = await findUp("src", {
cwd: fromCwd(name2),
type: "directory"
});
const ext = lang2 === "typescript" ? "ts" : "js";
const newMainDir = path2?.replace("src", srcName);
await rename(path2, newMainDir);
const cmdsPath = await findUp("commands", {
cwd: fromCwd(name2, srcName),
type: "directory"
});
const index = await findUp(`index.${ext}`, {
cwd: fromCwd(name2, srcName)
});
const newCmdsPath = cmdsPath?.replace("commands", cmds_dirName);
await rename(cmdsPath, newCmdsPath);
const tsconfig = await findUp("tsconfig.json", {
cwd: process.cwd() + "/" + name2
});
if (tsconfig) {
const output2 = await parseTsConfig(tsconfig);
if (!output2)
throw new Error("Can't read your tsconfig.json.");
if (!output2.compilerOptions)
throw new Error("Can't find compilerOptions in your tsconfig.json.");
output2.compilerOptions.rootDir = srcName;
await writeFile$1(tsconfig, JSON.stringify(output2, null, 2));
}
const output = await readFile(index, "utf8");
const oldfold = ext === "ts" ? "dist" : "src";
const newfold = ext === "ts" ? "dist" : srcName;
const regex = new RegExp(`commands: '${oldfold}/commands'`);
const edit = output.replace(regex, `commands: '${newfold}/${cmds_dirName}'`);
return writeFile$1(index, edit);
}
async function installDeps(choice, name2) {
const pkg = await findUp("package.json", {
cwd: process.cwd() + "/" + name2
});
if (!pkg)
throw new Error("No package.json found!");
const output = JSON.parse(await readFile$1(pkg, "utf8"));
if (!output)
throw new Error("Can't read file.");
const deps = output.dependencies;
if (!deps)
throw new Error("Can't find dependencies.");
if (choice === "skip") {
return console.log("Dependency installation skipped...");
}
const spin = ora({
text: `Installing dependencies...`,
spinner: "aesthetic"
}).start();
const result = await execa(choice, ["install"], {
cwd: process.cwd() + "/" + name2
}).catch(() => null);
if (!result || result?.failed) {
spin.fail(`${redBright("Failed")} to install dependencies!`);
process.exit(1);
} else
spin.succeed(`Dependencies installed!`);
}
async function cloneRepo(lang2, name2) {
try {
await execa("git", ["clone", `https://github.com/sern-handler/templates.git`]);
copyRecursiveSync(`templates/templates/${lang2}`, name2);
fs.rmSync(`templates/`, { recursive: true, force: true });
} catch (error) {
console.log(`${redBright("\u2716 Failed")} to clone github templates repo. Install git and try again!`);
process.exit(1);
}
}
function copyRecursiveSync(src, dest) {
const exists = fs.existsSync(src);
const stats = exists && fs.statSync(src);
const isDirectory = exists && stats.isDirectory();
if (isDirectory) {
fs.mkdirSync(dest);
fs.readdirSync(src).forEach(function(childItemName) {
copyRecursiveSync(path.join(src, childItemName), path.join(dest, childItemName));
});
} else {
fs.copyFileSync(src, dest);
}
}
async function npm() {
const npm2 = await execa("npm", ["-v"]).catch(() => null);
const npm_version = npm2?.stdout;
const yarn = await execa("yarn", ["-v"]).catch(() => null);
const yarn_version = yarn?.stdout;
if (npm_version && !yarn_version) {
return "npm";
}
if (!npm_version && yarn_version) {
return "yarn";
}
if (npm_version && yarn_version) {
return "both";
}
}
// src/commands/init.ts
async function init(flags) {
console.log(`${yellowBright("[WARN]:")} This command is deprecated, use ${greenBright("npm create @sern/bot")} instead`);
let data;
let git_init = true;
let pm = flags.sync ? void 0 : flags.y ? "npm" : await npm();
if (flags.y) {
const projectName = await prompt([name]);
git_init = true;
data = {
name: projectName.name,
lang: "typescript",
main_dir: "src",
cmds_dir: "commands"
};
} else if (flags.sync) {
data = await prompt([lang, main_dir, cmds_dir]);
} else {
data = await prompt([name, lang, main_dir, cmds_dir]);
git_init = (await prompt([gitInit])).gitinit;
}
const language = data.lang === "javascript-esm" ? "javascript" : data.lang;
const config = {
language,
paths: {
base: data.main_dir,
commands: data.cmds_dir
}
};
const file = JSON.stringify(config, null, 2);
const requiredData = flags.sync !== void 0 ? 3 : 4;
const receivedData = Object.keys(data).length;
const incompleteDataCondition = receivedData < requiredData;
if (incompleteDataCondition)
process.exit(1);
if (!flags.sync)
await cloneRepo(data.lang, data.name);
const pkg = await findUp("package.json", {
cwd: process.cwd() + "/" + data.name
});
if (!pkg)
throw new Error("No package.json found!");
await writeFile(pkg.replace("package.json", "sern.config.json"), file);
if (flags.sync) {
console.log("Project was successfully synced!");
process.exit(0);
}
git_init ? await git(data) : console.log(`Skipping git init...
`);
let choice;
if (pm === "both") {
choice = (await prompt([which_manager])).manager;
} else {
choice = (await prompt([skip_install_dep])).skip_install_dep ? pm : "skip";
}
await installDeps(choice, data.name);
await editMain(data.name);
await editDirs(data.main_dir, data.cmds_dir, data.name, data.lang);
console.log(`${greenBright("Success, project was initialised!")}`);
process.exit(0);
}
async function git(data) {
const spin = ora({
text: "Initializing git...",
spinner: "aesthetic"
}).start();
try {
await execa("git", ["init", data.name]);
await wait(300);
spin.succeed("Git initialized!");
} catch (error) {
spin.fail(`${redBright("Failed")} to initialize git!
Try to install it at ${underline("https://git-scm.com")}
Skipping for now.`);
}
}
async function wait(ms) {
const wait2 = (await import('util')).promisify(setTimeout);
return wait2(ms);
}
export { init };
//# sourceMappingURL=out.js.map
//# sourceMappingURL=init.js.map