1
var fs = require('fs');
2
var path = require('path');
3
var common = require('./common');
6
//@ ### mv(source [, source ...], dest')
7
//@ ### mv(source_array, dest')
15
//@ mv('-f', 'file', 'dir/');
16
//@ mv('file1', 'file2', 'dir/');
17
//@ mv(['file1', 'file2'], 'dir/'); // same as above
20
//@ Moves files. The wildcard `*` is accepted.
21
function _mv(options, sources, dest) {
22
options = common.parseOptions(options, {
27
if (arguments.length < 3) {
28
common.error('missing <source> and/or <dest>');
29
} else if (arguments.length > 3) {
30
sources = [].slice.call(arguments, 1, arguments.length - 1);
31
dest = arguments[arguments.length - 1];
32
} else if (typeof sources === 'string') {
34
} else if ('length' in sources) {
35
sources = sources; // no-op for array
37
common.error('invalid arguments');
40
sources = common.expand(sources);
42
var exists = fs.existsSync(dest),
43
stats = exists && fs.statSync(dest);
45
// Dest is not existing dir, but multiple sources given
46
if ((!exists || !stats.isDirectory()) && sources.length > 1)
47
common.error('dest is not a directory (too many sources)');
49
// Dest is an existing file, but no -f given
50
if (exists && stats.isFile() && !options.force)
51
common.error('dest file already exists: ' + dest);
53
sources.forEach(function(src) {
54
if (!fs.existsSync(src)) {
55
common.error('no such file or directory: '+src, true);
59
// If here, src exists
61
// When copying to '/path/dir':
62
// thisDest = '/path/dir/file1'
64
if (fs.existsSync(dest) && fs.statSync(dest).isDirectory())
65
thisDest = path.normalize(dest + '/' + path.basename(src));
67
if (fs.existsSync(thisDest) && !options.force) {
68
common.error('dest file already exists: ' + thisDest, true);
72
if (path.resolve(src) === path.dirname(path.resolve(thisDest))) {
73
common.error('cannot move to self: '+src, true);
77
fs.renameSync(src, thisDest);