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

function Shizzle(id, dataFields, options){
  var self = this;
  var id = id;
  var $searchBox = null;
  var $items = null;
  var $pills = null;
  var dataText = null;
  var dataValue = null;
  var dataValue2 = null;
  var dataValue3 = null;
  var data = null;
  var itemsVisibleOnPageLoad = false;
  var setToFocusOnPageLoad = false;
  var onItemSelected = null;
  var onPillRemoved = null;
  var onItemsCleared = null;
  var isRequired = false;
  var fieldErrorCss = null;
  var showValidationMessage = false;
  var validationMessageCss = null;
  var validationMessageText = null;
  var validationTriggered = false;
  var placeholder = '';

  self.dataSource = null;
  self.items = [];
  self.filteredItems = [];
  self.pills = [];
  self.$pillContainer = null;

  //
  // INITIALIZE
  //

  init();

  function init(){
    if (!id)
      throw new Error('id is required');

    if (!dataFields)
      throw new Error('dataFields are required');

    // Map the data fields
    setDataFields(dataFields);

    // Set options
    if (options){
      data = options.data || null;
      itemsVisibleOnPageLoad = options.itemsVisibleOnPageLoad || false;
      onItemSelected = options.onItemSelected || null;
      onPillRemoved = options.onPillRemoved || null;
      onItemsCleared = options.onItemsCleared || null;
      setToFocusOnPageLoad = options.setToFocusOnPageLoad || false;
      fieldErrorCss =  options.fieldErrorCss || null;
      isRequired = options.isRequired || null;
      showValidationMessage = options.showValidationMessage || false;
      validationMessageCss = options.validationMessageCss || nulll;
      validationMessageText = options.validationMessageText || null;
      placeholder = options.placeholder || '';
    }

    // Set data source
    self.dataSource = _.sortBy(data, ['text']);
    self.items = _.cloneDeep(self.dataSource);

    // Create Elements
    var select = document.getElementById(id);
    createMainShizzleContainer(select, id);

    // Initialize dynamically created containers
    $items = $('#shizzle-container-' + id).find('.sz-choices');
    $searchBox = $('#shizzle-container-' + id).find('.sz-search-box');
    self.$pillContainer = $('#shizzle-container-' + id).find('.sz-pills');

    if (isRequired && showValidationMessage)
      createValidationMessage();

    //hide the dropdown initially
    if (itemsVisibleOnPageLoad)
      $items.show();
    else
      $items.hide();

    // Bring the control into focus as soon as page loads
    if (setToFocusOnPageLoad)
      $searchBox.focus();

    // Populate the dropdown now if initial data is present
    if (self.items)
      populateList(self.items);

    // Bind our events for the control
    bindEvents();
  }

  function bindEvents(){
    handleSearchBoxKeyupAndChange();
    handleKeypress();
    handleOutsideClicked();
    handleSearchBoxclicked();
    handleItemSelected();
    handlePillClicked();
  }

  //
  // Events
  //

  function handleSearchBoxKeyupAndChange(){
    $searchBox.on('keyup change', function(e) {
      // Clear temporary array
      self.filteredItems.length = 0;
      $items.empty();

      // Iterate through our items and verify if matching the filter
      _.forEach(self.items, function (item) {

        // Add the item to the filtered items list if the entered value is present in
        // the provided dataText property value
        if (item[dataText].toLowerCase().indexOf(e.target.value.toLowerCase()) > -1) {
          addFilteredItem(item);
        }

      });

      // Re-populate list based on the filtered set
      populateList(self.filteredItems);
    });
  }

  function handleKeypress() {
    $searchBox.on('keypress', function(e) {
      // If the list is not visible show it
      // when the user types in the input field
      if ($items.not(':visible'))
        $items.show();
    });
  }

  function handleOutsideClicked() {
    $(document).click(function() {
      $items.hide();
    });
  }

  function handleSearchBoxclicked() {
    $searchBox.click(function(e) {
      e.stopPropagation();

      $items.toggle();
    });
  }

  function handleItemSelected() {
    $(document).on('click', '#shizzle-container-' + id + ' .sz-choices li', function() {

      // Get the selectedItem text
      self.selectedItem = {
        value: $(this).data('value'),
        text: $(this).text(),
        value2: $(this).attr('data-value-2'),
        value3: $(this).attr('data-value-3')
      };

      $searchBox.val('');
      $searchBox.focus();
      // Toggle items
      $items.toggle();

      self.addPill(self.selectedItem);

      // Fire onItemSelected callback if provided
      if (onItemSelected)
        onItemSelected();
    });
  }

  //
  // Helpers
  //

  function setDataFields(dataFields){
    //TODO: look at removing this since we are already checking for it when initializing
    if (dataFields) {
      if (!dataFields.dataValue)
        throw new Error('dataValue is required');

      if (!dataFields.dataText)
        throw new Error('displayText is required');

      dataValue = dataFields.dataValue;
      dataText = dataFields.dataText;
      dataValue2 = dataFields.dataValue2;
      dataValue3 = dataFields.dataValue3;
    }
  }

  function createMainShizzleContainer(mainSelectElement, id){
    var selectContainer = document.createElement('div');
    selectContainer.id = 'shizzle-container-' + id;
    selectContainer.className = 'shizzlex';
    selectContainer.innerHTML = '

<input type=\'text\' placeholder="' + placeholder + '" class=\'sz-search-box\'/>

';

    insertAfter(selectContainer, mainSelectElement);
  }

  function populateList(data) {
    if (!data)
      return;

    $items.empty();

    _.forEach(data, function (item) {
      $items.append("
" + item[dataText] + '
');
    });
  }

  function handlePillClicked(){
    $(document).on('click', '#shizzle-container-' + id + ' .sz-pills li', function(e) {

      var selectedPill = {};
      selectedPill[dataValue] = $(this).data('value');
      selectedPill[dataText] = $(this).data('text');
      selectedPill[dataValue2] = $(this).attr('data-value-2');
      selectedPill[dataValue3] = $(this).attr('data-value-3');

      self.items.push(selectedPill);

      _.remove(self.pills, function(pill){
        return pill.value === selectedPill[dataValue];
      });

      var pillElementToRemove = $('[data-value="' + selectedPill[dataValue] + '"]');
      pillElementToRemove.remove();

      populateList(_.sortBy(self.items, ['text']));

      $searchBox.focus();

      if (validationTriggered)
        fireValidation();

      if (onPillRemoved)
        onPillRemoved();
    });
  }

  function addFilteredItem(item) {
    var itemExists = false;

    // Verify if item already exists in filtered array
    _.forEach(self.filteredItems, function (filteredItem) {
      if (filteredItem[dataValue] === item[dataValue])
        itemExists = true;
    });

    if (!itemExists) {
      // Add item to filtered array
      self.filteredItems.push(item);
    }
  }

  function insertAfter(el, referenceNode) {
    referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling);
  }

  function fireValidation(){
    if (isRequired){
      validationTriggered = true;

      if (self.pills.length === 0){
        self.$pillContainer.addClass(fieldErrorCss);

        if (showValidationMessage)
          showValidationMessageText();

      } else {
        self.$pillContainer.removeClass(fieldErrorCss);
      }
    }
  }

  function createValidationMessage(){
    var spanMessage = document.createElement('span');
    spanMessage.className = 'shizzlex sz-validation-message ' + validationMessageCss;
    spanMessage.innerText = validationMessageText;
    spanMessage.style.display = 'none';

    var parentEl = document.getElementById('shizzle-container-' + id);
    insertAfter(spanMessage, parentEl);
  }

  function showValidationMessageText(){
    $('.' + validationMessageCss).show();
  }

  function hideValidationMessageText(){
    $('.' + validationMessageCss).hide();
  }

  this.addPill = function(selectedItem){
    self.pills.push(selectedItem);

    var pillElement = document.createElement('li');
    pillElement.setAttribute('data-id', selectedItem.id);
    pillElement.setAttribute('data-text', selectedItem.text);
    pillElement.setAttribute('data-value', selectedItem.value);
    pillElement.setAttribute('data-value-2', selectedItem.value2);
    pillElement.setAttribute('data-value-3', selectedItem.value3);
    pillElement.className = 'sz-pill';
    pillElement.innerHTML = '' + selectedItem.text + '';
    $(pillElement).insertBefore($('#shizzle-container-' + id).find('.sz-search-box').parent());

    $pills = $('#shizzle-container-' + id).find('.sz-pill');

    _.remove(self.items, function(item){
      return item[dataValue] === selectedItem.value;
    });

    if (validationTriggered)
      fireValidation();

    if (isRequired && showValidationMessage)
      hideValidationMessageText();

    populateList(self.items);
  };

  this.clearData = function(){
    self.dataSource = null;
    self.items = null;
    self.pills.length = 0;
    self.filteredItems.length = 0;
    $searchBox.val('');
    $items.empty();
    $items.hide();

    if ($pills)
      $pills.remove();

    if (onItemsCleared)
      onItemsCleared();
  };

  this.populateWithData = function(data) {
    // Set data source
    self.dataSource = _.sortBy(data, ['text']);
    self.items = _.cloneDeep(self.dataSource);

    populateList(self.items);
  };

  this.validateControl = function(){
    fireValidation();
  };
};

//
// Public methods
//

Shizzle.prototype.getSelectedItems = function(){
  return this.pills;
};

Shizzle.prototype.setSelectedItems = function(selectedItems){
  var self = this;
  _.forEach(selectedItems, function(item) {
    self.addPill(item);
  });
};

Shizzle.prototype.clear = function() {
  this.clearData();
};

Shizzle.prototype.populate = function(data) {
  this.populateWithData(data);
};

Shizzle.prototype.isValid = function(){
  if(this.pills.length === 0)
    return false;
  else
    return true;
};

/**
 * @deprecated Since version 1.1.0 Will be deleted in version 1.2.0 Use validate() instead.
 */
Shizzle.prototype.fireValidation = function(){
  console.warn('fireValidation is deprecated since version 1.1.0 . Use validate() instead.');
  this.validateControl();
};

Shizzle.prototype.validate = function(){
  this.validateControl();
};

module.exports = Shizzle;<commit_msg>Namespacing all the classes to .sz- but have no way to test :) - again<commit_after>var $ = require('jquery');
var _ = require('lodash');

function Shizzle(id, dataFields, options){
  var self = this;
  var id = id;
  var $searchBox = null;
  var $items = null;
  var $pills = null;
  var dataText = null;
  var dataValue = null;
  var dataValue2 = null;
  var dataValue3 = null;
  var data = null;
  var itemsVisibleOnPageLoad = false;
  var setToFocusOnPageLoad = false;
  var onItemSelected = null;
  var onPillRemoved = null;
  var onItemsCleared = null;
  var isRequired = false;
  var fieldErrorCss = null;
  var showValidationMessage = false;
  var validationMessageCss = null;
  var validationMessageText = null;
  var validationTriggered = false;
  var placeholder = '';

  self.dataSource = null;
  self.items = [];
  self.filteredItems = [];
  self.pills = [];
  self.$pillContainer = null;

  //
  // INITIALIZE
  //

  init();

  function init(){
    if (!id)
      throw new Error('id is required');

    if (!dataFields)
      throw new Error('dataFields are required');

    // Map the data fields
    setDataFields(dataFields);

    // Set options
    if (options){
      data = options.data || null;
      itemsVisibleOnPageLoad = options.itemsVisibleOnPageLoad || false;
      onItemSelected = options.onItemSelected || null;
      onPillRemoved = options.onPillRemoved || null;
      onItemsCleared = options.onItemsCleared || null;
      setToFocusOnPageLoad = options.setToFocusOnPageLoad || false;
      fieldErrorCss =  options.fieldErrorCss || null;
      isRequired = options.isRequired || null;
      showValidationMessage = options.showValidationMessage || false;
      validationMessageCss = options.validationMessageCss || nulll;
      validationMessageText = options.validationMessageText || null;
      placeholder = options.placeholder || '';
    }

    // Set data source
    self.dataSource = _.sortBy(data, ['text']);
    self.items = _.cloneDeep(self.dataSource);

    // Create Elements
    var select = document.getElementById(id);
    createMainShizzleContainer(select, id);

    // Initialize dynamically created containers
    $items = $('#shizzle-container-' + id).find('.sz-choices');
    $searchBox = $('#shizzle-container-' + id).find('.sz-search-box');
    self.$pillContainer = $('#shizzle-container-' + id).find('.sz-pills');

    if (isRequired && showValidationMessage)
      createValidationMessage();

    //hide the dropdown initially
    if (itemsVisibleOnPageLoad)
      $items.show();
    else
      $items.hide();

    // Bring the control into focus as soon as page loads
    if (setToFocusOnPageLoad)
      $searchBox.focus();

    // Populate the dropdown now if initial data is present
    if (self.items)
      populateList(self.items);

    // Bind our events for the control
    bindEvents();
  }

  function bindEvents(){
    handleSearchBoxKeyupAndChange();
    handleKeypress();
    handleOutsideClicked();
    handleSearchBoxclicked();
    handleItemSelected();
    handlePillClicked();
  }

  //
  // Events
  //

  function handleSearchBoxKeyupAndChange(){
    $searchBox.on('keyup change', function(e) {
      // Clear temporary array
      self.filteredItems.length = 0;
      $items.empty();

      // Iterate through our items and verify if matching the filter
      _.forEach(self.items, function (item) {

        // Add the item to the filtered items list if the entered value is present in
        // the provided dataText property value
        if (item[dataText].toLowerCase().indexOf(e.target.value.toLowerCase()) > -1) {
          addFilteredItem(item);
        }

      });

      // Re-populate list based on the filtered set
      populateList(self.filteredItems);
    });
  }

  function handleKeypress() {
    $searchBox.on('keypress', function(e) {
      // If the list is not visible show it
      // when the user types in the input field
      if ($items.not(':visible'))
        $items.show();
    });
  }

  function handleOutsideClicked() {
    $(document).click(function() {
      $items.hide();
    });
  }

  function handleSearchBoxclicked() {
    $searchBox.click(function(e) {
      e.stopPropagation();

      $items.toggle();
    });
  }

  function handleItemSelected() {
    $(document).on('click', '#shizzle-container-' + id + ' .sz-choices li', function() {

      // Get the selectedItem text
      self.selectedItem = {
        value: $(this).data('value'),
        text: $(this).text(),
        value2: $(this).attr('data-value-2'),
        value3: $(this).attr('data-value-3')
      };

      $searchBox.val('');
      $searchBox.focus();
      // Toggle items
      $items.toggle();

      self.addPill(self.selectedItem);

      // Fire onItemSelected callback if provided
      if (onItemSelected)
        onItemSelected();
    });
  }

  //
  // Helpers
  //

  function setDataFields(dataFields){
    //TODO: look at removing this since we are already checking for it when initializing
    if (dataFields) {
      if (!dataFields.dataValue)
        throw new Error('dataValue is required');

      if (!dataFields.dataText)
        throw new Error('displayText is required');

      dataValue = dataFields.dataValue;
      dataText = dataFields.dataText;
      dataValue2 = dataFields.dataValue2;
      dataValue3 = dataFields.dataValue3;
    }
  }

  function createMainShizzleContainer(mainSelectElement, id){
    var selectContainer = document.createElement('div');
    selectContainer.id = 'shizzle-container-' + id;
    selectContainer.className = 'shizzlex';
    selectContainer.innerHTML = '

<input type=\'text\' placeholder="' + placeholder + '" class=\'sz-search-box\'/>

';

    insertAfter(selectContainer, mainSelectElement);
  }

  function populateList(data) {
    if (!data)
      return;

    $items.empty();

    _.forEach(data, function (item) {
      $items.append("
" + item[dataText] + '
');
    });
  }

  function handlePillClicked(){
    $(document).on('click', '#shizzle-container-' + id + ' .sz-pills li', function(e) {

      var selectedPill = {};
      selectedPill[dataValue] = $(this).data('value');
      selectedPill[dataText] = $(this).data('text');
      selectedPill[dataValue2] = $(this).attr('data-value-2');
      selectedPill[dataValue3] = $(this).attr('data-value-3');

      self.items.push(selectedPill);

      _.remove(self.pills, function(pill){
        return pill.value === selectedPill[dataValue];
      });

      var pillElementToRemove = $('[data-value="' + selectedPill[dataValue] + '"]');
      pillElementToRemove.remove();

      populateList(_.sortBy(self.items, ['text']));

      $searchBox.focus();

      if (validationTriggered)
        fireValidation();

      if (onPillRemoved)
        onPillRemoved();
    });
  }

  function addFilteredItem(item) {
    var itemExists = false;

    // Verify if item already exists in filtered array
    _.forEach(self.filteredItems, function (filteredItem) {
      if (filteredItem[dataValue] === item[dataValue])
        itemExists = true;
    });

    if (!itemExists) {
      // Add item to filtered array
      self.filteredItems.push(item);
    }
  }

  function insertAfter(el, referenceNode) {
    referenceNode.parentNode.insertBefore(el, referenceNode.nextSibling);
  }

  function fireValidation(){
    if (isRequired){
      validationTriggered = true;

      if (self.pills.length === 0){
        self.$pillContainer.addClass(fieldErrorCss);

        if (showValidationMessage)
          showValidationMessageText();

      } else {
        self.$pillContainer.removeClass(fieldErrorCss);
      }
    }
  }

  function createValidationMessage(){
    var spanMessage = document.createElement('span');
    spanMessage.className = 'shizzlex sz-validation-message ' + validationMessageCss;
    spanMessage.innerText = validationMessageText;
    spanMessage.style.display = 'none';

    var parentEl = document.getElementById('shizzle-container-' + id);
    insertAfter(spanMessage, parentEl);
  }

  function showValidationMessageText(){
    $('.' + validationMessageCss).show();
  }

  function hideValidationMessageText(){
    $('.' + validationMessageCss).hide();
  }

  this.addPill = function(selectedItem){
    self.pills.push(selectedItem);

    var pillElement = document.createElement('li');
    pillElement.setAttribute('data-id', selectedItem.id);
    pillElement.setAttribute('data-text', selectedItem.text);
    pillElement.setAttribute('data-value', selectedItem.value);
    pillElement.setAttribute('data-value-2', selectedItem.value2);
    pillElement.setAttribute('data-value-3', selectedItem.value3);
    pillElement.className = 'sz-pill';
    pillElement.innerHTML = '' + selectedItem.text + '';
    $(pillElement).insertBefore($('#shizzle-container-' + id).find('.sz-search-box').parent());

    $pills = $('#shizzle-container-' + id).find('.sz-pill');

    _.remove(self.items, function(item){
      return item[dataValue] === selectedItem.value;
    });

    if (validationTriggered)
      fireValidation();

    if (isRequired && showValidationMessage)
      hideValidationMessageText();

    populateList(self.items);
  };

  this.clearData = function(){
    self.dataSource = null;
    self.items = null;
    self.pills.length = 0;
    self.filteredItems.length = 0;
    $searchBox.val('');
    $items.empty();
    $items.hide();

    if ($pills)
      $pills.remove();

    if (onItemsCleared)
      onItemsCleared();
  };

  this.populateWithData = function(data) {
    // Set data source
    self.dataSource = _.sortBy(data, ['text']);
    self.items = _.cloneDeep(self.dataSource);

    populateList(self.items);
  };

  this.validateControl = function(){
    fireValidation();
  };
};

//
// Public methods
//

Shizzle.prototype.getSelectedItems = function(){
  return this.pills;
};

Shizzle.prototype.setSelectedItems = function(selectedItems){
  var self = this;
  _.forEach(selectedItems, function(item) {
    self.addPill(item);
  });
};

Shizzle.prototype.clear = function() {
  this.clearData();
};

Shizzle.prototype.populate = function(data) {
  this.populateWithData(data);
};

Shizzle.prototype.isValid = function(){
  if(this.pills.length === 0)
    return false;
  else
    return true;
};

/**
 * @deprecated Since version 1.1.0 Will be deleted in version 1.2.0 Use validate() instead.
 */
Shizzle.prototype.fireValidation = function(){
  console.warn('fireValidation is deprecated since version 1.1.0 . Use validate() instead.');
  this.validateControl();
};

Shizzle.prototype.validate = function(){
  this.validateControl();
};

module.exports = Shizzle;<|endoftext|>


<commit_before>#!/usr/bin/env node
var fs = require('fs');
var url = require('url');
var path = require('path');
var http = require('http');
var prompt = require('prompt');
var request = require('request');
var httpProxy = require('http-proxy');
var portfinder = require('portfinder');

var home = process.env.HOME;
var confpath = path.join(home, '.godzilla', 'gozila.json');
var npmrc = path.join(home, '.npmrc');

var VERSION = 201407091825;

// hold npmrc
var oldrc = '';
if (fs.existsSync(npmrc)) {
    oldrc = fs.readFileSync(npmrc, 'utf8');
}

// trap `CTRL-C`
require('shutdown-handler').on('exit', function() {
    fs.writeFileSync(npmrc, oldrc, 'utf8');
});

// load local config
try {
    var config = JSON.parse(fs.readFileSync(confpath, 'utf8'));
} catch(err) {
    console.log(err);
    return;
}

// read credentials
readCredentials(fire);

// fire in the hole
function fire(err, credentials) {
    if (err) {
        console.log(err);
        return;
    }

    var s = credentials.username + ':' + credentials.password;
    config.user = credentials.username;
    config.auth = new Buffer(s).toString('base64');
    request.get(config['gozila-url'], prepare)
           .auth(credentials.username, credentials.password);
}

function prepare(err, resp, body) {
    if (err) {
        console.log(err);
        return;
    }

    var _config = JSON.parse(body);

    if (_config.error) {
        console.log(body);
        return;
    }

    // update config
    for (var key in _config) {
        config[key] = _config[key];
    }

    // update or start
    if (config.update && config.version){
        if (parseInt(config.version) > VERSION) {
            updateSelf();
        } else {
            start();
        }
    } else {
        start();
    }
};

function start() {
    portfinder.getPort(function (err, port) {
        if (err) {
            console.log(err);
            return;
        }
        useProxyNpmrc(port);
        startProxy(port);
    });
}

function useProxyNpmrc(port) {
    var content = '_auth=' + config.auth;
    content += '\nalways-auth=true';
    content += '\nunsafe-perm=true';
    content += '\nregistry=http://127.0.0.1:' + port + '/';
    content += '\nemail=' + config.user + '@' + config.host;
    content += '\nloglevel=http';
    fs.writeFileSync(npmrc, content, 'utf8');
}

function startProxy(port) {
    console.log(gozila + '\n');
    console.log("Proxy running on port:", port);
    console.log("Tip: use [Ctrl-C] to exit.");
    http.createServer(proxyHandler).listen(port);
}

function updateSelf() {
    //TODO
    console.log("TODO:update gozila");
}

function proxyHandler(req, res) {
    var proxy = httpProxy.createProxyServer({});
    var p = url.parse(req.url).path.split('/')[1];
    var isPublic = config['private-packages'].indexOf(p) === -1;
    var notSearch = p !== '-';

    console.log("\nrequesting:", req.url, "for", p);

    if (isPublic && notSearch) {//public
        var registry = selectRegistry(config['public-registry']);
        var urlpart = url.parse(registry);
        req.headers.host = url.parse(registry).hostname;
        if (urlpart.port) {
            req.headers.host += ':' + urlpart.port;
        }
    } else {// private
        var registry = selectRegistry(config['private-registry']);
        req.headers.host = config['registry-host'];
    }

    console.log('use registry:', registry);

    proxy.web(req, res, { target: registry });
}

function selectRegistry(array) {
    // select a registry randomly
    var i = Math.floor(Math.random() * array.length);
    return array[i];
}

function readCredentials(cb) {
    var schema = {
        properties: {
            username: { required: true },
            password: {
                required: true,
                hidden: true
            }
        }
    };

    prompt.start();
    prompt.get(schema, cb);
}

var gozila = function() {
    return new String(function() {
/*
                               /(  /(
                              /  \/  \
                       /(/(  /    \___\
                      /  \.-~         ~-._
                /^\.-~   __            /^~~~^\
           /\.-~       /~  ~\         (o\   /o)
      /\.-~            |    |         |.     .|
 /\.-~  __             |    |         |\'. .'/|
~    .-~  ~-.          |    |         |\\___//|
    :        \         (    |    _.-~`\ \) )/ /
    \         \         \   \_.-~      \_( (_/
    '\         \        .\   \___        )/\)
      \         \   _.-~  \_  _ _\
       \         \-~        `\\\\\\
        \        /           )/)/)/
    ___.~)      /
  _-    /      /
_-/    -\     /
  \    ( \   /
   \   | /   \_
    \__||     ~-.___
     \/ /__________/>
*/
    }).substring(17,788);
}();
<commit_msg>use pattern match to detect private package.<commit_after>#!/usr/bin/env node
var _ = require('underscore');
var fs = require('fs');
var url = require('url');
var path = require('path');
var http = require('http');
var prompt = require('prompt');
var request = require('request');
var httpProxy = require('http-proxy');
var portfinder = require('portfinder');

var home = process.env.HOME;
var confpath = path.join(home, '.godzilla', 'gozila.json');
var npmrc = path.join(home, '.npmrc');

var VERSION = 201407091825;

// init proxy handler
var proxy = httpProxy.createProxyServer({});
/*proxy.on('proxyReq', function(proxyReq, req, res, options) { });
proxy.on('proxyRes', function (res) { });
*/

// hold npmrc
var oldrc = '';
if (fs.existsSync(npmrc)) {
    oldrc = fs.readFileSync(npmrc, 'utf8');
}

// trap `CTRL-C`
require('shutdown-handler').on('exit', function() {
    fs.writeFileSync(npmrc, oldrc, 'utf8');
});

// load local config
try {
    var config = JSON.parse(fs.readFileSync(confpath, 'utf8'));
} catch(err) {
    console.log(err);
    return;
}

// read credentials
readCredentials(fire);

// fire in the hole
function fire(err, credentials) {
    if (err) {
        console.log(err);
        return;
    }

    var s = credentials.username + ':' + credentials.password;
    config.user = credentials.username;
    config.auth = new Buffer(s).toString('base64');
    request.get(config['gozila-url'], prepare)
           .auth(credentials.username, credentials.password);
}

function prepare(err, resp, body) {
    if (err) {
        console.log(err);
        return;
    }

    var _config = JSON.parse(body);

    if (_config.error) {
        console.log(body);
        return;
    }

    // update config
    for (var key in _config) {
        config[key] = _config[key];
    }

    // update or start
    if (config.update && config.version){
        if (parseInt(config.version) > VERSION) {
            updateSelf();
        } else {
            start();
        }
    } else {
        start();
    }
};

function start() {
    portfinder.getPort(function (err, port) {
        if (err) {
            console.log(err);
            return;
        }
        useProxyNpmrc(port);
        startProxy(port);
    });
}

function useProxyNpmrc(port) {
    var content = '_auth=' + config.auth;
    content += '\nalways-auth=true';
    content += '\nunsafe-perm=true';
    content += '\nregistry=http://127.0.0.1:' + port + '/';
    content += '\nemail=' + config.user + '@' + config.host;
    content += '\nloglevel=http';
    fs.writeFileSync(npmrc, content, 'utf8');
}

function startProxy(port) {
    console.log(gozila + '\n');
    console.log("Proxy running on port:", port);
    console.log("Tip: use [Ctrl-C] to exit.");
    http.createServer(proxyHandler).listen(port);
}

function updateSelf() {
    //TODO
    console.log("TODO:update gozila");
}

function proxyHandler(req, res) {
    var p = url.parse(req.url).path.split('/')[1];
    var notSearch = p !== '-';
    var isPrivate = _.some(config['private-packages'], function(s){
        return (new RegExp("^"+s)).test(p);
    });

    console.log("\nrequesting:", req.url, "for", p);

    if (!isPrivate && notSearch) {//public
        var registry = selectRegistry(config['public-registry']);
        var urlpart = url.parse(registry);
        req.headers.host = url.parse(registry).hostname;
        if (urlpart.port) {
            req.headers.host += ':' + urlpart.port;
        }
    } else {// private
        var registry = selectRegistry(config['private-registry']);
        req.headers.host = config['registry-host'];
    }

    console.log('use registry:', registry);

    proxy.web(req, res, { target: registry });
}

function selectRegistry(array) {
    // select a registry randomly
    var i = Math.floor(Math.random() * array.length);
    return array[i];
}

function readCredentials(cb) {
    var schema = {
        properties: {
            username: { required: true },
            password: {
                required: true,
                hidden: true
            }
        }
    };

    prompt.start();
    prompt.get(schema, cb);
}

var gozila = function() {
    return new String(function() {
/*
                               /(  /(
                              /  \/  \
                       /(/(  /    \___\
                      /  \.-~         ~-._
                /^\.-~   __            /^~~~^\
           /\.-~       /~  ~\         (o\   /o)
      /\.-~            |    |         |.     .|
 /\.-~  __             |    |         |\'. .'/|
~    .-~  ~-.          |    |         |\\___//|
    :        \         (    |    _.-~`\ \) )/ /
    \         \         \   \_.-~      \_( (_/
    '\         \        .\   \___        )/\)
      \         \   _.-~  \_  _ _\
       \         \-~        `\\\\\\
        \        /           )/)/)/
    ___.~)      /
  _-    /      /
_-/    -\     /
  \    ( \   /
   \   | /   \_
    \__||     ~-.___
     \/ /__________/>
*/
    }).substring(17,788);
}();
<|endoftext|>


<commit_before>'use strict';

const p = require('path');
const revHash = require('rev-hash');
const sortKeys = require('sort-keys');

const IGNORE = ['.png', 'jpg', '.jpeg', '.svg', '.gif', '.woff', '.ttf', '.eot'];
let MANIFEST;
let FILEPATH;

module.exports = function (fly) {
	/**
	 * Create new hashed file names based on contents
	 */
	fly.plugin('rev', {}, function * (file, opts) {
		// overwrite default opt values
		opts = Object.assign({}, {ignores: IGNORE}, opts);

		// bypass dirs or empty files
		if (!file.data) {
			return;
		}

		const ext = p.extname(file.base);
		// if this file's extension matches `ignores`, exit early
		if (!ext || opts.ignores.indexOf(ext) !== -1) {
			return;
		}

		file.orig = file.base;
		file.hash = revHash(file.data);

		// find first occurence of '.', NOT including first char
		const idx = file.base.indexOf('.', 1);

		// change filename; append hash to base name
		file.base = file.base.substr(0, idx).concat('-', file.hash, file.base.substr(idx));
	});

	/**
	 * Write the manifest file
	 */
	fly.plugin('revManifest', {every: 0}, function * (files, opts) {
		MANIFEST = {}; // reset

		opts = Object.assign({
			sort: true,
			dest: this.root, // place file
			trim: '', // path to trim
			file: 'rev-manifest.json'
		}, opts);

		// update known values
		FILEPATH = p.resolve(opts.dest, opts.file);

		// content to replace
		if (!opts.trim || typeof opts.trim === 'string') {
			const t = opts.trim;
			// create `replace` function
			opts.trim = str => str.replace(new RegExp(t, 'i'), '/');
		}

		for (const f of files) {
			// only if was revv'd
			if (!f.orig) continue;
			// strip a string from the `file.dir` path
			let dir = p.relative(this.root, f.dir);
			// apply `opts.trim` func
			dir = p.normalize(opts.trim(dir));
			// ensure no leading '/'
			dir = dir.charAt(0) === '/' ? dir.substr(1) : dir;
			// add pairing to manifest
			MANIFEST[p.join(dir, f.orig)] = p.join(dir, f.base);
		}

		// alphabetically sort
		if (opts.sort) {
			MANIFEST = sortKeys(MANIFEST);
		}

		// write the file
		yield this.$.write(FILEPATH, JSON.stringify(MANIFEST, false, '	'));
	});

	/**
	 * Read all files within a `dir` & Update to latest filenames
	 */
	fly.plugin('revReplace', {every: 0}, function * (files, opts) {
		opts = Object.assign({ignores: IGNORE}, opts);

		// get original manifest paths; escape safe characters
		const keys = Object.keys(MANIFEST).map(k => k.replace(/([[^$.|?*+(){}\\])/g, '\\$1')).join('|');
		const rgx = new RegExp(keys, 'gi');

		for (let f of files) {
			const ext = p.extname(f.base);
			// only if not in `ignores`
			if (!ext || opts.ignores.indexOf(ext) !== -1) continue;
			// replace orig with rev'd && write it
			const d = f.data.toString().replace(rgx, k => MANIFEST[k]);
			f.data = new Buffer(d);
		}
	});
};
<commit_msg>simplify assigns<commit_after>'use strict';

const p = require('path');
const revHash = require('rev-hash');
const sortKeys = require('sort-keys');

const IGNORE = ['.png', 'jpg', '.jpeg', '.svg', '.gif', '.woff', '.ttf', '.eot'];
let MANIFEST;
let FILEPATH;

module.exports = function (fly) {
	/**
	 * Create new hashed file names based on contents
	 */
	fly.plugin('rev', {}, function * (file, opts) {
		// overwrite default opt values
		opts = Object.assign({ignores: IGNORE}, opts);

		// bypass dirs or empty files
		if (!file.data) {
			return;
		}

		const ext = p.extname(file.base);
		// if this file's extension matches `ignores`, exit early
		if (!ext || opts.ignores.indexOf(ext) !== -1) {
			return;
		}

		file.orig = file.base;
		file.hash = revHash(file.data);

		// find first occurence of '.', NOT including first char
		const idx = file.base.indexOf('.', 1);

		// change filename; append hash to base name
		file.base = file.base.substr(0, idx).concat('-', file.hash, file.base.substr(idx));
	});

	/**
	 * Write the manifest file
	 */
	fly.plugin('revManifest', {every: 0}, function * (files, opts) {
		MANIFEST = {}; // reset

		opts = Object.assign({
			sort: true,
			dest: this.root, // place file
			trim: '', // path to trim
			file: 'rev-manifest.json'
		}, opts);

		// update known values
		FILEPATH = p.resolve(opts.dest, opts.file);

		// content to replace
		if (!opts.trim || typeof opts.trim === 'string') {
			const t = opts.trim;
			// create `replace` function
			opts.trim = str => str.replace(new RegExp(t, 'i'), '/');
		}

		for (const f of files) {
			// only if was revv'd
			if (!f.orig) continue;
			// strip a string from the `file.dir` path
			let dir = p.relative(this.root, f.dir);
			// apply `opts.trim` func
			dir = p.normalize(opts.trim(dir));
			// ensure no leading '/'
			dir = dir.charAt(0) === '/' ? dir.substr(1) : dir;
			// add pairing to manifest
			MANIFEST[p.join(dir, f.orig)] = p.join(dir, f.base);
		}

		// alphabetically sort
		if (opts.sort) {
			MANIFEST = sortKeys(MANIFEST);
		}

		// write the file
		yield this.$.write(FILEPATH, JSON.stringify(MANIFEST, false, '	'));
	});

	/**
	 * Read all files within a `dir` & Update to latest filenames
	 */
	fly.plugin('revReplace', {every: 0}, function * (files, opts) {
		opts = Object.assign({ignores: IGNORE}, opts);

		// get original manifest paths; escape safe characters
		const keys = Object.keys(MANIFEST).map(k => k.replace(/([[^$.|?*+(){}\\])/g, '\\$1')).join('|');
		const rgx = new RegExp(keys, 'gi');

		for (let f of files) {
			const ext = p.extname(f.base);
			// only if not in `ignores`
			if (!ext || opts.ignores.indexOf(ext) !== -1) continue;
			// replace orig with rev'd && write it
			const d = f.data.toString().replace(rgx, k => MANIFEST[k]);
			f.data = new Buffer(d);
		}
	});
};
<|endoftext|>


<commit_before>'use-strict'

const Web3 = require('web3'),
      Tx = require('ethereumjs-tx'),
      ut = require('ethereumjs-util')

const token_abi = require('./contracts/Token.abi'),
      registry_abi = require('./contracts/Registry.abi'),
      delivery_service_abi = require('./contracts/DeliveryService.abi')

const token_address = require('./contracts/Token.address'),
      registry_address = require('./contracts/Registry.address'),
      delivery_service_address = require('./contracts/DeliveryService.address')

module.exports = function(provider) {

  var tasks = {}
  var task_timer = setInterval(function() {
    var tx_hashes = Object.keys(tasks)
    for (var i = tx_hashes.length - 1; i >= 0; i--) {
      tasks[tx_hashes[i]].task()
    }
  }, 5 * 1000)

  const web3 = typeof provider === 'string' ? new Web3(new Web3.providers.HttpProvider(provider)) : provider

  const tokenInterface = web3.eth.contract(token_abi),
        registryInterface = web3.eth.contract(registry_abi),
        deliveryServiceInterface = web3.eth.contract(delivery_service_abi)

  const Token = tokenInterface.at(token_address),
        Registry = registryInterface.at(registry_address),
        DeliveryService = deliveryServiceInterface.at(delivery_service_address)

  function new_task(hash, callback) {
    tasks[hash] = {
      ttl: 100,
      callback: callback
    }
    tasks[hash].task = function(tx) {
      web3.eth.getTransactionReceipt(tx, function(err, receipt) {
        var removeflag = false
        if (err || this.ttl < 0) {
          removeflag = true
          this.callback(err || new Error('ran out of retries waiting for tx confirmation'))
        }
        if (!removeflag &&
            receipt &&
            ((web3.eth.blockNumber - receipt.blockNumber) > 0) &&
            Array.isArray(receipt.logs) &&
            receipt.logs.length
        ) {
          removeflag = true
          this.callback(null, `0x${receipt.logs[0].data.slice(26)}`)
        }
        if (removeflag) delete tasks[tx]
        else this.ttl -= 1
      }.bind(this))
    }.bind(tasks[hash], hash)
  }

  return {

    record: function(vchash, date, centreDID, attendees, claimedTokens, senderPrivateKey, callback) {

      const calldata = Registry.record.getData(vchash, date, centreDID, attendees, claimedTokens)

      const signer_buf = Buffer.from(senderPrivateKey, 'hex'),
          signer_addr = `0x${ut.privateToAddress(signer_buf).toString('hex')}`

      web3.eth.getTransactionCount(signer_addr, (err, nonce) => {

        if (err)
          return callback(err)

        const transaction = new Tx({
          to: registry_address,
          gasLimit: 3000000,
          gasPrice: +web3.toWei(20, 'gwei'),
          nonce: nonce,
          data: calldata,
        })

        transaction.sign(signer_buf)

        const raw = `0x${transaction.serialize().toString('hex')}`

        return web3.eth.sendRawTransaction(raw, function(error, txhash) {
          if (error)
            return callback(error)

          return new_task(txhash, callback)
        })
      })
    },

    execute: function(to, value, vchash, senderPrivateKey, callback) {
      const calldata = DeliveryService.execute.getData(to, value, vchash)

      const signer_buf = Buffer.from(senderPrivateKey, 'hex'),
            signer_addr = `0x${ut.privateToAddress(signer_buf).toString('hex')}`

      web3.eth.getTransactionCount(signer_addr, (err, nonce) => {

        if (err)
          return callback(err)

        const transaction = new Tx({
          to: delivery_service_address,
          gasLimit: 4000000,
          gasPrice: +web3.toWei(20, 'gwei'),
          nonce: nonce,
          data: calldata,
        })

        transaction.sign(signer_buf)

        const raw = `0x${transaction.serialize().toString('hex')}`

        return web3.eth.sendRawTransaction(raw, function(error, txhash) {
          if (error)
            return callback(error)

          return new_task(txhash, callback)
        })
      })
    },

    confirm: function(vchash, senderPrivateKey, callback) {
      const calldata = DeliveryService.confirm.getData(vchash)

      const signer_buf = Buffer.from(senderPrivateKey, 'hex'),
            signer_addr = `0x${ut.privateToAddress(signer_buf).toString('hex')}`

      web3.eth.getTransactionCount(signer_addr, (err, nonce) => {

        if (err)
          return callback(err)

        const transaction = new Tx({
          to: delivery_service_address,
          gasLimit: 4000000,
          gasPrice: +web3.toWei(20, 'gwei'),
          nonce: nonce,
          data: calldata,
        })

        transaction.sign(signer_buf)

        const raw = `0x${transaction.serialize().toString('hex')}`

        return web3.eth.sendRawTransaction(raw, function(error, txhash) {
          if (error)
            return callback(error)

          return new_task(txhash, callback)
        })
      })
    }

  }
}

<commit_msg>Allow to return without waiting for confirmations<commit_after>'use-strict'

const Web3 = require('web3'),
      Tx = require('ethereumjs-tx'),
      ut = require('ethereumjs-util')

const token_abi = require('./contracts/Token.abi'),
      registry_abi = require('./contracts/Registry.abi'),
      delivery_service_abi = require('./contracts/DeliveryService.abi')

const token_address = require('./contracts/Token.address'),
      registry_address = require('./contracts/Registry.address'),
      delivery_service_address = require('./contracts/DeliveryService.address')

module.exports = function(provider, verbose) {

  var tasks = {}
  var task_timer = setInterval(function() {
    var tx_hashes = Object.keys(tasks)
    for (var i = tx_hashes.length - 1; i >= 0; i--) {
      tasks[tx_hashes[i]].task()
    }
  }, 5 * 1000)

  const web3 = typeof provider === 'string' ? new Web3(new Web3.providers.HttpProvider(provider)) : provider

  const tokenInterface = web3.eth.contract(token_abi),
        registryInterface = web3.eth.contract(registry_abi),
        deliveryServiceInterface = web3.eth.contract(delivery_service_abi)

  const Token = tokenInterface.at(token_address),
        Registry = registryInterface.at(registry_address),
        DeliveryService = deliveryServiceInterface.at(delivery_service_address)

  function new_task(hash, callback) {
    tasks[hash] = {
      ttl: 100,
      callback: callback
    }
    tasks[hash].task = function(tx) {
      web3.eth.getTransactionReceipt(tx, function(err, receipt) {
        var removeflag = false
        if (err || this.ttl < 0) {
          removeflag = true
          this.callback(err || new Error('ran out of retries waiting for tx confirmation'))
        }
        if (!removeflag &&
            receipt &&
            ((web3.eth.blockNumber - receipt.blockNumber) > 0) &&
            Array.isArray(receipt.logs) &&
            receipt.logs.length
        ) {
          removeflag = true
          this.callback(null, `0x${receipt.logs[0].data.slice(26)}`)
        }
        if (removeflag) delete tasks[tx]
        else this.ttl -= 1
      }.bind(this))
    }.bind(tasks[hash], hash)
  }

  return {

    record: function(vchash, date, centreDID, attendees, claimedTokens, senderPrivateKey, callback) {

      const calldata = Registry.record.getData(vchash, date, centreDID, attendees, claimedTokens)

      const signer_buf = Buffer.from(senderPrivateKey, 'hex'),
          signer_addr = `0x${ut.privateToAddress(signer_buf).toString('hex')}`

      web3.eth.getTransactionCount(signer_addr, (err, nonce) => {

        if (err)
          return callback(err)

        const transaction = new Tx({
          to: registry_address,
          gasLimit: 3000000,
          gasPrice: +web3.toWei(20, 'gwei'),
          nonce: nonce,
          data: calldata,
        })

        transaction.sign(signer_buf)

        const raw = `0x${transaction.serialize().toString('hex')}`

        return web3.eth.sendRawTransaction(raw, function(error, txhash) {
          if (error)
            return callback(error)

          return verbose ? new_task(txhash, callback) : callback(error, txhash)
        })
      })
    },

    execute: function(to, value, vchash, senderPrivateKey, callback) {
      const calldata = DeliveryService.execute.getData(to, value, vchash)

      const signer_buf = Buffer.from(senderPrivateKey, 'hex'),
            signer_addr = `0x${ut.privateToAddress(signer_buf).toString('hex')}`

      web3.eth.getTransactionCount(signer_addr, (err, nonce) => {

        if (err)
          return callback(err)

        const transaction = new Tx({
          to: delivery_service_address,
          gasLimit: 4000000,
          gasPrice: +web3.toWei(20, 'gwei'),
          nonce: nonce,
          data: calldata,
        })

        transaction.sign(signer_buf)

        const raw = `0x${transaction.serialize().toString('hex')}`

        return web3.eth.sendRawTransaction(raw, function(error, txhash) {
          if (error)
            return callback(error)

          return verbose ? new_task(txhash, callback) : callback(error, txhash)
        })
      })
    },

    confirm: function(vchash, senderPrivateKey, callback) {
      const calldata = DeliveryService.confirm.getData(vchash)

      const signer_buf = Buffer.from(senderPrivateKey, 'hex'),
            signer_addr = `0x${ut.privateToAddress(signer_buf).toString('hex')}`

      web3.eth.getTransactionCount(signer_addr, (err, nonce) => {

        if (err)
          return callback(err)

        const transaction = new Tx({
          to: delivery_service_address,
          gasLimit: 4000000,
          gasPrice: +web3.toWei(20, 'gwei'),
          nonce: nonce,
          data: calldata,
        })

        transaction.sign(signer_buf)

        const raw = `0x${transaction.serialize().toString('hex')}`

        return web3.eth.sendRawTransaction(raw, function(error, txhash) {
          if (error)
            return callback(error)

          return verbose ? new_task(txhash, callback) : callback(error, txhash)
        })
      })
    }

  }
}

<|endoftext|>


<commit_before>/*!
 * koa-upload <https://github.com/tunnckoCore/koa-upload>
 *
 * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
 * Released under the MIT license.
 */

'use strict'

module.exports = function koaUpload () {
  // body
}
<commit_msg>return generator fn<commit_after>/*!
 * koa-upload <https://github.com/tunnckoCore/koa-upload>
 *
 * Copyright (c) 2015 Charlike Mike Reagent <@tunnckoCore> (http://www.tunnckocore.tk)
 * Released under the MIT license.
 */

'use strict'

module.exports = function koaUpload () {
  return function * () {

  }
}
<|endoftext|>


<commit_before>var fs = require('fs'),
    util = require('util'),
    path = require('path');

var preTest = require('./pre/pre_tests'),
    postTest = require('./post/post_tests');

var async = require('async'),
    cheerio = require('cheerio'),
    jsdom = require('jsdom'),
    wrench = require('wrench'),
    colors = require('colors');

var srcDir, srcFiles, outFiles, ext, stopOnFail, options;

var readFiles = {};

exports.runTests = function(src, opts, callback) {
  options = opts;
  stopOnFail = options.stopOnFail || false;
  ext = options.ext || ".html";
  srcDir = src;

  console.log("Running tests on " + srcDir);

  loadFiles(srcDir, function(err, srcFiles) {
    if (err) {
      console.error(err);
      process.exit(1);
    }

    async.forEach(srcFiles, runIndividualTest, function (err) {
        console.log("Finished running tests on " + srcDir);
        return callback(err);
    });
  });
};

function runIndividualTest(fileName, callback) {
  var file = srcDir + "/" + fileName;
  if (file.match(new RegExp(ext + "$"))) {
    fs.readFile(file, 'utf8', function(err, content) {
        if (err) {
            if (!fs.lstatSync(file).isDirectory()) {
              console.error("Error starting to read file " + file);
              console.error(err);
              process.exit(1);
            }
          }

        $ = cheerio.load(content);

        readFiles[file] = $;

        async.parallel([
            function(cb) {
              preTest.checkMissingAltTag(file, $, options, function(errors) {
                checkForErrors(errors, stopOnFail, cb);
              });
            },
            function(cb) {
              preTest.checkBrokenExternalLink(file, $, options, function(errors) {
                checkForErrors(errors, stopOnFail, cb);
              });
            },
            function(cb) {
              postTest.checkMissingImage(file, $, options, function(errors) {
                checkForErrors(errors, stopOnFail, cb);
              });
            },
            function(cb) {
              postTest.checkBrokenLocalLink(file, $, readFiles, options, function(errors) {
                checkForErrors(errors, stopOnFail, cb);
              });
            }
          ], function(err, results) {
              callback(err);
        });
    });
  }
  else {
    callback(null);
  }
}

function checkForErrors(errors, stopOnFail, cb) {
  while (errors.length) {
    console.error(errors[errors.length - 1].red);
    errors.pop();
    if (stopOnFail) {
      console.error("Halting due to failures".magenta);
      process.exit(1);
    }
  }

  cb(null);
}

function loadFiles(dirs, callback) {
  async.forEach(dirs, function(dir, cb) {
    var listOfFiles = wrench.readdirSyncRecursive(dir);
    callback(null, listOfFiles);
  });
}<commit_msg>Remove bad ref<commit_after>var fs = require('fs'),
    util = require('util'),
    path = require('path');

var preTest = require('./pre/pre_tests'),
    postTest = require('./post/post_tests');

var async = require('async'),
    cheerio = require('cheerio'),
    wrench = require('wrench'),
    colors = require('colors');

var srcDir, srcFiles, outFiles, ext, stopOnFail, options;

var readFiles = {};

exports.runTests = function(src, opts, callback) {
  options = opts;
  stopOnFail = options.stopOnFail || false;
  ext = options.ext || ".html";
  srcDir = src;

  console.log("Running tests on " + srcDir);

  loadFiles(srcDir, function(err, srcFiles) {
    if (err) {
      console.error(err);
      process.exit(1);
    }

    async.forEach(srcFiles, runIndividualTest, function (err) {
        console.log("Finished running tests on " + srcDir);
        return callback(err);
    });
  });
};

function runIndividualTest(fileName, callback) {
  var file = srcDir + "/" + fileName;
  if (file.match(new RegExp(ext + "$"))) {
    fs.readFile(file, 'utf8', function(err, content) {
        if (err) {
            if (!fs.lstatSync(file).isDirectory()) {
              console.error("Error starting to read file " + file);
              console.error(err);
              process.exit(1);
            }
          }

        $ = cheerio.load(content);

        readFiles[file] = $;

        async.parallel([
            function(cb) {
              preTest.checkMissingAltTag(file, $, options, function(errors) {
                checkForErrors(errors, stopOnFail, cb);
              });
            },
            function(cb) {
              preTest.checkBrokenExternalLink(file, $, options, function(errors) {
                checkForErrors(errors, stopOnFail, cb);
              });
            },
            function(cb) {
              postTest.checkMissingImage(file, $, options, function(errors) {
                checkForErrors(errors, stopOnFail, cb);
              });
            },
            function(cb) {
              postTest.checkBrokenLocalLink(file, $, readFiles, options, function(errors) {
                checkForErrors(errors, stopOnFail, cb);
              });
            }
          ], function(err, results) {
              callback(err);
        });
    });
  }
  else {
    callback(null);
  }
}

function checkForErrors(errors, stopOnFail, cb) {
  while (errors.length) {
    console.error(errors[errors.length - 1].red);
    errors.pop();
    if (stopOnFail) {
      console.error("Halting due to failures".magenta);
      process.exit(1);
    }
  }

  cb(null);
}

function loadFiles(dirs, callback) {
  async.forEach(dirs, function(dir, cb) {
    var listOfFiles = wrench.readdirSyncRecursive(dir);
    callback(null, listOfFiles);
  });
}<|endoftext|>


<commit_before>module.exports = inherits

function inherits (ctor, superCtor) {
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: true,
      writable: true,
      configurable: true
    }
  })
}
<commit_msg>constructor should not be enumerable<commit_after>module.exports = inherits

function inherits (ctor, superCtor) {
  ctor.prototype = Object.create(superCtor.prototype, {
    constructor: {
      value: ctor,
      enumerable: false,
      writable: true,
      configurable: true
    }
  })
}
<|endoftext|>


<commit_before>'use latest';

import P from 'bluebird';
import request from 'superagent-bluebird-promise';
import twilio from 'twilio';

const { TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_PHONE_NUMBER, MY_PHONE_NUMBER, URL } = ctx.data;

const twilioClient = new twilio.RestClient(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);
const createMessage = P.promisify(twilioClient.sms.messages.create, twilioClient);

export default function(ctx, cb) {

  if (!TWILIO_ACCOUNT_SID || !TWILIO_AUTH_TOKEN || !TWILIO_PHONE_NUMBER || !MY_PHONE_NUMBER) {
    return cb(new Error('Key missing'));
  }

  request.get(URL)
    .catch(() => {
      sendText(MY_PHONE_NUMBER, 'Site down!');
    }).finally(() => {
      cb();
    });

}
<commit_msg>redo twilio interaction, don't need promisified version here<commit_after>'use latest';

import P from 'bluebird';
import request from 'superagent-bluebird-promise';
import twilio from 'twilio';

const { TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_PHONE_NUMBER, MY_PHONE_NUMBER, URL } = ctx.data;

export default function(ctx, cb) {
  if (!TWILIO_ACCOUNT_SID || !TWILIO_AUTH_TOKEN || !TWILIO_PHONE_NUMBER || !MY_PHONE_NUMBER) {
    return cb(new Error('Key missing'));
  }

  request.get(URL)
    .catch(() => {
      notifyUser(MY_PHONE_NUMBER);
    }).finally(() => {
      cb();
    });
}

function sendText(phone) {
  return twilio.sms.messages.post({
    to: phone,
    from: TWILIO_PHONE_NUMBER,
    body: 'Site down!'
  });
}
<|endoftext|>


<commit_before>'use strict';
var chalk = require('chalk');

var main = {
	info: chalk.blue('ℹ'),
	success: chalk.green('✔'),
	warning: chalk.yellow('⚠'),
	error: chalk.red('✖')
};

var win = {
	info: chalk.blue('i'),
	success: chalk.green('√'),
	warning: chalk.yellow('‼'),
	error: chalk.red('×')
};

module.exports = process.platform === 'win32' ? win : main;
<commit_msg>Set alternate propery with otherOS symbol set.<commit_after>'use strict';
var chalk = require('chalk');

var main = {
	info: chalk.blue('ℹ'),
	success: chalk.green('✔'),
	warning: chalk.yellow('⚠'),
	error: chalk.red('✖')
};

var win = {
	info: chalk.blue('i'),
	success: chalk.green('√'),
	warning: chalk.yellow('‼'),
	error: chalk.red('×')
};

module.exports = process.platform === 'win32' ? win : main;
module.exports.alternate =
	process.platform === 'win32' ? main : win;
<|endoftext|>


<commit_before>//  Firefox Extension Packer
//  Copyright 2015 AVAST Software s.r.o.
//  http://www.avast.com
//
//  Wrapper around Firefox Add-on SDK

(function () {
    'use strict';

    var when = require('when');
    var path = require('path');
    var fs = require('fs');

    // pack Firefox extension
    //
    // @param xpiName name of the pcaked extension
    // @param addonDir source directory
    // @return promise
    //
    function pack(xpiName, addonDir, options) {
        try {
            var webExtManifest = path.join(addonDir, 'manifest.json');
            fs.accessSync(webExtManifest);
            try {
                return packWebExt(xpiName, addonDir, options);
            }
            catch (ex) {
                return Promise.reject(ex);
            }
        }
        catch (ex) {
            return packAddon(path.resolve(xpiName), path.resolve(addonDir));
        }
    }

    function packAddon(xpiName, addonDir) {
        var xpi = require('jpm/lib/xpi');
        var manifest = require(path.join(addonDir, 'package.json'));
        console.log("xpi ", addonDir, " ", path.dirname(xpiName), " ", path.basename(xpiName));
        return xpi(manifest, { addonDir: addonDir, xpiPath: path.dirname(xpiName), xpiName: path.basename(xpiName) })  // , verbose: true
            .then(function (fullPath) {
                fs.renameSync(fullPath, xpiName);
                return 0;
            });
    }

    function packWebExt(zipName, addonDir, options) {
        var myArgv = process.argv.slice();
        var webExtModulePath = path.resolve(require.resolve('web-ext/dist/web-ext.js'), '../..');
        var intermediateDir = options && options.tmpDir ? path.resolve(options.tmpDir, 'web-ext-artifacts') : path.resolve(path.dirname(zipName), 'web-ext-artifacts');

        process.argv = [ process.argv[0], path.resolve(webExtModulePath, 'bin/web-ext'), 'build', '--overwrite-dest', '--artifacts-dir=' +  intermediateDir];

        var rm = require('del').sync;
        rm(intermediateDir, {force: true});

        var wd = process.cwd();
        process.chdir(addonDir);

        var webExt = require('web-ext/dist/web-ext.js').main;
        return webExt(webExtModulePath)
            .then(function () {
                process.chdir(wd);
                var result = fs.readdirSync(intermediateDir)[0];
                fs.renameSync(path.resolve(intermediateDir, result), zipName);
                rm(intermediateDir, {force: true});
                console.log("WebExtension at " + zipName);
                return 0;
            })
            .catch(function (ex) {
                console.log(ex);
                process.chdir(wd);
                return 1;
            });
    }

    module.exports = pack;

})();
<commit_msg>do not change active directory during build<commit_after>//  Firefox Extension Packer
//  Copyright 2015 AVAST Software s.r.o.
//  http://www.avast.com
//
//  Wrapper around Firefox Add-on SDK

(function () {
    'use strict';

    var when = require('when');
    var path = require('path');
    var fs = require('fs');

    // pack Firefox extension
    //
    // @param xpiName name of the pcaked extension
    // @param addonDir source directory
    // @return promise
    //
    function pack(xpiName, addonDir, options) {
        try {
            var webExtManifest = path.join(addonDir, 'manifest.json');
            fs.accessSync(webExtManifest);
            try {
                return packWebExt(xpiName, addonDir, options);
            }
            catch (ex) {
                return Promise.reject(ex);
            }
        }
        catch (ex) {
            return packAddon(path.resolve(xpiName), path.resolve(addonDir));
        }
    }

    function packAddon(xpiName, addonDir) {
        var xpi = require('jpm/lib/xpi');
        var manifest = require(path.join(addonDir, 'package.json'));
        console.log("xpi ", addonDir, " ", path.dirname(xpiName), " ", path.basename(xpiName));
        return xpi(manifest, { addonDir: addonDir, xpiPath: path.dirname(xpiName), xpiName: path.basename(xpiName) })  // , verbose: true
            .then(function (fullPath) {
                fs.renameSync(fullPath, xpiName);
                return 0;
            });
    }

    function packWebExt(zipName, addonDir, options) {
        var myArgv = process.argv.slice();
        var webExtModulePath = path.resolve(require.resolve('web-ext/dist/web-ext.js'), '../..');
        var intermediateDir = options && options.tmpDir ? path.resolve(options.tmpDir, 'web-ext-artifacts') : path.resolve(path.dirname(zipName), 'web-ext-artifacts');

        process.argv = [ process.argv[0], path.resolve(webExtModulePath, 'bin/web-ext'), 'build', '--overwrite-dest', '--artifacts-dir=' +  intermediateDir, "--source-dir=" + addonDir];

        var rm = require('del').sync;
        rm(intermediateDir, {force: true});

        var webExt = require('web-ext/dist/web-ext.js').main;
        return webExt(webExtModulePath)
            .then(function () {
                var result = fs.readdirSync(intermediateDir)[0];
                fs.renameSync(path.resolve(intermediateDir, result), zipName);
                rm(intermediateDir, {force: true});
                console.log("WebExtension at " + zipName);
                return 0;
            })
            .catch(function (ex) {
                console.log(ex);
                return 1;
            });
    }

    module.exports = pack;

})();
<|endoftext|>


<commit_before>/**
 * Created by Nitai J. Perez
 * nitai.perez@ironsrc.com
 * on 16/07/2016
 */

var later = require('later');
var request = require('request');
var PushBullet = require('pushbullet');
console.log(`Launching process with Pushbullet key: ${process.env.PUSHBULLET_KEY}`)
var pusher = new PushBullet(process.env.PUSHBULLET_KEY);

var STATUS = 'Online';

var timer = later.setInterval(tick, later.parse.recur().every(5).minute());

function tick() {
    console.log(`Checking server status (${(new Date())})`);
    request('https://status.pokemongoserver.com/', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var status = body.indexOf('Online') > -1 ? 'Online' : 'Offline';

            if (STATUS === status) return;
            console.log(` > Status change found: ${STATUS} -> ${status}`);

            pusher.note('ujAwn5dAxi0sjAdP9ajVsq', `PG ${status}`, '', function (error, response) {
                if (!error) {
                    console.log(` > Reported status change: ${status}`);
                    STATUS = status;
                } else {
                    console.warn(` > Failed to reported status change: ${status}`);
                    console.error(error);
                }
            });
        } else {
            console.warn(' > Failed http query');
            console.error(error);
        }
    });
}<commit_msg>Add support for any status<commit_after>/**
 * Created by Nitai J. Perez
 * nitai.perez@ironsrc.com
 * on 16/07/2016
 */

var later = require('later');
var request = require('request');
var PushBullet = require('pushbullet');
console.log(`Launching process with Pushbullet key: ${process.env.PUSHBULLET_KEY}`)
var pusher = new PushBullet(process.env.PUSHBULLET_KEY);

var STATUS = 'Online';

var timer = later.setInterval(tick, later.parse.recur().every(5).minute());

function tick() {
    console.log(`Checking server status (${(new Date())})`);
    request('https://status.pokemongoserver.com/', function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var status = body.indexOf('Online') > -1 ? 'Online' : 'Offline';

            if (STATUS === status) return;
            console.log(` > Status change found: ${STATUS} -> ${status}`);

            pusher.note('ujAwn5dAxi0sjAdP9ajVsq', `PG ${status}`, '', function (error, response) {
                if (!error) {
                    console.log(` > Reported status change: ${status}`);
                    STATUS = status;
                } else {
                    console.warn(` > Failed to reported status change: ${status}`);
                    console.error(error);
                }
            });
        } else {
            console.warn(' > Failed http query');
            console.error(error);
        }
    });
}

function getStatus(body) {
    var find = '<h2>Status:';
    body = body.substring(body.indexOf(find) + find.length);
    body = body.split('>')[1].split('<')[0];
    return body;
}
<|endoftext|>


<commit_before>"use strict";

module.exports = parse;

var re_name = /^(?:\\.|[\w\-\u00c0-\uFFFF])+/,
    re_escape = /\\([\da-f]{1,6}\s?|(\s)|.)/ig,
    //modified version of https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L87
    re_attr = /^\s*((?:\\.|[\w\u00c0-\uFFFF\-])+)\s*(?:(\S?)=\s*(?:(['"])(.*?)\3|(#?(?:\\.|[\w\u00c0-\uFFFF\-])*)|)|)\s*(i)?\]/;

var actionTypes = {
	__proto__: null,
	"undefined": "exists",
	"":  "equals",
	"~": "element",
	"^": "start",
	"$": "end",
	"*": "any",
	"!": "not",
	"|": "hyphen"
};

var simpleSelectors = {
	__proto__: null,
	">": "child",
	"<": "parent",
	"~": "sibling",
	"+": "adjacent"
};

var attribSelectors = {
	__proto__: null,
	"#": ["id", "equals"],
	".": ["class", "element"]
};

//pseudos, whose data-property is parsed as well
var unpackPseudos = {
    __proto__: null,
    "has": true,
    "not": true,
    "matches": true
};

var stripQuotesFromPseudos = {
    __proto__: null,
    "contains": true
};

var quotes = {
    __proto__: null,
    "\"": true,
    "'": true
};

//unescape function taken from https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L139
function funescape( _, escaped, escapedWhitespace ) {
	var high = "0x" + escaped - 0x10000;
	// NaN means non-codepoint
	// Support: Firefox
	// Workaround erroneous numeric interpretation of +"0x"
	return high !== high || escapedWhitespace ?
		escaped :
		// BMP codepoint
		high < 0 ?
			String.fromCharCode( high + 0x10000 ) :
			// Supplemental Plane codepoint (surrogate pair)
			String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
}

function unescapeCSS(str){
	return str.replace(re_escape, funescape);
}

function isWhitespace(c){
    return c === " " || c === "\n" || c === "\t" || c === "\f" || c === "\r";
}

function parse(selector, options){
	var subselects = [];

    selector = parseSelector(subselects, selector + "", options);

    if(selector !== ""){
        throw new SyntaxError("Unmatched selector: " + selector);
    }

    return subselects;
}

function parseSelector(subselects, selector, options){
    var tokens = [],
        sawWS = false,
        data, firstChar, name, quot;

	function getName(){
		var sub = selector.match(re_name)[0];
		selector = selector.substr(sub.length);
		return unescapeCSS(sub);
	}

    function stripWhitespace(start){
        while(isWhitespace(selector.charAt(start))) start++;
        selector = selector.substr(start);
    }

    stripWhitespace(0);

	while(selector !== ""){
        firstChar = selector.charAt(0);

        if(isWhitespace(firstChar)){
			sawWS = true;
            stripWhitespace(1);
		} else if(firstChar in simpleSelectors){
            tokens.push({type: simpleSelectors[firstChar]});
            sawWS = false;

            stripWhitespace(1);
        } else if(firstChar === ","){
            if(tokens.length === 0){
                throw new SyntaxError("empty sub-selector");
            }
            subselects.push(tokens);
            tokens = [];
            sawWS = false;
            stripWhitespace(1);
        } else {
			if(sawWS){
                if(tokens.length > 0){
                    tokens.push({type: "descendant"});
                }
				sawWS = false;
			}

            if(firstChar === "*"){
                selector = selector.substr(1);
				tokens.push({type: "universal"});
			} else if(firstChar in attribSelectors){
                selector = selector.substr(1);
				tokens.push({
					type: "attribute",
					name: attribSelectors[firstChar][0],
					action: attribSelectors[firstChar][1],
					value: getName(),
					ignoreCase: false
				});
			} else if(firstChar === "["){
                selector = selector.substr(1);
				data = selector.match(re_attr);
				if(!data){
					throw new SyntaxError("Malformed attribute selector: " + selector);
				}
				selector = selector.substr(data[0].length);
				name = unescapeCSS(data[1]);

				if(
					!options || (
						"lowerCaseAttributeNames" in options ?
							options.lowerCaseAttributeNames :
							!options.xmlMode
					)
				){
					name = name.toLowerCase();
				}

				tokens.push({
					type: "attribute",
					name: name,
					action: actionTypes[data[2]],
					value: unescapeCSS(data[4] || data[5] || ""),
					ignoreCase: !!data[6]
				});

			} else if(firstChar === ":"){
				//if(selector.charAt(1) === ":"){} //TODO pseudo-element

                selector = selector.substr(1);

				name = getName().toLowerCase();
				data = null;

				if(selector.charAt(0) === "("){
                    if(name in unpackPseudos){
                        quot = selector.charAt(1);
                        var quoted = quot in quotes;

                        selector = selector.substr(quoted + 1);

                        data = [];
                        selector = parseSelector(data, selector, options);

                        if(quoted){
                            if(selector.charAt(0) !== quot){
                                throw new SyntaxError("unmatched quotes in :" + name);
                            } else {
                                selector = selector.substr(1);
                            }
                        }

                        if(selector.charAt(0) !== ")"){
                            throw new SyntaxError("missing closing parenthesis in :" + name + " " + selector);
                        }

                        selector = selector.substr(1);
                    } else {
                        var pos = 1, counter = 1;

                        for(; counter > 0 && pos < selector.length; pos++){
                            if(selector.charAt(pos) === "(") counter++;
                            else if(selector.charAt(pos) === ")") counter--;
                        }

                        if(counter){
                            throw new SyntaxError("parenthesis not matched");
                        }

    					data = selector.substr(1, pos - 2);
    					selector = selector.substr(pos);

                        if(name in stripQuotesFromPseudos){
                            quot = data.charAt(0);

                        	if(quot === data.slice(-1) && quot in quotes){
                        		data = data.slice(1, -1);
                        	}

                            data = unescapeCSS(data);
                        }
                    }
				}

				tokens.push({type: "pseudo", name: name, data: data});
			} else if(re_name.test(selector)){
    			name = getName();

    			if(!options || ("lowerCaseTags" in options ? options.lowerCaseTags : !options.xmlMode)){
    				name = name.toLowerCase();
    			}

    			tokens.push({type: "tag", name: name});
    		} else {
                if(tokens.length && tokens[tokens.length - 1].type === "descendant"){
                    tokens.pop();
                }
                addToken(subselects, tokens);
                return selector;
			}
		}
	}

    addToken(subselects, tokens);

	return selector;
}

function addToken(subselects, tokens){
    if(subselects.length > 0 && tokens.length === 0){
    	throw new SyntaxError("empty sub-selector");
    }

	subselects.push(tokens);
}
<commit_msg>consistently use tabs<commit_after>"use strict";

module.exports = parse;

var re_name = /^(?:\\.|[\w\-\u00c0-\uFFFF])+/,
    re_escape = /\\([\da-f]{1,6}\s?|(\s)|.)/ig,
    //modified version of https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L87
    re_attr = /^\s*((?:\\.|[\w\u00c0-\uFFFF\-])+)\s*(?:(\S?)=\s*(?:(['"])(.*?)\3|(#?(?:\\.|[\w\u00c0-\uFFFF\-])*)|)|)\s*(i)?\]/;

var actionTypes = {
	__proto__: null,
	"undefined": "exists",
	"":  "equals",
	"~": "element",
	"^": "start",
	"$": "end",
	"*": "any",
	"!": "not",
	"|": "hyphen"
};

var simpleSelectors = {
	__proto__: null,
	">": "child",
	"<": "parent",
	"~": "sibling",
	"+": "adjacent"
};

var attribSelectors = {
	__proto__: null,
	"#": ["id", "equals"],
	".": ["class", "element"]
};

//pseudos, whose data-property is parsed as well
var unpackPseudos = {
	__proto__: null,
	"has": true,
	"not": true,
	"matches": true
};

var stripQuotesFromPseudos = {
	__proto__: null,
	"contains": true
};

var quotes = {
	__proto__: null,
	"\"": true,
	"'": true
};

//unescape function taken from https://github.com/jquery/sizzle/blob/master/src/sizzle.js#L139
function funescape( _, escaped, escapedWhitespace ) {
	var high = "0x" + escaped - 0x10000;
	// NaN means non-codepoint
	// Support: Firefox
	// Workaround erroneous numeric interpretation of +"0x"
	return high !== high || escapedWhitespace ?
		escaped :
		// BMP codepoint
		high < 0 ?
			String.fromCharCode( high + 0x10000 ) :
			// Supplemental Plane codepoint (surrogate pair)
			String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
}

function unescapeCSS(str){
	return str.replace(re_escape, funescape);
}

function isWhitespace(c){
	return c === " " || c === "\n" || c === "\t" || c === "\f" || c === "\r";
}

function parse(selector, options){
	var subselects = [];

	selector = parseSelector(subselects, selector + "", options);

	if(selector !== ""){
		throw new SyntaxError("Unmatched selector: " + selector);
	}

	return subselects;
}

function parseSelector(subselects, selector, options){
	var tokens = [],
		sawWS = false,
		data, firstChar, name, quot;

	function getName(){
		var sub = selector.match(re_name)[0];
		selector = selector.substr(sub.length);
		return unescapeCSS(sub);
	}

	function stripWhitespace(start){
		while(isWhitespace(selector.charAt(start))) start++;
		selector = selector.substr(start);
	}

	stripWhitespace(0);

	while(selector !== ""){
		firstChar = selector.charAt(0);

		if(isWhitespace(firstChar)){
			sawWS = true;
			stripWhitespace(1);
		} else if(firstChar in simpleSelectors){
			tokens.push({type: simpleSelectors[firstChar]});
			sawWS = false;

			stripWhitespace(1);
		} else if(firstChar === ","){
			if(tokens.length === 0){
				throw new SyntaxError("empty sub-selector");
			}
			subselects.push(tokens);
			tokens = [];
			sawWS = false;
			stripWhitespace(1);
		} else {
			if(sawWS){
				if(tokens.length > 0){
					tokens.push({type: "descendant"});
				}
				sawWS = false;
			}

			if(firstChar === "*"){
				selector = selector.substr(1);
				tokens.push({type: "universal"});
			} else if(firstChar in attribSelectors){
				selector = selector.substr(1);
				tokens.push({
					type: "attribute",
					name: attribSelectors[firstChar][0],
					action: attribSelectors[firstChar][1],
					value: getName(),
					ignoreCase: false
				});
			} else if(firstChar === "["){
				selector = selector.substr(1);
				data = selector.match(re_attr);
				if(!data){
					throw new SyntaxError("Malformed attribute selector: " + selector);
				}
				selector = selector.substr(data[0].length);
				name = unescapeCSS(data[1]);

				if(
					!options || (
						"lowerCaseAttributeNames" in options ?
							options.lowerCaseAttributeNames :
							!options.xmlMode
					)
				){
					name = name.toLowerCase();
				}

				tokens.push({
					type: "attribute",
					name: name,
					action: actionTypes[data[2]],
					value: unescapeCSS(data[4] || data[5] || ""),
					ignoreCase: !!data[6]
				});

			} else if(firstChar === ":"){
				//if(selector.charAt(1) === ":"){} //TODO pseudo-element

				selector = selector.substr(1);

				name = getName().toLowerCase();
				data = null;

				if(selector.charAt(0) === "("){
					if(name in unpackPseudos){
						quot = selector.charAt(1);
						var quoted = quot in quotes;

						selector = selector.substr(quoted + 1);

						data = [];
						selector = parseSelector(data, selector, options);

						if(quoted){
							if(selector.charAt(0) !== quot){
								throw new SyntaxError("unmatched quotes in :" + name);
							} else {
								selector = selector.substr(1);
							}
						}

						if(selector.charAt(0) !== ")"){
							throw new SyntaxError("missing closing parenthesis in :" + name + " " + selector);
						}

						selector = selector.substr(1);
					} else {
						var pos = 1, counter = 1;

						for(; counter > 0 && pos < selector.length; pos++){
							if(selector.charAt(pos) === "(") counter++;
							else if(selector.charAt(pos) === ")") counter--;
						}

						if(counter){
							throw new SyntaxError("parenthesis not matched");
						}

						data = selector.substr(1, pos - 2);
						selector = selector.substr(pos);

						if(name in stripQuotesFromPseudos){
							quot = data.charAt(0);

							if(quot === data.slice(-1) && quot in quotes){
								data = data.slice(1, -1);
							}

							data = unescapeCSS(data);
						}
					}
				}

				tokens.push({type: "pseudo", name: name, data: data});
			} else if(re_name.test(selector)){
				name = getName();

				if(!options || ("lowerCaseTags" in options ? options.lowerCaseTags : !options.xmlMode)){
					name = name.toLowerCase();
				}

				tokens.push({type: "tag", name: name});
			} else {
				if(tokens.length && tokens[tokens.length - 1].type === "descendant"){
					tokens.pop();
				}
				addToken(subselects, tokens);
				return selector;
			}
		}
	}

	addToken(subselects, tokens);

	return selector;
}

function addToken(subselects, tokens){
	if(subselects.length > 0 && tokens.length === 0){
		throw new SyntaxError("empty sub-selector");
	}

	subselects.push(tokens);
}
<|endoftext|>


<commit_before>;(function(){ "use strict";

// # AA trees.
// This is a minimalistic implementation of [persistent][1]
// ordered dictinaries via [AA trees][2]
//
// [1]: (https://en.wikipedia.org/wiki/Persistent_data_structure)
// [2]: (https://en.wikipedia.org/wiki/AA_tree)

// ## Public construtor
// Given a comparison function `cmp` for keys,
// the constructor `AATree (cmp)` returns an empty AA tree, an object
// with four pure functions `{ select, insert, stream, each }`.

// I'm messing around with the closure pattern.
// I'd like the internals to be properly private.
// If I'd not export _fromInternal, then they would be!

var _fromInternal = {}

AATree.defaultCompare = function compare (a, b) {
	return a < b ? -1 : a > b ? 1 : 0 }

function AATree (cmp) {
  // private
  var cmp = cmp
  var store = EMPTY

  // public
  this.lookup = lookup
  this.select = select
  this.insert = insert
  this.stream = stream
  this.each = each
  this._reify = function () { return store }

  // init
  if (typeof cmp !== 'function')
    throw new Error ('First argument to AATree must be a comparison function.')

  if (arguments[1] === _fromInternal)
    store = arguments[2]

// ## Lookup
// Fast lookup a key `k`, returns an object `{ found:true, key, value }` if found,
// or `{ found:false }` otherwise.

function lookup (k) {
  var n = store
  while (true) {
    if (n === EMPTY)
      return { found:false }
    c = cmp(k, n.k)
    if (c === 0)
      return { found:true, key:k, value:n.v }
    n = (c < 0) ? n.l : n.r } }

// ## Select
// Lookup a key `k`, but return a 'Cursor' object.
// Cursor objects have methods to set and/ or remove key-value pairs from the store,
// depending on whether the key was found or not.

function select (k) {
  var n = store, p = null, c
  /* p is an internal cursor object;
   a path of nodes: path := null | { node, branch:-1|1, tail:path } */
  while (true) {
    if (n === EMPTY)
      return new Cursor (cmp, false, p, n, k)
    c = cmp(k, n.k)
    if (c === 0)
      return new Cursor (cmp, true, p, n, k)
    p = { branch:c, node:n, tail:p } // branch: -1 = left, 1 = right
    n = (c < 0) ? n.l : n.r } }

// ## Insert
// Insert an arbitrary number of key value pairs at once.
// Note that for a single pair, `t.insert(k, v)` is equivalent to `t.select(k).set(v)`.

function insert (k1, v1, k2, v2, _) {
  var r = self
  for (var i=0,l=arguments.length; i<l; i+=2)
    r = r.select(arguments[i]).set(arguments[i+1])
  return r }

// ## Each
// Execute a function `fn (k, v)` for each of the
// key-value pairs `(k, v)` in the AATree in ascending key order.

function each (fn) { /* Q: should I add a non-lazy- each for speed? */
  var ps = stream(), p = ps.next()
  while (p !== null) {
    fn(p.value, p.key)
    p = ps.next() } }

// ## Stream
// Returns a stateful lazy stream object `{ next }`.
// Each call of `next()` returns the subsequent key-value pair as
// an object `{ key, value }` in ascending order by key, or `null` if
// the end of the stream has been reached.

function stream () {
  var n = store, p = []
  return { next:next }
  /* where */
  function next () {
    while (n !== EMPTY) {
      p.push(n)
      n = n.l }
    if (p.length) {
      var n_ = p.pop()
      n = n_.r
      return { key:n_.k, value:n_.v } }
    return null } }

}

// ## Cursor
// A cursor into an AATree.
// `path` is the path up to, but *excluding* the selected node `nnode`.

AATree.Cursor = Cursor
function Cursor (cmp, found, path, node, key) {
  this.found = found
  this.value = node.v
  this.set = _set
  this.unset = found ? _unset : null

  // TODO: add `previous` and `next` methods.
  function _unset () {
    return new AATree (cmp, _fromInternal, unset (path, node)) }

  function _set (value) {
    return new AATree (cmp, _fromInternal, set (path, node, key, value)) }
}

// ## Private
// A constructor function `Node` for the internal node structure,
// and the AA tree's `skew` and `split` functions.

var LEFT = -1, RIGHT = 1
var EMPTY = Node (null, undefined, 0, null, null)
EMPTY.l = EMPTY.r = EMPTY

function Node (key, value, level, left, right) {
  return { l:left, lv:level, k:key, v:value, r:right } }

function skew (n) { // immutable
  if (!n.lv) return n
  var l = n.l
  return (l.lv === n.lv)
    ? Node (l.k, l.v, l.lv, l.l, Node (n.k, n.v, n.lv, l.r, n.r))
    : n }

function split (n) { // immutable
  if (!n.lv) return n
  var r = n.r
  return (r.r.lv === n.lv)
    ? Node (r.k, r.v, r.lv+1, Node (n.k, n.v, n.lv, n.l, r.l), r.r)
    : n }

function copy (n) {
  if (n === EMPTY) return n
  return { l:n.l, lv:n.lv, k:n.k, v:n.v, r:n.r } }

// ## Set
// `set(p, n0, k, v)` reconstructs an (internal) AA tree from a path `p`,
// but with the value of the selected node set to 'v'.

function set (p, n0, k, v) {
  var r = (n0 === EMPTY)
     ? Node (k, v, 1, EMPTY, EMPTY)
     : Node (k, v, n0.lv, n0.l, n0.r)
  while (p !== null) {
    var n = p.node
    r = (p.branch === RIGHT)
      ? Node (n.k, n.v, n.lv, n.l, r)
      : Node (n.k, n.v, n.lv, r, n.r)
    r = split(skew(r))
    p = p.tail }
  return r }

// ## Unset
// `unset(p, n0)` reconstructs an (internal) AA tree from a path `p`,
// but with the selected node `n0` removed.

function unset (p, n0) {

  // If n0 is not a leaf node, copy it for swapping its value with
  // a leaf node and extend the path upto just above a leaf node
  // by going left.right* and swap the values

  if (n0.l !== EMPTY) {
    n0 = copy(n0)
    p = { branch:LEFT, node:n0, tail:p }
    n = n0.l
    while (n.r !== EMPTY) {
      p = { branch:RIGHT, node:n, tail:p }
      n = n.r }
    n0.k = n.k
    n0.v = n.v }

  else if (n0.r !== EMPTY) {
    p = { branch:RIGHT, node:n0.r, tail:p } }

  // Then, reconstruct a tree from the path; make sure to copy
  // all nodes on the path, and rebalance on the way.

  var t = EMPTY
  while (p !== null) {
    var n = p.node
    t = (p.branch === RIGHT)
      ? Node (n.k, n.v, n.lv, n.l, t)
      : Node (n.k, n.v, n.lv, t, n.r)

    // Decrease and rebalance, make sure to copy rather than mutate nodes.
    // TODO don't copy anything more than strictly necessary!

    if (t.l.lv < t.lv-1 || t.r.lv < t.lv-1) {
      t.lv--
      t.r = copy(t.r)
      if (t.r.lv > t.lv)
        t.r.lv = t.lv
      t = skew(t)
      t.r = skew(t.r)
      t.r.r = skew(copy(t.r.r))
      t = split(t)
      t.r = split(t.r)
    }
    p = p.tail
  }
  return t
}

AATree._private = { Node:Node, EMPTY:EMPTY, _fromInternal:_fromInternal }
module.exports = AATree
})();<commit_msg>previous and next methods on Cursor<commit_after>(function(){ "use strict";

// # AA trees
// This is an implementation of [persistent][1]
// ordered dictinaries via [AA trees][2]
//
// [1]: (https://en.wikipedia.org/wiki/Persistent_data_structure)
// [2]: (https://en.wikipedia.org/wiki/AA_tree)

// I'm messing around with the closure pattern.
// I'd like the internals to be properly private.
// If I'd not export _fromInternal, then they would be!

var _fromInternal = {}

AATree.defaultCompare = function compare (a, b) {
  return a < b ? -1 : a > b ? 1 : 0 }

// ## Public AATree construtor
// Given a comparison function `cmp` for keys,
// the constructor `AATree (cmp)` returns an empty AA tree, an object
// with (pure) methods `{ lookup, select, insert, stream, each }`.

function AATree (cmp) {
  // private
  var cmp = cmp
  var store = EMPTY

  // public
  this.lookup = lookup
  this.select = select
  this.insert = insert
  this.stream = stream
  this.each = each
  this._reify = function () { return store }

  // init
  if (typeof cmp !== 'function')
    throw new Error ('First argument to AATree must be a comparison function.')

  if (arguments[1] === _fromInternal)
    store = arguments[2]

// ## Lookup
// Search for a key `k`, returns an object `{ found:true, key, value }` if found,
// or `{ found:false }` otherwise.

function lookup (k) {
  var n = store
  while (n !== EMPTY) {
    c = cmp(k, n.k)
    if (c === 0)
      return { found:true, key:k, value:n.v }
    n = (c < 0) ? n.l : n.r }
  return { found:false } }

// ## Select
// Lookup a key `k`, but trace the path to return a `Cursor` object.
// Cursor objects have methods to step through-, to set and/ or remove key-value pairs,
// depending on whether the key was found or not.

function select (k) {
  var n = store, p = null, c
  while (n !== EMPTY) {
    c = cmp(k, n.k)
    if (c === 0)
      return new Cursor (cmp, { node:n, branch:1, tail:p }, n.k)
    p = { branch:c, node:n, tail:p } // branch: -1 = left, 1 = right, >1 = after right.
    n = (c < 0) ? n.l : n.r }
  return new Cursor (cmp, { node:n, branch:-1, tail:p }, k)
}

// ## Insert
// Insert an arbitrary number of key value pairs at once.
// Note that for a single pair, `t.insert(k, v)` is equivalent to `t.select(k).set(v)`.

function insert (k1, v1, k2, v2, _) {
  var r = self
  for (var i=0,l=arguments.length; i<l; i+=2)
    r = r.select(arguments[i]).set(arguments[i+1])
  return r }

// ## Each
// Execute a function `fn (k, v)` for each of the
// key-value pairs `(k, v)` in the AATree in ascending key order.

function each (fn) { /* Q: should I add a non-lazy- each for speed? */
  var ps = stream(), p = ps.next()
  while (p !== null) {
    fn(p.value, p.key)
    p = ps.next() } }

// ## Stream
// Returns a stateful lazy stream object `{ next }`.
// Each call of `next()` returns the subsequent key-value pair as
// an object `{ key, value }` in ascending order by key, or `null` if
// the end of the stream has been reached.

function stream () {
  var n = store, p = []
  return { next:next }
  /* where */
  function next () {
    while (n !== EMPTY) {
      p.push(n)
      n = n.l }
    if (p.length) {
      var n_ = p.pop()
      n = n_.r
      return { key:n_.k, value:n_.v } }
    return null } }

}

// ## Cursor constructor
// `path` is an internal cursor structure.

AATree.Cursor = Cursor
function Cursor (cmp, path, key) {
  this.found = (path.node !== EMPTY)
  this.key = (path.node !== EMPTY) ? path.node.k : key
  this.value = path.node.v
  this.previous = previous
  this.next = next
  this.set = _set
  this.unset = this.found ? _unset : null

  // TODO: add `previous`
  function previous () {
    var path2 = step (path, -1)
    return path2 ? new Cursor (cmp, path2) : null }

  function next () {
    var path2 = step (path, 1)
    return path2 ? new Cursor (cmp, path2) : null }

  function _unset () {
    return new AATree (cmp, _fromInternal, unset (path)) }

  function _set (value) {
    return new AATree (cmp, _fromInternal, set (path, key, value)) }
}

// ## Internal tree structure
// A constructor function `Node`, the `copy`- and
// the AA tree's `skew` and `split` functions.

var LEFT = -1, RIGHT = 1
var EMPTY = Node (null, undefined, 0, null, null)
EMPTY.l = EMPTY.r = EMPTY

function Node (key, value, level, left, right) {
  return { l:left, lv:level, k:key, v:value, r:right } }

function skew (n) { // immutable
  if (!n.lv) return n
  var l = n.l
  return (l.lv === n.lv)
    ? Node (l.k, l.v, l.lv, l.l, Node (n.k, n.v, n.lv, l.r, n.r))
    : n }

function split (n) { // immutable
  if (!n.lv) return n
  var r = n.r
  return (r.r.lv === n.lv)
    ? Node (r.k, r.v, r.lv+1, Node (n.k, n.v, n.lv, n.l, r.l), r.r)
    : n }

function copy (n) {
  if (n === EMPTY) return n
  return { l:n.l, lv:n.lv, k:n.k, v:n.v, r:n.r } }

// ## Internal cursor structure
// Cursors are represented internally as a path of nodes,
// `path := null | { node, branch:-1|1, tail:path }`, representing a pointer
// at the left branch (-1), right branch (1), or when stepping through,
// before the left (<= 1) or after the right (>= 1) branch.

function step (path, direction) {
  var d = direction < 0 ? -1 : 1 /* normalise */
  while (true) {
    var n = path.node
      , i = path.branch

    if (n !== EMPTY && i === -1)
      path = { node:n.l, branch:-d, tail:path }

    else if (n !== EMPTY && i === 1)
      path = { node:n.r, branch:-d, tail:path }

    else if (path.tail !== null) {
      var t = path.tail
      path = { node:t.node, branch:t.branch+(2*d), tail:t.tail }
      if (t.branch === -d) return path } /* emit inorder */

    else return null }
}

// ## Set
// `set(p, n0, k, v)` reconstructs an (internal) AA tree from a path `p`,
// but with the value of the selected node `n0` set to 'v'.

function set (path, k, v) {
  var n0 = path.node, p = path.tail
  var r = (n0 === EMPTY)
     ? Node (k, v, 1, EMPTY, EMPTY)
     : Node (k, v, n0.lv, n0.l, n0.r)
  while (p !== null) {
    var n = p.node
    r = (p.branch === RIGHT)
      ? Node (n.k, n.v, n.lv, n.l, r)
      : Node (n.k, n.v, n.lv, r, n.r)
    r = split(skew(r))
    p = p.tail }
  return r }

// ## Unset
// `unset(p, n0)` reconstructs an (internal) AA tree from a path `p`,
// but with the selected node `n0` removed.

function unset (path) {
  var n0 = path.node, p = path.tail
  // If n0 is not a leaf node, copy it for swapping its value with
  // a leaf node and extend the path upto just above a leaf node
  // by going left.right* and swap the values

  if (n0.l !== EMPTY) {
    n0 = copy(n0)
    p = { branch:LEFT, node:n0, tail:p }
    n = n0.l
    while (n.r !== EMPTY) {
      p = { branch:RIGHT, node:n, tail:p }
      n = n.r }
    n0.k = n.k
    n0.v = n.v }

  else if (n0.r !== EMPTY) {
    p = { branch:RIGHT, node:n0.r, tail:p } }

  // Then, reconstruct a tree from the path; make sure to copy
  // all nodes on the path, and rebalance on the way.

  var t = EMPTY
  while (p !== null) {
    var n = p.node
    t = (p.branch === RIGHT)
      ? Node (n.k, n.v, n.lv, n.l, t)
      : Node (n.k, n.v, n.lv, t, n.r)

    // Decrease and rebalance, make sure to copy.
    // TODO don't copy more than strictly necessary!

    if (t.l.lv < t.lv-1 || t.r.lv < t.lv-1) {
      t.lv--
      t.r = copy(t.r)
      if (t.r.lv > t.lv)
        t.r.lv = t.lv
      t = skew(t)
      t.r = skew(t.r)
      t.r.r = skew(copy(t.r.r))
      t = split(t)
      t.r = split(t.r)
    }
    p = p.tail
  }
  return t
}

AATree._private = { Node:Node, EMPTY:EMPTY, _fromInternal:_fromInternal }
module.exports = AATree
})();<|endoftext|>


<commit_before>var fs = require('fs');
var path = require('path');
var Shell = require('child_process').exec;

var VOLUMES = '/Volumes';
var SHARE;

function mount(sharepath, cb) {
	SHARE = sharepath;
		}
}

function umount(cb) {
	var p = getMountedPath();
	if (!p) throw new Error("Cannot unmount an undefined path");
	Shell('umount ' + getMountedPath(), function(err, stdout, stderr) {
		cb(stderr);
	});
}

function getMountedPath() {
	return path.join(VOLUMES, path.basename(SHARE));
}

module.exports = {
	mount: mount,
	umount: umount,
	getPath: getMountedPath
};<commit_msg>simplify mount<commit_after>var fs = require('fs');
var path = require('path');
var Shell = require('child_process').exec;

var VOLUMES = '/Volumes';
var SHARE = null;

function mount(sharepath, cb) {
	SHARE = sharepath;
	var command =
		['osascript -e \'mount volume "smb://',
		path.normalize(SHARE),
		"\"'"];
	Shell(command.join(''), function(err, stdout, stderr) {
		var mountpath;
		if (!stderr && !err) {
			mountpath = getMountedPath();
		}
		cb(stderr, mountpath);
	});
}

function umount(cb) {
	var p = getMountedPath();
	if (!p) throw new Error("Cannot unmount an undefined path");
	Shell('umount ' + getMountedPath(), function(err, stdout, stderr) {
		cb(stderr);
	});
}

function getMountedPath() {
	return path.join(VOLUMES, path.basename(SHARE));
}

module.exports = {
	mount: mount,
	umount: umount,
	getPath: getMountedPath
};<|endoftext|>


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

module.exports = postcss.plugin('postcss-prepend-selector', function (opts) {
    opts = opts || {};
    return function (css) {
        css.walkRules(function (rule) {
            rule.selectors = rule.selectors.map( function (selector) {
                return opts.selector + selector;
            });
        });
    };
});
<commit_msg>Adding check to exclude keyframe rules.<commit_after>var postcss = require('postcss');

module.exports = postcss.plugin('postcss-prepend-selector', function (opts) {
    opts = opts || {};
    return function (css) {
        css.walkRules(function (rule) {
            rule.selectors = rule.selectors.map( function (selector) {
                if(/^\d*\%$|^from$|^to$/.test(selector)) {
                    // This is part of a keyframe
                    return selector;
                }
                return opts.selector + selector;
            });
        });
    };
});
<|endoftext|>


<commit_before>var debug = require('debug')('abacus');
var util = require('util');
var statsD = require('node-statsd').StatsD;
var config = require('../config');

var counters = function(conf){
  var self = this;
  self.config = conf || config;
  self.counters = {};
  self.statsD = false;

  // Start a statsD connection if configured
  if(self.config.statsD){
    var statsDConfig = self.config.statsD;
    self.statsD = new statsD(statsDConfig.connection.host, statsDConfig.connection.port);
  }
}

counters.prototype.increment = function(counter, increment){
  var self = this;
  if(!increment) increment = 1;
  if(!self.counters[counter]) self.counters[counter] = 0;
  self.counters[counter] += increment;
  if(self.statsD)
    self.statsD.increment(self.config.statsD.metricPrefix+counter);
}

counters.prototype.print = function(){
  var self = this;
  debug(util.inspect(self.counters));
}

counters.prototype.printPeriodically = function(interval){ // interval in seconds
  if(!interval) return;
  var self = this;
  self.period = setInterval(self.print.bind(self), interval * 1000);
}

counters.prototype.stopPeriod = function(){
  clearInterval(this.period);
}

counters.prototype.get = function(counter){
  return this.counters[counter] || 0;
}

module.exports = counters;
<commit_msg>set method for counters<commit_after>var debug = require('debug')('abacus');
var util = require('util');
var statsD = require('node-statsd').StatsD;
var config = require('../config');

var counters = function(conf){
  var self = this;
  self.config = conf || config;
  self.counters = {};
  self.statsD = false;

  // Start a statsD connection if configured
  if(self.config.statsD){
    var statsDConfig = self.config.statsD;
    self.statsD = new statsD(statsDConfig.connection.host, statsDConfig.connection.port);
  }
};

counters.prototype.increment = function(counter, increment){
  var self = this;
  if(!increment) increment = 1;
  if(!self.counters[counter]) self.counters[counter] = 0;
  self.counters[counter] += increment;
  if(self.statsD)
    self.statsD.increment(self.config.statsD.metricPrefix+counter);
};

counters.prototype.print = function(){
  var self = this;
  debug(util.inspect(self.counters));
};

counters.prototype.printPeriodically = function(interval){ // interval in seconds
  if(!interval) return;
  var self = this;
  self.period = setInterval(self.print.bind(self), interval * 1000);
};

counters.prototype.stopPeriod = function(){
  clearInterval(this.period);
};

counters.prototype.get = function(counter){
  return this.counters[counter] || 0;
};

counters.prototype.set = function(counter,value) {
  var self = this;
  if(!value) return;
  if(!self.counters[counter]) self.counters[counter] = 0;
  self.counters[counter] = value;
};

module.exports = counters;
<|endoftext|>