-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathrename.js
More file actions
90 lines (73 loc) · 2.76 KB
/
rename.js
File metadata and controls
90 lines (73 loc) · 2.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/*
* grunt-rename
* https://github.com/jdavis/grunt-rename
*
* Copyright (c) 2013 Josh Davis
* Licensed under the MIT license.
*/
'use strict';
var fs = require('fs'),
path = require('path');
module.exports = function(grunt) {
grunt.registerMultiTask('rename', 'Move and/or rename files.', function() {
var options = this.options({
ignore: false,
execSync: false
});
var done = options.execSync ? (function(){}) : this.async();
//console.log(options);
if (!this.files.length) {
grunt.log.writeln('Moved '+'0'.cyan+' files.');
return done();
}
this.files.forEach(function (f) {
var dest = f.dest,
dir = path.dirname(dest);
// Check if no source files were found
if (f.src.length === 0) {
// Continue if ignore is set
if (options.ignore) {
return done();
} else {
grunt.fail.warn('Could not move file to ' + f.dest + ' it did not exist.');
return done();
}
}
f.src.filter(function (file) {
// Resolve some conflicts because path doesn't work as I would
// expect
if (dest.lastIndexOf(path.sep) === dest.length - 1) {
dir = dest;
dest = path.join(dir, path.basename(file));
}
grunt.file.mkdir(dir);
// First try builtin rename ability
fs.rename(file, dest, function (err) {
// Easy peasy
if (!err) {
grunt.verbose.writeln('Moved ' + file + ' to ' + dest);
return done();
}
// Now fallback to copying/unlinking
var read = fs.createReadStream(file);
var write = fs.createWriteStream(dest);
read.on('error', function (err) {
grunt.fail.warn('Failed to read ' + file);
return done();
});
write.on('error', function (err) {
grunt.fail.warn('Failed to write to ' + dest);
return done();
});
write.on('close', function () {
// Now remove original file
grunt.file.delete(file);
grunt.verbose.writeln('Moved ' + file + ' to ' + dest);
return done();
});
read.pipe(write);
});
});
});
});
};