<commit_before>// Copyright 2014, Renasar Technologies Inc.
/* jshint node: true, newcap: false */
'use strict';

var di = require('di'),
    trace = require('stack-trace'),
    pretty = require('prettyjson'),
    colors = require('colors/safe');

module.exports = loggerFactory;

di.annotate(loggerFactory, new di.Provide('Logger'));
di.annotate(loggerFactory,
    new di.Inject(
        'Constants',
        'Services.Configuration',
        'Q',
        '_',
        di.Injector
    )
);

/**
 * loggerFactory returns a Logger instance.
 * @private
 * @param  {postal} postal Postal Instance.
 * * @param  {configuration} configuration Configuration Instance.
 * * @param  {Q} Q Q Instance.
 * * @param  {di.Injector} injector Dependency Injector.
 * @return {Logger} a Logger instance.
 */
function loggerFactory(Constants, configuration, Q, _, injector) {
    var levels = {
        emerg: 8,
        alert: 7,
        crit: 6,
        error: 5,
        warning: 4,
        notice: 3,
        info: 2,
        debug: 1,
        silly: 0
    };

    colors.setTheme({
      emerg: 'red',
      alert: 'yellow',
      crit: 'red',
      error: 'red',
      warning: 'red',
      notice: 'yellow',
      info: 'green',
      debug: 'blue',
      silly: 'rainbow'
    });

    var baseDirectory = process.cwd();

    var redacted = [
        'id',
        Constants.LOGGER_EVENT_META_ID,
        Constants.LOGGER_EVENT_META_IDENTIFIER,
        Constants.LOGGER_EVENT_META_IP,
        Constants.LOGGER_EVENT_META_MACADDRESS
    ];

    /**
     * Logger is a logger class which provides methods for logging based
     * on log levels with mesages & metadata provisions.  The Logger sends
     * all log method calls to the logger postal channel for consumption by other
     * services.
     *  logger.info('Your message here...', { hello: 'world', arbitrary: 'meta data object'});
     * @constructor
     */
    function Logger (context) {
        this.context = context !== undefined ? context.toString() : 'No Context';

        if (_.isFunction(context)) {
            if (context.annotations && context.annotations.length) {
                var provides = _.detect(context.annotations, function (annotation) {
                    return _.has(annotation, 'token');
                });

                if (provides) {
                    this.context = provides.token;
                    return;
                }
            }
        }

        console.log(this.context);
    }

    /**
     * log
     * @param {string} level Log Level
     * @param {string} message Log Message
     * @param {object} metadata Log Metadata (Optional)
     */
    Logger.prototype.log = function () {
        this._log.apply(this, Array.prototype.slice.call(arguments));
    };

    /**
     * _log
     * @param {string} level Log Level
     * @param {string} message Log Message
     * @param {object} metadata Log Metadata (Optional)
     * @private
     */
    Logger.prototype._log = function () {
        var self = this;

        this._parse(
            _.flatten(Array.prototype.slice.call(arguments))
        ).then(function (args) {
            return self._translate(args);
        }).then(function (args) {
            return self._write(args);
        }).then(function (args) {
            return self._publish(args);
        }).fail(function (err) {
            self.error(err.message, { error: err });
        });
    };

    _.keys(levels).forEach(function(level) {
        /**
         * level - Helper method to allow logging by using the specific level
         * as the method instead of calling log directly.
         * @param {string} message Log Message
         * @param {object} metadata Log Metadata (Optional)
         */
        Logger.prototype[level] = function () {
            var args = Array.prototype.slice.call(arguments);
            args.unshift(level);
            this._log.apply(this, args);
        };
    });

    /**
     * Converts the provided arguments into an object for further processing.
     * @private
     * @param  {array} args Array of arguments to the original call.
     * @return {object} An object for further processing.
     */
    Logger.prototype._parse = function(args) {
        args = args || [];

        var parsed = {};

        // Get the level from the caller.
        parsed.level = args.shift();

        // Verify the level
        if (!_.contains(_.keys(levels), parsed.level)) {
            args.unshift(parsed.level);

            // Set the level to invalid so we can root out bad log calls.
            parsed.level = 'invalid';
        }

        // Set a timestamp.
        parsed.timestamp = new Date().toISOString();

        // Get the message.
        parsed.message = args.shift();

        // Get the meta data similar to how Winston worked.
        if (_.isObject(args[args.length - 1])) {
            parsed.meta = args.pop();
        }

        // Leftover arguments from legacy calls.
        if (args.length) {
            parsed.message = _.flatten([ parsed.message, args ]);
        }

        if (configuration.get('verbose')) {
            parsed.caller = this._getCaller(4);
        }

        return Q.resolve(parsed);
    };

    /**
     * Translates the meta data from the call into an identifier and returns the updated args.
     * @private
     * @param  {object} args Object from the parse call.
     * @return {object} Updated object from the parse call.
     */
    Logger.prototype._translate = function(args) {
        var self = this;

        if (args.meta === undefined) {
            return self._redact(args);
        }

        if (args.meta.id) {
            return self._redact(args, args.meta.id);
        }

        if (args.meta._id) {
            return self._redact(args, args.meta._id);
        }

        if (args.meta.identifier) {
            return self._redact(args, args.meta.identifier);
        }

        if (args.meta.macaddress) {
            return injector.get('lookup-service')
                .macAddressToNodeId(args.meta.macaddress).then(function (identifier) {
                    return self._redact(args, identifier);
                }).fail(function() {
                    return self._redact(args);
                });
        }

        if (args.meta.ip) {
            return injector.get('lookup-service')
                .ipAddressToNodeId(args.meta.ip).then(function (identifier) {
                    return self._redact(args, identifier);
                }).fail(function() {
                    return self._redact(args);
                });
        }

        return self._redact(args);
    };

    /**
     * Writes the parsed object to the console and returns it.
     * @param  {object} args Object from the translate call.
     * @return {object} The object from the translate call.
     */
    Logger.prototype._write = function(args) {
        if (args.caller) {
            console.log(args.caller);
        }

        console.log(
            args.timestamp +
            ': ' +
            '[' + this.context + ']' +
            '[' + args.meta.identifier.substring(args.meta.identifier.length - 6) + '] ' +
            this._color(args.level) +
            ' ' + args.message
        );

        if (_.keys(_.omit(args.meta, 'identifier')).length !== 0) {
            console.log(
                pretty.render(
                    _.omit(args.meta, 'identifier'),
                    { noColor: !configuration.get('color') }
                )
            );
        }

        return Q.resolve(args);
    };

    /**
     * Publishess the parsed object to the postal channel and returns it.
     * @param  {object} args Object from the translate call.
     * @return {object} Object from the translate call.
     */
    Logger.prototype._publish = function(args) {
        // TODO: publish via Protocol.Http
        // postal.publish({
        //     channel: Constants.LOGGER_CHANNEL,
        //     topic: Constants.LOGGER_CHANNEL + '.' + args.level,
        //     data:  args
        // });

        return Q.resolve(args);
    };

    /**
     * Redacts the logging metadata and assigns the identifier.
     * @param  {object} args Object from the translate call.
     * @param  {string} identifier The identifier to use for the call.
     * @return {object} Object from translate call with fields redacted.
     */
    Logger.prototype._redact = function(args, identifier) {
        if (args.meta !== undefined) {
            args.meta = _.omit(args.meta, redacted);
        } else {
            args.meta = {};
        }

        args.meta.identifier = identifier || 'server';

        return Q.resolve(args);
    };

    /**
     * _getCaller returns the calling file:line for the original caller of the log statement.
     * @private
     * @return {string} file:line
     */
    Logger.prototype._getCaller = function (depth) {
        var current = trace.get()[depth];

        var file = current.getFileName().replace(baseDirectory, '') + ':' + current.getLineNumber();

        return file.replace(/^node_modules/, '');
    };

    /**
     * _filtered returns whether the requested log level is less than the configured
     * log level thus providing an opportunity for filtering out statements based on
     * level.
     * @param  {string} level One of the available log levels.
     * @return {boolean} true if the log statement is eligible for filtering, false if not.
     */
    Logger.prototype._filtered = function (level) {
        var configured = levels[(configuration.get('level') || 'silly')],
            targeted = levels[level];

        if (configured !== undefined && targeted !== undefined) {
            return targeted < configured;
        } else {
            return false;
        }
    };

    /**
     * _color returns the requested level colored with the current theme if color is enabled.
     * @param  {string} level Log level.
     * @return {string}       Color enabled string suitable for console output.
     */
    Logger.prototype._color = function (level) {
        if (configuration.get('color')) {
            return colors[level](level);
        } else {
            return level;
        }
    };

    Logger.initialize = function (context) {
        return new Logger(context);
    };

    return Logger;
}<commit_msg>Update injector string references to lookup-service<commit_after>// Copyright 2014, Renasar Technologies Inc.
/* jshint node: true, newcap: false */
'use strict';

var di = require('di'),
    trace = require('stack-trace'),
    pretty = require('prettyjson'),
    colors = require('colors/safe');

module.exports = loggerFactory;

di.annotate(loggerFactory, new di.Provide('Logger'));
di.annotate(loggerFactory,
    new di.Inject(
        'Constants',
        'Services.Configuration',
        'Q',
        '_',
        di.Injector
    )
);

/**
 * loggerFactory returns a Logger instance.
 * @private
 * @param  {postal} postal Postal Instance.
 * * @param  {configuration} configuration Configuration Instance.
 * * @param  {Q} Q Q Instance.
 * * @param  {di.Injector} injector Dependency Injector.
 * @return {Logger} a Logger instance.
 */
function loggerFactory(Constants, configuration, Q, _, injector) {
    var levels = {
        emerg: 8,
        alert: 7,
        crit: 6,
        error: 5,
        warning: 4,
        notice: 3,
        info: 2,
        debug: 1,
        silly: 0
    };

    colors.setTheme({
      emerg: 'red',
      alert: 'yellow',
      crit: 'red',
      error: 'red',
      warning: 'red',
      notice: 'yellow',
      info: 'green',
      debug: 'blue',
      silly: 'rainbow'
    });

    var baseDirectory = process.cwd();

    var redacted = [
        'id',
        Constants.LOGGER_EVENT_META_ID,
        Constants.LOGGER_EVENT_META_IDENTIFIER,
        Constants.LOGGER_EVENT_META_IP,
        Constants.LOGGER_EVENT_META_MACADDRESS
    ];

    /**
     * Logger is a logger class which provides methods for logging based
     * on log levels with mesages & metadata provisions.  The Logger sends
     * all log method calls to the logger postal channel for consumption by other
     * services.
     *  logger.info('Your message here...', { hello: 'world', arbitrary: 'meta data object'});
     * @constructor
     */
    function Logger (context) {
        this.context = context !== undefined ? context.toString() : 'No Context';

        if (_.isFunction(context)) {
            if (context.annotations && context.annotations.length) {
                var provides = _.detect(context.annotations, function (annotation) {
                    return _.has(annotation, 'token');
                });

                if (provides) {
                    this.context = provides.token;
                    return;
                }
            }
        }

        console.log(this.context);
    }

    /**
     * log
     * @param {string} level Log Level
     * @param {string} message Log Message
     * @param {object} metadata Log Metadata (Optional)
     */
    Logger.prototype.log = function () {
        this._log.apply(this, Array.prototype.slice.call(arguments));
    };

    /**
     * _log
     * @param {string} level Log Level
     * @param {string} message Log Message
     * @param {object} metadata Log Metadata (Optional)
     * @private
     */
    Logger.prototype._log = function () {
        var self = this;

        this._parse(
            _.flatten(Array.prototype.slice.call(arguments))
        ).then(function (args) {
            return self._translate(args);
        }).then(function (args) {
            return self._write(args);
        }).then(function (args) {
            return self._publish(args);
        }).fail(function (err) {
            self.error(err.message, { error: err });
        });
    };

    _.keys(levels).forEach(function(level) {
        /**
         * level - Helper method to allow logging by using the specific level
         * as the method instead of calling log directly.
         * @param {string} message Log Message
         * @param {object} metadata Log Metadata (Optional)
         */
        Logger.prototype[level] = function () {
            var args = Array.prototype.slice.call(arguments);
            args.unshift(level);
            this._log.apply(this, args);
        };
    });

    /**
     * Converts the provided arguments into an object for further processing.
     * @private
     * @param  {array} args Array of arguments to the original call.
     * @return {object} An object for further processing.
     */
    Logger.prototype._parse = function(args) {
        args = args || [];

        var parsed = {};

        // Get the level from the caller.
        parsed.level = args.shift();

        // Verify the level
        if (!_.contains(_.keys(levels), parsed.level)) {
            args.unshift(parsed.level);

            // Set the level to invalid so we can root out bad log calls.
            parsed.level = 'invalid';
        }

        // Set a timestamp.
        parsed.timestamp = new Date().toISOString();

        // Get the message.
        parsed.message = args.shift();

        // Get the meta data similar to how Winston worked.
        if (_.isObject(args[args.length - 1])) {
            parsed.meta = args.pop();
        }

        // Leftover arguments from legacy calls.
        if (args.length) {
            parsed.message = _.flatten([ parsed.message, args ]);
        }

        if (configuration.get('verbose')) {
            parsed.caller = this._getCaller(4);
        }

        return Q.resolve(parsed);
    };

    /**
     * Translates the meta data from the call into an identifier and returns the updated args.
     * @private
     * @param  {object} args Object from the parse call.
     * @return {object} Updated object from the parse call.
     */
    Logger.prototype._translate = function(args) {
        var self = this;

        if (args.meta === undefined) {
            return self._redact(args);
        }

        if (args.meta.id) {
            return self._redact(args, args.meta.id);
        }

        if (args.meta._id) {
            return self._redact(args, args.meta._id);
        }

        if (args.meta.identifier) {
            return self._redact(args, args.meta.identifier);
        }

        if (args.meta.macaddress) {
            return injector.get('Services.Lookup')
                .macAddressToNodeId(args.meta.macaddress).then(function (identifier) {
                    return self._redact(args, identifier);
                }).fail(function() {
                    return self._redact(args);
                });
        }

        if (args.meta.ip) {
            return injector.get('Services.Lookup')
                .ipAddressToNodeId(args.meta.ip).then(function (identifier) {
                    return self._redact(args, identifier);
                }).fail(function() {
                    return self._redact(args);
                });
        }

        return self._redact(args);
    };

    /**
     * Writes the parsed object to the console and returns it.
     * @param  {object} args Object from the translate call.
     * @return {object} The object from the translate call.
     */
    Logger.prototype._write = function(args) {
        if (args.caller) {
            console.log(args.caller);
        }

        console.log(
            args.timestamp +
            ': ' +
            '[' + this.context + ']' +
            '[' + args.meta.identifier.substring(args.meta.identifier.length - 6) + '] ' +
            this._color(args.level) +
            ' ' + args.message
        );

        if (_.keys(_.omit(args.meta, 'identifier')).length !== 0) {
            console.log(
                pretty.render(
                    _.omit(args.meta, 'identifier'),
                    { noColor: !configuration.get('color') }
                )
            );
        }

        return Q.resolve(args);
    };

    /**
     * Publishess the parsed object to the postal channel and returns it.
     * @param  {object} args Object from the translate call.
     * @return {object} Object from the translate call.
     */
    Logger.prototype._publish = function(args) {
        // TODO: publish via Protocol.Http
        // postal.publish({
        //     channel: Constants.LOGGER_CHANNEL,
        //     topic: Constants.LOGGER_CHANNEL + '.' + args.level,
        //     data:  args
        // });

        return Q.resolve(args);
    };

    /**
     * Redacts the logging metadata and assigns the identifier.
     * @param  {object} args Object from the translate call.
     * @param  {string} identifier The identifier to use for the call.
     * @return {object} Object from translate call with fields redacted.
     */
    Logger.prototype._redact = function(args, identifier) {
        if (args.meta !== undefined) {
            args.meta = _.omit(args.meta, redacted);
        } else {
            args.meta = {};
        }

        args.meta.identifier = identifier || 'server';

        return Q.resolve(args);
    };

    /**
     * _getCaller returns the calling file:line for the original caller of the log statement.
     * @private
     * @return {string} file:line
     */
    Logger.prototype._getCaller = function (depth) {
        var current = trace.get()[depth];

        var file = current.getFileName().replace(baseDirectory, '') + ':' + current.getLineNumber();

        return file.replace(/^node_modules/, '');
    };

    /**
     * _filtered returns whether the requested log level is less than the configured
     * log level thus providing an opportunity for filtering out statements based on
     * level.
     * @param  {string} level One of the available log levels.
     * @return {boolean} true if the log statement is eligible for filtering, false if not.
     */
    Logger.prototype._filtered = function (level) {
        var configured = levels[(configuration.get('level') || 'silly')],
            targeted = levels[level];

        if (configured !== undefined && targeted !== undefined) {
            return targeted < configured;
        } else {
            return false;
        }
    };

    /**
     * _color returns the requested level colored with the current theme if color is enabled.
     * @param  {string} level Log level.
     * @return {string}       Color enabled string suitable for console output.
     */
    Logger.prototype._color = function (level) {
        if (configuration.get('color')) {
            return colors[level](level);
        } else {
            return level;
        }
    };

    Logger.initialize = function (context) {
        return new Logger(context);
    };

    return Logger;
}
<|endoftext|>


<commit_before>// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.com/#x15.4.4.19
if (!Array.prototype.map) {
    Array.prototype.map = function(callback, thisArg) {

        var T, A, k;

        if (this == null) {
            throw new TypeError(" this is null or not defined");
        }

        // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
        var O = Object(this);

        // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
        // 3. Let len be ToUint32(lenValue).
        var len = O.length >>> 0;

        // 4. If IsCallable(callback) is false, throw a TypeError exception.
        // See: http://es5.github.com/#x9.11
        if ({}.toString.call(callback) != "[object Function]") {
            throw new TypeError(callback + " is not a function");
        }

        // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if (thisArg) {
            T = thisArg;
        }

        // 6. Let A be a new array created as if by the expression new Array(len) where Array is
        // the standard built-in constructor with that name and len is the value of len.
        A = new Array(len);

        // 7. Let k be 0
        k = 0;

        // 8. Repeat, while k < len
        while(k < len) {

            var kValue, mappedValue;

            // a. Let Pk be ToString(k).
            //   This is implicit for LHS operands of the in operator
            // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
            //   This step can be combined with c
            // c. If kPresent is true, then
            if (k in O) {

                // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
                kValue = O[ k ];

                // ii. Let mappedValue be the result of calling the Call internal method of callback
                // with T as the this value and argument list containing kValue, k, and O.
                mappedValue = callback.call(T, kValue, k, O);

                // iii. Call the DefineOwnProperty internal method of A with arguments
                // Pk, Property Descriptor {Value: mappedValue, Writable: true, Enumerable: true, Configurable: true},
                // and false.

                // In browsers that support Object.defineProperty, use the following:
                // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });

                // For best browser support, use the following:
                A[ k ] = mappedValue;
            }
            // d. Increase k by 1.
            k++;
        }

        // 9. return A
        return A;
    };
}

// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.com/#x15.4.4.18
if ( !Array.prototype.forEach ) {

    Array.prototype.forEach = function( callback, thisArg ) {

        var T, k;

        if ( this == null ) {
            throw new TypeError( " this is null or not defined" );
        }

        // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
        var O = Object(this);

        // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
        // 3. Let len be ToUint32(lenValue).
        var len = O.length >>> 0; // Hack to convert O.length to a UInt32

        // 4. If IsCallable(callback) is false, throw a TypeError exception.
        // See: http://es5.github.com/#x9.11
        if ( {}.toString.call(callback) != "[object Function]" ) {
            throw new TypeError( callback + " is not a function" );
        }

        // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if ( thisArg ) {
            T = thisArg;
        }

        // 6. Let k be 0
        k = 0;

        // 7. Repeat, while k < len
        while( k < len ) {

            var kValue;

            // a. Let Pk be ToString(k).
            //   This is implicit for LHS operands of the in operator
            // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
            //   This step can be combined with c
            // c. If kPresent is true, then
            if ( k in O ) {

                // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
                kValue = O[ k ];

                // ii. Call the Call internal method of callback with T as the this value and
                // argument list containing kValue, k, and O.
                callback.call( T, kValue, k, O );
            }
            // d. Increase k by 1.
            k++;
        }
        // 8. return undefined
    };
}

// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    };
}

// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
if (!Array.prototype.filter)
{
    Array.prototype.filter = function(fun /*, thisp */)
    {
        "use strict";

        if (this == null) {
            throw new TypeError();
        }

        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun != "function") {
            throw new TypeError();
        }

        var res = [];
        var thisp = arguments[1];
        for (var i = 0; i < len; i++)
        {
            if (i in t)
            {
                var val = t[i]; // in case fun mutates this
                if (fun.call(thisp, val, i, t)) {
                    res.push(val);
                }
            }
        }

        return res;
    };
}

if (!String.prototype.trim) {
    String.prototype.trim = function() {
      return this.replace(/^\s+|\s+$/g, '');
    };
}

window.CSSStyleDeclaration = window.CSSStyleDeclaration || function() { };

// https://github.com/mbostock/d3/issues/199#issuecomment-1487129
if (!CSSStyleDeclaration.prototype.getProperty) {
    CSSStyleDeclaration.prototype.getProperty = function(a) {
        return this.getAttribute(a);
    };
}

if(!CSSStyleDeclaration.prototype.setProperty) {
    CSSStyleDeclaration.prototype.setProperty = function(a,b) {
        return this.setAttribute(a,b);
    };
}

if(!CSSStyleDeclaration.prototype.removeProperty) {
    CSSStyleDeclaration.prototype.removeProperty = function(a) {
        return this.removeAttribute(a);
    };
}

// https://github.com/mbostock/d3/issues/42#issuecomment-1265410
if(!document.createElementNS) {
    document.createElementNS = function(ns, name) {
        return document.createElement(name);
    };
}

if (!window.JSON) {
    window.JSON = {};
}
if (!window.JSON.parse) {
    window.JSON.parse = (function() {
       var rvalidchars = /^[\],:{}\s]*$/,
           rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
           rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
           rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g;
       return function(data) {
            if ( rvalidchars.test( data.replace( rvalidescape, "@" )
                .replace( rvalidtokens, "]" )
                .replace( rvalidbraces, "")) )
            {
                return ( new Function( "return " + data ) )();
            }

            return null; // Invalid JSON
        };
    })();
}

if (!Object.create) {
    Object.create = function (o) {
        if (arguments.length > 1) {
            throw new Error('Object.create implementation only accepts the first parameter.');
        }
        function F() {}
        F.prototype = o;
        return new F();
    };
}
<commit_msg>Add reduce shiv to Array.prototype<commit_after>// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map
// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.com/#x15.4.4.19
if (!Array.prototype.map) {
    Array.prototype.map = function(callback, thisArg) {

        var T, A, k;

        if (this == null) {
            throw new TypeError(" this is null or not defined");
        }

        // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
        var O = Object(this);

        // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
        // 3. Let len be ToUint32(lenValue).
        var len = O.length >>> 0;

        // 4. If IsCallable(callback) is false, throw a TypeError exception.
        // See: http://es5.github.com/#x9.11
        if ({}.toString.call(callback) != "[object Function]") {
            throw new TypeError(callback + " is not a function");
        }

        // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if (thisArg) {
            T = thisArg;
        }

        // 6. Let A be a new array created as if by the expression new Array(len) where Array is
        // the standard built-in constructor with that name and len is the value of len.
        A = new Array(len);

        // 7. Let k be 0
        k = 0;

        // 8. Repeat, while k < len
        while(k < len) {

            var kValue, mappedValue;

            // a. Let Pk be ToString(k).
            //   This is implicit for LHS operands of the in operator
            // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
            //   This step can be combined with c
            // c. If kPresent is true, then
            if (k in O) {

                // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
                kValue = O[ k ];

                // ii. Let mappedValue be the result of calling the Call internal method of callback
                // with T as the this value and argument list containing kValue, k, and O.
                mappedValue = callback.call(T, kValue, k, O);

                // iii. Call the DefineOwnProperty internal method of A with arguments
                // Pk, Property Descriptor {Value: mappedValue, Writable: true, Enumerable: true, Configurable: true},
                // and false.

                // In browsers that support Object.defineProperty, use the following:
                // Object.defineProperty(A, Pk, { value: mappedValue, writable: true, enumerable: true, configurable: true });

                // For best browser support, use the following:
                A[ k ] = mappedValue;
            }
            // d. Increase k by 1.
            k++;
        }

        // 9. return A
        return A;
    };
}

// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/forEach
// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.com/#x15.4.4.18
if ( !Array.prototype.forEach ) {

    Array.prototype.forEach = function( callback, thisArg ) {

        var T, k;

        if ( this == null ) {
            throw new TypeError( " this is null or not defined" );
        }

        // 1. Let O be the result of calling ToObject passing the |this| value as the argument.
        var O = Object(this);

        // 2. Let lenValue be the result of calling the Get internal method of O with the argument "length".
        // 3. Let len be ToUint32(lenValue).
        var len = O.length >>> 0; // Hack to convert O.length to a UInt32

        // 4. If IsCallable(callback) is false, throw a TypeError exception.
        // See: http://es5.github.com/#x9.11
        if ( {}.toString.call(callback) != "[object Function]" ) {
            throw new TypeError( callback + " is not a function" );
        }

        // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if ( thisArg ) {
            T = thisArg;
        }

        // 6. Let k be 0
        k = 0;

        // 7. Repeat, while k < len
        while( k < len ) {

            var kValue;

            // a. Let Pk be ToString(k).
            //   This is implicit for LHS operands of the in operator
            // b. Let kPresent be the result of calling the HasProperty internal method of O with argument Pk.
            //   This step can be combined with c
            // c. If kPresent is true, then
            if ( k in O ) {

                // i. Let kValue be the result of calling the Get internal method of O with argument Pk.
                kValue = O[ k ];

                // ii. Call the Call internal method of callback with T as the this value and
                // argument list containing kValue, k, and O.
                callback.call( T, kValue, k, O );
            }
            // d. Increase k by 1.
            k++;
        }
        // 8. return undefined
    };
}

// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/indexOf
if (!Array.prototype.indexOf) {
    Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
        "use strict";
        if (this == null) {
            throw new TypeError();
        }
        var t = Object(this);
        var len = t.length >>> 0;
        if (len === 0) {
            return -1;
        }
        var n = 0;
        if (arguments.length > 0) {
            n = Number(arguments[1]);
            if (n != n) { // shortcut for verifying if it's NaN
                n = 0;
            } else if (n != 0 && n != Infinity && n != -Infinity) {
                n = (n > 0 || -1) * Math.floor(Math.abs(n));
            }
        }
        if (n >= len) {
            return -1;
        }
        var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
        for (; k < len; k++) {
            if (k in t && t[k] === searchElement) {
                return k;
            }
        }
        return -1;
    };
}

// https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
if (!Array.prototype.filter)
{
    Array.prototype.filter = function(fun /*, thisp */)
    {
        "use strict";

        if (this == null) {
            throw new TypeError();
        }

        var t = Object(this);
        var len = t.length >>> 0;
        if (typeof fun != "function") {
            throw new TypeError();
        }

        var res = [];
        var thisp = arguments[1];
        for (var i = 0; i < len; i++)
        {
            if (i in t)
            {
                var val = t[i]; // in case fun mutates this
                if (fun.call(thisp, val, i, t)) {
                    res.push(val);
                }
            }
        }

        return res;
    };
}

if (!Array.prototype.reduce) {
  Array.prototype.reduce = function reduce(accumulator){
    if (this===null || this===undefined) throw new TypeError("Object is null or undefined");
    var i = 0, l = this.length >> 0, curr;

    if(typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception."
      throw new TypeError("First argument is not callable");

    if(arguments.length < 2) {
      if (l === 0) throw new TypeError("Array length is 0 and no second argument");
      curr = this[0];
      i = 1; // start accumulating at the second element
    }
    else
      curr = arguments[1];

    while (i < l) {
      if(i in this) curr = accumulator.call(undefined, curr, this[i], i, this);
      ++i;
    }

    return curr;
  };
}

if (!String.prototype.trim) {
    String.prototype.trim = function() {
      return this.replace(/^\s+|\s+$/g, '');
    };
}

window.CSSStyleDeclaration = window.CSSStyleDeclaration || function() { };

// https://github.com/mbostock/d3/issues/199#issuecomment-1487129
if (!CSSStyleDeclaration.prototype.getProperty) {
    CSSStyleDeclaration.prototype.getProperty = function(a) {
        return this.getAttribute(a);
    };
}

if(!CSSStyleDeclaration.prototype.setProperty) {
    CSSStyleDeclaration.prototype.setProperty = function(a,b) {
        return this.setAttribute(a,b);
    };
}

if(!CSSStyleDeclaration.prototype.removeProperty) {
    CSSStyleDeclaration.prototype.removeProperty = function(a) {
        return this.removeAttribute(a);
    };
}

// https://github.com/mbostock/d3/issues/42#issuecomment-1265410
if(!document.createElementNS) {
    document.createElementNS = function(ns, name) {
        return document.createElement(name);
    };
}

if (!window.JSON) {
    window.JSON = {};
}
if (!window.JSON.parse) {
    window.JSON.parse = (function() {
       var rvalidchars = /^[\],:{}\s]*$/,
           rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
           rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g,
           rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d\d*\.|)\d+(?:[eE][\-+]?\d+|)/g;
       return function(data) {
            if ( rvalidchars.test( data.replace( rvalidescape, "@" )
                .replace( rvalidtokens, "]" )
                .replace( rvalidbraces, "")) )
            {
                return ( new Function( "return " + data ) )();
            }

            return null; // Invalid JSON
        };
    })();
}

if (!Object.create) {
    Object.create = function (o) {
        if (arguments.length > 1) {
            throw new Error('Object.create implementation only accepts the first parameter.');
        }
        function F() {}
        F.prototype = o;
        return new F();
    };
}
<|endoftext|>


<commit_before>'use strict';

var ruleModules = require('./_rules')
  , toHash = require('./util').toHash;

module.exports = function rules() {
  var RULES = [
    { type: 'number',
      rules: [ { 'maximum': ['exclusiveMaximum'] },
               { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
    { type: 'string',
      rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
    { type: 'array',
      rules: [ 'maxItems', 'minItems', 'uniqueItems', 'contains', 'items' ] },
    { type: 'object',
      rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
               { 'properties': ['additionalProperties', 'patternProperties'] } ] },
    { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf' ] }
  ];

  var ALL = [ 'type' ];
  var KEYWORDS = [
    'additionalItems', '$schema', 'id', 'title',
    'description', 'default', 'definitions'
  ];
  var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
  RULES.all = toHash(ALL);
  RULES.types = toHash(TYPES);

  RULES.forEach(function (group) {
    group.rules = group.rules.map(function (keyword) {
      var implKeywords;
      if (typeof keyword == 'object') {
        var key = Object.keys(keyword)[0];
        implKeywords = keyword[key];
        keyword = key;
        implKeywords.forEach(function (k) {
          ALL.push(k);
          RULES.all[k] = true;
        });
      }
      ALL.push(keyword);
      var rule = RULES.all[keyword] = {
        keyword: keyword,
        code: ruleModules[keyword],
        implements: implKeywords
      };
      return rule;
    });

    if (group.type) RULES.types[group.type] = group;
  });

  RULES.keywords = toHash(ALL.concat(KEYWORDS));
  RULES.custom = {};

  return RULES;
};
<commit_msg>reserve keyword $id<commit_after>'use strict';

var ruleModules = require('./_rules')
  , toHash = require('./util').toHash;

module.exports = function rules() {
  var RULES = [
    { type: 'number',
      rules: [ { 'maximum': ['exclusiveMaximum'] },
               { 'minimum': ['exclusiveMinimum'] }, 'multipleOf', 'format'] },
    { type: 'string',
      rules: [ 'maxLength', 'minLength', 'pattern', 'format' ] },
    { type: 'array',
      rules: [ 'maxItems', 'minItems', 'uniqueItems', 'contains', 'items' ] },
    { type: 'object',
      rules: [ 'maxProperties', 'minProperties', 'required', 'dependencies', 'propertyNames',
               { 'properties': ['additionalProperties', 'patternProperties'] } ] },
    { rules: [ '$ref', 'const', 'enum', 'not', 'anyOf', 'oneOf', 'allOf' ] }
  ];

  var ALL = [ 'type' ];
  var KEYWORDS = [
    'additionalItems', '$schema', '$id', 'id', 'title',
    'description', 'default', 'definitions'
  ];
  var TYPES = [ 'number', 'integer', 'string', 'array', 'object', 'boolean', 'null' ];
  RULES.all = toHash(ALL);
  RULES.types = toHash(TYPES);

  RULES.forEach(function (group) {
    group.rules = group.rules.map(function (keyword) {
      var implKeywords;
      if (typeof keyword == 'object') {
        var key = Object.keys(keyword)[0];
        implKeywords = keyword[key];
        keyword = key;
        implKeywords.forEach(function (k) {
          ALL.push(k);
          RULES.all[k] = true;
        });
      }
      ALL.push(keyword);
      var rule = RULES.all[keyword] = {
        keyword: keyword,
        code: ruleModules[keyword],
        implements: implKeywords
      };
      return rule;
    });

    if (group.type) RULES.types[group.type] = group;
  });

  RULES.keywords = toHash(ALL.concat(KEYWORDS));
  RULES.custom = {};

  return RULES;
};
<|endoftext|>


<commit_before>'use strict';

var _    = require('lodash');
var path = require('path');

// Build a path relative to `test/`
exports.buildPath = function() {
  var args  = _.slice(arguments, 0),
      paths = [__dirname].concat(args);

  return path.join.apply(this, paths);
};

exports.numberToString = _.method('toString');
<commit_msg>Add asynchronous handler for common test tasks<commit_after>'use strict';

var _    = require('lodash');
var path = require('path');

// Build a path relative to `test/`
exports.buildPath = function() {
  var args  = _.slice(arguments, 0),
      paths = [__dirname].concat(args);

  return path.join.apply(this, paths);
};

exports.numberToString = _.method('toString');

exports.handleExpectedFile = _.curry(function(actual, done, err, expected) {
  if(err) return done(err);

  actual.should.equal(expected);
  done();
}, 4);

exports.handleSetup = _.curry(
  function(that, testHTML, done, err, expected) {
    if(err) return done(err);

    that.expected = expected.trim();
    that.blocks   = _.map(testHTML, 'innerHTML');
    done();
  }, 5);
<|endoftext|>


<commit_before>var fs = require('fs');
var nodePath = require('path');
var index = require('./index');
var files = require('./files');
var objects = require('./objects');
var refs = require('./refs');
var diff = require('./diff');
var util = require('./util');

var checkout = module.exports = {
  readChangedFilesCheckoutWouldOverwrite: function(checkoutHash) {
    var localChanges = diff.readDiff("HEAD");
    var headToBranchChanges = diff.readDiff("HEAD", checkoutHash);
    return Object.keys(localChanges)
      .filter(function(path) { return path in headToBranchChanges; });
  },

  writeCheckout: function(ref) {
    addModifyDelete("HEAD", refs.readHash(ref));
    refs.write("HEAD", objects.read(ref) ? ref : refs.nameToBranchRef(ref));
  }
};

function addModifyDelete(diffFromRef, diffToRef) {
  var changes = diff.readDiff(diffFromRef, diffToRef);
  var checkoutIndex = index.readCommitIndex(diffToRef);
  Object.keys(changes).forEach(function(path) {
    if (changes[path] === diff.FILE_STATUS.ADD ||
        changes[path] === diff.FILE_STATUS.MODIFY) { // no line by line for now
        var content = objects.read(checkoutIndex[path]);
      files.writeFilesFromTree(util.assocIn({}, path.split(nodePath.sep).concat(content)),
                               files.repoDir());
    } else if (changes[path] === diff.FILE_STATUS.DELETE) {
      fs.unlinkSync(path);
    }
  });
};
<commit_msg>Delete empty dirs after checking out<commit_after>var fs = require('fs');
var nodePath = require('path');
var index = require('./index');
var files = require('./files');
var objects = require('./objects');
var refs = require('./refs');
var diff = require('./diff');
var util = require('./util');

var checkout = module.exports = {
  readChangedFilesCheckoutWouldOverwrite: function(checkoutHash) {
    var localChanges = diff.readDiff("HEAD");
    var headToBranchChanges = diff.readDiff("HEAD", checkoutHash);
    return Object.keys(localChanges)
      .filter(function(path) { return path in headToBranchChanges; });
  },

  writeCheckout: function(ref) {
    addModifyDelete("HEAD", refs.readHash(ref));
    fs.readdirSync(files.repoDir())
      .filter(function(dirChild) { return dirChild !== ".gitlet"; })
      .filter(function(dirChild) { return fs.statSync(dirChild).isDirectory(); })
      .forEach(function(dirChild) { files.deleteEmptyDirs(dirChild); });

    refs.write("HEAD", objects.read(ref) ? ref : refs.nameToBranchRef(ref));
  }
};

function addModifyDelete(diffFromRef, diffToRef) {
  var changes = diff.readDiff(diffFromRef, diffToRef);
  var checkoutIndex = index.readCommitIndex(diffToRef);
  Object.keys(changes).forEach(function(path) {
    if (changes[path] === diff.FILE_STATUS.ADD ||
        changes[path] === diff.FILE_STATUS.MODIFY) { // no line by line for now
        var content = objects.read(checkoutIndex[path]);
      files.writeFilesFromTree(util.assocIn({}, path.split(nodePath.sep).concat(content)),
                               files.repoDir());
    } else if (changes[path] === diff.FILE_STATUS.DELETE) {
      fs.unlinkSync(path);
    }
  });
};
<|endoftext|>


<commit_before>'use strict'

const path = require('path')
const inquirer = require('inquirer')
const mkdirp = require('mkdirp')
const fs = require('fs')
const installTemplates = require('./install-templates.js')
const chalk = require('chalk')

const defaultPalette = 'myblue: \'#99ccff\''

module.exports = function (projectPath, auto) {
  const folderName = path.basename(projectPath)
  const templateFiles = fs.readdirSync(path.resolve(__dirname, '../..', 'templates/syntax'))
  const indexBase = templateFiles.indexOf('base.yml')
  templateFiles.splice(indexBase, 1)
  let templateChoices = templateFiles.map(f => {
    return {
      name: f.slice(0, -4),
      value: f
    }
  })

  const questions = [
    {
      type: 'input',
      name: 'name',
      message: 'Project name:',
      default: folderName
    },
    {
      type: 'input',
      name: 'version',
      message: 'Version:',
      default: '1.0.0'
    },
    {
      type: 'input',
      name: 'license',
      message: 'License:',
      default: 'MIT'
    },
    {
      type: 'input',
      name: 'author',
      message: 'Author:'
    },
    {
      type: 'input',
      name: 'website',
      message: 'Project url:'
    },
    {
      type: 'input',
      name: 'description',
      message: 'Short description:'
    },
    {
      type: 'checkbox',
      message: 'Select some syntax templates',
      name: 'templates',
      choices: templateChoices
    }
  ]

  if (auto) {
    createBoilerplate(projectPath, {
      name: folderName,
      author: '',
      version: '1.0.0',
      website: '',
      license: 'MIT',
      airline: true,
      lightline: true,
      description: '',
      templates: []
    })
  } else {
    inquirer.prompt(questions).then(function (answers) {
      createBoilerplate(projectPath, answers)
    })
  }
}

function createBoilerplate (projectPath, options) {
  let estiloStr = `name: '${options.name}'
version: '${options.version || ''}'
license: '${options.license || ''}'
author: '${options.author || ''}'
url: '${options.url || ''}'
description: '${options.description || ''}'
colorschemes:
  - name: ${options.name}
    background: 'dark'
    palette: ${options.name}`

  fs.writeFileSync(path.resolve(projectPath, 'estilo.yml'), estiloStr)
  mkdirp.sync(path.resolve(projectPath, 'estilo'))
  mkdirp.sync(path.resolve(projectPath, 'estilo', 'syntax'))
  mkdirp.sync(path.resolve(projectPath, 'estilo', 'palettes'))
  fs.writeFileSync(path.resolve(projectPath, 'estilo/palettes', options.name + '.yml'), defaultPalette)

  installTemplates(options.templates.concat('base.yml'), function () {
    console.log(chalk.green.bold('\nYour project is ready'))
  })
}
<commit_msg>Fix: url property name when questining<commit_after>'use strict'

const path = require('path')
const inquirer = require('inquirer')
const mkdirp = require('mkdirp')
const fs = require('fs')
const installTemplates = require('./install-templates.js')
const chalk = require('chalk')

const defaultPalette = 'myblue: \'#99ccff\''

module.exports = function (projectPath, auto) {
  const folderName = path.basename(projectPath)
  const templateFiles = fs.readdirSync(path.resolve(__dirname, '../..', 'templates/syntax'))
  const indexBase = templateFiles.indexOf('base.yml')
  templateFiles.splice(indexBase, 1)
  let templateChoices = templateFiles.map(f => {
    return {
      name: f.slice(0, -4),
      value: f
    }
  })

  const questions = [
    {
      type: 'input',
      name: 'name',
      message: 'Project name:',
      default: folderName
    },
    {
      type: 'input',
      name: 'version',
      message: 'Version:',
      default: '1.0.0'
    },
    {
      type: 'input',
      name: 'license',
      message: 'License:',
      default: 'MIT'
    },
    {
      type: 'input',
      name: 'author',
      message: 'Author:'
    },
    {
      type: 'input',
      name: 'url',
      message: 'Project url:'
    },
    {
      type: 'input',
      name: 'description',
      message: 'Short description:'
    },
    {
      type: 'checkbox',
      message: 'Select some syntax templates',
      name: 'templates',
      choices: templateChoices
    }
  ]

  if (auto) {
    createBoilerplate(projectPath, {
      name: folderName,
      author: '',
      version: '1.0.0',
      url: '',
      license: 'MIT',
      airline: true,
      lightline: true,
      description: '',
      templates: []
    })
  } else {
    inquirer.prompt(questions).then(function (answers) {
      createBoilerplate(projectPath, answers)
    })
  }
}

function createBoilerplate (projectPath, options) {
  let estiloStr = `name: '${options.name}'
version: '${options.version || ''}'
license: '${options.license || ''}'
author: '${options.author || ''}'
url: '${options.url || ''}'
description: '${options.description || ''}'
colorschemes:
  - name: ${options.name}
    background: 'dark'
    palette: ${options.name}`

  fs.writeFileSync(path.resolve(projectPath, 'estilo.yml'), estiloStr)
  mkdirp.sync(path.resolve(projectPath, 'estilo'))
  mkdirp.sync(path.resolve(projectPath, 'estilo', 'syntax'))
  mkdirp.sync(path.resolve(projectPath, 'estilo', 'palettes'))
  fs.writeFileSync(path.resolve(projectPath, 'estilo/palettes', options.name + '.yml'), defaultPalette)

  installTemplates(options.templates.concat('base.yml'), function () {
    console.log(chalk.green.bold('\nYour project is ready'))
  })
}
<|endoftext|>


<commit_before>/**
Definition of the `main` function.
@module main.js
@license MIT. See LICENSE.md for details.
*/

(function(){

  var HMR  = require( '../hackmyapi')
    , PKG = require('../../package.json')
    , FS = require('fs')
    , EXTEND = require('../utils/extend')
    , chalk = require('chalk')
    , PATH = require('path')
    , HACKMYSTATUS = require('../core/status-codes')
    , HME = require('../core/event-codes')
    , safeLoadJSON = require('../utils/safe-json-loader')
    , _opts = { }
    , title = chalk.white.bold('\n*** HackMyResume v' + PKG.version + ' ***')
    , StringUtils = require('../utils/string.js')
    , _ = require('underscore')
    , OUTPUT = require('./out')
    , SAFELOADJSON = require('../utils/safe-json-loader')
    , PAD = require('string-padding')
    , Command = require('commander').Command;

  /**
  Main function for HackMyResume
  @license MIT. See LICENSE.md for details.
  @module main.js
  */
  var main = module.exports = function( rawArgs ) {

    var initInfo = initialize( rawArgs );
    var args = initInfo.args;

    // Create the top-level (application) command...
    var program = new Command('hackmyresume')
      .version(PKG.version)
      .description(chalk.yellow.bold('*** HackMyResume ***'))
      //.option('-o --optionsSafe <optionsFile>', 'Path to a .hackmyrc options file', /^\"(.*)\"$/i )
      .option('-s --silent', 'Run in silent mode')
      .option('--no-color', 'Disable colors')
      .option('--color', 'Enable colors')
      .option('-d --debug', 'Enable diagnostics', false)
      .option('-v --version', 'Show the version')
      .allowUnknownOption();
      program.jsonArgs = initInfo.options;
      //.usage('COMMAND <sources> [TO <targets>]');

    // Create the NEW command
    program
      .command('new')
      .arguments('<sources...>')
      .option('-f --format <fmt>', 'FRESH or JRS format', 'FRESH')
      .alias('create')
      .description('Create resume(s) in FRESH or JSON RESUME format.')
      .action(function( sources ) {
        execute.call( this, sources, [], this.opts(), logMsg);
      });

    // Create the VALIDATE command
    program
      .command('validate')
      .arguments('<sources...>')
      .option('-a --assert', 'Treat validation warnings as errors', false)
      .description('Validate a resume in FRESH or JSON RESUME format.')
      .action(function(sources) {
        execute.call( this, sources, [], this.opts(), logMsg);
      });

    // Create the CONVERT command
    program
      .command('convert')
      //.arguments('<sources...>')
      .description('Convert a resume to/from FRESH or JSON RESUME format.')
      .action(function() {
        var x = splitSrcDest.call( this );
        execute.call( this, x.src, x.dst, this.opts(), logMsg);
      });

    // Create the ANALYZE command
    program
      .command('analyze')
      .arguments('<sources...>')
      .description('Analyze one or more resumes.')
      .action(function( sources ) {
        execute.call( this, sources, [], this.opts(), logMsg);
      });

    // Create the BUILD command
    program
      .command('build')
      .alias('generate')
      //.arguments('<sources> TO [targets]')
      //.usage('...')
      .option('-t --theme <theme>', 'Theme name or path')
      .option('-n --no-prettify', 'Disable HTML prettification', true)
      .option('-c --css <option>', 'CSS linking / embedding', 'embed')
      .option('-p --pdf <engine>', 'PDF generation engine')
      .option('--no-tips', 'Disable theme tips and warnings.', false)
      .description('Generate resume to multiple formats')
      .action(function( sources, targets, options ) {
        var x = splitSrcDest.call( this );
        execute.call( this, x.src, x.dst, this.opts(), logMsg);
      });

    program.parse( args );

    if (!program.args.length) { throw { fluenterror: 4 }; }

  };

  /**
  Massage command-line args and setup Commander.js.
  */
  function initialize( ar ) {

    logMsg( title );

    var o = initOptions( ar );

    // Handle invalid verbs here (a bit easier here than in commander.js)...
    if( o.verb && !HMR.verbs[ o.verb ] && !HMR.alias[ o.verb ] ) {
      throw { fluenterror: HACKMYSTATUS.invalidCommand, shouldExit: true,
              attempted: o.orgVerb };
    }

    // Override the .missingArgument behavior
    Command.prototype.missingArgument = function(name) {
      if( this.name() !== 'new' )
        throw { fluenterror: HACKMYSTATUS.resumeNotFound };
    };

    // Override the .helpInformation behavior
    Command.prototype.helpInformation = function() {
      var manPage = FS.readFileSync(
        PATH.join(__dirname, 'use.txt'), 'utf8' );
      return chalk.green.bold(manPage);
    };

    return {
      args: o.args,
      options: o.json
    };
  }

  function initOptions( ar ) {
    var oVerb, verb = '', args = ar.slice(), cleanArgs = args.slice(2), oJSON;
    if( cleanArgs.length ) {

      // Support case-insensitive sub-commands (build, generate, validate, etc.)..
      var vidx = _.findIndex( cleanArgs, function(v){ return v[0] !== '-'; });
      if( vidx !== -1 ) {
        oVerb = cleanArgs[ vidx ];
        verb = args[ vidx + 2 ] = oVerb.trim().toLowerCase();
      }

      // Remove --options --opts -o and process separately
      var optsIdx = _.findIndex( cleanArgs, function(v){
        return v === '-o' || v === '--options' || v === '--opts';
      });
      if(optsIdx !== -1) {
        var optStr = cleanArgs[ optsIdx + 1];
        args.splice( optsIdx + 2, 2 );
        if( optStr && (optStr = optStr.trim()) ) {
          //var myJSON = JSON.parse(optStr);
          if( optStr[0] === '{')
            oJSON = eval('(' + optStr + ')'); // jshint ignore:line
          else {
            oJSON = SAFELOADJSON( optStr );
          }
        }
      }
    }

    return {
      orgVerb: oVerb,
      verb: verb,
      json: oJSON,
      args: args
    };
  }

  /**
  Invoke a HackMyResume verb.
  */
  function execute( src, dst, opts, log ) {

    loadOptions.call( this, opts, this.parent.jsonArgs );
    require( '../core/error-handler' ).init( _opts.debug );
    var out = new OUTPUT( _opts );
    var v = new HMR.verbs[ this.name() ]();
    v.on( 'hmr:status', function() { out.do.apply( out, arguments ); });
    v.invoke.call( v, src, dst, _opts, log );

  }

  /**
  Initialize HackMyResume options.
  TODO: Options loading is a little hacky, for two reasons:
    - Commander.js idiosyncracies
    - Need to accept JSON inputs from the command line.
  */
  function loadOptions( o, cmdO ) {

    // o and this.opts() seem to be the same (command-specific options)

    // Load the specified options file (if any) and apply options
    if( cmdO )
      o = EXTEND(true, o, cmdO);

    // Merge in command-line options
    o = EXTEND( true, o, this.opts() );

    // Kludge parent-level options until piping issue is resolved
    if( this.parent.silent !== undefined && this.parent.silent !== null)
      o.silent = this.parent.silent;
    if( this.parent.debug !== undefined && this.parent.debug !== null)
      o.debug = this.parent.debug;

    if( o.debug ) {
      logMsg(chalk.cyan('Merged options: '));
      _.each(o, function(val, key) {
        logMsg(chalk.cyan('%s: %s'), PAD(key,10), val);
      });
    }

    // Cache
    _opts = o;
  }

  /**
  Split multiple command-line filenames by the 'TO' keyword
  */
  function splitSrcDest() {

    var params = this.parent.args.filter(function(j) { return String.is(j); });
    if( params.length === 0 )
      throw { fluenterror: HACKMYSTATUS.resumeNotFound };

    // Find the TO keyword, if any
    var splitAt = _.findIndex( params, function(p) {
      return p.toLowerCase() === 'to';
    });

    // TO can't be the last keyword
    if( splitAt === params.length - 1 && splitAt !== -1 ) {
      logMsg(chalk.yellow('Please ') +
        chalk.yellow.bold('specify an output file') +
        chalk.yellow(' for this operation or ') +
        chalk.yellow.bold('omit the TO keyword') +
        chalk.yellow('.') );
      return;
    }

    return {
      src: params.slice(0, splitAt === -1 ? undefined : splitAt ),
      dst: splitAt === -1 ? [] : params.slice( splitAt + 1 )
    };
  }

  /**
  Simple logging placeholder.
  */
  function logMsg() {
    _opts.silent || console.log.apply( console.log, arguments );
  }

}());
<commit_msg>Remove commented lines.<commit_after>/**
Definition of the `main` function.
@module main.js
@license MIT. See LICENSE.md for details.
*/

(function(){

  var HMR  = require( '../hackmyapi')
    , PKG = require('../../package.json')
    , FS = require('fs')
    , EXTEND = require('../utils/extend')
    , chalk = require('chalk')
    , PATH = require('path')
    , HACKMYSTATUS = require('../core/status-codes')
    , HME = require('../core/event-codes')
    , safeLoadJSON = require('../utils/safe-json-loader')
    , _opts = { }
    , title = chalk.white.bold('\n*** HackMyResume v' + PKG.version + ' ***')
    , StringUtils = require('../utils/string.js')
    , _ = require('underscore')
    , OUTPUT = require('./out')
    , SAFELOADJSON = require('../utils/safe-json-loader')
    , PAD = require('string-padding')
    , Command = require('commander').Command;

  /**
  Main function for HackMyResume
  @license MIT. See LICENSE.md for details.
  @module main.js
  */
  var main = module.exports = function( rawArgs ) {

    var initInfo = initialize( rawArgs );
    var args = initInfo.args;

    // Create the top-level (application) command...
    var program = new Command('hackmyresume')
      .version(PKG.version)
      .description(chalk.yellow.bold('*** HackMyResume ***'))
      .option('-s --silent', 'Run in silent mode')
      .option('--no-color', 'Disable colors')
      .option('--color', 'Enable colors')
      .option('-d --debug', 'Enable diagnostics', false)
      .option('-v --version', 'Show the version')
      .allowUnknownOption();
      program.jsonArgs = initInfo.options;

    // Create the NEW command
    program
      .command('new')
      .arguments('<sources...>')
      .option('-f --format <fmt>', 'FRESH or JRS format', 'FRESH')
      .alias('create')
      .description('Create resume(s) in FRESH or JSON RESUME format.')
      .action(function( sources ) {
        execute.call( this, sources, [], this.opts(), logMsg);
      });

    // Create the VALIDATE command
    program
      .command('validate')
      .arguments('<sources...>')
      .option('-a --assert', 'Treat validation warnings as errors', false)
      .description('Validate a resume in FRESH or JSON RESUME format.')
      .action(function(sources) {
        execute.call( this, sources, [], this.opts(), logMsg);
      });

    // Create the CONVERT command
    program
      .command('convert')
      .description('Convert a resume to/from FRESH or JSON RESUME format.')
      .action(function() {
        var x = splitSrcDest.call( this );
        execute.call( this, x.src, x.dst, this.opts(), logMsg);
      });

    // Create the ANALYZE command
    program
      .command('analyze')
      .arguments('<sources...>')
      .description('Analyze one or more resumes.')
      .action(function( sources ) {
        execute.call( this, sources, [], this.opts(), logMsg);
      });

    // Create the BUILD command
    program
      .command('build')
      .alias('generate')
      .option('-t --theme <theme>', 'Theme name or path')
      .option('-n --no-prettify', 'Disable HTML prettification', true)
      .option('-c --css <option>', 'CSS linking / embedding', 'embed')
      .option('-p --pdf <engine>', 'PDF generation engine')
      .option('--no-tips', 'Disable theme tips and warnings.', false)
      .description('Generate resume to multiple formats')
      .action(function( sources, targets, options ) {
        var x = splitSrcDest.call( this );
        execute.call( this, x.src, x.dst, this.opts(), logMsg);
      });

    program.parse( args );

    if (!program.args.length) { throw { fluenterror: 4 }; }

  };

  /**
  Massage command-line args and setup Commander.js.
  */
  function initialize( ar ) {

    logMsg( title );

    var o = initOptions( ar );

    // Handle invalid verbs here (a bit easier here than in commander.js)...
    if( o.verb && !HMR.verbs[ o.verb ] && !HMR.alias[ o.verb ] ) {
      throw { fluenterror: HACKMYSTATUS.invalidCommand, shouldExit: true,
              attempted: o.orgVerb };
    }

    // Override the .missingArgument behavior
    Command.prototype.missingArgument = function(name) {
      if( this.name() !== 'new' )
        throw { fluenterror: HACKMYSTATUS.resumeNotFound };
    };

    // Override the .helpInformation behavior
    Command.prototype.helpInformation = function() {
      var manPage = FS.readFileSync(
        PATH.join(__dirname, 'use.txt'), 'utf8' );
      return chalk.green.bold(manPage);
    };

    return {
      args: o.args,
      options: o.json
    };
  }

  function initOptions( ar ) {
    var oVerb, verb = '', args = ar.slice(), cleanArgs = args.slice(2), oJSON;
    if( cleanArgs.length ) {

      // Support case-insensitive sub-commands (build, generate, validate, etc.)..
      var vidx = _.findIndex( cleanArgs, function(v){ return v[0] !== '-'; });
      if( vidx !== -1 ) {
        oVerb = cleanArgs[ vidx ];
        verb = args[ vidx + 2 ] = oVerb.trim().toLowerCase();
      }

      // Remove --options --opts -o and process separately
      var optsIdx = _.findIndex( cleanArgs, function(v){
        return v === '-o' || v === '--options' || v === '--opts';
      });
      if(optsIdx !== -1) {
        var optStr = cleanArgs[ optsIdx + 1];
        args.splice( optsIdx + 2, 2 );
        if( optStr && (optStr = optStr.trim()) ) {
          //var myJSON = JSON.parse(optStr);
          if( optStr[0] === '{')
            oJSON = eval('(' + optStr + ')'); // jshint ignore:line
          else {
            oJSON = SAFELOADJSON( optStr );
          }
        }
      }
    }

    return {
      orgVerb: oVerb,
      verb: verb,
      json: oJSON,
      args: args
    };
  }

  /**
  Invoke a HackMyResume verb.
  */
  function execute( src, dst, opts, log ) {

    loadOptions.call( this, opts, this.parent.jsonArgs );
    require( '../core/error-handler' ).init( _opts.debug );
    var out = new OUTPUT( _opts );
    var v = new HMR.verbs[ this.name() ]();
    v.on( 'hmr:status', function() { out.do.apply( out, arguments ); });
    v.invoke.call( v, src, dst, _opts, log );

  }

  /**
  Initialize HackMyResume options.
  TODO: Options loading is a little hacky, for two reasons:
    - Commander.js idiosyncracies
    - Need to accept JSON inputs from the command line.
  */
  function loadOptions( o, cmdO ) {

    // o and this.opts() seem to be the same (command-specific options)

    // Load the specified options file (if any) and apply options
    if( cmdO )
      o = EXTEND(true, o, cmdO);

    // Merge in command-line options
    o = EXTEND( true, o, this.opts() );

    // Kludge parent-level options until piping issue is resolved
    if( this.parent.silent !== undefined && this.parent.silent !== null)
      o.silent = this.parent.silent;
    if( this.parent.debug !== undefined && this.parent.debug !== null)
      o.debug = this.parent.debug;

    if( o.debug ) {
      logMsg(chalk.cyan('Merged options: '));
      _.each(o, function(val, key) {
        logMsg(chalk.cyan('%s: %s'), PAD(key,10), val);
      });
    }

    // Cache
    _opts = o;
  }

  /**
  Split multiple command-line filenames by the 'TO' keyword
  */
  function splitSrcDest() {

    var params = this.parent.args.filter(function(j) { return String.is(j); });
    if( params.length === 0 )
      throw { fluenterror: HACKMYSTATUS.resumeNotFound };

    // Find the TO keyword, if any
    var splitAt = _.findIndex( params, function(p) {
      return p.toLowerCase() === 'to';
    });

    // TO can't be the last keyword
    if( splitAt === params.length - 1 && splitAt !== -1 ) {
      logMsg(chalk.yellow('Please ') +
        chalk.yellow.bold('specify an output file') +
        chalk.yellow(' for this operation or ') +
        chalk.yellow.bold('omit the TO keyword') +
        chalk.yellow('.') );
      return;
    }

    return {
      src: params.slice(0, splitAt === -1 ? undefined : splitAt ),
      dst: splitAt === -1 ? [] : params.slice( splitAt + 1 )
    };
  }

  /**
  Simple logging placeholder.
  */
  function logMsg() {
    _opts.silent || console.log.apply( console.log, arguments );
  }

}());
<|endoftext|>


<commit_before>Accounts.config({forbidClientAccountCreation: true});

browserWhitelist = ["Chrome", "Firefox", "Mozilla"];

SimpleSchema.messages({
    minCount: "[label] must specify at least [minCount] value(s) (press <enter> after typing to add to list)",
    numOrNR: '[label] must either be numeric or the string "NR"',
});
<commit_msg>use html-escaped < and ><commit_after>Accounts.config({forbidClientAccountCreation: true});

browserWhitelist = ["Chrome", "Firefox", "Mozilla"];

SimpleSchema.messages({
    minCount: "[label] must specify at least [minCount] value(s) (press <enter> after typing to add to list)",
    numOrNR: '[label] must either be numeric or the string "NR"',
});
<|endoftext|>


<commit_before>var debug = require('debug')('connect:mysql');
var mysql = require('mysql');

/**
 * CREATE TABLE `sessions` (
 *  `sid` varchar(255) NOT NULL,
 *  `session` varchar(2048) NOT NULL DEFAULT '',
 *  `updated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 *  PRIMARY KEY (`sid`)
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 * @param session
 * @returns {MySQLStore}
 */
module.exports = function (session) {

    // express's session store
    var Store = session.Store;
    var tableName = 'sessions';

    function MySQLStore(options) {
        if (!(this instanceof MySQLStore)) {
            throw new TypeError('Cannot call MySQLStore constructor as a function');
        }

        var self = this;

        options = options || {};
        Store.call(this, options);

        if (options.url) {
            debug('connect to database via url', options.url);
            var db = mysql.createConnection(options.url);
            db.connect(function (err) {
                if (err) {
                    debug('cannot connect to ' + options.url, err);
                    self.emit('error', err);
                } else {
                    self.emit('connected');
                    self.db = db;

                    if (options.table) {
                        tableName = db.escapeId(options.table);
                    }
                    db.query('DESC ' + tableName, function (err, result) {
                        if (err) {
                            debug('cannot find session table: ' + tableName);
                            self.emit('error', err);
                        }
                    });
                }
            });
        }
    }

    MySQLStore.prototype.__proto__ = Store.prototype;

    MySQLStore.prototype.get = function (sid, cb) {
        debug('get store');
        this.db.query('SELECT session FROM ' + tableName + ' WHERE sid = ?', [sid], function (err, rows) {
            if (err) return cb(err);

            if (rows.length > 0) {
                cb(null, JSON.parse(rows[0].session));
            } else {
                cb(null, null);
            }
        });
    };

    MySQLStore.prototype.set = function (sid, sess, cb) {
        debug('set store');
        try {
            var jsess = JSON.stringify(sess);
        } catch (e) {
            return cb(e);
        }
        try {
            this.db.query('INSERT INTO ' + tableName + ' (sid, session) VALUES(?, ?) ON DUPLICATE KEY UPDATE session = ?', [sid, jsess, jsess],
                function (err, result) {
                    cb(err);
                }
            );
        } catch (e) {
            return cb(e);
        }
    };

    MySQLStore.prototype.destroy = function (sid, cb) {
        debug('destroy store');
        this.db.query('DELETE FROM ' + tableName + ' WHERE sid = ?', [sid], function (err) {
            cb(err);
        });
    };

    MySQLStore.prototype.clear = function (cb) {
        debug('clear store');
        this.db.query('TRUNCATE TABLE ' + tableName, function (err) {
            cb(err);
        });
    };

    return MySQLStore;
};
<commit_msg>minor debug change<commit_after>var debug = require('debug')('connect:mysql');
var mysql = require('mysql');

/**
 * CREATE TABLE `sessions` (
 *  `sid` varchar(255) NOT NULL,
 *  `session` varchar(2048) NOT NULL DEFAULT '',
 *  `updated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
 *  PRIMARY KEY (`sid`)
 * ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
 * @param session
 * @returns {MySQLStore}
 */
module.exports = function (session) {

    // express's session store
    var Store = session.Store;
    var tableName = 'sessions';

    function MySQLStore(options) {
        if (!(this instanceof MySQLStore)) {
            throw new TypeError('Cannot call MySQLStore constructor as a function');
        }

        var self = this;

        options = options || {};
        Store.call(this, options);

        if (options.url) {
            debug('connect to database via url', options.url);
            var db = mysql.createConnection(options.url);
            db.connect(function (err) {
                if (err) {
                    debug('cannot connect to ' + options.url, err);
                    self.emit('error', err);
                } else {
                    self.emit('connected');
                    self.db = db;

                    if (options.table) {
                        tableName = db.escapeId(options.table);
                    }
                    db.query('DESC ' + tableName, function (err, result) {
                        if (err) {
                            debug('cannot find session table: ' + tableName);
                            self.emit('error', err);
                        }
                    });
                }
            });
        }
    }

    MySQLStore.prototype.__proto__ = Store.prototype;

    MySQLStore.prototype.get = function (sid, cb) {
        debug('get store', sid);
        this.db.query('SELECT session FROM ' + tableName + ' WHERE sid = ?', [sid], function (err, rows) {
            if (err) return cb(err);

            if (rows.length > 0) {
                cb(null, JSON.parse(rows[0].session));
            } else {
                cb(null, null);
            }
        });
    };

    MySQLStore.prototype.set = function (sid, sess, cb) {
        debug('set store', sid);
        try {
            var jsess = JSON.stringify(sess);
        } catch (e) {
            return cb(e);
        }
        try {
            this.db.query('INSERT INTO ' + tableName + ' (sid, session) VALUES(?, ?) ON DUPLICATE KEY UPDATE session = ?', [sid, jsess, jsess],
                function (err, result) {
                    cb(err);
                }
            );
        } catch (e) {
            return cb(e);
        }
    };

    MySQLStore.prototype.destroy = function (sid, cb) {
        debug('destroy store', sid);
        this.db.query('DELETE FROM ' + tableName + ' WHERE sid = ?', [sid], function (err) {
            cb(err);
        });
    };

    MySQLStore.prototype.clear = function (cb) {
        debug('clear store');
        this.db.query('TRUNCATE TABLE ' + tableName, function (err) {
            cb(err);
        });
    };

    return MySQLStore;
};
<|endoftext|>


<commit_before>'use strict'

const fs = require('fs')
const path = require('path')
const {parse: parseURL} = require('url')
const handlebars = require('handlebars')

const config = require('../config')
const {assets} = require('../assets')

const console = require('../helpers/color-console')

// -------------------------------------------------------------
// Module.
// -------------------------------------------------------------

// Create a template object from a template of the assets folder.
// Use the type to determine which template must be selected.
function createTemplate (type) {
  const templatePath = getTemplatePath(assets, type)

  if (!templatePath) {
    throw new Error('Missing template! Make sure your presskit has a "type" field (product/company)')
  }

  registerPartials(assets)
  registerHelpers()

  const template = fs.readFileSync(templatePath, 'utf-8')
  return handlebars.compile(template)
}

// Get the path to the corresponding template in the assets folder.
function getTemplatePath (folder, type) {
  switch (type) {
    case 'product':
      return path.join(folder, 'product.html')
    case 'company':
      return path.join(folder, 'company.html')
  }
}

// Add all the required partials.
function registerPartials (folder) {
  const partialsFolder = path.join(folder, '_includes')

  const partials = fs.readdirSync(partialsFolder)
    .filter(isValidPartial)
    .reduce((result, partial) => {
      const ext = path.extname(partial)
      const fileFullPath = path.join(partialsFolder, partial)
      const data = fs.readFileSync(fileFullPath, 'utf-8')

      // Store as `"filename without extension": content`.
      result[path.basename(partial, ext)] = data
      return result
    }, {})

  handlebars.registerPartial(partials)
}

function registerHelpers () {
  handlebars.registerHelper({
    rawText: function (data) {
      // Not a string? Try to recover and show a warning.
      if (typeof data !== 'string') {
        console.warn(`There is an error in your data:`)
        console.error(`  "${data._.trim()}"`)
        console.warn(`Remove any XML tag, like <br />, <strong>, etc.`)
        return data._
      }

      return data
    },

    prettyURL: function (link) {
      const url = parseURL(link)
      if (!url.hostname) return link

      const path = url.pathname === '/' ? '' : url.pathname
      return url.hostname.replace('www.', '') + path
    },

    domainURL: function (link) {
      const url = parseURL(link)
      if (!url.hostname) return link

      return url.hostname.replace('www.', '')
    },

    permalink: function (link) {
      // Do nothing if the `--pretty-links` flag is not activated.
      if (!config.commands.build.prettyLinks) return link

      if (link.endsWith('index.html')) {
        return path.dirname(link) + '/'
      }

      return link
    },

    basename: function (name) {
      const ext = path.extname(name)
      return path.basename(name, ext)
    },

    trim: function (data) {
      return (data + '').trim()
    }
  })
}

// Is the file an HTML file?
function isValidPartial (file) {
  const ext = path.extname(file)
  return ext === '.html'
}

// -------------------------------------------------------------
// Exports.
// -------------------------------------------------------------

module.exports = {
  createTemplate
}
<commit_msg>Check if data exist in rawText<commit_after>'use strict'

const fs = require('fs')
const path = require('path')
const {parse: parseURL} = require('url')
const handlebars = require('handlebars')

const config = require('../config')
const {assets} = require('../assets')

const console = require('../helpers/color-console')

// -------------------------------------------------------------
// Module.
// -------------------------------------------------------------

// Create a template object from a template of the assets folder.
// Use the type to determine which template must be selected.
function createTemplate (type) {
  const templatePath = getTemplatePath(assets, type)

  if (!templatePath) {
    throw new Error('Missing template! Make sure your presskit has a "type" field (product/company)')
  }

  registerPartials(assets)
  registerHelpers()

  const template = fs.readFileSync(templatePath, 'utf-8')
  return handlebars.compile(template)
}

// Get the path to the corresponding template in the assets folder.
function getTemplatePath (folder, type) {
  switch (type) {
    case 'product':
      return path.join(folder, 'product.html')
    case 'company':
      return path.join(folder, 'company.html')
  }
}

// Add all the required partials.
function registerPartials (folder) {
  const partialsFolder = path.join(folder, '_includes')

  const partials = fs.readdirSync(partialsFolder)
    .filter(isValidPartial)
    .reduce((result, partial) => {
      const ext = path.extname(partial)
      const fileFullPath = path.join(partialsFolder, partial)
      const data = fs.readFileSync(fileFullPath, 'utf-8')

      // Store as `"filename without extension": content`.
      result[path.basename(partial, ext)] = data
      return result
    }, {})

  handlebars.registerPartial(partials)
}

function registerHelpers () {
  handlebars.registerHelper({
    rawText: function (data) {
      // Not a string? Try to recover and show a warning.
      if (data && typeof data !== 'string') {
        const content = typeof data._ === 'string' ? data._.trim() : data._

        console.warn(`There is an error in your data:`)
        console.error(`  "${content}"`)
        console.warn(`Remove any XML tag, like <br />, <strong>, etc.`)

        return data._
      }

      return data
    },

    prettyURL: function (link) {
      const url = parseURL(link)
      if (!url.hostname) return link

      const path = url.pathname === '/' ? '' : url.pathname
      return url.hostname.replace('www.', '') + path
    },

    domainURL: function (link) {
      const url = parseURL(link)
      if (!url.hostname) return link

      return url.hostname.replace('www.', '')
    },

    permalink: function (link) {
      // Do nothing if the `--pretty-links` flag is not activated.
      if (!config.commands.build.prettyLinks) return link

      if (link.endsWith('index.html')) {
        return path.dirname(link) + '/'
      }

      return link
    },

    basename: function (name) {
      const ext = path.extname(name)
      return path.basename(name, ext)
    },

    trim: function (data) {
      return (data + '').trim()
    }
  })
}

// Is the file an HTML file?
function isValidPartial (file) {
  const ext = path.extname(file)
  return ext === '.html'
}

// -------------------------------------------------------------
// Exports.
// -------------------------------------------------------------

module.exports = {
  createTemplate
}
<|endoftext|>


<commit_before>module.exports = {
	run(input) {
    var cinput = input.toLowerCase();
	let args = cinput.split(' ');
    switch (cinput) {
		case "ping":
			return "Pong!";
		break;
		case "8ball":
			let ballresp = require('./ballresp.json');
			let determine = ((Math.random() * (ballresp.length - 1) + 1).toFixed(0) - 1);
			return "
Oh, interesting question. The 8ball's response is " + ballresp[determine] + ".";
		break;
		case "clear":
			return "Matt was told to make this command, he failed miserably.";
		break;
		case "about":
			return "ElectronCLI is a Command-Line interface built from Electron.
ElectronCLI was (and currently is being) developed by MattSilverblood and SplitPixl.";
		break;
		default:
			return "Invalid syntax! Type \"help\" for infomation on how to use ElectronCLI."
	}
	}
};
<commit_msg>Case now listens for args[0] to allow command arguments.<commit_after>module.exports = {
	run(input) {
    var cinput = input.toLowerCase();
	let args = cinput.split(' ');
    switch (args[0]) {
		case "ping":
			return "Pong!";
		break;
		case "8ball":
			let ballresp = require('./ballresp.json');
			let determine = ((Math.random() * (ballresp.length - 1) + 1).toFixed(0) - 1);
			return "
Oh, interesting question. The 8ball's response is " + ballresp[determine] + ".";
		break;
		case "clear":
			return "Matt was told to make this command, he failed miserably.";
		break;
		case "about":
			return "ElectronCLI is a Command-Line interface built from Electron.
ElectronCLI was (and currently is being) developed by MattSilverblood and SplitPixl.";
		break;
		default:
			return "Invalid syntax! Type \"help\" for infomation on how to use ElectronCLI."
	}
	}
};
<|endoftext|>