<commit_before>/* jshint node: true */
var path = require('path');

module.exports = {
  name: 'ember-cli-bootstrap-sassy',

  _findBootstrapPath: function() {
    if (!this._bootstrapPath) {
      var resolve = require('resolve');
      this._bootstrapPath = path.dirname(resolve.sync('bootstrap-sass/package.json')) + '/assets';
    }
  },

  included: function included(app, parentAddon) {
    var target = parentAddon || app;
    var configMessage = [];
    var o = target.options['ember-cli-bootstrap-sassy'] || { js: true, glyphicons: true };

    var emberCLIVersion = target.project.emberCLIVersion().split(',').map(function(item) {return Number(item);});
    if (emberCLIVersion[1] === 0  || emberCLIVersion[13] === 13) {
      throw new Error('ember-cli-bootstrap-sassy requires ember-cli version 1.13.13 or greater.\n');
    }

    // Import JS from bootstrap
    if (process.env.EMBER_CLI_FASTBOOT) {
      configMessage.push('no JS enabled [FastBoot]');
    } else {
      if(o.js instanceof Array) {
        o.js.forEach(function(fileName) {
          target.import('vendor/bootstrap/javascripts/bootstrap/' + fileName + '.js');
        });
        configMessage.push('some JS loaded [' + o.js.join(',') + ']');
      } else if (o.js !== false) {
        target.import('vendor/bootstrap/javascripts/bootstrap.js');
        configMessage.push('all JS enabled');
      } else {
        configMessage.push('no JS enabled');
      }
    }

    // Import glyphicons from bootstrap
    if(o.glyphicons !== false) {
      target.import('vendor/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.eot', { destDir: '/fonts/bootstrap' });
      target.import('vendor/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.svg', { destDir: '/fonts/bootstrap' });
      target.import('vendor/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.ttf', { destDir: '/fonts/bootstrap' });
      target.import('vendor/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.woff', { destDir: '/fonts/bootstrap' });
      target.import('vendor/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.woff2', { destDir: '/fonts/bootstrap' });
      configMessage.push('glyphicons enabled');
    } else {
      configMessage.push('glyphicons disabled');
    }

    if(o.quiet !== true) {
      this.ui.writeLine('bootstrap-sassy config: ' + configMessage.join(', '));
    }
  },
  treeForStyles: function(){
    var Funnel = require('broccoli-funnel');

    this._findBootstrapPath();

    var bootstrapTree = new Funnel(this.treeGenerator(path.join(this._bootstrapPath, 'stylesheets')), {
      destDir: '/app/styles'
    });

    return bootstrapTree;
  },

  treeForVendor: function() {
    var Funnel = require('broccoli-funnel');

    this._findBootstrapPath();

    return new Funnel(this._bootstrapPath, {
      destDir: '/bootstrap',
    });
  },
};
<commit_msg>Simplify treeForStyles() hook<commit_after>/* jshint node: true */
var path = require('path');

module.exports = {
  name: 'ember-cli-bootstrap-sassy',

  _findBootstrapPath: function() {
    if (!this._bootstrapPath) {
      var resolve = require('resolve');
      this._bootstrapPath = path.dirname(resolve.sync('bootstrap-sass/package.json')) + '/assets';
    }
  },

  included: function included(app, parentAddon) {
    var target = parentAddon || app;
    var configMessage = [];
    var o = target.options['ember-cli-bootstrap-sassy'] || { js: true, glyphicons: true };

    var emberCLIVersion = target.project.emberCLIVersion().split(',').map(function(item) {return Number(item);});
    if (emberCLIVersion[1] === 0  || emberCLIVersion[13] === 13) {
      throw new Error('ember-cli-bootstrap-sassy requires ember-cli version 1.13.13 or greater.\n');
    }

    // Import JS from bootstrap
    if (process.env.EMBER_CLI_FASTBOOT) {
      configMessage.push('no JS enabled [FastBoot]');
    } else {
      if(o.js instanceof Array) {
        o.js.forEach(function(fileName) {
          target.import('vendor/bootstrap/javascripts/bootstrap/' + fileName + '.js');
        });
        configMessage.push('some JS loaded [' + o.js.join(',') + ']');
      } else if (o.js !== false) {
        target.import('vendor/bootstrap/javascripts/bootstrap.js');
        configMessage.push('all JS enabled');
      } else {
        configMessage.push('no JS enabled');
      }
    }

    // Import glyphicons from bootstrap
    if(o.glyphicons !== false) {
      target.import('vendor/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.eot', { destDir: '/fonts/bootstrap' });
      target.import('vendor/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.svg', { destDir: '/fonts/bootstrap' });
      target.import('vendor/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.ttf', { destDir: '/fonts/bootstrap' });
      target.import('vendor/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.woff', { destDir: '/fonts/bootstrap' });
      target.import('vendor/bootstrap/fonts/bootstrap/glyphicons-halflings-regular.woff2', { destDir: '/fonts/bootstrap' });
      configMessage.push('glyphicons enabled');
    } else {
      configMessage.push('glyphicons disabled');
    }

    if(o.quiet !== true) {
      this.ui.writeLine('bootstrap-sassy config: ' + configMessage.join(', '));
    }
  },

  treeForStyles: function() {
    var Funnel = require('broccoli-funnel');

    this._findBootstrapPath();

    return new Funnel(this.treeGenerator(path.join(this._bootstrapPath, 'stylesheets')), {
      destDir: '/app/styles'
    });
  },

  treeForVendor: function() {
    var Funnel = require('broccoli-funnel');

    this._findBootstrapPath();

    return new Funnel(this._bootstrapPath, {
      destDir: '/bootstrap',
    });
  },
};
<|endoftext|>


<commit_before>var JSON5 = require("json5");
var path = require("path");
var assign = require("object-assign");
var emojiRegex = /[\uD800-\uDFFF]./;
var emojiList = require("emojis-list").filter(function(emoji) {
	return emojiRegex.test(emoji)
});

var baseEncodeTables = {
	26: "abcdefghijklmnopqrstuvwxyz",
	32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
	36: "0123456789abcdefghijklmnopqrstuvwxyz",
	49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
	52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
	58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
	62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
	64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
};
var emojiCache = {};

function encodeStringToEmoji(content, length) {
	if (emojiCache[content]) return emojiCache[content];
	length = length || 1;
	var emojis = [];
	do {
		var index = Math.floor(Math.random() * emojiList.length);
		emojis.push(emojiList[index]);
		emojiList.splice(index, 1);
	} while (--length > 0);
	var emojiEncoding = emojis.join('');
	emojiCache[content] = emojiEncoding;
	return emojiEncoding;
}

function encodeBufferToBase(buffer, base) {
	var encodeTable = baseEncodeTables[base];
	if (!encodeTable) throw new Error("Unknown encoding base" + base);

	var readLength = buffer.length;

	var Big = require('big.js');
	Big.RM = Big.DP = 0;
	var b = new Big(0);
	for (var i = readLength - 1; i >= 0; i--) {
		b = b.times(256).plus(buffer[i]);
	}

	var output = "";
	while (b.gt(0)) {
		output = encodeTable[b.mod(base)] + output;
		b = b.div(base);
	}

	Big.DP = 20;
	Big.RM = 1;

	return output;
}

exports.parseQuery = function parseQuery(query) {
	var specialValues = {
		'null': null,
		'true': true,
		'false': false
	};
	if(!query) return {};
	if(typeof query !== "string")
		return query;
	if(query.substr(0, 1) !== "?")
		throw new Error("a valid query string passed to parseQuery should begin with '?'");
	query = query.substr(1);
	var queryLength = query.length;
	if(query.substr(0, 1) === "{" && query.substr(-1) === "}") {
		return JSON5.parse(query);
	}
	var queryArgs = query.split(/[,\&]/g);
	var result = {};
	queryArgs.forEach(function(arg) {
		var idx = arg.indexOf("=");
		if(idx >= 0) {
			var name = arg.substr(0, idx);
			var value = decodeURIComponent(arg.substr(idx+1));
			if (specialValues.hasOwnProperty(value)) {
				value = specialValues[value];
			}
			if(name.substr(-2) === "[]") {
				name = decodeURIComponent(name.substr(0, name.length-2));
				if(!Array.isArray(result[name]))
					result[name] = [];
				result[name].push(value);
			} else {
				name = decodeURIComponent(name);
				result[name] = value;
			}
		} else {
			if(arg.substr(0, 1) === "-") {
				result[decodeURIComponent(arg.substr(1))] = false;
			} else if(arg.substr(0, 1) === "+") {
				result[decodeURIComponent(arg.substr(1))] = true;
			} else {
				result[decodeURIComponent(arg)] = true;
			}
		}
	});
	return result;
};

exports.getLoaderConfig = function(loaderContext, defaultConfigKey) {
	var query = exports.parseQuery(loaderContext.query);
	var configKey = query.config || defaultConfigKey;
	if (configKey) {
		var config = loaderContext.options[configKey] || {};
		delete query.config;
		return assign({}, config, query);
	}

	return query;
};

exports.stringifyRequest = function(loaderContext, request) {
	var splitted = request.split("!");
	var context = loaderContext.context || (loaderContext.options && loaderContext.options.context);
	return JSON.stringify(splitted.map(function(part) {
		if(/^\/|^[A-Z]:/i.test(part) && context) {
			part = path.relative(context, part);
			if(/^[A-Z]:/i.test(part)) {
				return part;
			} else {
				return "./" + part.replace(/\\/g, "/");
			}
		}
		return part;
	}).join("!"));
};

function dotRequest(obj) {
	return obj.request;
}

exports.getRemainingRequest = function(loaderContext) {
	if(loaderContext.remainingRequest)
		return loaderContext.remainingRequest;
	var request = loaderContext.loaders.slice(loaderContext.loaderIndex+1).map(dotRequest).concat([loaderContext.resource]);
	return request.join("!");
};

exports.getCurrentRequest = function(loaderContext) {
	if(loaderContext.currentRequest)
		return loaderContext.currentRequest;
	var request = loaderContext.loaders.slice(loaderContext.loaderIndex).map(dotRequest).concat([loaderContext.resource]);
	return request.join("!");
};

exports.isUrlRequest = function(url, root) {
	// An URL is not an request if
	// 1. it's a Data Url
	// 2. it's an absolute url or and protocol-relative
	// 3. it's some kind of url for a template
	if(/^data:|^chrome-extension:|^(https?:)?\/\/|^[\{\}\[\]#*;,'§\$%&\(=?`´\^°<>]/.test(url)) return false;
	// 4. It's also not an request if root isn't set and it's a root-relative url
	if((root === undefined || root === false) && /^\//.test(url)) return false;
	return true;
};

exports.urlToRequest = function(url, root) {
	var moduleRequestRegex = /^[^?]*~/;
	var request;

	if(/^[a-zA-Z]:\\|^\\\\/.test(url)) {
		// absolute windows path, keep it
		request = url;
	} else if(root !== undefined && root !== false && /^\//.test(url)) {
		// if root is set and the url is root-relative
		switch(typeof root) {
			// 1. root is a string: root is prefixed to the url
			case "string":
				// special case: `~` roots convert to module request
				if (moduleRequestRegex.test(root)) {
					request = root.replace(/([^~\/])$/, "$1/") + url.slice(1);
				} else {
					request = root + url;
				}
				break;
			// 2. root is `true`: absolute paths are allowed
			//    *nix only, windows-style absolute paths are always allowed as they doesn't start with a `/`
			case "boolean":
				request = url;
				break;
			default:
				throw new Error("Unexpected parameters to loader-utils 'urlToRequest': url = " + url + ", root = " + root + ".");
		}
	} else if(/^\.\.?\//.test(url)) {
		// A relative url stays
		request = url;
	} else {
		// every other url is threaded like a relative url
		request = "./" + url;
	}

	// A `~` makes the url an module
	if (moduleRequestRegex.test(request)) {
		request = request.replace(moduleRequestRegex, "");
	}

	return request;
};

exports.parseString = function parseString(str) {
	try {
		if(str[0] === '"') return JSON.parse(str);
		if(str[0] === "'" && str.substr(str.length - 1) === "'") {
			return parseString(str.replace(/\\.|"/g, function(x) {
				if(x === '"') return '\\"';
				return x;
			}).replace(/^'|'$/g, '"'));
		}
		return JSON.parse('"' + str + '"');
	} catch(e) {
		return str;
	}
};

exports.getHashDigest = function getHashDigest(buffer, hashType, digestType, maxLength) {
	hashType = hashType || "md5";
	maxLength = maxLength || 9999;
	var hash = require("crypto").createHash(hashType);
	hash.update(buffer);
	if (digestType === "base26" || digestType === "base32" || digestType === "base36" ||
	    digestType === "base49" || digestType === "base52" || digestType === "base58" ||
	    digestType === "base62" || digestType === "base64") {
		return encodeBufferToBase(hash.digest(), digestType.substr(4)).substr(0, maxLength);
	} else {
		return hash.digest(digestType || "hex").substr(0, maxLength);
	}
};

exports.interpolateName = function interpolateName(loaderContext, name, options) {
	var filename = name || "[hash].[ext]";
	var context = options.context;
	var content = options.content;
	var regExp = options.regExp;
	var ext = "bin";
	var basename = "file";
	var directory = "";
	var folder = "";
	if(loaderContext.resourcePath) {
		var resourcePath = loaderContext.resourcePath;
		var idx = resourcePath.lastIndexOf(".");
		var i = resourcePath.lastIndexOf("\\");
		var j = resourcePath.lastIndexOf("/");
		var p = i < 0 ? j : j < 0 ? i : i < j ? i : j;
		if(idx >= 0) {
			ext = resourcePath.substr(idx+1);
			resourcePath = resourcePath.substr(0, idx);
		}
		if(p >= 0) {
			basename = resourcePath.substr(p+1);
			resourcePath = resourcePath.substr(0, p+1);
		}
		if (typeof context !== 'undefined') {
			directory = path.relative(context, resourcePath + "_").replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
			directory = directory.substr(0, directory.length-1);
		}
		else {
			directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
		}
		if (directory.length === 1) {
			directory = "";
		} else if (directory.length > 1) {
			folder = path.basename(directory);
		}
	}
	var url = filename;
	if(content) {
		// Match hash template
		url = url.replace(/\[(?:(\w+):)?hash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, function() {
			return exports.getHashDigest(content, arguments[1], arguments[2], parseInt(arguments[3], 10));
		}).replace(/\[emoji(?::(\d+))?\]/ig, function() {
			return encodeStringToEmoji(content, arguments[1]);
		});
	}
	url = url.replace(/\[ext\]/ig, function() {
		return ext;
	}).replace(/\[name\]/ig, function() {
		return basename;
	}).replace(/\[path\]/ig, function() {
		return directory;
	}).replace(/\[folder\]/ig, function() {
		return folder;
	});
	if(regExp && loaderContext.resourcePath) {
		var re = new RegExp(regExp);
		var match = loaderContext.resourcePath.match(re);
		if(match) {
			for (var i = 0; i < match.length; i++) {
				var re = new RegExp("\\[" + i + "\\]", "ig");
				url = url.replace(re, match[i]);
			}
		}
	}
	if(typeof loaderContext.options === "object" && typeof loaderContext.options.customInterpolateName === "function") {
		url = loaderContext.options.customInterpolateName.call(loaderContext, url, name, options);
	}
	return url;
};
<commit_msg>Add deprecation warning to parseQuery<commit_after>var JSON5 = require("json5");
var path = require("path");
var util = require("util");
var os = require("os");
var assign = require("object-assign");
var emojiRegex = /[\uD800-\uDFFF]./;
var emojiList = require("emojis-list").filter(function(emoji) {
	return emojiRegex.test(emoji)
});

var baseEncodeTables = {
	26: "abcdefghijklmnopqrstuvwxyz",
	32: "123456789abcdefghjkmnpqrstuvwxyz", // no 0lio
	36: "0123456789abcdefghijklmnopqrstuvwxyz",
	49: "abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no lIO
	52: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
	58: "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ", // no 0lIO
	62: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
	64: "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ-_"
};
var emojiCache = {};
var parseQueryDeprecationWarning = util.deprecate(function () {},
	"loaderUtils.parseQuery() just received a value type of " + typeof query +
	" which can be problematic, see https://github.com/webpack/loader-utils/issues/56" + os.EOL +
	"parseQuery() will be replaced with getOptions() in the next major version of loader-utils."
);

function encodeStringToEmoji(content, length) {
	if (emojiCache[content]) return emojiCache[content];
	length = length || 1;
	var emojis = [];
	do {
		var index = Math.floor(Math.random() * emojiList.length);
		emojis.push(emojiList[index]);
		emojiList.splice(index, 1);
	} while (--length > 0);
	var emojiEncoding = emojis.join('');
	emojiCache[content] = emojiEncoding;
	return emojiEncoding;
}

function encodeBufferToBase(buffer, base) {
	var encodeTable = baseEncodeTables[base];
	if (!encodeTable) throw new Error("Unknown encoding base" + base);

	var readLength = buffer.length;

	var Big = require('big.js');
	Big.RM = Big.DP = 0;
	var b = new Big(0);
	for (var i = readLength - 1; i >= 0; i--) {
		b = b.times(256).plus(buffer[i]);
	}

	var output = "";
	while (b.gt(0)) {
		output = encodeTable[b.mod(base)] + output;
		b = b.div(base);
	}

	Big.DP = 20;
	Big.RM = 1;

	return output;
}

exports.parseQuery = function parseQuery(query) {
	var specialValues = {
		'null': null,
		'true': true,
		'false': false
	};
	if(!query) return {};
	if(typeof query !== "string") {
		parseQueryDeprecationWarning();
		return query;
	}
	if(query.substr(0, 1) !== "?")
		throw new Error("a valid query string passed to parseQuery should begin with '?'");
	query = query.substr(1);
	var queryLength = query.length;
	if(query.substr(0, 1) === "{" && query.substr(-1) === "}") {
		return JSON5.parse(query);
	}
	var queryArgs = query.split(/[,\&]/g);
	var result = {};
	queryArgs.forEach(function(arg) {
		var idx = arg.indexOf("=");
		if(idx >= 0) {
			var name = arg.substr(0, idx);
			var value = decodeURIComponent(arg.substr(idx+1));
			if (specialValues.hasOwnProperty(value)) {
				value = specialValues[value];
			}
			if(name.substr(-2) === "[]") {
				name = decodeURIComponent(name.substr(0, name.length-2));
				if(!Array.isArray(result[name]))
					result[name] = [];
				result[name].push(value);
			} else {
				name = decodeURIComponent(name);
				result[name] = value;
			}
		} else {
			if(arg.substr(0, 1) === "-") {
				result[decodeURIComponent(arg.substr(1))] = false;
			} else if(arg.substr(0, 1) === "+") {
				result[decodeURIComponent(arg.substr(1))] = true;
			} else {
				result[decodeURIComponent(arg)] = true;
			}
		}
	});
	return result;
};

exports.getLoaderConfig = function(loaderContext, defaultConfigKey) {
	var query = exports.parseQuery(loaderContext.query);
	var configKey = query.config || defaultConfigKey;
	if (configKey) {
		var config = loaderContext.options[configKey] || {};
		delete query.config;
		return assign({}, config, query);
	}

	return query;
};

exports.stringifyRequest = function(loaderContext, request) {
	var splitted = request.split("!");
	var context = loaderContext.context || (loaderContext.options && loaderContext.options.context);
	return JSON.stringify(splitted.map(function(part) {
		if(/^\/|^[A-Z]:/i.test(part) && context) {
			part = path.relative(context, part);
			if(/^[A-Z]:/i.test(part)) {
				return part;
			} else {
				return "./" + part.replace(/\\/g, "/");
			}
		}
		return part;
	}).join("!"));
};

function dotRequest(obj) {
	return obj.request;
}

exports.getRemainingRequest = function(loaderContext) {
	if(loaderContext.remainingRequest)
		return loaderContext.remainingRequest;
	var request = loaderContext.loaders.slice(loaderContext.loaderIndex+1).map(dotRequest).concat([loaderContext.resource]);
	return request.join("!");
};

exports.getCurrentRequest = function(loaderContext) {
	if(loaderContext.currentRequest)
		return loaderContext.currentRequest;
	var request = loaderContext.loaders.slice(loaderContext.loaderIndex).map(dotRequest).concat([loaderContext.resource]);
	return request.join("!");
};

exports.isUrlRequest = function(url, root) {
	// An URL is not an request if
	// 1. it's a Data Url
	// 2. it's an absolute url or and protocol-relative
	// 3. it's some kind of url for a template
	if(/^data:|^chrome-extension:|^(https?:)?\/\/|^[\{\}\[\]#*;,'§\$%&\(=?`´\^°<>]/.test(url)) return false;
	// 4. It's also not an request if root isn't set and it's a root-relative url
	if((root === undefined || root === false) && /^\//.test(url)) return false;
	return true;
};

exports.urlToRequest = function(url, root) {
	var moduleRequestRegex = /^[^?]*~/;
	var request;

	if(/^[a-zA-Z]:\\|^\\\\/.test(url)) {
		// absolute windows path, keep it
		request = url;
	} else if(root !== undefined && root !== false && /^\//.test(url)) {
		// if root is set and the url is root-relative
		switch(typeof root) {
			// 1. root is a string: root is prefixed to the url
			case "string":
				// special case: `~` roots convert to module request
				if (moduleRequestRegex.test(root)) {
					request = root.replace(/([^~\/])$/, "$1/") + url.slice(1);
				} else {
					request = root + url;
				}
				break;
			// 2. root is `true`: absolute paths are allowed
			//    *nix only, windows-style absolute paths are always allowed as they doesn't start with a `/`
			case "boolean":
				request = url;
				break;
			default:
				throw new Error("Unexpected parameters to loader-utils 'urlToRequest': url = " + url + ", root = " + root + ".");
		}
	} else if(/^\.\.?\//.test(url)) {
		// A relative url stays
		request = url;
	} else {
		// every other url is threaded like a relative url
		request = "./" + url;
	}

	// A `~` makes the url an module
	if (moduleRequestRegex.test(request)) {
		request = request.replace(moduleRequestRegex, "");
	}

	return request;
};

exports.parseString = function parseString(str) {
	try {
		if(str[0] === '"') return JSON.parse(str);
		if(str[0] === "'" && str.substr(str.length - 1) === "'") {
			return parseString(str.replace(/\\.|"/g, function(x) {
				if(x === '"') return '\\"';
				return x;
			}).replace(/^'|'$/g, '"'));
		}
		return JSON.parse('"' + str + '"');
	} catch(e) {
		return str;
	}
};

exports.getHashDigest = function getHashDigest(buffer, hashType, digestType, maxLength) {
	hashType = hashType || "md5";
	maxLength = maxLength || 9999;
	var hash = require("crypto").createHash(hashType);
	hash.update(buffer);
	if (digestType === "base26" || digestType === "base32" || digestType === "base36" ||
	    digestType === "base49" || digestType === "base52" || digestType === "base58" ||
	    digestType === "base62" || digestType === "base64") {
		return encodeBufferToBase(hash.digest(), digestType.substr(4)).substr(0, maxLength);
	} else {
		return hash.digest(digestType || "hex").substr(0, maxLength);
	}
};

exports.interpolateName = function interpolateName(loaderContext, name, options) {
	var filename = name || "[hash].[ext]";
	var context = options.context;
	var content = options.content;
	var regExp = options.regExp;
	var ext = "bin";
	var basename = "file";
	var directory = "";
	var folder = "";
	if(loaderContext.resourcePath) {
		var resourcePath = loaderContext.resourcePath;
		var idx = resourcePath.lastIndexOf(".");
		var i = resourcePath.lastIndexOf("\\");
		var j = resourcePath.lastIndexOf("/");
		var p = i < 0 ? j : j < 0 ? i : i < j ? i : j;
		if(idx >= 0) {
			ext = resourcePath.substr(idx+1);
			resourcePath = resourcePath.substr(0, idx);
		}
		if(p >= 0) {
			basename = resourcePath.substr(p+1);
			resourcePath = resourcePath.substr(0, p+1);
		}
		if (typeof context !== 'undefined') {
			directory = path.relative(context, resourcePath + "_").replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
			directory = directory.substr(0, directory.length-1);
		}
		else {
			directory = resourcePath.replace(/\\/g, "/").replace(/\.\.(\/)?/g, "_$1");
		}
		if (directory.length === 1) {
			directory = "";
		} else if (directory.length > 1) {
			folder = path.basename(directory);
		}
	}
	var url = filename;
	if(content) {
		// Match hash template
		url = url.replace(/\[(?:(\w+):)?hash(?::([a-z]+\d*))?(?::(\d+))?\]/ig, function() {
			return exports.getHashDigest(content, arguments[1], arguments[2], parseInt(arguments[3], 10));
		}).replace(/\[emoji(?::(\d+))?\]/ig, function() {
			return encodeStringToEmoji(content, arguments[1]);
		});
	}
	url = url.replace(/\[ext\]/ig, function() {
		return ext;
	}).replace(/\[name\]/ig, function() {
		return basename;
	}).replace(/\[path\]/ig, function() {
		return directory;
	}).replace(/\[folder\]/ig, function() {
		return folder;
	});
	if(regExp && loaderContext.resourcePath) {
		var re = new RegExp(regExp);
		var match = loaderContext.resourcePath.match(re);
		if(match) {
			for (var i = 0; i < match.length; i++) {
				var re = new RegExp("\\[" + i + "\\]", "ig");
				url = url.replace(re, match[i]);
			}
		}
	}
	if(typeof loaderContext.options === "object" && typeof loaderContext.options.customInterpolateName === "function") {
		url = loaderContext.options.customInterpolateName.call(loaderContext, url, name, options);
	}
	return url;
};
<|endoftext|>


<commit_before>/*globals module, require */
(function() {
    'use strict';

    var through = require('through2'),
        utils = require('./lib/utils.js'),
        colorTrans = utils.colorTrans,
        processFilePath = require('./lib/process-file-path.js'),
        processFunction = require('./lib/process-function.js'),

        GulpLogger;

    GulpLogger = function(fnOpts, opts) {
        var options = typeof fnOpts === 'object' ? fnOpts : opts;

        if (options) {
            utils.colorsEnabled = typeof options.colors !== 'undefined' ? options.colors : true;

            if (options.before) {
                console.log(colorTrans(options.before, 'cyan'));
            }
        }

        function loggerEndHandler(flushCallback) {
            if (options && options.after) {
                console.log(colorTrans(options.after, 'cyan'));
            }

            flushCallback();
        }

        return through.obj(function(file, ext, streamCallback) {
            var filePath = file.path;

            if (typeof fnOpts === 'function') {
                processFunction(filePath, fnOpts, opts);
            } else if (typeof fnOpts === 'object') {
                processFilePath(filePath, fnOpts);
            } else {
                console.log(utils.getRelativePath(filePath));
            }

            streamCallback(null, file);
        }, loggerEndHandler);
    };

    module.exports = GulpLogger;

}());
<commit_msg>Fixing before bug<commit_after>/*globals module, require */
(function() {
    'use strict';

    var through = require('through2'),
        utils = require('./lib/utils.js'),
        colorTrans = utils.colorTrans,
        processFilePath = require('./lib/process-file-path.js'),
        processFunction = require('./lib/process-function.js'),

        GulpLogger;

    GulpLogger = function(fnOpts, opts) {
        var options = typeof fnOpts === 'object' ? fnOpts : opts,
            beforeComplete = false,
            afterComplete = false;

        if (options) {
            utils.colorsEnabled = typeof options.colors !== 'undefined' ? options.colors : true;
        }

        function loggerEndHandler(flushCallback) {
            if (options && options.after && !afterComplete) {
                console.log(colorTrans(options.after, 'cyan'));
                afterComplete = true;
            }

            flushCallback();
        }

        return through.obj(function(file, ext, streamCallback) {
            var filePath = file.path;

            if (options && options.before && !beforeComplete) {
                console.log(colorTrans(options.before, 'cyan'));
                beforeComplete = true;
            }

            if (typeof fnOpts === 'function') {
                processFunction(filePath, fnOpts, opts);
            } else if (typeof fnOpts === 'object') {
                processFilePath(filePath, fnOpts);
            } else {
                console.log(utils.getRelativePath(filePath));
            }

            streamCallback(null, file);
        }, loggerEndHandler);
    };

    module.exports = GulpLogger;

}());
<|endoftext|>


<commit_before>var xml = require('libxmljs'),
    request = require('request')

var Client = exports.Client = function Client(appKey) {
  if(!appKey)
    console.warn("Warning: Wolfram|Alpha application key not set")
  else
    this.appKey = appKey
}

Client.prototype.query = function(input, cb) {
  if(!this.appKey) {
    return cb("Application key not set", null)
  }

  var uri = 'http://api.wolframalpha.com/v2/query?input=' + encodeURIComponent(input) + '&primary=true&appid=' + this.appKey

  request(uri, function(error, response, body) {
    if(!error && response.statusCode == 200) {
      var doc = xml.parseXml(body),
          rootNode = doc.root()

      if(rootNode.attr('error').value() != 'false') {
        var message = rootNode.get('descendant-or-self::error/msg').text()
        return cb(message, null)
      } else {
        var result = [],
            podNodes = rootNode.find('descendant-or-self::pod')

        for(var i = 0; i < podNodes.length; i++) {
          var podNode = podNodes[i],
              pod = { subpods: [] }

          pod.title = podNode.attr('title').value()
          if(podNode.attr('primary') && podNode.attr('primary').value() == 'true')
            pod.primary = true
          else
            pod.primary = false

          var subpodNodes = podNode.find('descendant-or-self::subpod')
          for(var j = 0; j < subpodNodes.length; j++) {
            var subpodNode = subpodNodes[j]
              , subpod = {}

            subpod.title = subpodNode.attr('title').value()
            subpod.value = subpodNode.get('descendant-or-self::plaintext').text()
            subpod.image = subpodNode.get('descendant-or-self::img').attr('src').value()

            pod.subpods.push(subpod)
          }

          result.push(pod)
        }

        return cb(null, result)
      }
    }
  })
}

exports.createClient = function(appKey) {
  return new Client(appKey)
}
<commit_msg>Remove console warning about missing API key<commit_after>var xml = require('libxmljs'),
    request = require('request')

var Client = exports.Client = function Client(appKey) {
  this.appKey = appKey
}

Client.prototype.query = function(input, cb) {
  if(!this.appKey) {
    return cb("Application key not set", null)
  }

  var uri = 'http://api.wolframalpha.com/v2/query?input=' + encodeURIComponent(input) + '&primary=true&appid=' + this.appKey

  request(uri, function(error, response, body) {
    if(!error && response.statusCode == 200) {
      var doc = xml.parseXml(body),
          rootNode = doc.root()

      if(rootNode.attr('error').value() != 'false') {
        var message = rootNode.get('descendant-or-self::error/msg').text()
        return cb(message, null)
      } else {
        var result = [],
            podNodes = rootNode.find('descendant-or-self::pod')

        for(var i = 0; i < podNodes.length; i++) {
          var podNode = podNodes[i],
              pod = { subpods: [] }

          pod.title = podNode.attr('title').value()
          if(podNode.attr('primary') && podNode.attr('primary').value() == 'true')
            pod.primary = true
          else
            pod.primary = false

          var subpodNodes = podNode.find('descendant-or-self::subpod')
          for(var j = 0; j < subpodNodes.length; j++) {
            var subpodNode = subpodNodes[j]
              , subpod = {}

            subpod.title = subpodNode.attr('title').value()
            subpod.value = subpodNode.get('descendant-or-self::plaintext').text()
            subpod.image = subpodNode.get('descendant-or-self::img').attr('src').value()

            pod.subpods.push(subpod)
          }

          result.push(pod)
        }

        return cb(null, result)
      }
    }
  })
}

exports.createClient = function(appKey) {
  return new Client(appKey)
}
<|endoftext|>


<commit_before>import d3 from 'd3';
import { delimiters } from './delimiters';
import filterData from '../filterData';
import { metaballs } from '../metaballs';
import { init as initMetaballs } from '../metaballs';
import axesFactory from './axes';
import dropsFactory from './drops';
import labelsFactory from './labels';
import lineSeparatorFactory from './lineSeparator';

export default (svg, dimensions, scales, configuration) => {
    const defs = svg.append('defs');
    defs.append('svg:clipPath')
        .attr('id', 'drops-container')
            .append('svg:rect')
            .attr('id', 'drops-container-rect')
            .attr('x', configuration.margin.left + 10)
            .attr('y', 0)
            .attr('width', dimensions.width)
            .attr('height', dimensions.outer_height);

    const labelsContainer = svg
        .append('g')
        .classed('labels', true)
        .attr('transform', 'translate(0, 45)');

    const axesContainer = svg.append('g')
        .classed('axes', true)
        .attr('transform', 'translate(210, 55)');

    const dropsContainer = svg.append('g')
        .classed('drops-container', true)
        .style('filter', 'url(#metaballs)');

    const extremaContainer = svg.append('g')
        .classed('extremum', true)
        .attr('width', dimensions.width)
        .attr('height', 30)
        .attr('transform', `translate(${configuration.margin.left}, ${configuration.margin.top - 45})`);

    configuration.metaballs && metaballs(defs);

    const lineSeparator = lineSeparatorFactory(axesContainer, scales, configuration, dimensions);
    const axes = axesFactory(axesContainer, scales, configuration, dimensions);
    const labels = labelsFactory(labelsContainer, scales, configuration);
    const drops = dropsFactory(dropsContainer, scales, configuration);

    return data => {
        lineSeparator(data);
        delimiters(svg, scales, configuration.dateFormat);
        drops(data);
        labels(data);
        axes(data);
    };
};
<commit_msg>Remove dead code<commit_after>import d3 from 'd3';
import { delimiters } from './delimiters';
import filterData from '../filterData';
import { metaballs } from '../metaballs';
import axesFactory from './axes';
import dropsFactory from './drops';
import labelsFactory from './labels';
import lineSeparatorFactory from './lineSeparator';

export default (svg, dimensions, scales, configuration) => {
    const defs = svg.append('defs');
    defs.append('svg:clipPath')
        .attr('id', 'drops-container')
            .append('svg:rect')
            .attr('id', 'drops-container-rect')
            .attr('x', configuration.margin.left + 10)
            .attr('y', 0)
            .attr('width', dimensions.width)
            .attr('height', dimensions.outer_height);

    const labelsContainer = svg
        .append('g')
        .classed('labels', true)
        .attr('transform', 'translate(0, 45)');

    const axesContainer = svg.append('g')
        .classed('axes', true)
        .attr('transform', 'translate(210, 55)');

    const dropsContainer = svg.append('g')
        .classed('drops-container', true)
        .style('filter', 'url(#metaballs)');

    const extremaContainer = svg.append('g')
        .classed('extremum', true)
        .attr('width', dimensions.width)
        .attr('height', 30)
        .attr('transform', `translate(${configuration.margin.left}, ${configuration.margin.top - 45})`);

    configuration.metaballs && metaballs(defs);

    const lineSeparator = lineSeparatorFactory(axesContainer, scales, configuration, dimensions);
    const axes = axesFactory(axesContainer, scales, configuration, dimensions);
    const labels = labelsFactory(labelsContainer, scales, configuration);
    const drops = dropsFactory(dropsContainer, scales, configuration);

    return data => {
        lineSeparator(data);
        delimiters(svg, scales, configuration.dateFormat);
        drops(data);
        labels(data);
        axes(data);
    };
};
<|endoftext|>


<commit_before>var restify = require('restify')
var bunyan = require('bunyan')
var crypto = require('crypto')

// Setting a log to get all activities
var log = bunyan.createLogger({
    name: 'trello-api',
    level: process.env.LOG_LEVEL || 'info',
    stream: process.stdout,
    serializers: bunyan.stdSerializers
})

var base64Digest = function (content) {
    return crypto.createHmac('sha1', 'f464c9fadd96fe7faea26f2198a156f760f0ec2a57d9741cafb754f333454046').update(content).digest('base64');
}

function verifyTrelloWebhookRequest(request, secret, callbackURL) {
    // Double-HMAC to blind any timing channel attacks
    // https://www.isecpartners.com/blog/2011/february/double-hmac-verification.asp
    var base64Digest = function (s) {
        return crypto.createHmac('sha1', secret).update(s).digest('base64');
    }
    var content = request.body + callbackURL;
    var doubleHash = base64Digest(base64Digest(content));
    var headerHash = base64Digest(request.headers['x-trello-webhook']);

    return doubleHash == headerHash;
}

function watcher(req, res, next) {
    log.info("call");
    var isValid = verifyTrelloWebhookRequest(req, "f464c9fadd96fe7faea26f2198a156f760f0ec2a57d9741cafb754f333454046", "https://kyra-consulting.herokuapp.com/1/trello/webhook");
    log.info({trello_content: req.headers['x-trello-webhook'], valid: isValid})

    res.send()
    next()
}

var server = restify.createServer()

server.name = "trello-api"

server.head('/1/trello/webhook', watcher)

var port = (process.env.PORT || 5000)

server.listen(port, function()
    {
        console.log('%s listening at %s on port %s', server.name, server.url, port)
    }
)<commit_msg>version adjust<commit_after>var restify = require('restify')
var bunyan = require('bunyan')
var crypto = require('crypto')

// Setting a log to get all activities
var log = bunyan.createLogger({
    name: 'trello-api',
    level: process.env.LOG_LEVEL || 'info',
    stream: process.stdout,
    serializers: bunyan.stdSerializers
})

var base64Digest = function (content) {
    return crypto.createHmac('sha1', 'f464c9fadd96fe7faea26f2198a156f760f0ec2a57d9741cafb754f333454046').update(content).digest('base64');
}

function verifyTrelloWebhookRequest(request, secret, callbackURL) {
    // Double-HMAC to blind any timing channel attacks
    // https://www.isecpartners.com/blog/2011/february/double-hmac-verification.asp
    var base64Digest = function (s) {
        return crypto.createHmac('sha1', secret).update(s).digest('base64');
    }
    var content = request.body + callbackURL;
    var doubleHash = base64Digest(base64Digest(content));
    var headerHash = base64Digest(request.headers['x-trello-webhook']);

    return doubleHash == headerHash;
}

function doHead(req, res, next) {
    log.info({method: "HEAD"})
    doFlush(req, res, next);
}

function doPost(req, res, next) {
    log.info({method: "POST"})
    verifyTrelloWebhookRequest(req, "f464c9fadd96fe7faea26f2198a156f760f0ec2a57d9741cafb754f333454046", "https://kyra-consulting.herokuapp.com/1/trello/webhook")
    log.info({trello_content: req.headers['x-trello-webhook'], valid: isValid})
}

function doFlush(req, res, next){
    res.send()
    next()
}

var server = restify.createServer()

server.name = "trello-api"

server.head('/1/trello/webhook', doHead)

server.post('/1/trello/webhook', doPost)

var port = (process.env.PORT || 5000)

server.listen(port, function()
    {
        console.log('%s listening at %s on port %s', server.name, server.url, port)
    }
)<|endoftext|>


<commit_before>var spawn = require('child_process').spawn;

/**
 * Scans surrounding area for probe requests.
 *
 * @module plott/probeRequest
 * @category network
 * @return {Function}
 * @example
 * plott.probeRequest();
 * --Do something
 *})
 *
 *
 *
 */

module.exports = function(callback) {
  var tcpdump = spawn('tcpdump', ['-I -e -i wlan1 -s 256 type mgt subtype probe-req']);

  tcpdump.stdout.on('data', function (data) {
    console.log('tcpdump data: ' + data);
    return callback(null, data);
  });

  tcpdump.stderr.on('data', function (data) {
    console.log('tcpdump stderr: ' + data);
    return callback(data, null)
  });

  tcpdump.on('close', function (code) {
    if (code !== 0) {
      console.log('tcpdump process exited with code ' + code);
    }
  });

  tcpdump.on('error', function (err) {
    console.log('Failed to start child process.');
    return callback(err, null);
  });
};
<commit_msg>Changed tcpdump options<commit_after>var spawn = require('child_process').spawn;

/**
 * Scans surrounding area for probe requests.
 *
 * @module plott/probeRequest
 * @category network
 * @return {Function}
 * @example
 * plott.probeRequest();
 * --Do something
 *})
 *
 *
 *
 */

module.exports = function(callback) {
  var tcpdump = spawn('tcpdump', ['I -e -i wlan1 -s 256 type mgt subtype probe-req']);

  tcpdump.stdout.on('data', function (data) {
    console.log('tcpdump data: ' + data);
    return callback(null, data);
  });

  tcpdump.stderr.on('data', function (data) {
    console.log('tcpdump stderr: ' + data);
    return callback(data, null)
  });

  tcpdump.on('close', function (code) {
    if (code !== 0) {
      console.log('tcpdump process exited with code ' + code);
    }
  });

  tcpdump.on('error', function (err) {
    console.log('Failed to start child process.');
    return callback(err, null);
  });
};
<|endoftext|>


<commit_before>var internals = {};

internals.mod = internals.mod || {};
internals.mod.log = require('../log');
internals.mod.type = require('../data_type');
internals.mod.Class = require('../class');
var Shadow = require('./shadow');
var log = internals.mod.log;
var tunnel = require('tunnel-ssh'),
    Promise = require('bluebird');

var ShadowProto = {

  createTable: function() { return Promise.resolve(); },
  addForeignKey: function() { return Promise.resolve(); },
  createCollection: function() { return Promise.resolve(); }
};

exports.connect = function (config, intern, callback) {
  var driver, req;

  var mod = internals.mod;
  internals = intern;
  internals.mod = mod;

  if ( !config.user && config.username )
    config.user = config.username;

  if (config.driver === undefined) {
    throw new Error(
      'config must include a driver key specifing which driver to use');
  }

  if (config.driver && typeof (config.driver) === 'object') {

    log.verbose('require:', config.driver.require);
    driver = require(config.driver.require);

  }
  else {
    try {

      req = 'db-migrate-' + config.driver;
      log.verbose('require:', req);

      try {

        driver = require(req);
      }
      catch (Exception) {

        driver = require('../../../' + req);
      }
    }
    catch (Exception) {

      //Fallback to internal drivers, while moving drivers to new repos
      req = './' + config.driver;
      log.verbose('require:', req);
      driver = require(req);
    }
  }

  log.verbose('connecting');

  var connect = function(config) {
    driver.connect(config, intern, function (err, db) {

      if (err) {

        callback(err);
        return;
      }
      log.verbose('connected');

      if (!global.immunity)
        db = Shadow.infect(db, internals, ShadowProto);

      callback(null, db);
    });
  };

  if (config.tunnel) {
    var tunnelConfig = JSON.parse(JSON.stringify(config.tunnel));
    tunnelConfig.dstHost = config.host;
    tunnelConfig.dstPort = config.port;

    if (tunnelConfig.privateKeyPath) {
      tunnelConfig.privateKey = require('fs').readFileSync(tunnelConfig.privateKeyPath);
    }

    // Reassign the db host/port to point to our local ssh tunnel
    config.host = '127.0.0.1';
    config.port = tunnelConfig.localPort;

    tunnel(tunnelConfig, function (err) {

      if (err) {
        callback(err);
        return;
      }
      log.verbose('SSH tunnel connected on port ', tunnelConfig.localPort);

      connect(config);
    });
  }
  else {
    connect(config);
  }
};<commit_msg>add interfaces to internals<commit_after>var internals = {};

internals.mod = internals.mod || {};
internals.mod.log = require('../log');
internals.mod.type = require('../data_type');
internals.mod.Class = require('../class');
var Shadow = require('./shadow');
var log = internals.mod.log;
var tunnel = require('tunnel-ssh'),
    Promise = require('bluebird'),
    SeederInterface = require('../interface/seederInterface.js');

var ShadowProto = {

  createTable: function() { return Promise.resolve(); },
  addForeignKey: function() { return Promise.resolve(); },
  createCollection: function() { return Promise.resolve(); }
};

exports.connect = function (config, intern, callback) {
  var driver, req;

  var mod = internals.mod;
  internals = intern;
  internals.mod = mod;
  internals.interfaces = {

    SeederInterface: SeederInterface;
  };

  if ( !config.user && config.username )
    config.user = config.username;

  if (config.driver === undefined) {
    throw new Error(
      'config must include a driver key specifing which driver to use');
  }

  if (config.driver && typeof (config.driver) === 'object') {

    log.verbose('require:', config.driver.require);
    driver = require(config.driver.require);

  }
  else {
    try {

      req = 'db-migrate-' + config.driver;
      log.verbose('require:', req);

      try {

        driver = require(req);
      }
      catch (Exception) {

        driver = require('../../../' + req);
      }
    }
    catch (Exception) {

      //Fallback to internal drivers, while moving drivers to new repos
      req = './' + config.driver;
      log.verbose('require:', req);
      driver = require(req);
    }
  }

  log.verbose('connecting');

  var connect = function(config) {
    driver.connect(config, intern, function (err, db) {

      if (err) {

        callback(err);
        return;
      }
      log.verbose('connected');

      if (!global.immunity)
        db = Shadow.infect(db, internals, ShadowProto);

      callback(null, db);
    });
  };

  if (config.tunnel) {
    var tunnelConfig = JSON.parse(JSON.stringify(config.tunnel));
    tunnelConfig.dstHost = config.host;
    tunnelConfig.dstPort = config.port;

    if (tunnelConfig.privateKeyPath) {
      tunnelConfig.privateKey = require('fs').readFileSync(tunnelConfig.privateKeyPath);
    }

    // Reassign the db host/port to point to our local ssh tunnel
    config.host = '127.0.0.1';
    config.port = tunnelConfig.localPort;

    tunnel(tunnelConfig, function (err) {

      if (err) {
        callback(err);
        return;
      }
      log.verbose('SSH tunnel connected on port ', tunnelConfig.localPort);

      connect(config);
    });
  }
  else {
    connect(config);
  }
};<|endoftext|>


<commit_before>/*!
 * resolve-up <https://github.com/jonschlinkert/resolve-up>
 *
 * Copyright (c) 2015 Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var utils = require('./utils');

/**
 * Return a list of directories that match the given filepath/glob
 * patterns, optionally using a pre-filter function before matching
 * globs against paths.
 *
 * @param  {Array|String} `pattern`
 * @param  {Function} `fn` Optional pre-filter function
 * @return {Array}
 */

module.exports = function resolveUp(patterns, options, fn) {
  if (typeof options === 'function') {
    fn = options;
    options = {};
  }

  if (!utils.isValidGlob(patterns)) {
    throw new Error('resolve-up expects a string or array as the first argument.');
  }

  var opts = utils.extend({fast: true}, opts);
  var dirs = utils.paths(opts).concat(opts.paths || []);
  var len = dirs.length, i = -1;
  var res = [];

  while (++i < len) {
    opts.cwd = dirs[i];
    if (!opts.cwd) continue;
    res.push.apply(res, resolve(utils.glob.sync(patterns, opts), opts));
  }
  return utils.unique(res);
};

/**
 * Resolve the absolute path to a file using the given cwd.
 */

function resolve(files, opts) {
  var fn = opts.filter || function(fp) {
    return true;
  };

  if (opts.realpath === true) {
    return files.filter(fn);
  }

  var len = files.length;
  var res = [];

  while (len--) {
    var fp = path.join(opts.cwd, files[len]);
    if (!fn(fp) || res.indexOf(fp) > -1) continue;
    res.push(fp);
  }
  return res;
}
<commit_msg>use resolve instead of join, cache results<commit_after>/*!
 * resolve-up <https://github.com/jonschlinkert/resolve-up>
 *
 * Copyright (c) 2015 Jon Schlinkert.
 * Licensed under the MIT license.
 */

'use strict';

var path = require('path');
var utils = require('./utils');
var cache = {};

/**
 * Return a list of directories that match the given filepath/glob
 * patterns, optionally using a pre-filter function before matching
 * globs against paths.
 *
 * @param  {Array|String} `pattern`
 * @param  {Function} `fn` Optional pre-filter function
 * @return {Array}
 */

module.exports = function resolveUp(patterns, options, fn) {
  if (typeof options === 'function') {
    fn = options;
    options = {};
  }

  if (!utils.isValidGlob(patterns)) {
    throw new Error('resolve-up expects a string or array as the first argument.');
  }

  var opts = utils.extend({fast: true}, opts);
  var dirs = utils.paths(opts).concat(opts.paths || []);
  var len = dirs.length;
  var idx = -1;
  var res = [];

  while (++idx < len) {
    opts.cwd = dirs[idx];
    if (!opts.cwd) continue;
    opts.cwd = path.resolve(opts.cwd);
    var key = opts.cwd + ':' + patterns;
    if (cache[key]) {
      res.push.apply(res, cache[key]);
    } else {
      var files = resolve(utils.glob.sync(patterns, opts), opts);
      cache[key] = files;
      res.push.apply(res, files);
    }
  }
  return utils.unique(res);
};

/**
 * Resolve the absolute path to a file using the given cwd.
 */

function resolve(files, opts) {
  var fn = opts.filter || function(fp) {
    return true;
  };

  if (opts.realpath === true) {
    return files.filter(fn);
  }

  var len = files.length;
  var idx = -1;
  var res = [];

  while (++idx < len) {
    var fp = path.resolve(opts.cwd, files[idx]);
    if (!fn(fp) || ~res.indexOf(fp)) continue;
    res.push(fp);
  }
  return res;
}
<|endoftext|>


<commit_before>var Q = require('q');
var util = require('util');

module.exports = function(schema, options){

    /**
     * Tries to resolve the user this entry belongs to.
     * Recursively dereferences the path entry that must be specified in the options
     * and calls getUserId on the resulting model. Throws an exception if getUserId is not defined.
     * If path equals 'id' or '_id' the resolver stops and returns the id.
     * @returns {promise}
     */
    schema.methods.getUserId = function(cb) {
        var deferred = Q.defer();
        var mongoose = require('mongoose');

        if (!options || !options.path) {
            return Q.reject(new TypeError("options.path must be specified"));
        }

        var path = options.path;
        var self = this;

        if(['id', '_id'].indexOf(path) !== -1){
            if(cb) cb(null, self[path]);
            deferred.resolve(self[path]);
        } else if (util.isNullOrUndefined(self[path])) {
            var err = new TypeError(path + " is null or undefined");
            if(cb) cb(err);
            deferred.reject(err);
        } else if (self[path].getUserId && util.isFunction(self[path].getUserId)) {
            if(cb) self[path].getUserId(cb);
            deferred.resolve(self[path].getUserId());
        } else {
            var referencedModel = schema.paths[path].options.ref;
            mongoose.model(referencedModel).findById(self[path]).exec(function(err, instance){
                if(err) {
                    if(cb) cb(err);
                    deferred.reject(err);
                } else {
                    if (instance && instance.getUserId && util.isFunction(instance.getUserId)) {
                        if(cb) instance.getUserId(cb);
                        deferred.resolve(instance.getUserId());
                    } else {
                        err = new TypeError(path + " has no such method 'getUserId'");
                        if(cb) cb(err);
                        deferred.reject(err);
                    }
                }
            });
        }

        return deferred.promise;
    }
};<commit_msg>Added option to stop resolving<commit_after>var Q = require('q');
var util = require('util');

module.exports = function(schema, options){

    /**
     * Tries to resolve the user this entry belongs to.
     * Recursively dereferences the path entry that must be specified in the options
     * and calls getUserId on the resulting model. Throws an exception if getUserId is not defined.
     * If path equals 'id' or '_id' the resolver stops and returns the id.
     * If stop is set to true the resolver returns path.
     * @returns {promise}
     */
    schema.methods.getUserId = function(cb) {
        var deferred = Q.defer();
        var mongoose = require('mongoose');

        if (!options || !options.path) {
            return Q.reject(new TypeError("options.path must be specified"));
        }

        var path = options.path;
        var self = this;

        if(options.stop){
            deferred.resolve(self[path]);
        } else if(['id', '_id'].indexOf(path) !== -1){
            if(cb) cb(null, self[path]);
            deferred.resolve(self[path]);
        } else if (util.isNullOrUndefined(self[path])) {
            var err = new TypeError(path + " is null or undefined");
            if(cb) cb(err);
            deferred.reject(err);
        } else if (self[path].getUserId && util.isFunction(self[path].getUserId)) {
            if(cb) self[path].getUserId(cb);
            deferred.resolve(self[path].getUserId());
        } else {
            var referencedModel = schema.paths[path].options.ref;
            mongoose.model(referencedModel).findById(self[path]).exec(function(err, instance){
                if(err) {
                    if(cb) cb(err);
                    deferred.reject(err);
                } else {
                    if (instance && instance.getUserId && util.isFunction(instance.getUserId)) {
                        if(cb) instance.getUserId(cb);
                        deferred.resolve(instance.getUserId());
                    } else {
                        err = new TypeError(path + " has no such method 'getUserId'");
                        if(cb) cb(err);
                        deferred.reject(err);
                    }
                }
            });
        }

        return deferred.promise;
    }
};<|endoftext|>


<commit_before>'use strict';

var p = require('path');
var _ = require('lodash');
var $ = require('gulp-load-plugins')();
var Elixir = require('laravel-elixir');

require('./lib/compiler')();
require('./config');

/*
 |----------------------------------------------------------------
 | Jade Compilation Task
 |----------------------------------------------------------------
 |
 | This task will compile your Jade file, including html-prettify.
 | Jade is one of the HTML pre-precessors
 |
 */

Elixir.extend('blade', function(options) {
    overrides = options || {};

    overrides.basedir = overrides.basedir || overrides.sourcePath || Elixir.config.blade.basedir || Elixir.config.blade.sourcePath;
    config = _.merge(Elixir.config.blade, overrides);

    let paths = getPaths(config.sourcePath, config.outputPath);

    new Elixir.Task('blade', function() {
        return (
            gulp
            .src(paths.src.path)
            .pipe($.jade(config))
            .on('error', function(e) {
                new Elixir.Notification().error(e, ' Views Compilation Failed');
                this.emit('end');
            })
            .pipe($.removeEmptyLines())
            .pipe($.if(config.pretty, $.prettify(config.prettify)))
            .pipe($.extReplace('.blade.php'))
            .pipe(gulp.dest(paths.output.path))
            .pipe(new Elixir.Notification('Blade Views Compiled!'))
        );
    }, paths)
    .watch(paths.watch);
});

/**
 * Prep the Gulp src and output paths.
 *
 * @param  {string|null} src
 * @param  {string|null}  output
 * @return {GulpPaths}
 */
function getPaths(source, output) {
    let gulpPaths = () => {
        return new Elixir.GulpPaths()
            .src(source || Elixir.config.blade.sourcePath)
            .output(output || Elixir.config.blade.outputPath);
    };

    let paths = gulpPaths();

    // Stop compile if path is not directorie
    if (!paths.src.isDir) {
        console.error(`The { sourcePath: "${ paths.src.path }" } must be directory name!`, '');

        process.exit(1);
    }

    // Stop compile if path is not directorie
    if (!paths.output.isDir) {
        console.error(`The { outputPath: "${ paths.output.path }" } must be directory name!`, '');

        process.exit(1);
    }

    let basePath = paths.src.path.replace(/\*/g, '');
    let search = `${ p.normalize(basePath + '.') }/**/${ Elixir.config.blade.search }`;

    paths.watch = search;
    paths.src.path = [
        // Ignore compiled file if first char is `_`.
        // Ex: '_ignore.jade'
        '!' + search.replace('*.', '_*.'),

        search
    ];

    return paths;
}<commit_msg>fix overrides<commit_after>'use strict';

var p = require('path');
var _ = require('lodash');
var $ = require('gulp-load-plugins')();
var Elixir = require('laravel-elixir');

require('./lib/compiler')();
require('./config');

/*
 |----------------------------------------------------------------
 | Jade Compilation Task
 |----------------------------------------------------------------
 |
 | This task will compile your Jade file, including html-prettify.
 | Jade is one of the HTML pre-precessors
 |
 */

Elixir.extend('blade', function(options) {
    let overrides = options || {};

    overrides.basedir = overrides.basedir || overrides.sourcePath || Elixir.config.blade.basedir || Elixir.config.blade.sourcePath;
    config = _.merge(Elixir.config.blade, overrides);

    let paths = getPaths(config.sourcePath, config.outputPath);

    new Elixir.Task('blade', function() {
        return (
            gulp
            .src(paths.src.path)
            .pipe($.jade(config))
            .on('error', function(e) {
                new Elixir.Notification().error(e, ' Views Compilation Failed');
                this.emit('end');
            })
            .pipe($.removeEmptyLines())
            .pipe($.if(config.pretty, $.prettify(config.prettify)))
            .pipe($.extReplace('.blade.php'))
            .pipe(gulp.dest(paths.output.path))
            .pipe(new Elixir.Notification('Blade Views Compiled!'))
        );
    }, paths)
    .watch(paths.watch);
});

/**
 * Prep the Gulp src and output paths.
 *
 * @param  {string|null} src
 * @param  {string|null}  output
 * @return {GulpPaths}
 */
function getPaths(source, output) {
    let gulpPaths = () => {
        return new Elixir.GulpPaths()
            .src(source || Elixir.config.blade.sourcePath)
            .output(output || Elixir.config.blade.outputPath);
    };

    let paths = gulpPaths();

    // Stop compile if path is not directorie
    if (!paths.src.isDir) {
        console.error(`The { sourcePath: "${ paths.src.path }" } must be directory name!`, '');

        process.exit(1);
    }

    // Stop compile if path is not directorie
    if (!paths.output.isDir) {
        console.error(`The { outputPath: "${ paths.output.path }" } must be directory name!`, '');

        process.exit(1);
    }

    let basePath = paths.src.path.replace(/\*/g, '');
    let search = `${ p.normalize(basePath + '.') }/**/${ Elixir.config.blade.search }`;

    paths.watch = search;
    paths.src.path = [
        // Ignore compiled file if first char is `_`.
        // Ex: '_ignore.jade'
        '!' + search.replace('*.', '_*.'),

        search
    ];

    return paths;
}<|endoftext|>


<commit_before>var payload = require('request-payload');

var receiveJSON = function(req, opts, cb) {
  if (typeof opts === 'function') return receiveJSON(req, {}, opts);

  payload(req, opts, function(raw) {
    try {
      cb(null, JSON.parse(raw));
    } catch(err) {
      cb(err);
    }
  });
};

module.exports = receiveJSON;
<commit_msg>do not try catch the callback<commit_after>var payload = require('request-payload');

var receiveJSON = function(req, opts, cb) {
  if (typeof opts === 'function') return receiveJSON(req, {}, opts);

  payload(req, opts, function(raw) {
    try {
      raw = JSON.parse(raw);
    } catch(err) {
      return cb(err);
    }
    cb(null, raw);
  });
};

module.exports = receiveJSON;
<|endoftext|>


<commit_before>'use strict';
const util = require('util');
const chalk = require('chalk');
const { murmur3 } = require('./lib/murmur3.node');

let instance = {};

const colors = {
  silly: 'magenta',
  verbose: 'cyan',
  debug: 'blue',
  info: 'green',
  warn: 'yellow',
  error: 'red'
};

const callStackCache = new Map();
const rSplit = /\//i;
const rSkip = new RegExp([
  '_stream_readable\.js',
  '\/node_modules',
  'events\.js',
  'internal',
  'largin\/index\.js',
  'native',
  'next_tick\.js',
  'process\b'
].join('|'), 'i');

let padding = 0;

const genWhitespace = function*(padding) {
  while ((--padding)) yield ' ';
};

const padr = (str, padding = 0) => {
  if (padding === 0) return str;
  padding += 1;
  const whitespace = [...genWhitespace(padding)].join('');
  return `${str}${whitespace}`;
};

const traceCaller = (callStack) => {
  const sh = murmur3(Buffer.from(callStack)).readUInt32BE();
  if (!(sh in callStackCache)) {
    callStackCache.set(sh, callStack
      .split('\n')
      .filter((x) => !rSkip.test(x))
      .map((line) => {
        const lineNumberAndColumn = line.split(':');
        const lineNumber = lineNumberAndColumn[1];
        const filenamePieces = lineNumberAndColumn[0]
          .replace(/^.*?(?=\/)/, '')
          .replace(/\/[0-9]+\./, '/')
          .split(rSplit);
        const filename = filenamePieces.pop();
        const subDirectory = filenamePieces.pop();
        if (!subDirectory) return null;
        const path = `${subDirectory}/${filename}:${lineNumber}`;
        padding = Math.max(padding, path.length);
        return path;
      })
      .filter((line) => Boolean(line))
      .pop());
  }
  const message = callStackCache.get(sh) || '';
  return padr(message, padding - message.length);
};

const flargin = (opts) => {
  const { noColor, noTimestamps, expandErrors, severity } = opts;
  const colorize = (arg, i) => {
    if (noColor) return arg;
    let color = ['gray'][i % 1];
    if (i === 1) color = colors[severity];
    return chalk[color](arg);
  };
  const log = function() {
    const args = Array.from(arguments)
      .map((it) => (it instanceof Error && !expandErrors ?
        `${it.name}: ${it.message}` :
        it))
      .map((it) => (it instanceof Object && !(it instanceof Error) ?
        JSON.stringify(it) :
        it));

    const now = new Date().toISOString().replace(/T/, ' ').replace(/Z$/, '');
    const caller = traceCaller(new Error().stack);
    const arg0 = args[0];

    const message = util.format(...args);

    const line = [
      colorize(severity.charAt(0).toUpperCase(), 1),
      !noTimestamps ? colorize(now, 0) : null,
      colorize(caller, 1),
      message,
      log.newLine
    ].filter((it) => !!it).join('  ');
    process.stdout.write(line);
  };
  log.newLine = '\n';
  return log;
};

class Largin {
  static newInstance(opts) {
    instance = null;
    return Largin.instance(opts);
  }

  static instance(opts) {
    opts = opts || {
      noColor: false,
      noTimestamps: false,
      expandErrors: false
    };
    if (instance instanceof Largin) return instance;
    instance = new Largin();
    Object.keys(colors).forEach((severity) => {
      opts.severity = severity;
      instance[severity] = flargin(opts);
    });
    module.exports = instance;
    return instance;
  }
}

module.exports = Largin;
<commit_msg>cleanup<commit_after>'use strict';
const util = require('util');
const chalk = require('chalk');
const { murmur3 } = require('./lib/murmur3.node');

let instance = {};

const colors = {
  silly: 'magenta',
  verbose: 'cyan',
  debug: 'blue',
  info: 'green',
  warn: 'yellow',
  error: 'red'
};

const callStackCache = new Map();
const rSplit = /\//i;
const rSkip = new RegExp([
  '_stream_readable\.js',
  '\/node_modules',
  'events\.js',
  'internal',
  'largin\/index\.js',
  'native',
  'next_tick\.js',
  'process\b'
].join('|'), 'i');

let padding = 0;

const genWhitespace = function*(padding) {
  while ((--padding)) yield ' ';
};

const padr = (str, padding = 0) => {
  if (padding === 0) return str;
  padding += 1;
  const whitespace = [...genWhitespace(padding)].join('');
  return `${str}${whitespace}`;
};

const traceCaller = (callStack) => {
  const sh = murmur3(Buffer.from(callStack)).readUInt32BE();
  if (!(sh in callStackCache)) {
    callStackCache.set(sh, callStack
      .split('\n')
      .filter((x) => !rSkip.test(x))
      .map((line) => {
        const lineNumberAndColumn = line.split(':');
        const lineNumber = lineNumberAndColumn[1];
        const filenamePieces = lineNumberAndColumn[0]
          .replace(/^.*?(?=\/)/, '')
          .replace(/\/[0-9]+\./, '/')
          .split(rSplit);
        const filename = filenamePieces.pop();
        const subDirectory = filenamePieces.pop();
        if (!subDirectory) return null;
        const path = `${subDirectory}/${filename}:${lineNumber}`;
        padding = Math.max(padding, path.length);
        return path;
      })
      .filter((line) => Boolean(line))
      .pop());
  }
  const message = callStackCache.get(sh) || '';
  return padr(message, padding - message.length);
};

const flargin = (opts) => {
  const { noColor, noTimestamps, expandErrors, severity } = opts;
  const colorize = (arg, i) => {
    if (noColor) return arg;
    let color = ['gray'][i % 1];
    if (i === 1) color = colors[severity];
    return chalk[color](arg);
  };
  const log = function() {
    const args = Array.from(arguments)
      .map((it) => (it instanceof Error && !expandErrors ?
        `${it.name}: ${it.message}` :
        it))
      .map((it) => (it instanceof Object && !(it instanceof Error) ?
        JSON.stringify(it) :
        it));
    const now = new Date().toISOString().replace(/T/, ' ').replace(/Z$/, '');
    const caller = traceCaller(new Error().stack);
    const message = util.format(...args);
    const line = [
      colorize(severity.charAt(0).toUpperCase(), 1),
      !noTimestamps ? colorize(now, 0) : null,
      colorize(caller, 1),
      message,
      log.newLine
    ].filter((it) => !!it).join('  ');
    process.stdout.write(line);
  };
  log.newLine = '\n';
  return log;
};

class Largin {
  static newInstance(opts) {
    instance = null;
    return Largin.instance(opts);
  }

  static instance(opts) {
    opts = opts || {
      noColor: false,
      noTimestamps: false,
      expandErrors: false
    };
    if (instance instanceof Largin) return instance;
    instance = new Largin();
    Object.keys(colors).forEach((severity) => {
      opts.severity = severity;
      instance[severity] = flargin(opts);
    });
    module.exports = instance;
    return instance;
  }
}

module.exports = Largin;
<|endoftext|>


<commit_before>'use strict';

/**
 * Export `EventEmitter`
 *
 * @param {Object} config (optional)
 * @return {EventEmitter}
 */
var EventEmitter = module.exports = function (config) {
  this.tree = {'children': {}};
  this.delimiter = (config || {}).delimiter || '.';
};

/**
 * Call all callbacks for given tree
 *
 * @see #_searchTree();
 *
 * @param {Object} tree
 * @param {arguments} args
 */
EventEmitter.prototype._emit = function (tree, args) {
  var callbacks = tree.callbacks;

  if (! callbacks) {
    return this;
  }

  var argc = args.length;

  for (
    var i = 0,
    len = callbacks.length,
    callback;
    i < len;
    i += 1
  ) {
    callback = callbacks[i];

    if (argc === 1) {
      callback.fn.call(callback.context, args[0]);
    } else if (argc === 2) {
      callback.fn.call(callback.context, args[0], args[1]);
    } else {
      callback.fn.apply(callback.context, args);
    }

    if (callback.once) {
      callbacks.splice(i, 1);

      if (callbacks.length === 0) {
        tree.callbacks = undefined;
      }
    }
  }
};

/**
 * Parse given tree for given ns
 *
 * @see #emit();
 *
 * @param {Object} tree
 * @param {Array} ns
 * @param {Integer} start
 * @param {arguments} args
 */
EventEmitter.prototype._searchTree = function (tree, ns, start, args) {
  for (var i = start,
    len = ns.length,
    currentNs,
    currentTree,
    wildTree;
    i < len;
    i += 1
  ) {
    wildTree = tree.children['*'];

    if (wildTree) {
      if (wildTree.callbacks) {
        this._emit(wildTree, args);
      }

      this._searchTree(wildTree, ns, i + 1, args);
    }

    currentNs = ns[i];
    currentTree = tree.children[currentNs];

    if (! currentTree) {
      return this;
    }

    tree = currentTree;
  }

  if (currentTree) {
    this._emit(currentTree, args);
  }
};

/**
 * Add event listener
 *
 * @param {String} ns
 * @param {Function} callback
 * @param {Object} options (optional)
 * @return {EventEmitter}
 */
EventEmitter.prototype.on = function (ns, callback, context, once) {
  ns = ns.split(this.delimiter);
  var tree = this.tree;
  var currentNs;
  var currentTree;

  for (var i = 0, len = ns.length; i < len; i += 1) {
    currentNs = ns[i];
    currentTree = tree.children[currentNs];

    if (! currentTree) {
      currentTree = tree.children[currentNs] = {'children': {}};
    }

    tree = currentTree;
  }

  if (! tree.callbacks) {
    tree.callbacks = [];
  }

  tree.callbacks.push({
    'fn': callback,
    'context': context ? context : this,
    'once': !! once
  });

  return this;
};

/**
 * Remove event listener
 *
 * @param {String} ns
 * @param {Function} callback
 * @param {Object} options (optional)
 * @return {EventEmitter}
 */
EventEmitter.prototype.off = function (ns, callback, context) {
  if (! ns) {
    this.tree = {'children': {}};

    return this;
  }

  ns = ns.split(this.delimiter);
  var tree = this.tree;
  var currentTree;

  for (var i = 0, len = ns.length; i < len; i += 1) {
    currentTree = tree.children[ns[i]];

    if (! currentTree) {
      return this;
    }

    tree = currentTree;
  }

  if (! callback) {
    tree.callbacks = undefined;

    return this;
  }

  if (! tree.callbacks) {
    return this;
  }

  for (
    var i2 = 0,
    callbacks = tree.callbacks,
    len2 = callbacks.length,
    currentCallback;
    i2 < len2;
    i2 += 1
  ) {
    currentCallback = callbacks[i2];

    if (currentCallback.fn === callback) {
      if (context && context !== currentCallback.context) {
        continue;
      }

      callbacks.splice(i2, 1);

      break;
    }
  }

  if (! callbacks.length) {
    tree.callbacks = undefined;
  }

  return this;
};

/**
 * Emit event
 *
 * @param {String} ns
 * @param {*} ... (optional)
 * @return {EventEmitter}
 */
EventEmitter.prototype.emit = function (ns) {
  ns = ns.split(this.delimiter);

  this._searchTree(this.tree, ns, 0, arguments);

  return this;
};

/**
 * Add event listener for once
 *
 * @param {String} ns
 * @param {Function} callback
 * @param {Object} options (optional)
 * @return {EventEmitter}
 */
EventEmitter.prototype.once = function (ns, callback, context) {
  this.on(ns, callback, context, true);

  return this;
};
<commit_msg>Fixed multiple listeners with `once()`<commit_after>'use strict';

/**
 * Export `EventEmitter`
 *
 * @param {Object} config (optional)
 * @return {EventEmitter}
 */
var EventEmitter = module.exports = function (config) {
  this.tree = {'children': {}};
  this.delimiter = (config || {}).delimiter || '.';
};

/**
 * Call all callbacks for given tree
 *
 * @see #_searchTree();
 *
 * @param {Object} tree
 * @param {arguments} args
 */
EventEmitter.prototype._emit = function (tree, args) {
  var callbacks = tree.callbacks;

  if (! callbacks) {
    return this;
  }

  var argc = args.length;

  for (
    var i = 0,
    len = callbacks.length,
    callback;
    i < len;
    i += 1
  ) {
    callback = callbacks[i];

    if (argc === 1) {
      callback.fn.call(callback.context, args[0]);
    } else if (argc === 2) {
      callback.fn.call(callback.context, args[0], args[1]);
    } else {
      callback.fn.apply(callback.context, args);
    }

    if (callback.once) {
      callbacks.splice(i, 1);

      i -= 1;
      len -= 1;

      if (callbacks.length === 0) {
        tree.callbacks = undefined;
      }
    }
  }
};

/**
 * Parse given tree for given ns
 *
 * @see #emit();
 *
 * @param {Object} tree
 * @param {Array} ns
 * @param {Integer} start
 * @param {arguments} args
 */
EventEmitter.prototype._searchTree = function (tree, ns, start, args) {
  for (var i = start,
    len = ns.length,
    currentNs,
    currentTree,
    wildTree;
    i < len;
    i += 1
  ) {
    wildTree = tree.children['*'];

    if (wildTree) {
      if (wildTree.callbacks) {
        this._emit(wildTree, args);
      }

      this._searchTree(wildTree, ns, i + 1, args);
    }

    currentNs = ns[i];
    currentTree = tree.children[currentNs];

    if (! currentTree) {
      return this;
    }

    tree = currentTree;
  }

  if (currentTree) {
    this._emit(currentTree, args);
  }
};

/**
 * Add event listener
 *
 * @param {String} ns
 * @param {Function} callback
 * @param {Object} options (optional)
 * @return {EventEmitter}
 */
EventEmitter.prototype.on = function (ns, callback, context, once) {
  ns = ns.split(this.delimiter);
  var tree = this.tree;
  var currentNs;
  var currentTree;

  for (var i = 0, len = ns.length; i < len; i += 1) {
    currentNs = ns[i];
    currentTree = tree.children[currentNs];

    if (! currentTree) {
      currentTree = tree.children[currentNs] = {'children': {}};
    }

    tree = currentTree;
  }

  if (! tree.callbacks) {
    tree.callbacks = [];
  }

  tree.callbacks.push({
    'fn': callback,
    'context': context ? context : this,
    'once': !! once
  });

  return this;
};

/**
 * Remove event listener
 *
 * @param {String} ns
 * @param {Function} callback
 * @param {Object} options (optional)
 * @return {EventEmitter}
 */
EventEmitter.prototype.off = function (ns, callback, context) {
  if (! ns) {
    this.tree = {'children': {}};

    return this;
  }

  ns = ns.split(this.delimiter);
  var tree = this.tree;
  var currentTree;

  for (var i = 0, len = ns.length; i < len; i += 1) {
    currentTree = tree.children[ns[i]];

    if (! currentTree) {
      return this;
    }

    tree = currentTree;
  }

  if (! callback) {
    tree.callbacks = undefined;

    return this;
  }

  if (! tree.callbacks) {
    return this;
  }

  for (
    var i2 = 0,
    callbacks = tree.callbacks,
    len2 = callbacks.length,
    currentCallback;
    i2 < len2;
    i2 += 1
  ) {
    currentCallback = callbacks[i2];

    if (currentCallback.fn === callback) {
      if (context && context !== currentCallback.context) {
        continue;
      }

      callbacks.splice(i2, 1);

      break;
    }
  }

  if (! callbacks.length) {
    tree.callbacks = undefined;
  }

  return this;
};

/**
 * Emit event
 *
 * @param {String} ns
 * @param {*} ... (optional)
 * @return {EventEmitter}
 */
EventEmitter.prototype.emit = function (ns) {
  ns = ns.split(this.delimiter);

  this._searchTree(this.tree, ns, 0, arguments);

  return this;
};

/**
 * Add event listener for once
 *
 * @param {String} ns
 * @param {Function} callback
 * @param {Object} options (optional)
 * @return {EventEmitter}
 */
EventEmitter.prototype.once = function (ns, callback, context) {
  this.on(ns, callback, context, true);

  return this;
};
<|endoftext|>


<commit_before>// --------------------------------------------------------------------------------------------------------------------
//
// statto-backend-leveldb/index.js
//
// Copyright 2015 Tynio Ltd.
//
// --------------------------------------------------------------------------------------------------------------------

// core
var crypto = require('crypto')

// npm
var async = require('async')

// --------------------------------------------------------------------------------------------------------------------

var queue = async.queue()
var FIELD_SEP = '~'
var FIELD_END = '\xff'

function StattoBackendLevelDB(db) {
  this.db = db
  this.queue = async.queue(this.process.bind(this), 1)
}

StattoBackendLevelDB.prototype.stats = function stats(stats) {
  var self = this

  console.log('=== %s ===', stats.ts)
  console.log(JSON.stringify(stats, null, '  '))

  // Let's use async to store these things up, just in case it takes longer to process than
  // before the next one comes in ... in which case, you're in trouble!!!
  this.queue.push(stats)
}

StattoBackendLevelDB.prototype.process = function process(stats, done) {
  var self = this

  console.log('Processing:', JSON.stringify(stats, null, '  '))

  // figure out the SHA1 of these stats (should be unique due to 'ts' and 'info.pid' and 'info.host'
  var str = JSON.stringify(stats)
  var hash = crypto.createHash('sha1').update(str).digest('hex')

  // firstly, see if this file has already been started (ie. check the hash)
  var fileKeyBeg = makeFileKey(stats.ts, hash, 'beg')
  var fileKeyDat = makeFileKey(stats.ts, hash, 'dat')
  var fileKeyEnd = makeFileKey(stats.ts, hash, 'end')
  self.db.get(fileKeyBeg, function(err, val) {
    if (err) {
      if ( err.type !== 'NotFoundError' ) {
        return done(err)
      }
    }

    if (!err) {
      console.log('This file has already been processed')
      done()
    }

    // process this file
    console.log('Processing Stats ...')

    var ops = [
      { type : 'put', key : fileKeyBeg, value : (new Date()).toISOString() },
      { type : 'put', key : fileKeyDat, value : JSON.stringify(stats) },
    ]
    self.db.batch(ops, function(err) {
      if (err) return done(err)
      console.log('Set started on this file')

      // process the counters first
      async.parallel(
        [
          self.processCounters.bind(self, stats.ts, stats.counters),
          self.processTimers.bind(self, stats.ts, stats.timers),
        ],
        function(err) {
          console.log('Finished Processing Stats')

          // let's record that this has finished
          self.db.put(fileKeyEnd, (new Date()).toISOString(), function(err) {
            if (err) return done(err)
            done()
          })
        }
      )
    })
  })
}

StattoBackendLevelDB.prototype.processCounters = function processCounters(ts, counters, done) {
  var self = this

  console.log('Processing counters ...')

  var keys = Object.keys(counters)
  async.each(
    keys,
    function(name, done) {
      var key = makeCounterKey(name, ts)
      self.db.get(key, function(err, val) {
        if (err) {
          if (err.type == 'NotFoundError') {
            return self.db.put(key, counters[name], done)
          }
          return done(err)
        }
        return self.db.put(key, val + counters[name], done)
      })
    },
    done
  )
}

StattoBackendLevelDB.prototype.processTimers = function processTimers(ts, timers, done) {
  console.log('Processing timers ...')
  console.log(timers)
  process.nextTick(function() {
    console.log('Done timers')
    done()
  })
}

StattoBackendLevelDB.prototype.dump = function dump() {
  var self = this
}

// --------------------------------------------------------------------------------------------------------------------
// utility functions

function makeFileKey(ts, hash, type) {
  return 'f' + FIELD_SEP + ts + FIELD_SEP + hash + FIELD_SEP + type
}

function makeCounterKey(name, ts) {
  return 'c' + FIELD_SEP + name + FIELD_SEP + ts
}

// --------------------------------------------------------------------------------------------------------------------

module.exports = function backend(db, opts) {
  if ( !db ) {
    throw new Error('Required: db in statto-backend-leveldb')
  }

  return new StattoBackendLevelDB(db)
}

// --------------------------------------------------------------------------------------------------------------------
<commit_msg>Process gauges<commit_after>// --------------------------------------------------------------------------------------------------------------------
//
// statto-backend-leveldb/index.js
//
// Copyright 2015 Tynio Ltd.
//
// --------------------------------------------------------------------------------------------------------------------

// core
var crypto = require('crypto')

// npm
var async = require('async')

// --------------------------------------------------------------------------------------------------------------------

var queue = async.queue()
var FIELD_SEP = '~'
var FIELD_END = '\xff'

function StattoBackendLevelDB(db) {
  this.db = db
  this.queue = async.queue(this.process.bind(this), 1)
}

StattoBackendLevelDB.prototype.stats = function stats(stats) {
  var self = this

  console.log('=== %s ===', stats.ts)
  console.log(JSON.stringify(stats, null, '  '))

  // Let's use async to store these things up, just in case it takes longer to process than
  // before the next one comes in ... in which case, you're in trouble!!!
  this.queue.push(stats)
}

StattoBackendLevelDB.prototype.process = function process(stats, done) {
  var self = this

  console.log('Processing:', JSON.stringify(stats, null, '  '))

  // figure out the SHA1 of these stats (should be unique due to 'ts' and 'info.pid' and 'info.host'
  var str = JSON.stringify(stats)
  var hash = crypto.createHash('sha1').update(str).digest('hex')

  // firstly, see if this file has already been started (ie. check the hash)
  var fileKeyBeg = makeFileKey(stats.ts, hash, 'beg')
  var fileKeyDat = makeFileKey(stats.ts, hash, 'dat')
  var fileKeyEnd = makeFileKey(stats.ts, hash, 'end')
  self.db.get(fileKeyBeg, function(err, val) {
    if (err) {
      if ( err.type !== 'NotFoundError' ) {
        return done(err)
      }
    }

    if (!err) {
      console.log('This file has already been processed')
      done()
    }

    // process this file
    console.log('Processing Stats ...')

    var ops = [
      { type : 'put', key : fileKeyBeg, value : (new Date()).toISOString() },
      { type : 'put', key : fileKeyDat, value : JSON.stringify(stats) },
    ]
    self.db.batch(ops, function(err) {
      if (err) return done(err)
      console.log('Set started on this file')

      // process the counters first
      async.parallel(
        [
          self.processCounters.bind(self, stats.ts, stats.counters),
          self.processTimers.bind(self, stats.ts, stats.timers),
          self.processGauges.bind(self, stats.ts, stats.gauges),
        ],
        function(err) {
          console.log('Finished Processing Stats')

          // let's record that this has finished
          self.db.put(fileKeyEnd, (new Date()).toISOString(), function(err) {
            if (err) return done(err)
            done()
          })
        }
      )
    })
  })
}

StattoBackendLevelDB.prototype.processCounters = function processCounters(ts, counters, done) {
  var self = this

  console.log('Processing counters ...')

  var keys = Object.keys(counters)
  async.each(
    keys,
    function(name, done) {
      var key = makeCounterKey(name, ts)
      self.db.get(key, function(err, val) {
        if (err) {
          if (err.type == 'NotFoundError') {
            return self.db.put(key, counters[name], done)
          }
          return done(err)
        }
        return self.db.put(key, val + counters[name], done)
      })
    },
    done
  )
}

StattoBackendLevelDB.prototype.processTimers = function processTimers(ts, timers, done) {
  console.log('Processing timers ...')
  console.log(timers)

  var keys = Object.keys(timers)

  process.nextTick(function() {
    console.log('Done timers')
    done()
  })
}

StattoBackendLevelDB.prototype.processGauges = function processGauges(ts, gauges, done) {
  var self = this

  console.log('Processing gauges ...')

  // If we have processed a file from a different machine already, then we don't care if a gauge gets overwritten with
  // this info or not. ie. we don't care which one is processed last in this period, since it really shouldn't affect
  // things. This is true of any collector sending a gauge to a daemon anyway, the last measurement wins.

  var keys = Object.keys(gauges)
  async.each(
    keys,
    function(name, done) {
      var key = makeGaugeKey(name, ts)
      self.db.put(key, gauges[name], done)
    },
    done
  )
}

// --------------------------------------------------------------------------------------------------------------------
// utility functions

function makeFileKey(ts, hash, type) {
  return 'f' + FIELD_SEP + ts + FIELD_SEP + hash + FIELD_SEP + type
}

function makeCounterKey(name, ts) {
  return 'c' + FIELD_SEP + name + FIELD_SEP + ts
}

function makeGaugeKey(name, ts) {
  return 'g' + FIELD_SEP + name + FIELD_SEP + ts
}

// --------------------------------------------------------------------------------------------------------------------

module.exports = function backend(db, opts) {
  if ( !db ) {
    throw new Error('Required: db in statto-backend-leveldb')
  }

  return new StattoBackendLevelDB(db)
}

// --------------------------------------------------------------------------------------------------------------------
<|endoftext|>


<commit_before>#!/usr/bin/env node

'use strict';
var path = require('path');
var gutil = require('gulp-util');
var chalk = require('chalk');
var nomnom = require('nomnom');
var semver = require('semver');
var Liftoff = require('liftoff');
var tildify = require('tildify');
var interpret = require('interpret');
var v8flags = require('v8flags');
var exit = require('./lib/exit');
var cliOptions = require('./lib/cliOptions');
var completion = require('./lib/completion');
var verifyDeps = require('./lib/verifyDependencies');
var cliVersion = require('./package.json').version;
var getBlacklist = require('./lib/getBlacklist');

// Logging functions
var logVerify = require('./lib/log/verify');
var logBlacklistError = require('./lib/log/blacklistError');

// Set env var for ORIGINAL cwd
// before anything touches it
process.env.INIT_CWD = process.cwd();

var cli = new Liftoff({
  name: 'gulp',
  completions: completion,
  extensions: interpret.jsVariants,
  v8flags: v8flags,
});

var opts = nomnom
  .script('gulp')
  .options(cliOptions)
  .parse();
var tasks = opts._;
var toRun = tasks.length ? tasks : ['default'];

// This is a hold-over until we have a better logging system
// with log levels
var shouldLog = !opts.silent && !opts.tasksSimple;

if (!shouldLog) {
  gutil.log = function() {};
}

cli.on('require', function(name) {
  gutil.log('Requiring external module', chalk.magenta(name));
});

cli.on('requireFail', function(name) {
  gutil.log(chalk.red('Failed to load external module'), chalk.magenta(name));
});

cli.on('respawn', function(flags, child) {
  var nodeFlags = chalk.magenta(flags.join(', '));
  var pid = chalk.magenta(child.pid);
  gutil.log('Node flags detected:', nodeFlags);
  gutil.log('Respawned to PID:', pid);
});

function run() {
  cli.launch({
    cwd: opts.cwd,
    configPath: opts.gulpfile,
    require: opts.require,
    completion: opts.completion,
  }, handleArguments);
}

module.exports = run;

// The actual logic
function handleArguments(env) {
  if (opts.version) {
    gutil.log('CLI version', cliVersion);
    if (env.modulePackage && typeof env.modulePackage.version !== 'undefined') {
      gutil.log('Local version', env.modulePackage.version);
    }
    exit(0);
  }

  if (opts.verify) {
    var pkgPath = opts.verify !== true ? opts.verify : 'package.json';
    if (path.resolve(pkgPath) !== path.normalize(pkgPath)) {
      pkgPath = path.join(env.configBase, pkgPath);
    }
    gutil.log('Verifying plugins in ' + pkgPath);
    return getBlacklist(function(err, blacklist) {
      if (err) {
        return logBlacklistError(err);
      }

      var blacklisted = verifyDeps(require(pkgPath), blacklist);

      logVerify(blacklisted);
    });
  }

  if (!env.modulePath) {
    gutil.log(
      chalk.red('Local gulp not found in'),
      chalk.magenta(tildify(env.cwd))
    );
    gutil.log(chalk.red('Try running: npm install gulp'));
    exit(1);
  }

  if (!env.configPath) {
    gutil.log(chalk.red('No gulpfile found'));
    exit(1);
  }

  // Check for semver difference between cli and local installation
  if (semver.gt(cliVersion, env.modulePackage.version)) {
    gutil.log(chalk.red('Warning: gulp version mismatch:'));
    gutil.log(chalk.red('Global gulp is', cliVersion));
    gutil.log(chalk.red('Local gulp is', env.modulePackage.version));
  }

  // Chdir before requiring gulpfile to make sure
  // we let them chdir as needed
  if (process.cwd() !== env.cwd) {
    process.chdir(env.cwd);
    gutil.log(
      'Working directory changed to',
      chalk.magenta(tildify(env.cwd))
    );
  }

  if (semver.satisfies(env.modulePackage.version, '^3')) {
    return gulp3(env);
  }

  if (semver.satisfies(env.modulePackage.version, '^4')) {
    return gulp4(env);
  }
}

function gulp3(env) {
  var logTasks = require('./lib/3/logTasks');
  var logEvents = require('./lib/3/logEvents');
  var logTasksSimple = require('./lib/3/logTasksSimple');

  // This is what actually loads up the gulpfile
  require(env.configPath);
  gutil.log('Using gulpfile', chalk.magenta(tildify(env.configPath)));

  var gulpInst = require(env.modulePath);
  logEvents(gulpInst);

  process.nextTick(function() {
    if (opts.tasksSimple) {
      return logTasksSimple(env, gulpInst);
    }
    if (opts.tasks) {
      return logTasks(env, gulpInst);
    }
    gulpInst.start.apply(gulpInst, toRun);
  });
}

function gulp4(env) {
  var logTasks = require('./lib/log/tasks');
  var logEvents = require('./lib/logEvents');
  var logTasksSimple = require('./lib/log/tasksSimple');

  var gulpInst = require(env.modulePath);
  logEvents(gulpInst);

  // This is what actually loads up the gulpfile
  require(env.configPath);

  process.nextTick(function() {
    if (opts.tasksSimple) {
      return logTasksSimple(gulpInst.tree());
    }
    if (opts.tasks) {
      var tree = {
        label: 'Tasks for ' + chalk.magenta(tildify(env.configPath)),
        nodes: gulpInst.tree({ deep: true }),
      };
      return logTasks(tree);
    }
    if (opts.tasksJson) {
      return console.log(
        JSON.stringify(gulpInst.tree({ deep: true }), null, 2)
      );
    }
    try {
      gutil.log('Using gulpfile', chalk.magenta(tildify(env.configPath)));
      // TODO: do we care about the error/result from calling this?
      gulpInst.parallel(toRun)();
    } catch (err) {
      gutil.log(chalk.red(err.message));
      gutil.log(
        'Please check the documentation for proper gulpfile formatting'
      );
      exit(1);
    }
  });
}
<commit_msg>Fix: Use proper require path<commit_after>#!/usr/bin/env node

'use strict';
var path = require('path');
var gutil = require('gulp-util');
var chalk = require('chalk');
var nomnom = require('nomnom');
var semver = require('semver');
var Liftoff = require('liftoff');
var tildify = require('tildify');
var interpret = require('interpret');
var v8flags = require('v8flags');
var exit = require('./lib/exit');
var cliOptions = require('./lib/cliOptions');
var completion = require('./lib/completion');
var verifyDeps = require('./lib/verifyDependencies');
var cliVersion = require('./package.json').version;
var getBlacklist = require('./lib/getBlacklist');

// Logging functions
var logVerify = require('./lib/log/verify');
var logBlacklistError = require('./lib/log/blacklistError');

// Set env var for ORIGINAL cwd
// before anything touches it
process.env.INIT_CWD = process.cwd();

var cli = new Liftoff({
  name: 'gulp',
  completions: completion,
  extensions: interpret.jsVariants,
  v8flags: v8flags,
});

var opts = nomnom
  .script('gulp')
  .options(cliOptions)
  .parse();
var tasks = opts._;
var toRun = tasks.length ? tasks : ['default'];

// This is a hold-over until we have a better logging system
// with log levels
var shouldLog = !opts.silent && !opts.tasksSimple;

if (!shouldLog) {
  gutil.log = function() {};
}

cli.on('require', function(name) {
  gutil.log('Requiring external module', chalk.magenta(name));
});

cli.on('requireFail', function(name) {
  gutil.log(chalk.red('Failed to load external module'), chalk.magenta(name));
});

cli.on('respawn', function(flags, child) {
  var nodeFlags = chalk.magenta(flags.join(', '));
  var pid = chalk.magenta(child.pid);
  gutil.log('Node flags detected:', nodeFlags);
  gutil.log('Respawned to PID:', pid);
});

function run() {
  cli.launch({
    cwd: opts.cwd,
    configPath: opts.gulpfile,
    require: opts.require,
    completion: opts.completion,
  }, handleArguments);
}

module.exports = run;

// The actual logic
function handleArguments(env) {
  if (opts.version) {
    gutil.log('CLI version', cliVersion);
    if (env.modulePackage && typeof env.modulePackage.version !== 'undefined') {
      gutil.log('Local version', env.modulePackage.version);
    }
    exit(0);
  }

  if (opts.verify) {
    var pkgPath = opts.verify !== true ? opts.verify : 'package.json';
    if (path.resolve(pkgPath) !== path.normalize(pkgPath)) {
      pkgPath = path.join(env.configBase, pkgPath);
    }
    gutil.log('Verifying plugins in ' + pkgPath);
    return getBlacklist(function(err, blacklist) {
      if (err) {
        return logBlacklistError(err);
      }

      var blacklisted = verifyDeps(require(pkgPath), blacklist);

      logVerify(blacklisted);
    });
  }

  if (!env.modulePath) {
    gutil.log(
      chalk.red('Local gulp not found in'),
      chalk.magenta(tildify(env.cwd))
    );
    gutil.log(chalk.red('Try running: npm install gulp'));
    exit(1);
  }

  if (!env.configPath) {
    gutil.log(chalk.red('No gulpfile found'));
    exit(1);
  }

  // Check for semver difference between cli and local installation
  if (semver.gt(cliVersion, env.modulePackage.version)) {
    gutil.log(chalk.red('Warning: gulp version mismatch:'));
    gutil.log(chalk.red('Global gulp is', cliVersion));
    gutil.log(chalk.red('Local gulp is', env.modulePackage.version));
  }

  // Chdir before requiring gulpfile to make sure
  // we let them chdir as needed
  if (process.cwd() !== env.cwd) {
    process.chdir(env.cwd);
    gutil.log(
      'Working directory changed to',
      chalk.magenta(tildify(env.cwd))
    );
  }

  if (semver.satisfies(env.modulePackage.version, '^3')) {
    return gulp3(env);
  }

  if (semver.satisfies(env.modulePackage.version, '^4')) {
    return gulp4(env);
  }
}

function gulp3(env) {
  var logTasks = require('./lib/3/logTasks');
  var logEvents = require('./lib/3/logEvents');
  var logTasksSimple = require('./lib/3/logTasksSimple');

  // This is what actually loads up the gulpfile
  require(env.configPath);
  gutil.log('Using gulpfile', chalk.magenta(tildify(env.configPath)));

  var gulpInst = require(env.modulePath);
  logEvents(gulpInst);

  process.nextTick(function() {
    if (opts.tasksSimple) {
      return logTasksSimple(env, gulpInst);
    }
    if (opts.tasks) {
      return logTasks(env, gulpInst);
    }
    gulpInst.start.apply(gulpInst, toRun);
  });
}

function gulp4(env) {
  var logTasks = require('./lib/log/tasks');
  var logEvents = require('./lib/log/events');
  var logTasksSimple = require('./lib/log/tasksSimple');

  var gulpInst = require(env.modulePath);
  logEvents(gulpInst);

  // This is what actually loads up the gulpfile
  require(env.configPath);

  process.nextTick(function() {
    if (opts.tasksSimple) {
      return logTasksSimple(gulpInst.tree());
    }
    if (opts.tasks) {
      var tree = {
        label: 'Tasks for ' + chalk.magenta(tildify(env.configPath)),
        nodes: gulpInst.tree({ deep: true }),
      };
      return logTasks(tree);
    }
    if (opts.tasksJson) {
      return console.log(
        JSON.stringify(gulpInst.tree({ deep: true }), null, 2)
      );
    }
    try {
      gutil.log('Using gulpfile', chalk.magenta(tildify(env.configPath)));
      // TODO: do we care about the error/result from calling this?
      gulpInst.parallel(toRun)();
    } catch (err) {
      gutil.log(chalk.red(err.message));
      gutil.log(
        'Please check the documentation for proper gulpfile formatting'
      );
      exit(1);
    }
  });
}
<|endoftext|>