You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

82 lines
1.9 KiB

4 years ago
  1. 'use strict'
  2. const u = require('universalify').fromCallback
  3. const fs = require('graceful-fs')
  4. const path = require('path')
  5. const copy = require('../copy').copy
  6. const remove = require('../remove').remove
  7. const mkdirp = require('../mkdirs').mkdirp
  8. const pathExists = require('../path-exists').pathExists
  9. function move (src, dest, opts, cb) {
  10. if (typeof opts === 'function') {
  11. cb = opts
  12. opts = {}
  13. }
  14. const overwrite = opts.overwrite || opts.clobber || false
  15. src = path.resolve(src)
  16. dest = path.resolve(dest)
  17. if (src === dest) return fs.access(src, cb)
  18. fs.stat(src, (err, st) => {
  19. if (err) return cb(err)
  20. if (st.isDirectory() && isSrcSubdir(src, dest)) {
  21. return cb(new Error(`Cannot move '${src}' to a subdirectory of itself, '${dest}'.`))
  22. }
  23. mkdirp(path.dirname(dest), err => {
  24. if (err) return cb(err)
  25. return doRename(src, dest, overwrite, cb)
  26. })
  27. })
  28. }
  29. function doRename (src, dest, overwrite, cb) {
  30. if (overwrite) {
  31. return remove(dest, err => {
  32. if (err) return cb(err)
  33. return rename(src, dest, overwrite, cb)
  34. })
  35. }
  36. pathExists(dest, (err, destExists) => {
  37. if (err) return cb(err)
  38. if (destExists) return cb(new Error('dest already exists.'))
  39. return rename(src, dest, overwrite, cb)
  40. })
  41. }
  42. function rename (src, dest, overwrite, cb) {
  43. fs.rename(src, dest, err => {
  44. if (!err) return cb()
  45. if (err.code !== 'EXDEV') return cb(err)
  46. return moveAcrossDevice(src, dest, overwrite, cb)
  47. })
  48. }
  49. function moveAcrossDevice (src, dest, overwrite, cb) {
  50. const opts = {
  51. overwrite,
  52. errorOnExist: true
  53. }
  54. copy(src, dest, opts, err => {
  55. if (err) return cb(err)
  56. return remove(src, cb)
  57. })
  58. }
  59. function isSrcSubdir (src, dest) {
  60. const srcArray = src.split(path.sep)
  61. const destArray = dest.split(path.sep)
  62. return srcArray.reduce((acc, current, i) => {
  63. return acc && destArray[i] === current
  64. }, true)
  65. }
  66. module.exports = {
  67. move: u(move)
  68. }