copy-sync.js 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209
  1. 'use strict'
  2. const fs = require('graceful-fs')
  3. const path = require('path')
  4. const mkdirpSync = require('../mkdirs').mkdirsSync
  5. const utimesSync = require('../util/utimes.js').utimesMillisSync
  6. const notExist = Symbol('notExist')
  7. const existsReg = Symbol('existsReg')
  8. function copySync (src, dest, opts) {
  9. if (typeof opts === 'function') {
  10. opts = {filter: opts}
  11. }
  12. opts = opts || {}
  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. console.warn(`fs-extra: Using the preserveTimestamps option in 32-bit node is not recommended;\n
  18. see https://github.com/jprichardson/node-fs-extra/issues/269`)
  19. }
  20. src = path.resolve(src)
  21. dest = path.resolve(dest)
  22. // don't allow src and dest to be the same
  23. if (src === dest) throw new Error('Source and destination must not be the same.')
  24. if (opts.filter && !opts.filter(src, dest)) return
  25. const destParent = path.dirname(dest)
  26. if (!fs.existsSync(destParent)) mkdirpSync(destParent)
  27. return startCopy(src, dest, opts)
  28. }
  29. function startCopy (src, dest, opts) {
  30. if (opts.filter && !opts.filter(src, dest)) return
  31. return getStats(src, dest, opts)
  32. }
  33. function getStats (src, dest, opts) {
  34. const statSync = opts.dereference ? fs.statSync : fs.lstatSync
  35. const st = statSync(src)
  36. if (st.isDirectory()) return onDir(st, src, dest, opts)
  37. else if (st.isFile() ||
  38. st.isCharacterDevice() ||
  39. st.isBlockDevice()) return onFile(st, src, dest, opts)
  40. else if (st.isSymbolicLink()) return onLink(src, dest, opts)
  41. }
  42. function onFile (srcStat, src, dest, opts) {
  43. const resolvedPath = checkDest(dest)
  44. if (resolvedPath === notExist) {
  45. return copyFile(srcStat, src, dest, opts)
  46. } else if (resolvedPath === existsReg) {
  47. return mayCopyFile(srcStat, src, dest, opts)
  48. } else {
  49. if (src === resolvedPath) return
  50. return mayCopyFile(srcStat, src, dest, opts)
  51. }
  52. }
  53. function mayCopyFile (srcStat, src, dest, opts) {
  54. if (opts.overwrite) {
  55. fs.unlinkSync(dest)
  56. return copyFile(srcStat, src, dest, opts)
  57. } else if (opts.errorOnExist) {
  58. throw new Error(`'${dest}' already exists`)
  59. }
  60. }
  61. function copyFile (srcStat, src, dest, opts) {
  62. if (typeof fs.copyFileSync === 'function') {
  63. fs.copyFileSync(src, dest)
  64. fs.chmodSync(dest, srcStat.mode)
  65. if (opts.preserveTimestamps) {
  66. return utimesSync(dest, srcStat.atime, srcStat.mtime)
  67. }
  68. return
  69. }
  70. return copyFileFallback(srcStat, src, dest, opts)
  71. }
  72. function copyFileFallback (srcStat, src, dest, opts) {
  73. const BUF_LENGTH = 64 * 1024
  74. const _buff = require('../util/buffer')(BUF_LENGTH)
  75. const fdr = fs.openSync(src, 'r')
  76. const fdw = fs.openSync(dest, 'w', srcStat.mode)
  77. let bytesRead = 1
  78. let pos = 0
  79. while (bytesRead > 0) {
  80. bytesRead = fs.readSync(fdr, _buff, 0, BUF_LENGTH, pos)
  81. fs.writeSync(fdw, _buff, 0, bytesRead)
  82. pos += bytesRead
  83. }
  84. if (opts.preserveTimestamps) fs.futimesSync(fdw, srcStat.atime, srcStat.mtime)
  85. fs.closeSync(fdr)
  86. fs.closeSync(fdw)
  87. }
  88. function onDir (srcStat, src, dest, opts) {
  89. const resolvedPath = checkDest(dest)
  90. if (resolvedPath === notExist) {
  91. if (isSrcSubdir(src, dest)) {
  92. throw new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`)
  93. }
  94. return mkDirAndCopy(srcStat, src, dest, opts)
  95. } else if (resolvedPath === existsReg) {
  96. if (isSrcSubdir(src, dest)) {
  97. throw new Error(`Cannot copy '${src}' to a subdirectory of itself, '${dest}'.`)
  98. }
  99. return mayCopyDir(src, dest, opts)
  100. } else {
  101. if (src === resolvedPath) return
  102. return copyDir(src, dest, opts)
  103. }
  104. }
  105. function mayCopyDir (src, dest, opts) {
  106. if (!fs.statSync(dest).isDirectory()) {
  107. throw new Error(`Cannot overwrite non-directory '${dest}' with directory '${src}'.`)
  108. }
  109. return copyDir(src, dest, opts)
  110. }
  111. function mkDirAndCopy (srcStat, src, dest, opts) {
  112. fs.mkdirSync(dest, srcStat.mode)
  113. fs.chmodSync(dest, srcStat.mode)
  114. return copyDir(src, dest, opts)
  115. }
  116. function copyDir (src, dest, opts) {
  117. fs.readdirSync(src).forEach(item => {
  118. startCopy(path.join(src, item), path.join(dest, item), opts)
  119. })
  120. }
  121. function onLink (src, dest, opts) {
  122. let resolvedSrcPath = fs.readlinkSync(src)
  123. if (opts.dereference) {
  124. resolvedSrcPath = path.resolve(process.cwd(), resolvedSrcPath)
  125. }
  126. let resolvedDestPath = checkDest(dest)
  127. if (resolvedDestPath === notExist || resolvedDestPath === existsReg) {
  128. // if dest already exists, fs throws error anyway,
  129. // so no need to guard against it here.
  130. return fs.symlinkSync(resolvedSrcPath, dest)
  131. } else {
  132. if (opts.dereference) {
  133. resolvedDestPath = path.resolve(process.cwd(), resolvedDestPath)
  134. }
  135. if (resolvedDestPath === resolvedSrcPath) return
  136. // prevent copy if src is a subdir of dest since unlinking
  137. // dest in this case would result in removing src contents
  138. // and therefore a broken symlink would be created.
  139. if (fs.statSync(dest).isDirectory() && isSrcSubdir(resolvedDestPath, resolvedSrcPath)) {
  140. throw new Error(`Cannot overwrite '${resolvedDestPath}' with '${resolvedSrcPath}'.`)
  141. }
  142. return copyLink(resolvedSrcPath, dest)
  143. }
  144. }
  145. function copyLink (resolvedSrcPath, dest) {
  146. fs.unlinkSync(dest)
  147. return fs.symlinkSync(resolvedSrcPath, dest)
  148. }
  149. // check if dest exists and/or is a symlink
  150. function checkDest (dest) {
  151. let resolvedPath
  152. try {
  153. resolvedPath = fs.readlinkSync(dest)
  154. } catch (err) {
  155. if (err.code === 'ENOENT') return notExist
  156. // dest exists and is a regular file or directory, Windows may throw UNKNOWN error
  157. if (err.code === 'EINVAL' || err.code === 'UNKNOWN') return existsReg
  158. throw err
  159. }
  160. return resolvedPath // dest exists and is a symlink
  161. }
  162. // return true if dest is a subdir of src, otherwise false.
  163. // extract dest base dir and check if that is the same as src basename
  164. function isSrcSubdir (src, dest) {
  165. const baseDir = dest.split(path.dirname(src) + path.sep)[1]
  166. if (baseDir) {
  167. const destBasename = baseDir.split(path.sep)[0]
  168. if (destBasename) {
  169. return src !== dest && dest.indexOf(src) > -1 && destBasename === path.basename(src)
  170. }
  171. return false
  172. }
  173. return false
  174. }
  175. module.exports = copySync