copy.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264
  1. 'use strict'
  2. const fs = require('graceful-fs')
  3. const path = require('path')
  4. const mkdirp = require('../mkdirs').mkdirs
  5. const pathExists = require('../path-exists').pathExists
  6. const utimes = require('../util/utimes').utimesMillis
  7. const notExist = Symbol('notExist')
  8. const existsReg = Symbol('existsReg')
  9. function copy (src, dest, opts, cb) {
  10. if (typeof opts === 'function' && !cb) {
  11. cb = opts
  12. opts = {}
  13. } else if (typeof opts === 'function') {
  14. opts = {filter: opts}
  15. }
  16. cb = cb || function () {}
  17. opts = opts || {}
  18. opts.clobber = 'clobber' in opts ? !!opts.clobber : true // default to true for now
  19. opts.overwrite = 'overwrite' in opts ? !!opts.overwrite : opts.clobber // overwrite falls back to clobber
  20. // Warn about using preserveTimestamps on 32-bit node
  21. if (opts.preserveTimestamps && process.arch === 'ia32') {
  22. console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
  23. see https://github.com/jprichardson/node-fs-extra/issues/269`)
  24. }
  25. src = path.resolve(src)
  26. dest = path.resolve(dest)
  27. // don't allow src and dest to be the same
  28. if (src === dest) return cb(new Error('Source and destination must not be the same.'))
  29. if (opts.filter) return handleFilter(checkParentDir, src, dest, opts, cb)
  30. return checkParentDir(src, dest, opts, cb)
  31. }
  32. function checkParentDir (src, dest, opts, cb) {
  33. const destParent = path.dirname(dest)
  34. pathExists(destParent, (err, dirExists) => {
  35. if (err) return cb(err)
  36. if (dirExists) return startCopy(src, dest, opts, cb)
  37. mkdirp(destParent, err => {
  38. if (err) return cb(err)
  39. return startCopy(src, dest, opts, cb)
  40. })
  41. })
  42. }
  43. function startCopy (src, dest, opts, cb) {
  44. if (opts.filter) return handleFilter(getStats, src, dest, opts, cb)
  45. return getStats(src, dest, opts, cb)
  46. }
  47. function handleFilter (onInclude, src, dest, opts, cb) {
  48. Promise.resolve(opts.filter(src, dest))
  49. .then(include => {
  50. if (include) return onInclude(src, dest, opts, cb)
  51. return cb()
  52. }, error => cb(error))
  53. }
  54. function getStats (src, dest, opts, cb) {
  55. const stat = opts.dereference ? fs.stat : fs.lstat
  56. stat(src, (err, st) => {
  57. if (err) return cb(err)
  58. if (st.isDirectory()) return onDir(st, src, dest, opts, cb)
  59. else if (st.isFile() ||
  60. st.isCharacterDevice() ||
  61. st.isBlockDevice()) return onFile(st, src, dest, opts, cb)
  62. else if (st.isSymbolicLink()) return onLink(src, dest, opts, cb)
  63. })
  64. }
  65. function onFile (srcStat, src, dest, opts, cb) {
  66. checkDest(dest, (err, resolvedPath) => {
  67. if (err) return cb(err)
  68. if (resolvedPath === notExist) {
  69. return copyFile(srcStat, src, dest, opts, cb)
  70. } else if (resolvedPath === existsReg) {
  71. return mayCopyFile(srcStat, src, dest, opts, cb)
  72. } else {
  73. if (src === resolvedPath) return cb()
  74. return mayCopyFile(srcStat, src, dest, opts, cb)
  75. }
  76. })
  77. }
  78. function mayCopyFile (srcStat, src, dest, opts, cb) {
  79. if (opts.overwrite) {
  80. fs.unlink(dest, err => {
  81. if (err) return cb(err)
  82. return copyFile(srcStat, src, dest, opts, cb)
  83. })
  84. } else if (opts.errorOnExist) {
  85. return cb(new Error(`'${dest}' already exists`))
  86. } else return cb()
  87. }
  88. function copyFile (srcStat, src, dest, opts, cb) {
  89. if (typeof fs.copyFile === 'function') {
  90. return fs.copyFile(src, dest, err => {
  91. if (err) return cb(err)
  92. return setDestModeAndTimestamps(srcStat, dest, opts, cb)
  93. })
  94. }
  95. return copyFileFallback(srcStat, src, dest, opts, cb)
  96. }
  97. function copyFileFallback (srcStat, src, dest, opts, cb) {
  98. const rs = fs.createReadStream(src)
  99. rs.on('error', err => cb(err))
  100. .once('open', () => {
  101. const ws = fs.createWriteStream(dest, { mode: srcStat.mode })
  102. ws.on('error', err => cb(err))
  103. .on('open', () => rs.pipe(ws))
  104. .once('close', () => setDestModeAndTimestamps(srcStat, dest, opts, cb))
  105. })
  106. }
  107. function setDestModeAndTimestamps (srcStat, dest, opts, cb) {
  108. fs.chmod(dest, srcStat.mode, err => {
  109. if (err) return cb(err)
  110. if (opts.preserveTimestamps) {
  111. return utimes(dest, srcStat.atime, srcStat.mtime, cb)
  112. }
  113. return cb()
  114. })
  115. }
  116. function onDir (srcStat, src, dest, opts, cb) {
  117. checkDest(dest, (err, resolvedPath) => {
  118. if (err) return cb(err)
  119. if (resolvedPath === notExist) {
  120. if (isSrcSubdir(src, dest)) {
  121. return cb(new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`))
  122. }
  123. return mkDirAndCopy(srcStat, src, dest, opts, cb)
  124. } else if (resolvedPath === existsReg) {
  125. if (isSrcSubdir(src, dest)) {
  126. return cb(new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`))
  127. }
  128. return mayCopyDir(src, dest, opts, cb)
  129. } else {
  130. if (src === resolvedPath) return cb()
  131. return copyDir(src, dest, opts, cb)
  132. }
  133. })
  134. }
  135. function mayCopyDir (src, dest, opts, cb) {
  136. fs.stat(dest, (err, st) => {
  137. if (err) return cb(err)
  138. if (!st.isDirectory()) {
  139. return cb(new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`))
  140. }
  141. return copyDir(src, dest, opts, cb)
  142. })
  143. }
  144. function mkDirAndCopy (srcStat, src, dest, opts, cb) {
  145. fs.mkdir(dest, srcStat.mode, err => {
  146. if (err) return cb(err)
  147. fs.chmod(dest, srcStat.mode, err => {
  148. if (err) return cb(err)
  149. return copyDir(src, dest, opts, cb)
  150. })
  151. })
  152. }
  153. function copyDir (src, dest, opts, cb) {
  154. fs.readdir(src, (err, items) => {
  155. if (err) return cb(err)
  156. return copyDirItems(items, src, dest, opts, cb)
  157. })
  158. }
  159. function copyDirItems (items, src, dest, opts, cb) {
  160. const item = items.pop()
  161. if (!item) return cb()
  162. startCopy(path.join(src, item), path.join(dest, item), opts, err => {
  163. if (err) return cb(err)
  164. return copyDirItems(items, src, dest, opts, cb)
  165. })
  166. }
  167. function onLink (src, dest, opts, cb) {
  168. fs.readlink(src, (err, resolvedSrcPath) => {
  169. if (err) return cb(err)
  170. if (opts.dereference) {
  171. resolvedSrcPath = path.resolve(process.cwd(), resolvedSrcPath)
  172. }
  173. checkDest(dest, (err, resolvedDestPath) => {
  174. if (err) return cb(err)
  175. if (resolvedDestPath === notExist || resolvedDestPath === existsReg) {
  176. // if dest already exists, fs throws error anyway,
  177. // so no need to guard against it here.
  178. return fs.symlink(resolvedSrcPath, dest, cb)
  179. } else {
  180. if (opts.dereference) {
  181. resolvedDestPath = path.resolve(process.cwd(), resolvedDestPath)
  182. }
  183. if (resolvedDestPath === resolvedSrcPath) return cb()
  184. // prevent copy if src is a subdir of dest since unlinking
  185. // dest in this case would result in removing src contents
  186. // and therefore a broken symlink would be created.
  187. fs.stat(dest, (err, st) => {
  188. if (err) return cb(err)
  189. if (st.isDirectory() && isSrcSubdir(resolvedDestPath, resolvedSrcPath)) {
  190. return cb(new Error(`Cannot overwrite '${resolvedDestPath}' with '${resolvedSrcPath}'.`))
  191. }
  192. return copyLink(resolvedSrcPath, dest, cb)
  193. })
  194. }
  195. })
  196. })
  197. }
  198. function copyLink (resolvedSrcPath, dest, cb) {
  199. fs.unlink(dest, err => {
  200. if (err) return cb(err)
  201. return fs.symlink(resolvedSrcPath, dest, cb)
  202. })
  203. }
  204. // check if dest exists and/or is a symlink
  205. function checkDest (dest, cb) {
  206. fs.readlink(dest, (err, resolvedPath) => {
  207. if (err) {
  208. if (err.code === 'ENOENT') return cb(null, notExist)
  209. // dest exists and is a regular file or directory, Windows may throw UNKNOWN error.
  210. if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return cb(null, existsReg)
  211. return cb(err)
  212. }
  213. return cb(null, resolvedPath) // dest exists and is a symlink
  214. })
  215. }
  216. // return true if dest is a subdir of src, otherwise false.
  217. // extract dest base dir and check if that is the same as src basename
  218. function isSrcSubdir (src, dest) {
  219. const baseDir = dest.split(path.dirname(src) + path.sep)[1]
  220. if (baseDir) {
  221. const destBasename = baseDir.split(path.sep)[0]
  222. if (destBasename) {
  223. return src !== dest && dest.indexOf(src) > -1 && destBasename === path.basename(src)
  224. }
  225. return false
  226. }
  227. return false
  228. }
  229. module.exports = copy