@omnia/foundation
Version:
Provide omnia foundation typings and tooling work on client side for omnia extension
119 lines (90 loc) • 3.09 kB
JavaScript
;
var path = require('path');
var fs = require('fs');
var _timer = {};
function rewriteFile (args) {
args.path = args.path || process.cwd();
var fullPath = path.join(args.path, args.file);
args.spliceWithinLine = args.spliceWithinLine || false;
args.haystack = fs.readFileSync(fullPath, 'utf8');
var body = rewrite(args);
fs.writeFileSync(fullPath, body, 'utf8');
}
function escapeRegExp (str) {
return str.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&');
}
function rewrite (args) {
// check if splicable is already in the body text
var re = new RegExp(args.splicable.map(function (line) {
return '\s*' + escapeRegExp(line);
}).join('\r\n'));
if (re.test(args.haystack)) {
return args.haystack;
}
var lines = args.haystack.split('\r\n');
var otherwiseLineIndex = 0;
lines.forEach(function (line, i) {
if (line.indexOf(args.needle) !== -1) {
otherwiseLineIndex = i;
}
});
if ((otherwiseLineIndex > 0) && (args.spliceWithinLine)) {
var line = lines[otherwiseLineIndex];
var indexToSpliceAt = line.indexOf(args.needle);
lines[otherwiseLineIndex] = line.substr(0, indexToSpliceAt) + args.splicable[0] + line.substr(indexToSpliceAt);
return lines.join('\r\n');
}
var spaces = 0;
while (lines[otherwiseLineIndex].charAt(spaces) === ' ') {
spaces += 1;
}
var spaceStr = '';
while ((spaces -= 1) >= 0) {
spaceStr += ' ';
}
lines.splice(otherwiseLineIndex, 0, args.splicable.map(function (line) {
return spaceStr + line;
}).join('\r\n'));
return lines.join('\r\n');
}
function getCurrentDateTime() {
var d = new Date();
return d.getFullYear() + "-" + d.getMonth() + "-" + d.getDate() + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
}
function flatArrayFiles(listFiles) {
var flatFiles = "";
for (var i = 0; i < listFiles.length; i++) {
flatFiles += listFiles[i].replace(/^.*[\\\/]/, '') + ", ";
}
if (flatFiles.length > 2 && flatFiles.substr(flatFiles.length - 2, 2) === ", ") {
flatFiles = flatFiles.substr(0, flatFiles.length - 2);
}
return flatFiles;
}
function timeWatch(timerId, callBack, msWait) {
if (_timer[timerId]) {
clearTimeout(_timer[timerId]);
}
_timer[timerId] = setTimeout(callBack, msWait);
}
// Helper functions
var ROOT = process.cwd();
function hasProcessFlag(flag) {
return process.argv.join('').indexOf(flag) > -1;
}
function isWebpackDevServer() {
return process.argv[1] && !!(/webpack-dev-server/.exec(process.argv[1]));
}
function root(args) {
args = Array.prototype.slice.call(arguments, 0);
return path.join.apply(path, [ROOT].concat(args));
}
module.exports = {
rewriteFile: rewriteFile,
getCurrentDateTime: getCurrentDateTime,
timeWatch: timeWatch,
flatArrayFiles: flatArrayFiles,
hasProcessFlag: hasProcessFlag,
isWebpackDevServer: isWebpackDevServer,
root: root
};