import path from 'path';
import {readdirSync, statSync} from 'fs';

/**
 * Expand a path to a list of all files deeply contained in it
 */
export function expandPathToFilesSync(sourcePath: string, accept: (fileName: string) => boolean): string[] {
  const fullPath = path.resolve(sourcePath);
  const directory = statSync(fullPath);

  return directory.isDirectory()
    ? // eslint-disable-next-line unicorn/prefer-spread
      ([] as string[]).concat(
        ...readdirSync(fullPath).map(fragment =>
          expandPathToFilesSync(path.resolve(sourcePath, fragment), accept),
        ),
      )
    : [fullPath].filter(accept);
}
