All files / common/util fs.ts

100% Statements 35/35
100% Branches 6/6
100% Functions 5/5
100% Lines 30/30

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 693x 3x         3x 20x 20x 5x   15x             3x 11x 11x 11x   3x             3x 4x   4x   4x 6x 6x   6x 1x   5x 4x         4x           3x 10x 10x 10x           3x 10x 2x      
import * as fs from 'fs/promises';
import * as path from 'path';
 
/**
 * Checks if file exists with the given `filePath`.
 */
export const isFileExists = async (filePath: string) => {
  try {
    await fs.stat(filePath);
    return true;
  } catch (error) {
    return false;
  }
};
 
/**
 * Checks if the directory exists with the given `filePath`.
 */
export const isDirectoryExists = async (directoryPath: string) => {
  try {
    const stat = await fs.lstat(directoryPath);
    return stat.isDirectory();
  } catch (error) {
    return false;
  }
};
 
/**
 * Gets all files that have either .yml or .yaml extension in the given directory.
 */
export const getYamlFiles = async (directory: string) => {
  let yamlFiles: string[] = [];
 
  const files = await fs.readdir(directory);
 
  for (const file of files) {
    const fullPath = path.join(directory, file);
    const isDirExists = await isDirectoryExists(fullPath);
 
    if (isDirExists) {
      yamlFiles = yamlFiles.concat(await getYamlFiles(fullPath));
    } else {
      if (file.endsWith('.yml') || file.endsWith('.yaml')) {
        yamlFiles.push(fullPath);
      }
    }
  }
 
  return yamlFiles;
};
 
/**
 * Gets fileName from the given path without an extension.
 */
export const getFileName = (filePath: string) => {
  const baseName = path.basename(filePath);
  const extension = path.extname(filePath);
  return baseName.replace(extension, '');
};
 
/**
 * Removes the given file if exists.
 */
export const removeFileIfExists = async (filePath: string) => {
  if (await isFileExists(filePath)) {
    await fs.unlink(filePath);
  }
};