<commit_before>"use strict";

var assert = require("assert"),
    util = require("util");

var async = require("async"),
    request = require("crequest");

var TNT_URL_PREFIX = process.env.TNT_URL_PREFIX || "https://api.transitandtrails.org";

var TnT = function(options) {
  options = options || {};

  options.key = options.key || process.env.TNT_API_KEY;

  this.key = options.key;
};

TnT.prototype.toString = function() {
  return "[TransitAndTrails]";
};

TnT.prototype.get = function(options, callback) {
  assert.ok(this.key, "An API key is required.");

  if (typeof options === "string") {
    options = {
      url: options
    };
  }

  options.url = TNT_URL_PREFIX + options.url;

  options.qs = options.qs || {};

  // filter out undefined / null values
  Object.keys(options.qs).forEach(function(x) {
    if (options.qs[x] === undefined ||
        options.qs[x] === null) {
      delete options.qs[x];
    }
  });

  options.qs.key = this.key;

  return request.get(options, function(err, res, body) {
    if (res.statusCode !== 200) {
      return callback(body);
    }

    // reverse the order of body and res since clients shouldn't care about res
    return callback(err, body, res);
  });
};

//
// Attribute Categories
//

TnT.prototype.getAttributeCategories = function(options, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get({
    url: "/api/v1/attribute_categories",
    qs: options
  }, callback);
};

//
// Campgrounds
//

TnT.prototype.getCampground = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get("/api/v1/campgrounds/" + id, callback);
};

TnT.prototype.getCampgroundAttributes = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  var path = "/api/v1/campground_attributes";

  if (id) {
    path = util.format("/api/v1/campgrounds/%d/attributes", id);
  }

  return this.get(path, callback);
};

TnT.prototype.getCampgroundMaps = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/campgrounds/%d/maps", id), callback);
};

TnT.prototype.getCampgroundPhotos = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/campgrounds/%d/photos", id), callback);
};

TnT.prototype.getCampgrounds = function(options, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get({
    url: "/api/v1/campgrounds",
    qs: options
  }, callback);
};

//
// Trailheads
//

TnT.prototype.getTrailhead = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get("/api/v1/trailheads/" + id, callback);
};

TnT.prototype.getTrailheadAttributes = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  var path = "/api/v1/trailhead_attributes";

  if (id) {
    path = util.format("/api/v1/trailheads/%d/attributes", id);
  }

  return this.get(path, callback);
};

TnT.prototype.getTrailheadPhotos = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/trailheads/%d/photos", id), callback);
};

TnT.prototype.getTrailheadMaps = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/trailheads/%d/maps", id), callback);
};

TnT.prototype.getTrailheads = function(options, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get({
    url: "/api/v1/trailheads",
    qs: options
  }, callback);
};

//
// Trips
//

TnT.prototype.getTrip = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get("/api/v1/trips/" + id, callback);
};

TnT.prototype.getTripAsGeoJSON = function(id, callback) {
  var self = this;

  return async.parallel([
    function(done) {
      return self.getTrip(id, done);
    },
    function(done) {
      return self.getTripRoute(id, done);
    }
  ], function(err, data) {
    if (err) {
      return callback(err);
    }

    var trip = data[0][0],
        route = data[1][0];

    var geoJSON = {
      type: "FeatureCollection",
      features: [
        {
          type: "Feature",
          geometry: {
            type: "LineString",
            coordinates: route
          },
          properties: trip
        }
      ]
    };

    return callback(null, geoJSON);
  });
};

TnT.prototype.getTripAttributes = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  var path = "/api/v1/trip_attributes";

  if (id) {
    path = util.format("/api/v1/trips/%d/attributes", id);
  }

  return this.get(path, callback);
};

TnT.prototype.getTripPhotos = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/trips/%d/photos", id), callback);
};

TnT.prototype.getTripMaps = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/trips/%d/maps", id), callback);
};

TnT.prototype.getTripRoute = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/trips/%d/route", id), function(err, body, res) {
    if (err) {
      return callback(err, body, res);
    }

    var route;

    try {
      // route is stringified JSON (not JSON)
      route = JSON.parse(body.route);
    } catch (e) {
      return callback(e);
    }

    // flip coords to (x,y) order
    route = route.map(function(x) {
      return [x[1], x[0]];
    });

    return callback(null, route, res);
  });
};

TnT.prototype.getTrips = function(options, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get({
    url: "/api/v1/trips",
    qs: options
  }, callback);
};

//
// Users
//

TnT.prototype.getUser = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get("/api/v1/users/" + id, callback);
};

TnT.prototype.getUsers = function(options, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get({
    url: "/api/v1/users",
    qs: options
  }, callback);
};

module.exports = TnT;
<commit_msg>Expose the id as a top-level property<commit_after>"use strict";

var assert = require("assert"),
    util = require("util");

var async = require("async"),
    request = require("crequest");

var TNT_URL_PREFIX = process.env.TNT_URL_PREFIX || "https://api.transitandtrails.org";

var TnT = function(options) {
  options = options || {};

  options.key = options.key || process.env.TNT_API_KEY;

  this.key = options.key;
};

TnT.prototype.toString = function() {
  return "[TransitAndTrails]";
};

TnT.prototype.get = function(options, callback) {
  assert.ok(this.key, "An API key is required.");

  if (typeof options === "string") {
    options = {
      url: options
    };
  }

  options.url = TNT_URL_PREFIX + options.url;

  options.qs = options.qs || {};

  // filter out undefined / null values
  Object.keys(options.qs).forEach(function(x) {
    if (options.qs[x] === undefined ||
        options.qs[x] === null) {
      delete options.qs[x];
    }
  });

  options.qs.key = this.key;

  return request.get(options, function(err, res, body) {
    if (res.statusCode !== 200) {
      return callback(body);
    }

    // reverse the order of body and res since clients shouldn't care about res
    return callback(err, body, res);
  });
};

//
// Attribute Categories
//

TnT.prototype.getAttributeCategories = function(options, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get({
    url: "/api/v1/attribute_categories",
    qs: options
  }, callback);
};

//
// Campgrounds
//

TnT.prototype.getCampground = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get("/api/v1/campgrounds/" + id, callback);
};

TnT.prototype.getCampgroundAttributes = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  var path = "/api/v1/campground_attributes";

  if (id) {
    path = util.format("/api/v1/campgrounds/%d/attributes", id);
  }

  return this.get(path, callback);
};

TnT.prototype.getCampgroundMaps = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/campgrounds/%d/maps", id), callback);
};

TnT.prototype.getCampgroundPhotos = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/campgrounds/%d/photos", id), callback);
};

TnT.prototype.getCampgrounds = function(options, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get({
    url: "/api/v1/campgrounds",
    qs: options
  }, callback);
};

//
// Trailheads
//

TnT.prototype.getTrailhead = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get("/api/v1/trailheads/" + id, callback);
};

TnT.prototype.getTrailheadAttributes = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  var path = "/api/v1/trailhead_attributes";

  if (id) {
    path = util.format("/api/v1/trailheads/%d/attributes", id);
  }

  return this.get(path, callback);
};

TnT.prototype.getTrailheadPhotos = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/trailheads/%d/photos", id), callback);
};

TnT.prototype.getTrailheadMaps = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/trailheads/%d/maps", id), callback);
};

TnT.prototype.getTrailheads = function(options, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get({
    url: "/api/v1/trailheads",
    qs: options
  }, callback);
};

//
// Trips
//

TnT.prototype.getTrip = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get("/api/v1/trips/" + id, callback);
};

TnT.prototype.getTripAsGeoJSON = function(id, callback) {
  var self = this;

  return async.parallel([
    function(done) {
      return self.getTrip(id, done);
    },
    function(done) {
      return self.getTripRoute(id, done);
    }
  ], function(err, data) {
    if (err) {
      return callback(err);
    }

    var trip = data[0][0],
        route = data[1][0];

    var geoJSON = {
      type: "FeatureCollection",
      features: [
        {
          id: trip.id,
          type: "Feature",
          geometry: {
            type: "LineString",
            coordinates: route
          },
          properties: trip
        }
      ]
    };

    return callback(null, geoJSON);
  });
};

TnT.prototype.getTripAttributes = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  var path = "/api/v1/trip_attributes";

  if (id) {
    path = util.format("/api/v1/trips/%d/attributes", id);
  }

  return this.get(path, callback);
};

TnT.prototype.getTripPhotos = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/trips/%d/photos", id), callback);
};

TnT.prototype.getTripMaps = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/trips/%d/maps", id), callback);
};

TnT.prototype.getTripRoute = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get(util.format("/api/v1/trips/%d/route", id), function(err, body, res) {
    if (err) {
      return callback(err, body, res);
    }

    var route;

    try {
      // route is stringified JSON (not JSON)
      route = JSON.parse(body.route);
    } catch (e) {
      return callback(e);
    }

    // flip coords to (x,y) order
    route = route.map(function(x) {
      return [x[1], x[0]];
    });

    return callback(null, route, res);
  });
};

TnT.prototype.getTrips = function(options, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get({
    url: "/api/v1/trips",
    qs: options
  }, callback);
};

//
// Users
//

TnT.prototype.getUser = function(id, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get("/api/v1/users/" + id, callback);
};

TnT.prototype.getUsers = function(options, callback) {
  callback = Array.prototype.slice.call(arguments).pop();

  return this.get({
    url: "/api/v1/users",
    qs: options
  }, callback);
};

module.exports = TnT;
<|endoftext|>


<commit_before>'use strict';

// Modules
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
var taskOpts = require('./lib/tasks.js');

// "Constants"
var PLUGIN_NAME = 'kalabox-plugin-drush';

module.exports = function(kbox) {

  var globalConfig = kbox.core.deps.get('globalConfig');
  var events = kbox.core.events;
  var engine = kbox.engine;
  var Promise = kbox.Promise;

  kbox.ifApp(function(app) {

    // Grab the clients
    var Drush = require('./lib/drush.js');
    var drush = new Drush(kbox, app);

    // Events
    // Install the drush container for our things
    events.on('post-install', function(app, done) {
      // If profile is set to dev build from source
      var opts = {
        name: 'drush',
        srcRoot: path.resolve(__dirname)
      };
      engine.build(opts, done);
    });

    // Updates kalabox aliases when app is started.
    // This allows for both kbox drush to be used
    // and local drush to be used via: drush @<appname> status
    events.on('post-start-component', function(component, done) {
      // Only run on the db container
      if (component.name !== 'db') {
        done();
      }
      else {

        kbox.engine.inspect(component.containerId)
        .then(function(data) {
          var key = '3306/tcp';
          if (data && data.NetworkSettings.Ports[key]) {
            var port = data.NetworkSettings.Ports[key][0].HostPort;
            var cmd = [
              'sed',
              '-i',
              's/\'host\'.*/\'host\' => \'' + app.domain + '\',/g',
              '/src/config/drush/aliases.drushrc.php'
            ];

            // Image name
            var image = 'kalabox/debian:stable';

            // Build create options
            var createOpts = {};

            // Build start options
            var startOpts = kbox.util.docker.StartOpts()
              .bind(app.rootBind, '/src')
              .json();

            return kbox.engine.run(image, cmd, createOpts, startOpts);

          }
        })
        .nodeify(done);

      }
    });

    // Tasks
    // drush wrapper: kbox drush COMMAND
    kbox.tasks.add(function(task) {
      task.path = [app.name, 'drush'];
      task.description = 'Run drush commands.';
      task.kind = 'delegate';
      task.options.push(taskOpts.drushVersion);
      task.func = function(done) {
        var opts = drush.getOpts(this.options);
        var cmd = this.payload;
        cmd.unshift('@dev');
        drush.cmd(cmd, opts, done);
      };
    });

  });

};
<commit_msg>Add drush commadn to appCmd category<commit_after>'use strict';

// Modules
var path = require('path');
var fs = require('fs');
var _ = require('lodash');
var taskOpts = require('./lib/tasks.js');

// "Constants"
var PLUGIN_NAME = 'kalabox-plugin-drush';

module.exports = function(kbox) {

  var globalConfig = kbox.core.deps.get('globalConfig');
  var events = kbox.core.events;
  var engine = kbox.engine;
  var Promise = kbox.Promise;

  kbox.ifApp(function(app) {

    // Grab the clients
    var Drush = require('./lib/drush.js');
    var drush = new Drush(kbox, app);

    // Events
    // Install the drush container for our things
    events.on('post-install', function(app, done) {
      // If profile is set to dev build from source
      var opts = {
        name: 'drush',
        srcRoot: path.resolve(__dirname)
      };
      engine.build(opts, done);
    });

    // Updates kalabox aliases when app is started.
    // This allows for both kbox drush to be used
    // and local drush to be used via: drush @<appname> status
    events.on('post-start-component', function(component, done) {
      // Only run on the db container
      if (component.name !== 'db') {
        done();
      }
      else {

        kbox.engine.inspect(component.containerId)
        .then(function(data) {
          var key = '3306/tcp';
          if (data && data.NetworkSettings.Ports[key]) {
            var port = data.NetworkSettings.Ports[key][0].HostPort;
            var cmd = [
              'sed',
              '-i',
              's/\'host\'.*/\'host\' => \'' + app.domain + '\',/g',
              '/src/config/drush/aliases.drushrc.php'
            ];

            // Image name
            var image = 'kalabox/debian:stable';

            // Build create options
            var createOpts = {};

            // Build start options
            var startOpts = kbox.util.docker.StartOpts()
              .bind(app.rootBind, '/src')
              .json();

            return kbox.engine.run(image, cmd, createOpts, startOpts);

          }
        })
        .nodeify(done);

      }
    });

    // Tasks
    // drush wrapper: kbox drush COMMAND
    kbox.tasks.add(function(task) {
      task.path = [app.name, 'drush'];
      task.category = 'appCmd';
      task.description = 'Run drush commands.';
      task.kind = 'delegate';
      task.options.push(taskOpts.drushVersion);
      task.func = function(done) {
        var opts = drush.getOpts(this.options);
        var cmd = this.payload;
        cmd.unshift('@dev');
        drush.cmd(cmd, opts, done);
      };
    });

  });

};
<|endoftext|>


<commit_before>module.exports = {
  name: 'PrivacyMode',
  type: 'select',
  default: '0',
  section: 'general',
  title: 'Privacy Mode',
  description: 'Obscures dollar amounts everywhere until hovered.',
  options: [
    { 'name': 'Disabled', 'value': '0' },
    { 'name': 'Always On', 'value': '1' },
    { 'name': 'Add Toggle Button', 'value': '2' }
  ]
};
<commit_msg>Unquoted privacy mode settings file for consistency.<commit_after>module.exports = {
  name: 'PrivacyMode',
  type: 'select',
  default: '0',
  section: 'general',
  title: 'Privacy Mode',
  description: 'Obscures dollar amounts everywhere until hovered.',
  options: [
    { name: 'Disabled', value: '0' },
    { name: 'Always On', value: '1' },
    { name: 'Add Toggle Button', value: '2' }
  ]
};
<|endoftext|>


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

module.exports = function(command) {
  var homePath = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE

  fs.readFile(homePath+'/.ssh/config', 'utf8', function(err, data) {
    if (err) process.exit()

    var pattern  = new RegExp("Host "+command, "g")
      , sshExist = data.match(pattern)

    if (sshExist) {
      console.log('Command not found: '+command)
      console.log('SSH Host "'+command+'" found')
      spawn('ssh', [command], {stdio: 'inherit'})
    }
  })
}
<commit_msg>More strict regex to prevent finding a host with incomplete name<commit_after>var fs    = require('fs')
  , spawn = require('child_process').spawn

module.exports = function(command) {
  var homePath = process.env.HOME || process.env.HOMEPATH || process.env.USERPROFILE

  fs.readFile(homePath+'/.ssh/config', 'utf8', function(err, data) {
    if (err) process.exit()

    var pattern  = new RegExp("Host "+command+"\n", "g")
      , sshExist = data.match(pattern)

    if (sshExist) {
      console.log('Command not found: '+command)
      console.log('SSH Host "'+command+'" found')
      spawn('ssh', [command], {stdio: 'inherit'})
    }
  })
}
<|endoftext|>


<commit_before>'use strict'

const Handlebars = require('handlebars')

exports.name = 'handlebars'
exports.inputFormats = ['hbs', 'handlebars']
exports.outputFormat = 'html'
exports.handlebars = Handlebars

exports.compile = function (str, options) {
  options = options || {}
  for (const partial in options.partials || {}) {
    if ({}.hasOwnProperty.call(options.partials, partial)) {
      Handlebars.registerPartial(partial, options.partials[partial])
    }
  }
  for (const helper in options.helpers || {}) {
    if ({}.hasOwnProperty.call(options.helpers, helper)) {
      Handlebars.registerHelper(helper, options.helpers[helper])
    }
  }
  for (const decorator in options.decorators || {}) {
    if ({}.hasOwnProperty.call(options.decorators, decorator)) {
      Handlebars.registerDecorator(decorator, options.decorator[decorator])
    }
  }
  return Handlebars.compile(str, options)
}
<commit_msg>Update eslint<commit_after>'use strict'

const Handlebars = require('handlebars')

exports.name = 'handlebars'
exports.inputFormats = ['hbs', 'handlebars']
exports.outputFormat = 'html'
exports.handlebars = Handlebars

exports.compile = function (str, options) {
  options = options || {}
  for (const partial in options.partials || {}) {
    if ({}.hasOwnProperty.call(options.partials, partial)) {
      Handlebars.registerPartial(partial, options.partials[partial])
    }
  }

  for (const helper in options.helpers || {}) {
    if ({}.hasOwnProperty.call(options.helpers, helper)) {
      Handlebars.registerHelper(helper, options.helpers[helper])
    }
  }

  for (const decorator in options.decorators || {}) {
    if ({}.hasOwnProperty.call(options.decorators, decorator)) {
      Handlebars.registerDecorator(decorator, options.decorator[decorator])
    }
  }

  return Handlebars.compile(str, options)
}
<|endoftext|>


<commit_before>//Import dependencies
var ejs = require('ejs');
var electron = require('electron');
var fs = require('fs');
var mime = require('mime');
var path = require('path');
var url = require('url');

//Import app
var app = electron.app;

//Main function
module.exports = function(options)
{
  //Check options
  if(typeof options === 'undefined') { var options = {}; }

  //App ready event
  app.on('ready', function(){

    //Import protocol
    var protocol = electron.protocol;

    //Intercept the file protocol
    protocol.interceptBufferProtocol('file', function(request, callback){

      //Get the file
      var file = ParsePath(request.url);

      //Get the file extension
      var extension = path.extname(file);

      //Get the file content
      fs.readFile(file, 'utf8', function(err, content){

        //Check for error opening the file
        if(err)
        {
          //File not found
          return callback(-6);
        }

        try
        {
          //Convert the content to utf8
          content = content.toString('utf8');

          //Initialize the mime type
          var mimet = 'text/html';

          //Check the extension
          if(extension === '.ejs')
          {
            //Add the path to options
            options.filename = file;

            //Get the full file
            content = ejs.render(content, options);
          }
          else
          {
            //Get the mime type
            mimet = mime.lookup(extension);
          }

          //Return the callback
          return callback({ data: new Buffer(content), mimeType: mimet });
        }
        catch(ex)
        {
          //A generic failure occurred
          return callback(-2);
        }

      });
    });
  });
}

//Function to parse the path
function ParsePath(u)
{
  //Parse the url
  var p = url.parse(u);

  //Get the path name
  var pname = p.pathname;

  //Check for Windows
  if(process.platform === 'win32')
  {
    //Remove the first / from the path
    //https://github.com/jmjuanes/electron-ejs/pull/4#issuecomment-219254028
    pname = pname.substr(1);
  }

  //Return the path name
  return pname;
}
<commit_msg>Implementing error and before-render events<commit_after>//Import dependencies
var ejs = require('ejs');
var electron = require('electron');
var fs = require('fs');
var mime = require('mime');
var path = require('path');
var url = require('url');
var util = require('util');
var EventEmitter = require('events').EventEmitter;

//Import app
var app = electron.app;

//Main function
var ElectronEjs = function(data, options)
{
  var self = this;
  self.emit("test", "test");
  //Check data and options
  if(typeof data === 'undefined') { var data = {}; }
  if(typeof options === 'undefined') { var options = {}; }
  //App ready event
  app.on('ready', function(){

    //Import protocol
    var protocol = electron.protocol;

    //Intercept the file protocol
    protocol.interceptBufferProtocol('file', function(request, callback){

      //Get the file
      var file = ParsePath(request.url);

      //Get the file extension
      var extension = path.extname(file);

      fs.access(file, fs.F_OK | fs.R_OK, function(err) {
        if(err)
        {
          self.emit("error", err);
          //File not found
          return callback(-6);
        }

        //Check the extension
        if(extension === '.ejs')
        {
          //Add the path to data
          data.filename = file;

          var renderTemplate = function()
          {
            //Render the full file
            ejs.renderFile(file, data, options, function(err2, content) {
              if(err2)
              {
                self.emit("error", err2);
                //An unexpected error
                return callback(-9);
              }
              //Return the callback
              return callback({ data: new Buffer(content), mimeType: 'text/html' });
            });
          }
          if(!self.emit("before-render", file, data, options, renderTemplate))
          {
            renderTemplate();
          }
        }
        else
        {
          fs.readFile(file, function(err2, content){
            if(err2)
            {
              self.emit("error", err2);
              //Failed
              return callback(-2);
            }
            //Return the callback
            return callback({ data: content, mimeType: mime.lookup(extension) });
          });
        }
      });
    });
  });
}

//Function to parse the path
function ParsePath(u)
{
  //Parse the url
  var p = url.parse(u);

  //Get the path name
  var pname = p.pathname;

  //Check for Windows
  if(process.platform === 'win32')
  {
    //Remove the first / from the path
    //https://github.com/jmjuanes/electron-ejs/pull/4#issuecomment-219254028
    pname = pname.substr(1);
  }

  //Return the path name
  return pname;
}

// inheriting EventEmmiter to ElectronEjs
util.inherits(ElectronEjs, EventEmitter);

module.exports = ElectronEjs;<|endoftext|>


<commit_before>var fs = require('fs');
var express = require('express');
var app = express();
var http = require('http');
var bodyParser = require("body-parser");

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

app.get('/haproxy', function(req, res){

    function IPs(filePath){

        var regIP = /^(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])){3}\:[0-9]{1,4}\n?$/;

        var haproxy_origin = fs.readFileSync(filePath, 'utf8');
        var haproxy_splited_rows = haproxy_origin.split('\n');

        //cut and leave only configuration part of haproxy.cfg file
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            if(haproxy_splited_rows[i] != ''){
                 var temp = haproxy_splited_rows[i].split(' ');
                 if(temp[0] == 'frontend'){
                     haproxy_splited_rows = haproxy_splited_rows.slice(i);
                     break;
                 }
            }
        }

        //delete odd spaces
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            haproxy_splited_rows[i] = haproxy_splited_rows[i].replace(/^\s*/,'').replace(/\s*$/,'');
        }

        //search for {frontend name : frontend address}
        var frontend_names = {};

        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            for(var j = 0; j < temp.length; ++j){
                if(temp[j] == 'acl'){

                    frontend_names[temp[j+1]] = temp[temp.length - 1];

                }
            }
        }

        //search for {backend name : backend address}
        var backend_part_rows = [];
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            if(temp[0] == 'backend'){
                backend_part_rows = haproxy_splited_rows.slice(i);
                break;
            }
        }

        var backends_string = '';
        for(var i = 0; i < backend_part_rows.length; ++i){
            backends_string += ' ' + backend_part_rows[i];
        }

        var backend_names = {}; // {backend name : addresses}
        var backends_array_spaces = backends_string.split(' ');
        for(var i = 0; i < backends_array_spaces.length; ++i){

            if(backends_array_spaces[i] == 'backend'){

                backend_names[backends_array_spaces[i + 1]] = '';

                var temp_adr = '';

                for(var j = i; j < backends_array_spaces.length; ++j){

                    if(regIP.test(backends_array_spaces[j])){
                        temp_adr += backends_array_spaces[j] + ' ';
                        backend_names[backends_array_spaces[i + 1]] = temp_adr;
                    }
                    if(backends_array_spaces[j] == 'backend' && j != i){
                        i = j - 1;
                        break;
                    }
                }

            }

        }

        // define pairs front-backend
        var pairs = [];
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            for(var j = 0; j < temp.length; ++j) {
                if (temp[j] == 'use_backend'){
                    var obj = {};
                    obj.frontend = temp[temp.length - 1];
                    obj.backend = temp[j + 1];
                    pairs.push(obj);
                }
            }
        }

        // build config array [{frontend: 'IP', backend: 'IP', status: ''}, {...}]

        var IPs = [];

        for(var i = 0; i < pairs.length; ++i){
            var obj = {};
            obj.frontend = frontend_names[pairs[i].frontend];
            obj.backend = backend_names[pairs[i].backend];
            obj.status = "Not available";
            IPs.push(obj);
        }

        // preparing for status check
        var tempBackends = [];

        for(var i = 0; i < IPs.length; ++i){
            IPs[i].backend = IPs[i].backend.replace(/^\s*/,'').replace(/\s*$/,'');
            tempBackends[i] = "http://" + IPs[i].backend;
        }

        var Promise = require('promise');

        function getPromise(backend) {
            return new Promise(function(resolve) {
               http.get(backend, function(res) {
                    resolve(res.statusCode === 200 ? "Available" : "Not available");
            }).on('error', function () {
                   console.log("Error in request");
                   resolve("Not available");
                })
                .end();
         });
        }

        Promise.all(tempBackends . map(getPromise)) .
        then(function(stats) {

            for(var i = 0; i < stats.length; ++i)
            {
                IPs[i].status = stats[i];
            }

            res.json(IPs);
        });

    }
    try{IPs('/etc/haproxy/haproxy.cfg');}
    catch(e){ console.log(e);
    res.end('haproxy.cfg not found');
}

});

app.get('/download', function(req, res){

  var file = '/etc/haproxy/haproxy.cfg';
  res.download(file);

});

app.get('/view', function(req, res){
  var file = fs.readFileSync('/etc/haproxy/haproxy.cfg', 'utf8');
  res.end(file);

});

app.post('/certificate', function(req, res){

  var certificate = req.body.pem;
  var name = req.body.name;

  var path = '/etc/pki/tls/private/' + name + '.pem';

  fs.writeFile(path, certificate, function (err) {
            if (err) {
                return console.log(err);
            }
            console.log('wroten');
  });

});

var server = app.listen(3030, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('haproxyUI listening at http://%s:%s', host, port);
});
<commit_msg>Error in restarting haproxy.<commit_after>var fs = require('fs');
var express = require('express');
var app = express();
var http = require('http');
var bodyParser = require("body-parser");

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());

app.get('/haproxy', function(req, res){

    function IPs(filePath){

        var regIP = /^(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])(\.(25[0-5]|2[0-4][0-9]|[0-1][0-9]{2}|[0-9]{2}|[0-9])){3}\:[0-9]{1,4}\n?$/;

        var haproxy_origin = fs.readFileSync(filePath, 'utf8');
        var haproxy_splited_rows = haproxy_origin.split('\n');

        //cut and leave only configuration part of haproxy.cfg file
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            if(haproxy_splited_rows[i] != ''){
                 var temp = haproxy_splited_rows[i].split(' ');
                 if(temp[0] == 'frontend'){
                     haproxy_splited_rows = haproxy_splited_rows.slice(i);
                     break;
                 }
            }
        }

        //delete odd spaces
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            haproxy_splited_rows[i] = haproxy_splited_rows[i].replace(/^\s*/,'').replace(/\s*$/,'');
        }

        //search for {frontend name : frontend address}
        var frontend_names = {};

        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            for(var j = 0; j < temp.length; ++j){
                if(temp[j] == 'acl'){

                    frontend_names[temp[j+1]] = temp[temp.length - 1];

                }
            }
        }

        //search for {backend name : backend address}
        var backend_part_rows = [];
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            if(temp[0] == 'backend'){
                backend_part_rows = haproxy_splited_rows.slice(i);
                break;
            }
        }

        var backends_string = '';
        for(var i = 0; i < backend_part_rows.length; ++i){
            backends_string += ' ' + backend_part_rows[i];
        }

        var backend_names = {}; // {backend name : addresses}
        var backends_array_spaces = backends_string.split(' ');
        for(var i = 0; i < backends_array_spaces.length; ++i){

            if(backends_array_spaces[i] == 'backend'){

                backend_names[backends_array_spaces[i + 1]] = '';

                var temp_adr = '';

                for(var j = i; j < backends_array_spaces.length; ++j){

                    if(regIP.test(backends_array_spaces[j])){
                        temp_adr += backends_array_spaces[j] + ' ';
                        backend_names[backends_array_spaces[i + 1]] = temp_adr;
                    }
                    if(backends_array_spaces[j] == 'backend' && j != i){
                        i = j - 1;
                        break;
                    }
                }

            }

        }

        // define pairs front-backend
        var pairs = [];
        for(var i = 0; i < haproxy_splited_rows.length; ++i){
            var temp = haproxy_splited_rows[i].split(' ');
            for(var j = 0; j < temp.length; ++j) {
                if (temp[j] == 'use_backend'){
                    var obj = {};
                    obj.frontend = temp[temp.length - 1];
                    obj.backend = temp[j + 1];
                    pairs.push(obj);
                }
            }
        }

        // build config array [{frontend: 'IP', backend: 'IP', status: ''}, {...}]

        var IPs = [];

        for(var i = 0; i < pairs.length; ++i){
            var obj = {};
            obj.frontend = frontend_names[pairs[i].frontend];
            obj.backend = backend_names[pairs[i].backend];
            obj.status = "Not available";
            IPs.push(obj);
        }

        // preparing for status check
        var tempBackends = [];

        for(var i = 0; i < IPs.length; ++i){
            IPs[i].backend = IPs[i].backend.replace(/^\s*/,'').replace(/\s*$/,'');
            tempBackends[i] = "http://" + IPs[i].backend;
        }

        var Promise = require('promise');

        function getPromise(backend) {
            return new Promise(function(resolve) {
               http.get(backend, function(res) {
                    resolve(res.statusCode === 200 ? "Available" : "Not available");
            }).on('error', function () {
                   console.log("Error in request");
                   resolve("Not available");
                })
                .end();
         });
        }

        Promise.all(tempBackends . map(getPromise)) .
        then(function(stats) {

            for(var i = 0; i < stats.length; ++i)
            {
                IPs[i].status = stats[i];
            }

            res.json(IPs);
        });

    }
    try{IPs('/etc/haproxy/haproxy.cfg');}
    catch(e){ console.log(e);
    res.end('haproxy.cfg not found');
}

});

app.get('/download', function(req, res){

  var file = '/etc/haproxy/haproxy.cfg';
  res.download(file);

});

app.get('/view', function(req, res){
  var file = fs.readFileSync('/etc/haproxy/haproxy.cfg', 'utf8');
  res.end(file);

});

app.post('/certificate', function(req, res){

  var certificate = req.body.pem;
  var name = req.body.name;

  var path = '/etc/pki/tls/private/' + name + '.pem';
  var restartCmd = 'service haproxy restart';

  var exec = require('child_process').exec;

  fs.writeFile(path, certificate, function (err) {
            if (err) {
                return console.log(err);
            }
            console.log('Wroten in ' + path);

            exec(restartCmd, function (error, stdout, stderr) {
                if (error !== null) {
                    console.log('exec error: ' + error);
                }
                console.log('Restarting haproxy');
            });
  });

});

var server = app.listen(8083, function () {
    var host = server.address().address;
    var port = server.address().port;

    console.log('haproxyUI listening at http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>const defaultConfig = require('./lib/default-config')
const getContents = require('./lib/get-file-contents')
const generateBody = require('./lib/generate-body')
const commitIsInPR = require('./lib/commit-is-in-pr')
const ssrTemplate = require('./lib/ssr-template')
const React = require('react')
const ReactDOMServer = require('react-dom/server')
const App = require('./public/server.min.js').default

const express = require('express')
const path = require('path')

const ssrStr = ReactDOMServer.renderToString(React.createElement(App))
const tpl = ssrTemplate(ssrStr)

module.exports = (robot) => {
  const app = robot.route('/')
  app.use(express.static(path.join(__dirname, 'public')))
  app.get('/', (req, res) => {
    /* istanbul ignore next */
    if (process.env.NODE_ENV !== 'development') {
      res.setHeader('cache-control', 'public, max-age=1200, s-maxage=3200')
    }

    res.end(tpl)
  })

  robot.on('push', async context => {
    const config = await context.config('config.yml')
    const cfg = config && config.todo ? {...defaultConfig, ...config.todo} : defaultConfig

    // Get array of issue objects in the current repo
    const issues = await context.github.issues.getForRepo(context.repo())

    const {head_commit, commits} = context.payload
    const author = head_commit.author.username

    // Get the most up-to-date contents of each file
    // by the commit it was most recently edited in.
    const commitsByFiles = new Map()
    for (let c = 0; c < commits.length; c++) {
      const commit = commits[c]
      const files = [...commit.added, ...commit.modified]
      const mappedFiles = new Map()

      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        const sliced = commits.slice(c + 1)

        if (sliced.every(com => com.modified.indexOf(file) === -1)) {
          const contents = await getContents(context, commit.id, file)
          mappedFiles.set(file, contents)
        }
      }

      commitsByFiles.set(commit.id, mappedFiles)
    }

    commitsByFiles.forEach(async (files, sha) => {
      files.forEach(async (contents, file) => {
        // Get issue titles
        const re = new RegExp(`${cfg.keyword}\\s(.*)`, cfg.caseSensitive ? 'g' : 'gi')
        const matches = contents.match(re)
        if (!matches) return

        const titles = matches.map(title => title.replace(`${cfg.keyword} `, ''))
        titles.forEach(async title => {
          // Check if an issue with that title exists
          if (issues.data.some(issue => issue.title === title && issue.state === 'open')) return

          // :TODO: Reopen existing but closed issues if the same todo is introduced

          const pr = await commitIsInPR(context, sha)
          const body = generateBody(context, cfg, title, file, contents, author, sha, pr)

          // Generate an issue object
          // :TODO: Add labels

          const issueObj = { title, body }
          if (cfg.autoAssign === true) {
            issueObj.assignee = author
          } else if (typeof cfg.autoAssign === 'string') {
            issueObj.assignee = cfg.autoAssign
          } else if (Array.isArray(cfg.autoAssign)) {
            issueObj.assignees = cfg.autoAssign
          }

          const issue = context.issue(issueObj)

          return context.github.issues.create(issue)
        })
      })
    })
  })
}
<commit_msg>Add a todo<commit_after>const defaultConfig = require('./lib/default-config')
const getContents = require('./lib/get-file-contents')
const generateBody = require('./lib/generate-body')
const commitIsInPR = require('./lib/commit-is-in-pr')
const ssrTemplate = require('./lib/ssr-template')
const React = require('react')
const ReactDOMServer = require('react-dom/server')
const App = require('./public/server.min.js').default

const express = require('express')
const path = require('path')

const ssrStr = ReactDOMServer.renderToString(React.createElement(App))
const tpl = ssrTemplate(ssrStr)

module.exports = (robot) => {
  const app = robot.route('/')
  app.use(express.static(path.join(__dirname, 'public')))
  app.get('/', (req, res) => {
    /* istanbul ignore next */
    if (process.env.NODE_ENV !== 'development') {
      res.setHeader('cache-control', 'public, max-age=1200, s-maxage=3200')
    }

    res.end(tpl)
  })

  robot.on('push', async context => {
    const config = await context.config('config.yml')
    const cfg = config && config.todo ? {...defaultConfig, ...config.todo} : defaultConfig

    // Get array of issue objects in the current repo
    const issues = await context.github.issues.getForRepo(context.repo())

    const {head_commit, commits} = context.payload
    const author = head_commit.author.username

    // Get the most up-to-date contents of each file
    // by the commit it was most recently edited in.
    const commitsByFiles = new Map()
    for (let c = 0; c < commits.length; c++) {
      const commit = commits[c]
      const files = [...commit.added, ...commit.modified]
      const mappedFiles = new Map()

      for (let i = 0; i < files.length; i++) {
        const file = files[i]
        const sliced = commits.slice(c + 1)

        if (sliced.every(com => com.modified.indexOf(file) === -1)) {
          const contents = await getContents(context, commit.id, file)
          mappedFiles.set(file, contents)
        }
      }

      commitsByFiles.set(commit.id, mappedFiles)
    }

    commitsByFiles.forEach(async (files, sha) => {
      files.forEach(async (contents, file) => {
        // Get issue titles
        const re = new RegExp(`${cfg.keyword}\\s(.*)`, cfg.caseSensitive ? 'g' : 'gi')
        const matches = contents.match(re)
        if (!matches) return

        const titles = matches.map(title => title.replace(`${cfg.keyword} `, ''))
        titles.forEach(async title => {
          // Check if an issue with that title exists
          // :TODO: Use probot-metadata to store original title
          // @body By adding metadata to the original post, we can check there for the original title instead of hoping that the title of the existing issue hasn't changed
          if (issues.data.some(issue => issue.title === title && issue.state === 'open')) return

          // :TODO: Reopen existing but closed issues if the same todo is introduced

          const pr = await commitIsInPR(context, sha)
          const body = generateBody(context, cfg, title, file, contents, author, sha, pr)

          // Generate an issue object
          // :TODO: Add labels

          const issueObj = { title, body }
          if (cfg.autoAssign === true) {
            issueObj.assignee = author
          } else if (typeof cfg.autoAssign === 'string') {
            issueObj.assignee = cfg.autoAssign
          } else if (Array.isArray(cfg.autoAssign)) {
            issueObj.assignees = cfg.autoAssign
          }

          const issue = context.issue(issueObj)

          return context.github.issues.create(issue)
        })
      })
    })
  })
}
<|endoftext|>


<commit_before>var dgram = require('dgram')

function Node (id, address, port, generateProposalId) { // :: Int -> Int -> (Int) -> Node
  this.socket = dgram.createSocket('udp4')
  this.id = id
  this.address = address
  this.port = port
  this.acceptors = {} // ID -> [[port, address], last proposal]
  this.proposal = null
  this.value = null
  this.stateLog = {}
  this.roles = []
  this.quorum = null
  this.generateProposalId = generateProposalId
  this.sendToAcceptors = function (message) {
    for (var acceptor in this.acceptors) {
      this.socket.send(message, 0, this.acceptors[acceptor][0][0], this.acceptors[acceptors][0][1])
    }
  }
}

function Cluster (nodes) { // :: [Node] -> Cluster
  this.learners = {}
  this.acceptors = {}
  this.proposers = {}
  if (nodes) {
    nodes.ForEach(function (node, _, __) {
      this.addNode(node)
    }, this)
  }

  this.setQuorum = function () {
    if (this.acceptors.length % 2 == 0) {
      this.quorum = this.acceptors.length / 2 + 1
    } else {
      this.quorum = Math.ceil(Object.keys(this.acceptors).length / 2)
    }
    nodes.ForEach(function (node, _, _) {
      node.quorum = this.quorum
    }, this)()
  }

  this.addNode = function (node) {
    if (node.roles.indexOf('Learner') > -1) {
     this.learners[node.id] = [node.port, node.address]
    }
    if (node.roles.indexOf('Acceptor') > -1) {
     this.acceptors[node.id] = [node.port, node.address]
    }
    if (node.roles.indexOf('Proposer') > -1) {
     this.proposers[node.id] = [node.port, node.address]
    }
    for (var id in cluster.acceptors) {
      node.acceptors[id] = [cluster.acceptors[id], null]
    }
  }
}

function initializeProposer (node, cluster) { // :: Node -> Cluster -> a ->
  node.roles.push('Proposer')
  node.proposalId = null
  node.lastId = null
  node.promises = []
  node.nextProposalNum = 1

  node.socket.bind(node.port, node.address)
  node.socket.on("message", function (message, rinfo) {
    message = JSON.parse(message.toString())
    if (message.type == "promise") {
      node.receivePromise(message.id, message.proposalId, message.lastAcceptedId, message.lastValue)
    } else if (message.type == "proposal") {
      node.setProposal(message.proposal)
    } else if (message.type == "NAK") {
      node.prepare()
    } else if (message.type == "accepted") {
      node.recieveAccept()
    } else if (message.type == "known") {
      // message notifying this node that a specified acceptor is known
    }
  })

  node.setProposal = function (proposal, proposalId) {
    node.proposal = proposal
    node.proposalId = node.generateProposalId()
  }

  node.propose = function () {
    // TODO: create and send proposal to all acceptors
  }

  node.prepare = function () {
    node.promises = []
    node.nextProposalNum += 1
  }

  node.receivePromise = function (from, proposalId, lastAcceptedId, lastValue) { // :: Int -> Int -> Int -> a ->
    if (proposalId != node.proposalId || (node.promises.indexOf(from) < 0)) {
      return
    }

    if (node.acceptors[from] == null) {
      // we don't know this acceptor
      // TODO: query known acceptors
      identReq = new Buffer(JSON.stringify({
        type: "identify",
        address: from
      }))
      node.sendToAcceptors(identReq)
      return
    }

    if (node.promises.indexOf(from) < 0) {
      node.promises.push(from)
    } else { return } // we have already received a promise. Something is probably wrong.

    if (lastAcceptedId > node.lastId) {
      node.lastId = last_acceptedId
      if (lastValue) { node.proposal = lastValue }
    }

    if (node.promises.length == node.quorom) {
      if (node.proposal) {
        acceptReq = new Buffer(JSON.stringify({
          type: "accept",
          proposalId: node.proposalId,
          proposal: node.proposal,
        }))
        for (var acceptor in node.acceptors) {
          node.socket.send(acceptReq, 0, node.acceptors[acceptor][0][0], node.acceptors[acceptor][0][1])
        }
      }
    }
  }

  node.receiveAccept = function () {} //TODO

  cluster.addNode(node)
  cluster.setQuorum()
}

function initializeAcceptor (node, cluster) { // :: Node -> Cluster ->
  node.roles.push('Acceptor')
  // Sync stateLog with acceptors in cluster
  node.promisedId = null
  node.acceptedId = null

  node.receivePrepare = function (from, proposalId) {
    if (proposalID == node.promisedId) {
    } else if (proposalId > node.promisedId) {
      node.promisedId = proposalId
      // send prepare
    }
  }

  node.receiveAcceptRequest = function (from, proposalId, proposal) { // :: Int -> Int -> a ->
    if (proposalId == node.promisedId) {
      node.promisedId = proposalId
      node.acceptedId = proposalId
      node.value = proposal
      // alert other nodes that a value is accepted
    }
  }

  node.sendPromise = function () {} // TODO

  cluster.addNode(node)
  cluster.setQuorum()
}

function initializeLearner (node, cluster) { // :: Node -> Cluster ->
  node.roles.push('Learner')
  node.finalValue = null
  node.finalProposalId = null

  node.proposals = {} // proposal ID -> [accept count, retain count, value]

  node.receiveAccept = function (from, proposalId, acceptedValue) { // :: Int -> Int -> a ->
    if (node.finalValue != null) {
      return
    }

    var last = node.acceptors[from][1]
    if (last) {
      if (last > proposalId) { return }
      node.acceptors[from][1] = proposalId

      oldProposal = node.proposals[last]
      oldProposal[1] -= 1
      if (oldProposal[1] == 0) { delete node.proposals[last] }
    }

    if (node.proposals[proposalId] == null) {
      node.proposals[proposalId] = [1, 1, acceptedValue]
    }

    if (node.proposals[proposalId][0] == node.quorum) { // round over
      node.finalValue = acceptedValue
      node.finalProposalId = proposalId
    }
  }
  cluster.addNode(node)
  cluster.setQuorum()
}
<commit_msg>Handling identity requests.<commit_after>var dgram = require('dgram')

function Node (id, address, port, generateProposalId) { // :: Int -> Int -> (Int) -> Node
  this.socket = dgram.createSocket('udp4')
  this.id = id
  this.address = address
  this.port = port
  this.acceptors = {} // ID -> [[port, address], last proposal]
  this.proposal = null
  this.value = null
  this.stateLog = {}
  this.roles = []
  this.quorum = null
  this.generateProposalId = generateProposalId
  this.sendToAcceptors = function (message) {
    for (var acceptor in this.acceptors) {
      this.socket.send(message, 0, this.acceptors[acceptor][0][0], this.acceptors[acceptors][0][1])
    }
  }
}

function Cluster (nodes) { // :: [Node] -> Cluster
  this.learners = {}
  this.acceptors = {}
  this.proposers = {}
  if (nodes) {
    nodes.ForEach(function (node, _, __) {
      this.addNode(node)
    }, this)
  }

  this.setQuorum = function () {
    if (this.acceptors.length % 2 == 0) {
      this.quorum = this.acceptors.length / 2 + 1
    } else {
      this.quorum = Math.ceil(Object.keys(this.acceptors).length / 2)
    }
    nodes.ForEach(function (node, _, _) {
      node.quorum = this.quorum
    }, this)()
  }

  this.addNode = function (node) {
    if (node.roles.indexOf('Learner') > -1) {
     this.learners[node.id] = [node.port, node.address]
    }
    if (node.roles.indexOf('Acceptor') > -1) {
     this.acceptors[node.id] = [node.port, node.address]
    }
    if (node.roles.indexOf('Proposer') > -1) {
     this.proposers[node.id] = [node.port, node.address]
    }
    for (var id in cluster.acceptors) {
      node.acceptors[id] = [cluster.acceptors[id], null]
    }
  }
}

function initializeProposer (node, cluster) { // :: Node -> Cluster -> a ->
  node.roles.push('Proposer')
  node.proposalId = null
  node.lastId = null
  node.promises = []
  node.nextProposalNum = 1
  node.waiting = []

  node.socket.bind(node.port, node.address)
  node.socket.on("message", function (message, rinfo) {
    message = JSON.parse(message.toString())
    if (message.type == "promise") {
      node.receivePromise(message.id, message.proposalId, message.lastAcceptedId, message.lastValue)
    } else if (message.type == "proposal") {
      node.setProposal(message.proposal)
    } else if (message.type == "NAK") {
      node.prepare()
    } else if (message.type == "accepted") {
      node.recieveAccept()
    } else if (message.type == "known") {
      // message notifying this node that a specified acceptor is known
      node.acceptors[message.nodeId] = [[message.nodePort, message.nodeAddress], message.nodeLastProposal]
      // TODO: check node.waiting for address, log promise if present
    }
  })

  node.setProposal = function (proposal, proposalId) {
    node.proposal = proposal
    node.proposalId = node.generateProposalId()
  }

  node.propose = function () {
    // TODO: create and send proposal to all acceptors
  }

  node.prepare = function () {
    node.promises = []
    node.nextProposalNum += 1
  }

  node.receivePromise = function (from, proposalId, lastAcceptedId, lastValue) { // :: Int -> Int -> Int -> a ->
    if (proposalId != node.proposalId || (node.promises.indexOf(from) < 0)) {
      return
    }

    if (node.acceptors[from] == null) {
      // we don't know this acceptor
      // TODO: query known acceptors
      identReq = new Buffer(JSON.stringify({
        type: "identify",
        address: from
      }))
      node.sendToAcceptors(identReq)
      node.waiting.push(from)
      return
    }

    if (node.promises.indexOf(from) < 0) {
      node.promises.push(from)
    } else { return } // we have already received a promise. Something is probably wrong.

    if (lastAcceptedId > node.lastId) {
      node.lastId = last_acceptedId
      if (lastValue) { node.proposal = lastValue }
    }

    if (node.promises.length == node.quorom) {
      if (node.proposal) {
        acceptReq = new Buffer(JSON.stringify({
          type: "accept",
          proposalId: node.proposalId,
          proposal: node.proposal,
        }))
        for (var acceptor in node.acceptors) {
          node.socket.send(acceptReq, 0, node.acceptors[acceptor][0][0], node.acceptors[acceptor][0][1])
        }
      }
    }
  }

  node.receiveAccept = function () {} //TODO

  cluster.addNode(node)
  cluster.setQuorum()
}

function initializeAcceptor (node, cluster) { // :: Node -> Cluster ->
  node.roles.push('Acceptor')
  // Sync stateLog with acceptors in cluster
  node.promisedId = null
  node.acceptedId = null

  node.receivePrepare = function (from, proposalId) {
    if (proposalID == node.promisedId) {
    } else if (proposalId > node.promisedId) {
      node.promisedId = proposalId
      // send prepare
    }
  }

  node.receiveAcceptRequest = function (from, proposalId, proposal) { // :: Int -> Int -> a ->
    if (proposalId == node.promisedId) {
      node.promisedId = proposalId
      node.acceptedId = proposalId
      node.value = proposal
      // alert other nodes that a value is accepted
    }
  }

  node.sendPromise = function () {} // TODO

  cluster.addNode(node)
  cluster.setQuorum()
}

function initializeLearner (node, cluster) { // :: Node -> Cluster ->
  node.roles.push('Learner')
  node.finalValue = null
  node.finalProposalId = null

  node.proposals = {} // proposal ID -> [accept count, retain count, value]

  node.receiveAccept = function (from, proposalId, acceptedValue) { // :: Int -> Int -> a ->
    if (node.finalValue != null) {
      return
    }

    var last = node.acceptors[from][1]
    if (last) {
      if (last > proposalId) { return }
      node.acceptors[from][1] = proposalId

      oldProposal = node.proposals[last]
      oldProposal[1] -= 1
      if (oldProposal[1] == 0) { delete node.proposals[last] }
    }

    if (node.proposals[proposalId] == null) {
      node.proposals[proposalId] = [1, 1, acceptedValue]
    }

    if (node.proposals[proposalId][0] == node.quorum) { // round over
      node.finalValue = acceptedValue
      node.finalProposalId = proposalId
    }
  }
  cluster.addNode(node)
  cluster.setQuorum()
}
<|endoftext|>


<commit_before>'use strict';

var through        = require('through2');
var stylus         = require('accord').load('stylus');
var gutil          = require('gulp-util');
var rext           = require('replace-ext');
var path           = require('path');
var assign         = require('lodash.assign');
var applySourceMap = require('vinyl-sourcemaps-apply');

var PLUGIN_NAME = 'gulp-stylus';

module.exports = function (options) {
  var opts = assign({}, options);

  return through.obj(function (file, enc, cb) {

    if (file.isStream()) {
      return cb(new gutil.PluginError(PLUGIN_NAME, 'Streaming not supported'));
    }
    if (file.isNull()) {
      return cb(null, file);
    }
    if (path.extname(file.path) === '.css') {
      return cb(null, file);
    }
    if (file.sourceMap || opts.sourcemap) {
      opts.sourcemap = assign({basePath: file.base}, opts.sourcemap);
    }
    opts.filename = file.path;

    stylus.render(file.contents.toString('utf8'), opts)
      .catch(function(err) {
        delete err.input;
        return cb(new gutil.PluginError(PLUGIN_NAME, err));
      })
      .done(function(res) {
        if (res == null) return;
        if (res.result !== undefined) {
          file.path = rext(file.path, '.css');
          if (res.sourcemap) {
            res.result = res.result.replace(/^\s*\/\*[@#][\s\t]+sourceMappingURL=.*$/mg, '');
            res.sourcemap.file = file.relative;
            applySourceMap(file, res.sourcemap);
          }
          file.contents = new Buffer(res.result);
          return cb(null, file);
        }
      });
  });

};

module.exports.stylus = require('stylus');
<commit_msg>small code refactors<commit_after>'use strict';

var through        = require('through2');
var stylus         = require('accord').load('stylus');
var gutil          = require('gulp-util');
var rext           = require('replace-ext');
var extname        = require('path').extname;
var assign         = require('lodash.assign');
var applySourceMap = require('vinyl-sourcemaps-apply');

function guErr(err) {
  return new gutil.PluginError('gulp-stylus', err);
}

module.exports = function (options) {
  var opts = assign({}, options);

  return through.obj(function (file, enc, cb) {

    if (file.isStream()) {
      return cb(guErr('Streaming not supported'));
    }
    if (file.isNull()) {
      return cb(null, file);
    }
    if (extname(file.path) === '.css') {
      return cb(null, file);
    }
    if (file.sourceMap || opts.sourcemap) {
      opts.sourcemap = assign({basePath: file.base}, opts.sourcemap);
    }
    opts.filename = file.path;

    stylus.render(file.contents.toString('utf8'), opts)
      .catch(function(err) {
        delete err.input;
        return cb(guErr(err));
      })
      .done(function(res) {
        if (res == null) {
          return;
        }
        if (res.result !== undefined) {
          file.path = rext(file.path, '.css');
          if (res.sourcemap) {
            res.result = res.result.replace(/^\s*\/\*[@#][\s\t]+sourceMappingURL=.*$/mg, '');
            res.sourcemap.file = file.relative;
            applySourceMap(file, res.sourcemap);
          }
          file.contents = new Buffer(res.result);
          return cb(null, file);
        }
      });
  });

};

module.exports.stylus = require('stylus');
<|endoftext|>


<commit_before>'use strict'

// TODO: replace with Array.find once 0.10 support can be dropped
// https://github.com/nodejs/LTS#lts-schedule
var find = function(collection, predicate) {
  var i
  var element

  for (i = 0; i < collection.length; i++) {
    element = collection[i]

    if (predicate(element)) {
      return element
    }
  }
}

var layerTypes = [
  {
    id: 'tcu',
    name: {
      en: 'top copper'
    },
    match: /((F.Cu)|(top\.gbr))|(\.((cmp)|(top$)|(gtl)))|(\.toplayer\.ger)/i
  },
  {
    id: 'tsm',
    name: {
      en: 'top soldermask'
    },
    match: /((F.Mask)|(topmask))|(\.((stc)|(tsm)|(gts)|(smt)))|(\.topsoldermask\.ger)/i
  },
  {
    id: 'tss',
    name: {
      en: 'top silkscreen'
    },
    match: /((F.SilkS)|(topsilk))|(\.((plc)|(tsk)|(gto)|(sst)))|(\.topsilkscreen\.ger)/i
  },
  {
    id: 'tsp',
    name: {
      en: 'top solderpaste'
    },
    match: /((F.Paste)|(toppaste))|(\.((crc)|(tsp)|(gtp)|(spt)))|(\.tcream\.ger)/i
  },
  {
    id: 'bcu',
    name: {
      en: 'bottom copper'
    },
    match: /(B.Cu|bottom\.gbr)|(\.((sol)|(bot$)|(gbl)))|(\.bottomlayer\.ger)/i
  },
  {
    id: 'bsm',
    name: {
      en: 'bottom soldermask'
    },
    match: /(B.Mask|bottommask\.)|(\.((sts)|(bsm)|(gbs)|(smb)))|(\.bottomsoldermask\.ger)/i
  },
  {
    id: 'bss',
    name: {
      en: 'bottom silkscreen'
    },
    match: /((B.SilkS)|(bottomsilk\.))|(\.((pls)|(bsk)|(gbo)|(ssb)))|(\.bottomsilkscreen\.ger)/i
  },
  {
    id: 'bsp',
    name: {
      en: 'bottom solderpaste'
    },
    match: /(B.Paste)|(\.((crs)|(bsp)|(gbp)|(spb)))|(\.bcream\.ger)/i
  },
  {
    id: 'icu',
    name: {
      en: 'inner copper'
    },
    match: /(In(ner)?\d+.Cu)|(\.((ly)|(g)|(in))\d+)|(\.internalplane\d+\.ger)/i
  },
  {
    id: 'out',
    name: {
      en: 'board outline'
    },
    match: /((Edge.Cuts)|(outline))|(\.((dim)|(mil)|(gm[l\d])|(gko)|(fab$)))|(\.boardoutline\.ger)/i
  },
  {
    id: 'drl',
    name: {
      en: 'drill hits'
    },
    match: /\.((fab\.gbr)|(cnc)|(drl)|(xln)|(txt)|(tap)|(drd)|(exc))/i
  },
  {
    id: 'drw',
    name: {
      en: 'gerber drawing'
    },
    match: /.*/
  }
]

module.exports = function whatsThatGerber(filename) {
  return find(layerTypes, function(type) {
    return type.match.test(filename)
  }).id
}

module.exports.getAllTypes = function() {
  return layerTypes.map(function(type) {
    return type.id
  })
}

module.exports.isValidType = function(type) {
  return layerTypes.some(function(layerType) {
    return layerType.id === type
  })
}

module.exports.getFullName = function whatsThatGerberTypeName(typeId, locale) {
  var type = find(layerTypes, function(type) {
    return type.id === typeId
  })

  locale = locale || 'en'

  if (!type || !type.name[locale]) {
    return ''
  }

  return type.name[locale]
}
<commit_msg>(#17) Add an end anchor to extensions<commit_after>'use strict'

// TODO: replace with Array.find once 0.10 support can be dropped
// https://github.com/nodejs/LTS#lts-schedule
var find = function(collection, predicate) {
  var i
  var element

  for (i = 0; i < collection.length; i++) {
    element = collection[i]

    if (predicate(element)) {
      return element
    }
  }
}

var layerTypes = [
  {
    id: 'tcu',
    name: {
      en: 'top copper'
    },
    match: /((F.Cu)|(top\.gbr$))|(\.((cmp$)|(top$)|(gtl$)))|(\.toplayer\.ger$)/i
  },
  {
    id: 'tsm',
    name: {
      en: 'top soldermask'
    },
    match: /((F.Mask)|(topmask))|(\.((stc$)|(tsm$)|(gts$)|(smt$)))|(\.topsoldermask\.ger$)/i
  },
  {
    id: 'tss',
    name: {
      en: 'top silkscreen'
    },
    match: /((F.SilkS)|(topsilk))|(\.((plc$)|(tsk$)|(gto$)|(sst$)))|(\.topsilkscreen\.ger$)/i
  },
  {
    id: 'tsp',
    name: {
      en: 'top solderpaste'
    },
    match: /((F.Paste)|(toppaste))|(\.((crc$)|(tsp$)|(gtp$)|(spt$)))|(\.tcream\.ger$)/i
  },
  {
    id: 'bcu',
    name: {
      en: 'bottom copper'
    },
    match: /(B.Cu|bottom\.gbr$)|(\.((sol$)|(bot$)|(gbl$)))|(\.bottomlayer\.ger$)/i
  },
  {
    id: 'bsm',
    name: {
      en: 'bottom soldermask'
    },
    match: /(B.Mask|bottommask\.)|(\.((sts$)|(bsm$)|(gbs$)|(smb$)))|(\.bottomsoldermask\.ger$)/i
  },
  {
    id: 'bss',
    name: {
      en: 'bottom silkscreen'
    },
    match: /((B.SilkS)|(bottomsilk\.))|(\.((pls$)|(bsk$)|(gbo$)|(ssb$)))|(\.bottomsilkscreen\.ger$)/i
  },
  {
    id: 'bsp',
    name: {
      en: 'bottom solderpaste'
    },
    match: /(B.Paste)|(\.((crs$)|(bsp$)|(gbp$)|(spb$)))|(\.bcream\.ger$)/i
  },
  {
    id: 'icu',
    name: {
      en: 'inner copper'
    },
    match: /(In(ner)?\d+.Cu)|(\.((ly)|(g)|(in))\d+$)|(\.internalplane\d+\.ger$)/i
  },
  {
    id: 'out',
    name: {
      en: 'board outline'
    },
    match: /((Edge.Cuts)|(outline))|(\.((dim$)|(mil$)|(gm[l\d]$)|(gko$)|(fab$)))|(\.boardoutline\.ger$)/i
  },
  {
    id: 'drl',
    name: {
      en: 'drill hits'
    },
    match: /\.((fab\.gbr$)|(cnc$)|(drl$)|(xln$)|(txt$)|(tap$)|(drd$)|(exc$))/i
  },
  {
    id: 'drw',
    name: {
      en: 'gerber drawing'
    },
    match: /.*/
  }
]

module.exports = function whatsThatGerber(filename) {
  return find(layerTypes, function(type) {
    return type.match.test(filename)
  }).id
}

module.exports.getAllTypes = function() {
  return layerTypes.map(function(type) {
    return type.id
  })
}

module.exports.isValidType = function(type) {
  return layerTypes.some(function(layerType) {
    return layerType.id === type
  })
}

module.exports.getFullName = function whatsThatGerberTypeName(typeId, locale) {
  var type = find(layerTypes, function(type) {
    return type.id === typeId
  })

  locale = locale || 'en'

  if (!type || !type.name[locale]) {
    return ''
  }

  return type.name[locale]
}
<|endoftext|>


<commit_before>'use strict';
var gulp;
var pkg;
var browserSync = require('browser-sync');
var plugins = {
    autoprefixer: require('gulp-autoprefixer'),
    awsS3 : require('gulp-aws-s3'),
    bower : require('gulp-bower'),
    concat : require('gulp-concat'),
    ghPages : require('gulp-gh-pages'),
    replace : require('gulp-replace'),
    run : require('gulp-run'),
    sass : require('gulp-sass'),
    del : require('del'),
    minimist : require('minimist'),
    'if' : require('gulp-if'),
    bump : require('gulp-bump'),
    rename : require("gulp-rename"),
    uglify : require('gulp-uglify'),
    semver : require('semver'),
    flatten : require('gulp-flatten')
};
var paths = require('./paths');
var knownOptions = {
    string: 'version',
    default: { version: 'patch' }
};
var options = plugins.minimist(process.argv.slice(2), knownOptions);

function copyDir(location, fileType){
    var files = (fileType === 'css') ? '/' + pkg.name + '.css' : '/**/*';
    return gulp.src([paths[location][fileType] + files])
        .pipe(gulp.dest(paths.dist[fileType]));
}

function awsUpload(fileType, awsS3){
    var path = 'components/' + pkg.name + '/' + pkg.version + '/' + fileType + '/';
    return gulp.src(paths.dist[fileType] + '/**/*')
        .pipe(awsS3.upload({ path: path } ));
}

function updateDocs(files){
    var now = Date().split(' ').splice(0,5).join(' ');
    return gulp.src(files, { base : './' })
        .pipe(plugins.replace(/[0-9]+\.[0-9]+\.[0-9]/g, pkg.version))
        .pipe(plugins.replace(/{{ site.version }}/g, pkg.version))
        .pipe(plugins.replace(/{{ site.time }}/g, now))
        .pipe(gulp.dest('./'));
}

function setupHasErrors(){
    var errorText = '\nSky Component %s Error:' +
        '\nPlease update `package.json` (without spaces): \n  i.e.' +
        '%s\n';
    var error = false;

    if (pkg.name.indexOf(' ') >0){
        console.error(errorText, 'Name',' `"name" : "responsive-images"`');
        error = true;
    }
    if (pkg.repository.url.indexOf(' ') >0){
        console.error(errorText, 'URL', '`"url": "git://github.com/skyglobal/gulp-helper-test.git"`');
        error = true;
    }
    return error;
}

function isSkyGlobal(){
    return pkg.repository.url.indexOf('/skyglobal/')>0;
}

function initBower(cb){
    if (isSkyGlobal()){
        return plugins.run('bower register bskyb-' + pkg.name + ' ' + pkg.repository.url).exec('', cb);
    } else {
        console.log('**Bower skipped as its not a SkyGlobal Repo**');
        return cb();
    }
}

function initMaster(cb){
    //lines commented out as not needed for a 'cloned' repo
    return plugins.run(
//            '\n' +'git init;' +
            '\n' +'git add gulpfile.js;' +
            '\n' +'git add package.json;' +
            '\n' +'git commit -m "first commit";' +
//            '\n' +'git remote add origin ' + pkg.repository.url.replace('git://github.com/','git@github.com:') + ';' +
            '\n' +'git push -u origin master;' +
            '\n').exec('', cb);
}
function initGHPages(cb){
    return plugins.run(
            '\n' +'git checkout --orphan gh-pages;' +
            '\n' +'git rm -rf .;' +
            '\n' +'touch anyfile.md;' +
            '\n' +'git add anyfile.md;' +
            '\n' +'git commit -m "Init gh-pages";' +
            '\n' +'git push --set-upstream origin gh-pages;' +
            '\n' +'git checkout master;' +
            '\n').exec('', cb);
}

function gulpTasks(globalGulp, globalPkg){
    gulp = globalGulp;
    pkg = globalPkg;
    var gitUser = pkg.repository.url.match(/.com\/(.*)\//)[1];
    var runSequence = require('run-sequence').use(gulp);

    gulp.task('pre-build', function(cb){
        return cb();
    });

    gulp.task('sass', function() {
        browserSync.notify('Running: Sass compiling');
        return gulp.src([
                paths.source['sass'] + '/**/*.scss',
                paths.demo['sass'] + '/**/*.scss',
                paths.site['sass'] + '/**/*.scss'])
            .pipe(plugins.sass({
                includePaths: ['bower_components'],
                outputStyle: 'nested'
            }))
            .pipe(plugins.autoprefixer())
            .pipe(gulp.dest(paths.site['css']))
            .pipe(browserSync.reload({stream:true}));
    });

    gulp.task('js-min', function() {
        return gulp.src(paths.source['js'] + '/**/*')
            .pipe(plugins.concat(pkg.name + '.min.js'))
            .pipe(plugins.uglify())
            .pipe(gulp.dest(paths.site['js']));
    });

    gulp.task('js-dev', function() {
        return gulp.src(paths.source['js'] + '/**/*')
            .pipe(plugins.concat(pkg.name + '.js'))
            .pipe(gulp.dest(paths.site['js']));
    });

    gulp.task('js', function(cb) {
        return runSequence(['js-dev','js-min'],
            cb
        );
    });

    gulp.task('browserSync', function() {
        browserSync({
            port: 3456,
            server: {
                baseDir: paths.site['root']
            }
        });
    });

    gulp.task('watch', function() {
        gulp.watch([paths.site['root'], paths.demo['root']], ['create-site']);
        gulp.watch([paths.source['sass'] + '/**/*',paths.demo['sass']], ['sass']);
    });

//    create the _ste directories ready for demo
    gulp.task('create-site-html', function createSite() {
        return gulp.src([paths.demo['root'] + '/index.html',
                paths.demo['root'] +'/_includes/*.html'])
            .pipe(plugins.concat('index.html'))
            .pipe(gulp.dest(paths.site['root']));
    });

    gulp.task('create-site-images', function createSite() {
        return gulp.src(paths.demo['images'] + '/**/*')
            .pipe(gulp.dest(paths.site['images']));
    });

    gulp.task('create-site-fonts', function createSite() {
        return gulp.src([
                paths.source['fonts'] + '/**/*',
                paths.bower['fonts'] + '/**/*.{eot,ttf,woff,svg}'
        ])
            .pipe(plugins.flatten())
            .pipe(gulp.dest(paths.site['fonts']));
    });
    gulp.task('create-site', function createSite() {
        return runSequence(['create-site-html', 'create-site-images', 'create-site-fonts']);
    });

    gulp.task('build', function(cb) {
        return runSequence('clean', 'pre-build', ['create-site','bower'], ['update-docs-version', 'sass', 'js'],'create-bower-dist',
            cb
        );
    });

//remove temporary directors
    gulp.task('clean', function(cb) {
        return plugins.del([
            '.tmp',
            paths.site['root'],
            paths.dist['root']
        ], cb);
    });

//update the version number used within all documentation and html
    gulp.task('update-docs-version-within-md', function(){
        return updateDocs(['README.md']);
    });
    gulp.task('update-docs-version-within-site', function(){
        return updateDocs([paths.site['root'] + '/**/*.html']);
    });
    gulp.task('update-docs-version', function(cb){
        return runSequence(['update-docs-version-within-site', 'update-docs-version-within-md'],cb);
    });
    gulp.task('bump-version', function(cb){
        pkg.version = plugins.semver.inc(pkg.version, options.version);
        return gulp.src('./*.json')
            .pipe(plugins.bump({type: options.version}))
            .pipe(gulp.dest('./'));
    });

    /*
     * Initialising the component
     */
    gulp.task('copy-structure', function(cb) {
        return gulp.src(__dirname + '/component-structure/**/*')
            .pipe(plugins.replace(/{{ component }}/g, pkg.name))
            .pipe(plugins.replace(/{{ git.user }}/g, gitUser))
            .pipe(gulp.dest('./'));
    });
    gulp.task('name-component', function(cb) {
        return gulp.src('./package.json', { base : './' })
            .pipe(plugins.replace(/{{ component }}/g, pkg.name))
            .pipe(plugins.replace(/{{ git.user }}/g, gitUser))
            .pipe(gulp.dest('./'));
    });
    gulp.task('rename-js', function(cb) {
        return gulp.src(['./src/js/main.js'], { base : './' })
            .pipe(plugins.rename(pkg.name + '.js'))
            .pipe(gulp.dest('./src/js/'));
    });
    gulp.task('rename-scss', function(cb) {
        return gulp.src(['./src/scss/main.scss'], { base : './' })
            .pipe(plugins.rename(pkg.name + '.scss'))
            .pipe(gulp.dest('./src/scss/'));
    });
    gulp.task('rename-dot-gitignore', function(cb) {
        return gulp.src('./dot.gitignore', { base : './' })
            .pipe(plugins.rename('.gitignore'))
            .pipe(gulp.dest('./'));
    });
    gulp.task('remove-renamed-files', function(cb) {
        return plugins.del(
            ['./dot.gitignore', './src/js/main.js', './src/scss/main.scss' ],
            cb);
    });
    gulp.task('initMaster', function(cb) {
        return initMaster(cb);
    });
    gulp.task('initGHPages', function(cb) {
        return initGHPages(cb);
    });
    gulp.task('initBower', function(cb) {
        return initBower(cb);
    });

    gulp.task('git-commit-push', function(cb){
        return plugins.run(
                'git commit -am "Version bump for release";' +
                'git push origin master').exec('', cb);
    });

    /*
     * RELEASING
     */

//  RELEASING:  Bower tasks
    gulp.task('create-bower-dist', function() {
        copyDir('site', 'js');
        copyDir('site', 'css');
        copyDir('site', 'sass');
        copyDir('site', 'fonts');
        copyDir('source', 'fonts');
        return copyDir('source', 'sass');
    });

    gulp.task('release:bower', function(cb) {
        return plugins.run(
                'git tag -a v'+ pkg.version +' -m "release v' + pkg.version +' for bower"; ' +
                'git push origin master v'+ pkg.version
        ).exec('', cb);
    });

    gulp.task('bower', function() {
        return plugins.bower()
    });

//  RELEASING:  GH Pages
    gulp.task('release:gh-pages', function () {
        gulp.src(paths.site['root'] + "/**/*")
            .pipe(plugins.ghPages({
                cacheDir: '.tmp'
            })).pipe(gulp.dest('/tmp/gh-pages'));
    });

//  RELEASING:  Amazon Web Services
    gulp.task('release:cdn', function(cb) {
        if (process.env.AWS_SKYGLOBAL_BUCKET && isSkyGlobal()) {
            var awsS3 = plugins.awsS3.setup({bucket: process.env.AWS_SKYGLOBAL_BUCKET});
            awsUpload('css',awsS3);
            awsUpload('js', awsS3);
            awsUpload('fonts', awsS3);
            return awsUpload('icons', awsS3);
        } else {
            console.log('** Amazon S3 skipped **\n' +
                'AWS env variables are not set \n' +
                ' or \n' +
                ' This is not a `skyglobal` repo\n');
            return cb();
        }
    });

    /*
     * Common/public Gulp tasks
     */
    gulp.task('init', function(cb) {
        if (setupHasErrors()){
            return;
        }
        return runSequence(
            'copy-structure',
            ['initMaster','rename-dot-gitignore', 'rename-js', 'rename-scss'],
            ['initGHPages'],
            'remove-renamed-files',
            'initBower', //move with other init once automatic
            cb);
    });

    gulp.task('serve', function(callback) {
        return runSequence(
            'build',
            ['browserSync', 'watch'],
            callback
        );
    });

    gulp.task('release', function(cb) {
        return runSequence(
            'bump-version',
            'build',
            'git-commit-push',
            ['release:bower', 'release:gh-pages', 'release:cdn'],
            cb
        );
    });

    return {
        paths: paths
    }
}

module.exports = gulpTasks;<commit_msg>remove site fonts from dist dir<commit_after>'use strict';
var gulp;
var pkg;
var browserSync = require('browser-sync');
var debug = require('gulp-debug');
var plugins = {
    autoprefixer: require('gulp-autoprefixer'),
    awsS3 : require('gulp-aws-s3'),
    bower : require('gulp-bower'),
    concat : require('gulp-concat'),
    ghPages : require('gulp-gh-pages'),
    replace : require('gulp-replace'),
    run : require('gulp-run'),
    sass : require('gulp-sass'),
    del : require('del'),
    minimist : require('minimist'),
    'if' : require('gulp-if'),
    bump : require('gulp-bump'),
    rename : require("gulp-rename"),
    uglify : require('gulp-uglify'),
    semver : require('semver'),
    flatten : require('gulp-flatten')
};
var paths = require('./paths');
var knownOptions = {
    string: 'version',
    default: { version: 'patch' }
};
var options = plugins.minimist(process.argv.slice(2), knownOptions);

function copyDir(location, fileType){
    var files = (fileType === 'css') ? '/' + pkg.name + '.css' : '/**/*';
    return gulp.src([paths[location][fileType] + files])
        .pipe(gulp.dest(paths.dist[fileType]));
}

function awsUpload(fileType, awsS3){
    var path = 'components/' + pkg.name + '/' + pkg.version + '/' + fileType + '/';
    return gulp.src(paths.dist[fileType] + '/**/*')
        .pipe(awsS3.upload({ path: path } ));
}

function updateDocs(files){
    var now = Date().split(' ').splice(0,5).join(' ');
    return gulp.src(files, { base : './' })
        .pipe(plugins.replace(/[0-9]+\.[0-9]+\.[0-9]/g, pkg.version))
        .pipe(plugins.replace(/{{ site.version }}/g, pkg.version))
        .pipe(plugins.replace(/{{ site.time }}/g, now))
        .pipe(gulp.dest('./'));
}

function setupHasErrors(){
    var errorText = '\nSky Component %s Error:' +
        '\nPlease update `package.json` (without spaces): \n  i.e.' +
        '%s\n';
    var error = false;

    if (pkg.name.indexOf(' ') >0){
        console.error(errorText, 'Name',' `"name" : "responsive-images"`');
        error = true;
    }
    if (pkg.repository.url.indexOf(' ') >0){
        console.error(errorText, 'URL', '`"url": "git://github.com/skyglobal/gulp-helper-test.git"`');
        error = true;
    }
    return error;
}

function isSkyGlobal(){
    return pkg.repository.url.indexOf('/skyglobal/')>0;
}

function initBower(cb){
    if (isSkyGlobal()){
        return plugins.run('bower register bskyb-' + pkg.name + ' ' + pkg.repository.url).exec('', cb);
    } else {
        console.log('**Bower skipped as its not a SkyGlobal Repo**');
        return cb();
    }
}

function initMaster(cb){
    //lines commented out as not needed for a 'cloned' repo
    return plugins.run(
//            '\n' +'git init;' +
            '\n' +'git add gulpfile.js;' +
            '\n' +'git add package.json;' +
            '\n' +'git commit -m "first commit";' +
//            '\n' +'git remote add origin ' + pkg.repository.url.replace('git://github.com/','git@github.com:') + ';' +
            '\n' +'git push -u origin master;' +
            '\n').exec('', cb);
}
function initGHPages(cb){
    return plugins.run(
            '\n' +'git checkout --orphan gh-pages;' +
            '\n' +'git rm -rf .;' +
            '\n' +'touch anyfile.md;' +
            '\n' +'git add anyfile.md;' +
            '\n' +'git commit -m "Init gh-pages";' +
            '\n' +'git push --set-upstream origin gh-pages;' +
            '\n' +'git checkout master;' +
            '\n').exec('', cb);
}

function gulpTasks(globalGulp, globalPkg){
    gulp = globalGulp;
    pkg = globalPkg;
    var gitUser = pkg.repository.url.match(/.com\/(.*)\//)[1];
    var runSequence = require('run-sequence').use(gulp);

    gulp.task('pre-build', function(cb){
        return cb();
    });

    gulp.task('sass', function() {
        browserSync.notify('Running: Sass compiling');
        return gulp.src([
                paths.source['sass'] + '/**/*.scss',
                paths.demo['sass'] + '/**/*.scss',
                paths.site['sass'] + '/**/*.scss'])
            .pipe(plugins.sass({
                includePaths: ['bower_components'],
                outputStyle: 'nested'
            }))
            .pipe(plugins.autoprefixer())
            .pipe(gulp.dest(paths.site['css']))
            .pipe(browserSync.reload({stream:true}));
    });

    gulp.task('js-min', function() {
        return gulp.src(paths.source['js'] + '/**/*')
            .pipe(plugins.concat(pkg.name + '.min.js'))
            .pipe(plugins.uglify())
            .pipe(gulp.dest(paths.site['js']));
    });

    gulp.task('js-dev', function() {
        return gulp.src(paths.source['js'] + '/**/*')
            .pipe(plugins.concat(pkg.name + '.js'))
            .pipe(gulp.dest(paths.site['js']));
    });

    gulp.task('js', function(cb) {
        return runSequence(['js-dev','js-min'],
            cb
        );
    });

    gulp.task('browserSync', function() {
        browserSync({
            port: 3456,
            server: {
                baseDir: paths.site['root']
            }
        });
    });

    gulp.task('watch', function() {
        gulp.watch([paths.site['root'], paths.demo['root']], ['create-site']);
        gulp.watch([paths.source['sass'] + '/**/*',paths.demo['sass']], ['sass']);
    });

//    create the _ste directories ready for demo
    gulp.task('create-site-html', function createSite() {
        return gulp.src([paths.demo['root'] + '/index.html',
                paths.demo['root'] +'/_includes/*.html'])
            .pipe(plugins.concat('index.html'))
            .pipe(gulp.dest(paths.site['root']));
    });

    gulp.task('create-site-images', function createSite() {
        return gulp.src(paths.demo['images'] + '/**/*')
            .pipe(gulp.dest(paths.site['images']));
    });

    gulp.task('create-site-fonts', function createSite() {
        return gulp.src([
                paths.source['fonts'] + '/**/*',
                paths.bower['fonts'] + '/**/*.{eot,ttf,woff,svg}'
        ])
            .pipe(plugins.flatten())
            .pipe(gulp.dest(paths.site['fonts']));
    });
    gulp.task('create-site', function createSite() {
        return runSequence(['create-site-html', 'create-site-images', 'create-site-fonts']);
    });

    gulp.task('build', function(cb) {
        return runSequence('clean', 'pre-build', ['create-site','bower'], ['update-docs-version', 'sass', 'js'],'create-bower-dist',
            cb
        );
    });

//remove temporary directors
    gulp.task('clean', function(cb) {
        return plugins.del([
            '.tmp',
            paths.site['root'],
            paths.dist['root']
        ], cb);
    });

//update the version number used within all documentation and html
    gulp.task('update-docs-version-within-md', function(){
        return updateDocs(['README.md']);
    });
    gulp.task('update-docs-version-within-site', function(){
        return updateDocs([paths.site['root'] + '/**/*.html']);
    });
    gulp.task('update-docs-version', function(cb){
        return runSequence(['update-docs-version-within-site', 'update-docs-version-within-md'],cb);
    });
    gulp.task('bump-version', function(cb){
        pkg.version = plugins.semver.inc(pkg.version, options.version);
        return gulp.src('./*.json')
            .pipe(plugins.bump({type: options.version}))
            .pipe(gulp.dest('./'));
    });

    /*
     * Initialising the component
     */
    gulp.task('copy-structure', function(cb) {
        return gulp.src(__dirname + '/component-structure/**/*')
            .pipe(plugins.replace(/{{ component }}/g, pkg.name))
            .pipe(plugins.replace(/{{ git.user }}/g, gitUser))
            .pipe(gulp.dest('./'));
    });
    gulp.task('name-component', function(cb) {
        return gulp.src('./package.json', { base : './' })
            .pipe(plugins.replace(/{{ component }}/g, pkg.name))
            .pipe(plugins.replace(/{{ git.user }}/g, gitUser))
            .pipe(gulp.dest('./'));
    });
    gulp.task('rename-js', function(cb) {
        return gulp.src(['./src/js/main.js'], { base : './' })
            .pipe(plugins.rename(pkg.name + '.js'))
            .pipe(gulp.dest('./src/js/'));
    });
    gulp.task('rename-scss', function(cb) {
        return gulp.src(['./src/scss/main.scss'], { base : './' })
            .pipe(plugins.rename(pkg.name + '.scss'))
            .pipe(gulp.dest('./src/scss/'));
    });
    gulp.task('rename-dot-gitignore', function(cb) {
        return gulp.src('./dot.gitignore', { base : './' })
            .pipe(plugins.rename('.gitignore'))
            .pipe(gulp.dest('./'));
    });
    gulp.task('remove-renamed-files', function(cb) {
        return plugins.del(
            ['./dot.gitignore', './src/js/main.js', './src/scss/main.scss' ],
            cb);
    });
    gulp.task('initMaster', function(cb) {
        return initMaster(cb);
    });
    gulp.task('initGHPages', function(cb) {
        return initGHPages(cb);
    });
    gulp.task('initBower', function(cb) {
        return initBower(cb);
    });

    gulp.task('git-commit-push', function(cb){
        return plugins.run(
                'git commit -am "Version bump for release";' +
                'git push origin master').exec('', cb);
    });

    /*
     * RELEASING
     */

//  RELEASING:  Bower tasks
    gulp.task('create-bower-dist', function() {
        copyDir('site', 'js');
        copyDir('site', 'css');
        copyDir('site', 'sass');
        copyDir('source', 'fonts');
        return copyDir('source', 'sass');
    });

    gulp.task('release:bower', function(cb) {
        return plugins.run(
                'git tag -a v'+ pkg.version +' -m "release v' + pkg.version +' for bower"; ' +
                'git push origin master v'+ pkg.version
        ).exec('', cb);
    });

    gulp.task('bower', function() {
        return plugins.bower()
    });

//  RELEASING:  GH Pages
    gulp.task('release:gh-pages', function () {
        gulp.src(paths.site['root'] + "/**/*")
            .pipe(plugins.ghPages({
                cacheDir: '.tmp'
            })).pipe(gulp.dest('/tmp/gh-pages'));
    });

//  RELEASING:  Amazon Web Services
    gulp.task('release:cdn', function(cb) {
        if (process.env.AWS_SKYGLOBAL_BUCKET && isSkyGlobal()) {
            var awsS3 = plugins.awsS3.setup({bucket: process.env.AWS_SKYGLOBAL_BUCKET});
            awsUpload('css',awsS3);
            awsUpload('js', awsS3);
            awsUpload('fonts', awsS3);
            return awsUpload('icons', awsS3);
        } else {
            console.log('** Amazon S3 skipped **\n' +
                'AWS env variables are not set \n' +
                ' or \n' +
                ' This is not a `skyglobal` repo\n');
            return cb();
        }
    });

    /*
     * Common/public Gulp tasks
     */
    gulp.task('init', function(cb) {
        if (setupHasErrors()){
            return;
        }
        return runSequence(
            'copy-structure',
            ['initMaster','rename-dot-gitignore', 'rename-js', 'rename-scss'],
            ['initGHPages'],
            'remove-renamed-files',
            'initBower', //move with other init once automatic
            cb);
    });

    gulp.task('serve', function(callback) {
        return runSequence(
            'build',
            ['browserSync', 'watch'],
            callback
        );
    });

    gulp.task('release', function(cb) {
        return runSequence(
            'bump-version',
            'build',
            'git-commit-push',
            ['release:bower', 'release:gh-pages', 'release:cdn'],
            cb
        );
    });

    return {
        paths: paths
    }
}

module.exports = gulpTasks;<|endoftext|>


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

var livePort  = Number(process.env.GLSLIFY_LIVE_PORT = 12491)
var answers   = require('./lib/create-answers')
var exmap     = require('./lib/exercise-map')
var live      = require('glslify-live/server')
var exercises = require('./exercises')
var styles    = require('./style')
var opener    = require('opener')
var beefy     = require('beefy')
var chalk     = require('chalk')
var http      = require('http')
var path      = require('path')
var url       = require('url')
var fs        = require('fs')

var mainPort = 12492
var closeWindow = fs.readFileSync(
  path.join(__dirname, 'lib/close-window.html')
)

module.exports = createServer

createServer(process.cwd())

function createServer(root) {
  console.error(fs.readFileSync(
    __dirname + '/intro.txt', 'utf8'
  ))

  live().listen(livePort, function(err) {
    if (err) throw err

    answers(root, function(err) {
      if (err) throw err
      console.error('Done!')
      console.error('Booting up the workshop in your browser in just a second...')
      console.error('')
      setTimeout(loadedAnswers, 1000)
    })
  })

  function loadedAnswers(err) {
    if (err) throw err
    var exNames  = Object.keys(exercises)
    var exLinks  = exNames.map(function(k) { return exercises[k] })
    var exSlugs  = exLinks.map(function(k) { return exmap[k] })
    var exFiles  = exSlugs.map(function(link, i) {
      var dir = path.resolve(root, link)

      return fs.readdirSync(dir).map(function(name) {
        return path.resolve(dir, name)
      })
    })

    var exRoutes = exLinks.map(function(link, i) {
      return require('./exercises/' + link + '/server.js')(exFiles[i])
    })

    var menu = beefy({
        cwd: path.join(__dirname, 'menu')
      , entries: ['index.js']
      , quiet: false
      , watchify: false
    })

    http.createServer(function(req, res) {
      var uri = url.parse(req.url).pathname
      var paths = uri.split('/').filter(Boolean)

      if (uri === '/style.css') {
        res.setHeader('content-type', 'text/css')
        res.end(styles())
        return
      }

      if (paths[0] === 'open') {
        var exPath = exmap[paths[1]]
        if (exPath) {
          opener(path.join(root, exPath))
        }
        return res.end(closeWindow)
      }

      for (var i = 0; i < exLinks.length; i++) {
        if (uri.indexOf(exLinks[i]) === 1) {
          req.url = req.url
            .replace(exLinks[i], '')
            .replace(/\/+/g, '/')

          return exRoutes[i](req, res)
        }
      }

      return menu(req, res)
    }).listen(mainPort, function(err) {
      if (err) throw err

      var url = 'http://localhost:'+mainPort
      opener(url)
      console.log(chalk.yellow('WORKSHOP URL:'), chalk.underline.blue(url))
      console.log()
    })
  }
}
<commit_msg>Force addition of a query string for server routes<commit_after>#!/usr/bin/env node

var livePort  = Number(process.env.GLSLIFY_LIVE_PORT = 12491)
var answers   = require('./lib/create-answers')
var exmap     = require('./lib/exercise-map')
var live      = require('glslify-live/server')
var exercises = require('./exercises')
var styles    = require('./style')
var opener    = require('opener')
var beefy     = require('beefy')
var chalk     = require('chalk')
var http      = require('http')
var path      = require('path')
var url       = require('url')
var fs        = require('fs')

var mainPort = 12492
var closeWindow = fs.readFileSync(
  path.join(__dirname, 'lib/close-window.html')
)

module.exports = createServer

createServer(process.cwd())

function createServer(root) {
  console.error(fs.readFileSync(
    __dirname + '/intro.txt', 'utf8'
  ))

  live().listen(livePort, function(err) {
    if (err) throw err

    answers(root, function(err) {
      if (err) throw err
      console.error('Done!')
      console.error('Booting up the workshop in your browser in just a second...')
      console.error('')
      setTimeout(loadedAnswers, 1000)
    })
  })

  function loadedAnswers(err) {
    if (err) throw err
    var exNames  = Object.keys(exercises)
    var exLinks  = exNames.map(function(k) { return exercises[k] })
    var exSlugs  = exLinks.map(function(k) { return exmap[k] })
    var exFiles  = exSlugs.map(function(link, i) {
      var dir = path.resolve(root, link)

      return fs.readdirSync(dir).map(function(name) {
        return path.resolve(dir, name)
      })
    })

    var exRoutes = exLinks.map(function(link, i) {
      return require('./exercises/' + link + '/server.js')(exFiles[i])
    })

    var menu = beefy({
        cwd: path.join(__dirname, 'menu')
      , entries: ['index.js']
      , quiet: false
      , watchify: false
    })

    http.createServer(function(req, res) {
      // Force the addition of a query string. This
      // works around an issue in beefy until it gets fixed:
      // https://github.com/stackgl/shader-school/issues/107
      req.url = req.url.indexOf('?') === -1
        ? req.url + '?'
        : req.url

      var uri = url.parse(req.url).pathname
      var paths = uri.split('/').filter(Boolean)

      if (uri === '/style.css') {
        res.setHeader('content-type', 'text/css')
        res.end(styles())
        return
      }

      if (paths[0] === 'open') {
        var exPath = exmap[paths[1]]
        if (exPath) {
          opener(path.join(root, exPath))
        }
        return res.end(closeWindow)
      }

      for (var i = 0; i < exLinks.length; i++) {
        if (uri.indexOf(exLinks[i]) === 1) {
          req.url = req.url
            .replace(exLinks[i], '')
            .replace(/\/+/g, '/')

          return exRoutes[i](req, res)
        }
      }

      return menu(req, res)
    }).listen(mainPort, function(err) {
      if (err) throw err

      var url = 'http://localhost:'+mainPort
      opener(url)
      console.log(chalk.yellow('WORKSHOP URL:'), chalk.underline.blue(url))
      console.log()
    })
  }
}
<|endoftext|>