All files / lib/utils file.ts

92.59% Statements 25/27
50% Branches 4/8
100% Functions 9/9
92.31% Lines 24/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 525x 5x 5x   5x 5x 5x   5x       72x     5x       72x 220x     5x 116x   5x 28x 28x 116x         5x 44x   44x   104x 104x     104x           44x    
import * as fs from 'fs';
import * as path from 'path';
import { promisify } from 'util';
 
const readdir = promisify(fs.readdir);
const lstat = promisify(fs.lstat);
const exists = promisify(fs.exists);
 
export function mapAsync<T, U>(
  array: T[],
  callbackfn: (value: T, index: number, array: T[]) => Promise<U>,
): Promise<U[]> {
  return Promise.all(array.map(callbackfn));
}
 
export async function filterAsync<T>(
  array: T[],
  callbackfn: (value: T, index: number, array: T[]) => Promise<boolean>,
): Promise<T[]> {
  const filterMap = await mapAsync(array, callbackfn);
  return array.filter((value, index) => filterMap[index]);
}
 
export const isDirectory = async (source: string) =>
  (await lstat(source)).isDirectory();
 
export const getDirectories = async (source: string) => {
  const dirs = await readdir(source);
  return filterAsync(
    dirs.map(name => path.join(source, name)),
    isDirectory,
  );
};
 
export const getFiles = async (dirPath: string, pattern: RegExp) => {
  const dirs = await readdir(dirPath, { withFileTypes: true });
 
  return (
    await filterAsync(dirs, async (f: fs.Dirent | string) => {
      try {
        Iif (typeof f === 'string') {
          return (await exists(path.join(dirPath, f))) && pattern.test(f);
        } else {
          return f.isFile() && pattern.test(f.name);
        }
      } catch {
        return false;
      }
    })
  ).map(f => path.join(dirPath, typeof f === 'string' ? f : f.name));
};