All files / backend/src/utils file-dir-utils.ts

22.72% Statements 5/22
0% Branches 0/8
0% Functions 0/7
22.72% Lines 5/22

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81                                                                                                                                        2x 2x 2x 2x 2x                
/**
 * File and Directory Utilities
 *
 * Helper functions for file system operations.
 */
 
import fs from 'fs-extra';
import fssimple from 'fs';
 
/**
 * Extract filename from a full path
 * TODO: use everywhere in code
 */
export function filenameFromPath(fullPath: string): string {
  return fullPath.replace(/^.*[\\/]/, '');
}
 
/**
 * Recursively and forcefully remove a file or directory
 */
export async function recurForceRemove(dirPath: string): Promise<void> {
  if (fs.existsSync(dirPath)) {
    const lstat = fs.lstatSync(dirPath);
 
    if (lstat.isDirectory()) {
      fs.removeSync(dirPath);
    } else if (lstat.isFile()) {
      fs.unlinkSync(dirPath);
    }
  }
}
 
/**
 * Remove files in a directory matching a regex pattern
 * TODO: TEST ON WINDOWS
 */
export async function fileRegexRemove(dirPath: string, regex: RegExp): Promise<void> {
  fssimple
    .readdirSync(dirPath)
    .filter((f) => regex.test(f))
    .forEach((f) => fs.unlinkSync(dirPath + '/' + f));
}
 
/**
 * Ensure a directory exists and is empty
 */
export async function ensureEmptyDir(destination_dirPath: string): Promise<void> {
  await fs.ensureDir(destination_dirPath);
  await fs.emptyDir(destination_dirPath);
  await fs.ensureDir(destination_dirPath);
}
 
/**
 * Check if a path is a directory
 */
export function pathIsDirectory(dirPath: string): boolean {
  if (fs.existsSync(dirPath)) {
    const lstat = fs.lstatSync(dirPath);
    return lstat.isDirectory();
  }
  return false;
}
 
/**
 * Legacy class-based interface for backward compatibility
 * @deprecated Use named exports instead
 */
export class FileDirUtils {
  filenameFromPath = filenameFromPath;
  recurForceRemove = recurForceRemove;
  fileRegexRemove = fileRegexRemove;
  ensureEmptyDir = ensureEmptyDir;
  pathIsDirectory = pathIsDirectory;
}
 
/**
 * Default singleton instance for backward compatibility
 * @deprecated Use named function exports instead
 */
export default new FileDirUtils();