Skip to content

Commit a4c2759

Browse files
committed
feat: added support for declaring dependencies on file commands incase the dependencies is not yet defined in canis project
1 parent f4e7688 commit a4c2759

2 files changed

Lines changed: 41 additions & 5 deletions

File tree

src/commands/test.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ export const info = {
1111
};
1212

1313
export default async function (msg: Message) {
14-
if (!/^test$/i.test(msg.body)) return;
15-
16-
await msg.reply("This is a test response.");
17-
}
14+
if (!/^test$/i.test(msg.body)) return;
15+
16+
await msg.reply("This is a test response.");
17+
}

src/components/utils/cmd/loader.ts

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,41 @@ import log from "../log";
22
import { promises as fs } from "fs";
33
import path from "path";
44
import { commands } from "../../../index";
5+
import { exec } from "child_process";
6+
import util from "util";
7+
const execPromise = util.promisify(exec);
58

69
const commandsPath = path.join(__dirname, "..", "..", "..", "commands");
710

11+
async function ensureDependencies(
12+
dependencies: { name: string; version: string }[],
13+
) {
14+
for (const dep of dependencies) {
15+
try {
16+
require.resolve(dep.name);
17+
log.info("Loader", `Dependency already installed: ${dep.name}`);
18+
} catch {
19+
log.info(
20+
"Loader",
21+
`Installing missing dependency: ${dep.name}@${dep.version}`,
22+
);
23+
try {
24+
const { stdout, stderr } = await execPromise(
25+
`npm install ${dep.name}@${dep.version}`,
26+
);
27+
if (stdout) log.info("npm", stdout);
28+
if (stderr) log.error("npm", stderr);
29+
} catch (err) {
30+
log.error(
31+
"Loader",
32+
`Failed to install ${dep.name}@${dep.version}`,
33+
err,
34+
);
35+
}
36+
}
37+
}
38+
}
39+
840
export default async function loader(file: string, customPath?: string) {
941
if (/\.js$|\.ts$/.test(file)) {
1042
const filePath = path.join(customPath || commandsPath, file);
@@ -21,6 +53,10 @@ export default async function loader(file: string, customPath?: string) {
2153
commandModule.info &&
2254
commandModule.info.command
2355
) {
56+
if (Array.isArray(commandModule.info.dependencies)) {
57+
await ensureDependencies(commandModule.info.dependencies);
58+
}
59+
2460
commands[commandModule.info.command] = {
2561
command: commandModule.info.command,
2662
description: commandModule.info.description || "No description",
@@ -41,5 +77,5 @@ export async function mapCommands() {
4177
}
4278

4379
export function mapCommandsBackground() {
44-
mapCommands().catch(err => log.error("MapCommandLoader", err));
80+
mapCommands().catch((err) => log.error("MapCommandLoader", err));
4581
}

0 commit comments

Comments
 (0)