| 1 | 'use strict'
|
|---|
| 2 |
|
|---|
| 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 | const stat = require('../util/stat')
|
|---|
| 10 |
|
|---|
| 11 | function move (src, dest, opts, cb) {
|
|---|
| 12 | if (typeof opts === 'function') {
|
|---|
| 13 | cb = opts
|
|---|
| 14 | opts = {}
|
|---|
| 15 | }
|
|---|
| 16 |
|
|---|
| 17 | opts = opts || {}
|
|---|
| 18 |
|
|---|
| 19 | const overwrite = opts.overwrite || opts.clobber || false
|
|---|
| 20 |
|
|---|
| 21 | stat.checkPaths(src, dest, 'move', opts, (err, stats) => {
|
|---|
| 22 | if (err) return cb(err)
|
|---|
| 23 | const { srcStat, isChangingCase = false } = stats
|
|---|
| 24 | stat.checkParentPaths(src, srcStat, dest, 'move', err => {
|
|---|
| 25 | if (err) return cb(err)
|
|---|
| 26 | if (isParentRoot(dest)) return doRename(src, dest, overwrite, isChangingCase, cb)
|
|---|
| 27 | mkdirp(path.dirname(dest), err => {
|
|---|
| 28 | if (err) return cb(err)
|
|---|
| 29 | return doRename(src, dest, overwrite, isChangingCase, cb)
|
|---|
| 30 | })
|
|---|
| 31 | })
|
|---|
| 32 | })
|
|---|
| 33 | }
|
|---|
| 34 |
|
|---|
| 35 | function isParentRoot (dest) {
|
|---|
| 36 | const parent = path.dirname(dest)
|
|---|
| 37 | const parsedPath = path.parse(parent)
|
|---|
| 38 | return parsedPath.root === parent
|
|---|
| 39 | }
|
|---|
| 40 |
|
|---|
| 41 | function doRename (src, dest, overwrite, isChangingCase, cb) {
|
|---|
| 42 | if (isChangingCase) return rename(src, dest, overwrite, cb)
|
|---|
| 43 | if (overwrite) {
|
|---|
| 44 | return remove(dest, err => {
|
|---|
| 45 | if (err) return cb(err)
|
|---|
| 46 | return rename(src, dest, overwrite, cb)
|
|---|
| 47 | })
|
|---|
| 48 | }
|
|---|
| 49 | pathExists(dest, (err, destExists) => {
|
|---|
| 50 | if (err) return cb(err)
|
|---|
| 51 | if (destExists) return cb(new Error('dest already exists.'))
|
|---|
| 52 | return rename(src, dest, overwrite, cb)
|
|---|
| 53 | })
|
|---|
| 54 | }
|
|---|
| 55 |
|
|---|
| 56 | function rename (src, dest, overwrite, cb) {
|
|---|
| 57 | fs.rename(src, dest, err => {
|
|---|
| 58 | if (!err) return cb()
|
|---|
| 59 | if (err.code !== 'EXDEV') return cb(err)
|
|---|
| 60 | return moveAcrossDevice(src, dest, overwrite, cb)
|
|---|
| 61 | })
|
|---|
| 62 | }
|
|---|
| 63 |
|
|---|
| 64 | function moveAcrossDevice (src, dest, overwrite, cb) {
|
|---|
| 65 | const opts = {
|
|---|
| 66 | overwrite,
|
|---|
| 67 | errorOnExist: true
|
|---|
| 68 | }
|
|---|
| 69 | copy(src, dest, opts, err => {
|
|---|
| 70 | if (err) return cb(err)
|
|---|
| 71 | return remove(src, cb)
|
|---|
| 72 | })
|
|---|
| 73 | }
|
|---|
| 74 |
|
|---|
| 75 | module.exports = move
|
|---|