fswatcher
Version:
Um monitor de diretórios que permite executar vários programas
201 lines (162 loc) • 5.72 kB
JavaScript
/**
* Dependencias
*/
var watch = require('./node_modules/watch/main.js')
, assert = require('assert')
, path = require('path')
, fs = require('fs')
, exec = require('child_process').exec;
/**
* Cores para o console
*/
var consoleColors = {
red: "\033[31m",
cyan: "\033[1;36m",
red2: "\033[41m",
blue: "\033[35m",
green: "\033[42m",
lightGray: "\033[0;37m",
white: "\033[1;37m",
normal: "\033[m",
reset: "\033[0m"
}
/**
* Classe de controle
*
* Examples:
* var watcher = new FSWatcher();
*/
var FSWatcher = (function () {
function FSWatcher() {
this.arquivoDeConfiguracao = "./fswatcher.config.json";
this.verificaParametros();
this.configs = this.obtemConfiguracoes();
this.aplicaConfiguracoes();
}
/**
* Verifica a existencia dos parametros para a execução do script
*/
FSWatcher.prototype.verificaParametros = function() {
// Verifica a existencia de um arquivo de configuração.
var path = process.argv[2] || this.arquivoDeConfiguracao;
if (!fs.statSync(path).isFile()) {
console.log("Uso: node FSWatcher.js <caminho para o arquivo .config>");
process.exit(1);
} else {
this.arquivoDeConfiguracao = path;
}
};
/**
* Le o arquivo de configuração.
*/
FSWatcher.prototype.obtemConfiguracoes = function() {
var conteudo = fs.readFileSync(this.arquivoDeConfiguracao);
return JSON.parse(conteudo);
};
/**
* Aplica as configurações ligando aos listeners
*/
FSWatcher.prototype.aplicaConfiguracoes = function() {
var _this = this;
this.configs.forEach(function (item) {
console.log(consoleColors.cyan + item.titulo + consoleColors.reset);
item.diretorios.forEach(function (dir) {
console.log(" ((♦)) " + consoleColors.lightGray + _this.resumeString(dir, 70) + consoleColors.reset);
watch.watchTree(dir, function (f, curr, prev) {
if (typeof f == "object" && prev === null && curr === null) {
// Finished walking the tree
} else {
//console.log(f, curr, prev);
_this.executaComandosDoItem(item, f);
}
});
});
console.log("");
});
};
/**
* Executa um comando com base no listener.
*
* @param {Object} item item da configuração que contém os comandos a serem executados.
*/
FSWatcher.prototype.executaComandosDoItem = function(item, fileChanged) {
if (!this.regexpPermitida(item, fileChanged))
return;
if (!this.extensaoPermitida(item, fileChanged))
return;
var hora = consoleColors.green + (new Date()).toLocaleTimeString() + consoleColors.reset;
console.log("");
console.log(hora + " Ação: " + item.titulo);
console.log(hora + " Arquivo: " + this.resumeString(fileChanged));
item.executandoComando = null;
this.executaProximoComandoDoItem(item, fileChanged);
};
/**
* Faz a execução em séries dos comandos de um item.
*
* @param {Object} item item da configuração que contém os comandos a serem executados.
*/
FSWatcher.prototype.executaProximoComandoDoItem = function(item, fileChanged) {
if(item.executandoComando == null) {
item.executandoComando = 0;
} else if (item.executandoComando + 1 === item.acoes.length) {
item.executandoComando = null;
return;
} else {
item.executandoComando++;
}
var _this = this;
var cmd = item.acoes[item.executandoComando].replace(/\[filename\]/g, fileChanged);
var hora = consoleColors.green + (new Date()).toLocaleTimeString() + consoleColors.reset;
console.log(hora + " Comando: " + this.resumeString(cmd));
exec(cmd, function callback(error, stdout, stderr){
if(error) {
console.log("█["+ item.titulo +"] Erro ao executar " + cmd + ": ");
console.log("-------------------------------------------------------------------------------");
console.log(stderr);
console.log("-------------------------------------------------------------------------------");
} else {
_this.executaProximoComandoDoItem(item, fileChanged);
}
});
};
/**
* Verifica se o fileChanged está dentro das extenções permitidas
*
* @param {Object} item item da configuração que contém os comandos a serem executados.
* @param {String} filename nome do arquivo.
* @return {Boolean} indicador se a extenção é ou não permitida.
*/
FSWatcher.prototype.extensaoPermitida = function(item, filename) {
if (typeof item.extensoes == "undefined")
return true;
var i = filename.lastIndexOf('.');
var fileExtension = (i < 0) ? '' : filename.substr(i);
var itens = item.extensoes.filter(function(extensao){
return extensao == fileExtension;
});
return itens.length > 0 || item.extensoes.length == 0;
}
/**
* Verifica se o fileChanged está dentro das extenções permitidas
*
* @param {Object} item item da configuração que contém os comandos a serem executados.
* @param {String} filename nome do arquivo.
* @return {Boolean} indicador se a extenção é ou não permitida.
*/
FSWatcher.prototype.regexpPermitida = function(item, filename) {
if (typeof item.regexp == "undefined")
return true;
return new RegExp(item.regexp).test(filename);
}
FSWatcher.prototype.resumeString = function(str, maxLength) {
maxLength = maxLength || 60;
var intMeioDaLinha = parseInt(maxLength/2) - 3;
return (str.length > maxLength ?
str.substr(0, intMeioDaLinha) + "..." + str.substr(str.length - intMeioDaLinha) :
str);
}
return FSWatcher;
})();
new FSWatcher();