All files / cli/src file.ts

100% Statements 19/19
100% Branches 11/11
100% Functions 3/3
100% Lines 19/19

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                      10x 10x   3x 2x   1x   1x     2x                       5x 1x   4x                     9x   9x 3x   6x 5x   1x   3x   1x     2x      
import { isErrorWithCode } from '@metamask/utils';
import { copyFile, lstat, access } from 'node:fs/promises';
 
/**
 * Check if the target path is a directory.
 *
 * @param target The path to check.
 * @returns A promise which resolves to true if the target path is a directory.
 */
export async function isDirectory(target: string): Promise<boolean> {
  // May not work on Windows.
  try {
    return (await lstat(target)).isDirectory();
  } catch (error) {
    if (isErrorWithCode(error)) {
      switch (error.code) {
        case 'ENOENT':
          return false;
        default:
          break;
      }
    }
    throw error;
  }
}
 
/**
 * Asynchronously copy file(s) from source to destination.
 *
 * @param source - Where to copy file(s) from.
 * @param destination - Where to copy file(s) to.
 * @returns A promise that resolves when copying is complete.
 */
export async function cp(source: string, destination: string): Promise<void> {
  if (await isDirectory(source)) {
    throw new Error('Directory cp not implemented.');
  }
  await copyFile(source, destination);
}
 
/**
 * Asynchronously check if a file exists.
 *
 * @param path - The path to check
 * @returns A promise that resolves to true iff a file exists at the given path
 */
export async function fileExists(path: string): Promise<boolean> {
  // May not work on Windows.
  try {
    // if the file can be accessed, it exists
    await access(path);
    return true;
  } catch (error) {
    if (isErrorWithCode(error)) {
      switch (error.code) {
        case 'EEXIST':
          return true;
        case 'ENOENT':
          return false;
        default:
          break;
      }
    }
    throw error;
  }
}