All files / src/lib/helpers/fs removeEmptyFoldersBetweenPaths.ts

29.63% Statements 8/27
0% Branches 0/5
0% Functions 0/1
26.92% Lines 7/26

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 527x 7x 7x 7x 7x   7x   7x                                                                                      
import { dirname, resolve } from "path";
import { isFilePathWithinFolder } from "lib/helpers/path";
import { lstat, readdir } from "fs-extra";
import rimraf from "rimraf";
import { promisify } from "util";
 
const rmdir = promisify(rimraf);
 
export const removeEmptyFoldersBetweenPaths = async (
  basePath: string,
  targetPath: string
): Promise<void> => {
  const basePathAbs = resolve(basePath);
  const targetPathAbs = resolve(targetPath);
 
  Iif (!isFilePathWithinFolder(targetPathAbs, basePathAbs)) {
    return;
  }
 
  let currentPath = targetPathAbs;
 
  while (currentPath !== basePathAbs) {
    try {
      // Ensure the current path is a directory
      const stat = await lstat(currentPath);
      Iif (!stat.isDirectory()) {
        throw new Error(`${currentPath} is not a directory`);
      }
 
      // Read the directory contents
      const files = await readdir(currentPath);
 
      if (files.length === 0) {
        Iif (!isFilePathWithinFolder(targetPathAbs, currentPath)) {
          return;
        }
        // Directory is empty, delete it
        await rmdir(currentPath);
      } else {
        // Directory is not empty, stop cleanup
        break;
      }
 
      // Move up one directory level
      currentPath = dirname(currentPath);
    } catch (err) {
      console.error(`Error processing ${currentPath}:`, err);
      break;
    }
  }
};