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 |
|
40 | function _mv(options, sources, dest) {
|
41 |
|
42 | if (arguments.length < 3) {
|
43 | common.error('missing <source> and/or <dest>');
|
44 | } else if (arguments.length > 3) {
|
45 | sources = [].slice.call(arguments, 1, arguments.length - 1);
|
46 | dest = arguments[arguments.length - 1];
|
47 | } else if (typeof sources === 'string') {
|
48 | sources = [sources];
|
49 | } else {
|
50 |
|
51 | common.error('invalid arguments');
|
52 | }
|
53 |
|
54 | var exists = fs.existsSync(dest);
|
55 | var stats = exists && common.statFollowLinks(dest);
|
56 |
|
57 |
|
58 | if ((!exists || !stats.isDirectory()) && sources.length > 1) {
|
59 | common.error('dest is not a directory (too many sources)');
|
60 | }
|
61 |
|
62 |
|
63 | if (exists && stats.isFile() && options.no_force) {
|
64 | common.error('dest file already exists: ' + dest);
|
65 | }
|
66 |
|
67 | sources.forEach(function (src, srcIndex) {
|
68 | if (!fs.existsSync(src)) {
|
69 | common.error('no such file or directory: ' + src, { continue: true });
|
70 | return;
|
71 | }
|
72 |
|
73 |
|
74 |
|
75 |
|
76 |
|
77 | var thisDest = dest;
|
78 | if (fs.existsSync(dest) && common.statFollowLinks(dest).isDirectory()) {
|
79 | thisDest = path.normalize(dest + '/' + path.basename(src));
|
80 | }
|
81 |
|
82 | var thisDestExists = fs.existsSync(thisDest);
|
83 |
|
84 | if (thisDestExists && checkRecentCreated(sources, srcIndex)) {
|
85 |
|
86 | if (!options.no_force) {
|
87 | common.error("will not overwrite just-created '" + thisDest + "' with '" + src + "'", { continue: true });
|
88 | }
|
89 | return;
|
90 | }
|
91 |
|
92 | if (fs.existsSync(thisDest) && options.no_force) {
|
93 | common.error('dest file already exists: ' + thisDest, { continue: true });
|
94 | return;
|
95 | }
|
96 |
|
97 | if (path.resolve(src) === path.dirname(path.resolve(thisDest))) {
|
98 | common.error('cannot move to self: ' + src, { continue: true });
|
99 | return;
|
100 | }
|
101 |
|
102 | try {
|
103 | fs.renameSync(src, thisDest);
|
104 | } catch (e) {
|
105 |
|
106 | if (e.code === 'EXDEV') {
|
107 |
|
108 |
|
109 |
|
110 |
|
111 | cp('-r', src, thisDest);
|
112 | rm('-rf', src);
|
113 | }
|
114 | }
|
115 | });
|
116 | return '';
|
117 | }
|
118 | module.exports = _mv;
|