Skip to content

Commit

Permalink
added FileManager
Browse files Browse the repository at this point in the history
  • Loading branch information
FadTheChad committed Nov 10, 2022
1 parent 605f689 commit 5239b72
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
72 changes: 72 additions & 0 deletions src/modules/FileManager/FileManager.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { promises as fs } from "fs"
import path from "path"
import { CreateType } from "../../typings/CreateType"

export default class FileManager {
// Takes in { key: path } (Path is based on process.cwd())
// Eg: { command: './bot/slashCommands'}
constructor(private _fmOpts: { [key in CreateType]: string }, private _defaultCommandCat: string = "misc") {}

private async _pathExists(path: string) {
try {
await fs.access(path)
return true
} catch (e) {
return false
}
}

private async _createFile(fileName: string, fileContent: string | string[] = "") {
if (!fileName.endsWith(".ts")) fileName = fileName + ".ts"
const filePath = path.join(process.cwd(), fileName)

if (await this._pathExists(filePath)) throw new Error("File already exists")

await fs.writeFile(filePath, fileContent)
return filePath
}

private async _createDir(dirName: string) {
const dirPath = path.join(process.cwd(), dirName)

if (await this._pathExists(dirPath)) throw new Error("Dir already exists")

await fs.mkdir(dirPath).catch((e) => {
throw e
})
return dirPath
}

public async create(createType: CreateType, name: string) {
const createPath = this._fmOpts[createType]

if (!createPath) throw new Error("Specify a valid createType")

switch (createType) {
case "module":
return await this._createDir(path.join(createPath, name))

case "command":
// trys fetching `category/command`
// where opt1 = category;
// opt2 = command
let [opt1, opt2] = name.replace("\\", "/").split("/")

// user specified both options (category & command)
if (opt1 && opt2) {
const cmdPath = path.join(createPath, opt1, opt2)
await this._createDir(path.join(createPath, opt1)).catch(console.error)
return await this._createFile(cmdPath, "SKIBADAPAB")
}

// user specified one opt. We will assume this to be the command
else if (opt1) {
await this._createDir(path.join(createPath, this._defaultCommandCat)).catch(() => {})
return await this._createFile(path.join(createPath, this._defaultCommandCat, opt1), "SKIBADAPAB")
}

case "event":
return await this._createFile(path.join(createPath, name), "EVENTS YAY")
}
}
}
1 change: 1 addition & 0 deletions src/typings/CreateType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export type CreateType = "module" | "command" | "event"

0 comments on commit 5239b72

Please sign in to comment.