Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/detect template break changes #60

Merged
merged 4 commits into from
Aug 4, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
"start": "node ./bin/cli.js",
"start:dev": "tsnd ./src/cli.ts",
"build": "npm run clean && tsc -p tsconfig.json && yarn cp:templates && chmod +x ./bin/cli.js",
"cp:templates": "cp -r ./src/generate/templates ./bin/generate/templates && cp -r ./src/providers/prisma/templates ./bin/providers/prisma/templates",
"cp:templates": "cp -r ./src/generate/templates ./bin/generate/templates",
"clean": "rimraf ./bin",
"prepublish": "npm run build && npm pack",
"publish": "npm publish --tag latest",
Expand All @@ -50,6 +50,7 @@
},
"dependencies": {
"@expressots/boost-ts": "1.3.0",
"axios": "^1.7.3",
"chalk-animation": "2.0.3",
"cli-progress": "3.12.0",
"cli-table3": "0.6.5",
Expand Down
41 changes: 37 additions & 4 deletions src/cli.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,21 @@
#!/usr/bin/env node

import chalk from "chalk";
import { stdout } from "process";
import yargs from "yargs";
import { hideBin } from "yargs/helpers";
import {
devCommand,
buildCommand,
devCommand,
prodCommand,
} from "./commands/project.commands";
import { generateProject } from "./generate";
import { helpCommand } from "./help/cli";
import { infoProject } from "./info";
import { createProject } from "./new";
import { createExternalProviderCMD } from "./providers/create/cli";
import { addProviderCMD } from "./providers";
import chalk from "chalk";
import { stdout } from "process";
import { createExternalProviderCMD } from "./providers/create/cli";
import { printError } from "./utils/cli-ui";

stdout.write(`\n${[chalk.bold.green("🐎 Expressots")]}\n\n`);

Expand All @@ -30,6 +31,38 @@ yargs(hideBin(process.argv))
.command(infoProject())
.command(helpCommand())
.demandCommand(1, "You need at least one command before moving on")
.strict()
.fail((msg, err, yargs) => {
if (msg) {
if (msg.includes("Unknown argument")) {
// Get the command name
const command = process.argv[2];

if (command === "run") {
printError(
`The "run" command has been removed. Use "dev", "prod" or "build" instead.`,
"expressots help",
);
} else {
printError(
`Unknown command [${command}]. For help type`,
"expressots help",
);
}
} else {
printError(msg, "expressots help");
}
} else if (err) {
printError(err.message, "command-validator");
} else {
printError(
"Command invalid. Consider updating the CLI.",
"command-validator",
);
yargs.showHelp();
}
process.exit(1);
})
.epilog(
`${chalk.bold.green("For more information:")} \n\n` +
"🌐 visit:\t https://expresso-ts.com\n" +
Expand Down
126 changes: 87 additions & 39 deletions src/commands/project.commands.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,23 @@
import { spawn } from "child_process";
import { promises as fs } from "fs";
import path from "path";
import { Argv, CommandModule } from "yargs";
import { promises as fs, readFileSync } from "fs";
import os from "os";
import path, { join } from "path";
import { CommandModule } from "yargs";
import { printError, printSuccess } from "../utils/cli-ui";
import Compiler from "../utils/compiler";
import os from "os";

/**
* Load tsconfig path and extract outDir
*/
const tsconfigBuildPath = join(process.cwd(), "tsconfig.build.json");
const tsconfig = JSON.parse(readFileSync(tsconfigBuildPath, "utf-8"));
const outDir = tsconfig.compilerOptions.outDir;

/**
* Load the configuration from the compiler
* @param compiler The compiler to load the configuration from
* @returns The configuration
*/

const opinionatedConfig: Array<string> = [
"--transpile-only",
"--clear",
Expand All @@ -30,6 +36,45 @@ const nonOpinionatedConfig: Array<string> = [
"./src/main.ts",
];

/**
* Dev command module
* @type {CommandModule<object, object>}
* @returns The command module
*/
export const devCommand: CommandModule<object, object> = {
command: "dev",
describe: "Start development server.",
handler: async () => {
await runCommand({ command: "dev" });
},
};

/**
* Build command module
* @type {CommandModule<object, object>}
* @returns The command module
*/
export const buildCommand: CommandModule<object, object> = {
command: "build",
describe: "Build the project.",
handler: async () => {
await runCommand({ command: "build" });
},
};

/**
* Prod command module
* @type {CommandModule<object, object>}
* @returns The command module
*/
export const prodCommand: CommandModule<object, object> = {
command: "prod",
describe: "Run in production mode.",
handler: async () => {
await runCommand({ command: "prod" });
},
};

/**
* Helper function to execute a command
* @param command The command to execute
Expand Down Expand Up @@ -59,19 +104,25 @@ function execCmd(
});
}

// Helper to delete the dist directory
/**
* Helper function to clean the dist directory
*/
const cleanDist = async (): Promise<void> => {
await fs.rm("./dist", { recursive: true, force: true });
printSuccess("Deleted dist directory", "clean-dist");
await fs.rm(outDir, { recursive: true, force: true });
printSuccess(`Clean ${outDir} directory`, "clean-dist");
};

// Helper to compile TypeScript
/**
* Helper function to compile TypeScript
*/
const compileTypescript = async () => {
await execCmd("npx", ["tsc", "-p", "tsconfig.build.json"]);
printSuccess("Built successfully", "compile-typescript");
};

// Helper to copy files
/**
* Helper function to copy files to the dist directory
*/
const copyFiles = async () => {
const { opinionated } = await Compiler.loadConfig();
let filesToCopy: Array<string> = [];
Expand All @@ -85,41 +136,23 @@ const copyFiles = async () => {
filesToCopy = ["tsconfig.json", "package.json"];
}
filesToCopy.forEach((file) => {
fs.copyFile(file, path.join("./dist", path.basename(file)));
fs.copyFile(file, join(outDir, path.basename(file)));
});
};

// Helper clear screen
/**
* Helper function to clear the screen
*/
const clearScreen = () => {
const platform = os.platform();
const command = platform === "win32" ? "cls" : "clear";
spawn(command, { stdio: "inherit", shell: true });
};

export const devCommand: CommandModule<object, object> = {
command: "dev",
describe: "Start development server.",
handler: async () => {
await runCommand({ command: "dev" });
},
};

export const buildCommand: CommandModule<object, object> = {
command: "build",
describe: "Build the project.",
handler: async () => {
await runCommand({ command: "build" });
},
};

export const prodCommand: CommandModule<object, object> = {
command: "prod",
describe: "Run in production mode.",
handler: async () => {
await runCommand({ command: "prod" });
},
};

/**
* Helper function to run a command
* @param command The command to run
*/
export const runCommand = async ({
command,
}: {
Expand All @@ -136,22 +169,37 @@ export const runCommand = async ({
);
break;
case "build":
if (!outDir) {
printError(
"Cannot build project. Please provide an outDir in tsconfig.build.json",
"build-command",
);
process.exit(1);
}
await cleanDist();
await compileTypescript();
await copyFiles();
break;
case "prod": {
if (!outDir) {
printError(
"Cannot run in prod mode. Please provide an outDir in tsconfig.build.json",
"prod-command",
);
process.exit(1);
}

let config: Array<string> = [];
if (opinionated) {
config = [
"-r",
"dotenv/config",
"-r",
"./dist/register-path.js",
"./dist/src/main.js",
`./${outDir}/register-path.js`,
`./${outDir}/src/main.js`,
];
} else {
config = ["-r", "dotenv/config", "./dist/main.js"];
config = ["-r", "dotenv/config", `./${outDir}/main.js`];
}
clearScreen();
execCmd("node", config);
Expand Down
18 changes: 15 additions & 3 deletions src/info/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@ import chalk from "chalk";
import path from "path";
import fs from "fs";
import os from "os";
import { printError } from "../utils/cli-ui";
import { printError, printSuccess } from "../utils/cli-ui";
import axios from "axios";

function getInfosFromPackage() {
try {
Expand All @@ -27,12 +28,23 @@ function getInfosFromPackage() {
}
}

const infoForm = (): void => {
export const infoForm = (): void => {
getInfosFromPackage();

console.log(chalk.green("System information:"));
console.log(chalk.white(`\tOS Version: ${os.version()}`));
console.log(chalk.white(`\tNodeJS version: ${process.version}`));
currentCLIVersion();
};

export { infoForm };
async function currentCLIVersion(): Promise<void> {
try {
const response = await axios.get(
"https://api.github.com/repos/expressots/expressots-cli/releases",
);
const latestRelease = `v${response.data[0].tag_name}`;
printSuccess("CLI version:", latestRelease);
} catch (error: Error | any) {
printError("Error:", error.message);
}
}
Loading
Loading