All files / src copy-dir.ts

100% Statements 24/24
100% Branches 23/23
100% Functions 4/4
100% Lines 20/20

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                    7x 6x 5x 1x 1x     4x   4x   4x 16x 16x 16x 16x 10x 6x 6x     6x 6x 12x           15x       34x    
import fs from 'fs';
import path from 'path';
 
export type IOptions = {
  overwrite?: boolean
}
 
export function copyDir(src: string, dest: string, {
  overwrite = false
}: IOptions = {}) {
  if (!isDir(dest)) throw new Error(`Dest "${dest}" is not a directory`);
  if (!fs.existsSync(src)) throw new Error(`Src "${src}" not exist`);
  if (isFile(src) && (overwrite || !fs.existsSync(path.join(dest, path.basename(src))))) {
    fs.copyFileSync(src, path.join(dest, path.basename(src)));
    return;
  }
 
  const stack = [path.basename(src)];
 
  const srcParent = path.dirname(src);
 
  while (stack.length > 0) {
    const relativePath = stack.pop() as string;
    const absPathSrc = path.join(srcParent, relativePath);
    const absPathDest = path.join(dest, relativePath);
    if (isFile(absPathSrc)) {
      if (isFile(absPathDest) && !overwrite) continue;
      fs.copyFileSync(absPathSrc, absPathDest);
      continue;
    }
    // absPathSrc is dir
    !isDir(absPathDest) && fs.mkdirSync(absPathDest);
    const subDirs = fs.readdirSync(absPathSrc);
    stack.push(...subDirs.map(sub => path.join(relativePath, sub)));
    
  }
}
 
export function isDir(dest: string) {
  return fs.existsSync(dest) && fs.lstatSync(dest).isDirectory();
}
 
export function isFile(src: string) {
  return fs.existsSync(src) && fs.lstatSync(src).isFile();
}