1 | 'use strict'
|
---|
2 |
|
---|
3 | const fs = require('graceful-fs')
|
---|
4 | const path = require('path')
|
---|
5 | const copySync = require('../copy-sync').copySync
|
---|
6 | const removeSync = require('../remove').removeSync
|
---|
7 | const mkdirpSync = require('../mkdirs').mkdirpSync
|
---|
8 | const stat = require('../util/stat')
|
---|
9 |
|
---|
10 | function moveSync (src, dest, opts) {
|
---|
11 | opts = opts || {}
|
---|
12 | const overwrite = opts.overwrite || opts.clobber || false
|
---|
13 |
|
---|
14 | const { srcStat } = stat.checkPathsSync(src, dest, 'move')
|
---|
15 | stat.checkParentPathsSync(src, srcStat, dest, 'move')
|
---|
16 | mkdirpSync(path.dirname(dest))
|
---|
17 | return doRename(src, dest, overwrite)
|
---|
18 | }
|
---|
19 |
|
---|
20 | function doRename (src, dest, overwrite) {
|
---|
21 | if (overwrite) {
|
---|
22 | removeSync(dest)
|
---|
23 | return rename(src, dest, overwrite)
|
---|
24 | }
|
---|
25 | if (fs.existsSync(dest)) throw new Error('dest already exists.')
|
---|
26 | return rename(src, dest, overwrite)
|
---|
27 | }
|
---|
28 |
|
---|
29 | function rename (src, dest, overwrite) {
|
---|
30 | try {
|
---|
31 | fs.renameSync(src, dest)
|
---|
32 | } catch (err) {
|
---|
33 | if (err.code !== 'EXDEV') throw err
|
---|
34 | return moveAcrossDevice(src, dest, overwrite)
|
---|
35 | }
|
---|
36 | }
|
---|
37 |
|
---|
38 | function moveAcrossDevice (src, dest, overwrite) {
|
---|
39 | const opts = {
|
---|
40 | overwrite,
|
---|
41 | errorOnExist: true
|
---|
42 | }
|
---|
43 | copySync(src, dest, opts)
|
---|
44 | return removeSync(src)
|
---|
45 | }
|
---|
46 |
|
---|
47 | module.exports = moveSync
|
---|