UNPKG

2.9 kBJavaScriptView Raw
1var path = require('path'),
2 fs = require('fs'),
3 util = require('util'),
4 glob = require('glob'),
5 async = require('async');
6
7var supportedFileTypes = ['js', 'coffee'];
8
9exports.getFileMatchingStr = function() {
10 return '**/*.+(' + supportedFileTypes.join('|') + ')';
11}
12
13exports.mvFile = function(currentDir, sourceAbsPath, destAbsPath, cb) {
14 fs.exists(sourceAbsPath, function(exists) {
15 if (!exists) return cb(new Error('File ' + sourceAbsPath + ' does not exist!'));
16
17 fs.rename(sourceAbsPath, destAbsPath, function(err) {
18 if (err) return cb(err);
19
20 async.series([
21 function(cb) {exports.updateReferenceInFile(sourceAbsPath, destAbsPath, cb)},
22 function(cb) {exports.updateReferenceToMovedFile(currentDir, sourceAbsPath, destAbsPath, cb)}
23 ], cb)
24 })
25 });
26};
27
28exports.updateReferenceInFile = function(sourceAbsPath, destAbsPath, cb) {
29 fs.readFile(destAbsPath, 'utf8', function(err, data) {
30 if (err) return cb(err);
31
32 var re = /require(\(|\s)('|")(\.\S+)('|")(\))?/g;
33 var re1 = /require(\(|\s)('|")(\.\S+)('|")(\))?/;
34 var matches = data.match(re);
35 console.log(matches)
36
37 if (matches) {
38 matches.forEach(function(match) {
39 var oldRequire = match;
40 var groups = re1.exec(match);
41 var oldPath = groups[3];
42 var oldAsbPath = path.join(path.dirname(sourceAbsPath), oldPath);
43 var newRelativePath = path.relative(path.dirname(destAbsPath), oldAsbPath);
44 if (newRelativePath.indexOf(".") != 0 ) {
45 newRelativePath = './' + newRelativePath;
46 }
47 var newRequire = oldRequire.replace(re1, 'require$1$2' + newRelativePath + '$4$5');
48 data = data.replace(oldRequire, newRequire);
49 })
50 }
51 fs.writeFile(destAbsPath, data, {encoding: 'utf8'}, cb);
52 });
53}
54
55exports.updateReferenceToMovedFile = function(currentDir, sourceAbsPath, destAbsPath, cb) {
56 var fileMatchingStr = exports.getFileMatchingStr();
57 glob(fileMatchingStr, {cwd:currentDir}, function(err, files) {
58 if (err) return cb(err);
59
60 function updateReferenceForFile(file, cb) {
61 var oldRelativePath = path.relative(path.dirname(file), sourceAbsPath).replace(/\.(js|coffee)$/, ''),
62 newRelativePath = path.relative(path.dirname(file), destAbsPath).replace(/\.(js|coffee)$/, '');
63 if (oldRelativePath.indexOf(".") != 0 ) {
64 oldRelativePath = './' + oldRelativePath;
65 }
66 if (newRelativePath.indexOf(".") != 0 ) {
67 newRelativePath = './' + newRelativePath;
68 }
69 var regex = new RegExp("require\\('" + oldRelativePath+"'\\)", "g")
70 fs.readFile(file, 'utf8', function(err, data) {
71 if (err) return cb(err);
72
73 var result = data.replace(regex, "require('" + newRelativePath + "')");
74 fs.writeFile(file, result, {encoding: 'utf8'}, cb);
75 })
76 }
77 async.eachLimit(files, 20, updateReferenceForFile, cb);
78 })
79}