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

Fix/adjust provider #59

Merged
merged 5 commits into from
Aug 3, 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
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@
"cli-progress": "3.12.0",
"cli-table3": "0.6.5",
"degit": "2.8.4",
"glob": "10.4.1",
"glob": "10.4.5",
"inquirer": "8.2.6",
"mustache": "4.2.0",
"semver": "7.6.2",
Expand Down
31 changes: 16 additions & 15 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,35 +2,36 @@

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

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

yargs(hideBin(process.argv))
.scriptName("expressots")
.command(runCommandModule)
.command(createProject())
.command(generateProviders())
.command(devCommand)
.command(buildCommand)
.command(prodCommand)
.command(createExternalProviderCMD())
.command(addProviderCMD())
.command(generateProject())
.command(infoProject())
.command(helpCommand())
.example("$0 new expressots-demo", "Create interactively")
.example("$0 new expressots-demo -d ./", "Create interactively with path")
.example("$0 new expressots-demo -p yarn -t opinionated", "Create silently")
.example(
"$0 new expressots-demo -p yarn -t opinionated -d ./",
"Create silently with path",
)
.example("$0 generate service user-create", "Scaffold a service")
.example("$0 info", "Show CLI details")
.demandCommand(1, "You need at least one command before moving on")
.epilog(
"For more information: \n" +
`${chalk.bold.green("For more information:")} \n\n` +
"🌐 visit:\t https://expresso-ts.com\n" +
"💖 Sponsor:\t https://github.com/sponsors/expressots",
)
Expand Down
67 changes: 44 additions & 23 deletions src/commands/project.commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { spawn } from "child_process";
import { promises as fs } from "fs";
import path from "path";
import { Argv, CommandModule } from "yargs";
import { printError, printSuccess } from "../utils/cli-ui";
import Compiler from "../utils/compiler";
import os from "os";

/**
* Load the configuration from the compiler
Expand All @@ -12,6 +14,7 @@ import Compiler from "../utils/compiler";

const opinionatedConfig: Array<string> = [
"--transpile-only",
"--clear",
"-r",
"dotenv/config",
"-r",
Expand All @@ -21,6 +24,7 @@ const opinionatedConfig: Array<string> = [

const nonOpinionatedConfig: Array<string> = [
"--transpile-only",
"--clear",
"-r",
"dotenv/config",
"./src/main.ts",
Expand Down Expand Up @@ -58,11 +62,13 @@ function execCmd(
// Helper to delete the dist directory
const cleanDist = async (): Promise<void> => {
await fs.rm("./dist", { recursive: true, force: true });
printSuccess("Deleted dist directory", "clean-dist");
};

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

// Helper to copy files
Expand All @@ -83,31 +89,47 @@ const copyFiles = async () => {
});
};

// eslint-disable-next-line @typescript-eslint/ban-types
export const runCommandModule: CommandModule<{}, { command: string }> = {
command: "run <command>",
describe: "Runs a specified command (dev, build, prod)",
builder: (yargs: Argv) => {
return yargs.positional("command", {
describe: "The command to run",
type: "string",
choices: ["dev", "build", "prod"],
});
// Helper clear 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" });
},
handler: async (argv) => {
const { command } = argv;
// Now call your original runCommand function with the command
// Ensure runCommand is properly defined to handle these commands
await runCommand({ command });
};

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

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

export const runCommand = async ({
command,
}: {
command: string;
}): Promise<void> => {
const { opinionated } = await Compiler.loadConfig();

try {
switch (command) {
case "dev":
// Use execSync or spawn to run ts-node-dev programmatically
execCmd(
"tsnd",
opinionated ? opinionatedConfig : nonOpinionatedConfig,
Expand All @@ -131,16 +153,15 @@ const runCommand = async ({ command }: { command: string }): Promise<void> => {
} else {
config = ["-r", "dotenv/config", "./dist/main.js"];
}
// Ensure environment variables are set
clearScreen();
execCmd("node", config);
break;
}
default:
console.log(`Unknown command: ${command}`);
printError(`Unknown command: `, command);
break;
}
} catch (error) {
console.error("Error executing command:", error);
} catch (error: Error | any) {
printError("Error executing command:", error.message);
}
};

export { runCommand };
2 changes: 1 addition & 1 deletion src/generate/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ const coerceSchematicAliases = (arg: string) => {
const generateProject = (): CommandModule<CommandModuleArgs, any> => {
return {
command: "generate [schematic] [path] [method]",
describe: "Scaffold a new resource",
describe: "Generate ExpressoTS resource.",
aliases: ["g"],
builder: (yargs: Argv): Argv => {
yargs.positional("schematic", {
Expand Down
2 changes: 1 addition & 1 deletion src/help/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ type CommandModuleArgs = {};
const helpCommand = (): CommandModule<CommandModuleArgs, any> => {
return {
command: "resources",
describe: "Resource list",
describe: "Resource list.",
aliases: ["r"],
handler: async () => {
await helpForm();
Expand Down
4 changes: 2 additions & 2 deletions src/help/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,8 @@ const helpForm = async (): Promise<void> => {
["usecase", "g u", "Generate a usecase"],
["dto", "g d", "Generate a dto"],
["entity", "g e", "Generate an entity"],
["provider", "g p", "Generate a provider"],
["provider external", "a provider", "Generate an external provider"],
["provider", "add", "Add provider to the project"],
["provider", "create", "Create a provider"],
["module", "g mo", "Generate a module"],
["middleware", "g mi", "Generate a middleware"],
);
Expand Down
2 changes: 1 addition & 1 deletion src/info/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ type CommandModuleArgs = {};
const infoProject = (): CommandModule<CommandModuleArgs, any> => {
return {
command: "info",
describe: "Displays project details",
describe: "Displays project info.",
aliases: ["i"],
handler: async () => {
await infoForm();
Expand Down
2 changes: 1 addition & 1 deletion src/new/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ const checkNodeVersion = (): void => {
const createProject = (): CommandModule<CommandModuleArgs, any> => {
return {
command: "new <project-name> [package-manager] [template] [directory]",
describe: "Create a new project",
describe: "Create ExpressoTS application.",
builder: commandOptions,
handler: async ({
projectName,
Expand Down
16 changes: 1 addition & 15 deletions src/new/form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import fs from "node:fs";
import path from "node:path";
import { centerText } from "../utils/center-text";
import { printError } from "../utils/cli-ui";
import { changePackageName } from "../utils/change-package-info";

async function packageManagerInstall({
packageManager,
Expand Down Expand Up @@ -85,21 +86,6 @@ async function checkIfPackageManagerExists(packageManager: string) {
}
}

function changePackageName({
directory,
name,
}: {
directory: string;
name: string;
}): void {
const absDirPath = path.resolve(directory);
const packageJsonPath = path.join(absDirPath, "package.json");
const fileContents = fs.readFileSync(packageJsonPath, "utf-8");
const packageJson = JSON.parse(fileContents);
packageJson.name = name;
fs.writeFileSync(packageJsonPath, JSON.stringify(packageJson, null, 2));
}

function renameEnvFile(directory: string): void {
try {
const envExamplePath = path.join(directory, ".env.example");
Expand Down
29 changes: 29 additions & 0 deletions src/providers/add/cli.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { Argv, CommandModule } from "yargs";
import { addExternalProvider } from "./form";

// eslint-disable-next-line @typescript-eslint/ban-types
type CommandModuleArgs = {};

export const addProviderCMD = (): CommandModule<CommandModuleArgs, any> => {
return {
command: "add <provider> [version]",
describe: "Add provider to the project.",
builder: (yargs: Argv): Argv => {
yargs
.positional("provider", {
describe: "The provider to be added to the project",
type: "string",
})
.option("version", {
describe: "The provider version to be installed",
type: "string",
default: "latest",
alias: "v",
});
return yargs;
},
handler: async ({ provider, version }) => {
await addExternalProvider(provider, version);
},
};
};
Loading
Loading