<commit_before>var fs = require("fs");
var files = require("./files");
var index = require("./index");
var objects = require("./objects");
var refs = require("./refs");
var diff = require("./diff");
var checkout = require("./checkout");
var util = require("./util");
var parseOptions = require("./parse-options");
var config = require("./config");

var gitlet = module.exports = {
  init: function(_) {
    if (files.inRepo()) { return; }

    files.writeFilesFromTree({
      ".gitlet": {
        HEAD: "ref: refs/heads/master\n",
        config: "\n",
        objects: {},
        refs: {
          heads: {},
        }
      }
    }, process.cwd());
  },

  add: function(path, _) {
    files.assertInRepo();

    var addedFiles = files.lsRecursive(path);
    if (addedFiles.length === 0) {
      throw "fatal: pathspec '" + files.pathFromRepoRoot(path) + "' did not match any files";
    } else {
      for (var i = 0; i < addedFiles.length; i++) {
        this.update_index(addedFiles[i], { add: true });
      }
    }
  },

  update_index: function(path, opts) {
    files.assertInRepo();
    opts = opts || {};

    var pathFromRoot = files.pathFromRepoRoot(path)
    if (!fs.existsSync(path)) {
      throw "error: " + pathFromRoot + ": does not exist\n";
    } else if (fs.statSync(path).isDirectory()) {
      throw "error: " + pathFromRoot + ": is a directory - add files inside instead\n";
    } else if (!index.readHasFile(path) && opts.add === undefined) {
      throw "error: " + pathFromRoot  + ": cannot add to the index - missing --add option?\n";
    } else {
      index.writeFile(path);
    }
  },

  hash_object: function(file, opts) {
    files.assertInRepo();
    opts = opts || {};

    if (!fs.existsSync(file)) {
      throw "fatal: Cannot open '" + file + "': No such file or directory"
    } else {
      var fileContents = files.read(file);
      if (opts.w) {
        return objects.write(fileContents);
      }

      return util.hash(fileContents);
    }
  },

  write_tree: function(_) {
    files.assertInRepo();
    return objects.writeTree(files.nestFlatTree(index.read()));
  },

  commit: function(opts) {
    files.assertInRepo();

    var headHash = refs.readHash("HEAD");
    var treeHash = this.write_tree();
    var headDesc = refs.readIsHeadDetached() ? "detached HEAD" : refs.readCurrentBranchName();

    if (headHash !== undefined &&
        treeHash === objects.treeHash(objects.read(headHash))) {
      throw "# On " + headDesc + "\n" + "nothing to commit, working directory clean";
    } else {
      var parentHashes = headHash === undefined ? [] : [headHash];
      var commmitHash = objects.write(objects.composeCommit(treeHash, opts.m, parentHashes));
      this.update_ref("HEAD", commmitHash);
      return "[" + headDesc + " " + commmitHash + "] " + opts.m;
    }
  },

  branch: function(name, opts) {
    files.assertInRepo();
    opts = opts || {};

    if (name === undefined && opts.u === undefined) {
      return Object.keys(refs.readLocalHeads()).map(function(branch) {
        return (branch === refs.readCurrentBranchName() ? "* " : "  ") + branch;
      }).join("\n") + "\n";
    } else if (refs.readHash("HEAD") === undefined) {
      throw "fatal: Not a valid object name: 'master'.";
    } else if (name === undefined && opts.u !== undefined) {
      var rem = opts.u.split("/");

      if (refs.readIsHeadDetached()) {
        throw "fatal: could not set upstream of HEAD to " + opts.u +
          " when it does not point to any branch.";
      } else if (!refs.readExists("refs/remotes/" + rem[0] + "/" + rem[1])) {
        throw "error: the requested upstream branch '" + opts.u + "' does not exist";
      } else {
        config.write(util.assocIn(config.read(), ["branch", rem[1], "remote", rem[0]]));
        return "Branch " + refs.readCurrentBranchName() +
          " set up to track remote branch " + rem[1] + " from " + rem[0] + ".";
      }
    } else if (refs.readExists(refs.toLocalRef(name))) {
      throw "fatal: A branch named '" + name + "' already exists.";
    } else {
      refs.writeLocal(refs.toLocalRef(name), refs.readHash("HEAD"));
    }
  },

  update_ref: function(refToUpdate, refToUpdateTo, _) {
    files.assertInRepo();

    var hash = refs.readHash(refToUpdateTo);
    if (!objects.readExists(hash)) {
      throw "fatal: " + refToUpdateTo + ": not a valid SHA1";
    } else if (!refs.isRef(refToUpdate)) {
      throw "fatal: Cannot lock the ref " + refToUpdate + ".";
    } else if (objects.type(objects.read(hash)) !== "commit") {
      throw "error: Trying to write non-commit object " + hash + " to branch " +
        refs.readTerminalRef(refToUpdate) + "\n";
    } else {
      refs.writeLocal(refs.readTerminalRef(refToUpdate), hash);
    }
  },

  checkout: function(ref, _) {
    files.assertInRepo();

    var hash = refs.readHash(ref);
    if (!objects.readExists(hash)) {
      throw "error: pathspec " + ref + " did not match any file(s) known to gitlet."
    } else if (objects.type(objects.read(hash)) !== "commit") {
      throw "fatal: reference is not a tree: " + ref;
    } else {
      var paths = checkout.readChangedFilesCheckoutWouldOverwrite(hash);
      if (paths.length > 0) {
        throw "error: Aborting. Your local changes to these files would be overwritten:\n" +
	        paths.join("\n") + "\n";
      } else {
        process.chdir(files.repoDir());
        checkout.writeCheckout(ref);
        return objects.readExists(ref) ?
          "Note: checking out " + ref + "\nYou are in 'detached HEAD' state." :
          "Switched to branch '" + ref + "'\n";
      }
    }
  },

  diff: function(ref1, ref2, opts) {
    files.assertInRepo();

    if (ref1 !== undefined && refs.readHash(ref1) === undefined) {
      throw "fatal: ambiguous argument " + ref1 + ": unknown revision";
    } else if (ref2 !== undefined && refs.readHash(ref2) === undefined) {
      throw "fatal: ambiguous argument " + ref2 + ": unknown revision";
    } else {
      if (opts["name-status"] !== true) {
        throw "unsupported"; // for now
      } else {
        var nameToStatus = diff.readDiff(ref1, ref2);
        return Object.keys(nameToStatus)
          .map(function(path) { return nameToStatus[path] + " " + path; })
          .join("\n") + "\n";
      }
    }
  },

  remote: function(command, name, path, _) {
    files.assertInRepo();

    if (command !== "add") {
      throw "unsupported";
    } else if (name in config.read()["remote"]) {
      throw "fatal: remote " + name + " already exists.";
    } else if (command === "add") {
      config.write(util.assocIn(config.read(), ["remote", name, "url", path]));
      return "\n";
    }
  },

  fetch: function(remote, _) {
    files.assertInRepo();

    if (remote === undefined) {
      throw "unsupported";
    } else if (!(remote in config.read().remote)) {
      throw "fatal: '" + remote + "' does not appear to be a git repository";
    } else {
      var localUrl = files.repoDir();
      var remoteUrl = config.read().remote[remote].url;

      process.chdir(remoteUrl);
      var remoteRefs = refs.readLocalHeads();
      var remoteObjects = objects.readAllHashes().map(objects.read);

      process.chdir(localUrl);
      remoteObjects.forEach(objects.write);
      Object.keys(remoteRefs).forEach(function(r){refs.writeRemote(remote, r, remoteRefs[r])});
      refs.writeFetchHead(remoteRefs, remoteUrl);

      return "From " + remoteUrl + "\n" +
        "Count " + remoteObjects.length + "\n" +
        util.difference(Object.keys(remoteRefs), Object.keys(refs.readLocalHeads()))
          .map(function(b) { return "* [new branch] " + b + " -> " + remote + "/" + b; })
          .join("\n") + "\n";
    }
  }
};

var runCli = module.exports.runCli = function (argv) {
  var rawArgs = parseOptions(argv);
  var commandFnName = rawArgs._[2].replace(/-/g, "_");
  var fn = gitlet[commandFnName];
  var commandArgs = rawArgs._.slice(3);
  var unspecifiedArgs = Array
      .apply(null, new Array(fn.length - commandArgs.length - 1))
      .map(function() { return undefined; });
  return fn.apply(gitlet, commandArgs.concat(unspecifiedArgs).concat(rawArgs));
};

if (require.main === module) {
  var result = runCli(process.argv);
  if (result !== undefined) {
    console.log(result);
  }
}
<commit_msg>Use new fn<commit_after>var fs = require("fs");
var files = require("./files");
var index = require("./index");
var objects = require("./objects");
var refs = require("./refs");
var diff = require("./diff");
var checkout = require("./checkout");
var util = require("./util");
var parseOptions = require("./parse-options");
var config = require("./config");

var gitlet = module.exports = {
  init: function(_) {
    if (files.inRepo()) { return; }

    files.writeFilesFromTree({
      ".gitlet": {
        HEAD: "ref: refs/heads/master\n",
        config: "\n",
        objects: {},
        refs: {
          heads: {},
        }
      }
    }, process.cwd());
  },

  add: function(path, _) {
    files.assertInRepo();

    var addedFiles = files.lsRecursive(path);
    if (addedFiles.length === 0) {
      throw "fatal: pathspec '" + files.pathFromRepoRoot(path) + "' did not match any files";
    } else {
      for (var i = 0; i < addedFiles.length; i++) {
        this.update_index(addedFiles[i], { add: true });
      }
    }
  },

  update_index: function(path, opts) {
    files.assertInRepo();
    opts = opts || {};

    var pathFromRoot = files.pathFromRepoRoot(path)
    if (!fs.existsSync(path)) {
      throw "error: " + pathFromRoot + ": does not exist\n";
    } else if (fs.statSync(path).isDirectory()) {
      throw "error: " + pathFromRoot + ": is a directory - add files inside instead\n";
    } else if (!index.readHasFile(path) && opts.add === undefined) {
      throw "error: " + pathFromRoot  + ": cannot add to the index - missing --add option?\n";
    } else {
      index.writeFile(path);
    }
  },

  hash_object: function(file, opts) {
    files.assertInRepo();
    opts = opts || {};

    if (!fs.existsSync(file)) {
      throw "fatal: Cannot open '" + file + "': No such file or directory"
    } else {
      var fileContents = files.read(file);
      if (opts.w) {
        return objects.write(fileContents);
      }

      return util.hash(fileContents);
    }
  },

  write_tree: function(_) {
    files.assertInRepo();
    return objects.writeTree(files.nestFlatTree(index.read()));
  },

  commit: function(opts) {
    files.assertInRepo();

    var headHash = refs.readHash("HEAD");
    var treeHash = this.write_tree();
    var headDesc = refs.readIsHeadDetached() ? "detached HEAD" : refs.readCurrentBranchName();

    if (headHash !== undefined &&
        treeHash === objects.treeHash(objects.read(headHash))) {
      throw "# On " + headDesc + "\n" + "nothing to commit, working directory clean";
    } else {
      var parentHashes = headHash === undefined ? [] : [headHash];
      var commmitHash = objects.write(objects.composeCommit(treeHash, opts.m, parentHashes));
      this.update_ref("HEAD", commmitHash);
      return "[" + headDesc + " " + commmitHash + "] " + opts.m;
    }
  },

  branch: function(name, opts) {
    files.assertInRepo();
    opts = opts || {};

    if (name === undefined && opts.u === undefined) {
      return Object.keys(refs.readLocalHeads()).map(function(branch) {
        return (branch === refs.readCurrentBranchName() ? "* " : "  ") + branch;
      }).join("\n") + "\n";
    } else if (refs.readHash("HEAD") === undefined) {
      throw "fatal: Not a valid object name: 'master'.";
    } else if (name === undefined && opts.u !== undefined) {
      var rem = opts.u.split("/");

      if (refs.readIsHeadDetached()) {
        throw "fatal: could not set upstream of HEAD to " + opts.u +
          " when it does not point to any branch.";
      } else if (!refs.readExists(refs.toRemoteRef(rem[0], rem[1]))) {
        throw "error: the requested upstream branch '" + opts.u + "' does not exist";
      } else {
        config.write(util.assocIn(config.read(), ["branch", rem[1], "remote", rem[0]]));
        return "Branch " + refs.readCurrentBranchName() +
          " set up to track remote branch " + rem[1] + " from " + rem[0] + ".";
      }
    } else if (refs.readExists(refs.toLocalRef(name))) {
      throw "fatal: A branch named '" + name + "' already exists.";
    } else {
      refs.writeLocal(refs.toLocalRef(name), refs.readHash("HEAD"));
    }
  },

  update_ref: function(refToUpdate, refToUpdateTo, _) {
    files.assertInRepo();

    var hash = refs.readHash(refToUpdateTo);
    if (!objects.readExists(hash)) {
      throw "fatal: " + refToUpdateTo + ": not a valid SHA1";
    } else if (!refs.isRef(refToUpdate)) {
      throw "fatal: Cannot lock the ref " + refToUpdate + ".";
    } else if (objects.type(objects.read(hash)) !== "commit") {
      throw "error: Trying to write non-commit object " + hash + " to branch " +
        refs.readTerminalRef(refToUpdate) + "\n";
    } else {
      refs.writeLocal(refs.readTerminalRef(refToUpdate), hash);
    }
  },

  checkout: function(ref, _) {
    files.assertInRepo();

    var hash = refs.readHash(ref);
    if (!objects.readExists(hash)) {
      throw "error: pathspec " + ref + " did not match any file(s) known to gitlet."
    } else if (objects.type(objects.read(hash)) !== "commit") {
      throw "fatal: reference is not a tree: " + ref;
    } else {
      var paths = checkout.readChangedFilesCheckoutWouldOverwrite(hash);
      if (paths.length > 0) {
        throw "error: Aborting. Your local changes to these files would be overwritten:\n" +
	        paths.join("\n") + "\n";
      } else {
        process.chdir(files.repoDir());
        checkout.writeCheckout(ref);
        return objects.readExists(ref) ?
          "Note: checking out " + ref + "\nYou are in 'detached HEAD' state." :
          "Switched to branch '" + ref + "'\n";
      }
    }
  },

  diff: function(ref1, ref2, opts) {
    files.assertInRepo();

    if (ref1 !== undefined && refs.readHash(ref1) === undefined) {
      throw "fatal: ambiguous argument " + ref1 + ": unknown revision";
    } else if (ref2 !== undefined && refs.readHash(ref2) === undefined) {
      throw "fatal: ambiguous argument " + ref2 + ": unknown revision";
    } else {
      if (opts["name-status"] !== true) {
        throw "unsupported"; // for now
      } else {
        var nameToStatus = diff.readDiff(ref1, ref2);
        return Object.keys(nameToStatus)
          .map(function(path) { return nameToStatus[path] + " " + path; })
          .join("\n") + "\n";
      }
    }
  },

  remote: function(command, name, path, _) {
    files.assertInRepo();

    if (command !== "add") {
      throw "unsupported";
    } else if (name in config.read()["remote"]) {
      throw "fatal: remote " + name + " already exists.";
    } else if (command === "add") {
      config.write(util.assocIn(config.read(), ["remote", name, "url", path]));
      return "\n";
    }
  },

  fetch: function(remote, _) {
    files.assertInRepo();

    if (remote === undefined) {
      throw "unsupported";
    } else if (!(remote in config.read().remote)) {
      throw "fatal: '" + remote + "' does not appear to be a git repository";
    } else {
      var localUrl = files.repoDir();
      var remoteUrl = config.read().remote[remote].url;

      process.chdir(remoteUrl);
      var remoteRefs = refs.readLocalHeads();
      var remoteObjects = objects.readAllHashes().map(objects.read);

      process.chdir(localUrl);
      remoteObjects.forEach(objects.write);
      Object.keys(remoteRefs).forEach(function(r){refs.writeRemote(remote, r, remoteRefs[r])});
      refs.writeFetchHead(remoteRefs, remoteUrl);

      return "From " + remoteUrl + "\n" +
        "Count " + remoteObjects.length + "\n" +
        util.difference(Object.keys(remoteRefs), Object.keys(refs.readLocalHeads()))
          .map(function(b) { return "* [new branch] " + b + " -> " + remote + "/" + b; })
          .join("\n") + "\n";
    }
  }
};

var runCli = module.exports.runCli = function (argv) {
  var rawArgs = parseOptions(argv);
  var commandFnName = rawArgs._[2].replace(/-/g, "_");
  var fn = gitlet[commandFnName];
  var commandArgs = rawArgs._.slice(3);
  var unspecifiedArgs = Array
      .apply(null, new Array(fn.length - commandArgs.length - 1))
      .map(function() { return undefined; });
  return fn.apply(gitlet, commandArgs.concat(unspecifiedArgs).concat(rawArgs));
};

if (require.main === module) {
  var result = runCli(process.argv);
  if (result !== undefined) {
    console.log(result);
  }
}
<|endoftext|>


<commit_before>module.exports = {
    config: {
        locale: {
            name: 'id-ID',
            date: {
                format: 'DD MMMM YYYY'
            },
            currency: {
                style: 'decimal',
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            },
            currencyNotaItern: {
                style: 'decimal',
                minimumFractionDigits: 4,
                maximumFractionDigits: 4
            },
            decimal: {
                style: 'decimal',
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            }
        }
    }
}
<commit_msg>update cetakan SPB<commit_after>module.exports = {
    config: {
        locale: {
            name: 'id-ID',
            date: {
                format: 'DD MMMM YYYY'
            },
            currency: {
                style: 'decimal',
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            },
            currencyNotaItern: {
                style: 'decimal',
                minimumFractionDigits: 2,
                maximumFractionDigits: 2,
                minimumIntegerDigits:2
            },
            currencyNotaItern2: {
                style: 'decimal',
                minimumFractionDigits: 4,
                maximumFractionDigits: 4,
             },
            decimal: {
                style: 'decimal',
                minimumFractionDigits: 2,
                maximumFractionDigits: 2
            }
        }
    }
}
<|endoftext|>


<commit_before>
/**

  locals-editor

**/

//
//  Dependencies
//

var chalk = require("chalk"),
    utils = require("./cli-utils");

//
//  Exports
//

module.exports = {

  /**

    Outputs a list of local variables.

  **/

  list: function() {

    var editor = require("./config-editor"),
        locals = editor.get("locals") || {},
        str;

    console.log("");
    if (!Object.keys(locals).length)
      console.log(chalk.cyan("   Info:"), "there are no local variables in your project");
    else {
      console.log(chalk.cyan("   Local Variables:\n"));
      str = JSON.stringify(locals, null, 2).split("\n").map(function(line) { return "   " + line; }).join("\n");
      console.log(str);
    }

    console.log("");

  },

  /**

    Adds a local variable and acknolwedges with confirmation.

    @param {String} key The key to lookup (supports dot-notation)

  **/

  add: function(key, val) {

    var editor = require("./config-editor");

    console.log("");

    // Perform type casting
    if (val === "false")
      val = false;
    else if (val === "true")
      val = true;
    else if (/^\-?([0-9]+\.?[0-9]*|\.[0-9]*)$/.test(val))
      val = parseFloat(val);

    editor.set("locals." + key, val);
    editor.save();

    console.log("   " + chalk.cyan("Added:") + " local variable " + chalk.yellow(key) + " now contains " + chalk.yellow(val));
    console.log("");

  },

  /**

    Removes a local variable and acknowledges with confirmation.

    @param {String} key The key to remove (supports dot-notation)

  **/

  remove: function(key) {

    var editor = require("./config-editor"),
        prev = editor.get("locals." + key);

    console.log("");

    editor.unset("locals." + key);
    editor.save();

    if ("undefined" === typeof prev)
      console.log("   " + chalk.red("No Change:") + " there was no local variable called " + chalk.yellow(key));
    else if ("object" === typeof prev)
      console.log("   " + chalk.cyan("Removed:") + " local variable " + chalk.yellow(key) + " has been unset");
    else
      console.log("   " + chalk.cyan("Removed:") + " local variable " + chalk.yellow(key) + " has been unset from " + chalk.yellow(prev));
    console.log("");

  }

};
<commit_msg>locals-editor#list: indents consistent with pipelines and routes<commit_after>
/**

  locals-editor

**/

//
//  Dependencies
//

var chalk = require("chalk"),
    utils = require("./cli-utils");

//
//  Exports
//

module.exports = {

  /**

    Outputs a list of local variables.

  **/

  list: function() {

    var editor = require("./config-editor"),
        locals = editor.get("locals") || {},
        str;

    console.log("");
    console.log(chalk.cyan(" Locals:"));
    console.log("");

    if (!Object.keys(locals).length)
      console.log("   There are no local variables in your project");
    else {
      str = JSON.stringify(locals, null, 2).split("\n").map(function(line) { return "   " + line; }).join("\n");
      console.log(str);
    }

    console.log("");

  },

  /**

    Adds a local variable and acknolwedges with confirmation.

    @param {String} key The key to lookup (supports dot-notation)

  **/

  add: function(key, val) {

    var editor = require("./config-editor");

    console.log("");

    // Perform type casting
    if (val === "false")
      val = false;
    else if (val === "true")
      val = true;
    else if (/^\-?([0-9]+\.?[0-9]*|\.[0-9]*)$/.test(val))
      val = parseFloat(val);

    editor.set("locals." + key, val);
    editor.save();

    console.log("   " + chalk.cyan("Added:") + " local variable " + chalk.yellow(key) + " now contains " + chalk.yellow(val));
    console.log("");

  },

  /**

    Removes a local variable and acknowledges with confirmation.

    @param {String} key The key to remove (supports dot-notation)

  **/

  remove: function(key) {

    var editor = require("./config-editor"),
        prev = editor.get("locals." + key);

    console.log("");

    editor.unset("locals." + key);
    editor.save();

    if ("undefined" === typeof prev)
      console.log("   " + chalk.red("No Change:") + " there was no local variable called " + chalk.yellow(key));
    else if ("object" === typeof prev)
      console.log("   " + chalk.cyan("Removed:") + " local variable " + chalk.yellow(key) + " has been unset");
    else
      console.log("   " + chalk.cyan("Removed:") + " local variable " + chalk.yellow(key) + " has been unset from " + chalk.yellow(prev));
    console.log("");

  }

};
<|endoftext|>


<commit_before>global.Thousand = 1000; //For readability of number literals in code
global.lowerFirst = function(string) {
    return string && (string.charAt(0).toLowerCase() + string.slice(1));
};

global.tryRequire = (path, silent = false) => {
    let mod;
    try{
        mod = require(path);
    } catch(e) {
        if( e.message && e.message.indexOf('Unknown module') > -1 ){
            if(!silent) console.log(`Module "${path}" not found!`);
        } else if(mod == null) {
            console.log(`Error loading module "${path}"!<br/>${e.stack || e.toString()}`);
        }
        mod = null;
    }
    return mod;
};

global.Config = tryRequire('config.override', true) || require('config.default');
global.RoleObj = require('role.obj');
global.ActionObj = require('action.obj');
global.SetupObj = require('setup.obj');
global.FlagUtil = {
    dismantle: {
        color: COLOR_RED,
        secondaryColor: COLOR_RED,
    },
    guard: {
        color: COLOR_BLUE,
        secondaryColor: COLOR_BLUE,
    },
}
function makeExamineFunction(constant) {
    return o => o.color==constant.color && o.secondaryColor==constant.secondaryColor;
};
function addExamineToFlagUtil() {
    _.forEach(FlagUtil, o => o.examine = makeExamineFunction(o));
}
addExamineToFlagUtil();

global.Action = {
    Harvest: require('action.harvest'),
    Feed: require('action.feed'),
    Upgrade: require('action.upgrade'),
    ComplexUpgrade: require('action.complex.upgrade'),
    Build: require('action.build'),
    Withdraw: require('action.withdraw'),
    Put: require('action.put'),
    Fuel: require('action.fuel'),
    Guard: require('action.guard'),
    Pickup: require('action.pickup'),
    Drop: require('action.drop'),
    Maintain: require('action.maintain'),
    Repair: require('action.repair'),
    Recycle: require('action.recycle'),
    Dismantle: require('action.dismantle'),
    Travel: require('action.travel'),
};
global.Setup = {
    Worker: require('setup.worker'),
    Harvester: require('setup.harvester'),
    Upgrader: require('setup.upgrader'),
    Builder: require('setup.builder'),
    Hauler: require('setup.hauler'),
    Guardian: require('setup.guardian'),
    Ant: require('setup.ant'),
    Filler: require('setup.filler'),
};
global.Role = {
    Worker: require('role.worker'),
    Harvester: require('role.harvester'),
    Upgrader: require('role.upgrader'),
    Builder: require('role.builder'),
    Hauler: require('role.hauler'),
    Guardian: require('role.guardian'),
    Ant: require('role.ant'),
    Recycler: require('role.recycler'),
    Filler: require('role.filler'),
};
global.Util = {
    Defense: require('util.defense'),
    Mark: require('util.mark'),
    GC: require('util.gc'),
    Smalltask: require('util.smalltask'),
    Stat: require('util.stat'),
}
global.State= {};<commit_msg>now Config is can be truly override<commit_after>global.Thousand = 1000; //For readability of number literals in code
global.lowerFirst = function(string) {
    return string && (string.charAt(0).toLowerCase() + string.slice(1));
};

global.tryRequire = (path, silent = false) => {
    let mod;
    try{
        mod = require(path);
    } catch(e) {
        if( e.message && e.message.indexOf('Unknown module') > -1 ){
            if(!silent) console.log(`Module "${path}" not found!`);
        } else if(mod == null) {
            console.log(`Error loading module "${path}"!<br/>${e.stack || e.toString()}`);
        }
        mod = null;
    }
    return mod;
};

const DefaultConfig = require('config.default');
const OverrideConfig = tryRequire('config.override', true) || {};
global.Config = _.defaultsDeep(OverrideConfig, DefaultConfig);

global.RoleObj = require('role.obj');
global.ActionObj = require('action.obj');
global.SetupObj = require('setup.obj');
global.FlagUtil = {
    dismantle: {
        color: COLOR_RED,
        secondaryColor: COLOR_RED,
    },
    guard: {
        color: COLOR_BLUE,
        secondaryColor: COLOR_BLUE,
    },
}
function makeExamineFunction(constant) {
    return o => o.color==constant.color && o.secondaryColor==constant.secondaryColor;
};
function addExamineToFlagUtil() {
    _.forEach(FlagUtil, o => o.examine = makeExamineFunction(o));
}
addExamineToFlagUtil();

global.Action = {
    Harvest: require('action.harvest'),
    Feed: require('action.feed'),
    Upgrade: require('action.upgrade'),
    ComplexUpgrade: require('action.complex.upgrade'),
    Build: require('action.build'),
    Withdraw: require('action.withdraw'),
    Put: require('action.put'),
    Fuel: require('action.fuel'),
    Guard: require('action.guard'),
    Pickup: require('action.pickup'),
    Drop: require('action.drop'),
    Maintain: require('action.maintain'),
    Repair: require('action.repair'),
    Recycle: require('action.recycle'),
    Dismantle: require('action.dismantle'),
    Travel: require('action.travel'),
};
global.Setup = {
    Worker: require('setup.worker'),
    Harvester: require('setup.harvester'),
    Upgrader: require('setup.upgrader'),
    Builder: require('setup.builder'),
    Hauler: require('setup.hauler'),
    Guardian: require('setup.guardian'),
    Ant: require('setup.ant'),
    Filler: require('setup.filler'),
};
global.Role = {
    Worker: require('role.worker'),
    Harvester: require('role.harvester'),
    Upgrader: require('role.upgrader'),
    Builder: require('role.builder'),
    Hauler: require('role.hauler'),
    Guardian: require('role.guardian'),
    Ant: require('role.ant'),
    Recycler: require('role.recycler'),
    Filler: require('role.filler'),
};
global.Util = {
    Defense: require('util.defense'),
    Mark: require('util.mark'),
    GC: require('util.gc'),
    Smalltask: require('util.smalltask'),
    Stat: require('util.stat'),
}
global.State= {};<|endoftext|>


<commit_before>var fs     = require("fs"),
    path   = require("path"),
    crypto = require("crypto"),
    _      = require("underscore"),
    config = require("./config"),
    logger = require("../../server/logger.js");

var current_map,
    file_list,
    previous_map_file = path.join(config.tishadow_build, 'alloy_map.json');

exports.mapFiles = function(last_stat) {
  // full build if the previous map doesn't exits
  if (!fs.existsSync(previous_map_file)) {
    return file_list;
  }
  var previous_map = require(previous_map_file);
  file_list.files = file_list.files.filter(function(file) {
    return (!file.match("\.js$") && fs.statSync(path.join(config.resources_path,file)).mtime > last_stat)
      || current_map[file] !== previous_map[file];
  });
  return file_list;
};

exports.buildMap = function() {
  // regular filtered by last_stat won't do it alone
  file_list = fs.getList(config.resources_path);

  // create a map of hashes for js files
  var js_files = file_list.files.filter(function(name) { return name.match("\.js$"); });
  current_map = _.object(js_files, js_files.map(function(file) {
    return crypto.createHash('md5').update(fs.readFileSync(path.join(config.resources_path, file))).digest("hex");
  }));
};

exports.writeMap = function() {
  fs.writeFileSync(previous_map_file, JSON.stringify(current_map));
}
<commit_msg>need to map everything as mtime of assets changes on alloy copy<commit_after>var fs     = require("fs"),
    path   = require("path"),
    crypto = require("crypto"),
    _      = require("underscore"),
    config = require("./config"),
    logger = require("../../server/logger.js");

var current_map,
    file_list,
    previous_map_file = path.join(config.tishadow_build, 'alloy_map.json');

exports.mapFiles = function(last_stat) {
  // full build if the previous map doesn't exits
  if (!fs.existsSync(previous_map_file)) {
    return file_list;
  }
  var previous_map = require(previous_map_file);
  file_list.files = file_list.files.filter(function(file) {
      return current_map[file] !== previous_map[file];
  });
  return file_list;
};

exports.buildMap = function() {
  // regular filtered by last_stat won't do it alone
  file_list = fs.getList(config.resources_path);

  // create a map of hashes for js files
  current_map = _.object(file_list.files,file_list.files.map(function(file) {
    return crypto.createHash('md5').update(fs.readFileSync(path.join(config.resources_path, file))).digest("hex");
  }));
};

exports.writeMap = function() {
  fs.writeFileSync(previous_map_file, JSON.stringify(current_map));
}
<|endoftext|>


<commit_before>/*var showStep = function() {
  $('#product-info').children().removeClass('show');
  $('#product-info').children(':nth-child(' + Session.get('postState') + ')').addClass('show');
  }
  */

var verifyField = function(a) {
    var b = a.find('input, select').val();
    return (b != undefined && b != '') || Session.get('postState') == 5;
}

//The following code will take care of verfying and submitting all of the posts, when I care to finish writing it.
Template.addTitle.rendered = function(){
    $('.step-circle').removeClass('active complete');
    $($('.step-circle')[0]).addClass('active');

    if(Session.get('tempProdForm'))
        $('input[name=title]').val(Session.get('tempProdForm').title);

    $('form').submit(function(e) {
	e.preventDefault();
        var temp;
        if(Session.get('tempProdForm'))
	    temp = Session.get('tempProdForm');
	temp.title = $('input[name=title]').val();
	Session.set('tempProdForm',temp);
	Router.go('/sell/info');
    });
}

var populateInfo = function() {
    temp = Session.get('tempProdForm');
    $('input[name=title]').val(temp.title);
    $('input[name=category]').val(temp.category);
    $('input:radio[name="category"]').filter('[value=' + temp.category + ']').attr('checked', 'checked');
    $('input[name=so]').val(temp.so);
    $('input[name=bin]').val(temp.bin);
    $('select[name=condition]').val(temp.condition);
    $('#description').html(temp.description);
}

//should i put all of this code in it's own stuff hm
Template.addInfo.rendered = function() {
    //maybe i should take care of this by hiding the div instead of having different routes
    $('.step-circle').removeClass('active complete');
    $($('.step-circle')[0]).addClass('complete');
    $($('.step-circle')[1]).addClass('active');

    populateInfo();

    //check if it should be here
    /*
    if(!Session.get('tempProdForm'))
        Router.go('/sell/title');
        */

    if(Session.get('tempProdForm')) {
        temp = Session.get('tempProdForm');
        //nm use helpers HERE
    }
    $('#b_pNext').click(function(e) {
        e.preventDefault();
        temp = Session.get('tempProdForm');
        temp.title = $('input[name=title]').val();
	temp.category = $('input[name=category]').val();
	temp.so = $('input[name=so]').val();
	temp.bin = $('input[name=bin]').val();
	temp.condition = $('select[name=condition]').val();
	temp.description = $('#description').html();
        console.log(temp);

        //NEED A CHECK TO SEE IF THE FIELDS ARE ALL FILLED

        Session.set('tempProdForm', temp);
        Router.go('/sell/preview');
    });
    $('#back').click(function(e) {
        Router.go('/sell/title');
    });
}

Template.postPreview.rendered = function(){
    $('.step-circle').removeClass('active complete');
    $($('.step-circle')[0]).addClass('complete');
    $($('.step-circle')[1]).addClass('complete');
    $($('.step-circle')[2]).addClass('active');
    $('#addProdBut').click(function(e) {
	e.preventDefault();
	console.log("adding item");
	Meteor.call('addProduct', Session.get('tempProdForm'), function(e,r) {
	    console.log("something");
	    if(e) {
		alert(e);
	    }else{
		console.log("done");
		Router.go('/post/' + r);
	    }
	});
    });
    $('#back').click(function(e) {
	Router.go('/sell/info');
    });
}

Template.pageAddProduct.rendered = function(){
    if(!Session.get('tempProdForm'))
	Session.set('tempProdForm',{});
};

Template.postPreview.helpers({
    'title': function() {
	if(Session.get('tempProdForm'))
    return Session.get('tempProdForm').title;
    },
    'category': function() {
	if(Session.get('tempProdForm'))
    return Session.get('tempProdForm').category;
//return $('[name=category]').val();
    },
    'so': function() {
	if(Session.get('tempProdForm'))
    return Session.get('tempProdForm').so;
//return $('[name=so]').val();
    },
    'bin': function() {
	if(Session.get('tempProdForm'))
    return Session.get('tempProdForm').bin;
//return $('[name=bin]').val();
    },
    'condition': function() {
	if(Session.get('tempProdForm'))
	    return Session.get('tempProdForm').condition;
	//return $('[name=condition]').val();
    },
    'description': function() {
	if(Session.get('tempProdForm'))
	    return Session.get('tempProdForm').description;
	//return $('#itemDescription').html();
    },
});
<commit_msg>fixed some stuff that may have otten lost<commit_after>/*var showStep = function() {
  $('#product-info').children().removeClass('show');
  $('#product-info').children(':nth-child(' + Session.get('postState') + ')').addClass('show');
  }
  */

var verifyField = function(a) {
    var b = a.find('input, select').val();
    return (b != undefined && b != '') || Session.get('postState') == 5;
}

//The following code will take care of verfying and submitting all of the posts, when I care to finish writing it.
Template.addTitle.rendered = function(){
    $('.step-circle').removeClass('active complete');
    $($('.step-circle')[0]).addClass('active');

    if(Session.get('tempProdForm'))
        $('input[name=title]').val(Session.get('tempProdForm').title);

    $('form').submit(function(e) {
	e.preventDefault();
        var temp;
        if(Session.get('tempProdForm'))
	    temp = Session.get('tempProdForm');
	temp.title = $('input[name=title]').val();
	Session.set('tempProdForm',temp);
	Router.go('/sell/info');
    });
}

var populateInfo = function() {
    temp = Session.get('tempProdForm');
    $('input[name=title]').val(temp.title);
    $('input[name=category]').val(temp.category);
    $('input:radio[name="category"]').filter('[value=' + temp.category + ']').attr('checked', 'checked');
    $('input[name=so]').val(temp.so);
    $('input[name=bin]').val(temp.bin);
    $('select[name=condition]').val(temp.condition);
    $('#description').html(temp.description);
}

//should i put all of this code in it's own stuff hm
Template.addInfo.rendered = function() {
    //maybe i should take care of this by hiding the div instead of having different routes
    $('.step-circle').removeClass('active complete');
    $($('.step-circle')[0]).addClass('complete');
    $($('.step-circle')[1]).addClass('active');

    populateInfo();

    //check if it should be here
    /*
    if(!Session.get('tempProdForm'))
        Router.go('/sell/title');
        */

    if(Session.get('tempProdForm')) {
        temp = Session.get('tempProdForm');
        //nm use helpers HERE
    }
    $('#b_pNext').click(function(e) {
        e.preventDefault();
        temp = Session.get('tempProdForm');
        temp.title = $('input[name=title]').val();
	temp.category = $('input[name=category]').val();
	temp.so = $('input[name=so]').val();
	temp.bin = $('input[name=bin]').val();
	temp.condition = $('select[name=condition]').val();
	temp.description = $('#description').html();
        console.log(temp);

        //NEED A CHECK TO SEE IF THE FIELDS ARE ALL FILLED

        Session.set('tempProdForm', temp);
        Router.go('/sell/preview');
    });
    $('#back').click(function(e) {
        Router.go('/sell/title');
    });
}

Template.postPreview.rendered = function(){
    $('.step-circle').removeClass('active complete');
    $($('.step-circle')[0]).addClass('complete');
    $($('.step-circle')[1]).addClass('complete');
    $($('.step-circle')[2]).addClass('active');
    $('#addProdBut').click(function(e) {
	e.preventDefault();
	console.log("adding item");
	Meteor.call('addProduct', Session.get('tempProdForm'), function(e,r) {
	    console.log("something");
	    if(e) {
		alert(e);
	    }else{
		console.log("done");
                Session.set('tempProdForm',null);
		Router.go('/post/' + r);
	    }
	});
    });
    $('#back').click(function(e) {
	Router.go('/sell/info');
    });
}

Template.pageAddProduct.rendered = function(){
    if(!Session.get('tempProdForm'))
	Session.set('tempProdForm',{});
};

Template.postPreview.helpers({
    'title': function() {
	if(Session.get('tempProdForm'))
    return Session.get('tempProdForm').title;
    },
    'category': function() {
	if(Session.get('tempProdForm'))
    return Session.get('tempProdForm').category;
//return $('[name=category]').val();
    },
    'so': function() {
	if(Session.get('tempProdForm'))
    return Session.get('tempProdForm').so;
//return $('[name=so]').val();
    },
    'bin': function() {
	if(Session.get('tempProdForm'))
    return Session.get('tempProdForm').bin;
//return $('[name=bin]').val();
    },
    'condition': function() {
	if(Session.get('tempProdForm'))
	    return Session.get('tempProdForm').condition;
	//return $('[name=condition]').val();
    },
    'description': function() {
	if(Session.get('tempProdForm'))
	    return Session.get('tempProdForm').description;
	//return $('#itemDescription').html();
    },
});
<|endoftext|>


<commit_before>function routes( $stateProvider, $urlRouterProvider) {
  console.log(1,$stateProvider);
  $stateProvider.state( 'home', {
    name: 'home',
    url: '/',
    views: {
      '@': { templateUrl: 'app/views/home.html' }
    }
  })
  .state( 'forums', {
    name: 'forums',
    url: '/forums',
    views: {
      '@': { templateUrl: 'app/views/forums.html' }
    }
  })
  .state( 'forums.create', {
    name: 'forums.create',
    url: '/create',
    views: {
      '@': { templateUrl: 'app/views/forums_create.html' }
    }
  })
}
<commit_msg>appending route for forums.messages<commit_after>function routes( $stateProvider, $urlRouterProvider) {
  console.log(1,$stateProvider);
  $stateProvider.state( 'home', {
    name: 'home',
    url: '/',
    views: {
      '@': { templateUrl: 'app/views/home.html' }
    }
  })
  .state( 'forums', {
    name: 'forums',
    url: '/forums',
    views: {
      '@': { templateUrl: 'app/views/forums.html' }
    }
  })
  .state( 'forums.create', {
    name: 'forums.create',
    url: '/create',
    views: {
      '@': { templateUrl: 'app/views/forums_create.html' }
    }
  })
  .state( 'forums.messages', {
    name: 'forums.messages',
    url: '/:id/messages',
    params: { 'id': null },
    views: {
      '@': { templateUrl: 'app/views/forums_messages.html' }
    }
  })
}
<|endoftext|>


<commit_before>/**
 * This script is used to convert wikimedia dump of official wiki
 * to JSON format used in this extension.
 *
 * To get create xml files used by this file, you need to go to /Special:Export/,
 * select Functions or Commands category, then save them as functionsExport.xml and
 * operatorsExport.xml.
 *
 */

var fs = require('fs');
var xmldoc = require('xmldoc');

function fixSyntax(syntax) {
	syntax = removeMoreTags(syntax);

	var eq = syntax.indexOf('=');
	if (eq >= 0) {
		syntax = syntax.substr(eq + 1).trim();
	}

	return syntax.trim();
}

function parseValue(value, type) {
	if (type == "syntax") {
		return fixSyntax(value);
	}
	if (type == "return value") {
		var ret = value.trim();
		var dash = ret.indexOf("-");
		if (dash >= 0) {
			ret = ret.substr(0, dash - 1).trim();
		}
		return ret;
	}
}

function removeMoreTags(value) {
	if (!value)
		return value;

	return value
		.replace(/
/ig, '')
		.replace(/''since [^']*''/ig, '')
		.replace(/''\(since \[.*?\]\)''/ig, '')
		.replace(/\(''since .*?''\)/ig, '')
		.replace(/<nowiki>(.*?)<\/nowiki>/g, '$1')
		.replace(/'''(.*?)'''/g, '$1')
		.replace(/\[\[(.*?)\|(.*?)\]\]/g, '$2')
		.replace(/\[\[(.*?)\]\]/g, '$1')
		.replace(/ {2,}/g, ' ')
		.replace(/ /g, '');
}

function polishSyntaxArgument(item) {
	if (item.desc.length < 10) {
		return item.desc;
	}
	if (item.type.length > 10) {
		return item.type.substr(0, 8) + "..";
	}
	return item.type;
}

function parseDocument(doc, type, extended) {
	var document = new xmldoc.XmlDocument(doc);
	var pages = document.childrenNamed("page");
	var findCommand = /{{(?:Command|Function)\|=((?:.|\n)*?\n)}}/i;
	var findVariable = /\|\s*((?:.|\n)*?)\s*\|\s*=[\r\t\f\v ]*(.*)/g;
	var results = extended || {};
	var placeHolder = /\/\*\s*Description:\s*([^]*)\s*(?:Parameters|Parameter\(s\)):\s*([^]*)\s*Returns:\s*([^]*)\s*\*\/\s*/i;
	var placeHolderWithExamples = /\/\*\s*Description:\s*([^]*)\s*(?:Parameters|Parameter\(s\)):\s*([^]*)\s*Returns:\s*([^]*)\s*Examples:\s*([^]*)\s*\*\/\s*/i;
	var placeHolderArgument = /([0-9]+):\s*([^-]*)-\s*(.*)/g;
	var placeHolderSingularArgument = /_this:\s*([^-]*)-\s*(.*)/i;
	var placeHolderReturn = /\s*([^-]*)(.*)/;
	var sqfTypes = ["bool", "string", "object", "task", "array", "scalar", "number", "side", "group", "boolean", "code", "config", "control", "display", "namespace"];

	for(var i in pages) {
		var page = pages[i];

		if (parseInt(page.childNamed("ns").val) == 0) {
			var title = page.childNamed("title").val;
			var text = page.valueWithPath("revision.text");

			title = title.replace(/ /g, '_');

			var match = findCommand.exec(text);
			if (match) {
				var info;
				var wiki = match[1];
				var variables = {};

				var signatures = [];
				var description = {
					plain: "",
					formatted: ""
				};
				var returns = [];
				var syntax = [];

				var previousIdent = null;

				while (match = findVariable.exec(wiki)) {
					var ident = match[2].toLowerCase().trim();
					var value = match[1];

					value = value.replace(/[srp][0-9]*=/ig, '');

					if (title.toLowerCase() == 'setvariable') {
						console.log("IDENT", ident);
						console.log("VALUE", value);
					}

					// Empty nothing after description means syntax apparently
					if (ident == "" && previousIdent == 'description') {
						ident = "syntax";
					}

					if (ident.indexOf("syntax") == 0) {
						ident = "syntax";
					}

					// Fix this
					if (ident == "returnvalue") {
						ident = "return value";
					}

					if (ident == "syntax" || ident == "return value") {
						if (!variables[ident])
							variables[ident] = [];
						variables[ident].push(parseValue(value, ident));
					} else {
						variables[ident] = value;
					}

					previousIdent = ident;
				}

				if (variables["return value"])
					returns = variables["return value"];

				if (variables["syntax"])
					syntax = variables["syntax"];

				syntax = syntax.map((item) => {
					var commented = //i.exec(item);
					if (commented) {
						item = commented[1].trim();
					}
					return item;
				});

				// Parse description
				if (variables["description"]) {
					var desc = variables["description"];
					match = placeHolderWithExamples.exec(desc);
					if (!match) {
						match = placeHolder.exec(desc);
					}

					if (match) {
						desc = match[1];

						if (match[2].trim()) {
							var args = [];
							var amatch = null;
							while (amatch = placeHolderArgument.exec(match[2])) {
								args.push({
									type: amatch[2].trim().replace(/(\s+)or(\s+)/g, "/"),
									desc: amatch[3].trim()
								});
							}

							if (args.length > 0) {
								syntax = ["[" + args.map((item) => polishSyntaxArgument(item)).join(", ") + "] call " + title];

								desc += "\r\nArguments:\r\n";
								args.forEach((arg, index) => {
									// desc += "\r\n - " + (index + 1) + ": " + arg.type + " - " + arg.desc
									desc += "\r\n " + index + ". " + arg.type + " - " + arg.desc;
								});
							} else {
								amatch = placeHolderSingularArgument.exec(match[2]);
								if (amatch) {
									var arg = { type: amatch[1].trim(), desc: amatch[2].trim() };
									syntax = [polishSyntaxArgument(arg) + " call " + title];
									desc += "\r\nArgument: _this: " + arg.type + " - " + arg.desc;
								}
							}
						}

						if (match[3].trim()) {
							match[3] = match[3].trim();
							var rmatch = placeHolderReturn.exec(match[3]);
							if (rmatch) {
								returns = [rmatch[1]];
								desc += "\r\n\r\nReturns: " + match[3];
							} else if (sqfTypes.indexOf(match[3].toLowerCase()) != -1) {
								returns = [match[3]];
							} else {
								returns = ["ANY"];
								desc += "\r\n\r\nReturns: " + match[3];
							}
						}
					} else {
						// Remove image tags
						desc = desc.replace(/\[\[Image(.*?)\]\]/g, '');

						// Only use first sentence
						var dot = desc.indexOf(".");
						if (dot >= 0) {
							desc = desc.substr(0, dot + 1);
						}
					}

					description.plain = fixSyntax(desc).trim();
					description.formatted = desc.replace(/'''(.*?)'''/g, '**$1**')
						.replace(/
/ig, '')
						.replace(/\[\[(.*?)\|(.*?)\]\]/g, '[$1](https://community.bistudio.com/wiki/$2)')
						.replace(/\[\[(.*?)\]\]/g, '[$1](https://community.bistudio.com/wiki/$1)')
						.trim();
				}

				// Add more info to description
				if (variables["game version"] && variables["game name"]) {
					description.formatted += " _(" + variables["game name"] + " " + variables["game version"] + ")_";
				}

				description.formatted += " _([more info](https://community.bistudio.com/wiki/" + title + "))_\r\n\r\n";

				// Add signatures
				if (syntax.length > 0) {
					for(var s in syntax) {
						var signature = syntax[s].trim();
						var ret = returns[s];
						if (ret != null) ret = ret.trim();

						signatures.push({
							signature: removeMoreTags(signature),
							returns: removeMoreTags(ret || null)
						});
					}
				} else {
					signatures.push({
						signature: title
					});
				}

				results[title.toLowerCase()] = {
					type: type,
					title: title,
					description: description,
					signatures: signatures
				}
			}
		}
	}

	return results;
}

fs.readFile(__dirname + '/server/operatorsExport.xml', (err, data) => {
	if (err) throw err;

	var docs = parseDocument(data.toString(), "command");
	fs.readFile(__dirname + '/server/functionsExport.xml', (err, data) => {
		if (err) throw err;

		docs = parseDocument(data.toString(), "function", docs);
		fs.readFile(__dirname + '/../cba/cba.json', (err, data) => {
			if (err) throw err;

			var items = JSON.parse(data);
			for(var ident in items) {
				docs[ident] = items[ident];
			}

			fs.writeFile(__dirname + '/server/definitions/documentation.json', JSON.stringify(docs));
		});
	});
});
<commit_msg>Removed useless debug output<commit_after>/**
 * This script is used to convert wikimedia dump of official wiki
 * to JSON format used in this extension.
 *
 * To get create xml files used by this file, you need to go to /Special:Export/,
 * select Functions or Commands category, then save them as functionsExport.xml and
 * operatorsExport.xml.
 *
 */

var fs = require('fs');
var xmldoc = require('xmldoc');

function fixSyntax(syntax) {
	syntax = removeMoreTags(syntax);

	var eq = syntax.indexOf('=');
	if (eq >= 0) {
		syntax = syntax.substr(eq + 1).trim();
	}

	return syntax.trim();
}

function parseValue(value, type) {
	if (type == "syntax") {
		return fixSyntax(value);
	}
	if (type == "return value") {
		var ret = value.trim();
		var dash = ret.indexOf("-");
		if (dash >= 0) {
			ret = ret.substr(0, dash - 1).trim();
		}
		return ret;
	}
}

function removeMoreTags(value) {
	if (!value)
		return value;

	return value
		.replace(/
/ig, '')
		.replace(/''since [^']*''/ig, '')
		.replace(/''\(since \[.*?\]\)''/ig, '')
		.replace(/\(''since .*?''\)/ig, '')
		.replace(/<nowiki>(.*?)<\/nowiki>/g, '$1')
		.replace(/'''(.*?)'''/g, '$1')
		.replace(/\[\[(.*?)\|(.*?)\]\]/g, '$2')
		.replace(/\[\[(.*?)\]\]/g, '$1')
		.replace(/ {2,}/g, ' ')
		.replace(/ /g, '');
}

function polishSyntaxArgument(item) {
	if (item.desc.length < 10) {
		return item.desc;
	}
	if (item.type.length > 10) {
		return item.type.substr(0, 8) + "..";
	}
	return item.type;
}

function parseDocument(doc, type, extended) {
	var document = new xmldoc.XmlDocument(doc);
	var pages = document.childrenNamed("page");
	var findCommand = /{{(?:Command|Function)\|=((?:.|\n)*?\n)}}/i;
	var findVariable = /\|\s*((?:.|\n)*?)\s*\|\s*=[\r\t\f\v ]*(.*)/g;
	var results = extended || {};
	var placeHolder = /\/\*\s*Description:\s*([^]*)\s*(?:Parameters|Parameter\(s\)):\s*([^]*)\s*Returns:\s*([^]*)\s*\*\/\s*/i;
	var placeHolderWithExamples = /\/\*\s*Description:\s*([^]*)\s*(?:Parameters|Parameter\(s\)):\s*([^]*)\s*Returns:\s*([^]*)\s*Examples:\s*([^]*)\s*\*\/\s*/i;
	var placeHolderArgument = /([0-9]+):\s*([^-]*)-\s*(.*)/g;
	var placeHolderSingularArgument = /_this:\s*([^-]*)-\s*(.*)/i;
	var placeHolderReturn = /\s*([^-]*)(.*)/;
	var sqfTypes = ["bool", "string", "object", "task", "array", "scalar", "number", "side", "group", "boolean", "code", "config", "control", "display", "namespace"];

	for(var i in pages) {
		var page = pages[i];

		if (parseInt(page.childNamed("ns").val) == 0) {
			var title = page.childNamed("title").val;
			var text = page.valueWithPath("revision.text");

			title = title.replace(/ /g, '_');

			var match = findCommand.exec(text);
			if (match) {
				var info;
				var wiki = match[1];
				var variables = {};

				var signatures = [];
				var description = {
					plain: "",
					formatted: ""
				};
				var returns = [];
				var syntax = [];

				var previousIdent = null;

				while (match = findVariable.exec(wiki)) {
					var ident = match[2].toLowerCase().trim();
					var value = match[1];

					value = value.replace(/[srp][0-9]*=/ig, '');

					// Empty nothing after description means syntax apparently
					if (ident == "" && previousIdent == 'description') {
						ident = "syntax";
					}

					if (ident.indexOf("syntax") == 0) {
						ident = "syntax";
					}

					// Fix this
					if (ident == "returnvalue") {
						ident = "return value";
					}

					if (ident == "syntax" || ident == "return value") {
						if (!variables[ident])
							variables[ident] = [];
						variables[ident].push(parseValue(value, ident));
					} else {
						variables[ident] = value;
					}

					previousIdent = ident;
				}

				if (variables["return value"])
					returns = variables["return value"];

				if (variables["syntax"])
					syntax = variables["syntax"];

				syntax = syntax.map((item) => {
					var commented = //i.exec(item);
					if (commented) {
						item = commented[1].trim();
					}
					return item;
				});

				// Parse description
				if (variables["description"]) {
					var desc = variables["description"];
					match = placeHolderWithExamples.exec(desc);
					if (!match) {
						match = placeHolder.exec(desc);
					}

					if (match) {
						desc = match[1];

						if (match[2].trim()) {
							var args = [];
							var amatch = null;
							while (amatch = placeHolderArgument.exec(match[2])) {
								args.push({
									type: amatch[2].trim().replace(/(\s+)or(\s+)/g, "/"),
									desc: amatch[3].trim()
								});
							}

							if (args.length > 0) {
								syntax = ["[" + args.map((item) => polishSyntaxArgument(item)).join(", ") + "] call " + title];

								desc += "\r\nArguments:\r\n";
								args.forEach((arg, index) => {
									// desc += "\r\n - " + (index + 1) + ": " + arg.type + " - " + arg.desc
									desc += "\r\n " + index + ". " + arg.type + " - " + arg.desc;
								});
							} else {
								amatch = placeHolderSingularArgument.exec(match[2]);
								if (amatch) {
									var arg = { type: amatch[1].trim(), desc: amatch[2].trim() };
									syntax = [polishSyntaxArgument(arg) + " call " + title];
									desc += "\r\nArgument: _this: " + arg.type + " - " + arg.desc;
								}
							}
						}

						if (match[3].trim()) {
							match[3] = match[3].trim();
							var rmatch = placeHolderReturn.exec(match[3]);
							if (rmatch) {
								returns = [rmatch[1]];
								desc += "\r\n\r\nReturns: " + match[3];
							} else if (sqfTypes.indexOf(match[3].toLowerCase()) != -1) {
								returns = [match[3]];
							} else {
								returns = ["ANY"];
								desc += "\r\n\r\nReturns: " + match[3];
							}
						}
					} else {
						// Remove image tags
						desc = desc.replace(/\[\[Image(.*?)\]\]/g, '');

						// Only use first sentence
						var dot = desc.indexOf(".");
						if (dot >= 0) {
							desc = desc.substr(0, dot + 1);
						}
					}

					description.plain = fixSyntax(desc).trim();
					description.formatted = desc.replace(/'''(.*?)'''/g, '**$1**')
						.replace(/
/ig, '')
						.replace(/\[\[(.*?)\|(.*?)\]\]/g, '[$1](https://community.bistudio.com/wiki/$2)')
						.replace(/\[\[(.*?)\]\]/g, '[$1](https://community.bistudio.com/wiki/$1)')
						.trim();
				}

				// Add more info to description
				if (variables["game version"] && variables["game name"]) {
					description.formatted += " _(" + variables["game name"] + " " + variables["game version"] + ")_";
				}

				description.formatted += " _([more info](https://community.bistudio.com/wiki/" + title + "))_\r\n\r\n";

				// Add signatures
				if (syntax.length > 0) {
					for(var s in syntax) {
						var signature = syntax[s].trim();
						var ret = returns[s];
						if (ret != null) ret = ret.trim();

						signatures.push({
							signature: removeMoreTags(signature),
							returns: removeMoreTags(ret || null)
						});
					}
				} else {
					signatures.push({
						signature: title
					});
				}

				results[title.toLowerCase()] = {
					type: type,
					title: title,
					description: description,
					signatures: signatures
				}
			}
		}
	}

	return results;
}

fs.readFile(__dirname + '/server/operatorsExport.xml', (err, data) => {
	if (err) throw err;

	var docs = parseDocument(data.toString(), "command");
	fs.readFile(__dirname + '/server/functionsExport.xml', (err, data) => {
		if (err) throw err;

		docs = parseDocument(data.toString(), "function", docs);
		fs.readFile(__dirname + '/../cba/cba.json', (err, data) => {
			if (err) throw err;

			var items = JSON.parse(data);
			for(var ident in items) {
				docs[ident] = items[ident];
			}

			fs.writeFile(__dirname + '/server/definitions/documentation.json', JSON.stringify(docs));
		});
	});
});
<|endoftext|>


<commit_before>require.config(
{
  baseUrl: "js/lib",
  paths: {
    jquery: "jquery-1.9.1",
    handlebars: "handlebars-1.0.0",
    ember: "ember-1.0.0",
    socketio: "socket.io",
    hashes: "hashes.min",
    modernizr: "custom.modernizr",
    foundation: "foundation.min"
  },
  shim: {
    "ember": {
      exports: "Ember",
      deps: ["jquery","handlebars"]
    },
    "socketio": {
      exports: "io"
    },
    "modernizr": {
      exports: "Modernizr"
    },
    "foundation": {
      exports: "Foundation",
      deps: ["jquery","modernizr"]
    }
  }
});

require(
["jquery","ember","socketio","hashes","modernizr","foundation"],
function( $, Em, io, hashes, Modernizr, Foundation )
{
  App = Em.Application.create({
    rootElement: "#chat",
    LOG_TRANSITIONS: true
  });
  App.GravatarImageComponent = Em.Component.extend({
    size: 200,
    email: '',
    gravatarUrl: function() {
      var email = this.get('email'), size = this.get('size');
      var hash = new hashes.MD5;
      return 'http://www.gravatar.com/avatar/' + hash.hex(email) + '?s=' + size;
    }.property('email', 'size')
  });
  App.Router.map(function(){});
  App.IndexRoute = Em.Route.extend({
    model: function() {
      return ["tomster@emberjs.com",""];
    }
  });
  require(
    ["domReady!","jquery","modernizr","foundation"],
    function( document, $, Modernizr, Foundation )
    {
      $( document ).foundation();
    }
  );
});
<commit_msg>Switched to CDNJS hosted libraries<commit_after>require.config(
{
  baseUrl: "js/lib",
  paths: {
    jquery: "//cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min",
    handlebars: "//cdnjs.cloudflare.com/ajax/libs/handlebars.js/1.0.0/handlebars.min",
    ember: "//cdnjs.cloudflare.com/ajax/libs/ember.js/1.0.0/ember.min",
    socketio: "//cdnjs.cloudflare.com/ajax/libs/socket.io/0.9.16/socket.io.min",
    hashes: "hashes.min",
    modernizr: "//cdnjs.cloudflare.com/ajax/libs/modernizr/2.6.2/modernizr.min",
    foundation: "//cdnjs.cloudflare.com/ajax/libs/foundation/4.3.1/js/foundation.min"
  },
  shim: {
    "ember": {
      exports: "Ember",
      deps: ["jquery","handlebars"]
    },
    "socketio": {
      exports: "io"
    },
    "modernizr": {
      exports: "Modernizr"
    },
    "foundation": {
      exports: "Foundation",
      deps: ["jquery","modernizr"]
    }
  }
});

require(
["jquery","ember","socketio","hashes","modernizr","foundation"],
function( $, Em, io, hashes, Modernizr, Foundation )
{
  App = Em.Application.create({
    rootElement: "#chat",
    LOG_TRANSITIONS: true
  });
  App.GravatarImageComponent = Em.Component.extend({
    size: 200,
    email: '',
    gravatarUrl: function() {
      var email = this.get('email'), size = this.get('size');
      var hash = new hashes.MD5;
      return 'http://www.gravatar.com/avatar/' + hash.hex(email) + '?s=' + size;
    }.property('email', 'size')
  });
  App.Router.map(function(){});
  App.IndexRoute = Em.Route.extend({
    model: function() {
      return ["tomster@emberjs.com",""];
    }
  });
  require(
    ["domReady!","jquery","modernizr","foundation"],
    function( document, $, Modernizr, Foundation )
    {
      $( document ).foundation();
    }
  );
});
<|endoftext|>


<commit_before>import { pick, merge, bindAll } from 'lodash';
import { action } from 'mobx';

import {
    BaseModel, identifiedBy, field, identifier, computed,
} from './models/base';

import Config from './config';

@identifiedBy('lanes/user-session')
class Session extends BaseModel {
    @identifier id;
    @field login;
    @field password;
    setFromSync(data) {
        this.data = data;
    }
}

@identifiedBy('lanes/user')
export class UserModel extends BaseModel {

    @identifier({ type: 'number' }) id;
    @field login;
    @field name;
    @field email;
    @field password;
    @field password_confirm;

    @field access;

    @computed get isLoggedIn() { return !!Config.access_token; }

    constructor(attrs = {}) {
        super(attrs);
        bindAll(this, 'setFromSessionRequest');
    }

    @action logout() {
        const req = new Session({ id: this.id });
        return req.destroy().then(() => {
            this.reset();
            Config.access_token = '';
            return this;
        });
    }

    @action attemptLogin(login, password) {
        const req = new Session({ login, password });
        return req.save().then(this.setFromSessionRequest);
    }

    @action checkAccess() {
        const req = new Session({ id: 'test' });
        return req.fetch().then(this.setFromSessionRequest);
    }

    setFromSessionRequest(req) {
        merge(this, pick(req, 'errors', 'lastServerMessage'));
        if (req.isValid) {
            this.set(req.data.user);
            this.access = req.data.access;
            this.errors = {};
        }
        return this;
    }
}

const current_user = new UserModel();

export default current_user;

    //     static initClass() {

    //         this.prototype.derived = {
    //             roles: {
    //                 fn() { return []; }
    //             },
    //             isLoggedIn: {
    //                 fn() { return false; }
    //             },
    //             allRoles: {
    //                 fn() { return new Lanes.Models.Role.Collection; }
    //             }
    //         };

    //         this.prototype.session = {
    //             access_data: 'object',
    //             id:          'integer',
    //             login:       'string',
    //             name:        'string',
    //             email:       'string',
    //             role_names:  'array',
    //             options:     'object',
    //             password:    'string'
    //         };
    //     }

    //     constructor(attributes, access) {
    //         super(...arguments);
    //         this.access_data = access;
    //     }

    //     api_path() { return '/users'; }
    //     hasAccess() { return true; }
    //     canRead(model, field) { return true; }
    //     canWrite(model, field) { return true; }
    //     canDelete(model)        { return true; }
    // };
    // undefined.initClass();

// let CURRENT_USER = null;

// Object.defineProperty(Lanes, 'current_user', {

//     set(user) {
//         let events = null;
//         if (CURRENT_USER) {
//             events = CURRENT_USER._events;
//         }
//         if (_.some(events)) {
//             for (let key in events) {
//                 const callbacks = events[key];
//                 if (user._events[key]) {
//                     user._events[key] = user._events[key].concat(callbacks);
//                 } else {
//                     user._events[key] = callbacks;
//                 }
//             }
//         }
//         return CURRENT_USER = user;
//     },

//     get() {
//         return CURRENT_USER;
//     }
// });
<commit_msg>use get/setters<commit_after>import { pick, merge, bindAll } from 'lodash';
import { action } from 'mobx';

import {
    BaseModel, identifiedBy, field, identifier, computed,
} from './models/base';

import Config from './config';

@identifiedBy('lanes/user-session')
class Session extends BaseModel {
    @identifier id;
    @field login;
    @field password;
    set syncData(data) {
        this.data = data;
    }
    @computed
    get syncData() {
        return this.serialize();
    }
}

@identifiedBy('lanes/user')
export class UserModel extends BaseModel {

    @identifier({ type: 'number' }) id;
    @field login;
    @field name;
    @field email;
    @field password;
    @field password_confirm;

    @field access;

    @computed get isLoggedIn() { return !!Config.access_token; }

    @action logout() {
        const req = new Session({ id: this.id });
        return req.destroy().then(() => {
            this.reset();
            Config.access_token = '';
            return this;
        });
    }

    @action attemptLogin(login, password) {
        const req = new Session({ login, password });
        return req.save().then(this.setFromSessionRequest);
    }

    @action checkAccess() {
        const req = new Session({ id: 'test' });
        return req.fetch().then(this.setFromSessionRequest);
    }

    @action.bound
    setFromSessionRequest(req) {
        merge(this, pick(req, 'errors', 'lastServerMessage'));
        if (req.isValid) {
            this.set(req.data.user);
            this.access = req.data.access;
            this.errors = {};
        }
        return this;
    }
}

const current_user = new UserModel();

export default current_user;
<|endoftext|>


<commit_before>(function (root, factory) {
    if (typeof define === 'function' && define.amd) {
        define(function () {
            return factory();
        });
    } else {
        root.IClick = factory();
    }
}(this, function () {
    function find(obj /*[,item [,item ...]]*/){
        var list = Array.prototype.splice.call(arguments,1),
            name;

        if (!obj) return null;

        if (list.length == 1 && list[0].indexOf('.')>-1){
            list = list[0].split('.');
        }

        while (name = list.shift()){
            if (obj == null) return null;
            obj = obj[name];
        }

        return obj;
    }

    function extend(obj, props) {
        for (var key in props) obj[key] = props[key];
    }

    /**
     * This class provides a costume events that triggers immediately after
     * a user has clicked an element.
     * Class supports adding new drivers to allow multiple devices inputs.
     *
     * @class IClick
     * @constructor
     *
     * @param {Element}  [root] if provided will use this element as root element
     */
    function IClick(root) {
        this.resetFiredFlag = this.resetFiredFlag.bind(this);
        this.eventHandlers = IClick.eventHandlers;
        this.start_events = IClick.start_events;
        this.event_map = IClick.event_map;

        this.rootElement = root || document;

        this.attach();
    };

    /**
     * Adds device support
     * @method addDevice
     *
     * @static
     *
     * @param {String} name name of device
     * @param {Object} config  device configurations
     *
     *      @param {string} config.start_event name of start event
     *      @param {objcet} config.event_map a map of event names and their phase name. eg:
     *           {
     *             mousedown : 'START_EVENT',
     *             mousemove : 'MOVE_EVENT',
     *             mouseup   : 'END_EVENT'
     *           }
     *
     *      @param {objcet} config.handlers map of event handlers. basic structure:
     *
     *          type : {
     *           INITIAL : {
     *                TYPE : {
     *                   CAPTURING : fn(ev,_ev){}, //optional
     *                   BUBBLING : fn(ev,_ev){} //optional
     *                }
     *           },
     *           ACTIVE : {
     *                TYPE : {
     *                    CAPTURING : fn(ev,_ev){}, //optional
     *                    BUBBLING : fn(ev,_ev){} //optional
     *                }
     *           }
     *         }
     */
    IClick.addDevice = function addDevice(name, config) {
        IClick.start_events[config.start_event] = name;
        IClick.eventHandlers[name] = config.handlers;
        IClick.event_map[name] = config.event_map;
    };

    IClick.start_events = {};
    IClick.eventHandlers = {};
    IClick.event_map = {};

    IClick.prototype = {
        constructor: IClick,

        /**
         * @property event_name
         * @type {string}
         * @static
         *
         * this is the name of the event that will be fired when an immediate click is triggered
         */
        event_name : 'iclick',

        /**
         * whether or not to always prevent the real click event from firing
         * @property prevent_click
         * @public
         * @type {boolean}
         */
        prevent_click : false,
        /**
         * use this property within a driver to prevent the event from triggering
         * @property iclickPrevented
         * @protected
         * @type {Boolean}
         */
        iclickPrevented : false,

        /**
         * This property should be used by drivers to switch into the "active" stack
         * @property state
         * @protected
         * @type {String}
         */
        state : "INITIAL",

        moved : false,
        absDistX : 0,
        absDistY : 0,
        prevPageX : 0,
        prevPageY : 0,
        fired : false,

        max_move : 5,

        /**
         * attaches IClick to the root element
         * @method attach
         * @public
         * @chainable
         */
        attach : function(){
            var name;

            for (name in this.start_events) {
                this.rootElement.addEventListener(name, this, true);
            }

            return this;
        },

        /**
         * detaches IClick from the root element
         * @method detach
         * @public
         * @chainable
         */
        detach : function(){
            var name;

            for (name in this.start_events) {
                this.rootElement.removeEventListener(name, this, true);
            }

            this.removeEvents();

            return this;
        },

        // --- Event Handler Helpers --- //

        /**
         * check if user moved indicator more than allowed
         * @method isMoved
         * @protected
         *
         * @return {boolean}
         */
        isMoved: function(_event) {

            // Check if already moved to bypass calculations
            if (this.moved) {
                return true;
            }

            this.absDistX += Math.abs(_event.pageX - this.prevPageX);
            this.absDistY += Math.abs(_event.pageY - this.prevPageY);
            this.prevPageX = _event.pageX;
            this.prevPageY = _event.pageY;

            if (this.absDistX > this.max_move || this.absDistY > this.max_move) {
                this.moved = true;
            }

            return this.moved;
        },

        /**
         * fires the IClick event
         * @method fireIClick
         * @protected
         * @chainable
         */
        fireIClick: function() {
            var event = this.event,
                _event = event.changedTouches ? event.changedTouches[0] : event,
                target = _event.target,
                IClickEvent;

            if (this.moved && this.iclickPrevented) return;

            // Find the last touched element
            while (target.nodeType !== 1) {
                target = target.parentNode;
            }

            IClickEvent = document.createEvent('MouseEvents');
            IClickEvent.initMouseEvent(this.event_name, true, true, event.view, 1,
                _event.screenX, _event.screenY, _event.clientX, _event.clientY,
                event.ctrlKey, event.altKey, event.shiftKey, event.metaKey,
                0, null);

            target.dispatchEvent(IClickEvent);

            if (IClickEvent.defaultPrevented || this.prevent_click) {
                event.preventDefault();
            }

            this.$fired = true;
            clearTimeout(this.handle);
            this.handle = setTimeout(this.resetFiredFlag, 300);

            return this;
        },

        /**
         * reset IClick checks. remove all events handlers. Must be called on canceling states.
         * @method reset
         * @protected
         * @chainable
         */
        reset : function(){
            this.state = "INITIAL";
            this.removeEvents();
            this.started = false;
            this.iclickPrevented = false;

            return this;
        },

        // === private methods === //

        getType : function(ev) {
            var type = ev.type;

            if (type in this.start_events) return 'START_EVENT';
            else return this.event_map[this.input_type][type];
        },

        handleEvent: function(event) {
            var self = this,
                _event = event.changedTouches ? event.changedTouches[0] : event,
                phase,
                eventType;

            phase = event.eventPhase === Event.CAPTURING_PHASE ?
                "CAPTURING" :
                (event.eventPhase === Event.BUBBLING_PHASE ? "BUBBLING" : event.eventPhase);

            eventType = this.getType(event);

            if (eventType == 'START_EVENT') {
                if (!this.$fired && !this.started) {
                    this.init(event.type);
                }else{
                    return;
                }
            }

            if (phase === "CAPTURING") {
                event.preventIClick = function() {
                    self.iclickPrevented = true;
                };

                event.isIClickPrevented = function() {
                    return self.iclickPrevented;
                };

                event.hasIClickMoved = function() {
                    return self.moved;
                };
            }

            this.event = event;

            if (this.fireHandler(eventType, phase, event, _event) && this.state == 'INITIAL') {
                this.addEvents();
                this.initMoveCheck(_event);
                this.state = 'ACTIVE';
            }

            this.event = null;
        },

        fireHandler : function(type, phase, event, _event) {
            var handler = find(this.handlers, this.state, type, phase),
                result = handler && handler.apply(this,[event,_event]);

            return result !== false;
        },

        init : function(type){
            if (!(type in this.start_events)) throw new Error("IClick- unknow start event: " + type);
            this.reset();
            this.input_type = this.start_events[type];

            this.handlers = this.eventHandlers[this.input_type];

            this.started = true;
        },

        addEvents: function() {
            var name;

            for (name in this.event_map[this.input_type]) {
                this.rootElement.addEventListener(name,this, true);
                this.rootElement.addEventListener(name,this, false);
            }
        },

        removeEvents: function() {
            var name;

            for (name in this.event_map[this.input_type]) {
                this.rootElement.removeEventListener(name,this, true);
                this.rootElement.removeEventListener(name,this, false);
            }
        },

        initMoveCheck: function(_event) {
            this.moved = false;
            this.absDistX = 0;
            this.absDistY = 0;
            this.prevPageX = _event.pageX;
            this.prevPageY = _event.pageY;
        },

        resetFiredFlag : function(){
            this.$fired = false;
        }
    };

    return IClick;
}));
<commit_msg>Removing the iClick file so I can rename it to IClick; server case-sensitive issues<commit_after><|endoftext|>


<commit_before>const { camelCase } = require('./stringOperations')

const tagWithAttributes = /(<\/?)([^ ]*) ?([^/]*)(\/?>)/
const doubleQuotes = /"/g
const leadingSpaces = /^( *)/
const attributesAndValues = /[^=]*="[^"]*"/g
const closingRootTag = /(\n\s{4}\/>)|(^\s{4}<\/)/

const indentLine = indentLevel => str => ' '.repeat(indentLevel) + str
const getStyleAttribute = str => {
  const props = str.substring('style="'.length, str.length - 1).split(';')
  return [
    'style={{',
    ...props.map(prop => {
      const [key, val] = prop.split(':')
      return indentLine(2)(`${camelCase(key)}: '${val}',`)
    }),
    '}}'
  ]
}

module.exports = svg => svg
  .split('\n')
  .reduce((buffer, line, lineIndex) => {
    const matches = line.match(tagWithAttributes)
    if (!matches) { return buffer }
    const closingTag = matches[1] === '</'
    const tag = matches[2]
    const attrsStr = matches[3]
    const autoclosingTag = matches[4] === '/>'
    const indentLevel = line.match(leadingSpaces)[1].length
    const indentParentLine = indentLine(indentLevel + 2)
    const indentChildLine = indentLine(indentLevel + 2 + 2)
    const attributes = (attrsStr.match(attributesAndValues) || [])
      .map(str => {
        const [key, val] = str
          .trim()
          .replace(doubleQuotes, '\'')
          .split('=')
        if (key === 'class') { return null }
        if (key === 'style') {
          return getStyleAttribute(str)
            .map(indentChildLine)
            .join('\n')
        }
        return indentChildLine(`${camelCase(key)}=${val}`)
      })
      .filter(line => line)
      .join('\n')

    if (tag === 'svg') { return buffer }

    return buffer.concat((closingTag
      ? ([indentParentLine(`</${tag}>`)])
      : ([
        indentParentLine(`<${tag}`),
        attributes,
        indentParentLine(autoclosingTag ? '/>' : '>')
      ]))
      .filter(line => line)
      .join('\n'))
  }, [])
  .map((line, i, buffer) => {
    if (buffer[i + 1] && line.match(closingRootTag)) {
      return line + ','
    }
    return line
  })
  .join('\n')
  .trim()
<commit_msg>Fix: trim style string before parsing<commit_after>const { camelCase } = require('./stringOperations')

const tagWithAttributes = /(<\/?)([^ ]*) ?([^/]*)(\/?>)/
const doubleQuotes = /"/g
const leadingSpaces = /^( *)/
const attributesAndValues = /[^=]*="[^"]*"/g
const closingRootTag = /(\n\s{4}\/>)|(^\s{4}<\/)/

const indentLine = indentLevel => str => ' '.repeat(indentLevel) + str
const getStyleAttribute = str => {
  const trimmedStr = str.trim()
  const props = trimmedStr.substring('style="'.length, trimmedStr.length - 1).split(';')
  return [
    'style={{',
    ...props.map(prop => {
      const [key, val] = prop.split(':')
      return indentLine(2)(`${camelCase(key)}: '${val}',`)
    }),
    '}}'
  ]
}

module.exports = svg => svg
  .split('\n')
  .reduce((buffer, line, lineIndex) => {
    const matches = line.match(tagWithAttributes)
    if (!matches) { return buffer }
    const closingTag = matches[1] === '</'
    const tag = matches[2]
    const attrsStr = matches[3]
    const autoclosingTag = matches[4] === '/>'
    const indentLevel = line.match(leadingSpaces)[1].length
    const indentParentLine = indentLine(indentLevel + 2)
    const indentChildLine = indentLine(indentLevel + 2 + 2)
    const attributes = (attrsStr.match(attributesAndValues) || [])
      .map(str => {
        const [key, val] = str
          .trim()
          .replace(doubleQuotes, '\'')
          .split('=')
        if (key === 'class') { return null }
        if (key === 'style') {
          return getStyleAttribute(str)
            .map(indentChildLine)
            .join('\n')
        }
        return indentChildLine(`${camelCase(key)}=${val}`)
      })
      .filter(line => line)
      .join('\n')

    if (tag === 'svg') { return buffer }

    return buffer.concat((closingTag
      ? ([indentParentLine(`</${tag}>`)])
      : ([
        indentParentLine(`<${tag}`),
        attributes,
        indentParentLine(autoclosingTag ? '/>' : '>')
      ]))
      .filter(line => line)
      .join('\n'))
  }, [])
  .map((line, i, buffer) => {
    if (buffer[i + 1] && line.match(closingRootTag)) {
      return line + ','
    }
    return line
  })
  .join('\n')
  .trim()
<|endoftext|>


<commit_before>Template.feed.events({
  'submit [data-id=insert-post-form]': (event, template) => {
    event.preventDefault();

    Meteor.call('posts.insert', template.find('[data-id=body]').value, (error, result) => {
      if (error) {
        Bert.alert(error.reason, 'danger', 'growl-top-right');
      } else {
        Bert.alert('Post successfully submitted', 'success', 'growl-top-right');
        template.find('[data-id=body]').value = '';
      }
    });
  },

  'click [data-id=clear-form]': (event, template) => {
    template.find('[data-id=body]').value = '';
  },

  'click [data-id=load-more]': (event, template) => {
    template.limit.set(template.limit.get() + 20);
  },

  'keyup [data-id=search-query]': _.debounce((event, template) => {
    event.preventDefault();
    template.searchQuery.set(template.find('[data-id=search-query]').value);
    template.limit.set(20);
  }, 300),

  'submit [data-id=search-posts-form]': (event, template) => {
    event.preventDefault();
  }
});

Template.feed.helpers({
  posts: () => {
    const instance = Template.instance();
    if (instance.searchQuery.get()) {
      return Posts.find({}, { sort: [['score', 'desc']] }, { limit: instance.loaded.get() });
    }
    return Posts.find({}, { sort: { createdAt: -1 } }, { limit: instance.loaded.get() });
  },

  hasMorePosts: () => {
    return Template.instance().limit.get() <= Counts.get('posts.all');
  }
});

Template.feed.onCreated(function () {
  this.searchQuery = new ReactiveVar('');
  this.limit = new ReactiveVar(20);
  this.loaded = new ReactiveVar(0);

  this.autorun(() => {
    let subscription = this.subscribe('posts.all', this.searchQuery.get(), this.limit.get());
    if (subscription.ready()) {
      this.loaded.set(this.limit.get());
    }
  });
});
<commit_msg>Remove loaded variable in feed template<commit_after>Template.feed.events({
  'submit [data-id=insert-post-form]': (event, template) => {
    event.preventDefault();

    Meteor.call('posts.insert', template.find('[data-id=body]').value, (error, result) => {
      if (error) {
        Bert.alert(error.reason, 'danger', 'growl-top-right');
      } else {
        Bert.alert('Post successfully submitted', 'success', 'growl-top-right');
        template.find('[data-id=body]').value = '';
      }
    });
  },

  'click [data-id=clear-form]': (event, template) => {
    template.find('[data-id=body]').value = '';
  },

  'click [data-id=load-more]': (event, template) => {
    template.limit.set(template.limit.get() + 20);
  },

  'keyup [data-id=search-query]': _.debounce((event, template) => {
    event.preventDefault();
    template.searchQuery.set(template.find('[data-id=search-query]').value);
    template.limit.set(20);
  }, 300),

  'submit [data-id=search-posts-form]': (event, template) => {
    event.preventDefault();
  }
});

Template.feed.helpers({
  posts: () => {
    const instance = Template.instance();
    if (instance.searchQuery.get()) {
      return Posts.find({}, { sort: [['score', 'desc']] });
    }
    return Posts.find({}, { sort: { createdAt: -1 } });
  },

  hasMorePosts: () => {
    return Template.instance().limit.get() <= Counts.get('posts.all');
  }
});

Template.feed.onCreated(function () {
  this.searchQuery = new ReactiveVar('');
  this.limit = new ReactiveVar(20);

  this.autorun(() => {
    this.subscribe('posts.all', this.searchQuery.get(), this.limit.get());
  });
});
<|endoftext|>


<commit_before>module.exports = {
  devServer: {
    disableHostCheck: true
  }
}
<commit_msg>ms edge needs special care appearently<commit_after>module.exports = {
  devServer: {
    disableHostCheck: true
  },
  transpileDependencies: ['vuetify']
}
<|endoftext|>


<commit_before>const C = require('./constants')
const lib = require('./lib')
const builtins = require('./builtins')

export function evaluateExpression(expression, variables) {
  if(expression[0] === C.COMMENT) {
    return
  } else if (expression instanceof Array &&
             expression.every(e => e instanceof Array)) {
    return evaluateEachExpression(variables, expression)
  } if (expression[0] === C.VARIABLE_IDENTIFIER && expression[1] === 'environment') {
    return new lib.LEnvironment(variables);
  } else if (expression[0] === C.FUNCTION_CALL) {
    // Call a function: "function(arg1, arg2, arg3...)"

    // Get the function and argument expressions from the expression list.
    const fnExpression = expression[1]
    const argExpressions = expression[2]

    // Evaluate the function expression to get the actual function.
    const fn = evaluateExpression(fnExpression, variables)

    /* This code *used* to work but it doesn't any more, because some
     * parameters of the function could be unevaluated. Now argument evaluation
     * is done from within the call method of the function.
     */
    // Evaluate all of the arguments passed to the function.
    //const args = argExpressions.map(arg => evaluateExpression(arg, variables));
    fn.argumentScope = variables
    const args = argExpressions

    // Use lib.call to call the function with the evaluated arguments.
    return lib.call(fn, args)
  } else if(expression[0] === C.VARIABLE_IDENTIFIER) {
    // Get a variable: "name"

    // Get the name from the expression list.
    const name = expression[1]

    // Return the variable's value, or, if the variable doesn't exist, throw an
    // error.
    if (name in variables) {
      return variables[name].value
    } else {
      // FIXME: Change this message not to include *all* the variables within
      // the scope; maybe just say "variable (name) not found"?
      throw `variable ${name} not in [${Object.keys(variables)}]`
    }
  } else if (expression[0] === C.VARIABLE_ASSIGN) {
    // Set a variable to a value: "name => value"

    // Get the name and value expression from the expression list.
    const name = expression[1]
    const valueExpression = expression[2]

    // Evaluate the value of the variable.
    const value = evaluateExpression(valueExpression, variables)

    // Set the variable in the variables object to a new variable with the
    // evaluated value.
    variables[name] = new lib.variable(value)
    return
  } else if (expression[0] === C.VARIABLE_CHANGE) {
    // Change a variable to a new value: "name -> newValue"

    // Get the name and value expression from the expression list.
    const name = expression[1]
    const valueExpression = expression[2]

    // Evaluate the new value of the variable.
    const value = evaluateExpression(valueExpression, variables)

    // Change the value of the already defined variable.
    variables[name].value = value
    return
  } else if(expression[0] === C.FUNCTION_PRIM) {
    // A function literal: "fn(arg1, arg2, arg3...) { code }"

    // Get the code and paramaters from the expression list.
    const paramaters = expression[1]
    const code = expression[2]

    // Create the function using the given code.
    const fn = new lib.LFunction(code)

    // Set the scope variables for the function to a copy of the current
    // variables.
    fn.setScopeVariables(Object.assign({}, variables))

    // Set the paramaters for the function to the paramaters taken from the
    // expression list.
    fn.setParamaters(paramaters)

    // Return the function.
    return fn
  } else if(expression[0] === C.STRING_PRIM) {
    // String literal: "contents"

    // Get string from expression list.
    const string = expression[1]

    // Convert string to a language-usable string, and return.
    return lib.toLString(string)
  } else if(expression[0] === C.BOOLEAN_PRIM) {
    // Boolean literal: true/false

    // Get boolean value from expression list.
    const bool = expression[1]

    // Convert boolean value to a language-usable boolean, and return.
    return lib.toLBoolean(bool)
  } else if(expression[0] === C.NUMBER_PRIM) {
    // Number primitive: 1, 2, 3, 4, 7.25, -3, etc.

    // Get number value from expression list.
    const number = expression[1]

    // Convert number value to a language-usable number, and return.
    return lib.toLNumber(number)
  } else if(expression[0] === C.SET_PROP_USING_IDENTIFIER) {
    // Set a property of an object using an identifier literal:
    // "obj.key > value"

    // Get object expression, key, and value expression from expression list.
    const objExpression = expression[1]
    const key = expression[2]
    const valueExpression = expression[3]

    // Evaluate the object and value expressions.
    const obj = evaluateExpression(objExpression, variables)
    const value = evaluateExpression(valueExpression, variables)

    // Use lib.set to set the property of the evaluated object.
    lib.set(obj, key, value)
    return
  } else if(expression[0] === C.GET_PROP_USING_IDENTIFIER) {
    // Get a property of an object using an identifier literal: "obj.key"

    // Get object expression and key from the expression list.
    const objExpression = expression[1]
    const key = expression[2]

    // Evaluate the object expression.
    const obj = evaluateExpression(objExpression, variables)

    // Get the value from lib.get.
    const value = lib.get(obj, key)

    // Return the gotten value.
    return value
  } else {
    throw `Invalid expression type: ${expression[0]}`
  }
}

export function evaluateGetPropUsingIdentifier(variables, [_, objExpr, key]) {
  let obj = evaluateExpression(objExpr, variables)
  return lib.get(obj, key)
}

export function evaluateEachExpression(variables, expressions) {
  return expressions.map(e => evaluateExpression(e, variables))
}

export function interp(ast) {
  if(ast) {
    let variables = {}

    Object.assign(variables, builtins.makeBuiltins())

    let result = evaluateEachExpression(variables, ast)

    return { result, variables }
  } else {
    console.error('Haha, you didn\'t pass me a tree!')
  }
}
<commit_msg>lib.variable -> lib.Variable typo<commit_after>const C = require('./constants')
const lib = require('./lib')
const builtins = require('./builtins')

export function evaluateExpression(expression, variables) {
  if(expression[0] === C.COMMENT) {
    return
  } else if (expression instanceof Array &&
             expression.every(e => e instanceof Array)) {
    return evaluateEachExpression(variables, expression)
  } if (expression[0] === C.VARIABLE_IDENTIFIER && expression[1] === 'environment') {
    return new lib.LEnvironment(variables);
  } else if (expression[0] === C.FUNCTION_CALL) {
    // Call a function: "function(arg1, arg2, arg3...)"

    // Get the function and argument expressions from the expression list.
    const fnExpression = expression[1]
    const argExpressions = expression[2]

    // Evaluate the function expression to get the actual function.
    const fn = evaluateExpression(fnExpression, variables)

    /* This code *used* to work but it doesn't any more, because some
     * parameters of the function could be unevaluated. Now argument evaluation
     * is done from within the call method of the function.
     */
    // Evaluate all of the arguments passed to the function.
    //const args = argExpressions.map(arg => evaluateExpression(arg, variables));
    fn.argumentScope = variables
    const args = argExpressions

    // Use lib.call to call the function with the evaluated arguments.
    return lib.call(fn, args)
  } else if(expression[0] === C.VARIABLE_IDENTIFIER) {
    // Get a variable: "name"

    // Get the name from the expression list.
    const name = expression[1]

    // Return the variable's value, or, if the variable doesn't exist, throw an
    // error.
    if (name in variables) {
      return variables[name].value
    } else {
      // FIXME: Change this message not to include *all* the variables within
      // the scope; maybe just say "variable (name) not found"?
      throw `variable ${name} not in [${Object.keys(variables)}]`
    }
  } else if (expression[0] === C.VARIABLE_ASSIGN) {
    // Set a variable to a value: "name => value"

    // Get the name and value expression from the expression list.
    const name = expression[1]
    const valueExpression = expression[2]

    // Evaluate the value of the variable.
    const value = evaluateExpression(valueExpression, variables)

    // Set the variable in the variables object to a new variable with the
    // evaluated value.
    variables[name] = new lib.Variable(value)
    return
  } else if (expression[0] === C.VARIABLE_CHANGE) {
    // Change a variable to a new value: "name -> newValue"

    // Get the name and value expression from the expression list.
    const name = expression[1]
    const valueExpression = expression[2]

    // Evaluate the new value of the variable.
    const value = evaluateExpression(valueExpression, variables)

    // Change the value of the already defined variable.
    variables[name].value = value
    return
  } else if(expression[0] === C.FUNCTION_PRIM) {
    // A function literal: "fn(arg1, arg2, arg3...) { code }"

    // Get the code and paramaters from the expression list.
    const paramaters = expression[1]
    const code = expression[2]

    // Create the function using the given code.
    const fn = new lib.LFunction(code)

    // Set the scope variables for the function to a copy of the current
    // variables.
    fn.setScopeVariables(Object.assign({}, variables))

    // Set the paramaters for the function to the paramaters taken from the
    // expression list.
    fn.setParamaters(paramaters)

    // Return the function.
    return fn
  } else if(expression[0] === C.STRING_PRIM) {
    // String literal: "contents"

    // Get string from expression list.
    const string = expression[1]

    // Convert string to a language-usable string, and return.
    return lib.toLString(string)
  } else if(expression[0] === C.BOOLEAN_PRIM) {
    // Boolean literal: true/false

    // Get boolean value from expression list.
    const bool = expression[1]

    // Convert boolean value to a language-usable boolean, and return.
    return lib.toLBoolean(bool)
  } else if(expression[0] === C.NUMBER_PRIM) {
    // Number primitive: 1, 2, 3, 4, 7.25, -3, etc.

    // Get number value from expression list.
    const number = expression[1]

    // Convert number value to a language-usable number, and return.
    return lib.toLNumber(number)
  } else if(expression[0] === C.SET_PROP_USING_IDENTIFIER) {
    // Set a property of an object using an identifier literal:
    // "obj.key > value"

    // Get object expression, key, and value expression from expression list.
    const objExpression = expression[1]
    const key = expression[2]
    const valueExpression = expression[3]

    // Evaluate the object and value expressions.
    const obj = evaluateExpression(objExpression, variables)
    const value = evaluateExpression(valueExpression, variables)

    // Use lib.set to set the property of the evaluated object.
    lib.set(obj, key, value)
    return
  } else if(expression[0] === C.GET_PROP_USING_IDENTIFIER) {
    // Get a property of an object using an identifier literal: "obj.key"

    // Get object expression and key from the expression list.
    const objExpression = expression[1]
    const key = expression[2]

    // Evaluate the object expression.
    const obj = evaluateExpression(objExpression, variables)

    // Get the value from lib.get.
    const value = lib.get(obj, key)

    // Return the gotten value.
    return value
  } else {
    throw `Invalid expression type: ${expression[0]}`
  }
}

export function evaluateGetPropUsingIdentifier(variables, [_, objExpr, key]) {
  let obj = evaluateExpression(objExpr, variables)
  return lib.get(obj, key)
}

export function evaluateEachExpression(variables, expressions) {
  return expressions.map(e => evaluateExpression(e, variables))
}

export function interp(ast) {
  if(ast) {
    let variables = {}

    Object.assign(variables, builtins.makeBuiltins())

    let result = evaluateEachExpression(variables, ast)

    return { result, variables }
  } else {
    console.error('Haha, you didn\'t pass me a tree!')
  }
}
<|endoftext|>