<commit_before>var assert = require('assert');

module.exports = tapsert = recordAssert(assert);

for (var a in assert) {
  tapsert[a] = recordAssert(assert[a]);
}

var assertions = 0;
var failures = 0;

function recordAssert(assert) {
  return function() {
    var desc = (arguments.length === assert.length
                ? arguments[arguments.length-1]
                : '');
    if (assertions === 0)
      console.log('TAP version 13');
    var n = assertions += 1;
    try {
      assert.apply(null, arguments);
      console.log('ok %d - %s', n, desc);
    } catch (e) {
      failures += 1;
      console.log('not ok %d - %s', n, desc)
    }
  };
}

process.on('exit', function() {
  console.log('1..%d', assertions);
  process.exit(failures);
});
<commit_msg>Fix leaked global<commit_after>var assert = require('assert');

var tapsert = module.exports = tapifyAssert(assert);

for (var a in assert) {
  tapsert[a] = tapifyAssert(assert[a]);
}

var assertions = 0;
var failures = 0;

function tapifyAssert(assert) {
  return tapifiedAssert;

  function tapifiedAssert() {
    var desc = (arguments.length === assert.length
                ? arguments[arguments.length-1]
                : '');
    if (assertions === 0)
      console.log('TAP version 13');
    var n = assertions += 1;
    try {
      assert.apply(null, arguments);
      console.log('ok %d - %s', n, desc);
    } catch (e) {
      failures += 1;
      console.log('not ok %d - %s', n, desc)
    }
  }
}

process.on('exit', function() {
  console.log('1..%d', assertions);
  process.exit(failures);
});
<|endoftext|>


<commit_before>// dependencies
var async = require('async');
var path = require('path');
var AWS = require('aws-sdk');
var gm = require('gm').subClass({
  imageMagick: true
});

var util = require('util');

// get reference to S3 client

var s3 = new AWS.S3();

exports.handler = function(event, context) {
  var srcBucket = event.bucket.name;
  var dstBucket = srcBucket;

  // Object key may have spaces or unicode non-ASCII characters.
  var srcKey = decodeURIComponent(event.location.replace(/\+/g, " ")).substr(1);

  var _75px = { width: 75, dstnKey: srcKey, destinationPath: "thumb" };
  var _200px = { width: 200, dstnKey: srcKey, destinationPath: "medium" };
  var _600px = { width: 600, dstnKey: srcKey, destinationPath: "large" };

  var _sizesArray = [_75px, _200px, _600px];

  // Infer the image type.
  var typeMatch = srcKey.match(/\.([^.]*)$/);
  var fileName = path.basename(srcKey);

  if (!typeMatch) {
    console.error('unable to infer image type for key ' + srcKey);
    return;
  }

  var imageType = typeMatch[1].toLowerCase();

  if (imageType != "jpg" && imageType != "gif" && imageType != "png" && imageType != "eps") {
    console.log('skipping non-image ' + srcKey);
    return;
  }

  async.forEachOf(_sizesArray, function(value, key, callback) {
    async.waterfall([
      function download(next) {
        s3.getObject({
          Bucket: srcBucket,
          Key: srcKey
        }, next);
      },

      function convert(response, next) {
        gm(response.Body).antialias(true).density(300).toBuffer('JPG', function(err, buffer) {
          if (err) {
            next(err);
          } else {
            next(null, buffer);
          }
        });
      },

      function process(response, next) {
        gm(response).size(function(err, size) {
          if(err) { console.log(err); return; }

          var scalingFactor = Math.min(
            _sizesArray[key].width / size.width,
            _sizesArray[key].width / size.height
          );

          var width = _sizesArray[key].width;//scalingFactor * size.width;
          var height = _sizesArray[key].width;//scalingFactor * size.height;
          var index = key;

          this.resize(width, height).fill("#FFFFFF").fontSize(30).drawText(10, 10, "ImageUpload.com", "SouthWest").toBuffer(
            'JPG', function(err, buffer) {
              console.log("Printing the buffer...");
              console.log(buffer);

              if (err) {
                next(err);
              } else {
                next(null, buffer, key);
              }
            });
        });
      },

      function upload(data, index, next) {
        console.time("uploadImage");
        pathWithFolder = srcKey.split('/').slice(0, 5).join('/')
        console.log("upload to path : " + pathWithFolder + "/" + _sizesArray[index].destinationPath + "/" + fileName.slice(0, -4) + ".jpg");

        s3.putObject({
          Bucket: dstBucket,
          Key: pathWithFolder + "/" + _sizesArray[index].destinationPath + "/" + fileName.slice(0, -4) + ".jpg",
          Body: data,
          ContentType: 'JPG'
        }, next);
        console.timeEnd("uploadImage");
      }
    ], function(err, result) {
      if (err) {
        console.error(err);
      }

      console.log("End of step " + key);
      callback();
    });
  }, function(err) {
    if (err) {
      console.error('---->Unable to resize ' + srcBucket + '/' + srcKey + ' and upload to ' + dstBucket +
                    '/images' + ' due to an error: ' + err);
    } else {
      console.log('---->Successfully resized ' + srcBucket + ' and uploaded to' + dstBucket + "/images");
    }
    context.done();
  });
};<commit_msg>giving public-read permission to the uploaded file<commit_after>// dependencies
var async = require('async');
var path = require('path');
var AWS = require('aws-sdk');
var gm = require('gm').subClass({
  imageMagick: true
});

var util = require('util');

// get reference to S3 client

var s3 = new AWS.S3();

exports.handler = function(event, context) {
  var srcBucket = event.bucket.name;
  var dstBucket = srcBucket;

  // Object key may have spaces or unicode non-ASCII characters.
  var srcKey = decodeURIComponent(event.location.replace(/\+/g, " ")).substr(1);

  var _75px = { width: 75, dstnKey: srcKey, destinationPath: "thumb" };
  var _200px = { width: 200, dstnKey: srcKey, destinationPath: "medium" };
  var _600px = { width: 600, dstnKey: srcKey, destinationPath: "large" };

  var _sizesArray = [_75px, _200px, _600px];

  // Infer the image type.
  var typeMatch = srcKey.match(/\.([^.]*)$/);
  var fileName = path.basename(srcKey);

  if (!typeMatch) {
    console.error('unable to infer image type for key ' + srcKey);
    return;
  }

  var imageType = typeMatch[1].toLowerCase();

  if (imageType != "jpg" && imageType != "gif" && imageType != "png" && imageType != "eps") {
    console.log('skipping non-image ' + srcKey);
    return;
  }

  async.forEachOf(_sizesArray, function(value, key, callback) {
    async.waterfall([
      function download(next) {
        s3.getObject({
          Bucket: srcBucket,
          Key: srcKey
        }, next);
      },

      function convert(response, next) {
        gm(response.Body).antialias(true).density(300).toBuffer('JPG', function(err, buffer) {
          if (err) {
            next(err);
          } else {
            next(null, buffer);
          }
        });
      },

      function process(response, next) {
        gm(response).size(function(err, size) {
          if(err) { console.log(err); return; }

          var scalingFactor = Math.min(
            _sizesArray[key].width / size.width,
            _sizesArray[key].width / size.height
          );

          var width = scalingFactor * size.width;
          var height = scalingFactor * size.height;
          var index = key;

          this.resize(width, height).fill("#FFFFFF").fontSize(30).drawText(10, 10, "ImageUpload.com", "SouthWest").toBuffer(
            'JPG', function(err, buffer) {
              console.log("Printing the buffer...");
              console.log(buffer);

              if (err) {
                next(err);
              } else {
                next(null, buffer, key);
              }
            });
        });
      },

      function upload(data, index, next) {
        console.time("uploadImage");
        pathWithFolder = srcKey.split('/').slice(0, 5).join('/')
        console.log("upload to path : " + pathWithFolder + "/" + _sizesArray[index].destinationPath + "/" + fileName.slice(0, -4) + ".jpg");

        s3.putObject({
          Bucket: dstBucket,
          Key: pathWithFolder + "/" + _sizesArray[index].destinationPath + "/" + fileName.slice(0, -4) + ".jpg",
          Body: data,
          ContentType: 'JPG',
          ACL: 'public-read'
        }, next);
        console.timeEnd("uploadImage");
      }
    ], function(err, result) {
      if (err) {
        console.error(err);
      }

      console.log("End of step " + key);
      callback();
    });
  }, function(err) {
    if (err) {
      console.error('---->Unable to resize ' + srcBucket + '/' + srcKey + ' and upload to ' + dstBucket +
                    '/images' + ' due to an error: ' + err);
    } else {
      console.log('---->Successfully resized ' + srcBucket + ' and uploaded to' + dstBucket + "/images");
    }
    context.done();
  });
};<|endoftext|>


<commit_before>/* jshint node: true */
'use strict';

var path = require('path');
var autoprefixer = require('broccoli-autoprefixer');
var mergeTrees = require('broccoli-merge-trees');
var Funnel = require('broccoli-funnel');
var AngularScssFilter = require('./lib/angular-scss-filter');

module.exports = {
  name: 'ember-paper',

  included: function(app) {
    this._super.included(app);

    if (!process.env.EMBER_CLI_FASTBOOT) {
      app.import(app.bowerDirectory + '/hammer.js/hammer.js')
      app.import(app.bowerDirectory + '/matchMedia/matchMedia.js');
      app.import('vendor/propagating.js');
    }
  },

  contentFor: function(type) {
    if (type === 'head') {
      return '<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">' +
        '<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">';
    }
  },

  treeForStyles: function(tree) {
    var scssFiles = [
      //core styles
      'core/style/typography.scss',
      'core/style/mixins.scss',
      'core/style/variables.scss',
      'core/style/structure.scss',
      'core/services/layout/layout.attributes.scss',
      'core/services/layout/layout.scss',
      //component styles
      'components/content/content.scss',
      'components/content/content-theme.scss',

      'components/card/card.scss',
      'components/card/card-theme.scss',

      'components/button/button.scss',
      'components/button/button-theme.scss',

      'components/checkbox/checkbox.scss',
      'components/checkbox/checkbox-theme.scss',

      'components/radioButton/radio-button.scss',
      'components/radioButton/radio-button-theme.scss',

      'components/switch/switch.scss',
      'components/switch/switch-theme.scss',

      'components/input/input.scss',
      'components/input/input-theme.scss',

      'components/list/list.scss',
      'components/list/list-theme.scss',

      'components/divider/divider.scss',
      'components/divider/divider-theme.scss',

      'components/whiteframe/whiteframe.scss',

      'components/toolbar/toolbar.scss',
      'components/toolbar/toolbar-theme.scss',

      'components/icon/icon.scss',
      'components/icon/icon-theme.scss',

      'components/slider/slider.scss',
      'components/slider/slider-theme.scss',

      'components/subheader/subheader.scss',
      'components/subheader/subheader-theme.scss',

      'components/autocomplete/autocomplete.scss',
      'components/autocomplete/autocomplete-theme.scss',

      'components/progressLinear/progress-linear.scss',
      'components/progressLinear/progress-linear-theme.scss',

      'components/progressCircular/progress-circular.scss',
      'components/progressCircular/progress-circular-theme.scss',

      'components/menu/menu.scss',
      'components/menu/menu-theme.scss',

      'components/select/select.scss',
      'components/select/select-theme.scss',

      'components/gridList/grid-list.scss',

      'components/sidenav/sidenav.scss',
      'components/sidenav/sidenav-theme.scss',

      'components/backdrop/backdrop.scss',
      'components/backdrop/backdrop-theme.scss',

      'components/dialog/dialog.scss',
      'components/dialog/dialog-theme.scss',

      'components/virtualRepeat/virtual-repeater.scss'
    ];

    /*
      Find the angular-material-source module in a manner that works for npm 2.x
      and 3.x in both the addon itself and projects that depend on this addon

      This is an edge case b/c angular-material-source does not have a main
      module we can require.resolve through node itself and similarily ember-cli
      does not have such a hack for the same reason.

      tl;dr - We want the non built scss files, and b/c this dep is only provided via
      bower, we use this hack. Please change it if you read this and know a better way.
    */
    var pathBase = path.resolve(this.nodeModulesPath, 'angular-material-source', 'src')
    var angularScssFiles = new Funnel(pathBase, {
      files: scssFiles,
      destDir: 'angular-material',
      annotation: 'AngularScssFunnel'
    });

    angularScssFiles = new AngularScssFilter(angularScssFiles, {
      annotation: 'AngularScssFilter'
    });

    return this._super.treeForStyles(mergeTrees([angularScssFiles, tree], { overwrite: true }));
  },

  postprocessTree: function(type, tree) {
    if (type === 'all' || type === 'styles') {
      tree = autoprefixer(tree,
          this.app.options.autoprefixer || { browsers: ['last 2 versions'] });
    }
    return tree;
  },

  // TODO: Remove once ember-paper is stable.
  isDevelopingAddon: function() {
    return true;
  }
};
<commit_msg>Call power-select's contentFor hook for body-footer (#494)<commit_after>/* jshint node: true */
'use strict';

var path = require('path');
var autoprefixer = require('broccoli-autoprefixer');
var mergeTrees = require('broccoli-merge-trees');
var Funnel = require('broccoli-funnel');
var AngularScssFilter = require('./lib/angular-scss-filter');

module.exports = {
  name: 'ember-paper',

  included: function(app) {
    this._super.included(app);

    if (!process.env.EMBER_CLI_FASTBOOT) {
      app.import(app.bowerDirectory + '/hammer.js/hammer.js')
      app.import(app.bowerDirectory + '/matchMedia/matchMedia.js');
      app.import('vendor/propagating.js');
    }
  },

  contentFor: function(type, config) {
    if (type === 'head') {
      return '<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:300,400,500,700,400italic">' +
        '<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">';
    } else if (type === 'body-footer') {
      var emberPowerSelect = this.addons.filter(function(addon) {
        return addon.name === 'ember-power-select';
      })[0];
      return emberPowerSelect.contentFor(type, config);
    }
  },

  treeForStyles: function(tree) {
    var scssFiles = [
      //core styles
      'core/style/typography.scss',
      'core/style/mixins.scss',
      'core/style/variables.scss',
      'core/style/structure.scss',
      'core/services/layout/layout.attributes.scss',
      'core/services/layout/layout.scss',
      //component styles
      'components/content/content.scss',
      'components/content/content-theme.scss',

      'components/card/card.scss',
      'components/card/card-theme.scss',

      'components/button/button.scss',
      'components/button/button-theme.scss',

      'components/checkbox/checkbox.scss',
      'components/checkbox/checkbox-theme.scss',

      'components/radioButton/radio-button.scss',
      'components/radioButton/radio-button-theme.scss',

      'components/switch/switch.scss',
      'components/switch/switch-theme.scss',

      'components/input/input.scss',
      'components/input/input-theme.scss',

      'components/list/list.scss',
      'components/list/list-theme.scss',

      'components/divider/divider.scss',
      'components/divider/divider-theme.scss',

      'components/whiteframe/whiteframe.scss',

      'components/toolbar/toolbar.scss',
      'components/toolbar/toolbar-theme.scss',

      'components/icon/icon.scss',
      'components/icon/icon-theme.scss',

      'components/slider/slider.scss',
      'components/slider/slider-theme.scss',

      'components/subheader/subheader.scss',
      'components/subheader/subheader-theme.scss',

      'components/autocomplete/autocomplete.scss',
      'components/autocomplete/autocomplete-theme.scss',

      'components/progressLinear/progress-linear.scss',
      'components/progressLinear/progress-linear-theme.scss',

      'components/progressCircular/progress-circular.scss',
      'components/progressCircular/progress-circular-theme.scss',

      'components/menu/menu.scss',
      'components/menu/menu-theme.scss',

      'components/select/select.scss',
      'components/select/select-theme.scss',

      'components/gridList/grid-list.scss',

      'components/sidenav/sidenav.scss',
      'components/sidenav/sidenav-theme.scss',

      'components/backdrop/backdrop.scss',
      'components/backdrop/backdrop-theme.scss',

      'components/dialog/dialog.scss',
      'components/dialog/dialog-theme.scss',

      'components/virtualRepeat/virtual-repeater.scss'
    ];

    /*
      Find the angular-material-source module in a manner that works for npm 2.x
      and 3.x in both the addon itself and projects that depend on this addon

      This is an edge case b/c angular-material-source does not have a main
      module we can require.resolve through node itself and similarily ember-cli
      does not have such a hack for the same reason.

      tl;dr - We want the non built scss files, and b/c this dep is only provided via
      bower, we use this hack. Please change it if you read this and know a better way.
    */
    var pathBase = path.resolve(this.nodeModulesPath, 'angular-material-source', 'src')
    var angularScssFiles = new Funnel(pathBase, {
      files: scssFiles,
      destDir: 'angular-material',
      annotation: 'AngularScssFunnel'
    });

    angularScssFiles = new AngularScssFilter(angularScssFiles, {
      annotation: 'AngularScssFilter'
    });

    return this._super.treeForStyles(mergeTrees([angularScssFiles, tree], { overwrite: true }));
  },

  postprocessTree: function(type, tree) {
    if (type === 'all' || type === 'styles') {
      tree = autoprefixer(tree,
          this.app.options.autoprefixer || { browsers: ['last 2 versions'] });
    }
    return tree;
  },

  // TODO: Remove once ember-paper is stable.
  isDevelopingAddon: function() {
    return true;
  }
};
<|endoftext|>


<commit_before>/*

index.js - "tart-membrane": Tart implementation of a membrane

The MIT License (MIT)

Copyright (c) 2013 Dale Schumacher, Tristan Slominski

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
"use strict";

var assert = require('assert');

var membrane = module.exports;

var isUndefinedOrNull = function isUndefinedOrNull(value) {
    return value === null || value === undefined;
};

membrane.behaviors = function behaviors() {

    var inboundProxies = []; // proxies for actors "inside"
    var inboundProxied = []; // the "inside" actors that have a proxy
    var outboundProxies = []; // proxies for actors "outside"
    var outboundProxied = []; // the "outside" actors that have a proxy
    var revokeBehList = [];

    var rewriteNonFunctions = function rewriteNonFunctions(sponsor, rewrite, message) {
        if (isUndefinedOrNull(message)) {
            return message;
        }

        if (typeof message === 'string' || typeof message === 'number') {
            return message;
        }

        var rewriteByCopy = false;
        if (Object.isFrozen(message)) {
            rewriteByCopy = true;
        }

        if (Array.isArray(message)) {
            if (!rewriteByCopy) {
                for (var i = 0; i < message.length; i++) {
                    message.splice(i, 1, rewrite(sponsor, message[i]));
                }

                return message;

            } else {
                var result = [];
                message.forEach(function (element) {
                    result.push(rewrite(sponsor, element));
                });

                return result;
            }
        }

        assert.ok(typeof message === 'object');

        if (!rewriteByCopy) {
            Object.keys(message).forEach(function (key) {
                message[key] = rewrite(sponsor, message[key]);
            });

            return message;

        } else {
            var result = {};
            Object.keys(message).forEach(function (key) {
                result[key] = rewrite(sponsor, message[key]);
            });

            return result;
        }
    };

    var rewriteInbound = function rewriteInbound(sponsor, message) {
        if (typeof message !== 'function') {
            return rewriteNonFunctions(sponsor, rewriteInbound, message);
        }

        assert.ok(typeof message === 'function');

        // check if message itself is an inboundProxy that should be replaced
        var index = inboundProxies.indexOf(message);
        if (index >= 0) {
            // substitute the proxied actor for the proxy
            return inboundProxied[index];
        }

        // check if message is an already proxied inner actor
        index = outboundProxied.indexOf(message);
        if (index >= 0) {
            // substitute existing proxy for the actor
            return outboundProxies[index];
        }

        // message is an outside actor and should be replaced
        var outboundProxyBeh = outboundProxy(message);
        var proxy = sponsor(outboundProxyBeh);
        outboundProxies.push(proxy);
        outboundProxied.push(message);

        return proxy;
    };

    var rewriteOutbound = function rewriteOutbound(sponsor, message) {
        if (typeof message !== 'function') {
            return rewriteNonFunctions(sponsor, rewriteOutbound, message);
        }

        assert.ok(typeof message === 'function');

        // check if message itself is an outboundProxy that should be replaced
        var index = outboundProxies.indexOf(message);
        if (index >= 0) {
            // substitute the proxied actor for the proxy
            return outboundProxied[index];
        }

        // check if message is an already proxied inner actor
        index = inboundProxied.indexOf(message);
        if (index >= 0) {
            // substitute existing proxy for the actor
            return inboundProxies[index];
        }

        // message is an inside actor and should be replaced
        var inboundProxyBeh = inboundProxy(message);
        var proxy = sponsor(inboundProxyBeh);
        inboundProxies.push(proxy);
        inboundProxied.push(message);

        return proxy;
    };

    var revokeBeh = function revokeBeh(customer) {
        var revokeProxyBeh;
        while (revokeProxyBeh = revokeBehList.shift()) {
            // create and then trigger revoke actors
            this.sponsor(revokeProxyBeh)();
        };
        customer();
    };

    var inboundProxy = function inboundProxy(actor) {
        var proxyBeh = function proxyBeh(message) {
            // Because the inbound proxy can be created outside of the membrane
            // when bootstrapping, we have to make sure that the membrane is
            // tracking this particular proxy instance as well as the actor that
            // it proxies. If not, start tracking.
            if (inboundProxies.indexOf(this.self) < 0) {
                inboundProxies.push(this.self);
                inboundProxied.push(actor);
            }

            // proxy message contents and forward if proxy isn't revoked
            actor && actor(rewriteInbound(this.sponsor, message));
        };

        var revokeBeh = function revokeBeh(customer) {
            actor = null; // crash proxy
        };

        revokeBehList.push(revokeBeh);
        return proxyBeh;
    };

    var outboundProxy = function outboundProxy(actor) {
        var proxyBeh = function proxyBeh(message) {
            // Because outbound proxies are only created within the membrane,
            // they are guaranteed to already be tracked by the membrane
            // and the check similar to the one in the inboundProxy is not
            // necessary.

            // proxy message contents and forward if proxy isn't revoked
            actor && actor(rewriteOutbound(this.sponsor, message));
        };

        var revokeBeh = function revokeBeh(customer) {
            actor = null; // crash proxy
        };

        revokeBehList.push(revokeBeh);
        return proxyBeh;
    };

    return {
        proxy: inboundProxy,
        revokeBeh: revokeBeh
    };
};

membrane.factory = function factory(sponsor) {

    var behaviors = membrane.behaviors();

    var proxyBeh = function proxyBeh(message) {
        var proxies = [];
        for (var i = 0; i < message.actors.length; i++) {
            var actorProxyBeh = behaviors.proxy(message.actors[i]);
            proxies.push(this.sponsor(actorProxyBeh));
        }
        message.customer(proxies);
    };

    return {
        proxy: sponsor(proxyBeh),
        revoke: sponsor(behaviors.revokeBeh)
    };
};<commit_msg>rewriteNonFunctions() is a utility without closure.<commit_after>/*

index.js - "tart-membrane": Tart implementation of a membrane

The MIT License (MIT)

Copyright (c) 2013 Dale Schumacher, Tristan Slominski

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

*/
"use strict";

var assert = require('assert');

var membrane = module.exports;

var isUndefinedOrNull = function isUndefinedOrNull(value) {
    return value === null || value === undefined;
};

var rewriteNonFunctions = function rewriteNonFunctions(sponsor, rewrite, message) {
    if (isUndefinedOrNull(message)) {
        return message;
    }

    if (typeof message === 'string' || typeof message === 'number') {
        return message;
    }

    var rewriteByCopy = false;
    if (Object.isFrozen(message)) {
        rewriteByCopy = true;
    }

    if (Array.isArray(message)) {
        if (!rewriteByCopy) {
            for (var i = 0; i < message.length; i++) {
                message.splice(i, 1, rewrite(sponsor, message[i]));
            }

            return message;

        } else {
            var result = [];
            message.forEach(function (element) {
                result.push(rewrite(sponsor, element));
            });

            return result;
        }
    }

    assert.ok(typeof message === 'object');

    if (!rewriteByCopy) {
        Object.keys(message).forEach(function (key) {
            message[key] = rewrite(sponsor, message[key]);
        });

        return message;

    } else {
        var result = {};
        Object.keys(message).forEach(function (key) {
            result[key] = rewrite(sponsor, message[key]);
        });

        return result;
    }
};

membrane.behaviors = function behaviors() {

    var inboundProxies = []; // proxies for actors "inside"
    var inboundProxied = []; // the "inside" actors that have a proxy
    var outboundProxies = []; // proxies for actors "outside"
    var outboundProxied = []; // the "outside" actors that have a proxy
    var revokeBehList = [];

    var rewriteInbound = function rewriteInbound(sponsor, message) {
        if (typeof message !== 'function') {
            return rewriteNonFunctions(sponsor, rewriteInbound, message);
        }

        assert.ok(typeof message === 'function');

        // check if message itself is an inboundProxy that should be replaced
        var index = inboundProxies.indexOf(message);
        if (index >= 0) {
            // substitute the proxied actor for the proxy
            return inboundProxied[index];
        }

        // check if message is an already proxied inner actor
        index = outboundProxied.indexOf(message);
        if (index >= 0) {
            // substitute existing proxy for the actor
            return outboundProxies[index];
        }

        // message is an outside actor and should be replaced
        var outboundProxyBeh = outboundProxy(message);
        var proxy = sponsor(outboundProxyBeh);
        outboundProxies.push(proxy);
        outboundProxied.push(message);

        return proxy;
    };

    var rewriteOutbound = function rewriteOutbound(sponsor, message) {
        if (typeof message !== 'function') {
            return rewriteNonFunctions(sponsor, rewriteOutbound, message);
        }

        assert.ok(typeof message === 'function');

        // check if message itself is an outboundProxy that should be replaced
        var index = outboundProxies.indexOf(message);
        if (index >= 0) {
            // substitute the proxied actor for the proxy
            return outboundProxied[index];
        }

        // check if message is an already proxied inner actor
        index = inboundProxied.indexOf(message);
        if (index >= 0) {
            // substitute existing proxy for the actor
            return inboundProxies[index];
        }

        // message is an inside actor and should be replaced
        var inboundProxyBeh = inboundProxy(message);
        var proxy = sponsor(inboundProxyBeh);
        inboundProxies.push(proxy);
        inboundProxied.push(message);

        return proxy;
    };

    var revokeBeh = function revokeBeh(customer) {
        var revokeProxyBeh;
        while (revokeProxyBeh = revokeBehList.shift()) {
            // create and then trigger revoke actors
            this.sponsor(revokeProxyBeh)();
        };
        customer();
    };

    var inboundProxy = function inboundProxy(actor) {
        var proxyBeh = function proxyBeh(message) {
            // Because the inbound proxy can be created outside of the membrane
            // when bootstrapping, we have to make sure that the membrane is
            // tracking this particular proxy instance as well as the actor that
            // it proxies. If not, start tracking.
            if (inboundProxies.indexOf(this.self) < 0) {
                inboundProxies.push(this.self);
                inboundProxied.push(actor);
            }

            // proxy message contents and forward if proxy isn't revoked
            actor && actor(rewriteInbound(this.sponsor, message));
        };

        var revokeBeh = function revokeBeh(customer) {
            actor = null; // crash proxy
        };

        revokeBehList.push(revokeBeh);
        return proxyBeh;
    };

    var outboundProxy = function outboundProxy(actor) {
        var proxyBeh = function proxyBeh(message) {
            // Because outbound proxies are only created within the membrane,
            // they are guaranteed to already be tracked by the membrane
            // and the check similar to the one in the inboundProxy is not
            // necessary.

            // proxy message contents and forward if proxy isn't revoked
            actor && actor(rewriteOutbound(this.sponsor, message));
        };

        var revokeBeh = function revokeBeh(customer) {
            actor = null; // crash proxy
        };

        revokeBehList.push(revokeBeh);
        return proxyBeh;
    };

    return {
        proxy: inboundProxy,
        revokeBeh: revokeBeh
    };
};

membrane.factory = function factory(sponsor) {

    var behaviors = membrane.behaviors();

    var proxyBeh = function proxyBeh(message) {
        var proxies = [];
        for (var i = 0; i < message.actors.length; i++) {
            var actorProxyBeh = behaviors.proxy(message.actors[i]);
            proxies.push(this.sponsor(actorProxyBeh));
        }
        message.customer(proxies);
    };

    return {
        proxy: sponsor(proxyBeh),
        revoke: sponsor(behaviors.revokeBeh)
    };
};<|endoftext|>


<commit_before>'use strict';

var ReactNativeStore = require('./asyncstore');
var Events = require('eventemitter3')
var RNDBModel = {};
RNDBModel.DBEvents = new Events()

RNDBModel.create_db = function(db){
    var me = this;
    me.db_name = db;

    /**
     * @description Finds all the objects based on the query
     * @param query_data
     * @param callback
     */
    me.get = function(query_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            var results = collection.where(query_data).find();
            if(callback){
                callback(results)
            }
        });
    };

    /**
     * @description Finds by ID
     * @param id
     * @param callback
     */
    me.get_id = function(id, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            var results = collection.get(id);
            if(callback){
                callback(results)
            }
        });
    };

    /**
     * @description Gets all the data of the table
     * @param callback
     */
    me.get_all = function( callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            var results = collection.databaseData[me.db_name];
            if(callback){
                callback(results)
            }
        });
    };

    /**
     * @description Adds data to the Table in the DB
     * @param data_to_add
     * @param callback
     */
    me.add = function(data_to_add, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            // Add Data
            collection.add(data_to_add, function(added_data_id){
                if(callback){
                    callback(added_data_id)
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Removes all the objects matching the query
     * @param query_data
     * @param callback
     */
    me.remove = function(query_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.where(query_data).remove(function(data_removed){
                if(callback){
                    callback(data_removed);
                }
            });
        });
    };

    /**
     * @description Removed object by ID
     * @param id
     * @param callback
     */
    me.remove_id = function(id, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.removeById(id, function(data_removed){
                if(callback){
                    callback(data_removed);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Erases the complete DB
     * @param callback
     */
    me.erase_db = function(callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.remove(function(data_removed){
                if(callback){
                    callback(data_removed);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    }
    /**
     * @description Updates the Table with the query
     * @param query_data
     * @param replace_data
     * @param callback
     */
    me.update = function(query_data, replace_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.where(query_data).update(replace_data, function(data){
                if(callback){
                    callback(data);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Updates the DB Object by ID
     * @param id
     * @param replace_data
     * @param callback
     */
    me.update_id = function(id, replace_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.updateById(id, replace_data, function(data){
                if(callback){
                    callback(data);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Removed object by ID
     * @param id
     * @param callback
     */
    me.remove_id = function(id, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.removeById(id, function(data_removed){
                if(callback){
                    callback(data_removed);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

};

module.exports = RNDBModel;
<commit_msg>added add_all query to add an array to db<commit_after>'use strict';

var ReactNativeStore = require('./asyncstore');
var Events = require('eventemitter3')
var RNDBModel = {};
RNDBModel.DBEvents = new Events()

RNDBModel.create_db = function(db){
    var me = this;
    me.db_name = db;

    /**
     * @description Finds all the objects based on the query
     * @param query_data
     * @param callback
     */
    me.get = function(query_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            var results = collection.where(query_data).find();
            if(callback){
                callback(results)
            }
        });
    };

    /**
     * @description Finds by ID
     * @param id
     * @param callback
     */
    me.get_id = function(id, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            var results = collection.get(id);
            if(callback){
                callback(results)
            }
        });
    };

    /**
     * @description Gets all the data of the table
     * @param callback
     */
    me.get_all = function( callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            var results = collection.databaseData[me.db_name];
            if(callback){
                callback(results)
            }
        });
    };

    /**
     * @description Adds data to the Table in the DB
     * @param data_to_add
     * @param callback
     */
    me.add = function(data_to_add, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            // Add Data
            collection.add(data_to_add, function(added_data_id){
                if(callback){
                    callback(added_data_id)
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Adds array of data to the Table in the DB
     * @param data_to_add
     * @param callback
     */
    me.add_all = function(data_to_add, callback){
        if(data_to_add.length <= 0) return null;

        var added_data = [];

        var addItem = function(data_to_add) {
          if(data_to_add.length == 0 && callback) { return callback(added_data); }
          var data = data_to_add.pop();

          me.add(data, function(data_added){
            addItem(data_to_add);
            added_data.push(data_added);
          });
        };

        addItem(data_to_add);
    };

    /**
     * @description Removes all the objects matching the query
     * @param query_data
     * @param callback
     */
    me.remove = function(query_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.where(query_data).remove(function(data_removed){
                if(callback){
                    callback(data_removed);
                }
            });
        });
    };

    /**
     * @description Removed object by ID
     * @param id
     * @param callback
     */
    me.remove_id = function(id, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.removeById(id, function(data_removed){
                if(callback){
                    callback(data_removed);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Erases the complete DB
     * @param callback
     */
    me.erase_db = function(callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.remove(function(data_removed){
                if(callback){
                    callback(data_removed);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    }
    /**
     * @description Updates the Table with the query
     * @param query_data
     * @param replace_data
     * @param callback
     */
    me.update = function(query_data, replace_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.where(query_data).update(replace_data, function(data){
                if(callback){
                    callback(data);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Updates the DB Object by ID
     * @param id
     * @param replace_data
     * @param callback
     */
    me.update_id = function(id, replace_data, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.updateById(id, replace_data, function(data){
                if(callback){
                    callback(data);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

    /**
     * @description Removed object by ID
     * @param id
     * @param callback
     */
    me.remove_id = function(id, callback){
        ReactNativeStore.table(me.db_name).then(function(collection){
            collection.removeById(id, function(data_removed){
                if(callback){
                    callback(data_removed);
                }
                RNDBModel.DBEvents.emit("all")
            });
        });
    };

};

module.exports = RNDBModel;
<|endoftext|>


<commit_before>const express = require('express')
const request = require('request')
const bodyParser = require('body-parser')
const path = require('path')

const app = express()
const port = process.env.PORT || 3000
const token = process.env.TOKEN || 'null'

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

let wanted = require('./wanted.js')
let hint = require('./hint.js')

let chanel =
`章魚單車頻道：4747
御魂拾層頻道：1010
碎片挑戰頻道：818 (桃花/鐮鼬)
覺醒材料頻道：886
懸賞交換頻道：1700`
let help =
`懸賞 大天狗 - 顯示大天狗的分布情形
線索 蒲公英 - 顯示線索為蒲公英的目標，多個線索請以空白分隔
副本 第六章 - 顯示副本第六章的分布與金錢經驗掉落
圖鑑 螢草 - 顯示螢草的圖鑑資料
頻道 - 顯示特定用途的頻道代碼
留言 Bug - 對開發者留下訊息，例如報錯
幫助 - 顯示本訊息`
let autoReply =
`已將您的留言紀錄，但開發者不一定會回覆，請見諒`
let cmdNotFound =
`無法辨識指令，輸入 幫助 查看哪些指令可以用`

app.post('/in', (req, res) => {
  let data = req.body
  if (data.object === 'page') {
    data.entry.forEach((entry) => {
      entry.messaging.forEach((event) => {
        if (event.message) {
          let reply = looker(event.message.text)
          reply.forEach((msg) => {
            sendMsg(event.sender.id, msg)
            console.log(event.sender.id)
          })
        } else { console.log(' Error ') }
      })
    })
  }
  res.sendStatus(200)
})

app.get('/pp.html', (req, res) => {
  res.sendFile(path.join(__dirname, 'pp.html'))
})

app.all('/', (req, res) => {
  res.sendStatus(403)
})

function looker (input) {
  let spilt = input.match(/\S+/g)
  let reply = []
  switch (spilt[0]) {
    case '幫助':
      reply = reply.concat(help)
      break
    case '懸賞':
      reply = reply.concat(wanted[spilt[1]] || '查無資料，請確定目標名稱正確，查詢線索請使用 線索 (條件)')
      break
    case '副本':
      reply = reply.concat(mapLooker(spilt[1]) || '查無資料，請確定目標名稱正確')
      break
    case '圖鑑':
      reply = reply.concat(illLooker(spilt[1]))
      break
    case '線索':
      reply = reply.concat(wantedLooker(spilt))
      break
    case '頻道':
      reply = reply.concat(chanel)
      break
    case '留言':
      comment(input)
      reply = reply.concat(autoReply)
      break
    default:
      reply = reply.contact(cmdNotFound)
  }
  return reply
}

function wantedLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    let mat = hint[dex[1]]
    if (dex.length > 1) {
      dex.forEach((clue) => {
        let tmp = hint[clue]
        mat.forEach((sp) => {
          if (!(sp in tmp)) { mat.splice(mat.indexOf(sp), 1) }
        })
        result = result.concat('查詢結果為: ' + (mat.join(',') || '無資料'))
        if (mat.length === 1) { result = result.concat(wanted[mat[0]]) }
      })
    }
  } else { result = result.concat('沒有給予條件') }
  return result
}

function mapLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    let mapID = map.alias[dex[0]]
    result = result.concat(map.data(mapID))
  } else {
    result = result.concat('沒有給予條件')
  }
  return result
}

function illLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    result = result.concat(ill[dex[0]])
  } else {
    result = result.concat('沒有給予條件')
  }
  return result
}

function sendMsg (sender, message) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: token },
    method: 'POST',
    json: {
      recipient: { id: sender },
      message: { text: message }
    }
  })
}

function comment (input) {
}

app.get('/in', (req, res) => {
  if (req.query['hub.mode'] === 'subscribe') {
    if (req.query['hub.verify_token'] === 'YalaBomm') res.send(req.query['hub.challenge'])
    else res.status(403)
  }
})

app.listen(port, () => { console.log(`Listening to ${port}`) })
<commit_msg>comment<commit_after>const express = require('express')
const request = require('request')
const bodyParser = require('body-parser')
const path = require('path')

const app = express()
const port = process.env.PORT || 3000
const token = process.env.TOKEN || 'null'

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

let wanted = require('./wanted.js')
let hint = require('./hint.js')

let chanel =
`章魚單車頻道：4747
御魂拾層頻道：1010
碎片挑戰頻道：818 (桃花/鐮鼬)
覺醒材料頻道：886
懸賞交換頻道：1700`
let help =
`懸賞 大天狗 - 顯示大天狗的分布情形
線索 蒲公英 - 顯示線索為蒲公英的目標，多個線索請以空白分隔
副本 第六章 - 顯示副本第六章的分布與金錢經驗掉落
圖鑑 螢草 - 顯示螢草的圖鑑資料
頻道 - 顯示特定用途的頻道代碼
留言 Bug - 對開發者留下訊息，例如報錯
幫助 - 顯示本訊息`
let autoReply =
`已將您的留言紀錄，但開發者不一定會回覆，請見諒`
let cmdNotFound =
`無法辨識指令，輸入 幫助 查看哪些指令可以用`

app.post('/in', (req, res) => {
  let data = req.body
  if (data.object === 'page') {
    data.entry.forEach((entry) => {
      entry.messaging.forEach((event) => {
        if (event.message) {
          let reply = looker(event.message.text)
          reply.forEach((msg) => {
            sendMsg(event.sender.id, msg)
            console.log(event.sender.id)
          })
        } else { console.log(' Error ') }
      })
    })
  }
  res.sendStatus(200)
})

app.get('/pp.html', (req, res) => {
  res.sendFile(path.join(__dirname, 'pp.html'))
})

app.all('/', (req, res) => {
  res.sendStatus(403)
})

function looker (input) {
  let spilt = input.match(/\S+/g)
  let reply = []
  switch (spilt[0]) {
    case '幫助':
      reply = reply.concat(help)
      break
    case '懸賞':
      reply = reply.concat(wanted[spilt[1]] || '查無資料，請確定目標名稱正確，查詢線索請使用 線索 (條件)')
      break
    case '副本':
      reply = reply.concat(mapLooker(spilt[1]) || '查無資料，請確定目標名稱正確')
      break
    case '圖鑑':
      reply = reply.concat(illLooker(spilt[1]))
      break
    case '線索':
      reply = reply.concat(wantedLooker(spilt))
      break
    case '頻道':
      reply = reply.concat(chanel)
      break
    case '留言':
      comment(input)
      reply = reply.concat(autoReply)
      break
    default:
      reply = reply.contact(cmdNotFound)
  }
  return reply
}

function wantedLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    let mat = hint[dex[1]]
    if (dex.length > 1) {
      dex.forEach((clue) => {
        let tmp = hint[clue]
        mat.forEach((sp) => {
          if (!(sp in tmp)) { mat.splice(mat.indexOf(sp), 1) }
        })
        result = result.concat('查詢結果為: ' + (mat.join(',') || '無資料'))
        if (mat.length === 1) { result = result.concat(wanted[mat[0]]) }
      })
    }
  } else { result = result.concat('沒有給予條件') }
  return result
}

function mapLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    let mapID = map.alias[dex[0]]
    result = result.concat(map.data(mapID))
  } else {
    result = result.concat('沒有給予條件')
  }
  return result
}

function illLooker (dex) {
  let result = []
  dex.splice(0, 1)
  if (dex[0]) {
    result = result.concat(ill[dex[0]])
  } else {
    result = result.concat('沒有給予條件')
  }
  return result
}

function sendMsg (sender, message) {
  request({
    uri: 'https://graph.facebook.com/v2.6/me/messages',
    qs: { access_token: token },
    method: 'POST',
    json: {
      recipient: { id: sender },
      message: { text: message }
    }
  })
}

function comment (input) {
  sendMsg(process.env.DEVID, input)
}

app.get('/in', (req, res) => {
  if (req.query['hub.mode'] === 'subscribe') {
    if (req.query['hub.verify_token'] === 'YalaBomm') res.send(req.query['hub.challenge'])
    else res.status(403)
  }
})

app.listen(port, () => { console.log(`Listening to ${port}`) })
<|endoftext|>


<commit_before>module.exports = {
  "parser": "babel-eslint",

  "env": {
    "browser": true,
    "mocha": true,
    "node": true
  },

  "plugins": [
    "babel"
  ],

  "rules": {

    // Separate the rules into blocks based on what plugin they come from.
    // Default rules are split up based on sections found on the eslint rules page.
    // Rules should be sorted alphabetically inside each section.

    "strict": 0,

    // Possible Errors
    "comma-dangle": [2, "always-multiline"], // disallow or enforce trailing commas
    "no-cond-assign": 2, // disallow assignment in conditional expressions
    "no-console": 0, // disallow use of console in the node environment
    "no-constant-condition": 2, // disallow use of constant expressions in conditions
    "no-control-regex": 0, // disallow control characters in regular expressions
    "no-debugger": 0, // disallow use of debugger
    "no-dupe-args": 2, // disallow duplicate arguments in functions
    "no-dupe-keys": 2, // disallow duplicate keys when creating object literals
    "no-duplicate-case": 2, // disallow a duplicate case label
    "no-empty": 2, // disallow empty statements
    "no-empty-character-class": 0, // disallow the use of empty character classes in regular expressions
    "no-ex-assign": 2, // disallow assigning to the exception in a catch block
    "no-extra-boolean-cast": 2, // disallow double-negation boolean casts in a boolean context
    "no-extra-parens": [2, "functions"], // disallow unnecessary parentheses
    "no-extra-semi": 0, // disallow unnecessary semicolons
    "no-func-assign": 2, // disallow overwriting functions written as function declarations
    "no-inner-declarations": [2, "functions"], // disallow function or variable declarations in nested blocks
    "no-invalid-regexp": 0, // disallow invalid regular expression strings in the RegExp constructor
    "no-irregular-whitespace": 0, // disallow irregular whitespace outside of strings and comments
    "no-negated-in-lhs": 0, // disallow negation of the left operand of an in expression
    "no-obj-calls": 2, // disallow the use of object properties of the global object (Math and JSON) as functions
    "no-regex-spaces": 0, // disallow multiple spaces in a regular expression literal
    "no-sparse-arrays": 0, // disallow sparse arrays
    "no-undef": 2, // disallow use of undeclared variables unless mentioned in a /*global */ block
    "no-unexpected-multiline": 2, // avoid code that looks like two expressions but is actually one
    "no-unreachable": 2, // disallow unreachable statements after a return, throw, continue, or break statement
    "no-unused-vars": 2, // disallow declaration of variables that are not used in the code
    "no-use-before-define": [2, "nofunc"], // disallow use of variables before they are defined
    "use-isnan": 2, // disallow comparisons with the value NaN
    "valid-jsdoc": [1, {
      "requireReturn": false,
      "requireReturnDescription": false,
      "requireReturnType": false,
      "preferType": {
        "String": "String",
        "Object": "Object",
        "Array": "Array",
        "Number": "Number"
      }
    }], // Ensure JSDoc comments are valid
    "valid-typeof": 2, // Ensure that the results of typeof are compared against a valid string

    // Best Practices
    "accessor-pairs": 2, // Enforces getter/setter pairs in objects
    "block-scoped-var": 0, // treat var statements as if they were block scoped
    "complexity": [2, 7], // specify the maximum cyclomatic complexity allowed in a program
    "consistent-return": 2, // require return statements to either always or never specify values
    "curly": 0, // specify curly brace conventions for all control statements
    "default-case": 0, // require default case in switch statements
    "dot-location": 0, // enforces consistent newlines before or after dots
    "dot-notation": 2, // encourages use of dot notation whenever possible
    "eqeqeq": [2, "smart"], // require the use of === and !==
    "guard-for-in": 0, // make sure for-in loops have an if statement
    "no-alert": 0, // disallow the use of alert, confirm, and prompt
    "no-caller": 0, // disallow use of arguments.caller or arguments.callee
    "no-case-declarations": 0, // disallow lexical declarations in case clauses
    "no-div-regex": 0, // disallow division operators explicitly at beginning of regular expression
    "no-else-return": 2, // disallow else after a return in an if
    "no-empty-label": 0, // disallow use of labels for anything other than loops and switches
    "no-empty-pattern": 0, // disallow use of empty destructuring patterns
    "no-eq-null": 0, // disallow comparisons to null without a type-checking operator
    "no-eval": 0, // disallow use of eval()
    "no-extend-native": 0, // disallow adding to native types
    "no-extra-bind": 2, // disallow unnecessary function binding
    "no-fallthrough": 0, // disallow fallthrough of case statements
    "no-floating-decimal": 0, // disallow the use of leading or trailing decimal points in numeric literals
    "no-implicit-coercion": 0, // disallow the type conversions with shorter notations
    "no-implied-eval": 0, // disallow use of eval()-like methods
    "no-invalid-this": 0, // disallow this keywords outside of classes or class-like objects
    "no-iterator": 0, // disallow usage of __iterator__ property
    "no-labels": 0, // disallow use of labeled statements
    "no-lone-blocks": 2, // disallow unnecessary nested blocks
    "no-loop-func": 0, // disallow creation of functions within loops
    "no-magic-numbers ": 0, // isallow the use of magic numbers
    "no-multi-spaces": 0, // disallow use of multiple spaces
    "no-multi-str": 0, // disallow use of multiline strings
    "no-native-reassign": 0, // disallow reassignments of native objects
    "no-new": 0, // disallow use of the new operator when not part of an assignment or comparison
    "no-new-func": 0, // disallow use of new operator for Function object
    "no-new-wrappers": 0, // disallows creating new instances of String,Number, and Boolean
    "no-octal": 0, // disallow use of octal literals
    "no-octal-escape": 0, // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251";
    "no-param-reassign": 0, // disallow reassignment of function parameters
    "no-process-env": 0, // disallow use of process.env
    "no-proto": 0, // disallow usage of __proto__ property
    "no-redeclare": 0, // disallow declaring the same variable more than once
    "no-return-assign": 0, // disallow use of assignment in return statement
    "no-script-url": 0, // disallow use of javascript: urls.
    "no-self-compare": 0, // disallow comparisons where both sides are exactly the same
    "no-sequences": 0, // disallow use of the comma operator
    "no-throw-literal": 0, // restrict what can be thrown as an exception
    "no-unused-expressions": 0, // disallow usage of expressions in statement position
    "no-useless-call": 0, // disallow unnecessary .call() and .apply()
    "no-useless-concat": 0, // disallow unnecessary concatenation of literals or template literals
    "no-void": 0, // disallow use of the void operator
    "no-warning-comments": 0, // disallow usage of configurable warning terms in comments - e.g. TODO or FIXME
    "no-with": 0, // disallow use of the with statement
    "radix": 0, // require use of the second argument for parseInt()
    "vars-on-top": 0, // require declaration of all vars at the top of their containing scope
    "wrap-iife": 0, // require immediate function invocation to be wrapped in parentheses
    "yoda": 0, // require or disallow Yoda conditions

    // Stylistic Issues
    "array-bracket-spacing": [2, "never"], // enforce spacing inside array brackets
    "block-spacing": 0, // disallow or enforce spaces inside of single line blocks
    "brace-style": [2, "1tbs"], // enforce one true brace style
    "camelcase": 2, // require camel case names
    "comma-spacing": 2, // enforce spacing before and after comma
    "comma-style": 2, // enforce one true comma style
    "computed-property-spacing": 0, // require or disallow padding inside computed properties
    "consistent-this": 0, // enforce consistent naming when capturing the current execution context
    "eol-last": 2, // enforce newline at the end of file, with no multiple empty lines
    "func-names": 0, // require function expressions to have a name
    "func-style": [2, "declaration",  {"allowArrowFunctions": true}], // enforce use of function declarations or expressions
    "id-length": 0, // this option enforces minimum and maximum identifier lengths (variable names, property names etc.)
    "id-match": 0, // require identifiers to match the provided regular expression
    "indent": [2, 2], // specify tab or space width for your code
    "jsx-quotes": [2, "prefer-double"], // specify whether double or single quotes should be used in JSX attributes
    "key-spacing": 2, // enforce spacing between keys and values in object literal properties
    "linebreak-style": [2, "unix"], // disallow mixed 'LF' and 'CRLF' as linebreaks
    "lines-around-comment": 2, // enforce empty lines around comments
    "max-depth": 0, // specify the maximum depth that blocks can be nested
    "max-len": 0, // specify the maximum length of a line in your program
    "max-nested-callbacks": [2, 3], // specify the maximum depth callbacks can be nested
    "max-params": 0, // limits the number of parameters that can be used in the function declaration.
    "max-statements": 0, // specify the maximum number of statement allowed in a function
    "new-cap": [2, { "capIsNew": false }], // require a capital letter for constructors
    "new-parens": 2, // disallow the omission of parentheses when invoking a constructor with no arguments
    "newline-after-var": 0, // require or disallow an empty newline after variable declarations
    "no-array-constructor": 0, // disallow use of the Array constructor
    "no-bitwise": 0, // disallow use of bitwise operators
    "no-continue": 0, // disallow use of the continue statement
    "no-inline-comments": 0, // disallow comments inline after code
    "no-lonely-if": 0, // disallow if as the only statement in an else block
    "no-mixed-spaces-and-tabs": 0, // disallow mixed spaces and tabs for indentation
    "no-multiple-empty-lines": [1, { "max": 3 }], // disallow multiple empty lines
    "no-negated-condition": 0, // disallow negated conditions
    "no-nested-ternary": 2, // disallow nested ternary expressions
    "no-new-object": 0, // disallow the use of the Object constructor
    "no-plusplus": 0, // disallow use of unary operators, ++ and --
    "no-restricted-syntax": 0, // disallow use of certain syntax in code
    "no-spaced-func": 0, // disallow space between function identifier and application
    "no-ternary": 0, // disallow the use of ternary operators
    "no-trailing-spaces": 0, // disallow trailing whitespace at the end of lines
    "no-underscore-dangle": 0, // disallow dangling underscores in identifiers
    "no-underscore-dangle": 0, // disallow dangling underscores in identifiers
    "no-unneeded-ternary": 2, // disallow the use of ternary operators when a simpler alternative exists
    "object-curly-spacing": 0, // require or disallow padding inside curly braces
    "one-var": 0, // require or disallow one variable declaration per function
    "operator-assignment": 0, // require assignment operator shorthand where possible or prohibit it entirely
    "operator-linebreak": 0, // enforce operators to be placed before or after line breaks
    "padded-blocks": 0, // enforce padding within blocks
    "quote-props": 0, // require quotes around object literal property names
    "quotes": [2, "double"], // specify whether backticks, double or single quotes should be used
    "require-jsdoc": 0, // Require JSDoc comment
    "semi": [2, "never"], // require or disallow use of semicolons instead of ASI
    "semi-spacing": 0, // enforce spacing before and after semicolons
    "sort-vars": 2, // sort variables within the same declaration block
    "space-after-keywords": 2, // require a space after certain keywords
    "space-before-blocks": 2, // space-before-blocks
    "space-before-function-paren": [2, "never"], // require or disallow a space before function opening parenthesis
    "space-before-keywords": 0, // require a space before certain keywords
    "space-in-parens": [2, "never"], // require or disallow spaces inside parentheses
    "space-infix-ops": 2, // require spaces around operators
    "space-return-throw-case": 0, // require a space after return, throw, and case
    "space-unary-ops": 0, // require or disallow spaces before/after unary operators
    "spaced-comment": 2, // require or disallow a space immediately following the // or /* in a comment
    "wrap-regex": 0, // require regex literals to be wrapped in parentheses

    // ECMAScript 6
    "arrow-body-style": 0, // require braces in arrow function body
    "arrow-parens": 0, // require parens in arrow function arguments
    "arrow-spacing": 0, // require space before/after arrow function's arrow
    "constructor-super": 2, // verify calls of super() in constructors
    "generator-star-spacing": 0, // enforce spacing around the * in generator functions
    "no-arrow-condition": 0, // disallow arrow functions where a condition is expected
    "no-class-assign": 0, // disallow modifying variables of class declarations
    "no-const-assign": 0, // disallow modifying variables that are declared using const
    "no-dupe-class-members": 0, // disallow duplicate name in class members
    "no-this-before-super": 2, // disallow use of this/super before calling super() in constructors.
    "no-var": 2, // require let or const instead of var
    "object-shorthand": 0, // require method and property shorthand syntax for object literals
    "prefer-arrow-callback": 0, // suggest using arrow functions as callbacks
    "prefer-const": 2, // uggest using const declaration for variables that are never modified after declared
    "prefer-reflect": 0, // suggest using Reflect methods where applicable
    "prefer-spread": 0, // suggest using the spread operator instead of .apply().
    "prefer-template": 0, // suggest using template literals instead of strings concatenation
    "require-yield": 0, // disallow generator functions that do not have yield

    // Plugins
    // Babel
    "babel/array-bracket-spacing": 0,
    "babel/arrow-parens": 0,
    "babel/generator-star-spacing": 0,
    "babel/new-cap": 0,
    "babel/no-await-in-loop": 0,
    "babel/object-curly-spacing": 0,
    "babel/object-shorthand": 2,
  }
}
<commit_msg>Remove rule only valid in eslint v2<commit_after>module.exports = {
  "parser": "babel-eslint",

  "env": {
    "browser": true,
    "mocha": true,
    "node": true
  },

  "plugins": [
    "babel"
  ],

  "rules": {

    // Separate the rules into blocks based on what plugin they come from.
    // Default rules are split up based on sections found on the eslint rules page.
    // Rules should be sorted alphabetically inside each section.

    "strict": 0,

    // Possible Errors
    "comma-dangle": [2, "always-multiline"], // disallow or enforce trailing commas
    "no-cond-assign": 2, // disallow assignment in conditional expressions
    "no-console": 0, // disallow use of console in the node environment
    "no-constant-condition": 2, // disallow use of constant expressions in conditions
    "no-control-regex": 0, // disallow control characters in regular expressions
    "no-debugger": 0, // disallow use of debugger
    "no-dupe-args": 2, // disallow duplicate arguments in functions
    "no-dupe-keys": 2, // disallow duplicate keys when creating object literals
    "no-duplicate-case": 2, // disallow a duplicate case label
    "no-empty": 2, // disallow empty statements
    "no-empty-character-class": 0, // disallow the use of empty character classes in regular expressions
    "no-ex-assign": 2, // disallow assigning to the exception in a catch block
    "no-extra-boolean-cast": 2, // disallow double-negation boolean casts in a boolean context
    "no-extra-parens": [2, "functions"], // disallow unnecessary parentheses
    "no-extra-semi": 0, // disallow unnecessary semicolons
    "no-func-assign": 2, // disallow overwriting functions written as function declarations
    "no-inner-declarations": [2, "functions"], // disallow function or variable declarations in nested blocks
    "no-invalid-regexp": 0, // disallow invalid regular expression strings in the RegExp constructor
    "no-irregular-whitespace": 0, // disallow irregular whitespace outside of strings and comments
    "no-negated-in-lhs": 0, // disallow negation of the left operand of an in expression
    "no-obj-calls": 2, // disallow the use of object properties of the global object (Math and JSON) as functions
    "no-regex-spaces": 0, // disallow multiple spaces in a regular expression literal
    "no-sparse-arrays": 0, // disallow sparse arrays
    "no-undef": 2, // disallow use of undeclared variables unless mentioned in a /*global */ block
    "no-unexpected-multiline": 2, // avoid code that looks like two expressions but is actually one
    "no-unreachable": 2, // disallow unreachable statements after a return, throw, continue, or break statement
    "no-unused-vars": 2, // disallow declaration of variables that are not used in the code
    "no-use-before-define": [2, "nofunc"], // disallow use of variables before they are defined
    "use-isnan": 2, // disallow comparisons with the value NaN
    "valid-jsdoc": [1, {
      "requireReturn": false,
      "requireReturnDescription": false,
      "requireReturnType": false
    }], // Ensure JSDoc comments are valid
    "valid-typeof": 2, // Ensure that the results of typeof are compared against a valid string

    // Best Practices
    "accessor-pairs": 2, // Enforces getter/setter pairs in objects
    "block-scoped-var": 0, // treat var statements as if they were block scoped
    "complexity": [2, 7], // specify the maximum cyclomatic complexity allowed in a program
    "consistent-return": 2, // require return statements to either always or never specify values
    "curly": 0, // specify curly brace conventions for all control statements
    "default-case": 0, // require default case in switch statements
    "dot-location": 0, // enforces consistent newlines before or after dots
    "dot-notation": 2, // encourages use of dot notation whenever possible
    "eqeqeq": [2, "smart"], // require the use of === and !==
    "guard-for-in": 0, // make sure for-in loops have an if statement
    "no-alert": 0, // disallow the use of alert, confirm, and prompt
    "no-caller": 0, // disallow use of arguments.caller or arguments.callee
    "no-case-declarations": 0, // disallow lexical declarations in case clauses
    "no-div-regex": 0, // disallow division operators explicitly at beginning of regular expression
    "no-else-return": 2, // disallow else after a return in an if
    "no-empty-label": 0, // disallow use of labels for anything other than loops and switches
    "no-empty-pattern": 0, // disallow use of empty destructuring patterns
    "no-eq-null": 0, // disallow comparisons to null without a type-checking operator
    "no-eval": 0, // disallow use of eval()
    "no-extend-native": 0, // disallow adding to native types
    "no-extra-bind": 2, // disallow unnecessary function binding
    "no-fallthrough": 0, // disallow fallthrough of case statements
    "no-floating-decimal": 0, // disallow the use of leading or trailing decimal points in numeric literals
    "no-implicit-coercion": 0, // disallow the type conversions with shorter notations
    "no-implied-eval": 0, // disallow use of eval()-like methods
    "no-invalid-this": 0, // disallow this keywords outside of classes or class-like objects
    "no-iterator": 0, // disallow usage of __iterator__ property
    "no-labels": 0, // disallow use of labeled statements
    "no-lone-blocks": 2, // disallow unnecessary nested blocks
    "no-loop-func": 0, // disallow creation of functions within loops
    "no-magic-numbers ": 0, // isallow the use of magic numbers
    "no-multi-spaces": 0, // disallow use of multiple spaces
    "no-multi-str": 0, // disallow use of multiline strings
    "no-native-reassign": 0, // disallow reassignments of native objects
    "no-new": 0, // disallow use of the new operator when not part of an assignment or comparison
    "no-new-func": 0, // disallow use of new operator for Function object
    "no-new-wrappers": 0, // disallows creating new instances of String,Number, and Boolean
    "no-octal": 0, // disallow use of octal literals
    "no-octal-escape": 0, // disallow use of octal escape sequences in string literals, such as var foo = "Copyright \251";
    "no-param-reassign": 0, // disallow reassignment of function parameters
    "no-process-env": 0, // disallow use of process.env
    "no-proto": 0, // disallow usage of __proto__ property
    "no-redeclare": 0, // disallow declaring the same variable more than once
    "no-return-assign": 0, // disallow use of assignment in return statement
    "no-script-url": 0, // disallow use of javascript: urls.
    "no-self-compare": 0, // disallow comparisons where both sides are exactly the same
    "no-sequences": 0, // disallow use of the comma operator
    "no-throw-literal": 0, // restrict what can be thrown as an exception
    "no-unused-expressions": 0, // disallow usage of expressions in statement position
    "no-useless-call": 0, // disallow unnecessary .call() and .apply()
    "no-useless-concat": 0, // disallow unnecessary concatenation of literals or template literals
    "no-void": 0, // disallow use of the void operator
    "no-warning-comments": 0, // disallow usage of configurable warning terms in comments - e.g. TODO or FIXME
    "no-with": 0, // disallow use of the with statement
    "radix": 0, // require use of the second argument for parseInt()
    "vars-on-top": 0, // require declaration of all vars at the top of their containing scope
    "wrap-iife": 0, // require immediate function invocation to be wrapped in parentheses
    "yoda": 0, // require or disallow Yoda conditions

    // Stylistic Issues
    "array-bracket-spacing": [2, "never"], // enforce spacing inside array brackets
    "block-spacing": 0, // disallow or enforce spaces inside of single line blocks
    "brace-style": [2, "1tbs"], // enforce one true brace style
    "camelcase": 2, // require camel case names
    "comma-spacing": 2, // enforce spacing before and after comma
    "comma-style": 2, // enforce one true comma style
    "computed-property-spacing": 0, // require or disallow padding inside computed properties
    "consistent-this": 0, // enforce consistent naming when capturing the current execution context
    "eol-last": 2, // enforce newline at the end of file, with no multiple empty lines
    "func-names": 0, // require function expressions to have a name
    "func-style": [2, "declaration",  {"allowArrowFunctions": true}], // enforce use of function declarations or expressions
    "id-length": 0, // this option enforces minimum and maximum identifier lengths (variable names, property names etc.)
    "id-match": 0, // require identifiers to match the provided regular expression
    "indent": [2, 2], // specify tab or space width for your code
    "jsx-quotes": [2, "prefer-double"], // specify whether double or single quotes should be used in JSX attributes
    "key-spacing": 2, // enforce spacing between keys and values in object literal properties
    "linebreak-style": [2, "unix"], // disallow mixed 'LF' and 'CRLF' as linebreaks
    "lines-around-comment": 2, // enforce empty lines around comments
    "max-depth": 0, // specify the maximum depth that blocks can be nested
    "max-len": 0, // specify the maximum length of a line in your program
    "max-nested-callbacks": [2, 3], // specify the maximum depth callbacks can be nested
    "max-params": 0, // limits the number of parameters that can be used in the function declaration.
    "max-statements": 0, // specify the maximum number of statement allowed in a function
    "new-cap": [2, { "capIsNew": false }], // require a capital letter for constructors
    "new-parens": 2, // disallow the omission of parentheses when invoking a constructor with no arguments
    "newline-after-var": 0, // require or disallow an empty newline after variable declarations
    "no-array-constructor": 0, // disallow use of the Array constructor
    "no-bitwise": 0, // disallow use of bitwise operators
    "no-continue": 0, // disallow use of the continue statement
    "no-inline-comments": 0, // disallow comments inline after code
    "no-lonely-if": 0, // disallow if as the only statement in an else block
    "no-mixed-spaces-and-tabs": 0, // disallow mixed spaces and tabs for indentation
    "no-multiple-empty-lines": [1, { "max": 3 }], // disallow multiple empty lines
    "no-negated-condition": 0, // disallow negated conditions
    "no-nested-ternary": 2, // disallow nested ternary expressions
    "no-new-object": 0, // disallow the use of the Object constructor
    "no-plusplus": 0, // disallow use of unary operators, ++ and --
    "no-restricted-syntax": 0, // disallow use of certain syntax in code
    "no-spaced-func": 0, // disallow space between function identifier and application
    "no-ternary": 0, // disallow the use of ternary operators
    "no-trailing-spaces": 0, // disallow trailing whitespace at the end of lines
    "no-underscore-dangle": 0, // disallow dangling underscores in identifiers
    "no-underscore-dangle": 0, // disallow dangling underscores in identifiers
    "no-unneeded-ternary": 2, // disallow the use of ternary operators when a simpler alternative exists
    "object-curly-spacing": 0, // require or disallow padding inside curly braces
    "one-var": 0, // require or disallow one variable declaration per function
    "operator-assignment": 0, // require assignment operator shorthand where possible or prohibit it entirely
    "operator-linebreak": 0, // enforce operators to be placed before or after line breaks
    "padded-blocks": 0, // enforce padding within blocks
    "quote-props": 0, // require quotes around object literal property names
    "quotes": [2, "double"], // specify whether backticks, double or single quotes should be used
    "require-jsdoc": 0, // Require JSDoc comment
    "semi": [2, "never"], // require or disallow use of semicolons instead of ASI
    "semi-spacing": 0, // enforce spacing before and after semicolons
    "sort-vars": 2, // sort variables within the same declaration block
    "space-after-keywords": 2, // require a space after certain keywords
    "space-before-blocks": 2, // space-before-blocks
    "space-before-function-paren": [2, "never"], // require or disallow a space before function opening parenthesis
    "space-before-keywords": 0, // require a space before certain keywords
    "space-in-parens": [2, "never"], // require or disallow spaces inside parentheses
    "space-infix-ops": 2, // require spaces around operators
    "space-return-throw-case": 0, // require a space after return, throw, and case
    "space-unary-ops": 0, // require or disallow spaces before/after unary operators
    "spaced-comment": 2, // require or disallow a space immediately following the // or /* in a comment
    "wrap-regex": 0, // require regex literals to be wrapped in parentheses

    // ECMAScript 6
    "arrow-body-style": 0, // require braces in arrow function body
    "arrow-parens": 0, // require parens in arrow function arguments
    "arrow-spacing": 0, // require space before/after arrow function's arrow
    "constructor-super": 2, // verify calls of super() in constructors
    "generator-star-spacing": 0, // enforce spacing around the * in generator functions
    "no-arrow-condition": 0, // disallow arrow functions where a condition is expected
    "no-class-assign": 0, // disallow modifying variables of class declarations
    "no-const-assign": 0, // disallow modifying variables that are declared using const
    "no-dupe-class-members": 0, // disallow duplicate name in class members
    "no-this-before-super": 2, // disallow use of this/super before calling super() in constructors.
    "no-var": 2, // require let or const instead of var
    "object-shorthand": 0, // require method and property shorthand syntax for object literals
    "prefer-arrow-callback": 0, // suggest using arrow functions as callbacks
    "prefer-const": 2, // uggest using const declaration for variables that are never modified after declared
    "prefer-reflect": 0, // suggest using Reflect methods where applicable
    "prefer-spread": 0, // suggest using the spread operator instead of .apply().
    "prefer-template": 0, // suggest using template literals instead of strings concatenation
    "require-yield": 0, // disallow generator functions that do not have yield

    // Plugins
    // Babel
    "babel/array-bracket-spacing": 0,
    "babel/arrow-parens": 0,
    "babel/generator-star-spacing": 0,
    "babel/new-cap": 0,
    "babel/no-await-in-loop": 0,
    "babel/object-curly-spacing": 0,
    "babel/object-shorthand": 2,
  }
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var pkg = require(path.join(__dirname, 'package.json'));
var chalk = require('chalk');
var parser = require('gitignore-parser');
var endOfLine = require('os').EOL;

var program = require('commander');
program.version(pkg.version)
    .option('-d, --directory <path>', 'The directory to start the scan')
    .option('-o, --output', 'Displays the file currently being read')
    .parse(process.argv);

var start = __dirname;
if (fs.existsSync(program.directory)) {
    start = program.directory;
} else if (program.directory != undefined) {
    console.error(chalk.red('The directory \'%s\' dose not exist'), program.directory);
    program.help();
    process.exit(1);
}

var gitignore = undefined;
if (fs.existsSync('.gitignore')) {
    gitignore = parser.compile(fs.readFileSync('.gitignore', 'utf8'));
    console.log('Filtering using .gitignore');
}

var extensions = [
    "asm",
    "brs",
    "c",
    "cc",
    "clj",
    "cljs",
    "coffee",
    "cpp",
    "cr",
    "cs",
    "css",
    "cxx",
    "dart",
    "erl",
    "go",
    "groovy",
    "gs",
    "h",
    "handlebars", "hbs",
    "hpp",
    "hr",
    "hs",
    "html", "htm",
    "hx",
    "hxx",
    "hy",
    "iced",
    "ino",
    "jade",
    "java",
    "jl",
    "js",
    "jsx",
    "kt",
    "kts",
    "less",
    "lua",
    "ls",
    "ml",
    "mli",
    "mochi",
    "monkey",
    "mustache",
    "nix",
    "nim",
    "nut",
    "php", "php5",
    "pl",
    "py",
    "r",
    "rb",
    "rkt",
    "rs",
    "sass",
    "scala",
    "scss",
    "styl",
    "svg",
    "swift",
    "ts",
    "tsx",
    "vb",
    "xml",
    "yaml",
    "m",
    "mm"
]

function extensionsContains(extention) {
    var i = extensions.length;
    while (i--) {
        if (extensions[i] === extention) return true;
    }
    return false;
}

function scan(current, callback) {
    var cFiles = 0, cFolders = 0, cLines = 0;
    if (program.output) console.log(' dir > %s', chalk.gray(current));
    var files = fs.readdirSync(current);
    if (gitignore != undefined) files = files.filter(gitignore.accepts);
    files.forEach(next => {
        var next = path.join(current, next);
        if (fs.existsSync(next)) {
            var stat = fs.lstatSync(next);
            if (stat.isDirectory()) {
                cFolders++;
                scan(next, function(files, folders, lines) {
                    cFiles += files;
                    cFolders += folders;
                    cLines += lines;
                });
            } else if (stat.isFile()) {
                if (extensionsContains(next.split('.').pop())) {
                    cFiles++;
                    read(next, function(lines) {
                        cLines += lines;
                    });
                }
            }
        }
    });
    callback(cFiles, cFolders, cLines);
}

function read(file, callback) {
    var contents = fs.readFileSync(file, 'utf8');

    var lines = contents.split(endOfLine).length;

    // var lines = 0;
    // for (String line: contents.split(endOfLine)) {
    //     lines ++;
    // }

    if (program.output) console.log('file > %s %s line(s)', chalk.gray(file), lines);
    callback(lines);
}

console.log('Scanning %s', start);
scan(start, function(files, folders, lines) {
    console.log("Folders Scanned: %s", folders);
    console.log("Files: %s", files);
    console.log("Lines: %s", lines);
});
<commit_msg>fixed issue with the wrong dir<commit_after>#!/usr/bin/env node
var fs = require('fs');
var path = require('path');
var pkg = require(path.join(__dirname, 'package.json'));
var chalk = require('chalk');
var parser = require('gitignore-parser');
var endOfLine = require('os').EOL;

var program = require('commander');
program.version(pkg.version)
    .option('-d, --directory <path>', 'The directory to start the scan')
    .option('-o, --output', 'Displays the file currently being read')
    .parse(process.argv);

var start = process.cwd();
if (fs.existsSync(program.directory)) {
    start = program.directory;
} else if (program.directory != undefined) {
    console.error(chalk.red('The directory \'%s\' dose not exist'), program.directory);
    program.help();
    process.exit(1);
}

var gitignore = undefined;
if (fs.existsSync('.gitignore')) {
    gitignore = parser.compile(fs.readFileSync('.gitignore', 'utf8'));
    console.log('Filtering using .gitignore');
}

var extensions = [
    "asm",
    "brs",
    "c",
    "cc",
    "clj",
    "cljs",
    "coffee",
    "cpp",
    "cr",
    "cs",
    "css",
    "cxx",
    "dart",
    "erl",
    "go",
    "groovy",
    "gs",
    "h",
    "handlebars", "hbs",
    "hpp",
    "hr",
    "hs",
    "html", "htm",
    "hx",
    "hxx",
    "hy",
    "iced",
    "ino",
    "jade",
    "java",
    "jl",
    "js",
    "jsx",
    "kt",
    "kts",
    "less",
    "lua",
    "ls",
    "ml",
    "mli",
    "mochi",
    "monkey",
    "mustache",
    "nix",
    "nim",
    "nut",
    "php", "php5",
    "pl",
    "py",
    "r",
    "rb",
    "rkt",
    "rs",
    "sass",
    "scala",
    "scss",
    "styl",
    "svg",
    "swift",
    "ts",
    "tsx",
    "vb",
    "xml",
    "yaml",
    "m",
    "mm"
]

function extensionsContains(extention) {
    var i = extensions.length;
    while (i--) {
        if (extensions[i] === extention) return true;
    }
    return false;
}

function scan(current, callback) {
    var cFiles = 0, cFolders = 0, cLines = 0;
    if (program.output) console.log(' dir > %s', chalk.gray(current));
    var files = fs.readdirSync(current);
    if (gitignore != undefined) files = files.filter(gitignore.accepts);
    files.forEach(next => {
        var next = path.join(current, next);
        if (fs.existsSync(next)) {
            var stat = fs.lstatSync(next);
            if (stat.isDirectory()) {
                cFolders++;
                scan(next, function(files, folders, lines) {
                    cFiles += files;
                    cFolders += folders;
                    cLines += lines;
                });
            } else if (stat.isFile()) {
                if (extensionsContains(next.split('.').pop())) {
                    cFiles++;
                    read(next, function(lines) {
                        cLines += lines;
                    });
                }
            }
        }
    });
    callback(cFiles, cFolders, cLines);
}

function read(file, callback) {
    var contents = fs.readFileSync(file, 'utf8');

    var lines = contents.split(endOfLine).length;

    // var lines = 0;
    // for (String line: contents.split(endOfLine)) {
    //     lines ++;
    // }

    if (program.output) console.log('file > %s %s line(s)', chalk.gray(file), lines);
    callback(lines);
}

console.log('Scanning %s', start);
scan(start, function(files, folders, lines) {
    console.log("Folders Scanned: %s", folders);
    console.log("Files: %s", files);
    console.log("Lines: %s", lines);
});
<|endoftext|>


<commit_before>'use strict';

var through = require('through2'),
    glob = require('glob'),
    path = require('path'),
    replaceExt = require('replace-ext'),
    gutil = require('gulp-util'),
    fs = require('fs'),
    PluginError = gutil.PluginError;

var PLUGIN_NAME = 'gulp-include-source';

var placeholders = {
  'js' : '<script src="%"></script>',
  'css' : '<link rel="stylesheet" href="%">'
};

function matchExpressions(contents) {
  return contents.match(/<!--\s+include:([a-z]+)\(([^)]+)\)\s+-->/);
}

function replaceExtension(filename, type, options) {

  if( options.scriptExt && type === 'js' ) {
    filename = replaceExt(filename, '.' + options.scriptExt);
  } else if( options.styleExt && type === 'css' ) {
    filename = replaceExt(filename, '.' + options.styleExt);
  }

  return filename;
}

function parseFiles(source, cwd) {

  if( source.indexOf('list:') === 0 ) {
    var cleanSrc = source.replace('list:', '');
    return fs.readFileSync( cleanSrc ).toString().split('\n');
  }

  return glob.sync( source, { cwd : cwd } );
}

function injectFiles(file, options) {

  var contents = file.contents.toString();
  var cwd = options.cwd || path.dirname(file.path);
  var matches = matchExpressions(contents);

  while( matches ) {

    var type = matches[1];
    var placeholder = placeholders[ type ];
    var files = parseFiles(matches[2], cwd);
    var includes = '';

    if( placeholder && files && files.length > 0 ) {

      includes = files.map(function(filename) {
        filename = replaceExtension(filename, type, options);
        return placeholder.split('%').join(filename);
      }).join('\n');
    }

    contents = contents.substring(0, matches.index) + includes + contents.substring(matches.index + matches[0].length);
    matches = matchExpressions(contents);
  }

  return contents;
}

function gulpIncludeSource(options) {

  options = options || {};

  var stream = through.obj(function(file, enc, callback) {

    if (file.isNull()) {
      this.push(file); // Do nothing if no contents
      return callback();
    }

    if (file.isStream()) {
      this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported!'));
      return callback();
    }

    if (file.isBuffer()) {
      try {
        file.contents = new Buffer( injectFiles( file, options ) );
      } catch (err) {
        this.emit('error', new gutil.PluginError(PLUGIN_NAME, err));
      }
    }

    this.push(file);
    return callback();
  });

  return stream;
}

module.exports = gulpIncludeSource;<commit_msg>Add baseUrl option for setting results url prefix.<commit_after>'use strict';

var through = require('through2'),
    glob = require('glob'),
    path = require('path'),
    replaceExt = require('replace-ext'),
    gutil = require('gulp-util'),
    fs = require('fs'),
    PluginError = gutil.PluginError;

var PLUGIN_NAME = 'gulp-include-source';

var placeholders = {
  'js' : '<script src="%"></script>',
  'css' : '<link rel="stylesheet" href="%">'
};

function matchExpressions(contents) {
  return contents.match(/<!--\s+include:([a-z]+)\(([^)]+)\)\s+-->/);
}

function replaceExtension(filename, type, options) {

  if( options.scriptExt && type === 'js' ) {
    filename = replaceExt(filename, '.' + options.scriptExt);
  } else if( options.styleExt && type === 'css' ) {
    filename = replaceExt(filename, '.' + options.styleExt);
  }

  return filename;
}

function parseFiles(source, cwd) {

  if( source.indexOf('list:') === 0 ) {
    var cleanSrc = source.replace('list:', '');
    return fs.readFileSync( cleanSrc ).toString().split('\n');
  }

  return glob.sync( source, { cwd : cwd } );
}

function injectFiles(file, options) {

  var contents = file.contents.toString();
  var cwd = options.cwd || path.dirname(file.path);
  var baseUrl = options.baseUrl || '';
  var matches = matchExpressions(contents);

  while( matches ) {

    var type = matches[1];
    var placeholder = placeholders[ type ];
    var files = parseFiles(matches[2], cwd);
    var includes = '';

    if( placeholder && files && files.length > 0 ) {

      includes = files.map(function(filename) {
        filename = baseUrl + replaceExtension(filename, type, options);
        return placeholder.split('%').join(filename);
      }).join('\n');
    }

    contents = contents.substring(0, matches.index) + includes + contents.substring(matches.index + matches[0].length);
    matches = matchExpressions(contents);
  }

  return contents;
}

function gulpIncludeSource(options) {

  options = options || {};

  var stream = through.obj(function(file, enc, callback) {

    if (file.isNull()) {
      this.push(file); // Do nothing if no contents
      return callback();
    }

    if (file.isStream()) {
      this.emit('error', new PluginError(PLUGIN_NAME, 'Streaming not supported!'));
      return callback();
    }

    if (file.isBuffer()) {
      try {
        file.contents = new Buffer( injectFiles( file, options ) );
      } catch (err) {
        this.emit('error', new gutil.PluginError(PLUGIN_NAME, err));
      }
    }

    this.push(file);
    return callback();
  });

  return stream;
}

module.exports = gulpIncludeSource;<|endoftext|>