<commit_before>const Command = require("../base/Command");

class Faction extends Command {
    constructor(client) {
        super(client, {
            name: "faction",
            aliases: ["factions"],
            category: "Star Wars",
            permissions: ["EMBED_LINKS"],
            flags: {
                leader: {
                    aliases: ["leaders", "l"]
                },
                zetas: {
                    aliases: ["zeta", "z"]
                }
            }
        });
    }

    async run(client, message, args, options) {
        const charList = client.characters;
        let allyCode = null;
        if (!args[0]) {
            return super.error(message, message.language.get("COMMAND_FACTION_USAGE", message.guildSettings.prefix), {title: message.language.get("COMMAND_FACTION_MISSING_FACTION"), example: "faction sith"});
        }
        if (args[0].toLowerCase() === "me" || client.isAllyCode(args[0]) || client.isUserID(args[0])) {
            allyCode = args.splice(0, 1);
            try {
                allyCode = await client.getAllyCode(message, allyCode);
            } catch (e) {
                return super.error(message, e.message);
            }
        }

        const searchName = String(args.join(" ")).toLowerCase().replace(/[^\w\s]/gi, "");

        if (!searchName || !searchName.length || searchName === "") {
            return super.error(message, message.language.get("COMMAND_FACTION_USAGE", message.guildSettings.prefix), {title: message.language.get("COMMAND_FACTION_MISSING_FACTION"), example: "faction sith"});
        }

        const factionChars = [];
        let search = searchName.replace(/[^\w]/g, "").replace(/s$/, "");
        if (searchName.toLowerCase() === "galactic republic") search = "affiliation_republic";
        const query = new RegExp(`^(?!.*selftag).*${search}.*`, "gi");
        let chars = await client.cache.get("swapi", "units", {categoryIdList: query, language: message.guildSettings.swgohLanguage.toLowerCase()}, {_id: 0, baseId: 1, nameKey: 1});

        // Filter out any ships that show up
        chars = chars.filter(c => charList.find(char => char.uniqueName === c.baseId));

        if (!chars.length) {
            return super.error(message, message.language.get("COMMAND_FACTION_USAGE", message.guildSettings.prefix), {title: message.language.get("COMMAND_FACTION_INVALID_FACTION"), example: "faction sith"});
        } else if (chars.length > 40) {
            return super.error(message, "Your query came up with too many results, please try and be more specific");
        } else {
            chars = chars.sort((a, b) => a.nameKey.toLowerCase() > b.nameKey.toLowerCase() ? 1 : -1);
        }

        // If they want just characters with leader abilities or zetas, filter em out
        if (options.flags.leader || options.flags.zetas) {
            const units = [];

            for (const c of chars) {
                const char = await client.swgohAPI.getCharacter(c.baseId, message.guildSettings.swgohLanguage);
                units.push(char);
            }

            if (options.flags.leader) {
                chars = chars.filter(c => {
                    const char = units.find(u => u.baseId === c.baseId);
                    const leader = char.skillReferenceList.filter(s => s.skillId.startsWith("leader"));
                    if (leader.length) return true;
                    return false;
                });
            }
            if (options.flags.zetas) {
                chars = chars.filter(c => {
                    const char = units.find(u => u.baseId === c.baseId);
                    const zetas = char.skillReferenceList.filter(s => s.cost.AbilityMatZeta > 0);
                    if (zetas.length > 0) return true;
                    return false;
                });
            }
        }
        if (allyCode) {
            if (chars.length) {
                chars = chars.map(c => c.baseId);
                const cooldown = client.getPlayerCooldown(message.author.id);
                const player = await client.swgohAPI.player(allyCode, null, cooldown);
                const playerChars = [];
                for (const c of chars) {
                    let found = player.roster.find(char => char.defId === c);
                    if (found) {
                        found = await client.swgohAPI.langChar(found, message.guildSettings.swgohLanguage);
                        found.gp = found.gp.toLocaleString();
                        playerChars.push(found);
                    }
                }

                const gpMax   = Math.max(...playerChars.map(c => c.gp.length));
                const gearMax = Math.max(...playerChars.map(c => c.gear.toString().length));
                const lvlMax  = Math.max(...playerChars.map(c => c.level.toString().length));

                factionChars.push(`**\`[ * | Lvl${" ".repeat(lvlMax)}|   GP  ${" ".repeat(gpMax-5)}| ⚙${" ".repeat(gearMax)}]\`**`);
                factionChars.push("**`=================" + "=".repeat(lvlMax + gpMax + gearMax) + "`**");

                playerChars.forEach(c => {
                    const lvlStr  = " ".repeat(lvlMax  - c.level.toString().length) + c.level;
                    const gpStr   = " ".repeat(gpMax   - c.gp.length) + c.gp;
                    const gearStr = " ".repeat(gearMax - c.gear.toString().length) + c.gear;
                    const zetas   = "z".repeat(c.skills.filter(s => s.isZeta && s.tier === 8).length);
                    factionChars.push(`**\`[ ${c.rarity} |  ${lvlStr}  | ${gpStr} | ${gearStr} ]\` ${zetas}${c.nameKey}**`);
                });
                const msgArray = client.msgArray(factionChars, "\n", 1000);
                const fields = [];
                let desc;
                if (msgArray.length > 1) {
                    msgArray.forEach((m, ix) => {
                        fields.push({
                            name: ix+1,
                            value: m
                        });
                    });
                } else {
                    desc = msgArray[0];
                }
                if (options.defaults) {
                    fields.push({
                        name: "Default flags used:",
                        value: client.codeBlock(options.defaults)
                    });
                }

                const footer = client.updatedFooter(player.updated, message, "player", cooldown);
                return message.channel.send({embed: {
                    author: {
                        name: player.name + "'s matches for " + searchName.toProperCase()
                    },
                    description: desc,
                    fields: fields,
                    footer: footer
                }});
            } else {
                return super.error(message, message.language.get("COMMAND_FACTION_USAGE", message.guildSettings.prefix), {title: message.language.get("COMMAND_FACTION_INVALID_FACTION"), example: "faction sith"});
            }
        } else {
            return message.channel.send({embed: {
                author: {
                    name: "Matches for " + searchName.toProperCase()
                },
                description: chars.map(c => c.nameKey).join("\n")
            }});
        }
    }
}

module.exports = Faction;
<commit_msg>Extra error check<commit_after>const Command = require("../base/Command");

class Faction extends Command {
    constructor(client) {
        super(client, {
            name: "faction",
            aliases: ["factions"],
            category: "Star Wars",
            permissions: ["EMBED_LINKS"],
            flags: {
                leader: {
                    aliases: ["leaders", "l"]
                },
                zetas: {
                    aliases: ["zeta", "z"]
                }
            }
        });
    }

    async run(client, message, args, options) {
        const charList = client.characters;
        let allyCode = null;
        if (!args[0]) {
            return super.error(message, message.language.get("COMMAND_FACTION_USAGE", message.guildSettings.prefix), {title: message.language.get("COMMAND_FACTION_MISSING_FACTION"), example: "faction sith"});
        }
        if (args[0].toLowerCase() === "me" || client.isAllyCode(args[0]) || client.isUserID(args[0])) {
            allyCode = args.splice(0, 1);
            try {
                allyCode = await client.getAllyCode(message, allyCode);
            } catch (e) {
                return super.error(message, e.message);
            }
        }

        const searchName = String(args.join(" ")).toLowerCase().replace(/[^\w\s]/gi, "");

        if (!searchName || !searchName.length || searchName === "") {
            return super.error(message, message.language.get("COMMAND_FACTION_USAGE", message.guildSettings.prefix), {title: message.language.get("COMMAND_FACTION_MISSING_FACTION"), example: "faction sith"});
        }

        const factionChars = [];
        let search = searchName.replace(/[^\w]/g, "").replace(/s$/, "");
        if (searchName.toLowerCase() === "galactic republic") search = "affiliation_republic";
        const query = new RegExp(`^(?!.*selftag).*${search}.*`, "gi");
        let chars = await client.cache.get("swapi", "units", {categoryIdList: query, language: message.guildSettings.swgohLanguage.toLowerCase()}, {_id: 0, baseId: 1, nameKey: 1});

        // Filter out any ships that show up
        chars = chars.filter(c => charList.find(char => char.uniqueName === c.baseId));

        if (!chars.length) {
            return super.error(message, message.language.get("COMMAND_FACTION_USAGE", message.guildSettings.prefix), {title: message.language.get("COMMAND_FACTION_INVALID_FACTION"), example: "faction sith"});
        } else if (chars.length > 40) {
            return super.error(message, "Your query came up with too many results, please try and be more specific");
        } else {
            chars = chars.sort((a, b) => a.nameKey.toLowerCase() > b.nameKey.toLowerCase() ? 1 : -1);
        }

        // If they want just characters with leader abilities or zetas, filter em out
        if (options.flags.leader || options.flags.zetas) {
            const units = [];

            for (const c of chars) {
                const char = await client.swgohAPI.getCharacter(c.baseId, message.guildSettings.swgohLanguage);
                units.push(char);
            }

            if (options.flags.leader) {
                chars = chars.filter(c => {
                    const char = units.find(u => u.baseId === c.baseId);
                    const leader = char.skillReferenceList.filter(s => s.skillId.startsWith("leader"));
                    if (leader.length) return true;
                    return false;
                });
            }
            if (options.flags.zetas) {
                chars = chars.filter(c => {
                    const char = units.find(u => u.baseId === c.baseId);
                    const zetas = char.skillReferenceList.filter(s => s.cost.AbilityMatZeta > 0);
                    if (zetas.length > 0) return true;
                    return false;
                });
            }
        }
        if (allyCode) {
            if (chars.length) {
                chars = chars.map(c => c.baseId);
                const cooldown = client.getPlayerCooldown(message.author.id);
                let player;
                try {
                    player = await client.swgohAPI.player(allyCode, null, cooldown);
                } catch (e) {
                    return super.error(message, e.message);
                }
                const playerChars = [];
                for (const c of chars) {
                    let found = player.roster.find(char => char.defId === c);
                    if (found) {
                        found = await client.swgohAPI.langChar(found, message.guildSettings.swgohLanguage);
                        found.gp = found.gp.toLocaleString();
                        playerChars.push(found);
                    }
                }

                const gpMax   = Math.max(...playerChars.map(c => c.gp.length));
                const gearMax = Math.max(...playerChars.map(c => c.gear.toString().length));
                const lvlMax  = Math.max(...playerChars.map(c => c.level.toString().length));

                factionChars.push(`**\`[ * | Lvl${" ".repeat(lvlMax)}|   GP  ${" ".repeat(gpMax-5)}| ⚙${" ".repeat(gearMax)}]\`**`);
                factionChars.push("**`=================" + "=".repeat(lvlMax + gpMax + gearMax) + "`**");

                playerChars.forEach(c => {
                    const lvlStr  = " ".repeat(lvlMax  - c.level.toString().length) + c.level;
                    const gpStr   = " ".repeat(gpMax   - c.gp.length) + c.gp;
                    const gearStr = " ".repeat(gearMax - c.gear.toString().length) + c.gear;
                    const zetas   = "z".repeat(c.skills.filter(s => s.isZeta && s.tier === 8).length);
                    factionChars.push(`**\`[ ${c.rarity} |  ${lvlStr}  | ${gpStr} | ${gearStr} ]\` ${zetas}${c.nameKey}**`);
                });
                const msgArray = client.msgArray(factionChars, "\n", 1000);
                const fields = [];
                let desc;
                if (msgArray.length > 1) {
                    msgArray.forEach((m, ix) => {
                        fields.push({
                            name: ix+1,
                            value: m
                        });
                    });
                } else {
                    desc = msgArray[0];
                }
                if (options.defaults) {
                    fields.push({
                        name: "Default flags used:",
                        value: client.codeBlock(options.defaults)
                    });
                }

                const footer = client.updatedFooter(player.updated, message, "player", cooldown);
                return message.channel.send({embed: {
                    author: {
                        name: player.name + "'s matches for " + searchName.toProperCase()
                    },
                    description: desc,
                    fields: fields,
                    footer: footer
                }});
            } else {
                return super.error(message, message.language.get("COMMAND_FACTION_USAGE", message.guildSettings.prefix), {title: message.language.get("COMMAND_FACTION_INVALID_FACTION"), example: "faction sith"});
            }
        } else {
            return message.channel.send({embed: {
                author: {
                    name: "Matches for " + searchName.toProperCase()
                },
                description: chars.map(c => c.nameKey).join("\n")
            }});
        }
    }
}

module.exports = Faction;
<|endoftext|>


<commit_before>'use strict';
/* eslint no-sync: 0 */
/**
 * @see [Atom's publish-build-task.coffee](https://git.io/vaYu3)
 * - https://github.com/atom/electron/blob/master/script/create-dist.py
 */

/**
 * TODO (imlucas) If darwin, dump symbols for breakpad
 * and include in assets.
 * @see [Atom's dump-symbols-task.coffee](https://git.io/va3fG)
 */
const Target = require('../lib/target');
const cli = require('mongodb-js-cli')('hadron-build:release');
const util = require('util');
const format = util.format;
const glob = require('glob');
const path = require('path');
const del = require('del');
const fs = require('fs-extra');
const _ = require('lodash');
const async = require('async');
const asar = require('asar');
const packager = require('electron-packager');
const run = require('electron-installer-run');
const zip = require('electron-installer-zip');
const license = require('electron-license');
const ModuleCache = require('hadron-module-cache');
const CompileCache = require('hadron-compile-cache');

const ui = require('./ui');
const verify = require('./verify');

exports.command = 'release';

exports.describe = ':shipit:';

const COMPILE_CACHE = '.compiled-sources';
const COMPILE_CACHE_MAPPINGS = '_compileCacheMappings';
const CACHE_PATTERN = '**/*.{jade,jsx,md}';

/**
 * Clean out the existing development compile cache.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const cleanCompileCache = (CONFIG, done) => {
  cli.debug('cleaning out development compile cache');
  fs.remove(path.resolve(CONFIG.dir, COMPILE_CACHE), function() {
    done();
  });
};

/**
 * Create a precompiled cache of .jade and .jsx sources.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const createCompileCache = (CONFIG, done) => {
  cli.debug('creating compile cache');
  var appDir = path.join(CONFIG.resources, 'app');
  CompileCache.setHomeDirectory(appDir);
  glob(`src/${CACHE_PATTERN}`, function(error, files) {
    cli.abortIfError(error);
    _.each(files, function(file) {
      var compiler = CompileCache.COMPILERS[path.extname(file)];
      CompileCache.compileFileAtPath(compiler, file);
    });
    // Write the compile cache mappings to the package.json.
    var metadata = CONFIG.pkg;
    metadata[COMPILE_CACHE_MAPPINGS] = CompileCache.digestMappings;
    fs.writeFile(metadata._path, JSON.stringify(metadata, null, 2), done);
  });
};

/**
 * Run `electron-packager`
 *
 * @see https://npm.im/electron-packager
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const createBrandedApplication = (CONFIG, done) => {
  cli.debug('running electron-packager');
  packager(CONFIG.packagerOptions, function(err, res) {
    if (err) {
      return done(err);
    }
    cli.debug('Packager result is: ' + JSON.stringify(res, null, 2));

    if (CONFIG.platform !== 'darwin') {
      return done(null, true);
    }

    /**
     * @see https://jira.mongodb.org/browse/INT-1836
     */
    const atomIcns = path.join(CONFIG.resources, 'atom.icns');
    const electronIcns = path.join(CONFIG.resources, 'electron.icns');
    fs.exists(atomIcns, function(exists) {
      if (!exists) {
        return done(null, true);
      }
      fs.remove(electronIcns, function(_err) {
        if (_err) {
          return done(_err);
        }
        fs.move(atomIcns, electronIcns, done);
      });
    });
  });
};

/**
 * Symlinks the Electron executable to the product name.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const symlinkExecutable = (CONFIG, done) => {
  if (CONFIG.platform === 'darwin') {
    cli.debug('Ensuring `Contents/MacOS/Electron` is symlinked');
    const cwd = process.cwd();
    cli.debug('chdir', CONFIG.dest(`${CONFIG.productName}-darwin-x64`, 'Contents', 'MacOS'));
    process.chdir(CONFIG.dest(`${CONFIG.productName}-darwin-x64`, `${CONFIG.productName}.app`, 'Contents', 'MacOS'));

    fs.ensureSymlink(CONFIG.productName, 'Electron', function(_err) {
      process.chdir(cwd);
      if (_err) {
        return done(_err);
      }
      done();
    });
  } else {
    done();
  }
};

/**
 * For some platforms, there will be extraneous (to us) folders generated
 * we can remove to make the generated branded app less cluttered and easier
 * to debug.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const cleanupBrandedApplicationScaffold = (CONFIG, done) => {
  var globsToDelete = [];
  if (CONFIG.platform === 'win32') {
    globsToDelete.push(path.join(CONFIG.resources, '*.pak'));
  } else {
    globsToDelete.push(path.join(CONFIG.resources, '*.lproj'));
  }

  cli.debug('cleaning up extraneous files from template');
  del(globsToDelete, {
    force: true
  }).then(function(paths) {
    cli.debug(format('%d extraneous files removed', paths.length));
    done(null, true);
  }, done);
};

/**
 * Replace the LICENSE file `electron-packager` creates w/ a LICENSE
 * file specific to the project.
 *
 * @see [Atom's generate-license-task.coffee](https://git.io/vaZI7)
 * @param {Object} CONFIG
 * @param {Function} [done] Optional callback
 * @returns {Promise}
 * @api public
 */
const writeLicenseFile = (CONFIG, done) => {
  var LICENSE_DEST = path.join(CONFIG.resources, '..', '..', 'LICENSE');
  var opts = {
    dir: path.join(CONFIG.resources, 'app'),
    production: false,
    excludeOrg: 'mongodb-js,10gen,christkv'
  };
  /**
   * TODO (imlucas) If no license file at `opts.dir`, use `CONFIG`
   * to generate one and write it there before calling `license.build()`
   * or else this fails miserably.
   */
  return license.build(opts)
    .then((contents) => {
      fs.writeFileSync(LICENSE_DEST, contents);
      cli.debug(format('LICENSE written to `%s`', LICENSE_DEST));
      if (done) {
        done(null, true);
      }
    });
};

/**
 * Replace the version file `electron-packager` creates w/ a version
 * file specific to the project.
 *
 * @see [Atom's set-version-task.coffee](https://git.io/vaZkN)
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const writeVersionFile = (CONFIG, done) => {
  const VERSION_DEST = path.join(CONFIG.resources, '..', '..', 'version');
  cli.debug(`Writing version file to ${VERSION_DEST}`);
  fs.writeFile(VERSION_DEST, CONFIG.version, function(err) {
    if (err) {
      return done(err);
    }
    cli.debug(format('version file written to `%s`', VERSION_DEST));
    done(null, CONFIG.version);
  });
};

/**
 * Update the project's `./package.json` (like npm does when it
 * installs a package) for inclusion in the application
 * `electron-packager` creates.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const transformPackageJson = (CONFIG, done) => {
  const PACKAGE_JSON_DEST = path.join(CONFIG.resources, 'app', 'package.json');
  const packageKeysToRemove = [
    'scripts',
    'devDependencies',
    'dependency-check',
    'repository',
    'check',
    'config.hadron.build'
  ];

  let contents = _.omit(CONFIG.pkg, packageKeysToRemove);

  _.assign(contents, {
    productName: CONFIG.productName,
    channel: CONFIG.channel
  });

  fs.writeFile(PACKAGE_JSON_DEST, JSON.stringify(contents, null, 2), done);
};

/**
 * TODO (imlucas) Switch to using http://npm.im/yarn instead of npm.
 *
 * @see [Atom's fingerprint-task.js](https://git.io/vaZLq)
 * @see [Atom's fingerprint.js](https://git.io/vaZLZ)
 * @see [Atom's generate-module-cache-task.coffee](https://git.io/vaY0O)
 * @see [Atom's native-compile-cache](https://git.io/vaY0a)
 * @see [Atom's module-cache.coffee](https://git.io/vaY0K)
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const installDependencies = (CONFIG, done) => {
  var args = [
    'install',
    '--production'
  ];
  cli.debug('Installing dependencies');
  var opts = {
    env: process.env,
    cwd: path.join(CONFIG.resources, 'app')
  };
  run('npm', args, opts, function(err) {
    if (err) {
      return done(err);
    }
    cli.debug('Dependencies installed');
    done();
  });
};

/**
 * Before creating installers for distribution to
 * customers, there are thousands of files
 * they don't need in order to run the application.
 *
 * TODO (imlucas) even more we can remove!  see
 * `EXCLUDE_FROM_RELEASE` in INT-1225.
 *
 * @see https://jira.mongodb.org/browse/INT-1225
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const removeDevelopmentFiles = (CONFIG, done) => {
  if (CONFIG.platform !== 'darwin') {
    done();
    return;
  }
  var DOT_FILES = [
    '.DS_Store',
    '.eslint*',
    '.evergreen*',
    '.travis*',
    '.npm*',
    '.jsfmt*',
    '.git*',
    'report*'
  ];

  var globsToDelete = [
    path.join(CONFIG.resources, 'app', 'test'),
    path.join(CONFIG.resources, 'app', 'scripts')
  ];

  if (CONFIG.platform === 'darwin') {
    globsToDelete.push(path.join(CONFIG.resources,
      'app', '{' + DOT_FILES.join(',') + '}'));
  }

  cli.debug('Checking for extraneous files to remove:\n' +
    JSON.stringify(globsToDelete, null, 2));

  del(globsToDelete).then(function(paths) {
    if (paths.length === 0) {
      cli.debug('No extraneous files to remove');
    } else {
      cli.debug(format('%s extraneous files removed', paths.length));
    }
    done(null, true);
  }, done);
};

/**
 * Package the application as a single `asar` file.
 *
 * @see [Atom's generate-asar-task.coffee](https://git.io/vaY4O)
 * @see https://gist.github.com/imlucas/7a8956cf153595168109
 * @see https://jira.mongodb.org/browse/INT-1225
 * @param {Object} CONFIG
 * @param {Function} done
 */
const createApplicationAsar = (CONFIG, done) => {
  var opts = {
    /**
     * TODO (imlucas) Find a good way to automate generating
     * the hints file using `ELECTRON_LOG_ASAR_READS=1`.
     *
     *  ordering: path.join(process.cwd(),
     *   'resources', 'asar-ordering-hint.txt'),
     */
    unpack: '{' + [
      '*.node',
      '**/vendor/**'
    ].join(',') + '}'
  };

  var src = path.join(CONFIG.resources, 'app');
  var dest = path.join(CONFIG.resources, 'app.asar');

  asar.createPackageWithOptions(src, dest, opts, function() {
    del(src, {force: true}).then(function() {
      done();
    }, done);
  });
};

/**
 * Packages the app as a plain zip using `electron-installer-zip`
 * for auto updates.
 *
 * NOTE (imlucas) This should be run after the installers have been
 * created.  The modules that generate the installers also
 * handle signinging the assets. If we zip unsigned assets
 * and publish them for the release, auto updates will be rejected.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 */
const createApplicationZip = (CONFIG, done) => {
  const DIR = path.join(CONFIG.resources, '..');

  const OUT = CONFIG.assets.filter(function(asset) {
    return path.extname(asset.path) === '.zip';
  })[0].path;

  cli.debug('Zipping `%s` to `%s`', DIR, OUT);
  zip({
    dir: DIR,
    out: OUT,
    platform: CONFIG.platform
  }, done);
};

/**
 * Create the application installer.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const createBrandedInstaller = (CONFIG, done) => {
  cli.debug('Creating installer');
  CONFIG.createInstaller().then(done).catch(done);
};

const createModuleCache = (CONFIG, done) => {
  const appDir = path.join(CONFIG.resources, 'app');
  ModuleCache.create(appDir);

  let metadata = CONFIG.pkg;

  for (let folder in _.get(metadata, '_compassModuleCache.folders')) {
    if (_.includes(folder.paths, '')) {
      folder.paths = ['', 'test', 'src', 'src/app'];
    }
  }
  fs.writeFile(metadata._path, JSON.stringify(metadata, null, 2), done);
};

exports.builder = {
  dir: {
    description: 'Project root directory',
    default: process.cwd()
  }
};

_.assign(exports.builder, ui.builder, verify.builder);

exports.run = (argv, done) => {
  cli.argv = argv;

  const target = new Target(argv.dir);
  const task = (name, fn) => {
    return function(cb) {
      cli.debug(`start: ${name}`);
      fn(target, function(err) {
        if (err) {
          cli.error(err);
          return cb(err);
        }
        cli.debug(`completed: ${name}`);
        cb();
      });
    };
  };

  const tasks = _.flatten([
    function(cb) {
      verify.tasks(argv)
        .then(() => ui.tasks(argv))
        .then(() => cb())
        .catch(cb);
    },
    task('clean compile cache', cleanCompileCache),
    task('create branded application', createBrandedApplication),
    task('create executable symlink', symlinkExecutable),
    task('cleanup branded application scaffold', cleanupBrandedApplicationScaffold),
    task('write version file', writeVersionFile),
    task('transform package.json', transformPackageJson),
    task('install dependencies', installDependencies),
    task('write license file', writeLicenseFile),
    task('create compile cache', createCompileCache),
    task('create module cache', createModuleCache),
    task('remove development files', removeDevelopmentFiles),
    task('create application asar', createApplicationAsar),
    task('create branded installer', createBrandedInstaller),
    task('create application zip', createApplicationZip)
  ]);

  return async.series(tasks, (_err) => {
    if (_err) {
      return done(_err);
    }
    done(null, target);
  });
};

exports.handler = (argv) => {
  exports.run(argv, (_err, CONFIG) => {
    cli.abortIfError(_err);
    cli.ok(`${CONFIG.assets.length} assets successfully built`);
    CONFIG.assets.map(function(asset) {
      cli.info(asset.path);
    });
  });
};
<commit_msg>Fix license and version dest paths<commit_after>'use strict';
/* eslint no-sync: 0 */
/**
 * @see [Atom's publish-build-task.coffee](https://git.io/vaYu3)
 * - https://github.com/atom/electron/blob/master/script/create-dist.py
 */

/**
 * TODO (imlucas) If darwin, dump symbols for breakpad
 * and include in assets.
 * @see [Atom's dump-symbols-task.coffee](https://git.io/va3fG)
 */
const Target = require('../lib/target');
const cli = require('mongodb-js-cli')('hadron-build:release');
const util = require('util');
const format = util.format;
const glob = require('glob');
const path = require('path');
const del = require('del');
const fs = require('fs-extra');
const _ = require('lodash');
const async = require('async');
const asar = require('asar');
const packager = require('electron-packager');
const run = require('electron-installer-run');
const zip = require('electron-installer-zip');
const license = require('electron-license');
const ModuleCache = require('hadron-module-cache');
const CompileCache = require('hadron-compile-cache');

const ui = require('./ui');
const verify = require('./verify');

exports.command = 'release';

exports.describe = ':shipit:';

const COMPILE_CACHE = '.compiled-sources';
const COMPILE_CACHE_MAPPINGS = '_compileCacheMappings';
const CACHE_PATTERN = '**/*.{jade,jsx,md}';

/**
 * Clean out the existing development compile cache.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const cleanCompileCache = (CONFIG, done) => {
  cli.debug('cleaning out development compile cache');
  fs.remove(path.resolve(CONFIG.dir, COMPILE_CACHE), function() {
    done();
  });
};

/**
 * Create a precompiled cache of .jade and .jsx sources.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const createCompileCache = (CONFIG, done) => {
  cli.debug('creating compile cache');
  var appDir = path.join(CONFIG.resources, 'app');
  CompileCache.setHomeDirectory(appDir);
  glob(`src/${CACHE_PATTERN}`, function(error, files) {
    cli.abortIfError(error);
    _.each(files, function(file) {
      var compiler = CompileCache.COMPILERS[path.extname(file)];
      CompileCache.compileFileAtPath(compiler, file);
    });
    // Write the compile cache mappings to the package.json.
    var metadata = CONFIG.pkg;
    metadata[COMPILE_CACHE_MAPPINGS] = CompileCache.digestMappings;
    fs.writeFile(metadata._path, JSON.stringify(metadata, null, 2), done);
  });
};

/**
 * Run `electron-packager`
 *
 * @see https://npm.im/electron-packager
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const createBrandedApplication = (CONFIG, done) => {
  cli.debug('running electron-packager');
  packager(CONFIG.packagerOptions, function(err, res) {
    if (err) {
      return done(err);
    }
    cli.debug('Packager result is: ' + JSON.stringify(res, null, 2));

    if (CONFIG.platform !== 'darwin') {
      return done(null, true);
    }

    /**
     * @see https://jira.mongodb.org/browse/INT-1836
     */
    const atomIcns = path.join(CONFIG.resources, 'atom.icns');
    const electronIcns = path.join(CONFIG.resources, 'electron.icns');
    fs.exists(atomIcns, function(exists) {
      if (!exists) {
        return done(null, true);
      }
      fs.remove(electronIcns, function(_err) {
        if (_err) {
          return done(_err);
        }
        fs.move(atomIcns, electronIcns, done);
      });
    });
  });
};

/**
 * Symlinks the Electron executable to the product name.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const symlinkExecutable = (CONFIG, done) => {
  if (CONFIG.platform === 'darwin') {
    cli.debug('Ensuring `Contents/MacOS/Electron` is symlinked');
    const cwd = process.cwd();
    cli.debug('chdir', CONFIG.dest(`${CONFIG.productName}-darwin-x64`, 'Contents', 'MacOS'));
    process.chdir(CONFIG.dest(`${CONFIG.productName}-darwin-x64`, `${CONFIG.productName}.app`, 'Contents', 'MacOS'));

    fs.ensureSymlink(CONFIG.productName, 'Electron', function(_err) {
      process.chdir(cwd);
      if (_err) {
        return done(_err);
      }
      done();
    });
  } else {
    done();
  }
};

/**
 * For some platforms, there will be extraneous (to us) folders generated
 * we can remove to make the generated branded app less cluttered and easier
 * to debug.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const cleanupBrandedApplicationScaffold = (CONFIG, done) => {
  var globsToDelete = [];
  if (CONFIG.platform === 'win32') {
    globsToDelete.push(path.join(CONFIG.resources, '*.pak'));
  } else {
    globsToDelete.push(path.join(CONFIG.resources, '*.lproj'));
  }

  cli.debug('cleaning up extraneous files from template');
  del(globsToDelete, {
    force: true
  }).then(function(paths) {
    cli.debug(format('%d extraneous files removed', paths.length));
    done(null, true);
  }, done);
};

/**
 * Replace the LICENSE file `electron-packager` creates w/ a LICENSE
 * file specific to the project.
 *
 * @see [Atom's generate-license-task.coffee](https://git.io/vaZI7)
 * @param {Object} CONFIG
 * @param {Function} [done] Optional callback
 * @returns {Promise}
 * @api public
 */
const writeLicenseFile = (CONFIG, done) => {
  var LICENSE_DEST = path.join(CONFIG.appPath, '..', 'LICENSE');
  var opts = {
    dir: path.join(CONFIG.resources, 'app'),
    production: false,
    excludeOrg: 'mongodb-js,10gen,christkv'
  };
  /**
   * TODO (imlucas) If no license file at `opts.dir`, use `CONFIG`
   * to generate one and write it there before calling `license.build()`
   * or else this fails miserably.
   */
  return license.build(opts)
    .then((contents) => {
      fs.writeFileSync(LICENSE_DEST, contents);
      cli.debug(format('LICENSE written to `%s`', LICENSE_DEST));
      if (done) {
        done(null, true);
      }
    });
};

/**
 * Replace the version file `electron-packager` creates w/ a version
 * file specific to the project.
 *
 * @see [Atom's set-version-task.coffee](https://git.io/vaZkN)
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const writeVersionFile = (CONFIG, done) => {
  const VERSION_DEST = path.join(CONFIG.appPath, '..', 'version');
  cli.debug(`Writing version file to ${VERSION_DEST}`);
  fs.writeFile(VERSION_DEST, CONFIG.version, function(err) {
    if (err) {
      return done(err);
    }
    cli.debug(format('version file written to `%s`', VERSION_DEST));
    done(null, CONFIG.version);
  });
};

/**
 * Update the project's `./package.json` (like npm does when it
 * installs a package) for inclusion in the application
 * `electron-packager` creates.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const transformPackageJson = (CONFIG, done) => {
  const PACKAGE_JSON_DEST = path.join(CONFIG.resources, 'app', 'package.json');
  const packageKeysToRemove = [
    'scripts',
    'devDependencies',
    'dependency-check',
    'repository',
    'check',
    'config.hadron.build'
  ];

  let contents = _.omit(CONFIG.pkg, packageKeysToRemove);

  _.assign(contents, {
    productName: CONFIG.productName,
    channel: CONFIG.channel
  });

  fs.writeFile(PACKAGE_JSON_DEST, JSON.stringify(contents, null, 2), done);
};

/**
 * TODO (imlucas) Switch to using http://npm.im/yarn instead of npm.
 *
 * @see [Atom's fingerprint-task.js](https://git.io/vaZLq)
 * @see [Atom's fingerprint.js](https://git.io/vaZLZ)
 * @see [Atom's generate-module-cache-task.coffee](https://git.io/vaY0O)
 * @see [Atom's native-compile-cache](https://git.io/vaY0a)
 * @see [Atom's module-cache.coffee](https://git.io/vaY0K)
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const installDependencies = (CONFIG, done) => {
  var args = [
    'install',
    '--production'
  ];
  cli.debug('Installing dependencies');
  var opts = {
    env: process.env,
    cwd: path.join(CONFIG.resources, 'app')
  };
  run('npm', args, opts, function(err) {
    if (err) {
      return done(err);
    }
    cli.debug('Dependencies installed');
    done();
  });
};

/**
 * Before creating installers for distribution to
 * customers, there are thousands of files
 * they don't need in order to run the application.
 *
 * TODO (imlucas) even more we can remove!  see
 * `EXCLUDE_FROM_RELEASE` in INT-1225.
 *
 * @see https://jira.mongodb.org/browse/INT-1225
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const removeDevelopmentFiles = (CONFIG, done) => {
  if (CONFIG.platform !== 'darwin') {
    done();
    return;
  }
  var DOT_FILES = [
    '.DS_Store',
    '.eslint*',
    '.evergreen*',
    '.travis*',
    '.npm*',
    '.jsfmt*',
    '.git*',
    'report*'
  ];

  var globsToDelete = [
    path.join(CONFIG.resources, 'app', 'test'),
    path.join(CONFIG.resources, 'app', 'scripts')
  ];

  if (CONFIG.platform === 'darwin') {
    globsToDelete.push(path.join(CONFIG.resources,
      'app', '{' + DOT_FILES.join(',') + '}'));
  }

  cli.debug('Checking for extraneous files to remove:\n' +
    JSON.stringify(globsToDelete, null, 2));

  del(globsToDelete).then(function(paths) {
    if (paths.length === 0) {
      cli.debug('No extraneous files to remove');
    } else {
      cli.debug(format('%s extraneous files removed', paths.length));
    }
    done(null, true);
  }, done);
};

/**
 * Package the application as a single `asar` file.
 *
 * @see [Atom's generate-asar-task.coffee](https://git.io/vaY4O)
 * @see https://gist.github.com/imlucas/7a8956cf153595168109
 * @see https://jira.mongodb.org/browse/INT-1225
 * @param {Object} CONFIG
 * @param {Function} done
 */
const createApplicationAsar = (CONFIG, done) => {
  var opts = {
    /**
     * TODO (imlucas) Find a good way to automate generating
     * the hints file using `ELECTRON_LOG_ASAR_READS=1`.
     *
     *  ordering: path.join(process.cwd(),
     *   'resources', 'asar-ordering-hint.txt'),
     */
    unpack: '{' + [
      '*.node',
      '**/vendor/**'
    ].join(',') + '}'
  };

  var src = path.join(CONFIG.resources, 'app');
  var dest = path.join(CONFIG.resources, 'app.asar');

  asar.createPackageWithOptions(src, dest, opts, function() {
    del(src, {force: true}).then(function() {
      done();
    }, done);
  });
};

/**
 * Packages the app as a plain zip using `electron-installer-zip`
 * for auto updates.
 *
 * NOTE (imlucas) This should be run after the installers have been
 * created.  The modules that generate the installers also
 * handle signinging the assets. If we zip unsigned assets
 * and publish them for the release, auto updates will be rejected.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 */
const createApplicationZip = (CONFIG, done) => {
  const DIR = path.join(CONFIG.resources, '..');

  const OUT = CONFIG.assets.filter(function(asset) {
    return path.extname(asset.path) === '.zip';
  })[0].path;

  cli.debug('Zipping `%s` to `%s`', DIR, OUT);
  zip({
    dir: DIR,
    out: OUT,
    platform: CONFIG.platform
  }, done);
};

/**
 * Create the application installer.
 *
 * @param {Object} CONFIG
 * @param {Function} done
 * @api public
 */
const createBrandedInstaller = (CONFIG, done) => {
  cli.debug('Creating installer');
  CONFIG.createInstaller().then(done).catch(done);
};

const createModuleCache = (CONFIG, done) => {
  const appDir = path.join(CONFIG.resources, 'app');
  ModuleCache.create(appDir);

  let metadata = CONFIG.pkg;

  for (let folder in _.get(metadata, '_compassModuleCache.folders')) {
    if (_.includes(folder.paths, '')) {
      folder.paths = ['', 'test', 'src', 'src/app'];
    }
  }
  fs.writeFile(metadata._path, JSON.stringify(metadata, null, 2), done);
};

exports.builder = {
  dir: {
    description: 'Project root directory',
    default: process.cwd()
  }
};

_.assign(exports.builder, ui.builder, verify.builder);

exports.run = (argv, done) => {
  cli.argv = argv;

  const target = new Target(argv.dir);
  const task = (name, fn) => {
    return function(cb) {
      cli.debug(`start: ${name}`);
      fn(target, function(err) {
        if (err) {
          cli.error(err);
          return cb(err);
        }
        cli.debug(`completed: ${name}`);
        cb();
      });
    };
  };

  const tasks = _.flatten([
    function(cb) {
      verify.tasks(argv)
        .then(() => ui.tasks(argv))
        .then(() => cb())
        .catch(cb);
    },
    task('clean compile cache', cleanCompileCache),
    task('create branded application', createBrandedApplication),
    task('create executable symlink', symlinkExecutable),
    task('cleanup branded application scaffold', cleanupBrandedApplicationScaffold),
    task('write version file', writeVersionFile),
    task('transform package.json', transformPackageJson),
    task('install dependencies', installDependencies),
    task('write license file', writeLicenseFile),
    task('create compile cache', createCompileCache),
    task('create module cache', createModuleCache),
    task('remove development files', removeDevelopmentFiles),
    task('create application asar', createApplicationAsar),
    task('create branded installer', createBrandedInstaller),
    task('create application zip', createApplicationZip)
  ]);

  return async.series(tasks, (_err) => {
    if (_err) {
      return done(_err);
    }
    done(null, target);
  });
};

exports.handler = (argv) => {
  exports.run(argv, (_err, CONFIG) => {
    cli.abortIfError(_err);
    cli.ok(`${CONFIG.assets.length} assets successfully built`);
    CONFIG.assets.map(function(asset) {
      cli.info(asset.path);
    });
  });
};
<|endoftext|>


<commit_before>module.exports.alias = [
	'unwatch'
];

module.exports.command = async (message, content, bot, server) => {
  if (!message.member.hasPermission('ADMINISTRATOR')) return;
	if (content == '') {
		message.channel.send('Please specify a user with an ID or mention them');
		return;
	}
	let mentions = message.mentions.members;
	var userID = content;
  if (mentions.size != 0) {
    userID = mentions.firstKey();
  }

	if (server.watchedUsers.includes(userID)) {
		delete server.watchedUsers[userID];
		message.channel.send(`<@${userID}> is now off the hook`);
	} else {
		message.channel.send(`<@${userID}> wasn\'t being watched tho :cirithink:`);
	}
};
<commit_msg>splice<commit_after>module.exports.alias = [
	'unwatch'
];

module.exports.command = async (message, content, bot, server) => {
  if (!message.member.hasPermission('ADMINISTRATOR')) return;
	if (content == '') {
		message.channel.send('Please specify a user with an ID or mention them');
		return;
	}
	let mentions = message.mentions.members;
	var userID = content;
  if (mentions.size != 0) {
    userID = mentions.firstKey();
  }

	if (server.watchedUsers.includes(userID)) {
		var index = server.watchedUsers.indexOf(userID);
    server.watchedUsers.splice(index, 1);
		message.channel.send(`<@${userID}> is now off the hook`);
	} else {
		message.channel.send(`<@${userID}> wasn\'t being watched tho :cirithink:`);
	}
};
<|endoftext|>


<commit_before>if (typeof HotPotatoe === "undefined") {
    HotPotatoe = {};
}

/**
 * Main game object
 *
 * @param {Phaser.Game} game
 * @param {string} id
 * @constructor
 */
HotPotatoe.Game = function(game, id) {
    var self = this;

    this.phaser = game;
    this.id = id;

    this.players = [];

    //Will hold every sprites by their syncId
    this.sprites = {};

    //small fix on server to avoid update before create was called
    this.createDone = false;

    var mainState = {
        preload: function() {
            for (var i = 0; i < self.players.length; i++) {
                self.players[i].preload();
            }
        },
        create: function() {
            if (Meteor.isServer) {
                self.phaser.physics.startSystem(Phaser.Physics.P2JS);
            }
            self.phaser.stage.backgroundColor = '#2d2d2d';

            for (var i = 0; i < self.players.length; i++) {
                self.players[i].create();
                if (Meteor.isServer) {
                    SyncPlayer.insert(self.id, self.players[i]);
                }
            }

            if (Meteor.isClient) {
                //Handling input sent to server
                self.cursors = self.phaser.input.keyboard.createCursorKeys();
                self.cursors.left.onDown.add(InputManager.keyDown, self.cursors.left);
                self.cursors.left.onUp.add(InputManager.keyUp, self.cursors.left);
                self.cursors.right.onDown.add(InputManager.keyDown, self.cursors.right);
                self.cursors.right.onUp.add(InputManager.keyUp, self.cursors.right);
                self.cursors.up.onDown.add(InputManager.keyDown, self.cursors.up);
                self.cursors.up.onUp.add(InputManager.keyUp, self.cursors.up);
                self.cursors.down.onDown.add(InputManager.keyDown, self.cursors.down);
                self.cursors.down.onUp.add(InputManager.keyUp, self.cursors.down);
            }
            self.createDone = true;
        },
        update: function() {
            if (!self.createDone) {
                return;
            }

            for (var i = 0; i < self.players.length; i++) {
                self.players[i].update();
                if (Meteor.isServer) {
                    SyncPlayer.update(self.players[i]);
                }
            }
        }
    };

    this.phaser.state.add('main', mainState);
};

/**
 * Configure game with players
 *
 * @param {string[]} players
 */
HotPotatoe.Game.prototype.setUp = function(players) {
    //Add players to game
    for (var i = 0; i < players.length; i++) {
        this.players.push(new HotPotatoe.Player(this, players[i]));
    }

    if (Meteor.isServer) {
        this.players[new Phaser.RandomDataGenerator().between(0, this.players.length - 1)].setHotPotatoe(true);
    }

    if (Meteor.isClient) {
        //Flag user's player
        for (var j = 0; j < this.players.length; j++) {
            if (this.players[j].id == Session.get('userId')) {
                this.players[j].isCurrentPlayer = true;
            }
        }
    }
};

/**
 * Start game
 */
HotPotatoe.Game.prototype.start = function() {
    this.phaser.state.start('main');
};<commit_msg>Fix for player hot potatoe notification with the new game players package<commit_after>if (typeof HotPotatoe === "undefined") {
    HotPotatoe = {};
}

/**
 * Main game object
 *
 * @param {Phaser.Game} game
 * @param {string} id
 * @constructor
 */
HotPotatoe.Game = function(game, id) {
    var self = this;

    this.phaser = game;
    this.id = id;

    this.players = [];

    //Will hold every sprites by their syncId
    this.sprites = {};

    //small fix on server to avoid update before create was called
    this.createDone = false;

    var mainState = {
        preload: function() {
            for (var i = 0; i < self.players.length; i++) {
                self.players[i].preload();
            }
        },
        create: function() {
            if (Meteor.isServer) {
                self.phaser.physics.startSystem(Phaser.Physics.P2JS);
            }
            self.phaser.stage.backgroundColor = '#2d2d2d';

            for (var i = 0; i < self.players.length; i++) {
                self.players[i].create();
                if (Meteor.isServer) {
                    SyncPlayer.insert(self.id, self.players[i]);
                }
            }

            if (Meteor.isClient) {
                //Handling input sent to server
                self.cursors = self.phaser.input.keyboard.createCursorKeys();
                self.cursors.left.onDown.add(InputManager.keyDown, self.cursors.left);
                self.cursors.left.onUp.add(InputManager.keyUp, self.cursors.left);
                self.cursors.right.onDown.add(InputManager.keyDown, self.cursors.right);
                self.cursors.right.onUp.add(InputManager.keyUp, self.cursors.right);
                self.cursors.up.onDown.add(InputManager.keyDown, self.cursors.up);
                self.cursors.up.onUp.add(InputManager.keyUp, self.cursors.up);
                self.cursors.down.onDown.add(InputManager.keyDown, self.cursors.down);
                self.cursors.down.onUp.add(InputManager.keyUp, self.cursors.down);
            }
            self.createDone = true;
        },
        update: function() {
            if (!self.createDone) {
                return;
            }

            for (var i = 0; i < self.players.length; i++) {
                self.players[i].update();
                if (Meteor.isServer) {
                    SyncPlayer.update(self.players[i]);
                }
            }
        }
    };

    this.phaser.state.add('main', mainState);
};

/**
 * Configure game with players
 *
 * @param {string[]} players
 */
HotPotatoe.Game.prototype.setUp = function(players) {
    //Add players to game
    for (var i = 0; i < players.length; i++) {
        this.players.push(new HotPotatoe.Player(this, players[i]));
    }

    if (Meteor.isServer) {
        this.players[new Phaser.RandomDataGenerator().between(0, this.players.length - 1)].setHotPotatoe(true);
    }

    if (Meteor.isClient) {
        //Flag user's player
        for (var j = 0; j < this.players.length; j++) {
            if (this.players[j].id == GamePlayers.playerId()) {
                this.players[j].isCurrentPlayer = true;
            }
        }
    }
};

/**
 * Start game
 */
HotPotatoe.Game.prototype.start = function() {
    this.phaser.state.start('main');
};<|endoftext|>


<commit_before>/*
 * pygments.js: A node.js wrapper for pygments
 *
 * (C) 2011, Pavan Kumar Sunkara
 *
 */
'use strict';
var spawn = require('child_process').spawn,
    exists = require('path').existsSync,
    fs = require('fs');

var _ = require('underscore');

var pygments = {};

//
// Default timeout threshold for pygments
//
pygments.timeout = 10;

//
// Default binary path for pygmentize
//
pygments.bin = 'pygmentize';

//
// ### function colorize
// #### @target {String} Target to be highlighted
// #### @lexer {String} Lexer to use for highlighting
// #### @format {String} Format for the output
// #### @options {Object} Other options
//
pygments.colorize = function(target, lexer, format, callback, options) {
  options = options || {};
  if(lexer) options['l'] = lexer;
  if(format) options['f'] = format;
  options = this.merge_options(options);
  target = this.stringize(target, (options['force']));
  delete options['force'];

  this.execute(target, options, callback);
};

//
// ### function execute
// #### @target {String} Target to be highlighted
// #### @options {Object} Options
//
pygments.execute = function(target, options, callback) {
  var pyg = spawn(this.bin, this.convert_options(options));
  var chunks = [];
  pyg.stdout.on('data', function(chunk) {
    chunks.push(chunk);
  });
  pyg.stderr.on('data', function (data) {
    console.log(data.toString());
  });
  pyg.on('exit', function() {
    var length = 0;
    chunks.forEach(function(chunk) {
      length += chunk.length;
    });
    var content = new Buffer(length);
    var index = 0;
    chunks.forEach(function(chunk) {
      chunk.copy(content, index, 0, chunk.length);
      index += chunk.length;
    });
    callback(content.toString());
  });
  pyg.stdin.write(target);
  pyg.stdin.end();
};

//
// ### function convert_options
// #### @options {Object} Options to be converted
//
pygments.convert_options = function(options) {
  var cmd = [];
  for(var option in options) {
    validate_args(option, options[option]);
    cmd.push("-"+option + options[option]);
  }
  return cmd;
};

//
// ### function merge_options
// #### @opts {Object} Options to be merged
//
pygments.merge_options = function(options) {
  var default_options = {
    'force': false,
    'l': 'js',
    'f': 'html',
    'O': 'encoding=utf-8'
  };
  return _.defaults(options, default_options);
};

//
// ### function stringize
// #### @target {String} Target to be highlighted
// #### @force {Boolean} Force the target to be string
//
pygments.stringize = function(target, force) {
  force = (force===undefined ? false : force);
  if(exists(target) && !force) {
    var target_stats = fs.statSync(target);
    if(target_stats.isFile()) {
      var target_fd = fs.openSync(target, 'r');
      target = fs.readSync(target_fd, target_stats['size'], null)[0];
      fs.closeSync(target_fd);
    }
  }
  return target;
};

var validate_args = function(flag, value) {
  if(!flag.match(/^[a-z]+$/i)) throw new Error("Flag is invalid: " + flag);
  if(!value.match(/^[a-z0-9\-\_\+\=\#\,\s]+$/i)) throw new Error("Flag value is invalid: -"+flag+" "+value);
};

exports.pygments = pygments;<commit_msg>fixed module.exports<commit_after>/*
 * pygments.js: A node.js wrapper for pygments
 *
 * (C) 2011, Pavan Kumar Sunkara
 *
 */
'use strict';
var spawn = require('child_process').spawn,
    exists = require('path').existsSync,
    fs = require('fs');

var _ = require('underscore');

var pygments = {};

//
// Default timeout threshold for pygments
//
pygments.timeout = 10;

//
// Default binary path for pygmentize
//
pygments.bin = 'pygmentize';

//
// ### function colorize
// #### @target {String} Target to be highlighted
// #### @lexer {String} Lexer to use for highlighting
// #### @format {String} Format for the output
// #### @options {Object} Other options
//
pygments.colorize = function(target, lexer, format, callback, options) {
  options = options || {};
  if(lexer) options['l'] = lexer;
  if(format) options['f'] = format;
  options = this.merge_options(options);
  target = this.stringize(target, (options['force']));
  delete options['force'];

  this.execute(target, options, callback);
};

//
// ### function execute
// #### @target {String} Target to be highlighted
// #### @options {Object} Options
//
pygments.execute = function(target, options, callback) {
  var pyg = spawn(this.bin, this.convert_options(options));
  var chunks = [];
  pyg.stdout.on('data', function(chunk) {
    chunks.push(chunk);
  });
  pyg.stderr.on('data', function (data) {
    console.log(data.toString());
  });
  pyg.on('exit', function() {
    var length = 0;
    chunks.forEach(function(chunk) {
      length += chunk.length;
    });
    var content = new Buffer(length);
    var index = 0;
    chunks.forEach(function(chunk) {
      chunk.copy(content, index, 0, chunk.length);
      index += chunk.length;
    });
    callback(content.toString());
  });
  pyg.stdin.write(target);
  pyg.stdin.end();
};

//
// ### function convert_options
// #### @options {Object} Options to be converted
//
pygments.convert_options = function(options) {
  var cmd = [];
  for(var option in options) {
    validate_args(option, options[option]);
    cmd.push("-"+option + options[option]);
  }
  return cmd;
};

//
// ### function merge_options
// #### @opts {Object} Options to be merged
//
pygments.merge_options = function(options) {
  var default_options = {
    'force': false,
    'l': 'js',
    'f': 'html',
    'O': 'encoding=utf-8'
  };
  return _.defaults(options, default_options);
};

//
// ### function stringize
// #### @target {String} Target to be highlighted
// #### @force {Boolean} Force the target to be string
//
pygments.stringize = function(target, force) {
  force = (force===undefined ? false : force);
  if(exists(target) && !force) {
    var target_stats = fs.statSync(target);
    if(target_stats.isFile()) {
      var target_fd = fs.openSync(target, 'r');
      target = fs.readSync(target_fd, target_stats['size'], null)[0];
      fs.closeSync(target_fd);
    }
  }
  return target;
};

var validate_args = function(flag, value) {
  if(!flag.match(/^[a-z]+$/i)) throw new Error("Flag is invalid: " + flag);
  if(!value.match(/^[a-z0-9\-\_\+\=\#\,\s]+$/i)) throw new Error("Flag value is invalid: -"+flag+" "+value);
};

module.exports = pygments;<|endoftext|>


<commit_before>module.exports = Quadtree;
function Quadtree(options) {
    initialize.call(this, options);
}

Quadtree.prototype.add = add;
Quadtree.prototype.remove = remove;
Quadtree.prototype.check = check;
Quadtree.prototype.update = update;

function initialize(options) {
    options = options || {};
    this.isRoot = options.parent == null;
    if (this.isRoot) {
        this.root = this;
        this.allChildSectors = [];
        this.translate = options.translate || function (obj) {return {x: obj.x, y: obj.y}};
        this.dimension = options.dimension || 1E5;
        this.sectorObjectLimit = options.sectorObjectLimit || 16;
        this.duplicateCoordinateSensitivity = options.duplicateCoordinateSensitivity || .00001;
        configureAsParent.call(this);
    } else {
        this.root = options.parent.root;
        this.parent = options.parent;
        increaseSectorCount.call(this);
        configureAsChild.call(this);
        this.dimension = options.parent.childDimension;
    }

    this.left = options.left || 0;
    this.top = options.top || 0;
    this.childDimension = this.dimension / 2;
    this.objectCount = 0;
    this.sectorCount = 0;
}

/**
 * A parent sector contains other sectors. It does not directly contain objects.
 */
function configureAsParent() {
    this.tree = [];
    this.children = [];
    if (this.objects) {
        var i = this.objects.length;
        while (i--) {
            var obj = this.objects.pop();
            var coordinates = this.root.translate(obj);
            getLowestSectorAtCoordinates.call(this, coordinates.x, coordinates.y, 0, true).add(obj);
        }
    }

    var indexOf = this.root.allChildSectors.indexOf(this);
    if (indexOf > -1) this.root.allChildSectors.splice(indexOf, 1);

    this.isChildSector = false;
    this.objects = null;
    this.nearbyObjects = null;
    this.nearbySectors = null;
    this.far = null;
}

/**
 * A child sector does not contain other sectors. It directly contains objects.
 */
function configureAsChild() {
    if (this.parent.children.indexOf(this) == -1) {
        this.parent.children.push(this);
        // TODO: I once thought this was necessary. I don't currently understand why.
        orderArray.call(this.parent.children);
    }

    if (this.root.allChildSectors.indexOf(this) === -1) {
        this.root.allChildSectors.push(this);
        // TODO: I once thought this was necessary. I don't currently understand why.
        orderArray.call(this.root.allChildSectors);
    }

    this.isChildSector = true;
    this.tree = null;
    this.children = null;
    this.objects = [];
    this.nearbyObjects = [];
    this.nearbySectors = [];
    this.far = [];
}

function convertToParent() {
    configureAsParent.call(this);
    this.root.allChildSectors.splice(this.root.allChildSectors.indexOf(this), 1);
}

function update() {
    updateNearby.call(this);
    updateFar.call(this);
}
function updateNearby() {
    this.nearbySectors = [];
    this.nearbyObjects = [];
    var x = this.left;
    var y = this.top;

    for (var ix = x - 1; ix <= x + 1; ix++) {
        for (var iy = y - 1; iy <= y + 1; iy++) {
            var temp = getLowestSectorAtCoordinates.call(this.root, ix * this.dimension, iy * this.dimension, this.dimension, false);
            if (temp != null && this.nearbySectors.indexOf(temp) == -1) {
                this.nearbySectors.push(temp);
                var allObj = getAllObjects.call(temp);
                var k = allObj.length;
                while (k--) this.nearbyObjects.push(allObj[k]);
            }
        }
    }
}
function updateFar() {
    this.far = [];
    var i = this.root.allChildSectors.length;
    while (i--) {
        var temp = this.root.allChildSectors[i];
        if (this.nearbySectors.indexOf(temp) == -1) {
            var j = this.nearbySectors.length, check = true;
            while (j--) {
                if (getAllChildren.call(this.nearbySectors[j]).indexOf(temp) >= 0) check = false;
            }
            if (check) this.far.push(temp);
        }
    }
}

/**
 * Finds the lowest sector at the specified coordinate.
 */
function increaseSectorCount() {
    var sector = this;
    while (sector.parent != null) {
        sector = sector.parent;
        sector.sectorCount++;
    }
}
function decreaseSectorCount() {
    var sector = this;
    while (sector.parent != null) {
        sector.sectorCount--;
        sector = sector.parent;
    }
}
function getObjectSector(obj) {
    var coordinate = this.root.translate(obj);
    return getLowestSectorAtCoordinates.call(this, coordinate.x, coordinate.y, 0, false);
}
function getLowestSectorAtCoordinates(x, y, dimension, createIfNotFound) {
    var sector = this;
    var left;
    var top;
    while (sector.tree != null) {
        left = Math.floor(x / sector.childDimension);
        top = Math.floor(y / sector.childDimension);
        var treeX = sector.tree[left];
        if (!createIfNotFound && treeX == null) return null;
        if (treeX == null) {
            treeX = sector.tree[left] = [];
            sector = treeX[top] = new Quadtree({parent: sector, left: left, top: top});
        } else {
            var treeY = treeX[top];
            if (!createIfNotFound && treeY == null) return null;
            sector = treeX[top] = (treeY != null ? treeY : new Quadtree({parent: sector, left: left, top: top}));
        }

        var countAtSameCoordinate = getObjectCountAtSameCoordinate.call(sector, {x: x, y: y});
        if (countAtSameCoordinate < this.root.sectorObjectLimit && isSectorFull.call(sector) && sector.isChildSector) {
            convertToParent.call(sector);
        }

        if (sector.dimension == dimension) break;
    }
    return sector;
}

/**
 * This recursive method will return all child sectors underneath the current sector.
 * @returns {Array}
 */
function getAllChildren() {
    if (this.children == null) return [];
    var i = this.children.length;
    var array = [];
    while (i--) {
        var child = this.children[i];
        array.push(child);
        var childChildren = getAllChildren.call(child);
        var k = childChildren.length;
        while (k--) array.push(childChildren[k]);
    }
    return array;
}
/**
 * This recursive method will return all objects in or underneath the current sector.
 * @returns {Array}
 */
function getAllObjects() {
    if (this.objects)
        return this.objects;
    else {
        var i = this.children.length, array = [];
        while (i--) {
            var objects = getAllObjects.call(this.children[i]);
            var j = objects.length - 1, k = -1;
            while (k++ < j) array.push(objects[k]);
        }
        return array;
    }
}

// Done Refactoring
function orderArray() {
    var i = this.length;
    while (i-- > 1) {
        var c1 = this[i];
        var c2 = this[i - 1];
        if (c1.left < c2.left || c1.left == c2.left && c1.top < c2.top) {
            this.push(this.splice(i - 1, 1)[0]);
        }
    }
}
function isSectorFull() {
    return this.objectCount >= this.root.sectorObjectLimit;
}

function add(obj) {
    var coordinate = this.root.translate(obj);
    var sector = getLowestSectorAtCoordinates.call(this, coordinate.x, coordinate.y, 0, true);
    addObjectToSelf.call(sector);
    addObjectToNearbyObjects.call(sector, obj);
    addObjectToParents.call(sector);

}
function remove(obj) {
    var sector = getObjectSector.call(this, obj);
    removeObjectFromSelf.call(sector, obj);
    removeObjectFromNearbySectors.call(sector, obj);
    removeObjectFromParents.call(sector);
}

function addObjectToSelf(obj) {
    this.objectCount++;
    this.objects.push(obj);
    this.nearbyObjects.push(obj);
}
function removeObjectFromSelf(obj) {
    var objectIndex = this.objects.indexOf(obj);
    this.objectCount--;
    this.objects.splice(objectIndex, 1);

    var nearbyObjectsIndex = this.nearbyObjects.indexOf(obj);
    if (nearbyObjectsIndex !== -1) this.nearbyObjects.splice(nearbyObjectsIndex, 1);

    if (this.objectCount == 0) {
        var indexOf = this.root.allChildSectors.indexOf(this);
        if (indexOf > -1) this.root.allChildSectors.splice(indexOf, 1);
    }
}

function addObjectToParents() {
    var parent = this.parent;
    while (parent != null) {
        parent.objectCount++;
        parent = parent.parent;
    }
}
function removeObjectFromParents() {
    var parent = this.parent;
    while (parent != null) {
        parent.objectCount--;
        if (parent.objectCount == 0 && parent.parent != null) {
            decreaseSectorCount.call(parent);
            configureAsChild.call(parent);
        }
        parent = parent.parent;
    }
}

function addObjectToNearbyObjects(obj) {
    var nearbySectorsIndex = this.nearbySectors.length;
    var nearbySector;
    while (nearbySectorsIndex--) {
        nearbySector = this.nearbySectors[nearbySectorsIndex];
        if (nearbySector.nearbyObjects != null)
            nearbySector.nearbyObjects.push(obj);
    }
}
function removeObjectFromNearbySectors(obj) {
    var nearbySectorsIndex = this.nearbySectors.length;
    var nearbySector;
    var indexOf;
    while (nearbySectorsIndex--) {
        nearbySector = this.nearbySectors[nearbySectorsIndex];
        if (nearbySector.nearbyObjects != null) {
            indexOf = nearbySector.nearbyObjects.indexOf(obj);
            if (indexOf > -1) nearbySector.nearbyObjects.splice(indexOf, 1);
        }
    }
}

function getObjectCountAtSameCoordinate(coordinate) {
    var countAtSameCoordinate = 0;
    var childrenIndex = this.objects.length;
    while (childrenIndex--) {
        var treeObject = this.objects[childrenIndex];
        if (Math.abs(treeObject.x - coordinate.x) < this.root.duplicateCoordinateSensitivity &&
            Math.abs(treeObject.y - coordinate.y) < this.root.duplicateCoordinateSensitivity)
            countAtSameCoordinate++;
    }
    return countAtSameCoordinate;
}<commit_msg>fix comment locale<commit_after>module.exports = Quadtree;
function Quadtree(options) {
    initialize.call(this, options);
}

Quadtree.prototype.add = add;
Quadtree.prototype.remove = remove;
Quadtree.prototype.check = check;
Quadtree.prototype.update = update;

function initialize(options) {
    options = options || {};
    this.isRoot = options.parent == null;
    if (this.isRoot) {
        this.root = this;
        this.allChildSectors = [];
        this.translate = options.translate || function (obj) {return {x: obj.x, y: obj.y}};
        this.dimension = options.dimension || 1E5;
        this.sectorObjectLimit = options.sectorObjectLimit || 16;
        this.duplicateCoordinateSensitivity = options.duplicateCoordinateSensitivity || .00001;
        configureAsParent.call(this);
    } else {
        this.root = options.parent.root;
        this.parent = options.parent;
        increaseSectorCount.call(this);
        configureAsChild.call(this);
        this.dimension = options.parent.childDimension;
    }

    this.left = options.left || 0;
    this.top = options.top || 0;
    this.childDimension = this.dimension / 2;
    this.objectCount = 0;
    this.sectorCount = 0;
}

/**
 * A parent sector contains other sectors. It does not directly contain objects.
 */
function configureAsParent() {
    this.tree = [];
    this.children = [];
    if (this.objects) {
        var i = this.objects.length;
        while (i--) {
            var obj = this.objects.pop();
            var coordinates = this.root.translate(obj);
            getLowestSectorAtCoordinates.call(this, coordinates.x, coordinates.y, 0, true).add(obj);
        }
    }

    var indexOf = this.root.allChildSectors.indexOf(this);
    if (indexOf > -1) this.root.allChildSectors.splice(indexOf, 1);

    this.isChildSector = false;
    this.objects = null;
    this.nearbyObjects = null;
    this.nearbySectors = null;
    this.far = null;
}

/**
 * A child sector does not contain other sectors. It directly contains objects.
 */
function configureAsChild() {
    if (this.parent.children.indexOf(this) == -1) {
        this.parent.children.push(this);
        // TODO: I once thought this was necessary. I don't currently understand why.
        orderArray.call(this.parent.children);
    }

    if (this.root.allChildSectors.indexOf(this) === -1) {
        this.root.allChildSectors.push(this);
        // TODO: I once thought this was necessary. I don't currently understand why.
        orderArray.call(this.root.allChildSectors);
    }

    this.isChildSector = true;
    this.tree = null;
    this.children = null;
    this.objects = [];
    this.nearbyObjects = [];
    this.nearbySectors = [];
    this.far = [];
}

function convertToParent() {
    configureAsParent.call(this);
    this.root.allChildSectors.splice(this.root.allChildSectors.indexOf(this), 1);
}

function update() {
    updateNearby.call(this);
    updateFar.call(this);
}
function updateNearby() {
    this.nearbySectors = [];
    this.nearbyObjects = [];
    var x = this.left;
    var y = this.top;

    for (var ix = x - 1; ix <= x + 1; ix++) {
        for (var iy = y - 1; iy <= y + 1; iy++) {
            var temp = getLowestSectorAtCoordinates.call(this.root, ix * this.dimension, iy * this.dimension, this.dimension, false);
            if (temp != null && this.nearbySectors.indexOf(temp) == -1) {
                this.nearbySectors.push(temp);
                var allObj = getAllObjects.call(temp);
                var k = allObj.length;
                while (k--) this.nearbyObjects.push(allObj[k]);
            }
        }
    }
}
function updateFar() {
    this.far = [];
    var i = this.root.allChildSectors.length;
    while (i--) {
        var temp = this.root.allChildSectors[i];
        if (this.nearbySectors.indexOf(temp) == -1) {
            var j = this.nearbySectors.length, check = true;
            while (j--) {
                if (getAllChildren.call(this.nearbySectors[j]).indexOf(temp) >= 0) check = false;
            }
            if (check) this.far.push(temp);
        }
    }
}

function increaseSectorCount() {
    var sector = this;
    while (sector.parent != null) {
        sector = sector.parent;
        sector.sectorCount++;
    }
}
function decreaseSectorCount() {
    var sector = this;
    while (sector.parent != null) {
        sector.sectorCount--;
        sector = sector.parent;
    }
}
function getObjectSector(obj) {
    var coordinate = this.root.translate(obj);
    return getLowestSectorAtCoordinates.call(this, coordinate.x, coordinate.y, 0, false);
}

/**
 * Finds the lowest sector at the specified coordinate.
 */
function getLowestSectorAtCoordinates(x, y, dimension, createIfNotFound) {
    var sector = this;
    var left;
    var top;
    while (sector.tree != null) {
        left = Math.floor(x / sector.childDimension);
        top = Math.floor(y / sector.childDimension);
        var treeX = sector.tree[left];
        if (!createIfNotFound && treeX == null) return null;
        if (treeX == null) {
            treeX = sector.tree[left] = [];
            sector = treeX[top] = new Quadtree({parent: sector, left: left, top: top});
        } else {
            var treeY = treeX[top];
            if (!createIfNotFound && treeY == null) return null;
            sector = treeX[top] = (treeY != null ? treeY : new Quadtree({parent: sector, left: left, top: top}));
        }

        var countAtSameCoordinate = getObjectCountAtSameCoordinate.call(sector, {x: x, y: y});
        if (countAtSameCoordinate < this.root.sectorObjectLimit && isSectorFull.call(sector) && sector.isChildSector) {
            convertToParent.call(sector);
        }

        if (sector.dimension == dimension) break;
    }
    return sector;
}

/**
 * This recursive method will return all child sectors underneath the current sector.
 * @returns {Array}
 */
function getAllChildren() {
    if (this.children == null) return [];
    var i = this.children.length;
    var array = [];
    while (i--) {
        var child = this.children[i];
        array.push(child);
        var childChildren = getAllChildren.call(child);
        var k = childChildren.length;
        while (k--) array.push(childChildren[k]);
    }
    return array;
}
/**
 * This recursive method will return all objects in or underneath the current sector.
 * @returns {Array}
 */
function getAllObjects() {
    if (this.objects)
        return this.objects;
    else {
        var i = this.children.length, array = [];
        while (i--) {
            var objects = getAllObjects.call(this.children[i]);
            var j = objects.length - 1, k = -1;
            while (k++ < j) array.push(objects[k]);
        }
        return array;
    }
}

// Done Refactoring
function orderArray() {
    var i = this.length;
    while (i-- > 1) {
        var c1 = this[i];
        var c2 = this[i - 1];
        if (c1.left < c2.left || c1.left == c2.left && c1.top < c2.top) {
            this.push(this.splice(i - 1, 1)[0]);
        }
    }
}
function isSectorFull() {
    return this.objectCount >= this.root.sectorObjectLimit;
}

function add(obj) {
    var coordinate = this.root.translate(obj);
    var sector = getLowestSectorAtCoordinates.call(this, coordinate.x, coordinate.y, 0, true);
    addObjectToSelf.call(sector);
    addObjectToNearbyObjects.call(sector, obj);
    addObjectToParents.call(sector);

}
function remove(obj) {
    var sector = getObjectSector.call(this, obj);
    removeObjectFromSelf.call(sector, obj);
    removeObjectFromNearbySectors.call(sector, obj);
    removeObjectFromParents.call(sector);
}

function addObjectToSelf(obj) {
    this.objectCount++;
    this.objects.push(obj);
    this.nearbyObjects.push(obj);
}
function removeObjectFromSelf(obj) {
    var objectIndex = this.objects.indexOf(obj);
    this.objectCount--;
    this.objects.splice(objectIndex, 1);

    var nearbyObjectsIndex = this.nearbyObjects.indexOf(obj);
    if (nearbyObjectsIndex !== -1) this.nearbyObjects.splice(nearbyObjectsIndex, 1);

    if (this.objectCount == 0) {
        var indexOf = this.root.allChildSectors.indexOf(this);
        if (indexOf > -1) this.root.allChildSectors.splice(indexOf, 1);
    }
}

function addObjectToParents() {
    var parent = this.parent;
    while (parent != null) {
        parent.objectCount++;
        parent = parent.parent;
    }
}
function removeObjectFromParents() {
    var parent = this.parent;
    while (parent != null) {
        parent.objectCount--;
        if (parent.objectCount == 0 && parent.parent != null) {
            decreaseSectorCount.call(parent);
            configureAsChild.call(parent);
        }
        parent = parent.parent;
    }
}

function addObjectToNearbyObjects(obj) {
    var nearbySectorsIndex = this.nearbySectors.length;
    var nearbySector;
    while (nearbySectorsIndex--) {
        nearbySector = this.nearbySectors[nearbySectorsIndex];
        if (nearbySector.nearbyObjects != null)
            nearbySector.nearbyObjects.push(obj);
    }
}
function removeObjectFromNearbySectors(obj) {
    var nearbySectorsIndex = this.nearbySectors.length;
    var nearbySector;
    var indexOf;
    while (nearbySectorsIndex--) {
        nearbySector = this.nearbySectors[nearbySectorsIndex];
        if (nearbySector.nearbyObjects != null) {
            indexOf = nearbySector.nearbyObjects.indexOf(obj);
            if (indexOf > -1) nearbySector.nearbyObjects.splice(indexOf, 1);
        }
    }
}

function getObjectCountAtSameCoordinate(coordinate) {
    var countAtSameCoordinate = 0;
    var childrenIndex = this.objects.length;
    while (childrenIndex--) {
        var treeObject = this.objects[childrenIndex];
        if (Math.abs(treeObject.x - coordinate.x) < this.root.duplicateCoordinateSensitivity &&
            Math.abs(treeObject.y - coordinate.y) < this.root.duplicateCoordinateSensitivity)
            countAtSameCoordinate++;
    }
    return countAtSameCoordinate;
}<|endoftext|>