"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
// tslint:disable:no-console
const chalk_1 = require("chalk");
const path = require("path");
const _ = require("underscore");
const util_1 = require("util");
const debugFlags = {};
function w(str, l) {
return (str + " ").substr(0, l);
}
function setDebugFlag(scriptFullpath, flag) {
const filename = path.basename(scriptFullpath, ".js");
if (process.env.DEBUG) {
const decoratedFilename = chalk_1.default.yellow(w(filename, 30));
console.log(" Setting debug for ", decoratedFilename, " to ", (flag ? chalk_1.default.cyan : chalk_1.default.red)(flag.toString()));
}
debugFlags[filename] = flag;
}
exports.setDebugFlag = setDebugFlag;
function checkDebugFlag(scriptFullpath) {
const filename = path.basename(scriptFullpath, ".js");
let doDebug = debugFlags[filename];
if (process && process.env && process.env.DEBUG && !debugFlags.hasOwnProperty(filename)) {
doDebug = (process.env.DEBUG.indexOf(filename) >= 0 || process.env.DEBUG.indexOf("ALL") >= 0);
setDebugFlag(filename, doDebug);
}
return doDebug;
}
exports.checkDebugFlag = checkDebugFlag;
function file_line(filename, callerLine) {
const d = (new Date()).toISOString().substr(11);
return chalk_1.default.bgWhite.cyan(w(d, 14) + ":" + w(filename, 30) + ":" + w(callerLine.toString(), 5));
}
/**
* @method make_debugLog
* @param scripFullpath:string
* @return returns a debugLog function that will write message to the console
* if the DEBUG environment variable indicates that the provided source file shall display debug trace
*
*/
function make_debugLog(scripFullpath) {
const doDebug = checkDebugFlag(scripFullpath);
const filename = path.basename(scripFullpath, ".js");
function debugLogFunc() {
if (debugFlags[filename]) {
const stack = new Error("").stack || "";
// caller line number
const l = stack.split("\n")[2].split(":");
const callerLine = parseInt(l[l.length - 2], 10);
let a1 = [file_line(filename, callerLine)];
const a2 = _.values(arguments);
const output = util_1.format.apply(null, a2);
let i = 0;
for (const line of output.split("\n")) {
const args = [].concat(a1, [line]);
console.log.apply(console, args);
a1 = [w(" ... ", 51)];
i = i + 1;
if (i > 20) {
const a3 = a1.concat([" .... TRUNCATED ....."]);
console.log.apply(console, a3);
break;
}
}
}
}
return debugLogFunc;
}
exports.make_debugLog = make_debugLog;
//# sourceMappingURL=make_debug_log.js.map