<commit_before>//
// Eyes.js - a customizable value inspector for Node.js
//
//   usage:
//
//       var inspect = require('eyes').inspector({styles: {all: 'magenta'}});
//       inspect(something); // inspect with the settings passed to `inspector`
//
//     or
//
//       var eyes = require('eyes');
//       eyes.inspect(something); // inspect with the default settings
//
var eyes = exports,
    stack = [];

eyes.defaults = {
    styles: {                 // Styles applied to stdout
        all:     'cyan',      // Overall style applied to everything
        label:   'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]`
        other:   'inverted',  // Objects which don't have a literal representation, such as functions
        key:     'bold',      // The keys in object literals, like 'a' in `{a: 1}`
        special: 'grey',      // null, undefined...
        string:  'green',
        number:  'magenta',
        bool:    'blue',      // true false
        regexp:  'green',     // /\d+/
    },
    pretty: true,             // Indent object literals
    hideFunctions: false,
    showHidden: false,
    stream: process.stdout,
    maxLength: 2048           // Truncate output if longer
};

// Return a curried inspect() function, with the `options` argument filled in.
eyes.inspector = function (options) {
    var that = this;
    return function (obj, label, opts) {
        return that.inspect.call(that, obj, label,
            merge(options || {}, opts || {}));
    };
};

// If we have a `stream` defined, use it to print a styled string,
// if not, we just return the stringified object.
eyes.inspect = function (obj, label, options) {
    options = merge(this.defaults, options || {});

    if (options.stream) {
        return this.print(stringify(obj, options), label, options);
    } else {
        return stringify(obj, options) + (options.styles ? '\033[39m' : '');
    }
};

// Output using the 'stream', and an optional label
// Loop through `str`, and truncate it after `options.maxLength` has been reached.
// Because escape sequences are, at this point embeded within
// the output string, we can't measure the length of the string
// in a useful way, without separating what is an escape sequence,
// versus a printable character (`c`). So we resort to counting the
// length manually.
eyes.print = function (str, label, options) {
    for (var c = 0, i = 0; i < str.length; i++) {
        if (str.charAt(i) === '\033') { i += 4 } // `4` because '\033[25m'.length + 1 == 5
        else if (c === options.maxLength) {
           str = str.slice(0, i - 1) + '…';
           break;
        } else { c++ }
    }
    return options.stream.write.call(options.stream, (label ?
        this.stylize(label, options.styles.label, options.styles) + ': ' : '') +
        this.stylize(str,   options.styles.all, options.styles) + '\033[0m' + "\n");
};

// Apply a style to a string, eventually,
// I'd like this to support passing multiple
// styles.
eyes.stylize = function (str, style, styles) {
    var codes = {
        'bold'      : [1,  22],
        'underline' : [4,  24],
        'inverse'   : [7,  27],
        'cyan'      : [36, 39],
        'magenta'   : [35, 39],
        'blue'      : [34, 39],
        'yellow'    : [33, 39],
        'green'     : [32, 39],
        'red'       : [31, 39],
        'grey'      : [90, 39]
    }, endCode;

    if (style && codes[style]) {
        endCode = (codes[style][1] === 39 && styles.all) ? codes[styles.all][0]
                                                         : codes[style][1];
        return '\033[' + codes[style][0] + 'm' + str +
               '\033[' + endCode + 'm';
    } else { return str }
};

// Convert any object to a string, ready for output.
// When an 'array' or an 'object' are encountered, they are
// passed to specialized functions, which can then recursively call
// stringify().
function stringify(obj, options) {
    var that = this, stylize = function (str, style) {
        return eyes.stylize(str, options.styles[style], options.styles)
    }, index, result;

    if ((index = stack.indexOf(obj)) !== -1) {
        return stylize(new(Array)(stack.length - index + 1).join('.'), 'special');
    }
    stack.push(obj);

    result = (function (obj) {
        switch (typeOf(obj)) {
            case "string"   : obj = stringifyString(obj, options);
                              return stylize(obj.indexOf("'") === -1 ? "'" + obj + "'"
                                                                     : '"' + obj + '"'
                                                                     , 'string');
            case "regexp"   : return stylize('/' + obj.source + '/', 'regexp');
            case "number"   : return stylize(obj + '',    'number');
            case "function" : return options.stream ? stylize("Function", 'other') : '[Function]';
            case "null"     : return stylize("null",      'special');
            case "undefined": return stylize("undefined", 'special');
            case "boolean"  : return stylize(obj + '',    'bool');
            case "date"     : return stylize(obj.toUTCString());
            case "array"    : return stringifyArray(obj,  options, stack.length);
            case "object"   : return stringifyObject(obj, options, stack.length);
        }
    })(obj);

    stack.pop();
    return result;
};

// Escape invisible characters in a string
function stringifyString(str, options) {
    result = str.replace(/\\/g, '\\\\')
              .replace(/\n/g, '\\n')
              .replace(/[\u0001-\u001F]/g, function (match) {
                  return '\\0' + match[0].charCodeAt(0).toString(8);
              });

    // Truncate the string if a maximum length is configured
    var truncate = options.hasOwnProperty('maxStringLength') && options.maxStringLength >= 0;
    if(truncate && result.length > options.maxStringLength) {
        var length = Math.min(result.length, options.maxStringLength - 3);
        result = result.substr(0, length) + "...";
    }

    return result;
}

// Convert an array to a string, such as [1, 2, 3].
// This function calls stringify() for each of the elements
// in the array.
function stringifyArray(ary, options, level) {
    var out = [];
    var pretty = options.pretty && (ary.length > 4 || ary.some(function (o) {
        return (o !== null && typeof(o) === 'object' && Object.keys(o).length > 0) ||
               (Array.isArray(o) && o.length > 0);
    }));
    var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' ';

    var truncate = options.hasOwnProperty('maxArrayLength') && options.maxArrayLength >= 0;

    var length = truncate ? Math.min(ary.length, options.maxArrayLength) : ary.length;
    for (var i = 0; i < length; i++) {
        out.push(stringify(ary[i], options));
    }

    // Add a special String if the array was truncated
    if(length < ary.length) {
        out.push('<<truncated>>');
    }

    if (out.length === 0) {
        return '[]';
    } else {
        return '[' + ws
                   + out.join(',' + (pretty ? ws : ' '))
                   + (pretty ? ws.slice(0, -4) : ws) +
               ']';
    }
};

// Convert an object to a string, such as {a: 1}.
// This function calls stringify() for each of its values,
// and does not output functions or prototype values.
function stringifyObject(obj, options, level) {
    var out = [];
    var pretty = options.pretty && (Object.keys(obj).length > 2 ||
                                    Object.keys(obj).some(function (k) { return typeof(obj[k]) === 'object' }));
    var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' ';

    var keys = options.showHidden ? Object.keys(obj) : Object.getOwnPropertyNames(obj);
    var truncate = options.hasOwnProperty('maxObjectKeys') && options.maxObjectKeys >= 0;

    // Slice the keys to the maximum length if they exceed the maxObjectKeys option
    var includeKeys = (truncate) ? keys.slice(0, options.maxObjectKeys) : keys;
    includeKeys.forEach(function (k) {
        if (Object.prototype.hasOwnProperty.call(obj, k)
          && !(obj[k] instanceof Function && options.hideFunctions)) {
            out.push(eyes.stylize(k, options.styles.key, options.styles) + ': ' +
                     stringify(obj[k], options));
        }
    });

    // Append a special String if the Object was truncated
    if (includeKeys.length < keys.length) {
        out.push(eyes.stylize('<<truncated>>', options.styles.key, options.styles));
    }

    if (out.length === 0) {
        return '{}';
    } else {
        return "{" + ws
                   + out.join(',' + (pretty ? ws : ' '))
                   + (pretty ? ws.slice(0, -4) : ws) +
               "}";
   }
};

// A better `typeof`
function typeOf(value) {
    var s = typeof(value),
        types = [Object, Array, String, RegExp, Number, Function, Boolean, Date];

    if (s === 'object' || s === 'function') {
        if (value) {
            types.forEach(function (t) {
                if (value instanceof t) { s = t.name.toLowerCase() }
            });
        } else { s = 'null' }
    }
    return s;
}

function merge(/* variable args */) {
    var objs = Array.prototype.slice.call(arguments);
    var target = {};

    objs.forEach(function (o) {
        Object.keys(o).forEach(function (k) {
            if (k === 'styles') {
                if (! o.styles) {
                    target.styles = false;
                } else {
                    target.styles = {}
                    for (var s in o.styles) {
                        target.styles[s] = o.styles[s];
                    }
                }
            } else {
                target[k] = o[k];
            }
        });
    });
    return target;
}
<commit_msg>declare result as local variable<commit_after>//
// Eyes.js - a customizable value inspector for Node.js
//
//   usage:
//
//       var inspect = require('eyes').inspector({styles: {all: 'magenta'}});
//       inspect(something); // inspect with the settings passed to `inspector`
//
//     or
//
//       var eyes = require('eyes');
//       eyes.inspect(something); // inspect with the default settings
//
var eyes = exports,
    stack = [];

eyes.defaults = {
    styles: {                 // Styles applied to stdout
        all:     'cyan',      // Overall style applied to everything
        label:   'underline', // Inspection labels, like 'array' in `array: [1, 2, 3]`
        other:   'inverted',  // Objects which don't have a literal representation, such as functions
        key:     'bold',      // The keys in object literals, like 'a' in `{a: 1}`
        special: 'grey',      // null, undefined...
        string:  'green',
        number:  'magenta',
        bool:    'blue',      // true false
        regexp:  'green',     // /\d+/
    },
    pretty: true,             // Indent object literals
    hideFunctions: false,
    showHidden: false,
    stream: process.stdout,
    maxLength: 2048           // Truncate output if longer
};

// Return a curried inspect() function, with the `options` argument filled in.
eyes.inspector = function (options) {
    var that = this;
    return function (obj, label, opts) {
        return that.inspect.call(that, obj, label,
            merge(options || {}, opts || {}));
    };
};

// If we have a `stream` defined, use it to print a styled string,
// if not, we just return the stringified object.
eyes.inspect = function (obj, label, options) {
    options = merge(this.defaults, options || {});

    if (options.stream) {
        return this.print(stringify(obj, options), label, options);
    } else {
        return stringify(obj, options) + (options.styles ? '\033[39m' : '');
    }
};

// Output using the 'stream', and an optional label
// Loop through `str`, and truncate it after `options.maxLength` has been reached.
// Because escape sequences are, at this point embeded within
// the output string, we can't measure the length of the string
// in a useful way, without separating what is an escape sequence,
// versus a printable character (`c`). So we resort to counting the
// length manually.
eyes.print = function (str, label, options) {
    for (var c = 0, i = 0; i < str.length; i++) {
        if (str.charAt(i) === '\033') { i += 4 } // `4` because '\033[25m'.length + 1 == 5
        else if (c === options.maxLength) {
           str = str.slice(0, i - 1) + '…';
           break;
        } else { c++ }
    }
    return options.stream.write.call(options.stream, (label ?
        this.stylize(label, options.styles.label, options.styles) + ': ' : '') +
        this.stylize(str,   options.styles.all, options.styles) + '\033[0m' + "\n");
};

// Apply a style to a string, eventually,
// I'd like this to support passing multiple
// styles.
eyes.stylize = function (str, style, styles) {
    var codes = {
        'bold'      : [1,  22],
        'underline' : [4,  24],
        'inverse'   : [7,  27],
        'cyan'      : [36, 39],
        'magenta'   : [35, 39],
        'blue'      : [34, 39],
        'yellow'    : [33, 39],
        'green'     : [32, 39],
        'red'       : [31, 39],
        'grey'      : [90, 39]
    }, endCode;

    if (style && codes[style]) {
        endCode = (codes[style][1] === 39 && styles.all) ? codes[styles.all][0]
                                                         : codes[style][1];
        return '\033[' + codes[style][0] + 'm' + str +
               '\033[' + endCode + 'm';
    } else { return str }
};

// Convert any object to a string, ready for output.
// When an 'array' or an 'object' are encountered, they are
// passed to specialized functions, which can then recursively call
// stringify().
function stringify(obj, options) {
    var that = this, stylize = function (str, style) {
        return eyes.stylize(str, options.styles[style], options.styles)
    }, index, result;

    if ((index = stack.indexOf(obj)) !== -1) {
        return stylize(new(Array)(stack.length - index + 1).join('.'), 'special');
    }
    stack.push(obj);

    result = (function (obj) {
        switch (typeOf(obj)) {
            case "string"   : obj = stringifyString(obj, options);
                              return stylize(obj.indexOf("'") === -1 ? "'" + obj + "'"
                                                                     : '"' + obj + '"'
                                                                     , 'string');
            case "regexp"   : return stylize('/' + obj.source + '/', 'regexp');
            case "number"   : return stylize(obj + '',    'number');
            case "function" : return options.stream ? stylize("Function", 'other') : '[Function]';
            case "null"     : return stylize("null",      'special');
            case "undefined": return stylize("undefined", 'special');
            case "boolean"  : return stylize(obj + '',    'bool');
            case "date"     : return stylize(obj.toUTCString());
            case "array"    : return stringifyArray(obj,  options, stack.length);
            case "object"   : return stringifyObject(obj, options, stack.length);
        }
    })(obj);

    stack.pop();
    return result;
};

// Escape invisible characters in a string
function stringifyString(str, options) {
    var result = str.replace(/\\/g, '\\\\')
              .replace(/\n/g, '\\n')
              .replace(/[\u0001-\u001F]/g, function (match) {
                  return '\\0' + match[0].charCodeAt(0).toString(8);
              });

    // Truncate the string if a maximum length is configured
    var truncate = options.hasOwnProperty('maxStringLength') && options.maxStringLength >= 0;
    if(truncate && result.length > options.maxStringLength) {
        var length = Math.min(result.length, options.maxStringLength - 3);
        result = result.substr(0, length) + "...";
    }

    return result;
}

// Convert an array to a string, such as [1, 2, 3].
// This function calls stringify() for each of the elements
// in the array.
function stringifyArray(ary, options, level) {
    var out = [];
    var pretty = options.pretty && (ary.length > 4 || ary.some(function (o) {
        return (o !== null && typeof(o) === 'object' && Object.keys(o).length > 0) ||
               (Array.isArray(o) && o.length > 0);
    }));
    var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' ';

    var truncate = options.hasOwnProperty('maxArrayLength') && options.maxArrayLength >= 0;

    var length = truncate ? Math.min(ary.length, options.maxArrayLength) : ary.length;
    for (var i = 0; i < length; i++) {
        out.push(stringify(ary[i], options));
    }

    // Add a special String if the array was truncated
    if(length < ary.length) {
        out.push('<<truncated>>');
    }

    if (out.length === 0) {
        return '[]';
    } else {
        return '[' + ws
                   + out.join(',' + (pretty ? ws : ' '))
                   + (pretty ? ws.slice(0, -4) : ws) +
               ']';
    }
};

// Convert an object to a string, such as {a: 1}.
// This function calls stringify() for each of its values,
// and does not output functions or prototype values.
function stringifyObject(obj, options, level) {
    var out = [];
    var pretty = options.pretty && (Object.keys(obj).length > 2 ||
                                    Object.keys(obj).some(function (k) { return typeof(obj[k]) === 'object' }));
    var ws = pretty ? '\n' + new(Array)(level * 4 + 1).join(' ') : ' ';

    var keys = options.showHidden ? Object.keys(obj) : Object.getOwnPropertyNames(obj);
    var truncate = options.hasOwnProperty('maxObjectKeys') && options.maxObjectKeys >= 0;

    // Slice the keys to the maximum length if they exceed the maxObjectKeys option
    var includeKeys = (truncate) ? keys.slice(0, options.maxObjectKeys) : keys;
    includeKeys.forEach(function (k) {
        if (Object.prototype.hasOwnProperty.call(obj, k)
          && !(obj[k] instanceof Function && options.hideFunctions)) {
            out.push(eyes.stylize(k, options.styles.key, options.styles) + ': ' +
                     stringify(obj[k], options));
        }
    });

    // Append a special String if the Object was truncated
    if (includeKeys.length < keys.length) {
        out.push(eyes.stylize('<<truncated>>', options.styles.key, options.styles));
    }

    if (out.length === 0) {
        return '{}';
    } else {
        return "{" + ws
                   + out.join(',' + (pretty ? ws : ' '))
                   + (pretty ? ws.slice(0, -4) : ws) +
               "}";
   }
};

// A better `typeof`
function typeOf(value) {
    var s = typeof(value),
        types = [Object, Array, String, RegExp, Number, Function, Boolean, Date];

    if (s === 'object' || s === 'function') {
        if (value) {
            types.forEach(function (t) {
                if (value instanceof t) { s = t.name.toLowerCase() }
            });
        } else { s = 'null' }
    }
    return s;
}

function merge(/* variable args */) {
    var objs = Array.prototype.slice.call(arguments);
    var target = {};

    objs.forEach(function (o) {
        Object.keys(o).forEach(function (k) {
            if (k === 'styles') {
                if (! o.styles) {
                    target.styles = false;
                } else {
                    target.styles = {}
                    for (var s in o.styles) {
                        target.styles[s] = o.styles[s];
                    }
                }
            } else {
                target[k] = o[k];
            }
        });
    });
    return target;
}
<|endoftext|>


<commit_before>import React from 'react';
import LayoutDefault from './layouts/Default';

var helper = require('../data-store/helper.js');

const App = ({location}) => {
  const url = location.getUrl();

  let data = helper.getPathData(url);

  if (!data.current_page) {
    console.log(url);
    console.log('NO DATA');
    // return false;
  }

  return (
    <LayoutDefault data={ data } />
  );
};

export default App;<commit_msg>Commiting<commit_after>import React from 'react';
import LayoutDefault from './layouts/Default';

var helper = require('../data-store/helper.js');

const App = ({ location }) => {
  const url = location.getUrl();

  let data = helper.getPathData(url);

  if (!data.current_page) {
    // console.log(url);
    // console.log('NO DATA');
    // return false;
  }

  return (
    <LayoutDefault data={ data } />
  );
};

export default App;<|endoftext|>


<commit_before>window.feta = (function(document,$){

    //these are the events we track for now
    var events =
    [
        "onclick",
        "onfocus",
        "onkeydown",
        "onblur",
        "onchange" //plus the rest
    ];

    function bindall(base){
        for(var j = 0; j < events.length; j++)
        {
            base[events[j]]=globalHandler(base[events[j]]);
        }

        var elms = base.childNodes;
        if (elms){
            for(var i = 0; i < elms.length; i++)
            {
                bindall(elms[i]);
            }
        }
    }

    var trackedEvents=[];
    var trackingEnabled=false;

    function globalHandler(handler)
    {
        return function(e){
            if (trackingEnabled){
                if (trackedEvents.length > 0){
                    var last = trackedEvents[trackedEvents.length-1];
                    if (last.timeStamp == e.timeStamp &&
                        last.type == e.type &&
                        last.srcElement == e.srcElement){
                        return;
                    }
                }
                console.log("TRACKING EVENT");
                trackedEvents.push(e);
            }
            if (handler){
                handler(e);
            }
        };
    }

    function identifySrc(el){
        if (!el || el == document){ return ""; }
        return (el.id || el.className || (el.tagName ? (identifySrc(el.parentNode) + " " + el.tagName): "DOCUMENT") );
    }

    function outputEvent(e){
        if (e.type == "click" ||
            e.type == "blur" ||
            e.type == "focus"){
            return e.type+
                " event triggered from "+
                identifySrc(e.srcElement)+
                " at "+e.timeStamp;
        }
        if (e.type == "keydown"){
            return e.type+
                " event triggered with "+
                e.keyCode+
                " at "+e.timeStamp;
        }
        return e.type +
            " event triggered from "+
            identifySrc(e.srcElement)+
                " at "+e.timeStamp;
    }

    function outputEventRaw(e){
        return JSON.stringify(
            {
                type: e.type,
                elem: getSelector(e.srcElement),
                timeStamp: e.timeStamp
            }
        );
    }

    function getSelector(elem){
        if ($(elem).parents().length === 0){
            return "DOCUMENT";
        }
        var selector =  $(elem).parents()[0] !== $("body")[0] ?
                        $(elem).parents()
                            .map(function() { return this.tagName + getIdClass(this); })
                            .get().reverse().join(" ")
                        : null;

        if (selector) {
          selector += " ";
        }else{
            selector = "";
        }
        selector += $(elem)[0].nodeName;

        selector += getIdClass(elem);
        return selector;
    }

    function getIdClass(elem){
        if (elem.tagName.toUpperCase() == "BODY" || elem.tagName.toUpperCase() == "HTML"){
            return "";
        }
        var selector="";
        var id = $(elem).attr("id");
        if (id) {
          selector += "#"+ id;
        }

        var classNames = $(elem).attr("class");
        if (classNames) {
          selector += "." + $.trim(classNames).replace(/\s/gi, ".");
        }
        return selector;
    }

    function renderOutput(indx,raw){
        if(raw){
            return outputEventRaw(trackedEvents[indx])+",";
        }else{
            return ("#"+(indx+1)+ " "+ outputEvent(trackedEvents[indx])+"\n");
        }
    }

    function playEvent(playlist){
        if (playlist.length > 0){
                var evt = playlist.shift();
                var delay = 0;
                if (playlist.length > 0){
                    delay = playlist[0].timeStamp - evt.timeStamp;
                }
                $(evt.elem).trigger(evt.type);
                setTimeout(function(){ playEvent(playlist); } ,delay);
            }
    }

    return{
        start: function (){
            trackingEnabled=true;
            var root = document.body;
            console.log("binding event handlers");
            bindall(root);
            console.log("done binding");
        },
        stop: function(noReport){
            trackingEnabled=false;
            if (!noReport){
                this.report();
            }
        },
        report: function(raw,cb){
            var output="";
            for(var i=0;i<trackedEvents.length;i++){
                output += renderOutput(i,raw);
            }
            if (cb){
                cb('{ "playlist": [' +output.slice(0,output.length-1) +']}');
            }else{
                console.log("//start\n"+output+"//end\n");
            }
        },
        play: function(script){
            console.log(script);
            var playlist = JSON.parse(script).playlist;
            console.log("Playing...");
            playEvent(playlist);
            console.log("Done.");
        }
    };
})(document,jQuery);
//@ sourceURL=trackEvents.js
<commit_msg>Still have one extra event..<commit_after>window.feta = (function(document,$){

    //these are the events we track for now
    var events =
    [
        "onclick",
        "onfocus",
        "onkeydown",
        "onblur",
        "onchange" //plus the rest
    ];

    function bindall(base){
        for(var j = 0; j < events.length; j++)
        {
            base[events[j]]=globalHandler(base[events[j]]);
        }

        var elms = base.childNodes;
        if (elms){
            for(var i = 0; i < elms.length; i++)
            {
                bindall(elms[i]);
            }
        }
    }

    var trackedEvents=[];
    var trackingEnabled=false;

    function globalHandler(handler)
    {
        return function(e){
            if (trackingEnabled ){

                if (trackedEvents.length > 0){

                    var last = trackedEvents[trackedEvents.length-1];

                    if (last.timeStamp == e.timeStamp &&
                        last.type == e.type &&
                        last.target == e.target){
                        return;
                    }

                }

                if (e.target == window &&
                    (e.type == "focus" || e.type == "blur")){
                    return;
                }

                console.log("TRACKING EVENT");
                trackedEvents.push(e);
            }
            if (handler){
                handler(e);
            }
        };
    }

    function identifySrc(el){
        if (!el || el == document){ return ""; }
        return (el.id || el.className || (el.tagName ? (identifySrc(el.parentNode) + " " + el.tagName): "DOCUMENT") );
    }

    function outputEvent(e){
        if (e.type == "click" ||
            e.type == "blur" ||
            e.type == "focus"){
            return e.type+
                " event triggered from "+
                identifySrc(e.target)+
                " at "+e.timeStamp;
        }
        if (e.type == "keydown"){
            return e.type+
                " event triggered with "+
                e.keyCode+
                " at "+e.timeStamp;
        }
        return e.type +
            " event triggered from "+
            identifySrc(e.target)+
                " at "+e.timeStamp;
    }

    function outputEventRaw(e){
        return JSON.stringify(
            {
                type: e.type,
                elem: getSelector(e.target),
                timeStamp: e.timeStamp
            }
        );
    }

    function getSelector(elem){
        if ($(elem).parents().length === 0){
            return "DOCUMENT";
        }
        var selector =  $(elem).parents()[0] !== $("body")[0] ?
                        $(elem).parents()
                            .map(function() { return this.tagName + getIdClass(this); })
                            .get().reverse().join(" ")
                        : null;

        if (selector) {
          selector += " ";
        }else{
            selector = "";
        }
        selector += $(elem)[0].nodeName;

        selector += getIdClass(elem);
        return selector;
    }

    function getIdClass(elem){
        if (elem.tagName.toUpperCase() == "BODY" || elem.tagName.toUpperCase() == "HTML"){
            return "";
        }
        var selector="";
        var id = $(elem).attr("id");
        if (id) {
          selector += "#"+ id;
        }

        var classNames = $(elem).attr("class");
        if (classNames) {
          selector += "." + $.trim(classNames).replace(/\s/gi, ".");
        }
        return selector;
    }

    function renderOutput(indx,raw){
        if(raw){
            return outputEventRaw(trackedEvents[indx])+",";
        }else{
            return ("#"+(indx+1)+ " "+ outputEvent(trackedEvents[indx])+"\n");
        }
    }

    function playEvent(playlist,before){
        if (playlist.length > 0){
            var evt = playlist.shift();

            var delay = 0;
            if (playlist.length > 0){
                delay = playlist[0].timeStamp - evt.timeStamp;
            }
            console.log("Playing event:",evt.type,",",evt.elem);

            $(evt.elem).trigger(evt.type);
            setTimeout(function(){ playEvent(playlist,before); } ,delay);
        }else{
            console.log("RAW:",trackedEvents);

            var after = feta.stop(false,true,function(out){
                if (before == out.length){
                    console.log("NO REGRESSION");
                }else{
                    console.log("POSSIBLE REGRESSION, EXPECTED "+before+" BUT SAW ",JSON.parse(out).playlist.length,"\nEVENTS:",out);
                }
                console.log("Done.");
            });

        }
    }

    return{
        start: function (){
            trackedEvents=[];
            trackingEnabled=true;
            var root = document.body;
            console.log("binding event handlers");
            bindall(root);
            console.log("done binding");
        },
        stop: function(noReport,raw,cb){
            trackingEnabled=false;
            if (!noReport){
                this.report(raw,cb);
            }
        },
        report: function(raw,cb){
            var output="";
            for(var i=0;i<trackedEvents.length;i++){
                output += renderOutput(i,raw);
            }
            if (cb){
                cb('{ "playlist": [' +output.slice(0,output.length-1) +']}');
            }else{
                console.log("//start\n"+output+"//end\n");
            }
        },
        play: function(script){
            console.log(script);
            var playlist = JSON.parse(script).playlist;
            //we want to match the playback
            var before = playlist.length;
            feta.start();
            console.log("Playing...");
            playEvent(playlist,before);

        }
    };
})(document,jQuery);
//@ sourceURL=trackEvents.js
<|endoftext|>


<commit_before>var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<commit_msg>Fix file->dir transition to include relative path adjustments<commit_after>var express = require('express');
var path = require('path');
var favicon = require('static-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('../routes/index');
var users = require('../routes/users');

var app = express();

// view engine setup
app.set('views', path.join(__dirname, '..', 'views'));
app.set('view engine', 'jade');

app.use(favicon());
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded());
app.use(cookieParser());
app.use(express.static(path.join(__dirname, '..', 'public')));

app.use('/', routes);
app.use('/users', users);

/// catch 404 and forwarding to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

/// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;
<|endoftext|>


<commit_before>var _ = require('lodash');

var buffer
  , print
  , indentationLevel
  ;

var initializeCompiler = function() {
    buffer = [];
    print = _.bind(buffer.push, buffer);
    indentationLevel = 0;
};

var indent = function() {
    indentationLevel++;
};

var outdent = function() {
    indentationLevel--;
    if(indentationLevel < 0) {
        throw new Error('Tried to outdent too far.');
    }
};

var printIndent = function() {
    // TODO create customizable indentation level
    // TODO make this faster?
    _.times(indentationLevel, function() {
        print('    ');
    });
};

// TODO properly translate all binops and unops:
//   ones that GML has that JS doesn't have
//   ones with different behavior that need to be implemented differently
//   DIV, MOD, ^^, bitwise ops
//   how does GML do type coercion (42 + "hello world")?  Do I need to emulate that behavior?
var generateExpression = function(astNode) {
    switch(astNode.type) {

        case 'identifier':
            print(astNode.name);
            // TODO will this ever need to be enclosed in parentheses?
            // How should I be handling this in the general case?
            break;

        case 'binop':
            print('(');
            // special-case the dot operator
            if(astNode.op === '.') {
                print('resolveObjectBeforeDot(');
                generateExpression(astNode.expr1);
                print(').');
                generateExpression(astNode.expr2);
            } else { // all other operators
                generateExpression(astNode.expr1);
                print(' ' + astNode.op + ' ');
                generateExpression(astNode.expr2);
            }
            print(')');
            break;

        case 'unop':
            print('(');
            print(astNode.op);
            generateExpression(astNode.expr);
            print(')');
            break;

        case 'number':
            print('(');
            print(astNode.val.toString());
            // TODO does toString always produce valid Javascript that will create the exact same number?
            print(')');
            break;

        case 'string':
            print('(');
            print(JSON.stringify(astNode.val));
            // TODO this fails in a select few corner cases.  Use something better,
            // perhaps stolen from the Jade source code
            print(')');
            break;

        case 'index2d':
            // TODO this needs a lot of work
            // What do we do when index values aren't numbers?  Aren't integers?
            // What about when the array isn't initialized or the target isn't an array?
            print('(');
            generateExpression(astNode.expr);
            print(')[');
            generateExpression(astNode.indexexpr1);
            print('][');
            generateExpression(astNode.indexexpr2);
            print(']');
            break;

        case 'index1d':
            print('(');
            generateExpression(astNode.expr);
            print(')[');
            generateExpression(astNode.indexexpr);
            print(']');
            break;

        case 'funccall':
            print('(');
            generateExpression(astNode.expr);
            print(')((');
            _.each(astNode.args, function(arg, i, args) {
                generateExpression(arg);
                if(i < args.length - 1) {
                    print('), (');
                }
            });
            print('))');
            break;

        default:
            throw new Error('Unknown expression type: "' + astNode.type + '"');
    }
};

var generateStatement = function(astNode, omitTerminator, omitIndentation) {
    if(arguments.length < 2) omitTerminator = false;
    switch(astNode.type) {

        case 'var':
            omitIndentation || printIndent();
            print('var ');
            print(astNode.list.join(', '));
            break;

        case 'assign':
            omitIndentation || printIndent();
            generateExpression(astNode.lval);
            print(' = ');
            generateExpression(astNode.rval);
            break;

        case 'scriptdef':
            omitIndentation || printIndent();
            print('function ');
            print(astNode.name);
            print('(');
            print(astNode.args.join(', '));
            print(') {\n');
            indent();
            // TODO this part of the AST doesn't seem quite right, suggesting there are
            // possibilities I'm not aware of.
            // These sanity checks will reject anything unexpected.
            /*if(!(_.isObject(astNode.stmts) && _(_.keys(astNode.stmts).sort()).isEqual(['list', 'type']) && astNode.stmts.type === 'statements' && _.isArray(astNode.stmts.list))) {
                throw new Error('Failed sanity checks on stmts!')
            }
            _.each(astNode.stmts.list, generateStatement)*/
            generateStatement(astNode.stmts);
            outdent();
            omitIndentation || printIndent();
            print('}');
            break;

        case 'switch':
            omitIndentation || printIndent();
            print('switch(');
            generateExpression(astNode.expr);
            print(') {\n');
            indent();
            _.each(astNode.cases, function(caseNode) {
                generateCase(caseNode);
            });
            outdent();
            omitIndentation || printIndent();
            print('}');
            break;

        case 'for':
            omitIndentation || printIndent();
            print('for(');
            generateStatement(astNode.initstmt, true, true);
            print('; ');
            generateExpression(astNode.contexpr);
            print('; ');
            generateStatement(astNode.stepstmt, true, true);
            print(') {\n');
            indent();
            // TODO I bet there are some scoping issues I'm not dealing with correctly.
            generateStatement(astNode.stmt);
            outdent();
            omitIndentation || printIndent();
            print('}');
            break;

        case 'cmpassign':
            // Rewrite the cmpassign into a simpler binop and assign combo.
            // E.g. a += 1 becomes a = a + 1
            // TODO this will produce somewhat uglier code.  Maybe pretty it up later.
            // TODO what if the lval contains a function call?  Will it execute twice?
            generateStatement({
                type: 'assign',
                lval: astNode.lval,
                rval: {
                    type: 'binop',
                    op: astNode.op,
                    expr1: astNode.lval,
                    expr2: astNode.rval
                }
            }, omitTerminator, omitIndentation);
            break;

        case 'ifelse':
            omitIndentation || printIndent();
            print('if(');
            generateExpression(astNode.expr);
            print(') {\n');
            indent();
            generateStatement(astNode.stmt1);
            outdent();
            omitIndentation || printIndent();
            print('} else {\n');
            indent();
            generateStatement(astNode.stmt2);
            outdent();
            omitIndentation || printIndent();
            print('}');
            break;

        case 'break':
            omitIndentation || printIndent();
            print('break');
            // TODO are break semantics ever different in Angl than they are in JS?
            break;

        case 'statements':
            _.each(astNode.list, function(statement) {
                generateStatement(statement);
            });
            break;

        case 'funccall':
            // Delegate to the expression generator
            omitIndentation || printIndent();
            generateExpression(astNode);
            break;

        case 'with':
            // TODO I DONT WANNA IMPLEMENT THIS WAAAAAH
            // Also it requires some sort of runtime that can find all instances of
            // a given object type to iterate over.
            // For now, I'm emitting a comment that explains code has been omitted.
            omitIndentation || printIndent();
            print('/* with(){} block has been omitted.  Not implemented yet.*/');
            break;

        case 'return':
            // TODO is there ever a situation where a Javascript 'return' won't do what we want?
            // For example, inside a _.each() iterator function
            omitIndentation || printIndent();
            print('return (');
            generateExpression(astNode.expr);
            print(')');
            break;

        case 'exit':
            // TODO same caveats as 'return'
            omitIndentation || printIndent();
            print('return');
            break;

        case 'nop':
            // No-ops don't do anything.  I'm assuming they never trigger any behavior by
            // "seperating" adjacent statements.
            break;

        default:
            throw new Error('Unknown statement type: "' + astNode.type + '"');
    }
    // Statements are terminated by a semicolon and a newline
    // except for a few exceptions.
    // Also, in certain contexts we want to omit this termination
    // (e.g., initializer statement of a for loop)
    if(!_.contains(['nop', 'statements'], astNode.type) && !omitTerminator) {
        print(';\n');
    }
};

var generateCase = function(astNode) {
    switch(astNode.type) {

        case 'case':
            printIndent();
            print('case (');
            generateExpression(astNode.expr);
            print('):\n');
            indent();
            generateStatement(astNode.stmts);
            outdent();
            break;

        case 'defaultcase':
            printIndent();
            print('default:\n');
            indent();
            generateStatement(astNode.stmts);
            outdent();
            break;

        default:
            throw new Error('Unknown case type: "' + astNode.type + '"');
    }
};

var generateTopNode = function(astNode) {
    switch(astNode.type) {

        case 'statements':
            // delegate to the statement generator
            generateStatement(astNode);
            break;

        default:
            throw new Error('Unknown root node type: "' + astNode.type + '"');
    }
};

var compile = module.exports = function(ast) {
    initializeCompiler();
    generateTopNode(ast);
    return _.flatten(buffer).join('');
};

<commit_msg>Fixed bug where function invocation with no arguments would emit invalid javascript<commit_after>var _ = require('lodash');

var buffer
  , print
  , indentationLevel
  ;

var initializeCompiler = function() {
    buffer = [];
    print = _.bind(buffer.push, buffer);
    indentationLevel = 0;
};

var indent = function() {
    indentationLevel++;
};

var outdent = function() {
    indentationLevel--;
    if(indentationLevel < 0) {
        throw new Error('Tried to outdent too far.');
    }
};

var printIndent = function() {
    // TODO create customizable indentation level
    // TODO make this faster?
    _.times(indentationLevel, function() {
        print('    ');
    });
};

// TODO properly translate all binops and unops:
//   ones that GML has that JS doesn't have
//   ones with different behavior that need to be implemented differently
//   DIV, MOD, ^^, bitwise ops
//   how does GML do type coercion (42 + "hello world")?  Do I need to emulate that behavior?
var generateExpression = function(astNode) {
    switch(astNode.type) {

        case 'identifier':
            print(astNode.name);
            // TODO will this ever need to be enclosed in parentheses?
            // How should I be handling this in the general case?
            break;

        case 'binop':
            print('(');
            // special-case the dot operator
            if(astNode.op === '.') {
                print('resolveObjectBeforeDot(');
                generateExpression(astNode.expr1);
                print(').');
                generateExpression(astNode.expr2);
            } else { // all other operators
                generateExpression(astNode.expr1);
                print(' ' + astNode.op + ' ');
                generateExpression(astNode.expr2);
            }
            print(')');
            break;

        case 'unop':
            print('(');
            print(astNode.op);
            generateExpression(astNode.expr);
            print(')');
            break;

        case 'number':
            print('(');
            print(astNode.val.toString());
            // TODO does toString always produce valid Javascript that will create the exact same number?
            print(')');
            break;

        case 'string':
            print('(');
            print(JSON.stringify(astNode.val));
            // TODO this fails in a select few corner cases.  Use something better,
            // perhaps stolen from the Jade source code
            print(')');
            break;

        case 'index2d':
            // TODO this needs a lot of work
            // What do we do when index values aren't numbers?  Aren't integers?
            // What about when the array isn't initialized or the target isn't an array?
            print('(');
            generateExpression(astNode.expr);
            print(')[');
            generateExpression(astNode.indexexpr1);
            print('][');
            generateExpression(astNode.indexexpr2);
            print(']');
            break;

        case 'index1d':
            print('(');
            generateExpression(astNode.expr);
            print(')[');
            generateExpression(astNode.indexexpr);
            print(']');
            break;

        case 'funccall':
            print('(');
            generateExpression(astNode.expr);
            print(')(');
            _.each(astNode.args, function(arg, i, args) {
                generateExpression(arg);
                if(i < args.length - 1) {
                    print(', ');
                }
            });
            print(')');
            break;

        default:
            throw new Error('Unknown expression type: "' + astNode.type + '"');
    }
};

var generateStatement = function(astNode, omitTerminator, omitIndentation) {
    if(arguments.length < 2) omitTerminator = false;
    switch(astNode.type) {

        case 'var':
            omitIndentation || printIndent();
            print('var ');
            print(astNode.list.join(', '));
            break;

        case 'assign':
            omitIndentation || printIndent();
            generateExpression(astNode.lval);
            print(' = ');
            generateExpression(astNode.rval);
            break;

        case 'scriptdef':
            omitIndentation || printIndent();
            print('function ');
            print(astNode.name);
            print('(');
            print(astNode.args.join(', '));
            print(') {\n');
            indent();
            // TODO this part of the AST doesn't seem quite right, suggesting there are
            // possibilities I'm not aware of.
            // These sanity checks will reject anything unexpected.
            /*if(!(_.isObject(astNode.stmts) && _(_.keys(astNode.stmts).sort()).isEqual(['list', 'type']) && astNode.stmts.type === 'statements' && _.isArray(astNode.stmts.list))) {
                throw new Error('Failed sanity checks on stmts!')
            }
            _.each(astNode.stmts.list, generateStatement)*/
            generateStatement(astNode.stmts);
            outdent();
            omitIndentation || printIndent();
            print('}');
            break;

        case 'switch':
            omitIndentation || printIndent();
            print('switch(');
            generateExpression(astNode.expr);
            print(') {\n');
            indent();
            _.each(astNode.cases, function(caseNode) {
                generateCase(caseNode);
            });
            outdent();
            omitIndentation || printIndent();
            print('}');
            break;

        case 'for':
            omitIndentation || printIndent();
            print('for(');
            generateStatement(astNode.initstmt, true, true);
            print('; ');
            generateExpression(astNode.contexpr);
            print('; ');
            generateStatement(astNode.stepstmt, true, true);
            print(') {\n');
            indent();
            // TODO I bet there are some scoping issues I'm not dealing with correctly.
            generateStatement(astNode.stmt);
            outdent();
            omitIndentation || printIndent();
            print('}');
            break;

        case 'cmpassign':
            // Rewrite the cmpassign into a simpler binop and assign combo.
            // E.g. a += 1 becomes a = a + 1
            // TODO this will produce somewhat uglier code.  Maybe pretty it up later.
            // TODO what if the lval contains a function call?  Will it execute twice?
            generateStatement({
                type: 'assign',
                lval: astNode.lval,
                rval: {
                    type: 'binop',
                    op: astNode.op,
                    expr1: astNode.lval,
                    expr2: astNode.rval
                }
            }, omitTerminator, omitIndentation);
            break;

        case 'ifelse':
            omitIndentation || printIndent();
            print('if(');
            generateExpression(astNode.expr);
            print(') {\n');
            indent();
            generateStatement(astNode.stmt1);
            outdent();
            omitIndentation || printIndent();
            print('} else {\n');
            indent();
            generateStatement(astNode.stmt2);
            outdent();
            omitIndentation || printIndent();
            print('}');
            break;

        case 'break':
            omitIndentation || printIndent();
            print('break');
            // TODO are break semantics ever different in Angl than they are in JS?
            break;

        case 'statements':
            _.each(astNode.list, function(statement) {
                generateStatement(statement);
            });
            break;

        case 'funccall':
            // Delegate to the expression generator
            omitIndentation || printIndent();
            generateExpression(astNode);
            break;

        case 'with':
            // TODO I DONT WANNA IMPLEMENT THIS WAAAAAH
            // Also it requires some sort of runtime that can find all instances of
            // a given object type to iterate over.
            // For now, I'm emitting a comment that explains code has been omitted.
            omitIndentation || printIndent();
            print('/* with(){} block has been omitted.  Not implemented yet.*/');
            break;

        case 'return':
            // TODO is there ever a situation where a Javascript 'return' won't do what we want?
            // For example, inside a _.each() iterator function
            omitIndentation || printIndent();
            print('return (');
            generateExpression(astNode.expr);
            print(')');
            break;

        case 'exit':
            // TODO same caveats as 'return'
            omitIndentation || printIndent();
            print('return');
            break;

        case 'nop':
            // No-ops don't do anything.  I'm assuming they never trigger any behavior by
            // "seperating" adjacent statements.
            break;

        default:
            throw new Error('Unknown statement type: "' + astNode.type + '"');
    }
    // Statements are terminated by a semicolon and a newline
    // except for a few exceptions.
    // Also, in certain contexts we want to omit this termination
    // (e.g., initializer statement of a for loop)
    if(!_.contains(['nop', 'statements'], astNode.type) && !omitTerminator) {
        print(';\n');
    }
};

var generateCase = function(astNode) {
    switch(astNode.type) {

        case 'case':
            printIndent();
            print('case (');
            generateExpression(astNode.expr);
            print('):\n');
            indent();
            generateStatement(astNode.stmts);
            outdent();
            break;

        case 'defaultcase':
            printIndent();
            print('default:\n');
            indent();
            generateStatement(astNode.stmts);
            outdent();
            break;

        default:
            throw new Error('Unknown case type: "' + astNode.type + '"');
    }
};

var generateTopNode = function(astNode) {
    switch(astNode.type) {

        case 'statements':
            // delegate to the statement generator
            generateStatement(astNode);
            break;

        default:
            throw new Error('Unknown root node type: "' + astNode.type + '"');
    }
};

var compile = module.exports = function(ast) {
    initializeCompiler();
    generateTopNode(ast);
    return _.flatten(buffer).join('');
};

<|endoftext|>


<commit_before>/*
 * fis
 * http://fis.baidu.com/
 */

'use strict';
var _ = require('./util.js');

function getReleaseExt(ext) {
  if (ext) {
    var rExt = fis.config.env().get('project.ext' + ext);
    if (rExt) {
      ext = normalizeExt(rExt);
    }
  }
  return ext;
}

function normalizeExt(ext) {
  if (ext[0] !== '.') {
    ext = '.' + ext;
  }
  return ext;
}

function normalizePath(path, reg, rExt) {
  return path
    .replace(reg, '')
    .replace(/[:*?"<>|]/g, '_') + rExt;
}

function addHash(path, file) {
  var rExt = file.rExt,
    qRExt = fis.util.escapeReg(rExt),
    qExt = fis.util.escapeReg(file.ext),
    hash = file.getHash(),
    onnector = fis.config.env().get('project.md5Connector', '_'),
    reg = new RegExp(qRExt + '$|' + qExt + '$', 'i');
  return path.replace(reg, '') + onnector + hash + rExt;
}

function getDomainsByPath(path) {
  var domain = fis.config.env().get('project.domain', {}),
    value = [];
  if (typeof domain === 'string') {
    value = domain.split(/\s*,\s*/);
  } else if (fis.util.is(domain, 'Array')) {
    value = domain;
  } else {
    fis.util.map(domain, function(pattern, domain) {
      if ((pattern === 'image' && fis.util.isImageFile(path)) || fis.util.glob(pattern, path)) {
        if (typeof domain === 'string') {
          value = domain.split(/\s*,\s*/);
        } else if (fis.util.is(domain, 'Array')) {
          value = domain;
        } else {
          fis.log.warning('invalid domain [' + domain + '] of [project.domain.' + pattern + ']');
        }
        return true;
      }
    });
  }
  return value;
}

function getDomain(path) {
  var hash = fis.util.md5(path),
    domains = getDomainsByPath(path),
    len = domains.length,
    domain = '';
  if (len) {
    domain = domains[hash.charCodeAt(0) % len];
  }
  return domain;
}

function applyMatches(obj, path, matches) {
  matches.forEach(function(item) {
    var properties = item.properties || {};
    var keys = Object.keys(properties);

    if (!keys.length) {
      return;
    }

    var m = item.reg.exec(path);
    var match = !!m;

    if (match !== item.negate) {
      keys.forEach(function(key) {
        var value = properties[key];

        if (typeof value === 'string') {
          value = value.replace(/\$(\d+|&)/g, function(_, k) {
            k = k === '&' ? 0 : k;
            return m[k] || '';
          });
        }

        var useKey = 'use' + key.charAt(0).toUpperCase() + key.substr(1);
        if (typeof obj[useKey] !== 'undefined') {
          obj[useKey] = true;
        }

        if (typeof value === 'object' && typeof obj[key] === 'object') {
          fis.util.assign(obj[key], value, true);
        } else {
          obj[key] = value;
        }
      });
    }
  });
}

var File = Object.derive(function() {
  var _ = fis.util;
  var self = _.assign(this, _.pathinfo(arguments));
  var ext = self.ext;
  var rExt = this.rExt;
  var realpath = this.realpath = _.realpathSafe(self.fullname);
  var realpathNoExt = this.realpathNoExt = self.rest;
  var root = fis.project.getProjectPath();

  if (!rExt) {
    rExt = this.rExt = getReleaseExt(ext);
  }

  this.useCompile = true;
  this.useDomain = false;
  this.useCache = true;
  this.useHash = false;
  this.useMap = false;

  this.domain = '';

  this._isImage = true;
  this._isText = false;

  this.requires = [];
  this.links = [];
  this.asyncs = [];
  this.extras = {};
  this.derived = [];

  this._likes = {};
  this.defineLikes();

  if (_.isTextFile(rExt)) {
    this._isImage = false;
    this._isText = true;
    this.charset = null;

    var map = {
      isJsLike: [
        '.js',
        '.jsx',
        '.coffee'
      ],

      isCssLike: [
        '.css',
        '.less',
        '.sass',
        '.styl',
        '.scss'
      ],

      isHtmlLike: [
        '.html',
        '.xhtml',
        '.shtml',
        '.htm',
        '.tpl',
        '.ftl',
        '.vm',
        '.php',
        '.phtml',
        '.jsp',
        '.asp',
        '.aspx',
        '.ascx',
        '.cshtml',
        '.master',
      ],

      isJsonLike: [
        '.json'
      ]
    };

    Object.keys(map).every(function(key) {
      var list = map[key];

      if (~list.indexOf(rExt)) {
        self[key] = true;
        return false;
      }

      return true;
    });
  } else if (_.isImageFile(rExt)) {
    this.useDomain = true;
    this.useHash = rExt !== '.ico';
  } else {
    this.useCompile = false;
  }

  if (realpath.indexOf(root) === 0) {
    //subpath
    var len = root.length,
      subpath;
    this.subpath = subpath = realpath.substring(len);
    this.subdirname = self.dirname.substring(len);
    this.subpathNoExt = realpathNoExt.substring(len);

    applyMatches(this, this.subpath, fis.media().getSortedMatches());

    //release
    if (this.release === false) {
      this.useMap = false;
      var self = this;
      Object.defineProperty(this, 'url', {
        enumerable: true,
        get: function() {
          fis.log.error('unreleasable file [' + self.realpath + ']');
        }
      });
    } else {
      this.useMap = this.isMod ? true : this.useMap;
      //release & url
      var reg = new RegExp(_.escapeReg(ext) + '$|' + _.escapeReg(rExt) + '$', 'i');
      var release;
      if (this.release) {
        release = this.release.replace(/[\/\\]+/g, '/');
        if (release[0] !== '/') {
          release = '/' + release;
        }
      } else {
        release = this.subpath;
      }
      this.release = normalizePath(release, reg, rExt);
      this.url = this.url ? normalizePath(this.url, reg, rExt) : this.release;
    }

    //charset
    if (this._isText) {
      this.charset = (
        this.charset || fis.config.env().get('project.charset', 'utf8')
      ).toLowerCase();
    }

    //file id
    var id = this.id || subpath.replace(/^\//, '');
    var ns = fis.config.env().get('namespace');
    if (ns) {
      id = ns + fis.config.env().get('namespaceConnector', ':') + id;
    }
    this.id = id;

    // this.moduleId = this.moduleId || this.id.replace(new RegExp(_.escapeReg(ext) + '$', 'i'), '');
  }
}, {
  defineLikes: function() {
    if (typeof this.isHtmlLike !== 'undefined') {
      return;
    }

    var likes = ['isHtmlLike', 'isJsLike', 'isCssLike'];
    var props = {};

    likes.forEach(function(v) {
      props[v] = {
        set: (function(prop) {
          return function(val) {

            if (val === false) {
              this._likes[v] = false;
              return;
            }

            var that = this;
            likes.forEach(function(v) {
              if (prop === v) {
                that._likes[v] = true
              } else {
                that._likes[v] = false;
              }
            });
          }
        })(v),
        get: (function(prop) {
          return function() {
            return this._likes[prop];
          };
        })(v)
      };
    });

    Object.defineProperties(this, props);
  },
  exists: function() {
    return fis.util.exists(this.realpath);
  },
  isText: function() {
    return this._isText;
  },
  isImage: function() {
    return this._isImage;
  },
  toString: function() {
    return this.realpath;
  },
  getMtime: function() {
    return fis.util.mtime(this.realpath) || new Date();
  },
  isFile: function() {
    return fis.util.isFile(this.realpath);
  },
  isDir: function() {
    return fis.util.isDir(this.realpath);
  },
  setContent: function(c) {
    this._content = c;
    return this;
  },
  getContent: function() {
    if (typeof this._content === 'undefined') {
      this._content = fis.util.read(this.realpath, this.isText());
    }
    return this._content;
  },
  getHash: function() {
    if (typeof this._md5 === 'undefined') {
      Object.defineProperty(this, '_md5', {
        value: fis.util.md5(this.getContent()),
        writable: false
      });
    }
    return this._md5;
  },
  getBase64: function(prefix) {
    prefix = typeof prefix === 'undefined' ? true : prefix;
    if (prefix) {
      prefix = 'data:' + fis.util.getMimeType(this.rExt) + ';base64,';
    } else {
      prefix = '';
    }
    return prefix + fis.util.base64(this._content);
  },
  getId: function() {
    return this.id;
  },
  getUrl: function() {
    var url = this.url;
    if (this.useHash) {
      url = addHash(url, this);
    }
    if (this.useDomain) {
      if (!this.domain) {
        this.domain = getDomain(this.subpath);
      }
      url = this.domain + url;
    }
    return url + this.query;
  },
  getHashRelease: function(release) {
    release = release || this.release;
    if (release) {
      if (this.useHash) {
        return addHash(release, this);
      } else {
        return release;
      }
    } else {
      fis.log.error('unreleasable file [' + this.realpath + ']');
    }
  },
  addRequire: function(id) {
    if (id && (id = id.trim())) {
      if (!~this.requires.indexOf(id)) {
        this.requires.push(id);
      }

      // 如果在异步依赖中，则需要把它删了。
      var idx;
      if (~(idx = this.asyncs.indexOf(id))) {
        this.asyncs.splice(idx, 1);
      }

      return id;
    }
    return false;
  },
  addAsyncRequire: function(id) {
    if (id && (id = id.trim())) {

      // 已经在同步依赖中，则忽略
      if (~this.requires.indexOf(id)) {
        return id;
      }

      if (!~this.asyncs.indexOf(id)) {
        this.asyncs.push(id);
      }

      // 兼容老的用法。
      this.extras.async = this.asyncs.concat();
      return id;
    }
    return false;
  },

  addLink: function(filepath) {
    var links = this.links;

    ~links.indexOf(filepath) || links.push(filepath);
  },

  addSameNameRequire: function(ext) {
    var path;
    if (fis.util.isFile(this.realpathNoExt + ext)) {
      path = './' + this.filename + ext;
    } else {
      var map = fis.config.env().get('project.ext');
      for (var key in map) {
        if (map.hasOwnProperty(key)) {
          var oExt = normalizeExt(key);
          var rExt = normalizeExt(map[key]);
          if (rExt === ext && fis.util.isFile(this.realpathNoExt + oExt)) {
            path = './' + this.filename + oExt;
            break;
          }
        }
      }
    }
    if (path) {
      var info = fis.uri.getId(path, this.dirname);
      if (info.file && info.file.useMap && !~this.asyncs.indexOf(info.id)) {
        this.addLink(info.file.subpath);
        this.addRequire(info.id);
      }
    }
  },

  removeRequire: function(id) {
    var pos = this.requires.indexOf(id);
    if (pos > -1) {
      this.requires.splice(pos, 1);
    }
  },

  removeAsyncRequire: function(id) {
    var pos = this.asyncs.indexOf(id);
    if (pos > -1) {
      this.asyncs.splice(pos, 1);

      // 兼容老的用法。
      this.extras.async = this.asyncs.concat();
    }
  },

  getCacheData: function() {
    return {
      requires: this.requires,
      extras: this.extras,
      links: this.links,
      derived: this.derived,
      release: this.release,
      useMap: this.useMap
    };
  },

  revertFromCacheData: function(cached) {
    _.assign(this, cached);
  }
});

module.exports = File.factory();
module.exports.wrap = function(file) {
  if (typeof file === 'string') {
    return new File(file);
  } else if (file instanceof File) {
    return file;
  } else {
    fis.log.error('unable to convert [' + (typeof file) + '] to [File] object.');
  }
};
<commit_msg>rm useless code<commit_after>/*
 * fis
 * http://fis.baidu.com/
 */

'use strict';
var _ = require('./util.js');

function getReleaseExt(ext) {
  if (ext) {
    var rExt = fis.config.env().get('project.ext' + ext);
    if (rExt) {
      ext = normalizeExt(rExt);
    }
  }
  return ext;
}

function normalizeExt(ext) {
  if (ext[0] !== '.') {
    ext = '.' + ext;
  }
  return ext;
}

function normalizePath(path, reg, rExt) {
  return path
    .replace(reg, '')
    .replace(/[:*?"<>|]/g, '_') + rExt;
}

function addHash(path, file) {
  var rExt = file.rExt,
    qRExt = fis.util.escapeReg(rExt),
    qExt = fis.util.escapeReg(file.ext),
    hash = file.getHash(),
    onnector = fis.config.env().get('project.md5Connector', '_'),
    reg = new RegExp(qRExt + '$|' + qExt + '$', 'i');
  return path.replace(reg, '') + onnector + hash + rExt;
}

function getDomainsByPath(path) {
  var domain = fis.config.env().get('project.domain', {}),
    value = [];
  if (typeof domain === 'string') {
    value = domain.split(/\s*,\s*/);
  } else if (fis.util.is(domain, 'Array')) {
    value = domain;
  } else {
    fis.util.map(domain, function(pattern, domain) {
      if ((pattern === 'image' && fis.util.isImageFile(path)) || fis.util.glob(pattern, path)) {
        if (typeof domain === 'string') {
          value = domain.split(/\s*,\s*/);
        } else if (fis.util.is(domain, 'Array')) {
          value = domain;
        } else {
          fis.log.warning('invalid domain [' + domain + '] of [project.domain.' + pattern + ']');
        }
        return true;
      }
    });
  }
  return value;
}

function getDomain(path) {
  var hash = fis.util.md5(path),
    domains = getDomainsByPath(path),
    len = domains.length,
    domain = '';
  if (len) {
    domain = domains[hash.charCodeAt(0) % len];
  }
  return domain;
}

function applyMatches(obj, path, matches) {
  matches.forEach(function(item) {
    var properties = item.properties || {};
    var m = item.reg.exec(path);
    var match = !!m;

    if (match !== item.negate) {
      _.assign(obj, properties, true);
    }
  });
}

var File = Object.derive(function() {
  var _ = fis.util;
  var self = _.assign(this, _.pathinfo(arguments));
  var ext = self.ext;
  var rExt = this.rExt;
  var realpath = this.realpath = _.realpathSafe(self.fullname);
  var realpathNoExt = this.realpathNoExt = self.rest;
  var root = fis.project.getProjectPath();

  if (!rExt) {
    rExt = this.rExt = getReleaseExt(ext);
  }

  this.useCompile = true;
  this.useDomain = false;
  this.useCache = true;
  this.useHash = false;
  this.useMap = false;

  this.domain = '';

  this._isImage = true;
  this._isText = false;

  this.requires = [];
  this.links = [];
  this.asyncs = [];
  this.extras = {};
  this.derived = [];

  this._likes = {};
  this.defineLikes();

  if (_.isTextFile(rExt)) {
    this._isImage = false;
    this._isText = true;
    this.charset = null;

    var map = {
      isJsLike: [
        '.js',
        '.jsx',
        '.coffee'
      ],

      isCssLike: [
        '.css',
        '.less',
        '.sass',
        '.styl',
        '.scss'
      ],

      isHtmlLike: [
        '.html',
        '.xhtml',
        '.shtml',
        '.htm',
        '.tpl',
        '.ftl',
        '.vm',
        '.php',
        '.phtml',
        '.jsp',
        '.asp',
        '.aspx',
        '.ascx',
        '.cshtml',
        '.master',
      ],

      isJsonLike: [
        '.json'
      ]
    };

    Object.keys(map).every(function(key) {
      var list = map[key];

      if (~list.indexOf(rExt)) {
        self[key] = true;
        return false;
      }

      return true;
    });
  } else if (_.isImageFile(rExt)) {
    this.useDomain = true;
    this.useHash = rExt !== '.ico';
  } else {
    this.useCompile = false;
  }

  if (realpath.indexOf(root) === 0) {
    //subpath
    var len = root.length,
      subpath;
    this.subpath = subpath = realpath.substring(len);
    this.subdirname = self.dirname.substring(len);
    this.subpathNoExt = realpathNoExt.substring(len);

    applyMatches(this, this.subpath, fis.media().getSortedMatches());

    //release
    if (this.release === false) {
      this.useMap = false;
      var self = this;
      Object.defineProperty(this, 'url', {
        enumerable: true,
        get: function() {
          fis.log.error('unreleasable file [' + self.realpath + ']');
        }
      });
    } else {
      this.useMap = this.isMod ? true : this.useMap;
      //release & url
      var reg = new RegExp(_.escapeReg(ext) + '$|' + _.escapeReg(rExt) + '$', 'i');
      var release;
      if (this.release) {
        release = this.release.replace(/[\/\\]+/g, '/');
        if (release[0] !== '/') {
          release = '/' + release;
        }
      } else {
        release = this.subpath;
      }
      this.release = normalizePath(release, reg, rExt);
      this.url = this.url ? normalizePath(this.url, reg, rExt) : this.release;
    }

    //charset
    if (this._isText) {
      this.charset = (
        this.charset || fis.config.env().get('project.charset', 'utf8')
      ).toLowerCase();
    }

    //file id
    var id = this.id || subpath.replace(/^\//, '');
    var ns = fis.config.env().get('namespace');
    if (ns) {
      id = ns + fis.config.env().get('namespaceConnector', ':') + id;
    }
    this.id = id;

    // this.moduleId = this.moduleId || this.id.replace(new RegExp(_.escapeReg(ext) + '$', 'i'), '');
  }
}, {
  defineLikes: function() {
    if (typeof this.isHtmlLike !== 'undefined') {
      return;
    }

    var likes = ['isHtmlLike', 'isJsLike', 'isCssLike'];
    var props = {};

    likes.forEach(function(v) {
      props[v] = {
        set: (function(prop) {
          return function(val) {

            if (val === false) {
              this._likes[v] = false;
              return;
            }

            var that = this;
            likes.forEach(function(v) {
              if (prop === v) {
                that._likes[v] = true
              } else {
                that._likes[v] = false;
              }
            });
          }
        })(v),
        get: (function(prop) {
          return function() {
            return this._likes[prop];
          };
        })(v)
      };
    });

    Object.defineProperties(this, props);
  },
  exists: function() {
    return fis.util.exists(this.realpath);
  },
  isText: function() {
    return this._isText;
  },
  isImage: function() {
    return this._isImage;
  },
  toString: function() {
    return this.realpath;
  },
  getMtime: function() {
    return fis.util.mtime(this.realpath) || new Date();
  },
  isFile: function() {
    return fis.util.isFile(this.realpath);
  },
  isDir: function() {
    return fis.util.isDir(this.realpath);
  },
  setContent: function(c) {
    this._content = c;
    return this;
  },
  getContent: function() {
    if (typeof this._content === 'undefined') {
      this._content = fis.util.read(this.realpath, this.isText());
    }
    return this._content;
  },
  getHash: function() {
    if (typeof this._md5 === 'undefined') {
      Object.defineProperty(this, '_md5', {
        value: fis.util.md5(this.getContent()),
        writable: false
      });
    }
    return this._md5;
  },
  getBase64: function(prefix) {
    prefix = typeof prefix === 'undefined' ? true : prefix;
    if (prefix) {
      prefix = 'data:' + fis.util.getMimeType(this.rExt) + ';base64,';
    } else {
      prefix = '';
    }
    return prefix + fis.util.base64(this._content);
  },
  getId: function() {
    return this.id;
  },
  getUrl: function() {
    var url = this.url;
    if (this.useHash) {
      url = addHash(url, this);
    }
    if (this.useDomain) {
      if (!this.domain) {
        this.domain = getDomain(this.subpath);
      }
      url = this.domain + url;
    }
    return url + this.query;
  },
  getHashRelease: function(release) {
    release = release || this.release;
    if (release) {
      if (this.useHash) {
        return addHash(release, this);
      } else {
        return release;
      }
    } else {
      fis.log.error('unreleasable file [' + this.realpath + ']');
    }
  },
  addRequire: function(id) {
    if (id && (id = id.trim())) {
      if (!~this.requires.indexOf(id)) {
        this.requires.push(id);
      }

      // 如果在异步依赖中，则需要把它删了。
      var idx;
      if (~(idx = this.asyncs.indexOf(id))) {
        this.asyncs.splice(idx, 1);
      }

      return id;
    }
    return false;
  },
  addAsyncRequire: function(id) {
    if (id && (id = id.trim())) {

      // 已经在同步依赖中，则忽略
      if (~this.requires.indexOf(id)) {
        return id;
      }

      if (!~this.asyncs.indexOf(id)) {
        this.asyncs.push(id);
      }

      // 兼容老的用法。
      this.extras.async = this.asyncs.concat();
      return id;
    }
    return false;
  },

  addLink: function(filepath) {
    var links = this.links;

    ~links.indexOf(filepath) || links.push(filepath);
  },

  addSameNameRequire: function(ext) {
    var path;
    if (fis.util.isFile(this.realpathNoExt + ext)) {
      path = './' + this.filename + ext;
    } else {
      var map = fis.config.env().get('project.ext');
      for (var key in map) {
        if (map.hasOwnProperty(key)) {
          var oExt = normalizeExt(key);
          var rExt = normalizeExt(map[key]);
          if (rExt === ext && fis.util.isFile(this.realpathNoExt + oExt)) {
            path = './' + this.filename + oExt;
            break;
          }
        }
      }
    }
    if (path) {
      var info = fis.uri.getId(path, this.dirname);
      if (info.file && info.file.useMap && !~this.asyncs.indexOf(info.id)) {
        this.addLink(info.file.subpath);
        this.addRequire(info.id);
      }
    }
  },

  removeRequire: function(id) {
    var pos = this.requires.indexOf(id);
    if (pos > -1) {
      this.requires.splice(pos, 1);
    }
  },

  removeAsyncRequire: function(id) {
    var pos = this.asyncs.indexOf(id);
    if (pos > -1) {
      this.asyncs.splice(pos, 1);

      // 兼容老的用法。
      this.extras.async = this.asyncs.concat();
    }
  },

  getCacheData: function() {
    return {
      requires: this.requires,
      extras: this.extras,
      links: this.links,
      derived: this.derived,
      release: this.release,
      useMap: this.useMap
    };
  },

  revertFromCacheData: function(cached) {
    _.assign(this, cached);
  }
});

module.exports = File.factory();
module.exports.wrap = function(file) {
  if (typeof file === 'string') {
    return new File(file);
  } else if (file instanceof File) {
    return file;
  } else {
    fis.log.error('unable to convert [' + (typeof file) + '] to [File] object.');
  }
};
<|endoftext|>


<commit_before>'use strict';
var path = require('path');
var fs = require('fs');
var superb = require('superb');
var normalizeUrl = require('normalize-url');
var humanizeUrl = require('humanize-url');
var yeoman = require('yeoman-generator');
var _s = require('underscore.string');

module.exports = yeoman.generators.Base.extend({
	init: function () {
		var cb = this.async();

		this.prompt([{
			name: 'appName',
			message: 'What do you want to name your app?',
			default: this.appname.replace(/\s/g, '-'),
			filter: function (val) {
				return _s.slugify(val);
			}
		}, {
			name: 'githubUsername',
			message: 'What is your GitHub username?',
			store: true,
			validate: function (val) {
				return val.length > 0 ? true : 'You have to provide a username';
			}
		}, {
			name: 'website',
			message: 'What is the URL of your website?',
			store: true,
			validate: function (val) {
				return val.length > 0 ? true : 'You have to provide a website URL';
			},
			filter: function (val) {
				return normalizeUrl(val);
			}
		}], function (props) {
			this.appName = props.appName;
			this.classifiedAppName = _s.classify(props.appName);
			this.githubUsername = props.githubUsername;
			this.name = this.user.git.name();
			this.email = this.user.git.email();
			this.website = props.website;
			this.humanizedWebsite = humanizeUrl(this.website);
			this.superb = superb();

			this.template('editorconfig', '.editorconfig');
			this.template('gitattributes', '.gitattributes');
			this.template('gitignore', '.gitignore');
			this.template('jshintrc', '.jshintrc');
			this.template('index.js');
			this.template('index.html');
			this.template('index.css');
			this.template('license');
			// needed so npm doesn't try to use it and fail
			this.template('_package.json', 'package.json');
			this.template('readme.md');

			cb();
		}.bind(this));
	},
	install: function () {
		this.installDependencies({bower: false});
	}
});
<commit_msg>Remove useless `require` calls<commit_after>'use strict';
var superb = require('superb');
var normalizeUrl = require('normalize-url');
var humanizeUrl = require('humanize-url');
var yeoman = require('yeoman-generator');
var _s = require('underscore.string');

module.exports = yeoman.generators.Base.extend({
	init: function () {
		var cb = this.async();

		this.prompt([{
			name: 'appName',
			message: 'What do you want to name your app?',
			default: this.appname.replace(/\s/g, '-'),
			filter: function (val) {
				return _s.slugify(val);
			}
		}, {
			name: 'githubUsername',
			message: 'What is your GitHub username?',
			store: true,
			validate: function (val) {
				return val.length > 0 ? true : 'You have to provide a username';
			}
		}, {
			name: 'website',
			message: 'What is the URL of your website?',
			store: true,
			validate: function (val) {
				return val.length > 0 ? true : 'You have to provide a website URL';
			},
			filter: function (val) {
				return normalizeUrl(val);
			}
		}], function (props) {
			this.appName = props.appName;
			this.classifiedAppName = _s.classify(props.appName);
			this.githubUsername = props.githubUsername;
			this.name = this.user.git.name();
			this.email = this.user.git.email();
			this.website = props.website;
			this.humanizedWebsite = humanizeUrl(this.website);
			this.superb = superb();

			this.template('editorconfig', '.editorconfig');
			this.template('gitattributes', '.gitattributes');
			this.template('gitignore', '.gitignore');
			this.template('jshintrc', '.jshintrc');
			this.template('index.js');
			this.template('index.html');
			this.template('index.css');
			this.template('license');
			// needed so npm doesn't try to use it and fail
			this.template('_package.json', 'package.json');
			this.template('readme.md');

			cb();
		}.bind(this));
	},
	install: function () {
		this.installDependencies({bower: false});
	}
});
<|endoftext|>


<commit_before>'use babel';
/* globals atom */

import { CompositeDisposable } from 'atom';
import helpers from 'atom-linter';
import { parseString } from './xml2js-promise';
import _ from 'underscore';

export default {
  activate: () => {
    require('atom-package-deps').install('linter-cflint', true);
    atom.config.unset('linter-cflint.cflintPath');
    atom.config.unset('linter-cflint.javaPath');
    this.subscriptions = new CompositeDisposable;
  },

  deactivate: () => {
    return this.subscriptions.dispose();
  },

  provideLinter: () => {
    return {
      name: 'cflint',
      grammarScopes: [
        'text.html.cfml',
        'source.cfscript.embedded',
        'punctuation.definition.tag.cfml',
        'source.cfscript',
      ],
      scope: 'file',
      lintOnFly: true,
      lint: (textEditor) => {
        return new Promise(resolve => {
          require('find-java-home')((err, home) => {
            const filePath = textEditor.getPath();
            const cflintPath = atom.packages.resolvePackagePath('linter-cflint') + '/bin/CFLint-0.5.0-all.jar';
            const javaPath = home + '/bin/java';
            const javaArgs = [ '-jar', cflintPath, '-q', '-stdout', '-stdin', '-xml'];
            helpers.exec(javaPath, javaArgs, {
              stdin: textEditor.getText(),
              stdio: 'pipe',
              encoding: 'utf8',
              throwOnStdErr: false,
            })
            .then(xmlResult => {
              let lintXML = xmlResult;
              if (lintXML.trim()[0] !== '<') {
                lintXML = lintXML.split('\n').slice(1).join('\n');
              }
              return parseString(lintXML);
            })
            .then(result => {
              const messages =
                _.chain(result.issues.issue)
                .map(issue => {
                  const line = parseInt(issue.location[0].$.line, 10);
                  return {
                    filePath: filePath,
                    type: issue.$.severity in ['FATAL', 'CRITICAL', 'ERROR'] ? 'Error' : 'Warning',
                    text: issue.location[0].$.message,
                    line: parseInt(issue.location[0].$.line, 10) - 1,
                    range: helpers.rangeFromLineNumber(textEditor, line - 1, issue.location[0].$.column),
                  };
                })
                .value();
              resolve(messages);
            });
          });
        });
      },
    };
  },
};
<commit_msg>:bug: Sort issues by line number again<commit_after>'use babel';
/* globals atom */

import { CompositeDisposable } from 'atom';
import helpers from 'atom-linter';
import { parseString } from './xml2js-promise';
import _ from 'underscore';

export default {
  activate: () => {
    require('atom-package-deps').install('linter-cflint', true);
    atom.config.unset('linter-cflint.cflintPath');
    atom.config.unset('linter-cflint.javaPath');
    this.subscriptions = new CompositeDisposable;
  },

  deactivate: () => {
    return this.subscriptions.dispose();
  },

  provideLinter: () => {
    return {
      name: 'cflint',
      grammarScopes: [
        'text.html.cfml',
        'source.cfscript.embedded',
        'punctuation.definition.tag.cfml',
        'source.cfscript',
      ],
      scope: 'file',
      lintOnFly: true,
      lint: (textEditor) => {
        return new Promise(resolve => {
          require('find-java-home')((err, home) => {
            const filePath = textEditor.getPath();
            const cflintPath = atom.packages.resolvePackagePath('linter-cflint') + '/bin/CFLint-0.5.0-all.jar';
            const javaPath = home + '/bin/java';
            const javaArgs = [ '-jar', cflintPath, '-q', '-stdout', '-stdin', '-xml'];
            helpers.exec(javaPath, javaArgs, {
              stdin: textEditor.getText(),
              stdio: 'pipe',
              encoding: 'utf8',
              throwOnStdErr: false,
            })
            .then(xmlResult => {
              let lintXML = xmlResult;
              if (lintXML.trim()[0] !== '<') {
                lintXML = lintXML.split('\n').slice(1).join('\n');
              }
              return parseString(lintXML);
            })
            .then(result => {
              const messages =
                _.chain(result.issues.issue)
                .map(issue => {
                  const line = parseInt(issue.location[0].$.line, 10);
                  return {
                    filePath: filePath,
                    type: issue.$.severity in ['FATAL', 'CRITICAL', 'ERROR'] ? 'Error' : 'Warning',
                    text: issue.location[0].$.message,
                    line: parseInt(issue.location[0].$.line, 10) - 1,
                    range: helpers.rangeFromLineNumber(textEditor, line - 1, issue.location[0].$.column),
                  };
                })
                .sortBy(issue => issue.line)
                .value();
              resolve(messages);
            });
          });
        });
      },
    };
  },
};
<|endoftext|>


<commit_before>'use strict';

// Multi-sandbox support
// Maintains multiple independent execution contexts for JavaScript, using sandboxed iframes (unique origins)

let nextSbID = 0;
let iframes = new Map();

// Create a new sandboxed execution context
function newsb() {
  const container = document.getElementById('sandboxes');

  const iframe = document.createElement('iframe');
  const sbID = nextSbID;
  nextSbID += 1;

  iframes.set(sbID, iframe);

  iframe.setAttribute('id', 'sandbox-' + sbID);
  iframe.setAttribute('src', 'sandbox.html');
  iframe.addEventListener('load', (event) => {
    console.log('sandbox frame load',sbID);
    iframe.contentWindow.postMessage({cmd: 'ping', sbID: sbID}, '*');
  });

  container.appendChild(iframe);

  return iframe;
}

// Send a message to the sandboxed iframe
function postSandbox(sbID, msg) {
  const iframe = iframes.get(sbID);
  if (!iframe) throw new Error(`no such sandbox: ${sbID}`);

  iframe.contentWindow.postMessage(msg, '*');
}

// Evaluate code within a given sandbox
function evalin(sbID, code) {
  postSandbox(sbID, {cmd: 'eval', code: code});
}

module.exports = {
  newsb,
  evalin,
  postSandbox,
};
<commit_msg>Start sandbox ID ('pid') at 1 so its always truthy<commit_after>'use strict';

// Multi-sandbox support
// Maintains multiple independent execution contexts for JavaScript, using sandboxed iframes (unique origins)

let nextSbID = 1;
let iframes = new Map();

// Create a new sandboxed execution context
function newsb() {
  const container = document.getElementById('sandboxes');

  const iframe = document.createElement('iframe');
  const sbID = nextSbID;
  nextSbID += 1;

  iframes.set(sbID, iframe);

  iframe.setAttribute('id', 'sandbox-' + sbID);
  iframe.setAttribute('src', 'sandbox.html');
  iframe.addEventListener('load', (event) => {
    console.log('sandbox frame load',sbID);
    iframe.contentWindow.postMessage({cmd: 'ping', sbID: sbID}, '*');
  });

  container.appendChild(iframe);

  return iframe;
}

// Send a message to the sandboxed iframe
function postSandbox(sbID, msg) {
  const iframe = iframes.get(sbID);
  if (!iframe) throw new Error(`no such sandbox: ${sbID}`);

  iframe.contentWindow.postMessage(msg, '*');
}

// Evaluate code within a given sandbox
function evalin(sbID, code) {
  postSandbox(sbID, {cmd: 'eval', code: code});
}

module.exports = {
  newsb,
  evalin,
  postSandbox,
};
<|endoftext|>


<commit_before>/** @babel */

import * as path from 'path';
import { CompositeDisposable } from 'atom';
import config from './config';
import SymbolsView from './symbols-view';

class Package {

  activate() {
    this.config = config.schema;
    this.overrideCommands = null;
    this.symbolsView = null;
    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(
      config.watchOverrideCommands(updateOverrideCommands.bind(this)),
      config.watchToggleFileSymbolsCommand(() => updateOverrideCommands.bind(this)()),
      config.watchToggleProjectSymbolsCommand(() => updateOverrideCommands.bind(this)()),
      atom.commands.add('atom-text-editor', 'rustsym:toggle-file-symbols', this.toggleFileSymbols.bind(this)),
      atom.commands.add('atom-workspace', 'rustsym:toggle-project-symbols', this.toggleProjectSymbols.bind(this)),
    );
    // Call required to set up initial state for override commands
    updateOverrideCommands.bind(this)();
  }

  deactivate() {
    if (this.symbolsView) {
      this.symbolsView.destroy();
      this.symbolsView = null;
    }
    if (this.overrideCommands) {
      this.overrideCommands.dispose();
      this.overrideCommands = null;
    }
    if (this.subscriptions) {
      this.subscriptions.dispose();
      this.subscriptions = null;
    }
  }

  isEditingRust() {
    let editor = atom.workspace.getActiveTextEditor();
    if (!editor) return false;
    return path.extname(editor.getPath()) === '.rs';
  }

  toggleFileSymbols(event) {
    if (!initializeSymbolsView.bind(this)(event)) return;
    this.symbolsView.toggleFileSymbols(event.target);
  }

  toggleProjectSymbols(event) {
    if (!initializeSymbolsView.bind(this)(event)) return;
    this.symbolsView.toggleProjectSymbols(event.target);
  }

}

function initializeSymbolsView(event) {
  if (!this.isEditingRust()) return false;
  // Consume triggering event
  event.stopImmediatePropagation();
  if (this.symbolsView == null) {
    this.symbolsView = new SymbolsView();
  }
  return true;
}

function prioritizeCommandListener(command, listenerName) {
  let listeners = atom.commands.selectorBasedListenersByCommandName[command];
  let listener = listeners.find(
    // Allow substring comparison as bound functions will have their names
    // altered slightly (i.e. 'bound <fn-name>')
    listener => listener.callback.name.indexOf(listenerName) !== -1
  );
  // Although setting the lowest possible specificity should be enough to
  // guarantee the listener of interest is preferred, an extra precaution
  // would be to rearrange all listeners for the command such that the listener
  // of interest is the first item in the collection
  listener.specificity = -Infinity;
}

function updateOverrideCommands(enableOverrides) {
  // Clean up and rebind all override commands for simplicity
  if (this.overrideCommands != null) {
    this.overrideCommands.dispose();
    this.overrideCommands = null;
  }
  // Update using current override commands state if none is given
  if (typeof enableOverrides === 'undefined') {
    enableOverrides = config.isOverrideCommandsEnabled();
  }
  if (!enableOverrides) return;
  this.overrideCommands = new CompositeDisposable();
  const FILE_SYMBOLS_CMD = config.getToggleFileSymbolsCommand();
  const PROJECT_SYMBOLS_CMD = config.getToggleProjectSymbolsCommand();
  this.overrideCommands.add(
    atom.commands.add('atom-text-editor', FILE_SYMBOLS_CMD, this.toggleFileSymbols.bind(this)),
    atom.commands.add('atom-workspace', PROJECT_SYMBOLS_CMD, this.toggleProjectSymbols.bind(this))
  );
  // Ensure precedence is given to the listeners of this package
  prioritizeCommandListener(FILE_SYMBOLS_CMD, this.toggleFileSymbols.name);
  prioritizeCommandListener(PROJECT_SYMBOLS_CMD, this.toggleProjectSymbols.name);
}

export default new Package();
<commit_msg>Fix package activation error due to Atom API change<commit_after>/** @babel */

import * as path from 'path';
import { CompositeDisposable } from 'atom';
import config from './config';
import SymbolsView from './symbols-view';

class Package {

  activate() {
    this.config = config.schema;
    this.overrideCommands = null;
    this.symbolsView = null;
    this.subscriptions = new CompositeDisposable();
    this.subscriptions.add(
      config.watchOverrideCommands(updateOverrideCommands.bind(this)),
      config.watchToggleFileSymbolsCommand(() => updateOverrideCommands.bind(this)()),
      config.watchToggleProjectSymbolsCommand(() => updateOverrideCommands.bind(this)()),
      atom.commands.add('atom-text-editor', 'rustsym:toggle-file-symbols', this.toggleFileSymbols.bind(this)),
      atom.commands.add('atom-workspace', 'rustsym:toggle-project-symbols', this.toggleProjectSymbols.bind(this)),
    );
    // Call required to set up initial state for override commands
    updateOverrideCommands.bind(this)();
  }

  deactivate() {
    if (this.symbolsView) {
      this.symbolsView.destroy();
      this.symbolsView = null;
    }
    if (this.overrideCommands) {
      this.overrideCommands.dispose();
      this.overrideCommands = null;
    }
    if (this.subscriptions) {
      this.subscriptions.dispose();
      this.subscriptions = null;
    }
  }

  isEditingRust() {
    let editor = atom.workspace.getActiveTextEditor();
    if (!editor) return false;
    return path.extname(editor.getPath()) === '.rs';
  }

  toggleFileSymbols(event) {
    if (!initializeSymbolsView.bind(this)(event)) return;
    this.symbolsView.toggleFileSymbols(event.target);
  }

  toggleProjectSymbols(event) {
    if (!initializeSymbolsView.bind(this)(event)) return;
    this.symbolsView.toggleProjectSymbols(event.target);
  }

}

function initializeSymbolsView(event) {
  if (!this.isEditingRust()) return false;
  // Consume triggering event
  event.stopImmediatePropagation();
  if (this.symbolsView == null) {
    this.symbolsView = new SymbolsView();
  }
  return true;
}

function prioritizeCommandListener(command, listenerName) {
  let listeners = atom.commands.selectorBasedListenersByCommandName[command];
  let listener = listeners.find(
    // Allow substring comparison as bound functions will have their names
    // altered slightly (i.e. 'bound <fn-name>')
    listener => listener.didDispatch.name.indexOf(listenerName) !== -1
  );
  // Although setting the lowest possible specificity should be enough to
  // guarantee the listener of interest is preferred, an extra precaution
  // would be to rearrange all listeners for the command such that the listener
  // of interest is the first item in the collection
  listener.specificity = -Infinity;
}

function updateOverrideCommands(enableOverrides) {
  // Clean up and rebind all override commands for simplicity
  if (this.overrideCommands != null) {
    this.overrideCommands.dispose();
    this.overrideCommands = null;
  }
  // Update using current override commands state if none is given
  if (typeof enableOverrides === 'undefined') {
    enableOverrides = config.isOverrideCommandsEnabled();
  }
  if (!enableOverrides) return;
  this.overrideCommands = new CompositeDisposable();
  const FILE_SYMBOLS_CMD = config.getToggleFileSymbolsCommand();
  const PROJECT_SYMBOLS_CMD = config.getToggleProjectSymbolsCommand();
  this.overrideCommands.add(
    atom.commands.add('atom-text-editor', FILE_SYMBOLS_CMD, this.toggleFileSymbols.bind(this)),
    atom.commands.add('atom-workspace', PROJECT_SYMBOLS_CMD, this.toggleProjectSymbols.bind(this))
  );
  // Ensure precedence is given to the listeners of this package
  prioritizeCommandListener(FILE_SYMBOLS_CMD, this.toggleFileSymbols.name);
  prioritizeCommandListener(PROJECT_SYMBOLS_CMD, this.toggleProjectSymbols.name);
}

export default new Package();
<|endoftext|>


<commit_before>'use strict';

var request = require('request')
  , config = require('../config')
  , url = require('url')
  , cache = require('../lib/cache')
  , NPM_REGISTRY = 'http://registry.npmjs.org'
  ;

// set default proxy
if (process.env.proxy || config.proxy) {
  request.defaults({
    proxy: process.env.proxy || config.proxy
  });
}

var replaceTarballUrls = function (obj) {
  Object.keys(obj.versions).forEach(function (v) {
    var parsed = url.parse(obj.versions[v].dist.tarball);
    obj.versions[v].dist.tarball = url.resolve(process.env.DOMAIN || config.domain, parsed.path);
  });
};

exports.metadata = function (req, res) {
  cache.get(req.params.pkg, function (err, doc) {
    if (err) {
      request(NPM_REGISTRY + req.path, function (err, proxy, body) {
        body = JSON.parse(body);
        // forward npmjs errors
        if (!body.error) {
          replaceTarballUrls(body);
          cache.put(body._id, body);
        }
        res.status(proxy.statusCode).set(proxy.headers).json(body);
      });
    } else {
      req.log('getting ' + req.params.pkg + ' from cache...');
      res.status(200).json(doc);
    }
  });
};

exports.tarball = function (req, res) {
  cache.get(req.params.tar, function (err, body) {
    if (err) {
      request(NPM_REGISTRY + req.path, { encoding: null }, function (err, resp, body) {
        cache.put(req.params.tar, body);
      }).pipe(res);
    } else {
      req.log('getting ' + req.params.tar + ' from cache...');
      res.send(new Buffer(body, 'binary'));
    }
  });
};
<commit_msg>Fixed issue with proxy not working. Forgot to assign request back to request.<commit_after>'use strict';

var request = require('request')
  , config = require('../config')
  , url = require('url')
  , cache = require('../lib/cache')
  , proxy = process.env.PROXY || config.proxy
  , NPM_REGISTRY = 'http://registry.npmjs.org'
  ;

// set default proxy, if supplied
if (proxy) {
  console.log('> using proxy: "' + proxy + '"\n');
  request = request.defaults({ proxy: proxy });
}

var replaceTarballUrls = function (obj) {
  Object.keys(obj.versions).forEach(function (v) {
    var parsed = url.parse(obj.versions[v].dist.tarball);
    obj.versions[v].dist.tarball = url.resolve(process.env.DOMAIN || config.domain, parsed.path);
  });
};

exports.metadata = function (req, res) {
  cache.get(req.params.pkg, function (err, doc) {
    if (err) {
      request(NPM_REGISTRY + req.path, function (err, proxy, body) {
        body = JSON.parse(body);
        // forward npmjs errors
        if (!body.error) {
          replaceTarballUrls(body);
          cache.put(body._id, body);
        }
        res.status(proxy.statusCode).set(proxy.headers).json(body);
      });
    } else {
      req.log('getting ' + req.params.pkg + ' from cache...');
      res.status(200).json(doc);
    }
  });
};

exports.tarball = function (req, res) {
  cache.get(req.params.tar, function (err, body) {
    if (err) {
      request(NPM_REGISTRY + req.path, { encoding: null }, function (err, resp, body) {
        cache.put(req.params.tar, body);
      }).pipe(res);
    } else {
      req.log('getting ' + req.params.tar + ' from cache...');
      res.send(new Buffer(body, 'binary'));
    }
  });
};
<|endoftext|>