<commit_before>// PORTAL DETAILS TOOLS //////////////////////////////////////////////
// hand any of these functions the details-hash of a portal, and they
// will return useful, but raw data.

// returns a float. Displayed portal level is always rounded down from
// that value.
window.getPortalLevel = function(d) {
  var lvl = 0;
  var hasReso = false;
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso) return true;
    lvl += parseInt(reso.level);
    hasReso = true;
  });
  return hasReso ? Math.max(1, lvl/8) : 0;
}

window.getTotalPortalEnergy = function(d) {
  var nrg = 0;
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso) return true;
    var level = parseInt(reso.level);
    var max = RESO_NRG[level];
    nrg += max;
  });
  return nrg;
}

// For backwards compatibility
window.getPortalEnergy = window.getTotalPortalEnergy;

window.getCurrentPortalEnergy = function(d) {
  var nrg = 0;
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso) return true;
    nrg += parseInt(reso.energyTotal);
  });
  return nrg;
}

window.getPortalRange = function(d) {
  // formula by the great gals and guys at
  // http://decodeingress.me/2012/11/18/ingress-portal-levels-and-link-range/

  var lvl = 0;
  var resoMissing = false;
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso) {
      resoMissing = true;
      return false;
    }
    lvl += parseInt(reso.level);
  });
  if(resoMissing) return 0;

  var range = 160*Math.pow(getPortalLevel(d), 4);

  var boost = getLinkAmpRangeBoost(d);

  return range*boost;

}

window.getLinkAmpRangeBoost = function(d) {
  // additional range boost calculation
  // (at the time of writing, only rare link amps have been seen in the wild, so there's a little guesswork at how
  // the stats work and combine - jon 2013-06-26)

  // link amps scale: first is full, second half, the last two a quarter
  var scale = [1.0, 0.5, 0.25, 0.25];

  var boost = 1.0;  // initial boost is 1.0 (i.e. no boost over standard range)
  var count = 0;

  $.each(d.portalV2.linkedModArray, function(ind, mod) {
    if(mod && mod.type === 'LINK_AMPLIFIER' && mod.stats && mod.stats.LINK_RANGE_MULTIPLIER) {
      // link amp stat LINK_RANGE_MULTIPLIER is 2000 for rare, and gives 2x boost to the range
      var baseMultiplier = mod.stats.LINK_RANGE_MULTIPLIER/1000;
      boost += (baseMultiplier-1)*scale[count];
      count++;
    }
  });

  return boost;
}

window.getAvgResoDist = function(d) {
  var sum = 0, resos = 0;
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso) return true;
    sum += parseInt(reso.distanceToPortal);
    resos++;
  });
  return resos ? sum/resos : 0;
}

window.getAttackApGain = function(d) {
  var resoCount = 0;
  var maxResonators = MAX_RESO_PER_PLAYER.slice(0);
  var curResonators = [ 0, 0, 0, 0, 0, 0, 0, 0, 0];

  for(var n = PLAYER.level + 1; n < 9; n++) {
    maxResonators[n] = 0;
  }
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso)
      return true;
    resoCount += 1;
    var reslevel=parseInt(reso.level);
    if(reso.ownerGuid === PLAYER.guid) {
      if(maxResonators[reslevel] > 0) {
        maxResonators[reslevel] -= 1;
      }
    } else {
      curResonators[reslevel] += 1;
    }
  });

  var linkCount = d.portalV2.linkedEdges ? d.portalV2.linkedEdges.length : 0;
  var fieldCount = d.portalV2.linkedFields ? d.portalV2.linkedFields.length : 0;

  var resoAp = resoCount * DESTROY_RESONATOR;
  var linkAp = linkCount * DESTROY_LINK;
  var fieldAp = fieldCount * DESTROY_FIELD;
  var destroyAp = resoAp + linkAp + fieldAp;
  var captureAp = CAPTURE_PORTAL + 8 * DEPLOY_RESONATOR + COMPLETION_BONUS;
  var enemyAp = destroyAp + captureAp;
  var deployCount = 8 - resoCount;
  var completionAp = (deployCount > 0) ? COMPLETION_BONUS : 0;
  var upgradeCount = 0;
  var upgradeAvailable = maxResonators[8];
  for(var n = 7; n >= 0; n--) {
    upgradeCount += curResonators[n];
    if(upgradeAvailable < upgradeCount) {
        upgradeCount -= (upgradeCount - upgradeAvailable);
    }
    upgradeAvailable += maxResonators[n];
  }
  var friendlyAp = deployCount * DEPLOY_RESONATOR + upgradeCount * UPGRADE_ANOTHERS_RESONATOR + completionAp;
  return {
    friendlyAp: friendlyAp,
    deployCount: deployCount,
    upgradeCount: upgradeCount,
    enemyAp: enemyAp,
    destroyAp: destroyAp,
    resoAp: resoAp,
    captureAp: captureAp
  };
}

//This function will return the potential level a player can upgrade it to
window.potentialPortalLevel = function(d) {
  var current_level = getPortalLevel(d);
  var potential_level = current_level;

  if(PLAYER.team === d.controllingTeam.team) {
    var resonators_on_portal = d.resonatorArray.resonators;
    var resonator_levels = new Array();
    // figure out how many of each of these resonators can be placed by the player
    var player_resontators = new Array();
    for(var i=1;i<=MAX_PORTAL_LEVEL; i++) {
      player_resontators[i] = i > PLAYER.level ? 0 : MAX_RESO_PER_PLAYER[i];
    }
    $.each(resonators_on_portal, function(ind, reso) {
      if(reso !== null && reso.ownerGuid === window.PLAYER.guid) {
        player_resontators[reso.level]--;
      }
      resonator_levels.push(reso === null ? 0 : reso.level);
    });

    resonator_levels.sort(function(a, b) {
      return(a - b);
    });

    // Max out portal
    var install_index = 0;
    for(var i=MAX_PORTAL_LEVEL;i>=1; i--) {
      for(var install = player_resontators[i]; install>0; install--) {
        if(resonator_levels[install_index] < i) {
          resonator_levels[install_index] = i;
          install_index++;
        }
      }
    }
    //console.log(resonator_levels);
    potential_level = resonator_levels.reduce(function(a, b) {return a + b;}) / 8;
  }
  return(potential_level);
}

window.getPortalImageUrl = function(d) {
  if (d.imageByUrl && d.imageByUrl.imageUrl) {
    url = d.imageByUrl.imageUrl;

    if (window.location.protocol === 'https:') {
      url = url.indexOf('www.panoramio.com') !== -1
            ? url.replace(/^http:\/\/www/, 'https://ssl').replace('small', 'medium')
            : url.replace(/^http:\/\//, '//');
    }
    return url;
  } else {
    return DEFAULT_PORTAL_IMG;
  }

}
<commit_msg>utility functions to - get mods from portal details, filtered by type and sorted by strength - get mitigation values TODO: convert existing plugins to use these new functions<commit_after>// PORTAL DETAILS TOOLS //////////////////////////////////////////////
// hand any of these functions the details-hash of a portal, and they
// will return useful, but raw data.

// returns a float. Displayed portal level is always rounded down from
// that value.
window.getPortalLevel = function(d) {
  var lvl = 0;
  var hasReso = false;
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso) return true;
    lvl += parseInt(reso.level);
    hasReso = true;
  });
  return hasReso ? Math.max(1, lvl/8) : 0;
}

window.getTotalPortalEnergy = function(d) {
  var nrg = 0;
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso) return true;
    var level = parseInt(reso.level);
    var max = RESO_NRG[level];
    nrg += max;
  });
  return nrg;
}

// For backwards compatibility
window.getPortalEnergy = window.getTotalPortalEnergy;

window.getCurrentPortalEnergy = function(d) {
  var nrg = 0;
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso) return true;
    nrg += parseInt(reso.energyTotal);
  });
  return nrg;
}

window.getPortalRange = function(d) {
  // formula by the great gals and guys at
  // http://decodeingress.me/2012/11/18/ingress-portal-levels-and-link-range/

  var lvl = 0;
  var resoMissing = false;
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso) {
      resoMissing = true;
      return false;
    }
    lvl += parseInt(reso.level);
  });
  if(resoMissing) return 0;

  var range = 160*Math.pow(getPortalLevel(d), 4);

  var boost = getLinkAmpRangeBoost(d);

  return range*boost;

}

window.getLinkAmpRangeBoost = function(d) {
  // additional range boost calculation
  // (at the time of writing, only rare link amps have been seen in the wild, so there's a little guesswork at how
  // the stats work and combine - jon 2013-06-26)

  // link amps scale: first is full, second half, the last two a quarter
  var scale = [1.0, 0.5, 0.25, 0.25];

  var boost = 1.0;  // initial boost is 1.0 (i.e. no boost over standard range)
  var count = 0;

  $.each(d.portalV2.linkedModArray, function(ind, mod) {
    if(mod && mod.type === 'LINK_AMPLIFIER' && mod.stats && mod.stats.LINK_RANGE_MULTIPLIER) {
      // link amp stat LINK_RANGE_MULTIPLIER is 2000 for rare, and gives 2x boost to the range
      var baseMultiplier = mod.stats.LINK_RANGE_MULTIPLIER/1000;
      boost += (baseMultiplier-1)*scale[count];
      count++;
    }
  });

  return boost;
}

window.getAvgResoDist = function(d) {
  var sum = 0, resos = 0;
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso) return true;
    sum += parseInt(reso.distanceToPortal);
    resos++;
  });
  return resos ? sum/resos : 0;
}

window.getAttackApGain = function(d) {
  var resoCount = 0;
  var maxResonators = MAX_RESO_PER_PLAYER.slice(0);
  var curResonators = [ 0, 0, 0, 0, 0, 0, 0, 0, 0];

  for(var n = PLAYER.level + 1; n < 9; n++) {
    maxResonators[n] = 0;
  }
  $.each(d.resonatorArray.resonators, function(ind, reso) {
    if(!reso)
      return true;
    resoCount += 1;
    var reslevel=parseInt(reso.level);
    if(reso.ownerGuid === PLAYER.guid) {
      if(maxResonators[reslevel] > 0) {
        maxResonators[reslevel] -= 1;
      }
    } else {
      curResonators[reslevel] += 1;
    }
  });

  var linkCount = d.portalV2.linkedEdges ? d.portalV2.linkedEdges.length : 0;
  var fieldCount = d.portalV2.linkedFields ? d.portalV2.linkedFields.length : 0;

  var resoAp = resoCount * DESTROY_RESONATOR;
  var linkAp = linkCount * DESTROY_LINK;
  var fieldAp = fieldCount * DESTROY_FIELD;
  var destroyAp = resoAp + linkAp + fieldAp;
  var captureAp = CAPTURE_PORTAL + 8 * DEPLOY_RESONATOR + COMPLETION_BONUS;
  var enemyAp = destroyAp + captureAp;
  var deployCount = 8 - resoCount;
  var completionAp = (deployCount > 0) ? COMPLETION_BONUS : 0;
  var upgradeCount = 0;
  var upgradeAvailable = maxResonators[8];
  for(var n = 7; n >= 0; n--) {
    upgradeCount += curResonators[n];
    if(upgradeAvailable < upgradeCount) {
        upgradeCount -= (upgradeCount - upgradeAvailable);
    }
    upgradeAvailable += maxResonators[n];
  }
  var friendlyAp = deployCount * DEPLOY_RESONATOR + upgradeCount * UPGRADE_ANOTHERS_RESONATOR + completionAp;
  return {
    friendlyAp: friendlyAp,
    deployCount: deployCount,
    upgradeCount: upgradeCount,
    enemyAp: enemyAp,
    destroyAp: destroyAp,
    resoAp: resoAp,
    captureAp: captureAp
  };
}

//This function will return the potential level a player can upgrade it to
window.potentialPortalLevel = function(d) {
  var current_level = getPortalLevel(d);
  var potential_level = current_level;

  if(PLAYER.team === d.controllingTeam.team) {
    var resonators_on_portal = d.resonatorArray.resonators;
    var resonator_levels = new Array();
    // figure out how many of each of these resonators can be placed by the player
    var player_resontators = new Array();
    for(var i=1;i<=MAX_PORTAL_LEVEL; i++) {
      player_resontators[i] = i > PLAYER.level ? 0 : MAX_RESO_PER_PLAYER[i];
    }
    $.each(resonators_on_portal, function(ind, reso) {
      if(reso !== null && reso.ownerGuid === window.PLAYER.guid) {
        player_resontators[reso.level]--;
      }
      resonator_levels.push(reso === null ? 0 : reso.level);
    });

    resonator_levels.sort(function(a, b) {
      return(a - b);
    });

    // Max out portal
    var install_index = 0;
    for(var i=MAX_PORTAL_LEVEL;i>=1; i--) {
      for(var install = player_resontators[i]; install>0; install--) {
        if(resonator_levels[install_index] < i) {
          resonator_levels[install_index] = i;
          install_index++;
        }
      }
    }
    //console.log(resonator_levels);
    potential_level = resonator_levels.reduce(function(a, b) {return a + b;}) / 8;
  }
  return(potential_level);
}

window.getPortalImageUrl = function(d) {
  if (d.imageByUrl && d.imageByUrl.imageUrl) {
    url = d.imageByUrl.imageUrl;

    if (window.location.protocol === 'https:') {
      url = url.indexOf('www.panoramio.com') !== -1
            ? url.replace(/^http:\/\/www/, 'https://ssl').replace('small', 'medium')
            : url.replace(/^http:\/\//, '//');
    }
    return url;
  } else {
    return DEFAULT_PORTAL_IMG;
  }

}

window.getPortalModsByType = function(d, type) {
  var mods = [];

  $.each(d.portalV2.linkedModArray || [], function(i,mod) {
    if (mod && mod.type == type) mods.push(mod);
  });

  var sortKey = {
    RES_SHIELD: 'MITIGATION',
    FORCE_AMP: 'FORCE_AMPLIFIER',
    TURRET: 'HIT_BONUS',  // and/or ATTACK_FREQUENCY??
    HEATSINK: 'HACK_SPEED',
    MULTIHACK: 'BURNOUT_INSULATION',
    LINK_AMPLIFIER: 'LINK_RANGE_MULTIPLIER'
  };

  // prefer to sort mods by stat - so if stats change (as they have for shields and turrets) we still put the highest first
  if (sortKey[type]) {
    // we have a stat type to sort by
    var key = sortKey[type];

    mods.sort (function(a,b) {
      return b.stats[key] - a.stats[key];
    });
  } else {
    // no known stat type - sort by rarity
    mods.sort (function(a,b) {
      // rarity values are COMMON, RARE and VERY_RARE. handy, as that's alphabetical order!
      if (a.rarity < b.rarity) return -1;
      if (a.rarity > b.rarity) return 1;
      return 0;
    });
  }

  return mods;
}

window.getPortalShieldMitigation = function(d) {
  var shields = getPortalModsByType(d, 'RES_SHIELD');

  var mitigation = 0;
  $.each(shields, function(i,s) {
    mitigation += parseInt(s.stats.MITIGATION);
  });

  return mitigation;
}

window.getPortalLinksMitigation = function(d) {
  var links = (d.portalV2.linkedEdges||[]).length;
  var mitigation = Math.round(400/9*Math.atan(links/Math.E));
  return mitigation;
}

window.getPortalMitigationDetails = function(d) {
  var mitigation = {
    shields: getPortalShieldMitigation(d),
    links: getPortalLinksMitigation(d)
  };

  // mitigation is limited to 95% (as confirmed by Brandon Badger on G+)
  mitigation.total = Math.min(95, mitigation.shields+mitigation.links);

  mitigation.excess = (mitigation.shields+mitigation.links) - mitigation.total;

  return mitigation;
}
<|endoftext|>


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

const path = require('path');
const fs = require('fs');
const url = require('url');
const program = require('commander');
const package = require('../package.json');
const fetch = require('../lib/fetch');
const Server = require('../lib/Server');

/**
 * Create a server instance using the provided options.
 * @param  {Object} opts react-native-webpack-server options
 * @return {Server}      react-native-webpack-server server
 */
function createServer(opts) {
  opts.webpackConfigPath = path.resolve(process.cwd(), opts.webpackConfigPath);
  if (fs.existsSync(opts.webpackConfigPath)) {
    opts.webpackConfig = require(path.resolve(process.cwd(), opts.webpackConfigPath));
  } else {
    throw new Error('Must specify webpackConfigPath or create ./webpack.config.js');
  }
  delete opts.webpackConfigPath;

  const server = new Server(opts);
  return server;
}

function commonOptions(program) {
  return program
    .option(
      '-H, --hostname [hostname]',
      'Hostname on which the server will listen. [localhost]',
      'localhost'
    )
    .option(
      '-P, --port [port]',
      'Port on which the server will listen. [8080]',
      8080
    )
    .option(
      '-p, --packagerPort [port]',
      'Port on which the react-native packager will listen. [8081]',
      8081
    )
    .option(
      '-w, --webpackPort [port]',
      'Port on which the webpack dev server will listen. [8082]',
      8082
    )
    .option(
      '-c, --webpackConfigPath [path]',
      'Path to the webpack configuration file. [webpack.config.js]',
      'webpack.config.js'
    )
    .option(
      '-e, --entry [name]',
      'Webpack entry module. [index.ios]',
      'index.ios'
    );
}

program.version(package.version);

commonOptions(program.command('start'))
  .description('Start the webpack server.')
  .option('-r, --hot', 'Enable hot module replacement. [false]', false)
  .action(function(options) {
    const opts = options.opts();
    const server = createServer(opts);
    server.start();
  });

commonOptions(program.command('bundle'))
  .description('Bundle the app for distribution.')
  .option(
    '-b, --bundlePath [path]',
    'Path where the bundle should be written. [./iOS/main.jsbundle]',
    './iOS/main.jsbundle'
  )
  .option(
    '--no-optimize',
    'Whether the bundle should skip optimization. [false]',
    false
  )
  .option(
    '--platform',
    'The platform for which to create the bundle. [ios]',
    'ios'
  )
  .action(function(options) {
    const opts = options.opts();
    const server = createServer(opts);
    const query = opts.optimize ? {dev: false, minify: true} : {};
    query.platform = opts.platform || 'ios';
    const bundleUrl = url.format({
      protocol: 'http',
      hostname: 'localhost',
      port: opts.port,
      pathname: 'index.ios.bundle',
      query: query,
    });
    const targetPath = path.resolve(opts.bundlePath);

    server.start();

    fetch(bundleUrl).then(function(content) {
      fs.writeFileSync(targetPath, content);
      server.stop();

      // XXX: Hack something is keeping the process alive but we can still
      // safely kill here without leaving processes hanging around...
      process.exit(0);
    }).catch(function(err) {
      console.log('Error creating bundle...', err.stack);
      server.stop();
    });
  });

program.parse(process.argv);
<commit_msg>Combine bundle query parameters<commit_after>#!/usr/bin/env node

const path = require('path');
const fs = require('fs');
const url = require('url');
const program = require('commander');
const package = require('../package.json');
const fetch = require('../lib/fetch');
const Server = require('../lib/Server');

/**
 * Create a server instance using the provided options.
 * @param  {Object} opts react-native-webpack-server options
 * @return {Server}      react-native-webpack-server server
 */
function createServer(opts) {
  opts.webpackConfigPath = path.resolve(process.cwd(), opts.webpackConfigPath);
  if (fs.existsSync(opts.webpackConfigPath)) {
    opts.webpackConfig = require(path.resolve(process.cwd(), opts.webpackConfigPath));
  } else {
    throw new Error('Must specify webpackConfigPath or create ./webpack.config.js');
  }
  delete opts.webpackConfigPath;

  const server = new Server(opts);
  return server;
}

function commonOptions(program) {
  return program
    .option(
      '-H, --hostname [hostname]',
      'Hostname on which the server will listen. [localhost]',
      'localhost'
    )
    .option(
      '-P, --port [port]',
      'Port on which the server will listen. [8080]',
      8080
    )
    .option(
      '-p, --packagerPort [port]',
      'Port on which the react-native packager will listen. [8081]',
      8081
    )
    .option(
      '-w, --webpackPort [port]',
      'Port on which the webpack dev server will listen. [8082]',
      8082
    )
    .option(
      '-c, --webpackConfigPath [path]',
      'Path to the webpack configuration file. [webpack.config.js]',
      'webpack.config.js'
    )
    .option(
      '-e, --entry [name]',
      'Webpack entry module. [index.ios]',
      'index.ios'
    );
}

program.version(package.version);

commonOptions(program.command('start'))
  .description('Start the webpack server.')
  .option('-r, --hot', 'Enable hot module replacement. [false]', false)
  .action(function(options) {
    const opts = options.opts();
    const server = createServer(opts);
    server.start();
  });

commonOptions(program.command('bundle'))
  .description('Bundle the app for distribution.')
  .option(
    '-b, --bundlePath [path]',
    'Path where the bundle should be written. [./iOS/main.jsbundle]',
    './iOS/main.jsbundle'
  )
  .option(
    '--no-optimize',
    'Whether the bundle should skip optimization. [false]',
    false
  )
  .option(
    '--platform',
    'The platform for which to create the bundle. [ios]',
    'ios'
  )
  .action(function(options) {
    const opts = options.opts();
    const server = createServer(opts);
    const query = {
      dev: !opts.optimize,
      minify: opts.optimize,
      platform: opts.platform,
    };
    const bundleUrl = url.format({
      protocol: 'http',
      hostname: 'localhost',
      port: opts.port,
      pathname: 'index.ios.bundle',
      query: query,
    });
    const targetPath = path.resolve(opts.bundlePath);

    server.start();

    fetch(bundleUrl).then(function(content) {
      fs.writeFileSync(targetPath, content);
      server.stop();

      // XXX: Hack something is keeping the process alive but we can still
      // safely kill here without leaving processes hanging around...
      process.exit(0);
    }).catch(function(err) {
      console.log('Error creating bundle...', err.stack);
      server.stop();
    });
  });

program.parse(process.argv);
<|endoftext|>


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

var program = require("commander");
var inspect = require("util").inspect;
var colors = require("colors");
var path = require("path");
var _ = require("underscore");

var Config = require("../lib/Config");
var Host = require("../lib/Host");
var Deploy = require("../lib/Deploy");
var Service = require("../lib/Service");

console.log( ("\nRockUp".green.bold + ": Faceted Meteor Deployments".green).underline );

/** Define RockUp CLI **/
program
  .version("0.0.1")
  .description("Faceted deployment and configuration management for Meteor applications");

/** list: List all of the target environments available locally **/
program
  .command("list")
  .description("List target environments available")
  .action( function () {
    console.log("Available Environments:");
    _.each( Config.list(), function(envName) {
      console.log(" -", envName);
    });
  });

/** lint: Lint a configuration file **/
program
  .command("lint <environment>")
  .description("Check configuration file for issues")
  .action( function(env, cliOptions) {
    var filePath = path.resolve( process.cwd(), 'deploy', env+'.rockup.json' );
    var config = new Config(filePath);
    console.log("Configuration:\n", inspect(config, {colors:true, depth:null}));

    console.log("app:", config.app);
    console.log("appName:", config.app.name);
    console.log("appPath:", config.app.path);
    console.log("hosts.list:", config.hosts.list);
    console.log("hosts.names:", config.hosts.names);
    console.log("host.get():", config.hosts.get('dev2.emmerge.com'));
    console.log("host.sshOptions():", config.hosts.get('dev2.emmerge.com').sshConfig());
    console.log("services:", config.services('dev2.emmerge.com'));
    console.log("service:", config.service('dev2.emmerge.com', 'bennett-1'));

    console.log("host.services.tasks.status:", config.hosts.get('dev2.emmerge.com').services.tasks.status());
  });

/** init: Initializes local configuration **/
program
  .command("init <environment>")
  .description("Initialize a local configuration")
  .option("--upstart", "Add upstart configuration template")
  .option("--nginx", "Add nginx configuration template")
  .action( function(env, options) {
    console.log("Creating local rockup configs for ", env.cyan, "environment");
    var files = ['rockup','meteor'];  // upstart, nginx
    if (options.upstart) files.push('upstart');
    if (options.nginx) files.push('nginx');
    Config.initialize(env, files);
  });

/** prepare: Preps server to accept deployments **/
program
  .command("prepare <environment>")
  .alias("prep")
  .description("Prepare a server host to accept deployments")
  .action( function(env, options) {
    var config = new Config(env);
    var hostNames = config.hostNames();
    console.log("Will prepare "+hostNames.length+" host(s) for deployment:", inspect(hostNames));
    _.each( hostNames, function(hostName) {
      var host = new Host(config, hostName);
      host.prepare( _endCommandCallback("Preparation") );
    });
  });

/** deploy: Push code and configuration to server(s) **/
program
  .command("deploy <environment>")
  .alias("push")
  .description("Deploy application to environment")
  .option("--host <name>", "The specific host to target")
  .option("--bundle <path>", "Deploy a bundle.tar.gz already in-hand")
  .action( function(env, cliOptions) {
      var config = new Config(env);
      cliOptions = cliOptions || {};
      var options = {};
      if ( cliOptions.host )
        options.hosts = [cliOptions.host];            // Target a single host
      if ( cliOptions.bundle )
        options.bundle = cliOptions.bundle;           // Use an already-tarred app bundle
      var deployment = new Deploy(config, options);
      deployment.push( _endCommandCallback("Deployment") );
  });

/** rollback: Roll server back to a previously deployed version **/
program
  .command("rollback <environment>")
  .alias("undo")
  .description("Rollback to a previous deployment")
  .option("-r, --release <name>", "Name of release to roll back to (defaults to previous)")
  .action( function(env, options) {
    var targetRelease = options.release;
    if (! targetRelease) {
      targetRelease = "previous";     // TODO: Retrieve most recent release from history
    }
    console.log( "Will rollback to".red, targetRelease.red.bold.underline, "release.".red );
    var config = new Config(env);
    //Deploy.rollback(config);
  });

/** reconfig: Push only configuration changes and restart **/
program
  .command("reconfig <environment>")
  .description("Push configuration only and restart");

/** start, stop, restart: Run start, stop, restart commands against services **/
_.each(["start", "stop", "restart"], function(command) {
  program
    .command(command+" <environment>")
    .option("--host <name>", "The specific host to target")
    .option("--service <name>", "The specific service to target")
    .action( function(env, cliOptions) {
      console.log(command+" the service in "+env);
    });
});

/** status: Dislay status informatin for services **/
program
  .command("status <environment>")
  .description("Display a status for services in environment")
  .option("--host <name>", "A specific host to target")
  .option("--service <name>", "A specific service to target")
  .action( function(env, cliOptions) {
    var config = new Config(env);
    if ( cliOptions.host ) {
      var host = new Host(config, cliOptions.host);
      console.log("Working on host:", inspect(host));
      host.status( function(err, results) {
        if (err) { _endCommandCallback(err); }
        else {
          console.log("Status results:", inspect(results, {colors:true}));
          process.exit(0);
        }
      });

    } else {
      console.log("Can't do it for everyone, yet. Pass a --host");
    }

  });

/** logs: Tail service logs from hosts **/
program
  .command("logs <environment>")
  .description("Tail service logs");

/** history: Retrieve list of deployment history available on hosts **/
program
  .command("history <environment>")
  .alias("hist")
  .description("Deployment history");

/** Catch-all for unhandled commands: **/
program
  .command("*", null, {noHelp: true})
  .action( function(command, options) {
    var commandDef = _.findWhere(program.commands, {_name: command});
    if (commandDef)
      console.log("Command", command.underline, "not yet implemented");
    else {
      console.log("No such command", command.underline);
      process.exit(1);
    }
  });

program.parse(process.argv);

/**
 * Generate a callback function to be used in the CLI context as a
 * callback passed to delayed result commands. The returned function
 * accepts error as the first argument and exits the process with
 * a error code of non-zero for error, zero for success.
 *
 * @param {String} commandName      Name to use in status messages
 * @returns {Function}              Callback
 **/
function _endCommandCallback (commandName) {
  return function(err) {
    if (err) {
      console.log( (commandName+" failed:").red.bold, inspect(err).red );
      process.exit(1);
    }
    else {
      console.log( (commandName+" succeeded!").green.bold );
      process.exit(0);
    }
  };
}
<commit_msg>Move file path for config into bin<commit_after>#!/usr/bin/env node

var program = require("commander");
var inspect = require("util").inspect;
var colors = require("colors");
var path = require("path");
var _ = require("underscore");

var Config = require("../lib/Config");
var Host = require("../lib/Host");
var Deploy = require("../lib/Deploy");
var Service = require("../lib/Service");

console.log( ("\nRockUp".green.bold + ": Faceted Meteor Deployments".green).underline );

/** Define RockUp CLI **/
program
  .version("0.0.1")
  .description("Faceted deployment and configuration management for Meteor applications");

/** list: List all of the target environments available locally **/
program
  .command("list")
  .description("List target environments available")
  .action( function () {
    console.log("Available Environments:");
    _.each( Config.list(), function(envName) {
      console.log(" -", envName);
    });
  });

/** lint: Lint a configuration file **/
program
  .command("lint <environment>")
  .description("Check configuration file for issues")
  .action( function(env, cliOptions) {
    var config = _loadLocalConfigFile(env);
    console.log("Configuration:\n", inspect(config, {colors:true, depth:null}));

    console.log("app:", config.app);
    console.log("appName:", config.app.name);
    console.log("appPath:", config.app.path);
    console.log("hosts.list:", config.hosts.list);
    console.log("hosts.names:", config.hosts.names);
    console.log("host.get():", config.hosts.get('dev2.emmerge.com'));
    console.log("host.sshOptions():", config.hosts.get('dev2.emmerge.com').sshConfig());
    console.log("services:", config.services('dev2.emmerge.com'));
    console.log("service:", config.service('dev2.emmerge.com', 'bennett-1'));

    console.log("host.services.tasks.status:", config.hosts.get('dev2.emmerge.com').services.tasks.status());
  });

/** init: Initializes local configuration **/
program
  .command("init <environment>")
  .description("Initialize a local configuration")
  .option("--upstart", "Add upstart configuration template")
  .option("--nginx", "Add nginx configuration template")
  .action( function(env, options) {
    console.log("Creating local rockup configs for ", env.cyan, "environment");
    var files = ['rockup','meteor'];  // upstart, nginx
    if (options.upstart) files.push('upstart');
    if (options.nginx) files.push('nginx');
    Config.initialize(env, files);
  });

/** prepare: Preps server to accept deployments **/
program
  .command("prepare <environment>")
  .alias("prep")
  .description("Prepare a server host to accept deployments")
  .action( function(env, options) {
    var config = _loadLocalConfigFile(env);
    var hostNames = config.hostNames();
    console.log("Will prepare "+hostNames.length+" host(s) for deployment:", inspect(hostNames));
    _.each( hostNames, function(hostName) {
      var host = new Host(config, hostName);
      host.prepare( _endCommandCallback("Preparation") );
    });
  });

/** deploy: Push code and configuration to server(s) **/
program
  .command("deploy <environment>")
  .alias("push")
  .description("Deploy application to environment")
  .option("--host <name>", "The specific host to target")
  .option("--bundle <path>", "Deploy a bundle.tar.gz already in-hand")
  .action( function(env, cliOptions) {
      var config = _loadLocalConfigFile(env);
      cliOptions = cliOptions || {};
      var options = {};
      if ( cliOptions.host )
        options.hosts = [cliOptions.host];            // Target a single host
      if ( cliOptions.bundle )
        options.bundle = cliOptions.bundle;           // Use an already-tarred app bundle
      var deployment = new Deploy(config, options);
      deployment.push( _endCommandCallback("Deployment") );
  });

/** rollback: Roll server back to a previously deployed version **/
program
  .command("rollback <environment>")
  .alias("undo")
  .description("Rollback to a previous deployment")
  .option("-r, --release <name>", "Name of release to roll back to (defaults to previous)")
  .action( function(env, options) {
    var targetRelease = options.release;
    if (! targetRelease) {
      targetRelease = "previous";     // TODO: Retrieve most recent release from history
    }
    console.log( "Will rollback to".red, targetRelease.red.bold.underline, "release.".red );
    var config = new _loadLocalConfigFile(env);
    //Deploy.rollback(config);
  });

/** reconfig: Push only configuration changes and restart **/
program
  .command("reconfig <environment>")
  .description("Push configuration only and restart");

/** start, stop, restart: Run start, stop, restart commands against services **/
_.each(["start", "stop", "restart"], function(command) {
  program
    .command(command+" <environment>")
    .option("--host <name>", "The specific host to target")
    .option("--service <name>", "The specific service to target")
    .action( function(env, cliOptions) {
      var config = _loadLocalConfigFile(env);
    });
});

/** status: Dislay status informatin for services **/
program
  .command("status <environment>")
  .description("Display a status for services in environment")
  .option("--host <name>", "A specific host to target")
  .option("--service <name>", "A specific service to target")
  .action( function(env, cliOptions) {
    var config = _loadLocalConfigFile(env);
    if ( cliOptions.host ) {
      var host = new Host(config, cliOptions.host);
      console.log("Working on host:", inspect(host));
      host.status( function(err, results) {
        if (err) { _endCommandCallback(err); }
        else {
          console.log("Status results:", inspect(results, {colors:true}));
          process.exit(0);
        }
      });

    } else {
      console.log("Can't do it for everyone, yet. Pass a --host");
    }

  });

/** logs: Tail service logs from hosts **/
program
  .command("logs <environment>")
  .description("Tail service logs");

/** history: Retrieve list of deployment history available on hosts **/
program
  .command("history <environment>")
  .alias("hist")
  .description("Deployment history");

/** Catch-all for unhandled commands: **/
program
  .command("*", null, {noHelp: true})
  .action( function(command, options) {
    var commandDef = _.findWhere(program.commands, {_name: command});
    if (commandDef)
      console.log("Command", command.underline, "not yet implemented");
    else {
      console.log("No such command", command.underline);
      process.exit(1);
    }
  });

program.parse(process.argv);

/**
 * Load RockUp configuration file from the expected path relative to
 * this process' working directory.
 *
 * @param {String} environment  Name of target environment
 * @returns {Config}            RockUp Config object
 * @throws Errors associated with loading Config (non-exist, syntax)
 **/
function _loadLocalConfigFile (environment) {
  return new Config( path.resolve( process.cwd(), 'deploy', environment+'.rockup.json' ) );
}

/**
 * Generate a callback function to be used in the CLI context as a
 * callback passed to delayed result commands. The returned function
 * accepts error as the first argument and exits the process with
 * a error code of non-zero for error, zero for success.
 *
 * @param {String} commandName      Name to use in status messages
 * @returns {Function}              Callback
 **/
function _endCommandCallback (commandName) {
  return function(err) {
    if (err) {
      console.log( (commandName+" failed:").red.bold, inspect(err).red );
      process.exit(1);
    }
    else {
      console.log( (commandName+" succeeded!").green.bold );
      process.exit(0);
    }
  };
}
<|endoftext|>


<commit_before>var topFilms =[{
          title: "Don't Breath",
          tomatoMeter: 86,
          boxOffice: 15.7
        },{
          title: "Suicide Squad",
          tomatoMeter: 26,
          boxOffice: 73.2
        },{
          title: "Top Gun Part 2",
          tomatoMeter: 87,
          boxOffice: 222.2
        },{
          title: "Kubo and the Two Strings",
          tomatoMeter: 96,
          boxOffice: 23.1
        },{
          title: "Sausage Party Redux",
          tomatoMeter: 92,
          boxOffice: 1.2
        }];

function grabBoxOfficeData(arr){
  // var results = [];

  //Method 3
  //This returns a newe array with the results.
  return arr.map(function(value){
    return "$" + value.boxOffice;
  });

  //method 2
  // arr.forEach(function(value){
  //   results.push("$" + value.boxOffice);
  // });

  //Method 1
  // for (var i = 0; i < arr.length; i++) {
  //   results.push("$"+arr[i].boxOffice);
  // };

  return results;
}

// In node... use the console.log
console.log(grabBoxOfficeData(topFilms));

//We have the original repo in Github
//I forked the repo and cloned it locally
//after typing git remote -v
//we can see where we can upate to
//to have changes updated to the main repo on my repo
//submit a change
<commit_msg>added git comments<commit_after>var topFilms =[{
          title: "Don't Breath",
          tomatoMeter: 86,
          boxOffice: 15.7
        },{
          title: "Suicide Squad",
          tomatoMeter: 26,
          boxOffice: 73.2
        },{
          title: "Top Gun Part 2",
          tomatoMeter: 87,
          boxOffice: 222.2
        },{
          title: "Kubo and the Two Strings",
          tomatoMeter: 96,
          boxOffice: 23.1
        },{
          title: "Sausage Party Redux",
          tomatoMeter: 92,
          boxOffice: 1.2
        }];

function grabBoxOfficeData(arr){
  // var results = [];

  //Method 3
  //This returns a newe array with the results.
  return arr.map(function(value){
    return "$" + value.boxOffice;
  });

  //method 2
  // arr.forEach(function(value){
  //   results.push("$" + value.boxOffice);
  // });

  //Method 1
  // for (var i = 0; i < arr.length; i++) {
  //   results.push("$"+arr[i].boxOffice);
  // };

  return results;
}

// In node... use the console.log
// console.log(grabBoxOfficeData(topFilms));

//We have the original repo in Github
//I forked the repo and cloned it locally
//after typing git remote -v
//we can see where we can upate to
//to have changes updated to the main repo on my repo
//submit a change
//
// How do you get the changes on your machine?
//
// we can't just do a git pull
// that's just linked to my master Account
// let's add another connection
// we have one named origin
// what should we add? parent?
//
// git remote add parent https://github.com/danieloostra/mean-charlie-workspace.git
//
// then I can pull from the new parent connection that I just made...
// look at what I see when I type git remote -v
//
// but who says we're limited to one origin
//
// why don't we git
<|endoftext|>


<commit_before>/*jshint multiline:true */
var fs = require('fs');
var async = require('async');
var open = require('open');
var generator = require('yeoman-generator');
var util = require('util');
var path = require('path');
var updateNotifier = require('update-notifier');
var chalk = require('chalk');

// The `yo yo` generator provides users with a few common, helpful commands.
var yoyo = module.exports = function yoyo(args, options) {
  generator.Base.apply(this, arguments);
  this.insight = options.insight;

  this.insight.track('yoyo', 'init');
  process.once('exit', this._exit.bind(this));
};

util.inherits(yoyo, generator.Base);

// Runs parallel `npm update -g`s for each detected generator.
yoyo.prototype._updateGenerators = function _updateGenerators() {
  var self = this;

  var resolveGenerators = function (pkg) {
    return function (next) {
      self.spawnCommand('npm', ['update', '-g', pkg.name])
        .on('error', next)
        .on('exit', next);
    };
  };

  self.insight.track('yoyo', 'update');
  async.parallel(self._.map(self.pkgs, resolveGenerators), function (err) {
    if (err) {
      self.insight.track('yoyo:err', 'update');
      return self.emit('error', err);
    }

    self.insight.track('yoyo', 'updated');
    self.home({
      message:
        'I\'ve just updated all of your generators. Remember, you can update'
        + '\na specific generator with npm by running:'
        + '\n'
        + chalk.magenta('\n    npm update -g generator-_______')
    });
  });
};

// Initializes a generator.
//
// - generator - (string) The generator to initialize.
yoyo.prototype._initGenerator = function _initGenerator(generator, done) {
  console.log(
    chalk.yellow('\nBefore you create a new application, be sure you are in the directory you'
    + '\nwish your application to be dropped into.'
    + '\n'
    + '\nYou may also run the following command to initiate this generator:'
    + '\n')
    + chalk.magenta('\n    yo ' + generator.split(':')[0])
    + '\n'
  );

  this.insight.track('yoyo', 'run', generator);
  this.env.run(generator, done);
};

// Serves as the response prompt for "Install a generator" as well as simply
// installs a generator if a string is passed in.
//
// - pkgName - (optional) A string that matches the NPM package name.
yoyo.prototype._installGenerator = function _installGenerator(pkgName) {
  if (this._.isString(pkgName)) {
    this.insight.track('yoyo', 'install', pkgName);

    // We know what generator we want to install
    return this.spawnCommand('npm', ['install', '-g', pkgName])
      .on('error', function (err) {
        this.insight.track('yoyo:err', 'install', pkgName);
        this.emit('error', err);
      }.bind(this))
      .on('exit', function () {
        this.insight.track('yoyo', 'installed', pkgName);
        this.home({
          refresh: true,
          message:
            '\nI just installed your generator by running:'
            + '\n'
            + chalk.magenta('\n    npm install -g ' + pkgName)
        });
      }.bind(this));
  }

  this.insight.track('yoyo', 'install');

  this.prompt([{
    name: 'searchTerm',
    message: 'Search NPM for generators'
  }], this._searchNpm.bind(this));
};

// Grabs all of the packages with a `yeoman-generator` keyword on NPM.
//
// - term - (object) Contains the search term & gets passed back to callback().
// - cb   - Callback to execute once generators have been found.
yoyo.prototype._findAllNpmGenerators = function _findAllNpmGenerators(term, cb) {
  var url = 'http://isaacs.iriscouch.com/registry/_design/app/_view/byKeyword?startkey=[%22yeoman-generator%22]&endkey=[%22yeoman-generator%22,{}]&group_level=3';

  this.request(url, function (err, res, body) {
    if (err) {
      return this.emit('error', err);
    }

    try {
      this.npmGenerators = JSON.parse(body);
    } catch (err) {
      return this.emit('error', new Error(chalk.bold(
        'A problem occurred contacting the registry.'
        + '\nUnable to parse response: not valid JSON.'
      )));
    }

    cb(term);
  }.bind(this));
};

// Takes a search term, looks it up in the registry, prompts the user with the
// results, allowing them to choose to install it, or go back home.
//
// - term - Object with a 'searchTerm' property containing the term to search
//          NPM for.
yoyo.prototype._searchNpm = function _searchNpm(term) {
  if (!this.npmGenerators) {
    return this._findAllNpmGenerators(term, this._searchNpm.bind(this));
  }

  // Find any matches from NPM.
  var choices = this._.chain(this.npmGenerators.rows).map(function (generator) {
    // Make sure it's not already installed.
    if (!this.pkgs[generator.key[1]] && generator.key.join(' ').indexOf(term.searchTerm) > -1) {
      return {
        name: generator.key[1],
        value: generator.key[1]
      };
    }
  }.bind(this)).compact().value();

  var resultsPrompt = [{
    name: '_installGenerator',
    type: 'list',
    message: choices.length > 0
      ? 'Here\'s what I found. Install one?'
      : 'Sorry, nothing was found',
    choices: this._.union(choices, {
      name: 'Search again',
      value: '_installGenerator'
    }, {
      name: 'Return home',
      value: 'home'
    })
  }];

  this.prompt(resultsPrompt, function (answer) {
    if (this._.isFunction(this[answer._installGenerator])) {
      return this[answer._installGenerator]();
    }

    this._installGenerator(answer._installGenerator);
  }.bind(this));
};

// Prompts user with a few helpful resources, then opens it in their browser.
yoyo.prototype._findHelp = function _findHelp() {
  this.insight.track('yoyo', 'help');
  this.prompt([{
    name: 'whereTo',
    type: 'list',
    message:
      'Here are a few helpful resources.'
      + '\n'
      + '\nI will open the link you select in your browser for you',
    choices: [{
      name: 'Take me to the documentation',
      value: 'https://github.com/yeoman/yeoman/wiki'
    }, {
      name: 'View Frequently Asked Questions',
      value: 'https://github.com/yeoman/yeoman/wiki/FAQ'
    }, {
      name: 'File an issue on GitHub',
      value: 'https://github.com/yeoman/yeoman/blob/master/contributing.md#issue-submission'
    }, {
      name: 'Take me back home, Yo!',
      value: {
        method: 'home',
        args: {
          message: 'I get it, you like learning on your own. I respect that.'
        }
      }
    }]
  }], function (answer) {
    this.insight.track('yoyo', 'help', answer);

    if (this._.isFunction(this[answer.whereTo.method])) {
      this[answer.whereTo.method](answer.whereTo.args);
    } else {
      open(answer.whereTo);
    }
  }.bind(this));
};

// Serves as a quick escape from the `yo yo` prompts.
yoyo.prototype._exit = function _exit() {
  this.insight.track('yoyo', 'exit');

  console.log(
      '\nBye from us! Chat soon.'
    + '\n'
    + '\n            Add' + chalk.red.bold('y') + ' Osmani'
    + '\n          Sindr' + chalk.red.bold('e') + ' Sorhus'
    + '\n        Brian F' + chalk.red.bold('o') + 'rd'
    + '\n     Eric Bidel' + chalk.red.bold('m') + 'an'
    + '\n              P' + chalk.red.bold('a') + 'ul Irish'
    + '\n     Mickael Da' + chalk.red.bold('n') + 'iel'
    + '\n          Pasca' + chalk.yellow.bold('1') + ' Hartig'
    + '\n      Stephen S' + chalk.cyan.bold('.') + 'wchuk'
    + '\n    Frederick R' + chalk.yellow.bold('0') + 's'
    + '\n');
};

// I'm sorry...
yoyo.prototype._noop = function _noop() {};

// Rolls through all of the generators provided by `env.generators`, finding
// their `package.json` files, then storing them internally in `this.pkgs`.
yoyo.prototype.findGenerators = function findGenerators() {
  var self = this;
  self.pkgs = {};

  var done = this.async();

  // This should be a Set with ES6.
  var resolvedGenerators = {};
  var resolveGenerators = function (generator) {
    var generatorPath = generator.resolved.replace(/([\/\\].*generator[^\/\\]*)[\/\\].*/, '$1/package.json');

    return function (next) {
      var alreadyResolved = generatorPath in resolvedGenerators;
      var isPackageJSON = path.basename(generatorPath) === 'package.json';

      if (alreadyResolved || !isPackageJSON || !fs.existsSync(generatorPath)) {
        return next();
      }

      var pkg = JSON.parse(self.readFileAsString(generatorPath));
      pkg.namespace = generator.namespace;

      if (/[app|all]/.test(generator.namespace)) {
        pkg.appGenerator = true;
        pkg.prettyName = generator.namespace.replace(/(\w+):\w+/, '$1');
        pkg.prettyName = pkg.prettyName.charAt(0).toUpperCase() + pkg.prettyName.slice(1);

        pkg.update = updateNotifier({
          packageName: pkg.name,
          packageVersion: pkg.version
        }).update;

        if (pkg.update && pkg.version !== pkg.update.latest) {
          pkg.updateAvailable = true;
        }
      }

      self.pkgs[pkg.name] = pkg;

      resolvedGenerators[generatorPath] = true;

      next();
    };
  };

  async.parallel(self._.map(self.env.generators, resolveGenerators), function (err) {
    if (err) {
      return self.emit('error', err);
    }

    done();
  });
};

// Display the home `yo` screen, with the intial set of options.
//
// - options - (optional)
//           - message (string) - String to print before prompt.
//           - refresh (bool) - Spawn a new `yo` command.
yoyo.prototype.home = function home(options) {
  var done = this.async();

  options = options || {};

  if (options.refresh) {
    this.env.lookup('*:*');
  }

  if (options.message) {
    console.log('\n' + chalk.cyan(options.message) + '\n');
  }

  var defaultChoices = [{
    name: 'Install a generator',
    value: {
      method: '_installGenerator'
    }
  }, {
    name: 'Find some help',
    value: {
      method: '_findHelp'
    }
  }, {
    name: 'Get me out of here!',
    value: {
      method: '_noop'
    }
  }];

  var generatorList = this._.chain(this.pkgs).map(function (generator) {
    if (!generator.appGenerator) {
      return;
    }

    var versionInfo = chalk.gray('(' + generator.version + ')');

    if (generator.updateAvailable) {
      versionInfo += chalk.yellow(' Update Available! ') + chalk.red('(' + generator.update.latest + ')');
    }

    return {
      name: 'Run the ' + generator.prettyName + ' generator ' + versionInfo,
      value: {
        method: '_initGenerator',
        args: generator.namespace
      }
    };
  }).compact().value();

  if (generatorList.length) {
    defaultChoices.unshift({
      name: 'Update your generators',
      value: {
        method: '_updateGenerators'
      }
    });
  }

  this.insight.track('yoyo', 'home');
  this.prompt([{
    name: 'whatNext',
    type: 'list',
    message: 'What would you like to do?',
    choices: this._.union(generatorList, defaultChoices)
  }], function (answer) {
    this[answer.whatNext.method](answer.whatNext.args, done);
  }.bind(this));
};
<commit_msg>Add a separator to yoyo<commit_after>/*jshint multiline:true */
var fs = require('fs');
var async = require('async');
var open = require('open');
var generator = require('yeoman-generator');
var util = require('util');
var path = require('path');
var updateNotifier = require('update-notifier');
var chalk = require('chalk');

// The `yo yo` generator provides users with a few common, helpful commands.
var yoyo = module.exports = function yoyo(args, options) {
  generator.Base.apply(this, arguments);
  this.insight = options.insight;

  this.insight.track('yoyo', 'init');
  process.once('exit', this._exit.bind(this));
};

util.inherits(yoyo, generator.Base);

// Runs parallel `npm update -g`s for each detected generator.
yoyo.prototype._updateGenerators = function _updateGenerators() {
  var self = this;

  var resolveGenerators = function (pkg) {
    return function (next) {
      self.spawnCommand('npm', ['update', '-g', pkg.name])
        .on('error', next)
        .on('exit', next);
    };
  };

  self.insight.track('yoyo', 'update');
  async.parallel(self._.map(self.pkgs, resolveGenerators), function (err) {
    if (err) {
      self.insight.track('yoyo:err', 'update');
      return self.emit('error', err);
    }

    self.insight.track('yoyo', 'updated');
    self.home({
      message:
        'I\'ve just updated all of your generators. Remember, you can update'
        + '\na specific generator with npm by running:'
        + '\n'
        + chalk.magenta('\n    npm update -g generator-_______')
    });
  });
};

// Initializes a generator.
//
// - generator - (string) The generator to initialize.
yoyo.prototype._initGenerator = function _initGenerator(generator, done) {
  console.log(
    chalk.yellow('\nBefore you create a new application, be sure you are in the directory you'
    + '\nwish your application to be dropped into.'
    + '\n'
    + '\nYou may also run the following command to initiate this generator:'
    + '\n')
    + chalk.magenta('\n    yo ' + generator.split(':')[0])
    + '\n'
  );

  this.insight.track('yoyo', 'run', generator);
  this.env.run(generator, done);
};

// Serves as the response prompt for "Install a generator" as well as simply
// installs a generator if a string is passed in.
//
// - pkgName - (optional) A string that matches the NPM package name.
yoyo.prototype._installGenerator = function _installGenerator(pkgName) {
  if (this._.isString(pkgName)) {
    this.insight.track('yoyo', 'install', pkgName);

    // We know what generator we want to install
    return this.spawnCommand('npm', ['install', '-g', pkgName])
      .on('error', function (err) {
        this.insight.track('yoyo:err', 'install', pkgName);
        this.emit('error', err);
      }.bind(this))
      .on('exit', function () {
        this.insight.track('yoyo', 'installed', pkgName);
        this.home({
          refresh: true,
          message:
            '\nI just installed your generator by running:'
            + '\n'
            + chalk.magenta('\n    npm install -g ' + pkgName)
        });
      }.bind(this));
  }

  this.insight.track('yoyo', 'install');

  this.prompt([{
    name: 'searchTerm',
    message: 'Search NPM for generators'
  }], this._searchNpm.bind(this));
};

// Grabs all of the packages with a `yeoman-generator` keyword on NPM.
//
// - term - (object) Contains the search term & gets passed back to callback().
// - cb   - Callback to execute once generators have been found.
yoyo.prototype._findAllNpmGenerators = function _findAllNpmGenerators(term, cb) {
  var url = 'http://isaacs.iriscouch.com/registry/_design/app/_view/byKeyword?startkey=[%22yeoman-generator%22]&endkey=[%22yeoman-generator%22,{}]&group_level=3';

  this.request(url, function (err, res, body) {
    if (err) {
      return this.emit('error', err);
    }

    try {
      this.npmGenerators = JSON.parse(body);
    } catch (err) {
      return this.emit('error', new Error(chalk.bold(
        'A problem occurred contacting the registry.'
        + '\nUnable to parse response: not valid JSON.'
      )));
    }

    cb(term);
  }.bind(this));
};

// Takes a search term, looks it up in the registry, prompts the user with the
// results, allowing them to choose to install it, or go back home.
//
// - term - Object with a 'searchTerm' property containing the term to search
//          NPM for.
yoyo.prototype._searchNpm = function _searchNpm(term) {
  if (!this.npmGenerators) {
    return this._findAllNpmGenerators(term, this._searchNpm.bind(this));
  }

  // Find any matches from NPM.
  var choices = this._.chain(this.npmGenerators.rows).map(function (generator) {
    // Make sure it's not already installed.
    if (!this.pkgs[generator.key[1]] && generator.key.join(' ').indexOf(term.searchTerm) > -1) {
      return {
        name: generator.key[1],
        value: generator.key[1]
      };
    }
  }.bind(this)).compact().value();

  var resultsPrompt = [{
    name: '_installGenerator',
    type: 'list',
    message: choices.length > 0
      ? 'Here\'s what I found. Install one?'
      : 'Sorry, nothing was found',
    choices: this._.union(choices, {
      name: 'Search again',
      value: '_installGenerator'
    }, {
      name: 'Return home',
      value: 'home'
    })
  }];

  this.prompt(resultsPrompt, function (answer) {
    if (this._.isFunction(this[answer._installGenerator])) {
      return this[answer._installGenerator]();
    }

    this._installGenerator(answer._installGenerator);
  }.bind(this));
};

// Prompts user with a few helpful resources, then opens it in their browser.
yoyo.prototype._findHelp = function _findHelp() {
  this.insight.track('yoyo', 'help');
  this.prompt([{
    name: 'whereTo',
    type: 'list',
    message:
      'Here are a few helpful resources.'
      + '\n'
      + '\nI will open the link you select in your browser for you',
    choices: [{
      name: 'Take me to the documentation',
      value: 'https://github.com/yeoman/yeoman/wiki'
    }, {
      name: 'View Frequently Asked Questions',
      value: 'https://github.com/yeoman/yeoman/wiki/FAQ'
    }, {
      name: 'File an issue on GitHub',
      value: 'https://github.com/yeoman/yeoman/blob/master/contributing.md#issue-submission'
    }, {
      name: 'Take me back home, Yo!',
      value: {
        method: 'home',
        args: {
          message: 'I get it, you like learning on your own. I respect that.'
        }
      }
    }]
  }], function (answer) {
    this.insight.track('yoyo', 'help', answer);

    if (this._.isFunction(this[answer.whereTo.method])) {
      this[answer.whereTo.method](answer.whereTo.args);
    } else {
      open(answer.whereTo);
    }
  }.bind(this));
};

// Serves as a quick escape from the `yo yo` prompts.
yoyo.prototype._exit = function _exit() {
  this.insight.track('yoyo', 'exit');

  console.log(
      '\nBye from us! Chat soon.'
    + '\n'
    + '\n            Add' + chalk.red.bold('y') + ' Osmani'
    + '\n          Sindr' + chalk.red.bold('e') + ' Sorhus'
    + '\n        Brian F' + chalk.red.bold('o') + 'rd'
    + '\n     Eric Bidel' + chalk.red.bold('m') + 'an'
    + '\n              P' + chalk.red.bold('a') + 'ul Irish'
    + '\n     Mickael Da' + chalk.red.bold('n') + 'iel'
    + '\n          Pasca' + chalk.yellow.bold('1') + ' Hartig'
    + '\n      Stephen S' + chalk.cyan.bold('.') + 'wchuk'
    + '\n    Frederick R' + chalk.yellow.bold('0') + 's'
    + '\n');
};

// I'm sorry...
yoyo.prototype._noop = function _noop() {};

// Rolls through all of the generators provided by `env.generators`, finding
// their `package.json` files, then storing them internally in `this.pkgs`.
yoyo.prototype.findGenerators = function findGenerators() {
  var self = this;
  self.pkgs = {};

  var done = this.async();

  // This should be a Set with ES6.
  var resolvedGenerators = {};
  var resolveGenerators = function (generator) {
    var generatorPath = generator.resolved.replace(/([\/\\].*generator[^\/\\]*)[\/\\].*/, '$1/package.json');

    return function (next) {
      var alreadyResolved = generatorPath in resolvedGenerators;
      var isPackageJSON = path.basename(generatorPath) === 'package.json';

      if (alreadyResolved || !isPackageJSON || !fs.existsSync(generatorPath)) {
        return next();
      }

      var pkg = JSON.parse(self.readFileAsString(generatorPath));
      pkg.namespace = generator.namespace;

      if (/[app|all]/.test(generator.namespace)) {
        pkg.appGenerator = true;
        pkg.prettyName = generator.namespace.replace(/(\w+):\w+/, '$1');
        pkg.prettyName = pkg.prettyName.charAt(0).toUpperCase() + pkg.prettyName.slice(1);

        pkg.update = updateNotifier({
          packageName: pkg.name,
          packageVersion: pkg.version
        }).update;

        if (pkg.update && pkg.version !== pkg.update.latest) {
          pkg.updateAvailable = true;
        }
      }

      self.pkgs[pkg.name] = pkg;

      resolvedGenerators[generatorPath] = true;

      next();
    };
  };

  async.parallel(self._.map(self.env.generators, resolveGenerators), function (err) {
    if (err) {
      return self.emit('error', err);
    }

    done();
  });
};

// Display the home `yo` screen, with the intial set of options.
//
// - options - (optional)
//           - message (string) - String to print before prompt.
//           - refresh (bool) - Spawn a new `yo` command.
yoyo.prototype.home = function home(options) {
  var done = this.async();

  options = options || {};

  if (options.refresh) {
    this.env.lookup('*:*');
  }

  if (options.message) {
    console.log('\n' + chalk.cyan(options.message) + '\n');
  }

  var defaultChoices = [{
    name: 'Install a generator',
    value: {
      method: '_installGenerator'
    }
  }, {
    name: 'Find some help',
    value: {
      method: '_findHelp'
    }
  }, {
    name: 'Get me out of here!',
    value: {
      method: '_noop'
    }
  }];

  var generatorList = this._.chain(this.pkgs).map(function (generator) {
    if (!generator.appGenerator) {
      return;
    }

    var versionInfo = chalk.gray('(' + generator.version + ')');

    if (generator.updateAvailable) {
      versionInfo += chalk.yellow(' Update Available! ') + chalk.red('(' + generator.update.latest + ')');
    }

    return {
      name: 'Run the ' + generator.prettyName + ' generator ' + versionInfo,
      value: {
        method: '_initGenerator',
        args: generator.namespace
      }
    };
  }).compact().value();

  if (generatorList.length) {
    defaultChoices.unshift({
      name: 'Update your generators',
      value: {
        method: '_updateGenerators'
      }
    });
  }

  this.insight.track('yoyo', 'home');
  this.prompt([{
    name: 'whatNext',
    type: 'list',
    message: 'What would you like to do?',
    choices: this._.union(generatorList, new generator.inquirer.Separator(), defaultChoices)
  }], function (answer) {
    this[answer.whatNext.method](answer.whatNext.args, done);
  }.bind(this));
};
<|endoftext|>


<commit_before>exports.run = async(client, msg, args) => {
  const moment = require('moment');
  const ms = require('ms')
  const uptime = require('../functions/botUptime.js')
  let DiscordMoji = msg.guild.emojis.find('name', 'discord')
  embedMessage.advanced({
    author : {
      name : `Take a look at my info`,
      pic  : client.user.displayAvatarURL
    },
    fields : [{
        title : `${DiscordMoji}My Discord Info:`,
        content: `**Username:** ${client.user.username}\n\
**Descriminator:** ${client.user.tag}\n\
**ID:** ${client.user.id}`
    },
    {
      title : `💻Process:`,
      content : `**uptime:** ${ms(client.uptime, { long: true })}`
    }
    ],
    thumbnail : client.user.displayAvatarURL
  })
};

exports.help = {
    category   : 'util',
    usage      : '',
    description: 'Shows bot\'s info',
    detail     : 'When using bot info you will see all the info about the bot',
    botPerm    : ['SEND_MESSAGES', 'EMBED_LINKS'],
    authorPerm : ['SEND_MESSAGES'],
    alias      : [
        null
    ]
};
<commit_msg>Botinfo<commit_after>exports.run = async(client, msg, args) => {
  const moment = require('moment');
  const ms = require('ms')
  let DiscordMoji = msg.guild.emojis.find('name', 'discord')
  embedMessage.advanced({
    author : {
      name : `Take a look at my info`,
      pic  : client.user.displayAvatarURL
    },
    fields : [{
        title : `${DiscordMoji}My Discord Info:`,
        content: `**Username:** ${client.user.username}\n\
**Descriminator:** ${client.user.tag}\n\
**ID:** ${client.user.id}`
    },
    {
      title : `💻Process:`,
      content : `**Online since:** ${ms(client.uptime, { long: false })}`
    }
    ],
    thumbnail : client.user.displayAvatarURL
  })
};

exports.help = {
    category   : 'util',
    usage      : '',
    description: 'Shows bot\'s info',
    detail     : 'When using bot info you will see all the info about the bot',
    botPerm    : ['SEND_MESSAGES', 'EMBED_LINKS'],
    authorPerm : ['SEND_MESSAGES'],
    alias      : [
        null
    ]
};
<|endoftext|>


<commit_before>
exports.run = async (client, msg, args) => {

  if (!msg.mentions.users.first()) {
      await msg.reply('You must mention someone.');
      return;
  }

  let exists = await r.table('ModHistory').filter({
    guildID : msg.guild.id,
    userID  : msg.mentions.users.first().id
  }).run();

  let textArray =  [
    `= 🔨History for ${msg.mentions.users.first().username} =🔨`,
    `Bans: ${exists[0] && exists[0]['banCount'] ? exists[0]['banCount'] : 0}`,
    `Mutes: ${exists[0] && exists[0]['muteCount'] ? exists[0]['muteCount'] : 0}`,
    `Kicks: ${exists[0] && exists[0]['kickCount'] ? exists[0]['kickCount'] : 0}`,
    `Softbans: ${exists[0] && exists[0]['softbanCount'] ? exists[0]['softbanCount'] : 0}`,
    `Warns: ${exists[0] && exists[0]['warnCount'] ? exists[0]['warnCount'] : 0}`,
  ];

  try {
    await msg.channel.send(textArray.join('\n'), {code : "asciidoc"});
  } catch (e) {
    logger.error(e);
  }
};

exports.help = {
    category: 'moderation',
    usage: false,
    description: 'Shows mentioned user punishment history',
    detail: 'When using history you can take a look at detailed amount of punishments of any kind the user got',
    botPerm: ['SEND_MESSAGES'],
    authorPerm: [],
    example: '@user#5743',
    alias: [
        null
    ]
};
<commit_msg>Cleanup<commit_after>
exports.run = async (client, msg, args) => {

    if (!msg.mentions.users.first()) {
        await msg.reply('You must mention someone.');
        return;
    }

    let exists = await r.table('ModHistory').filter({
        guildID : msg.guild.id,
        userID  : msg.mentions.users.first().id
    }).run();

    let textArray =  [
        `= 🔨History for ${msg.mentions.users.first().username} =🔨`,
        `Bans: ${exists[0] && exists[0]['banCount'] ? exists[0]['banCount'] : 0}`,
        `Mutes: ${exists[0] && exists[0]['muteCount'] ? exists[0]['muteCount'] : 0}`,
        `Kicks: ${exists[0] && exists[0]['kickCount'] ? exists[0]['kickCount'] : 0}`,
        `Softbans: ${exists[0] && exists[0]['softbanCount'] ? exists[0]['softbanCount'] : 0}`,
        `Warns: ${exists[0] && exists[0]['warnCount'] ? exists[0]['warnCount'] : 0}`,
    ];

    try {
        await msg.channel.send(textArray.join('\n'), {code : "asciidoc"});
    } catch (e) {
        logger.error(e);
    }
};

exports.help = {
    category: 'moderation',
    usage: false,
    description: 'Shows mentioned user punishment history',
    detail: 'When using history you can take a look at detailed amount of punishments of any kind the user got',
    botPerm: ['SEND_MESSAGES'],
    authorPerm: [],
    example: '@user#5743',
    alias: [
        null
    ]
};
<|endoftext|>


<commit_before>const config = require('../config.js');
const utils = require('../utils.js');

module.exports = {
  run: function(message, lang) {
    if (message.channel.type != 'text') return;
    var expression = /^\w+\!(\w+) *(.*)/;
    var embed = utils.generateDekuDiv(message);
    if (message.content.match(expression)[2]) {
      var game = message.content.match(expression)[2];
      var count = message.guild.members.filter(m => {if(m.user.presence.game){ if(m.user.presence.game.name.toLowerCase() == game.toLowerCase()){return true;}}}).size;
      var text = '';
      if (count == 0) {
        text = lang.playing.zero.replace('{0}', game);
      } else if (count == 1) {
        text = lang.playing.one.replace('{0}', game);
      } else {
        text = lang.playing.more.replace('{0}', game).replace('{1}', count);
      }
      embed.setDescription(text);
    } else {
      embed.setColor(config.colors.error);
      embed.addField(lang.commands.playing.error_no_args, lang.commands.playing.usage);
    }
    message.channel.send({embed});
  }
}
<commit_msg>Fix translation error<commit_after>const config = require('../config.js');
const utils = require('../utils.js');

module.exports = {
  run: function(message, lang) {
    if (message.channel.type != 'text') return;
    var expression = /^\w+\!(\w+) *(.*)/;
    var embed = utils.generateDekuDiv(message);
    if (message.content.match(expression)[2]) {
      var game = message.content.match(expression)[2];
      var count = message.guild.members.filter(m => {if(m.user.presence.game){ if(m.user.presence.game.name.toLowerCase() == game.toLowerCase()){return true;}}}).size;
      var text = '';
      if (count == 0) {
        text = lang.commands.playing.zero.replace('{0}', game);
      } else if (count == 1) {
        text = lang.commands.playing.one.replace('{0}', game);
      } else {
        text = lang.commands.playing.more.replace('{0}', game).replace('{1}', count);
      }
      embed.setDescription(text);
    } else {
      embed.setColor(config.colors.error);
      embed.addField(lang.commands.playing.error_no_args, lang.commands.playing.usage);
    }
    message.channel.send({embed});
  }
}
<|endoftext|>


<commit_before>'use strict';

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

var $$users = {};
var standups;

module.exports = function reboot(controller, db) {

  standups = db.collection('standups');

  controller.hears(['standup'], ['direct_message','mention','direct_mention', 'message_received'], function(bot, message) {
    bot.api.users.info({user: message.user}, function (err, user) {
      $$users[message.user] = user.user;
      // console.log(user);
      // convo.$user = user;
      bot.reply(message, 'Hello ' + user.user.real_name + '!');
      bot.startPrivateConversation(message, step1);
    });
  });
};

function step1(response, convo) {
  convo.ask('What did you do yesterday?', function(response, convo) {
    step2(response, convo);
    convo.next();
  });
}

function step2(response, convo) {
  convo.ask('What will you do today?', function(response, convo) {
    step3(response, convo);
    convo.next();
  });
}

function step3(response, convo) {
  convo.ask('Do you have any pain points / road blocks?', function(response, convo) {
    step4(response, convo);
    convo.next();
  });
}

function step4(response, convo) {
  convo.ask('What is 1 win that you have experienced in the last 24 hours?', function(response, convo) {
    step5(response, convo);
    convo.next();
  });
}

function step5(response, convo) {

  var obj = {};
  obj.userID = convo.responses['What did you do yesterday?'].user;
  obj.userName = $$users[obj.userID].real_name;
  obj.timestamp = Date.now();
  obj.responses = convo.responses;
  console.log(obj);

  standups.insertMany([obj], function(err, result) {
    if(err) {
      convo.say('Whoops. Something happened and your standup was unable to be saved to the database. Please try again. If the error persists please contact hrr.communication@hackreactor.com')
    } else {
      convo.say('Thank you!');
    }
    convo.next();
  });
}
<commit_msg>Update standup.js<commit_after>'use strict';

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

var $$users = {};
var standups;

module.exports = function reboot(controller, db) {

//   standups = db.collection('standups');

//   controller.hears(['standup'], ['direct_message','mention','direct_mention', 'message_received'], function(bot, message) {
//     bot.api.users.info({user: message.user}, function (err, user) {
//       $$users[message.user] = user.user;
//       // console.log(user);
//       // convo.$user = user;
//       bot.reply(message, 'Hello ' + user.user.real_name + '!');
//       bot.startPrivateConversation(message, step1);
//     });
//   });
};

function step1(response, convo) {
  convo.ask('What did you do yesterday?', function(response, convo) {
    step2(response, convo);
    convo.next();
  });
}

function step2(response, convo) {
  convo.ask('What will you do today?', function(response, convo) {
    step3(response, convo);
    convo.next();
  });
}

function step3(response, convo) {
  convo.ask('Do you have any pain points / road blocks?', function(response, convo) {
    step4(response, convo);
    convo.next();
  });
}

function step4(response, convo) {
  convo.ask('What is 1 win that you have experienced in the last 24 hours?', function(response, convo) {
    step5(response, convo);
    convo.next();
  });
}

function step5(response, convo) {

  var obj = {};
  obj.userID = convo.responses['What did you do yesterday?'].user;
  obj.userName = $$users[obj.userID].real_name;
  obj.timestamp = Date.now();
  obj.responses = convo.responses;
  console.log(obj);

  standups.insertMany([obj], function(err, result) {
    if(err) {
      convo.say('Whoops. Something happened and your standup was unable to be saved to the database. Please try again. If the error persists please contact hrr.communication@hackreactor.com')
    } else {
      convo.say('Thank you!');
    }
    convo.next();
  });
}
<|endoftext|>


<commit_before>'use strict'
const chalk = require('chalk')
const semver = require('semver')
const packageConfig = require('../package.json')
const shell = require('shelljs')
function exec (cmd) {
  return require('child_process').execSync(cmd).toString().trim()
}

const versionRequirements = [
  {
    name: 'node',
    currentVersion: semver.clean(process.version),
    versionRequirement: packageConfig.engines.node
  }
]

if (shell.which('npm')) {
  versionRequirements.push({
    name: 'npm',
    currentVersion: exec('npm --version'),
    versionRequirement: packageConfig.engines.npm
  })
}

module.exports = function () {
  const warnings = []
  for (let i = 0; i < versionRequirements.length; i++) {
    const mod = versionRequirements[i]
    if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
      warnings.push(mod.name + ': ' +
        chalk.red(mod.currentVersion) + ' should be ' +
        chalk.green(mod.versionRequirement)
      )
    }
  }

  if (warnings.length) {
    console.log('')
    console.log(chalk.yellow('To use this template, you must update following to modules:'))
    console.log()
    for (let i = 0; i < warnings.length; i++) {
      const warning = warnings[i]
      console.log('  ' + warning)
    }
    console.log()
    process.exit(1)
  }
}
<commit_msg>make it better<commit_after>'use strict'
const chalk = require('chalk')
const semver = require('semver')
function exec (cmd) {
  return require('child_process').execSync(cmd).toString().trim()
}

module.exports = function () {
  const warnings = []
  for (let i = 0; i < versionRequirements.length; i++) {
    const mod = versionRequirements[i]
    if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) {
      warnings.push(mod.name + ': ' +
        chalk.red(mod.currentVersion) + ' should be ' +
        chalk.green(mod.versionRequirement)
      )
    }
  }

  if (warnings.length) {
    console.log('')
    console.log(chalk.yellow('To use this template, you must update following to modules:'))
    console.log()
    for (let i = 0; i < warnings.length; i++) {
      const warning = warnings[i]
      console.log('  ' + warning)
    }
    console.log()
    process.exit(1)
  }
}
<|endoftext|>


<commit_before>'use strict';

var fs      = require('fs')
var runner  = require('urbit-runner')
var Urbit   = runner.Urbit;
var ERROR   = runner.ERROR;
var actions = runner.actions

var hash  = fs.readFileSync('./pin-arvo-commit.txt', 'utf-8').slice(0, 10)
var pill  = 'https://bootstrap.urbit.org/git-' + hash + '.pill'

var args  = ['-u', pill, '-cgPSF', 'zod', 'zod'];
var urbit = new Urbit(args);

// vere hangs (always?) with run in travis-ci with -P
// so we send ^Z if we hang for ~s30
function exit() {
  setTimeout(function(){
    urbit.pty.write('\x1a');
    urbit.pty.on('exit', function(code, signal){
      process.exit(0);
    })
  }, 30 * 1000);

  return urbit.exit(0);
}

Promise.resolve(urbit)
//  XX temporary
//  send ctrl-x to select dojo
//
.then(function(){
  return urbit.expect(/talk\[\] /)
  .then(function() {
    return urbit.pty.write("\x18")
  })
  .then(function() { return urbit })
})
.then(actions.safeBoot)
.then(actions.test)
.then(exit)
.catch(function(err){
  // we still exit 0, Arvo errors are not our fault ...
  return urbit.waitSilent()
  .then(function(){
    return urbit.warn("Arvo test aborted:", err);
  })
  .then(exit);
});
<commit_msg>[CI] run |mass after +test<commit_after>'use strict';

var fs      = require('fs')
var runner  = require('urbit-runner')
var Urbit   = runner.Urbit;
var ERROR   = runner.ERROR;
var actions = runner.actions

var hash  = fs.readFileSync('./pin-arvo-commit.txt', 'utf-8').slice(0, 10)
var pill  = 'https://bootstrap.urbit.org/git-' + hash + '.pill'

var args  = ['-u', pill, '-cgPSF', 'zod', 'zod'];
var urbit = new Urbit(args);

// vere hangs (always?) with run in travis-ci with -P
// so we send ^Z if we hang for ~s30
function exit() {
  setTimeout(function(){
    urbit.pty.write('\x1a');
    urbit.pty.on('exit', function(code, signal){
      process.exit(0);
    })
  }, 30 * 1000);

  return urbit.exit(0);
}

Promise.resolve(urbit)
//  XX temporary
//  send ctrl-x to select dojo
//
.then(function(){
  return urbit.expect(/talk\[\] /)
  .then(function() {
    return urbit.pty.write("\x18")
  })
  .then(function() { return urbit })
})
.then(actions.safeBoot)
.then(actions.test)
.then(function(){
  return urbit.line("|mass")
  .then(function(){
    return urbit.expectEcho("%ran-mass")
    .then(function(){ return urbit.resetListeners(); })
  })
})
.then(exit)
.catch(function(err){
  // we still exit 0, Arvo errors are not our fault ...
  return urbit.waitSilent()
  .then(function(){
    return urbit.warn("Arvo test aborted:", err);
  })
  .then(exit);
});
<|endoftext|>


<commit_before>/**
 * Tag Manager container names component.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import { AMPContainerNameTextField, WebContainerNameTextField } from '../common';
import { CONTAINER_CREATE, STORE_NAME } from '../../datastore/constants';
const { useSelect } = Data;

export default function ContainerNames() {
	const containerID = useSelect( ( select ) => select( STORE_NAME ).getContainerID() );
	const ampContainerID = useSelect( ( select ) => select( STORE_NAME ).getAMPContainerID() );

	if ( containerID !== CONTAINER_CREATE && ampContainerID !== CONTAINER_CREATE ) {
		return null;
	}

	return (

			{ containerID === CONTAINER_CREATE && <WebContainerNameTextField /> }
			{ ampContainerID === CONTAINER_CREATE && <AMPContainerNameTextField /> }

	);
}
<commit_msg>Fix circular dependency issue.<commit_after>/**
 * Tag Manager container names component.
 *
 * Site Kit by Google, Copyright 2020 Google LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

/**
 * Internal dependencies
 */
import Data from 'googlesitekit-data';
import AMPContainerNameTextField from './AMPContainerNameTextField';
import WebContainerNameTextField from './WebContainerNameTextField';
import { CONTAINER_CREATE, STORE_NAME } from '../../datastore/constants';
const { useSelect } = Data;

export default function ContainerNames() {
	const containerID = useSelect( ( select ) => select( STORE_NAME ).getContainerID() );
	const ampContainerID = useSelect( ( select ) => select( STORE_NAME ).getAMPContainerID() );

	if ( containerID !== CONTAINER_CREATE && ampContainerID !== CONTAINER_CREATE ) {
		return null;
	}

	return (

			{ containerID === CONTAINER_CREATE && <WebContainerNameTextField /> }
			{ ampContainerID === CONTAINER_CREATE && <AMPContainerNameTextField /> }

	);
}
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';
require('shelljs/global');

var paths = require('./paths');
var path = require('path');

set('-e');
set('-v');

// build
exec('npm run build-dist');
cd('demo');
mv('index-gh.html', 'index.html');
mkdir('-p', 'dist');
cp('-R', '../dist/*', './dist/');
cd('..');

var version = 'v' + require(path.join(__dirname, '../package.json')).version + '/';
var versionDir = path.join(paths.releases, version);
var latestDir = path.join(paths.releases, 'latest/');
mkdir('-p', versionDir)
mkdir('-p', latestDir);
cp(paths.redocBuilt + '.min.js', versionDir);
cp(paths.redocBuilt + '.min.js', latestDir);
<commit_msg>Creating CDN major release 1.x.x (#87)<commit_after>#!/usr/bin/env node
'use strict';
require('shelljs/global');

var paths = require('./paths');
var path = require('path');

set('-e');
set('-v');

// build
exec('npm run build-dist');
cd('demo');
mv('index-gh.html', 'index.html');
mkdir('-p', 'dist');
cp('-R', '../dist/*', './dist/');
cd('..');

var version = 'v' + require(path.join(__dirname, '../package.json')).version + '/';
var versionDir = path.join(paths.releases, version);
var latestDir = path.join(paths.releases, 'latest/');
var v1Dir = path.join(paths.releases, '1.x.x/');
mkdir('-p', versionDir)
mkdir('-p', latestDir);
mkdir('-p', v1Dir);
cp(paths.redocBuilt + '.min.js', versionDir);
cp(paths.redocBuilt + '.min.js', latestDir);
cp(paths.redocBuilt + '.min.js', v1Dir);
<|endoftext|>


<commit_before>module.exports = function(RED) {
    var noble = require('noble');

    function BleUartNode(config) {
        RED.nodes.createNode(this, config);

        // The proprietary UART profile by Nordic Semiconductor
        var uartServiceUuid = '6e400001b5a3f393e0a9e50e24dcca9e';
        var txCharacteristicUuid = '6e400002b5a3f393e0a9e50e24dcca9e';
        var rxCharacteristicUuid = '6e400003b5a3f393e0a9e50e24dcca9e';

        var txCharacteristic, rxCharacteristic;
        var writeWithoutResponse = false;

        var node = this;
        var localName = config.localName;
        if (localName === "") {
            node.error("Please specify a local name");
        }

        this.on('input', function(msg) {
            if (txCharacteristic) {
                // Oou can only send at most 20 bytes in a Bluetooth LE pacet,
                // so slice the data into 20-byte chunks:
                while (msg.payload.length > 20) {
                    var output = msg.payload.slice(0, 19);
                    txCharacteristic.write(new Buffer(output), writeWithoutResponse);
                    msg.payload = data.slice(20);
                }

                // Send any remainder bytes less than the last 20:
                txCharacteristic.write(new Buffer(msg.payload), writeWithoutResponse);
            }
        });

        noble.on('stateChange', function(state) {
            if (state === 'poweredOn') {
                noble.startScanning([uartServiceUuid], false);
                node.status({ fill: "blue", shape: "ring", text: "BLE powered on" });
            } else {
                noble.stopScanning();
                node.status({ fill: "red", shape: "ring", text: "BLE powered off" });
            }
        });

        noble.on('scanStart', function() {
            node.log('Started scanning');
            node.status({ fill: "blue", shape: "ring", text: "Scanning..." });
        });

        noble.on('scanStop', function() {
            node.log('Stopped scanning');
            node.status({ fill: "blue", shape: "dot", text: "Scanning finished" });
        });

        noble.on('warning', function(message) {
            node.warn(message);
        });

        noble.on('discover', function(peripheral) {
            node.log('Discovered: ' + peripheral);

            if (peripheral.advertisement.localName !== localName) {
                // Ignore non-specified peripherals
                return;
            }

            // We found a peripheral, stop scanning
            noble.stopScanning();
            node.log('Found: ' + peripheral.advertisement.localName);
            node.status({ fill: "green", shape: "ring", text: "Device found" });

            peripheral.connect(function(err) {
                if (err) {
                    node.error('Error connecting: ' + err);
                    return;
                }

                node.log('Connected to ' + peripheral.advertisement.localName);
                node.status({ fill: "green", shape: "ring", text: "Device connected" });

                peripheral.discoverServices(null, function(err, services) {
                    if (err) {
                        node.error('Error discovering services: ' + err);
                        return;
                    }

                    node.log('Services: ' + services.length);
                    services.forEach(function(service) {
                        if (service.uuid !== uartServiceUuid) {
                            // Ignore non-UART services
                            return;
                        } else {
                            node.log('Found a UART service');
                        }

                        service.discoverCharacteristics(null, function(err, characteristics) {
                            characteristics.forEach(function(characteristic) {
                                if (txCharacteristicUuid == characteristic.uuid) {
                                    txCharacteristic = characteristic;

                                    if (characteristic.properties.indexOf("writeWithoutResponse") > -1) {
                                        writeWithoutResponse = true;
                                    }
                                    node.log('writeWithoutResponse: ' + writeWithoutResponse);

                                    node.log('Found a TX characteristic');
                                } else if (rxCharacteristicUuid == characteristic.uuid) {
                                    rxCharacteristic = characteristic;
                                    node.log('Found a RX characteristic');

                                    // Turn on notifications
                                    rxCharacteristic.notify(true);

                                    rxCharacteristic.on('read', function(data, notification) {
                                        node.log(data);

                                        // If you got a notification
                                        if (notification) {
                                            // var msg = { "payload": String(data) };
                                            var msg = { "payload": data };
                                            node.send(msg);
                                        }
                                    });
                                }

                                if (txCharacteristic && rxCharacteristic) {
                                    node.log('Ready');
                                    node.status({ fill: "green", shape: "dot", text: "Device ready" });
                                }
                            });
                        });
                    });
                });

                peripheral.once('disconnect', function(err) {
                    node.log('Disconnected');

                    // Reset characteristics
                    txCharacteristic = undefined;
                    rxCharacteristic = undefined;

                    // Try to be connected again
                    noble.startScanning([uartServiceUuid], false);
                });
            });
        });
    }

    RED.nodes.registerType("ble uart", BleUartNode);
}<commit_msg>Fix typos<commit_after>module.exports = function(RED) {
    var noble = require('noble');

    function BleUartNode(config) {
        RED.nodes.createNode(this, config);

        // The proprietary UART profile by Nordic Semiconductor
        var uartServiceUuid = '6e400001b5a3f393e0a9e50e24dcca9e';
        var txCharacteristicUuid = '6e400002b5a3f393e0a9e50e24dcca9e';
        var rxCharacteristicUuid = '6e400003b5a3f393e0a9e50e24dcca9e';

        var txCharacteristic, rxCharacteristic;
        var writeWithoutResponse = false;

        var node = this;
        var localName = config.localName;
        if (localName === "") {
            node.error("Please specify a local name");
        }

        this.on('input', function(msg) {
            if (txCharacteristic) {
                // You can only send at most 20 bytes in a Bluetooth LE packet,
                // so slice the data into 20-byte chunks:
                while (msg.payload.length > 20) {
                    var output = msg.payload.slice(0, 19);
                    txCharacteristic.write(new Buffer(output), writeWithoutResponse);
                    msg.payload = data.slice(20);
                }

                // Send any remainder bytes less than the last 20:
                txCharacteristic.write(new Buffer(msg.payload), writeWithoutResponse);
            }
        });

        noble.on('stateChange', function(state) {
            if (state === 'poweredOn') {
                noble.startScanning([uartServiceUuid], false);
                node.status({ fill: "blue", shape: "ring", text: "BLE powered on" });
            } else {
                noble.stopScanning();
                node.status({ fill: "red", shape: "ring", text: "BLE powered off" });
            }
        });

        noble.on('scanStart', function() {
            node.log('Started scanning');
            node.status({ fill: "blue", shape: "ring", text: "Scanning..." });
        });

        noble.on('scanStop', function() {
            node.log('Stopped scanning');
            node.status({ fill: "blue", shape: "dot", text: "Scanning finished" });
        });

        noble.on('warning', function(message) {
            node.warn(message);
        });

        noble.on('discover', function(peripheral) {
            node.log('Discovered: ' + peripheral);

            if (peripheral.advertisement.localName !== localName) {
                // Ignore non-specified peripherals
                return;
            }

            // We found a peripheral, stop scanning
            noble.stopScanning();
            node.log('Found: ' + peripheral.advertisement.localName);
            node.status({ fill: "green", shape: "ring", text: "Device found" });

            peripheral.connect(function(err) {
                if (err) {
                    node.error('Error connecting: ' + err);
                    return;
                }

                node.log('Connected to ' + peripheral.advertisement.localName);
                node.status({ fill: "green", shape: "ring", text: "Device connected" });

                peripheral.discoverServices(null, function(err, services) {
                    if (err) {
                        node.error('Error discovering services: ' + err);
                        return;
                    }

                    node.log('Services: ' + services.length);
                    services.forEach(function(service) {
                        if (service.uuid !== uartServiceUuid) {
                            // Ignore non-UART services
                            return;
                        } else {
                            node.log('Found a UART service');
                        }

                        service.discoverCharacteristics(null, function(err, characteristics) {
                            characteristics.forEach(function(characteristic) {
                                if (txCharacteristicUuid == characteristic.uuid) {
                                    txCharacteristic = characteristic;

                                    if (characteristic.properties.indexOf("writeWithoutResponse") > -1) {
                                        writeWithoutResponse = true;
                                    }
                                    node.log('writeWithoutResponse: ' + writeWithoutResponse);

                                    node.log('Found a TX characteristic');
                                } else if (rxCharacteristicUuid == characteristic.uuid) {
                                    rxCharacteristic = characteristic;
                                    node.log('Found a RX characteristic');

                                    // Turn on notifications
                                    rxCharacteristic.notify(true);

                                    rxCharacteristic.on('read', function(data, notification) {
                                        node.log(data);

                                        // If you got a notification
                                        if (notification) {
                                            // var msg = { "payload": String(data) };
                                            var msg = { "payload": data };
                                            node.send(msg);
                                        }
                                    });
                                }

                                if (txCharacteristic && rxCharacteristic) {
                                    node.log('Ready');
                                    node.status({ fill: "green", shape: "dot", text: "Device ready" });
                                }
                            });
                        });
                    });
                });

                peripheral.once('disconnect', function(err) {
                    node.log('Disconnected');

                    // Reset characteristics
                    txCharacteristic = undefined;
                    rxCharacteristic = undefined;

                    // Try to be connected again
                    noble.startScanning([uartServiceUuid], false);
                });
            });
        });
    }

    RED.nodes.registerType("ble uart", BleUartNode);
}<|endoftext|>