1 | var fs = require('fs');
|
2 | var path = require('path');
|
3 | var common = require('./common');
|
4 | var cp = require('./cp');
|
5 | var rm = require('./rm');
|
6 |
|
7 | common.register('mv', _mv, {
|
8 | cmdOptions: {
|
9 | 'f': '!no_force',
|
10 | 'n': 'no_force',
|
11 | },
|
12 | });
|
13 |
|
14 |
|
15 | function checkRecentCreated(sources, index) {
|
16 | var lookedSource = sources[index];
|
17 | return sources.slice(0, index).some(function (src) {
|
18 | return path.basename(src) === path.basename(lookedSource);
|
19 | });
|
20 | }
|
21 |
|
22 |
|
23 |
|
24 |
|
25 |
|
26 |
|
27 |
|
28 |
|
29 |
|
30 |
|
31 |
|
32 |
|
33 |
|
34 |
|
35 |
|
36 |
|
37 |
|
38 |
|
39 | function _mv(options, sources, dest) {
|
40 |
|
41 | if (arguments.length < 3) {
|
42 | common.error('missing <source> and/or <dest>');
|
43 | } else if (arguments.length > 3) {
|
44 | sources = [].slice.call(arguments, 1, arguments.length - 1);
|
45 | dest = arguments[arguments.length - 1];
|
46 | } else if (typeof sources === 'string') {
|
47 | sources = [sources];
|
48 | } else {
|
49 |
|
50 | common.error('invalid arguments');
|
51 | }
|
52 |
|
53 | var exists = fs.existsSync(dest);
|
54 | var stats = exists && common.statFollowLinks(dest);
|
55 |
|
56 |
|
57 | if ((!exists || !stats.isDirectory()) && sources.length > 1) {
|
58 | common.error('dest is not a directory (too many sources)');
|
59 | }
|
60 |
|
61 |
|
62 | if (exists && stats.isFile() && options.no_force) {
|
63 | common.error('dest file already exists: ' + dest);
|
64 | }
|
65 |
|
66 | sources.forEach(function (src, srcIndex) {
|
67 | if (!fs.existsSync(src)) {
|
68 | common.error('no such file or directory: ' + src, { continue: true });
|
69 | return;
|
70 | }
|
71 |
|
72 |
|
73 |
|
74 |
|
75 |
|
76 | var thisDest = dest;
|
77 | if (fs.existsSync(dest) && common.statFollowLinks(dest).isDirectory()) {
|
78 | thisDest = path.normalize(dest + '/' + path.basename(src));
|
79 | }
|
80 |
|
81 | var thisDestExists = fs.existsSync(thisDest);
|
82 |
|
83 | if (thisDestExists && checkRecentCreated(sources, srcIndex)) {
|
84 |
|
85 | if (!options.no_force) {
|
86 | common.error("will not overwrite just-created '" + thisDest + "' with '" + src + "'", { continue: true });
|
87 | }
|
88 | return;
|
89 | }
|
90 |
|
91 | if (fs.existsSync(thisDest) && options.no_force) {
|
92 | common.error('dest file already exists: ' + thisDest, { continue: true });
|
93 | return;
|
94 | }
|
95 |
|
96 | if (path.resolve(src) === path.dirname(path.resolve(thisDest))) {
|
97 | common.error('cannot move to self: ' + src, { continue: true });
|
98 | return;
|
99 | }
|
100 |
|
101 | try {
|
102 | fs.renameSync(src, thisDest);
|
103 | } catch (e) {
|
104 |
|
105 | if (e.code === 'EXDEV') {
|
106 |
|
107 |
|
108 |
|
109 |
|
110 | cp('-r', src, thisDest);
|
111 | rm('-rf', src);
|
112 | }
|
113 | }
|
114 | });
|
115 | return '';
|
116 | }
|
117 | module.exports = _mv;
|