import * as fs from 'fs' import { Utils } from './utils.js' import { defaultGitConfig } from './constants.js' export class FileHandlers { cwd = process.cwd() projectFiles: string[] = [] async getProjectConfig() { // if there is a code-review.json file in the project then we should use that // if not then we should return a default config const file = await this.getFileContent(`${this.cwd}/codereview.json`) if (file) { return JSON.parse(file.content.toString()) } return defaultGitConfig } @Utils.catchError getFileContentInDirectory({ extensions = ['.js', '.ts', '.tsx', '.jsx'], projectPath = this.cwd, }: { extensions?: string[], projectPath?: string }): string[] { projectPath = !projectPath ? this.cwd : projectPath const files = fs.readdirSync(projectPath) // uses a recursive function to get all the files in the directory files.forEach((file) => { // exclude the node_modules folder if (!(file === 'node_modules' || file.startsWith('.') || file === 'dist')) { const filePath = `${projectPath}/${file}` const isDirectory = fs.lstatSync(filePath).isDirectory() const isSupportedFile = extensions.some((extension) => file.endsWith(extension), ) if (isDirectory) { const subFiles = this.getFileContentInDirectory({ extensions, projectPath: filePath }) subFiles.length && this.projectFiles.push(...subFiles) } else if (isSupportedFile) { this.projectFiles.push(filePath) } } }) return this.projectFiles } // gets the content of a file @Utils.catchError getFileContent(path: string) { if (fs.existsSync(path)) { return { content: fs.readFileSync(path, 'utf8'), path, } } return null } // writes the content to a file @Utils.catchError writeFileContent(path: string, content: string) { if (!fs.existsSync(path)) { fs.writeFileSync(path, content, 'utf8') } else { fs.appendFileSync(path, content, 'utf8') } } // deletes a file @Utils.catchError delete(path: string) { if (fs.existsSync(path)) { // check if file exists fs.unlinkSync(path) // delete file } } }