copy.js 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. 'use strict'
  2. const fs = require('../fs')
  3. const path = require('path')
  4. const { mkdirs } = require('../mkdirs')
  5. const { pathExists } = require('../path-exists')
  6. const { utimesMillis } = require('../util/utimes')
  7. const stat = require('../util/stat')
  8. const { asyncIteratorConcurrentProcess } = require('../util/async')
  9. async function copy (src, dest, opts = {}) {
  10. if (typeof opts === 'function') {
  11. opts = { filter: opts }
  12. }
  13. opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
  14. opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
  15. // Warn about using preserveTimestamps on 32-bit node
  16. if (opts.preserveTimestamps && process.arch === 'ia32') {
  17. process.emitWarning(
  18. 'Using the preserveTimestamps option in 32-bit node is not recommended;\n\n' +
  19. '\tsee https://github.com/jprichardson/node-fs-extra/issues/269',
  20. 'Warning', 'fs-extra-WARN0001'
  21. )
  22. }
  23. const { srcStat, destStat } = await stat.checkPaths(src, dest, 'copy', opts)
  24. await stat.checkParentPaths(src, srcStat, dest, 'copy')
  25. const include = await runFilter(src, dest, opts)
  26. if (!include) return
  27. // check if the parent of dest exists, and create it if it doesn't exist
  28. const destParent = path.dirname(dest)
  29. const dirExists = await pathExists(destParent)
  30. if (!dirExists) {
  31. await mkdirs(destParent)
  32. }
  33. await getStatsAndPerformCopy(destStat, src, dest, opts)
  34. }
  35. async function runFilter (src, dest, opts) {
  36. if (!opts.filter) return true
  37. return opts.filter(src, dest)
  38. }
  39. async function getStatsAndPerformCopy (destStat, src, dest, opts) {
  40. const statFn = opts.dereference ? fs.stat : fs.lstat
  41. const srcStat = await statFn(src)
  42. if (srcStat.isDirectory()) return onDir(srcStat, destStat, src, dest, opts)
  43. if (
  44. srcStat.isFile() ||
  45. srcStat.isCharacterDevice() ||
  46. srcStat.isBlockDevice()
  47. ) return onFile(srcStat, destStat, src, dest, opts)
  48. if (srcStat.isSymbolicLink()) return onLink(destStat, src, dest, opts)
  49. if (srcStat.isSocket()) throw new Error(`Cannot copy a socket file: ${src}`)
  50. if (srcStat.isFIFO()) throw new Error(`Cannot copy a FIFO pipe: ${src}`)
  51. throw new Error(`Unknown file: ${src}`)
  52. }
  53. async function onFile (srcStat, destStat, src, dest, opts) {
  54. if (!destStat) return copyFile(srcStat, src, dest, opts)
  55. if (opts.overwrite) {
  56. await fs.unlink(dest)
  57. return copyFile(srcStat, src, dest, opts)
  58. }
  59. if (opts.errorOnExist) {
  60. throw new Error(`'${dest}' already exists`)
  61. }
  62. }
  63. async function copyFile (srcStat, src, dest, opts) {
  64. await fs.copyFile(src, dest)
  65. if (opts.preserveTimestamps) {
  66. // Make sure the file is writable before setting the timestamp
  67. // otherwise open fails with EPERM when invoked with 'r+'
  68. // (through utimes call)
  69. if (fileIsNotWritable(srcStat.mode)) {
  70. await makeFileWritable(dest, srcStat.mode)
  71. }
  72. // Set timestamps and mode correspondingly
  73. // Note that The initial srcStat.atime cannot be trusted
  74. // because it is modified by the read(2) system call
  75. // (See https://nodejs.org/api/fs.html#fs_stat_time_values)
  76. const updatedSrcStat = await fs.stat(src)
  77. await utimesMillis(dest, updatedSrcStat.atime, updatedSrcStat.mtime)
  78. }
  79. return fs.chmod(dest, srcStat.mode)
  80. }
  81. function fileIsNotWritable (srcMode) {
  82. return (srcMode & 0o200) === 0
  83. }
  84. function makeFileWritable (dest, srcMode) {
  85. return fs.chmod(dest, srcMode | 0o200)
  86. }
  87. async function onDir (srcStat, destStat, src, dest, opts) {
  88. // the dest directory might not exist, create it
  89. if (!destStat) {
  90. await fs.mkdir(dest)
  91. }
  92. // iterate through the files in the current directory to copy everything
  93. await asyncIteratorConcurrentProcess(await fs.opendir(src), async (item) => {
  94. const srcItem = path.join(src, item.name)
  95. const destItem = path.join(dest, item.name)
  96. const include = await runFilter(srcItem, destItem, opts)
  97. // only copy the item if it matches the filter function
  98. if (include) {
  99. const { destStat } = await stat.checkPaths(srcItem, destItem, 'copy', opts)
  100. // If the item is a copyable file, `getStatsAndPerformCopy` will copy it
  101. // If the item is a directory, `getStatsAndPerformCopy` will call `onDir` recursively
  102. await getStatsAndPerformCopy(destStat, srcItem, destItem, opts)
  103. }
  104. })
  105. if (!destStat) {
  106. await fs.chmod(dest, srcStat.mode)
  107. }
  108. }
  109. async function onLink (destStat, src, dest, opts) {
  110. let resolvedSrc = await fs.readlink(src)
  111. if (opts.dereference) {
  112. resolvedSrc = path.resolve(process.cwd(), resolvedSrc)
  113. }
  114. if (!destStat) {
  115. return fs.symlink(resolvedSrc, dest)
  116. }
  117. let resolvedDest = null
  118. try {
  119. resolvedDest = await fs.readlink(dest)
  120. } catch (e) {
  121. // dest exists and is a regular file or directory,
  122. // Windows may throw UNKNOWN error. If dest already exists,
  123. // fs throws error anyway, so no need to guard against it here.
  124. if (e.code === 'EINVAL' || e.code === 'UNKNOWN') return fs.symlink(resolvedSrc, dest)
  125. throw e
  126. }
  127. if (opts.dereference) {
  128. resolvedDest = path.resolve(process.cwd(), resolvedDest)
  129. }
  130. if (stat.isSrcSubdir(resolvedSrc, resolvedDest)) {
  131. throw new Error(`Cannot copy '${resolvedSrc}' to a subdirectory of itself, '${resolvedDest}'.`)
  132. }
  133. // do not copy if src is a subdir of dest since unlinking
  134. // dest in this case would result in removing src contents
  135. // and therefore a broken symlink would be created.
  136. if (stat.isSrcSubdir(resolvedDest, resolvedSrc)) {
  137. throw new Error(`Cannot overwrite '${resolvedDest}' with '${resolvedSrc}'.`)
  138. }
  139. // copy the link
  140. await fs.unlink(dest)
  141. return fs.symlink(resolvedSrc, dest)
  142. }
  143. module.exports = copy