copy.js 5.5 KB

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