All files / lib/internal/fs/cp cp.js

92.71% Statements 356/384
90.09% Branches 100/111
100% Functions 28/28
92.71% Lines 356/384

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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 3852x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 27x 27x 27x         27x 23x 23x 27x 2x 2x 20x 27x 2x 173x 173x 173x 40x 1x 1x 1x 1x 1x 1x 1x 40x 1x 1x 1x 1x 1x 1x 1x 1x 40x 1x 1x 1x 1x 1x 1x 1x 1x 40x 170x 173x 1x 1x 1x 1x 1x 1x 1x 169x 173x 2x 204x 204x 204x 204x 2x 173x 173x 173x 173x 173x 173x 173x 133x   173x 173x 173x 2x 22x 22x 22x 22x 1x 1x 22x 2x 22x 22x 22x 22x 22x 22x 2x 2x 2x 2x 2x 84x 84x 84x 84x 21x 21x 63x 63x 63x 84x 1x     84x 1x 1x 1x 1x 1x 1x 1x 61x 84x 2x 2x 2x 2x 2x 2x 156x 156x 156x 156x 156x 2x 28x 28x 28x 28x 2x 146x 146x 26x 26x 120x 146x 2x 160x 160x 160x 160x 66x 160x 1x 1x 1x 1x 1x 1x 94x 93x 93x 88x 93x 4x 5x 1x 1x 1x 1x 1x 1x 1x                           160x 2x 88x 88x 13x 88x 2x 13x 13x 10x 10x 13x 2x 2x 2x 2x 2x 2x 2x 13x 2x 85x 85x 85x 10x 10x 75x 85x 2x 10x 10x 10x 10x 10x 1x 1x 1x 9x 10x 2x 10x 10x 10x 2x 1x 1x 1x 2x 10x 10x 10x 10x 2x 133x 133x 133x 2x 10x 10x 10x 10x 10x 10x 10x 2x 66x 66x 19x 66x 2x 47x 47x 47x 47x 47x 2x 66x 66x 66x 146x 146x 146x 146x 146x 139x 66x 2x 4x 4x 4x     4x     4x 4x 4x 4x 1x 1x 1x 1x 1x 1x     4x     4x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 2x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 4x 2x 1x 1x 1x 1x 2x 2x 2x 2x 2x 2x  
'use strict';
 
// This file is a modified version of the fs-extra's copy method.
 
const {
  ArrayPrototypeEvery,
  ArrayPrototypeFilter,
  Boolean,
  PromiseAll,
  PromisePrototypeCatch,
  PromisePrototypeThen,
  PromiseReject,
  SafeArrayIterator,
  StringPrototypeSplit,
} = primordials;
const {
  codes: {
    ERR_FS_CP_DIR_TO_NON_DIR,
    ERR_FS_CP_EEXIST,
    ERR_FS_CP_EINVAL,
    ERR_FS_CP_FIFO_PIPE,
    ERR_FS_CP_NON_DIR_TO_DIR,
    ERR_FS_CP_SOCKET,
    ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY,
    ERR_FS_CP_UNKNOWN,
    ERR_FS_EISDIR,
  },
} = require('internal/errors');
const {
  os: {
    errno: {
      EEXIST,
      EISDIR,
      EINVAL,
      ENOTDIR,
    }
  }
} = internalBinding('constants');
const {
  chmod,
  copyFile,
  lstat,
  mkdir,
  readdir,
  readlink,
  stat,
  symlink,
  unlink,
  utimes,
} = require('fs/promises');
const {
  dirname,
  isAbsolute,
  join,
  parse,
  resolve,
  sep,
} = require('path');
 
async function cpFn(src, dest, opts) {
  // Warn about using preserveTimestamps on 32-bit node
  if (opts.preserveTimestamps && process.arch === 'ia32') {
    const warning = 'Using the preserveTimestamps option in 32-bit ' +
      'node is not recommended';
    process.emitWarning(warning, 'TimestampPrecisionWarning');
  }
  const stats = await checkPaths(src, dest, opts);
  const { srcStat, destStat } = stats;
  await checkParentPaths(src, srcStat, dest);
  if (opts.filter) {
    return handleFilter(checkParentDir, destStat, src, dest, opts);
  }
  return checkParentDir(destStat, src, dest, opts);
}
 
async function checkPaths(src, dest, opts) {
  const { 0: srcStat, 1: destStat } = await getStats(src, dest, opts);
  if (destStat) {
    if (areIdentical(srcStat, destStat)) {
      throw new ERR_FS_CP_EINVAL({
        message: 'src and dest cannot be the same',
        path: dest,
        syscall: 'cp',
        errno: EINVAL,
      });
    }
    if (srcStat.isDirectory() && !destStat.isDirectory()) {
      throw new ERR_FS_CP_DIR_TO_NON_DIR({
        message: `cannot overwrite directory ${src} ` +
            `with non-directory ${dest}`,
        path: dest,
        syscall: 'cp',
        errno: EISDIR,
      });
    }
    if (!srcStat.isDirectory() && destStat.isDirectory()) {
      throw new ERR_FS_CP_NON_DIR_TO_DIR({
        message: `cannot overwrite non-directory ${src} ` +
            `with directory ${dest}`,
        path: dest,
        syscall: 'cp',
        errno: ENOTDIR,
      });
    }
  }
 
  if (srcStat.isDirectory() && isSrcSubdir(src, dest)) {
    throw new ERR_FS_CP_EINVAL({
      message: `cannot copy ${src} to a subdirectory of self ${dest}`,
      path: dest,
      syscall: 'cp',
      errno: EINVAL,
    });
  }
  return { srcStat, destStat };
}
 
function areIdentical(srcStat, destStat) {
  return destStat.ino && destStat.dev && destStat.ino === srcStat.ino &&
    destStat.dev === srcStat.dev;
}
 
function getStats(src, dest, opts) {
  const statFunc = opts.dereference ?
    (file) => stat(file, { bigint: true }) :
    (file) => lstat(file, { bigint: true });
  return PromiseAll(new SafeArrayIterator([
    statFunc(src),
    PromisePrototypeCatch(statFunc(dest), (err) => {
      if (err.code === 'ENOENT') return null;
      throw err;
    }),
  ]));
}
 
async function checkParentDir(destStat, src, dest, opts) {
  const destParent = dirname(dest);
  const dirExists = await pathExists(destParent);
  if (dirExists) return getStatsForCopy(destStat, src, dest, opts);
  await mkdir(destParent, { recursive: true });
  return getStatsForCopy(destStat, src, dest, opts);
}
 
function pathExists(dest) {
  return PromisePrototypeThen(
    stat(dest),
    () => true,
    (err) => (err.code === 'ENOENT' ? false : PromiseReject(err)));
}
 
// Recursively check if dest parent is a subdirectory of src.
// It works for all file types including symlinks since it
// checks the src and dest inodes. It starts from the deepest
// parent and stops once it reaches the src parent or the root path.
async function checkParentPaths(src, srcStat, dest) {
  const srcParent = resolve(dirname(src));
  const destParent = resolve(dirname(dest));
  if (destParent === srcParent || destParent === parse(destParent).root) {
    return;
  }
  let destStat;
  try {
    destStat = await stat(destParent, { bigint: true });
  } catch (err) {
    if (err.code === 'ENOENT') return;
    throw err;
  }
  if (areIdentical(srcStat, destStat)) {
    throw new ERR_FS_CP_EINVAL({
      message: `cannot copy ${src} to a subdirectory of self ${dest}`,
      path: dest,
      syscall: 'cp',
      errno: EINVAL,
    });
  }
  return checkParentPaths(src, srcStat, destParent);
}
 
const normalizePathToArray = (path) =>
  ArrayPrototypeFilter(StringPrototypeSplit(resolve(path), sep), Boolean);
 
// Return true if dest is a subdir of src, otherwise false.
// It only checks the path strings.
function isSrcSubdir(src, dest) {
  const srcArr = normalizePathToArray(src);
  const destArr = normalizePathToArray(dest);
  return ArrayPrototypeEvery(srcArr, (cur, i) => destArr[i] === cur);
}
 
async function handleFilter(onInclude, destStat, src, dest, opts, cb) {
  const include = await opts.filter(src, dest);
  if (include) return onInclude(destStat, src, dest, opts, cb);
}
 
function startCopy(destStat, src, dest, opts) {
  if (opts.filter) {
    return handleFilter(getStatsForCopy, destStat, src, dest, opts);
  }
  return getStatsForCopy(destStat, src, dest, opts);
}
 
async function getStatsForCopy(destStat, src, dest, opts) {
  const statFn = opts.dereference ? stat : lstat;
  const srcStat = await statFn(src);
  if (srcStat.isDirectory() && opts.recursive) {
    return onDir(srcStat, destStat, src, dest, opts);
  } else if (srcStat.isDirectory()) {
    throw new ERR_FS_EISDIR({
      message: `${src} is a directory (not copied)`,
      path: src,
      syscall: 'cp',
      errno: EINVAL,
    });
  } else if (srcStat.isFile() ||
            srcStat.isCharacterDevice() ||
            srcStat.isBlockDevice()) {
    return onFile(srcStat, destStat, src, dest, opts);
  } else if (srcStat.isSymbolicLink()) {
    return onLink(destStat, src, dest);
  } else if (srcStat.isSocket()) {
    throw new ERR_FS_CP_SOCKET({
      message: `cannot copy a socket file: ${dest}`,
      path: dest,
      syscall: 'cp',
      errno: EINVAL,
    });
  } else if (srcStat.isFIFO()) {
    throw new ERR_FS_CP_FIFO_PIPE({
      message: `cannot copy a FIFO pipe: ${dest}`,
      path: dest,
      syscall: 'cp',
      errno: EINVAL,
    });
  }
  throw new ERR_FS_CP_UNKNOWN({
    message: `cannot copy an unknown file type: ${dest}`,
    path: dest,
    syscall: 'cp',
    errno: EINVAL,
  });
}
 
function onFile(srcStat, destStat, src, dest, opts) {
  if (!destStat) return _copyFile(srcStat, src, dest, opts);
  return mayCopyFile(srcStat, src, dest, opts);
}
 
async function mayCopyFile(srcStat, src, dest, opts) {
  if (opts.force) {
    await unlink(dest);
    return _copyFile(srcStat, src, dest, opts);
  } else if (opts.errorOnExist) {
    throw new ERR_FS_CP_EEXIST({
      message: `${dest} already exists`,
      path: dest,
      syscall: 'cp',
      errno: EEXIST,
    });
  }
}
 
async function _copyFile(srcStat, src, dest, opts) {
  await copyFile(src, dest);
  if (opts.preserveTimestamps) {
    return handleTimestampsAndMode(srcStat.mode, src, dest);
  }
  return setDestMode(dest, srcStat.mode);
}
 
async function handleTimestampsAndMode(srcMode, src, dest) {
  // Make sure the file is writable before setting the timestamp
  // otherwise open fails with EPERM when invoked with 'r+'
  // (through utimes call)
  if (fileIsNotWritable(srcMode)) {
    await makeFileWritable(dest, srcMode);
    return setDestTimestampsAndMode(srcMode, src, dest);
  }
  return setDestTimestampsAndMode(srcMode, src, dest);
}
 
function fileIsNotWritable(srcMode) {
  return (srcMode & 0o200) === 0;
}
 
function makeFileWritable(dest, srcMode) {
  return setDestMode(dest, srcMode | 0o200);
}
 
async function setDestTimestampsAndMode(srcMode, src, dest) {
  await setDestTimestamps(src, dest);
  return setDestMode(dest, srcMode);
}
 
function setDestMode(dest, srcMode) {
  return chmod(dest, srcMode);
}
 
async function setDestTimestamps(src, dest) {
  // The initial srcStat.atime cannot be trusted
  // because it is modified by the read(2) system call
  // (See https://nodejs.org/api/fs.html#fs_stat_time_values)
  const updatedSrcStat = await stat(src);
  return utimes(dest, updatedSrcStat.atime, updatedSrcStat.mtime);
}
 
function onDir(srcStat, destStat, src, dest, opts) {
  if (!destStat) return mkDirAndCopy(srcStat.mode, src, dest, opts);
  return copyDir(src, dest, opts);
}
 
async function mkDirAndCopy(srcMode, src, dest, opts) {
  await mkdir(dest);
  await copyDir(src, dest, opts);
  return setDestMode(dest, srcMode);
}
 
async function copyDir(src, dest, opts) {
  const dir = await readdir(src);
  for (let i = 0; i < dir.length; i++) {
    const item = dir[i];
    const srcItem = join(src, item);
    const destItem = join(dest, item);
    const { destStat } = await checkPaths(srcItem, destItem, opts);
    await startCopy(destStat, srcItem, destItem, opts);
  }
}
 
async function onLink(destStat, src, dest) {
  let resolvedSrc = await readlink(src);
  if (!isAbsolute(resolvedSrc)) {
    resolvedSrc = resolve(dirname(src), resolvedSrc);
  }
  if (!destStat) {
    return symlink(resolvedSrc, dest);
  }
  let resolvedDest;
  try {
    resolvedDest = await readlink(dest);
  } catch (err) {
    // Dest exists and is a regular file or directory,
    // Windows may throw UNKNOWN error. If dest already exists,
    // fs throws error anyway, so no need to guard against it here.
    if (err.code === 'EINVAL' || err.code === 'UNKNOWN') {
      return symlink(resolvedSrc, dest);
    }
    throw err;
  }
  if (!isAbsolute(resolvedDest)) {
    resolvedDest = resolve(dirname(dest), resolvedDest);
  }
  if (isSrcSubdir(resolvedSrc, resolvedDest)) {
    throw new ERR_FS_CP_EINVAL({
      message: `cannot copy ${resolvedSrc} to a subdirectory of self ` +
            `${resolvedDest}`,
      path: dest,
      syscall: 'cp',
      errno: EINVAL,
    });
  }
  // Do not copy if src is a subdir of dest since unlinking
  // dest in this case would result in removing src contents
  // and therefore a broken symlink would be created.
  const srcStat = await stat(src);
  if (srcStat.isDirectory() && isSrcSubdir(resolvedDest, resolvedSrc)) {
    throw new ERR_FS_CP_SYMLINK_TO_SUBDIRECTORY({
      message: `cannot overwrite ${resolvedDest} with ${resolvedSrc}`,
      path: dest,
      syscall: 'cp',
      errno: EINVAL,
    });
  }
  return copyLink(resolvedSrc, dest);
}
 
async function copyLink(resolvedSrc, dest) {
  await unlink(dest);
  return symlink(resolvedSrc, dest);
}
 
module.exports = {
  areIdentical,
  cpFn,
  isSrcSubdir,
};