<commit_before>var _ = require('lodash');
var Constants = require('./constants');

/*
 * Returns a size x size matrix with all entries initialized to Constants.EMPTY
 */
function createIntersections(size) {
  var range = _.range(size);
  return _.map(range, function() {
    return _.map(range, function() { return Constants.EMPTY; });
  });
};

var BoardPrototype = {

  inBounds: function(coords) {
    var i = coords[0], j = coords[1];
    return i >= 0 && i < this.size && j >= 0 && j < this.size;
  },

  getStone: function(coords) {
    return this.intersections[coords[0]][coords[1]];
  },

  toString: function() {
    return _.map(this.intersections, function(row) {return row.join('');}).join('\n');
  },

  /*
   * Attempt to place a stone at (i,j).
   */
  play: function(playerColor, i, j) {
    if (!this.inBounds([i, j]))
      throw "Intersection out of bounds";

    if (this.intersections[i][j] != Constants.EMPTY)
      throw "Intersection occupied by existing stone";

    var color = this.intersections[i][j] = playerColor;
    var neighbors = this.getAdjacentIntersections(i, j);

    var captured = _(neighbors)
      .zip(_.map(neighbors, this.getStone.bind(this)))
      .filter(function(x) { return x[1] != Constants.EMPTY && x[1] != color; })
      .map(_.first)
      .map(this.getGroup.bind(this))
      .filter(function(g) { return g.liberties === 0; })
      .value();

    // detect suicide
    var newGroup = this.getGroup([i, j]);
    if (_.isEmpty(captured) && newGroup.liberties === 0) {
      captured = [newGroup];
    }

    // remove captured stones
    var self = this;
    _.each(captured, function(group) {
      _.each(group["stones"], function(stone) {
        self.intersections[stone[0]][stone[1]] = Constants.EMPTY;
      });
    });

    return this;
  },

  /*
   * Given a board position, returns a list of [i,j] coordinates representing
   * orthagonally adjacent intersections
   */
  getAdjacentIntersections: function(i , j) {
    var neighbors = [];
    if (i > 0)
      neighbors.push([i - 1, j]);
    if (j < this.size - 1)
      neighbors.push([i, j + 1]);
    if (i < this.size - 1)
      neighbors.push([i + 1, j]);
    if (j > 0)
      neighbors.push([i, j - 1]);
    return neighbors;
  },

  /*
   * Performs a breadth-first search about an (i,j) position to find recursively
   * orthagonally adjacent stones of the same color (stones with which it shares
   * liberties). Returns null for if there is no stone at the specified position,
   * otherwise returns an object with two keys: "liberties", specifying the
   * number of liberties the group has, and "stones", the list of [i,j]
   * coordinates of the group's members.
   */
  getGroup: function(coords) {
    var color = this.getStone(coords);
    if (color == Constants.EMPTY)
      return null;

    var visited = {}; // for O(1) lookups
    var visited_list = []; // for returning
    var queue = [coords];
    var count = 0;

    while (queue.length > 0) {
      var stone = queue.pop();
      if (visited[stone])
        continue;

      var neighbors = this.getAdjacentIntersections(stone[0], stone[1]);
      var self = this;
      _.each(neighbors, function(n) {
        var state = self.getStone(n);
        if (state == Constants.EMPTY)
          count++;
        if (state == color)
          queue.push(n);
      });

      visited[stone] = true;
      visited_list.push(stone);
    }

    return {
      "liberties": count,
      "stones": visited_list
    };
  }
};

function createBoard(size) {
  var board = Object.create(BoardPrototype);
  board.size = size;
  board.intersections = createIntersections(size);
  return board;
};

module.exports = {
  createBoard: createBoard,
  EMPTY: Constants.EMPTY,
  BLACK: Constants.BLACK,
  WHITE: Constants.WHITE
};
<commit_msg>getAdjacentIntersections accepts coordinate pair<commit_after>var _ = require('lodash');
var Constants = require('./constants');

/*
 * Returns a size x size matrix with all entries initialized to Constants.EMPTY
 */
function createIntersections(size) {
  var range = _.range(size);
  return _.map(range, function() {
    return _.map(range, function() { return Constants.EMPTY; });
  });
};

var BoardPrototype = {

  inBounds: function(coords) {
    var i = coords[0], j = coords[1];
    return i >= 0 && i < this.size && j >= 0 && j < this.size;
  },

  getStone: function(coords) {
    return this.intersections[coords[0]][coords[1]];
  },

  toString: function() {
    return _.map(this.intersections, function(row) {return row.join('');}).join('\n');
  },

  /*
   * Attempt to place a stone at (i,j).
   */
  play: function(playerColor, i, j) {
    var coords = [i, j];
    if (!this.inBounds(coords))
      throw "Intersection out of bounds";

    if (this.intersections[i][j] != Constants.EMPTY)
      throw "Intersection occupied by existing stone";

    var color = this.intersections[i][j] = playerColor;
    var neighbors = this.getAdjacentIntersections(coords);

    var captured = _(neighbors)
      .zip(_.map(neighbors, this.getStone.bind(this)))
      .filter(function(x) { return x[1] != Constants.EMPTY && x[1] != color; })
      .map(_.first)
      .map(this.getGroup.bind(this))
      .filter(function(g) { return g.liberties === 0; })
      .value();

    // detect suicide
    var newGroup = this.getGroup([i, j]);
    if (_.isEmpty(captured) && newGroup.liberties === 0) {
      captured = [newGroup];
    }

    // remove captured stones
    var self = this;
    _.each(captured, function(group) {
      _.each(group["stones"], function(stone) {
        self.intersections[stone[0]][stone[1]] = Constants.EMPTY;
      });
    });

    return this;
  },

  /*
   * Given a board position, returns a list of [i,j] coordinates representing
   * orthagonally adjacent intersections
   */
  getAdjacentIntersections: function(coords) {
    var i = coords[0], j = coords[1];
    var neighbors = [];
    if (i > 0)
      neighbors.push([i - 1, j]);
    if (j < this.size - 1)
      neighbors.push([i, j + 1]);
    if (i < this.size - 1)
      neighbors.push([i + 1, j]);
    if (j > 0)
      neighbors.push([i, j - 1]);
    return neighbors;
  },

  /*
   * Performs a breadth-first search about an (i,j) position to find recursively
   * orthagonally adjacent stones of the same color (stones with which it shares
   * liberties). Returns null for if there is no stone at the specified position,
   * otherwise returns an object with two keys: "liberties", specifying the
   * number of liberties the group has, and "stones", the list of [i,j]
   * coordinates of the group's members.
   */
  getGroup: function(coords) {
    var color = this.getStone(coords);
    if (color == Constants.EMPTY)
      return null;

    var visited = {}; // for O(1) lookups
    var visited_list = []; // for returning
    var queue = [coords];
    var count = 0;

    while (queue.length > 0) {
      var stone = queue.pop();
      if (visited[stone])
        continue;

      var neighbors = this.getAdjacentIntersections(stone);
      var self = this;
      _.each(neighbors, function(n) {
        var state = self.getStone(n);
        if (state == Constants.EMPTY)
          count++;
        if (state == color)
          queue.push(n);
      });

      visited[stone] = true;
      visited_list.push(stone);
    }

    return {
      "liberties": count,
      "stones": visited_list
    };
  }
};

function createBoard(size) {
  var board = Object.create(BoardPrototype);
  board.size = size;
  board.intersections = createIntersections(size);
  return board;
};

module.exports = {
  createBoard: createBoard,
  EMPTY: Constants.EMPTY,
  BLACK: Constants.BLACK,
  WHITE: Constants.WHITE
};
<|endoftext|>


<commit_before><commit_msg>do never remove page 1, just leave it blank<commit_after><|endoftext|>


<commit_before><commit_msg>create action-path if not exists<commit_after><|endoftext|>


<commit_before>
'use strict';

var sh = require('shelljs')
  , fs = require('fs')
  , Handlebars = require('handlebars')
  , Trello = require('./trello')
  , async = require('async')
  , slug = require('slug')
  , path = require('path')
  , kramed = require('kramed');

var registerHelpers = function() {
  // We'll provide a `markdown` helper but do before registering uerland helpers
  // so they  can override use if desired
  Handlebars.registerHelper('markdown', function(markup, options) {
    return new Handlebars.SafeString(kramed(markup));
  });

  sh.ls('./src/helpers/*.js').forEach(function(f) {
    var helperName = path.basename(f, '.js')
      , helper = require(path.join(process.cwd(), f));
    Handlebars.registerHelper(helperName, helper);
  });
};

module.exports = function(opts, cb) {
  registerHelpers();
  sh.rm('-rf', 'dist');
  sh.mkdir('dist');
  fs.readFile('./src/index.hbs', function(err, data) {
    if(err) { return cb(err); }
    var cardTplSrc = data.toString()
      , cardTpl = Handlebars.compile(cardTplSrc);

    var t = new Trello(opts.trelloApiKey, opts.trelloToken);

    t.getBoardCards(opts.trelloBoardUrl, function(err, cards) {
      if(err) { return cb(err); }

      // Don't really want to force the use to install a markdow compiler...
      // just augment card data here?

      async.each(cards,
        function(card, done) {
          fs.writeFile('dist/' + slug(card.name).toLowerCase() + '.html', cardTpl(card), done)
        },
        function(err) {
          cb(err);
        });
    });
  });
  cb();
};
<commit_msg>feature: Add position to card file names<commit_after>
'use strict';

var sh = require('shelljs')
  , fs = require('fs')
  , Handlebars = require('handlebars')
  , Trello = require('./trello')
  , async = require('async')
  , slug = require('slug')
  , path = require('path')
  , kramed = require('kramed');

var registerHelpers = function() {
  // We'll provide a `markdown` helper but do before registering uerland helpers
  // so they  can override use if desired
  Handlebars.registerHelper('markdown', function(markup, options) {
    return new Handlebars.SafeString(kramed(markup));
  });

  sh.ls('./src/helpers/*.js').forEach(function(f) {
    var helperName = path.basename(f, '.js')
      , helper = require(path.join(process.cwd(), f));
    Handlebars.registerHelper(helperName, helper);
  });
};

module.exports = function(opts, cb) {
  registerHelpers();
  sh.rm('-rf', 'dist');
  sh.mkdir('dist');
  fs.readFile('./src/index.hbs', function(err, data) {
    if(err) { return cb(err); }
    var cardTplSrc = data.toString()
      , cardTpl = Handlebars.compile(cardTplSrc);

    var t = new Trello(opts.trelloApiKey, opts.trelloToken);

    t.getBoardCards(opts.trelloBoardUrl, function(err, cards) {
      if(err) { return cb(err); }

      // Don't really want to force the use to install a markdow compiler...
      // just augment card data here?

      async.each(cards,
        function(card, done) {
          fs.writeFile('dist/' + card.pos + '-' + slug(card.name).toLowerCase() + '.html', cardTpl(card), done)
        },
        function(err) {
          cb(err);
        });
    });
  });
  cb();
};
<|endoftext|>


<commit_before>
// npm build command

// everything about the installation after the creation of
// the .npm/{name}/{version}/package folder.
// linking the main.js and libs folder, dropping these into
// the npm.root, resolving dependencies, etc.

// This runs AFTER install or link are completed.

var npm = require("../npm")
  , log = require("./utils/log")
  , rm = require("./utils/rm-rf")
  , chain = require("./utils/chain")
  , fetch = require("./utils/fetch")
  , fs = require("fs")
  , path = require("path")
  , semver = require("./utils/semver")
  , mkdir = require("./utils/mkdir-p")
  , lifecycle = require("./utils/lifecycle")
  , readJson = require("./utils/read-json")
  , ini = require("./utils/ini")
  , sys = require("sys")
  , writeShim = require("./utils/write-shim")
  , link = require("./utils/link")
  , linkIfExists = link.ifExists
  , shimIfExists = writeShim.ifExists

module.exports = build

// pkg is either a "package" folder, or a package.json data obj, or an
// object that has the package.json data on the _data member.
function build (args, cb) {
  readAll(args, function (er, args) {
    if (er) return cb(er)
    chain(args.map(function (a) {
      return [buildStep, a]
    }).concat(
      [ [ linkDependencies, args]
      , [ finishBuild, args ]
      ]).concat(cb))
  })
}

function buildStep (pkg, cb) {
  pkg = pkg && pkg._data || pkg
  if (!pkg) return cb(new Error("Invalid package data "+sys.inspect(pkg)))

  var ROOT = npm.root
    , npmdir = npm.dir

  chain
    ( [lifecycle, pkg, "preinstall"]
      // make sure that all dependencies are already installed.
    , [resolveDependencies, pkg]

      // generate ROOT/.npm/{name}/{version}/main.js
    , [createMain, pkg]

      // symlink ROOT/{name}-{version}.js to ROOT/.npm/{name}/{version}/main.js
    , [linkMain, pkg]

      // symlink ROOT/{name}-{version}/ to ROOT/.npm/{name}/{version}/{lib}
    , [linkLib, pkg]

      // symlink any bins into the node install prefix
    , [linkBins, pkg]

    , cb
    )
}

function autoActivate (pkg, cb) {
  var auto = npm.config.get("auto-activate")
  if (!auto) {
    log("auto-activate disabled by config", "auto-activate")
    return cb()
  }
  pkg = pkg && pkg._data || pkg
  // get the list of versions of this package.
  fs.readdir(path.join(npm.dir, pkg.name), function (er, versions) {
    if (er) return cb(er)
    if (auto !== "always" && versions.indexOf("active") !== -1) {
      log("another version already active", "auto-activate")
      log("to activate, do:   npm activate "+
        pkg.name+" "+pkg.version, "auto-activate")
      return cb()
    }
    log(pkg.name+"@"+pkg.version, "activate")
    npm.commands.activate([pkg.name+"@"+pkg.version], cb)
  })
}

function readAll (folders, cb) {
  folders = folders.slice(0)
  var data = []
  ;(function R (folder) {
    if (!folder) return cb(null, data)
    if (typeof folder === "object") {
      data.push(folder)
      return R(folders.pop())
    }
    readJson(path.join(folder, "package.json"), function (er, d) {
      if (er) return cb(er)
      data.push(d)
      return R(folders.pop())
    })
  })(folders.pop())
}

// make sure that all the dependencies have been installed.
function resolveDependencies (pkg, topCb) {
  if (!pkg) return topCb(new Error("Package not found to resolve dependencies"))
  // link foo-1.0.3 to ROOT/.npm/{pkg}/{version}/dependencies/foo

  var found = []
  chain
    ( [mkdir, path.join(npm.dir, pkg.name, pkg.version, "dependencies")]
    , function (cb) {
        if (!pkg.dependencies) return topCb()
        // don't create anything until they're all verified.
        var reqs = []
        for (var i in pkg.dependencies) reqs.push({name:i, version:pkg.dependencies[i]})
        if (!reqs.length) return topCb()
        ;(function R (req) {
          if (!req) {
            found.forEach(function (req) {
              log(req.name + "@" + req.version, "found")
            })
            return cb()
          }
          log(req.name+"-"+req.version, "required")
          // see if we have this thing installed.
          fs.readdir(path.join(npm.dir, req.name), function (er, versions) {
            if (er) return cb(new Error(
              "Required package: "+req.name+"("+req.version+") not found."))
            // TODO: Get the "stable" version if there is one.
            // Look that up from the registry.
            var satis = semver.maxSatisfying(versions, req.version)
            if (satis) {
              found.push({name:req.name, version:satis})
              return R(reqs.pop())
            }
            return cb(new Error(
              "Required package: "+req.name+"("+req.version+") not found. "+
              "(Found: "+JSON.stringify(versions)+")"))
          })
        })(reqs.pop())
      }

      // save the resolved dependencies on the pkg data for later
    , function (cb) { pkg._resolvedDeps = found; cb() }
    , topCb
    )
}

function linkDependencies (args, cb) {
  // at this point, we know that all the packages in the "args" list have
  // been installed, and so have all the dependencies in each of their
  // _resolvedDeps array.
  // link each package's _resolvedDeps properly.
  var c = []
  args.filter(function (pkg) {
    return pkg._resolvedDeps && pkg._resolvedDeps.length
  }).forEach(function (pkg) {
    c.push( [ dependentLink, pkg ]
          , [ dependencyLink, pkg ]
          )
  })
  c.push(cb)
  chain(c)
}
// for each dependency, link this pkg into the proper "dependent" folder
function dependentLink (pkg, cb) {
  if (!pkg._resolvedDeps || !pkg._resolvedDeps.length) return cb()
  chain(pkg._resolvedDeps.map(function (dep) {
    var dependents = path.join(npm.dir, dep.name, dep.version, "dependents")
      , to = path.join(dependents, pkg.name + "-" + pkg.version)
      , from = path.join(npm.dir, pkg.name, pkg.version)
    return [link, from, to]
  }).concat(cb))
}
// link each dep into this pkg's "dependencies" folder
function dependencyLink (pkg, cb) {
  if (!pkg._resolvedDeps || !pkg._resolvedDeps.length) return cb()
  chain(pkg._resolvedDeps.map(function (dep) { return function (cb) {
    pkg.link = pkg.link || {}
    var dependencies = path.join(npm.dir, pkg.name, pkg.version, "dependencies")
      , dependsOn = path.join( npm.dir, pkg.name, pkg.version
                             , "dependson", dep.name + "-" + dep.version
                             )
      , fromRoot = path.join(npm.dir, dep.name, dep.version)
      , fromLib = path.join(npm.root, dep.name + "-" + dep.version)
      , fromMain = fromLib + ".js"
      , toLib = path.join(dependencies, dep.name)
      , toMain = toLib+".js"
      , linkToLib = (dep.name in pkg.link)
        ? path.join(npm.dir, pkg.name, pkg.version, "package", pkg.link[dep.name])
        : null
      , linkToMain = linkToLib ? linkToLib + ".js" : null
    chain([ [ mkdir, dependsOn ]
          , [ link, fromRoot, dependsOn ]
          , [ shimIfExists, fromMain, toMain ]
          , [ linkIfExists, fromLib, toLib ]
          , linkToLib && [ linkIfExists, fromLib, linkToLib ]
          , linkToMain && [ shimIfExists, fromMain, linkToMain ]
          , cb
          ].filter(function (_) { return _ }))
  }}).concat(cb))
}

function createMain (pkg,cb) {
  if (!pkg.main) return cb()
  log(pkg.main, "createMain")
  writeShim
    ( path.join(npm.dir, pkg.name, pkg.version, "package", pkg.main)
    , path.join(npm.dir, pkg.name, pkg.version, "main.js")
    , path.join(npm.dir, pkg.name, pkg.version, "dependencies")
    , cb
    )
}

// symlink ROOT/{name}-{version}/ to ROOT/.npm/{name}/{version}/{lib}
function linkLib (pkg, cb) {
  var lib = pkg.directories && pkg.directories.lib || pkg.lib
  if (!lib) return cb()
  log(pkg._id, "linkLib")
  log(" ", "! WARNING !")
  log("Symlinking the lib directory is deprecated", "! WARNING !")
  log("Please don't rely on this feature, as it will be removed.", "! WARNING !")
  log("Use the 'main' module instead.", "! WARNING !")
  log(" ", "! WARNING !")
  var from = path.join(npm.dir, pkg.name, pkg.version, "package", lib)
    , toInternal = path.join(npm.dir, pkg.name, pkg.version, "lib")
    , to = path.join(npm.root, pkg.name+"-"+pkg.version)

  function doLink (er) {
    if (er) return cb(er)
    chain
      ( [rm, toInternal]
      , [rm, to]
      , function (cb) { fs.symlink(from, toInternal, function (er) {
          if (er) return cb(er)
          fs.symlink(toInternal, to, cb)
        })}
      , cb
      )
  }

  fs.stat(from, function (er, s) {
    if (er) return cb(new Error("Libs dir not found "+from))
    if (!s.isDirectory()) return cb(new Error("Libs dir not a dir: "+lib))
    // make sure that it doesn't already exist.  If so, rm it.
    fs.lstat(to, function (er, s) {
      if (!er) fs.unlink(to, doLink)
      else doLink()
    })
  })
}

function linkMain (pkg, cb) {
  if (!pkg.main) return cb()
  var from = path.join(npm.dir, pkg.name, pkg.version, "main.js")
    , to = path.join(npm.root, pkg.name+"-"+pkg.version+".js")
  fs.lstat(to, function (er) {
    if (!er) rm(to, function (er) {
      if (er) cb(er)
      else linkMain(pkg, cb)
    })
    else writeShim(from, to, cb)
  })
}

function linkBins (pkg, cb) {
  if (!pkg.bin) return cb()
  log(pkg._id, "linkBins")
  var binroot = npm.config.get("binroot")
    , dep = path.join(npm.dir, pkg.name, pkg.version, "dependencies")
  if (!binroot) return cb()
  if (!process.env.PATH || -1 === process.env.PATH.indexOf(binroot)) {
    log("bins installing to "+binroot+", outside PATH", "warning")
  }
  chain(Object.keys(pkg.bin).filter(function (i) {
    return i.charAt(0) !== "_"
  }).map(function (i) {
    log(i+" "+pkg.bin[i], "linkBin")
    var to = path.join(binroot, i+"-"+pkg.version)
      , from = path.join(npm.dir, pkg.name, pkg.version, "package", pkg.bin[i])
    return [shimTest, from, to, dep]
  }).concat(log.er(cb, "failed to link bins")))
}

function shimTest (from, to, dep, cb) {
  // if it needs a shim, then call writeShim
  // otherwise, just link it in.
  if (from.match(/\.(node|js)$/)) return writeShim(from, to, dep, cb)
  fs.readFile(from, function (er, data) {
    if (er) return cb(er)
    data = data.toString("ascii")
    var envNode = data.match(/#!(\/usr\/bin\/)?env node/)
      , node = data.match(/#!(\/usr(\/local)?\/bin\/)?node/)
    if (envNode && envNode.index === 0 || node && node.index === 0) {
      return writeShim(from, to, dep, cb)
    }
    return link(from, to, cb)
  })
}

function finishBuild (args, cb) {
  chain(args.map(function (pkg) { return function (cb) {
    chain
      ( [lifecycle, pkg, "install"]
      , [lifecycle, pkg, "postinstall"]
      , [autoActivate, pkg]
      , cb
      )
  }}).concat(args.map(function (pkg) {
    pkg = pkg && pkg._data || pkg
    return [ log, "Success: "+(pkg.name + "@"+pkg.version), "build" ]
  })).concat(cb))
}
<commit_msg>Remove unnecessary vars<commit_after>
// npm build command

// everything about the installation after the creation of
// the .npm/{name}/{version}/package folder.
// linking the main.js and libs folder, dropping these into
// the npm.root, resolving dependencies, etc.

// This runs AFTER install or link are completed.

var npm = require("../npm")
  , log = require("./utils/log")
  , rm = require("./utils/rm-rf")
  , chain = require("./utils/chain")
  , fetch = require("./utils/fetch")
  , fs = require("fs")
  , path = require("path")
  , semver = require("./utils/semver")
  , mkdir = require("./utils/mkdir-p")
  , lifecycle = require("./utils/lifecycle")
  , readJson = require("./utils/read-json")
  , ini = require("./utils/ini")
  , sys = require("sys")
  , writeShim = require("./utils/write-shim")
  , link = require("./utils/link")
  , linkIfExists = link.ifExists
  , shimIfExists = writeShim.ifExists

module.exports = build

// pkg is either a "package" folder, or a package.json data obj, or an
// object that has the package.json data on the _data member.
function build (args, cb) {
  readAll(args, function (er, args) {
    if (er) return cb(er)
    chain(args.map(function (a) {
      return [buildStep, a]
    }).concat(
      [ [ linkDependencies, args]
      , [ finishBuild, args ]
      ]).concat(cb))
  })
}

function buildStep (pkg, cb) {
  pkg = pkg && pkg._data || pkg
  if (!pkg) return cb(new Error("Invalid package data "+sys.inspect(pkg)))
  chain
    ( [lifecycle, pkg, "preinstall"]
      // make sure that all dependencies are already installed.
    , [resolveDependencies, pkg]

      // generate ROOT/.npm/{name}/{version}/main.js
    , [createMain, pkg]

      // symlink ROOT/{name}-{version}.js to ROOT/.npm/{name}/{version}/main.js
    , [linkMain, pkg]

      // symlink ROOT/{name}-{version}/ to ROOT/.npm/{name}/{version}/{lib}
    , [linkLib, pkg]

      // symlink any bins into the node install prefix
    , [linkBins, pkg]

    , cb
    )
}

function autoActivate (pkg, cb) {
  var auto = npm.config.get("auto-activate")
  if (!auto) {
    log("auto-activate disabled by config", "auto-activate")
    return cb()
  }
  pkg = pkg && pkg._data || pkg
  // get the list of versions of this package.
  fs.readdir(path.join(npm.dir, pkg.name), function (er, versions) {
    if (er) return cb(er)
    if (auto !== "always" && versions.indexOf("active") !== -1) {
      log("another version already active", "auto-activate")
      log("to activate, do:   npm activate "+
        pkg.name+" "+pkg.version, "auto-activate")
      return cb()
    }
    log(pkg.name+"@"+pkg.version, "activate")
    npm.commands.activate([pkg.name+"@"+pkg.version], cb)
  })
}

function readAll (folders, cb) {
  folders = folders.slice(0)
  var data = []
  ;(function R (folder) {
    if (!folder) return cb(null, data)
    if (typeof folder === "object") {
      data.push(folder)
      return R(folders.pop())
    }
    readJson(path.join(folder, "package.json"), function (er, d) {
      if (er) return cb(er)
      data.push(d)
      return R(folders.pop())
    })
  })(folders.pop())
}

// make sure that all the dependencies have been installed.
function resolveDependencies (pkg, topCb) {
  if (!pkg) return topCb(new Error("Package not found to resolve dependencies"))
  // link foo-1.0.3 to ROOT/.npm/{pkg}/{version}/dependencies/foo

  var found = []
  chain
    ( [mkdir, path.join(npm.dir, pkg.name, pkg.version, "dependencies")]
    , function (cb) {
        if (!pkg.dependencies) return topCb()
        // don't create anything until they're all verified.
        var reqs = []
        for (var i in pkg.dependencies) reqs.push({name:i, version:pkg.dependencies[i]})
        if (!reqs.length) return topCb()
        ;(function R (req) {
          if (!req) {
            found.forEach(function (req) {
              log(req.name + "@" + req.version, "found")
            })
            return cb()
          }
          log(req.name+"-"+req.version, "required")
          // see if we have this thing installed.
          fs.readdir(path.join(npm.dir, req.name), function (er, versions) {
            if (er) return cb(new Error(
              "Required package: "+req.name+"("+req.version+") not found."))
            // TODO: Get the "stable" version if there is one.
            // Look that up from the registry.
            var satis = semver.maxSatisfying(versions, req.version)
            if (satis) {
              found.push({name:req.name, version:satis})
              return R(reqs.pop())
            }
            return cb(new Error(
              "Required package: "+req.name+"("+req.version+") not found. "+
              "(Found: "+JSON.stringify(versions)+")"))
          })
        })(reqs.pop())
      }

      // save the resolved dependencies on the pkg data for later
    , function (cb) { pkg._resolvedDeps = found; cb() }
    , topCb
    )
}

function linkDependencies (args, cb) {
  // at this point, we know that all the packages in the "args" list have
  // been installed, and so have all the dependencies in each of their
  // _resolvedDeps array.
  // link each package's _resolvedDeps properly.
  var c = []
  args.filter(function (pkg) {
    return pkg._resolvedDeps && pkg._resolvedDeps.length
  }).forEach(function (pkg) {
    c.push( [ dependentLink, pkg ]
          , [ dependencyLink, pkg ]
          )
  })
  c.push(cb)
  chain(c)
}
// for each dependency, link this pkg into the proper "dependent" folder
function dependentLink (pkg, cb) {
  if (!pkg._resolvedDeps || !pkg._resolvedDeps.length) return cb()
  chain(pkg._resolvedDeps.map(function (dep) {
    var dependents = path.join(npm.dir, dep.name, dep.version, "dependents")
      , to = path.join(dependents, pkg.name + "-" + pkg.version)
      , from = path.join(npm.dir, pkg.name, pkg.version)
    return [link, from, to]
  }).concat(cb))
}
// link each dep into this pkg's "dependencies" folder
function dependencyLink (pkg, cb) {
  if (!pkg._resolvedDeps || !pkg._resolvedDeps.length) return cb()
  chain(pkg._resolvedDeps.map(function (dep) { return function (cb) {
    pkg.link = pkg.link || {}
    var dependencies = path.join(npm.dir, pkg.name, pkg.version, "dependencies")
      , dependsOn = path.join( npm.dir, pkg.name, pkg.version
                             , "dependson", dep.name + "-" + dep.version
                             )
      , fromRoot = path.join(npm.dir, dep.name, dep.version)
      , fromLib = path.join(npm.root, dep.name + "-" + dep.version)
      , fromMain = fromLib + ".js"
      , toLib = path.join(dependencies, dep.name)
      , toMain = toLib+".js"
      , linkToLib = (dep.name in pkg.link)
        ? path.join(npm.dir, pkg.name, pkg.version, "package", pkg.link[dep.name])
        : null
      , linkToMain = linkToLib ? linkToLib + ".js" : null
    chain([ [ mkdir, dependsOn ]
          , [ link, fromRoot, dependsOn ]
          , [ shimIfExists, fromMain, toMain ]
          , [ linkIfExists, fromLib, toLib ]
          , linkToLib && [ linkIfExists, fromLib, linkToLib ]
          , linkToMain && [ shimIfExists, fromMain, linkToMain ]
          , cb
          ].filter(function (_) { return _ }))
  }}).concat(cb))
}

function createMain (pkg,cb) {
  if (!pkg.main) return cb()
  log(pkg.main, "createMain")
  writeShim
    ( path.join(npm.dir, pkg.name, pkg.version, "package", pkg.main)
    , path.join(npm.dir, pkg.name, pkg.version, "main.js")
    , path.join(npm.dir, pkg.name, pkg.version, "dependencies")
    , cb
    )
}

// symlink ROOT/{name}-{version}/ to ROOT/.npm/{name}/{version}/{lib}
function linkLib (pkg, cb) {
  var lib = pkg.directories && pkg.directories.lib || pkg.lib
  if (!lib) return cb()
  log(pkg._id, "linkLib")
  log(" ", "! WARNING !")
  log("Symlinking the lib directory is deprecated", "! WARNING !")
  log("Please don't rely on this feature, as it will be removed.", "! WARNING !")
  log("Use the 'main' module instead.", "! WARNING !")
  log(" ", "! WARNING !")
  var from = path.join(npm.dir, pkg.name, pkg.version, "package", lib)
    , toInternal = path.join(npm.dir, pkg.name, pkg.version, "lib")
    , to = path.join(npm.root, pkg.name+"-"+pkg.version)

  function doLink (er) {
    if (er) return cb(er)
    chain
      ( [rm, toInternal]
      , [rm, to]
      , function (cb) { fs.symlink(from, toInternal, function (er) {
          if (er) return cb(er)
          fs.symlink(toInternal, to, cb)
        })}
      , cb
      )
  }

  fs.stat(from, function (er, s) {
    if (er) return cb(new Error("Libs dir not found "+from))
    if (!s.isDirectory()) return cb(new Error("Libs dir not a dir: "+lib))
    // make sure that it doesn't already exist.  If so, rm it.
    fs.lstat(to, function (er, s) {
      if (!er) fs.unlink(to, doLink)
      else doLink()
    })
  })
}

function linkMain (pkg, cb) {
  if (!pkg.main) return cb()
  var from = path.join(npm.dir, pkg.name, pkg.version, "main.js")
    , to = path.join(npm.root, pkg.name+"-"+pkg.version+".js")
  fs.lstat(to, function (er) {
    if (!er) rm(to, function (er) {
      if (er) cb(er)
      else linkMain(pkg, cb)
    })
    else writeShim(from, to, cb)
  })
}

function linkBins (pkg, cb) {
  if (!pkg.bin) return cb()
  log(pkg._id, "linkBins")
  var binroot = npm.config.get("binroot")
    , dep = path.join(npm.dir, pkg.name, pkg.version, "dependencies")
  if (!binroot) return cb()
  if (!process.env.PATH || -1 === process.env.PATH.indexOf(binroot)) {
    log("bins installing to "+binroot+", outside PATH", "warning")
  }
  chain(Object.keys(pkg.bin).filter(function (i) {
    return i.charAt(0) !== "_"
  }).map(function (i) {
    log(i+" "+pkg.bin[i], "linkBin")
    var to = path.join(binroot, i+"-"+pkg.version)
      , from = path.join(npm.dir, pkg.name, pkg.version, "package", pkg.bin[i])
    return [shimTest, from, to, dep]
  }).concat(log.er(cb, "failed to link bins")))
}

function shimTest (from, to, dep, cb) {
  // if it needs a shim, then call writeShim
  // otherwise, just link it in.
  if (from.match(/\.(node|js)$/)) return writeShim(from, to, dep, cb)
  fs.readFile(from, function (er, data) {
    if (er) return cb(er)
    data = data.toString("ascii")
    var envNode = data.match(/#!(\/usr\/bin\/)?env node/)
      , node = data.match(/#!(\/usr(\/local)?\/bin\/)?node/)
    if (envNode && envNode.index === 0 || node && node.index === 0) {
      return writeShim(from, to, dep, cb)
    }
    return link(from, to, cb)
  })
}

function finishBuild (args, cb) {
  chain(args.map(function (pkg) { return function (cb) {
    chain
      ( [lifecycle, pkg, "install"]
      , [lifecycle, pkg, "postinstall"]
      , [autoActivate, pkg]
      , cb
      )
  }}).concat(args.map(function (pkg) {
    pkg = pkg && pkg._data || pkg
    return [ log, "Success: "+(pkg.name + "@"+pkg.version), "build" ]
  })).concat(cb))
}
<|endoftext|>


<commit_before>/*jshint node: true */

var fs = require('fs'),
    path = require('path'),
    async = require('async'),
    mkdirp = require('mkdirp'),
    css = require('./css'),
    js = require('./js'),
    lint = require('./lint');

module.exports = build;

function build(options, callback) {
    var exampleDir = path.join(process.cwd(), 'example'),
        outputDir = path.join(process.cwd(), 'build'),
        jsOpts = { debug: options.debug };

    lint(options, linted);

    function linted(err) {
        if (err) {
            return callback(err);
        }

        mkdirp(outputDir, createdDir);
    }

    function createdDir(err) {
        if (err) {
            return callback(err);
        }

        async.parallel([
            writeBuild('example.js', jsOpts, js),
            writeBuild('example.css', null, css),
            writeBuild('index.html', null, fs.createReadStream)
        ], callback);
    }

    function writeBuild(file, options, source) {
        var input = path.join(exampleDir, file),
            output = path.join(outputDir, file);

        function build(callback) {
            pipe(
                source(input, options),
                fs.createWriteStream(output),
                callback);
        }

        return function(callback) {
            fs.exists(input, checked);

            function checked(exists) {
                // Skip file if it doesn't exist
                if (!exists) {
                    return callback();
                }

                build(callback);
            }
        };
    }
}

function pipe(input, output, callback) {
    var isDone = false;

    function error(err) {
        if (!isDone) {
            isDone = true;
            output.end();
            callback(err);
        }
    }

    function done() {
        if (!isDone) {
            isDone = true;
            output.end();
            callback();
        }
    }

    input.on('error', error);
    output.on('error', error);
    output.on('finish', done);

    input.pipe(output);
}
<commit_msg>Refactor file building<commit_after>/*jshint node: true */

var fs = require('fs'),
    path = require('path'),
    mkdirp = require('mkdirp'),
    css = require('./css'),
    js = require('./js'),
    lint = require('./lint');

module.exports = build;

function build(options, callback) {
    var exampleDir = path.join(process.cwd(), 'example'),
        outputDir = path.join(process.cwd(), 'build'),
        jsOpts = { debug: options.debug };

    lint(options, linted);

    function linted(err) {
        if (err) {
            return callback(err);
        }

        mkdirp(outputDir, createdDir);
    }

    function createdDir(err) {
        if (err) {
            return callback(err);
        }

        buildFiles(callback);
    }
}

function buildFiles(callback) {
    var counter = 3;

    make('example.js', function(input) { return js(input, jsOpts); });
    make('example.css', css);
    make('index.html', fs.createReadStream);

    function make(name, process) {
        var input = path.join(exampleDir, name),
            output = path.join(outputDir, name);

        fs.exists(input, checked);

        function checked(exists) {
            if (!exists) {
                return done();
            }

            pipe(process(input), fs.createWriteStream(output), done);
        }
    }

    var error;
    function done(err) {
        if (err && !error) {
            error = err;
        }

        if (--counter === 0) {
            callback(error);
        }
    }
}

function pipe(input, output, callback) {
    var isDone = false;

    function error(err) {
        if (!isDone) {
            isDone = true;
            output.end();
            callback(err);
        }
    }

    function done() {
        if (!isDone) {
            isDone = true;
            output.end();
            callback();
        }
    }

    input.on('error', error);
    output.on('error', error);
    output.on('finish', done);

    input.pipe(output);
}
<|endoftext|>


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

var _ = (function () {
  var exports = {};
  exports.isUndefined = function (obj) {
    return typeof obj === 'undefined';
  };
  exports.isString = function (obj) {
    return typeof obj === 'string';
  };
  exports.isArray = function (obj) {
    return obj instanceof Array;
  };
  exports.isFunction = function (obj) {
    return typeof obj === 'function';
  };
  exports.argsToArray = function (args) {
    return Array.prototype.slice.call(args);
  };
  exports.each = function (list, func) {
    var i, len;
    if (exports.isArray(list)) {
      for (i = 0, len = list.length; i < len; i++) {
        func(list[i], i, list);
      }
    } else {
      for (i in list) {
        func(list[i], i, list);
      }
    }
    return list;
  };
  exports.map = function (list, func) {
    var result = exports.isArray(list) ? [] : {};
    exports.each(list, function (val, key, list) {
      result[key] = func(val, key, list);
    });
    return result;
  };
  exports.defaults = function (options, defaults) {
    var result = {};
    exports.each(defaults, function (val, key) {
      result[key] = val;
    });
    exports.each(options, function (val, key) {
      result[key] = val;
    });
    return result;
  };
  return exports;
})();

var isExt = function (filename, ext) {
  if (!_.isString(filename) || !_.isString(ext)) {
    return false;
  }
  ext = ext.slice(0, 1) === '.' ? ext : ('.' + ext);
  return !!(filename && filename.split(ext).pop() === '');
};

var slim = function (store) {
  return _.map(store, function (val) {
    return val.replace(/\n\s*/g, '').replace(/\\n/g, '\n');
  });
};

var Cache = function () {
  this._loaded = false;
  this._basepath = '';
  this._ext = '';
  this._options = {};
  this._store = {};
  return this;
};

Cache.prototype.load = function (basepath, ext, options) {
  options = _.defaults((options = options || {}), {
    slim: false
  });

  var files = (function () {
    var result = [];
    _.each(fs.readdirSync(basepath), function (filename) {
      if (isExt(filename, ext)) {
        result.push(filename);
      }
    });
    return result;
  })();

  var store = (function () {
    var result = {};
    _.each(files, function (filename) {
      result[filename] = fs.readFileSync(path.join(basepath, filename), {encoding: 'utf8'});
    });
    return result;
  })();

  if (options.slim) {
    store = slim(store);
  }

  this._loaded = true;
  this._basepath = basepath;
  this._ext = ext;
  this._options = options;
  this._store = store;

  return this;
};

Cache.prototype.require = function (filename) {
  if (!_.isString(filename)) {
    throw new TypeError('unexpected arguments');
  }

  if (!this._loaded) {
    throw new Error('files not loaded yet');
  }

  filename = isExt(filename, this._ext) ? filename : [filename, this._ext].join('');

  if (!(filename in this._store)) {
    throw new Error('file not found: ' + filename);
  }

  return this._store[filename];
};

var cache = new Cache();

var test = function () {
  var basepath = path.join(process.cwd(), './tpl')
  var ext = '.tpl';
  console.log(cache.load(basepath, ext, {slim: true}));
  console.log(cache._store);
};

(function (env) {
  if (env === 'templateStore:test') {
    test();
  }
})(process.env.NODE_ENV);

module.exports = cache;
<commit_msg>move arg ext into options<commit_after>var fs = require('fs');
var path = require('path');

var _ = (function () {
  var exports = {};
  exports.isUndefined = function (obj) {
    return typeof obj === 'undefined';
  };
  exports.isString = function (obj) {
    return typeof obj === 'string';
  };
  exports.isArray = function (obj) {
    return obj instanceof Array;
  };
  exports.isFunction = function (obj) {
    return typeof obj === 'function';
  };
  exports.argsToArray = function (args) {
    return Array.prototype.slice.call(args);
  };
  exports.each = function (list, func) {
    var i, len;
    if (exports.isArray(list)) {
      for (i = 0, len = list.length; i < len; i++) {
        func(list[i], i, list);
      }
    } else {
      for (i in list) {
        func(list[i], i, list);
      }
    }
    return list;
  };
  exports.map = function (list, func) {
    var result = exports.isArray(list) ? [] : {};
    exports.each(list, function (val, key, list) {
      result[key] = func(val, key, list);
    });
    return result;
  };
  exports.defaults = function (options, defaults) {
    var result = {};
    exports.each(defaults, function (val, key) {
      result[key] = val;
    });
    exports.each(options, function (val, key) {
      result[key] = val;
    });
    return result;
  };
  return exports;
})();

var isExt = function (filename, ext) {
  if (!_.isString(filename) || !_.isString(ext)) {
    return false;
  }
  ext = ext.slice(0, 1) === '.' ? ext : ('.' + ext);
  return !!(filename && filename.split(ext).pop() === '');
};

var joinExt = function (filename, ext) {
  return [filename, ext.slice(0, 1) === '.' ? ext : ('.' + ext)].join('');
};

var slim = function (store) {
  return _.map(store, function (val) {
    return val.replace(/\n\s*/g, '').replace(/\\n/g, '\n');
  });
};

var Cache = function () {
  this._loaded = false;
  this._basepath = '';
  this._options = {};
  this._store = {};
  return this;
};

Cache.prototype.load = function (basepath, options) {
  options = _.defaults((options = options || {}), {
    slim: false,
    ext: '.tpl'
  });

  var files = (function () {
    var result = [];
    _.each(fs.readdirSync(basepath), function (filename) {
      if (isExt(filename, options.ext)) {
        result.push(filename);
      }
    });
    return result;
  })();

  var store = (function () {
    var result = {};
    _.each(files, function (filename) {
      result[filename] = fs.readFileSync(path.join(basepath, filename), {encoding: 'utf8'});
    });
    return result;
  })();

  if (options.slim) {
    store = slim(store);
  }

  this._loaded = true;
  this._basepath = basepath;
  this._options = options;
  this._store = store;

  return this;
};

Cache.prototype.require = function (filename) {
  if (!_.isString(filename)) {
    throw new TypeError('unexpected arguments');
  }

  if (!this._loaded) {
    throw new Error('files not loaded yet');
  }

  filename = isExt(filename, this._options.ext) ? filename : joinExt(filename, this._options.ext);

  if (!(filename in this._store)) {
    throw new Error('file not found: ' + filename);
  }

  return this._store[filename];
};

var cache = new Cache();

var test = function () {
  var basepath = path.join(process.cwd(), './tpl')
  var ext = '.tpl';
  console.log(cache.load(basepath, ext, {slim: true}));
  console.log(cache._store);
};

(function (env) {
  if (env === 'templateStore:test') {
    test();
  }
})(process.env.NODE_ENV);

module.exports = cache;
<|endoftext|>


<commit_before>"use strict";

var Q = require("q");
var fs = require("fs");

module.exports = function Cache(tempPath, log) {
    var that = this;

    var filePath = tempPath + "/cache.json";
    var data = {};

    that.load = function() {

        return Q.nfcall(fs.readFile, filePath)
        .then(function(raw) {
            data = JSON.parse(raw);
        })
        .fail(function() {
            // This failure is recoverable (and even expected in case of a cold cache)
            log.info("Using fresh cache for %s", filePath);
        })
        .then(function() { return that; });
    };

    that.lookup = function(type, key, cacheMissFunction) {
        if (!data[type]) {
            data[type] = {};
        }

        if (data[type][key]) {
            return Q(data[type][key]);
        }

        return Q(cacheMissFunction())
        .then(function(result) {
            // Make sure we're only using serialisable results
            result = JSON.parse(JSON.stringify(result));
            data[type][key] = result;
            return result;
        });
    };

    that.save = function() {
        return Q.nfcall(fs.writeFile, filePath, JSON.stringify(data, null, 4));
    };
};
<commit_msg>Add cache version support<commit_after>"use strict";

var Q = require("q");
var fs = require("fs");

module.exports = function Cache(tempPath, log) {
    var that = this;

    var filePath = tempPath + "/cache.json";
    var data = {};

    that.load = function() {

        return Q.nfcall(fs.readFile, filePath)
        .then(function(raw) {
            data = JSON.parse(raw);
        })
        .fail(function() {
            // This failure is recoverable (and even expected in case of a cold cache)
            log.info("Using fresh cache for %s", filePath);
        })
        .then(function() { return that; });
    };

    that.lookup = function(type, key, cacheMissFunction, version) {
        version = version || 0;

        if (!data[type]) {
            data[type] = {};
        }

        if (data[type][key] && data[type][key].version === version) {
            return Q(data[type][key].data);
        }

        return Q(cacheMissFunction())
        .then(function(result) {
            // Make sure we're only using serialisable results
            result = JSON.parse(JSON.stringify(result));
            data[type][key] = {
                version: version,
                data: result
            };
            return result;
        });
    };

    that.save = function() {
        return Q.nfcall(fs.writeFile, filePath, JSON.stringify(data, null, 4));
    };
};
<|endoftext|>


<commit_before>'use babel';

import fs from 'fs';

export const config = {
  cargoPath: {
    title: 'Path to the Cargo executable',
    type: 'string',
    default: 'cargo',
    order: 1
  },
  verbose: {
    title: 'Verbose Cargo output',
    description: 'Pass the --verbose flag to cargo',
    type: 'boolean',
    default: false,
    order: 2
  },
  openDocs: {
    title: 'Open documentation in browser after \'doc\' target is built',
    type: 'boolean',
    default: false,
    order: 3
  }
};

export function provideBuilder() {
  return class CargoBuildProvider {
    constructor(cwd) {
      this.cwd = cwd;
    }

    getNiceName() {
      return 'Cargo';
    }

    isEligible() {
      return fs.existsSync(`${this.cwd}/Cargo.toml`);
    }

    settings() {
      const cargoPath = atom.config.get('build-cargo.cargoPath');
      const args = [];
      atom.config.get('build-cargo.verbose') && args.push('--verbose');

      const docArgs = [ 'doc' ];
      atom.config.get('build-cargo.openDocs') && docArgs.push('--open');

      return [
        {
          name: 'Cargo: build (debug)',
          exec: cargoPath,
          args: [ 'build' ].concat(args),
          sh: false,
          errorMatch: [
            '(?<file>.+.rs):(?<line>\\d+):(?<col>\\d+):(error):',
            'thread \'[^\\\']+\' panicked at \'[^\\\']+\', (?<file>[^\\/][^\\:]+):(?<line>\\d+)'
          ]
        },
        {
          name: 'Cargo: build (release)',
          exec: cargoPath,
          args: [ 'build', '--release' ].concat(args),
          sh: false,
          errorMatch: [
            '(?<file>.+.rs):(?<line>\\d+):(?<col>\\d+):',
            'thread \'[^\\\']+\' panicked at \'[^\\\']+\', (?<file>[^\\/][^\\:]+):(?<line>\\d+)'
          ]
        },
        {
          name: 'Cargo: bench',
          exec: cargoPath,
          args: [ 'bench' ].concat(args),
          sh: false,
          errorMatch: [
            '(?<file>.+.rs):(?<line>\\d+):(?<col>\\d+):(error):',
            'thread \'[^\\\']+\' panicked at \'[^\\\']+\', (?<file>[^\\/][^\\:]+):(?<line>\\d+)'
          ]
        },
        {
          name: 'Cargo: clean',
          exec: cargoPath,
          args: [ 'clean' ].concat(args),
          sh: false,
          errorMatch: []
        },
        {
          name: 'Cargo: doc',
          exec: cargoPath,
          args: docArgs.concat(args),
          sh: false,
          errorMatch: []
        },
        {
          name: 'Cargo: run',
          exec: cargoPath,
          env: { RUST_BACKTRACE: '1' },
          args: [ 'run' ].concat(args),
          sh: false,
          errorMatch: [
            '(?<file>.+.rs):(?<line>\\d+):(?<col>\\d+):',
            'at (?<file>[^.\/][^\\/][^\\:]+):(?<line>\\d+)',
            'thread \'[^\\\']+\' panicked at \'[^\\\']+\', (?<file>[^\\/][^\\:]+):(?<line>\\d+)'
          ]
        },
        {
          name: 'Cargo: test',
          exec: cargoPath,
          env: { RUST_BACKTRACE: '1' },
          args: [ 'test' ].concat(args),
          sh: false,
          errorMatch: [
            '(?<file>.+.rs):(?<line>\\d+):(?<col>\\d+):',
            'at (?<file>[^.\/][^\\/][^\\:]+):(?<line>\\d+)',
            'thread \'[^\\\']+\' panicked at \'[^\\\']+\', (?<file>[^\\/][^\\:]+):(?<line>\\d+)'
          ]
        },
        {
          name: 'Cargo: update',
          exec: cargoPath,
          args: [ 'update' ].concat(args),
          sh: false,
          errorMatch: []
        }
      ];
    }
  };
}
<commit_msg>Handle error spans<commit_after>'use babel';

import fs from 'fs';

export const config = {
  cargoPath: {
    title: 'Path to the Cargo executable',
    type: 'string',
    default: 'cargo',
    order: 1
  },
  verbose: {
    title: 'Verbose Cargo output',
    description: 'Pass the --verbose flag to cargo',
    type: 'boolean',
    default: false,
    order: 2
  },
  openDocs: {
    title: 'Open documentation in browser after \'doc\' target is built',
    type: 'boolean',
    default: false,
    order: 3
  }
};

export function provideBuilder() {
  return class CargoBuildProvider {
    constructor(cwd) {
      this.cwd = cwd;
    }

    getNiceName() {
      return 'Cargo';
    }

    isEligible() {
      return fs.existsSync(`${this.cwd}/Cargo.toml`);
    }

    settings() {
      const cargoPath = atom.config.get('build-cargo.cargoPath');
      const args = [];
      atom.config.get('build-cargo.verbose') && args.push('--verbose');

      const docArgs = [ 'doc' ];
      atom.config.get('build-cargo.openDocs') && docArgs.push('--open');

      return [
        {
          name: 'Cargo: build (debug)',
          exec: cargoPath,
          args: [ 'build' ].concat(args),
          sh: false,
          errorMatch: [
            '(?<file>.+.rs):(?<line>\\d+):(?<col>\\d+):(?: \\d+:\\d+ )?(error):',
            'thread \'[^\\\']+\' panicked at \'[^\\\']+\', (?<file>[^\\/][^\\:]+):(?<line>\\d+)'
          ]
        },
        {
          name: 'Cargo: build (release)',
          exec: cargoPath,
          args: [ 'build', '--release' ].concat(args),
          sh: false,
          errorMatch: [
            '(?<file>.+.rs):(?<line>\\d+):(?<col>\\d+):',
            'thread \'[^\\\']+\' panicked at \'[^\\\']+\', (?<file>[^\\/][^\\:]+):(?<line>\\d+)'
          ]
        },
        {
          name: 'Cargo: bench',
          exec: cargoPath,
          args: [ 'bench' ].concat(args),
          sh: false,
          errorMatch: [
            '(?<file>.+.rs):(?<line>\\d+):(?<col>\\d+):(error):',
            'thread \'[^\\\']+\' panicked at \'[^\\\']+\', (?<file>[^\\/][^\\:]+):(?<line>\\d+)'
          ]
        },
        {
          name: 'Cargo: clean',
          exec: cargoPath,
          args: [ 'clean' ].concat(args),
          sh: false,
          errorMatch: []
        },
        {
          name: 'Cargo: doc',
          exec: cargoPath,
          args: docArgs.concat(args),
          sh: false,
          errorMatch: []
        },
        {
          name: 'Cargo: run',
          exec: cargoPath,
          env: { RUST_BACKTRACE: '1' },
          args: [ 'run' ].concat(args),
          sh: false,
          errorMatch: [
            '(?<file>.+.rs):(?<line>\\d+):(?<col>\\d+):',
            'at (?<file>[^.\/][^\\/][^\\:]+):(?<line>\\d+)',
            'thread \'[^\\\']+\' panicked at \'[^\\\']+\', (?<file>[^\\/][^\\:]+):(?<line>\\d+)'
          ]
        },
        {
          name: 'Cargo: test',
          exec: cargoPath,
          env: { RUST_BACKTRACE: '1' },
          args: [ 'test' ].concat(args),
          sh: false,
          errorMatch: [
            '(?<file>.+.rs):(?<line>\\d+):(?<col>\\d+):',
            'at (?<file>[^.\/][^\\/][^\\:]+):(?<line>\\d+)',
            'thread \'[^\\\']+\' panicked at \'[^\\\']+\', (?<file>[^\\/][^\\:]+):(?<line>\\d+)'
          ]
        },
        {
          name: 'Cargo: update',
          exec: cargoPath,
          args: [ 'update' ].concat(args),
          sh: false,
          errorMatch: []
        }
      ];
    }
  };
}
<|endoftext|>


<commit_before>
const _        = require('ramda');
const Bluebird = require('bluebird');

// PASS : Nothing
const PASS = _.always(null);

// FAIL : String -> (* -> String)
const FAIL = (msg) => _.always(msg);

const MSG  = {
  REQUIRED           : 'required'
, CANNOT_BE_EQUAL    : 'cannot_be_equal'
, NOT_FUNCTION       : 'not_function'
, NOT_ARRAY          : 'not_array'
, LIST_ITEM_NOT_SPEC : 'list_item_not_spec'
};

// basic : (a -> Bool), String -> (a -> Maybe String)
const basic = (test, msg) => _.ifElse(test, PASS, FAIL(msg));

// extern : (a -> Bool), String -> (a -> Maybe String)
const extern = (test, msg) => _.composeP(
  basic(_.equals(true), msg)
, _.when(_.isNil, _.T)
, _.compose(Bluebird.resolve, test)
);

// required : a -> Maybe String
const required = basic(
  _.compose(_.not, _.either(_.isEmpty, _.isNil))
, MSG.REQUIRED
);
required.always_run = true;

// notEqual : a -> Maybe String
const notEqual = (x) => basic(
  _.compose(_.not, _.equals(x))
, MSG.CANNOT_BE_EQUAL
);

// isArray : a -> Maybe String
const isFunction = basic(_.is(Function), MSG.NOT_FUNCTION);

// isArray : a -> Maybe String
const isArray = basic(_.is(Array), MSG.NOT_ARRAY);

// listOf : (a -> Bool), String -> Array a -> Promise Maybe String
const listOf  = (check, msg) => (list) => {

  const validator = extern(check, msg || MSG.LIST_ITEM_NOT_SPEC);
  const reducer   = (result, item) => result ? result : validator(item);

  return Bluebird.reduce(list, reducer, null);
};

module.exports = {
  MSG
, extern
, required
, notEqual
, isFunction
, isArray
, listOf
};
<commit_msg>add notNullable and immutable check functions for validation<commit_after>
const _        = require('ramda');
const Bluebird = require('bluebird');

// PASS : Nothing
const PASS = _.always(null);

// FAIL : String -> (* -> String)
const FAIL = (msg) => _.always(msg);

const MSG  = {
  REQUIRED           : 'required'
, CANNOT_BE_EQUAL    : 'cannot_be_equal'
, NOT_FUNCTION       : 'not_function'
, NOT_ARRAY          : 'not_array'
, LIST_ITEM_NOT_SPEC : 'list_item_not_spec'
, NOT_NULLABLE       : 'cannot_be_null'
, IMMUTABLE          : 'cannot_change_immutable'
};

// basic : (a -> Bool), String -> (a -> Maybe String)
const basic = (test, msg) => _.ifElse(test, PASS, FAIL(msg));

// extern : (a -> Bool), String -> (a -> Maybe String)
const extern = (test, msg) => _.composeP(
  basic(_.equals(true), msg)
, _.when(_.isNil, _.T)
, _.compose(Bluebird.resolve, test)
);

// required : a -> Maybe String
const required = basic(
  _.compose(_.not, _.either(_.isEmpty, _.isNil))
, MSG.REQUIRED
);
required.always_run = true;

// notEqual : a -> Maybe String
const notEqual = (x) => basic(
  _.compose(_.not, _.equals(x))
, MSG.CANNOT_BE_EQUAL
);

// isFunction : a -> Maybe String
const isFunction = basic(_.is(Function), MSG.NOT_FUNCTION);

// isArray : a -> Maybe String
const isArray = basic(_.is(Array), MSG.NOT_ARRAY);

// listOf : (a -> Bool), String -> Array a -> Promise Maybe String
const listOf  = (check, msg) => (list) => {

  const validator = extern(check, msg || MSG.LIST_ITEM_NOT_SPEC);
  const reducer   = (result, item) => result ? result : validator(item);

  return Bluebird.reduce(list, reducer, null);
};

// notNullable : a -> Maybe String
const notNullable = basic(
  (value, request, current, key) => { return _.all(
    _.compose(_.not, _.equals(null))
    , [ value, _.prop(key, current) ]
    )
  }
  , MSG.NOT_NULLABLE
);

// immutable : a -> Maybe String
const immutable = basic(
  (value, request, current, key) => { return _.propEq(key, value, current) }
  , MSG.IMMUTABLE
);

module.exports = {
  MSG
, extern
, required
, notEqual
, isFunction
, isArray
, listOf
, notNullable
, immutable
};
<|endoftext|>


<commit_before>var path = require('path'),
crypto = require('crypto'),
_ = require('underscore'),
http = require('http');

var banks = {
	"CIC": "https://ssl.paiement.cic-banques.fr",
	"CM" : "https://paiement.creditmutuel.fr",
	"OBC": "https://ssl.paiement.banque-obc.fr"
};

var CMCIC = function() {};

/**
* TPE method
*/

CMCIC.calculateMAC = function(data, key) {
	return crypto.createHmac('sha1', CMCIC.getHashKey(key)).update(data).digest('hex');
};

CMCIC.getHashKey = function(key) {
	var hexStrkey = key.slice(0, 38),
	hexFinal = '' + key.slice(38) + '00',
	cca0 = hexFinal.charCodeAt(0);

	if (cca0  > 70 && cca0 < 97){
		hexStrkey += String.fromCharCode(cca0-23) + hexFinal.charAt(1);
	} else {
		if (hexFinal.charAt(1) == 'M'){
			hexStrkey += hexFinal.charAt(0) + '0';
		} else {
			hexStrkey += hexFinal.slice(0, 2);
		}
	}

	var r = "";
	for (var i = 0; i < hexStrkey.length / 2; i++) {
		var hex = hexStrkey[i*2] + hexStrkey[i*2 + 1];
		hexPack = parseInt(hex, 16);
		r +=  String.fromCharCode(hexPack);
	}
	return r;
};

CMCIC.prototype.tpe = function(config) {
	var tpe = {};
	this.init(config);
};

CMCIC.prototype.tpe.prototype.init = function(config) {
	this.tpe = {
		CMCIC_TPE			: '',
		CMCIC_CODESOCIETE	: '',
		CMCIC_CLE			: '',
		CMCIC_BANK			: 'CIC',
		CMCIC_VERSION		: '3.0',
		CMCIC_LNG			: 'FR',
		CMCIC_CURRENCY		: 'EUR',
		CMCIC_SERVEUR		: 'https://ssl.paiement.cic-banques.fr',
		CMCIC_URL_RETOUR	: "",
		CMCIC_URLOK			: "",
		CMCIC_URLKO			: "",
		test				: false
	};
	this.postOptions = {
			  host: '',
			  path: '',
			  method: 'POST'
	};
	if (config) {
		_.extend(this.tpe, config);
	}
	this.setServer(this.tpe.CMCIC_BANK);
};

CMCIC.prototype.tpe.prototype.configure = function(cmcic) {
	if (cmcic) {
		_.extend(this.tpe, cmcic);
	}
	this.setServer(this.tpe.CMCIC_BANK);
};

CMCIC.prototype.tpe.prototype.setServer = function(bankName) {
	var server = banks[bankName];
	this.postOptions.host = server.replace('https://', '');
	if (this.tpe.test) {
		server += "/test";
		this.postOptions.path = '/test/paiement.cgi';
	}
	if (!this.tpe.test) {
		this.postOptions.path = '/paiement.cgi';
	}
	server += "/paiement.cgi";
	this.tpe.CMCIC_SERVEUR = server;
};

CMCIC.prototype.tpe.prototype.checkTransactionReturn = function(transactionData) {
	if (!transactionData.motifrefus) {
		transactionData.motifrefus = '';
	}
	var data =  transactionData.TPE
		+ '*' + transactionData.date
		+ '*' + transactionData.montant
		+ '*' + transactionData.reference
		+ '*' + transactionData['texte-libre']
		+ '*' + this.tpe.CMCIC_VERSION
		+ '*' + transactionData['code-retour']
		+ '*' + transactionData.cvx
		+ '*' + transactionData.vld
		+ '*' + transactionData.brand
		+ '*' + transactionData.status3ds
		+ '*' + transactionData.numauto
		+ '*' + transactionData.motifrefus
		+ '*' + transactionData.originecb
		+ '*' + transactionData.bincb
		+ '*' + transactionData.hpancb
		+ '*' + transactionData.ipclient
		+ '*' + transactionData.originetr
		+ '*' + transactionData.veres
		+ '*' + transactionData.pares
		+ '*';
	var mac = CMCIC.calculateMAC(data, this.tpe.CMCIC_CLE);
	if (mac.toUpperCase() === transactionData.MAC.toUpperCase() && (transactionData['code-retour'] === 'paiement' ||  transactionData['code-retour'] === 'payetest')) {
		return {
			status: true,
			date: transactionData.date,
			TPE : transactionData.TPE,
			montant: transactionData.montant,
			reference:transactionData.reference,
			'texte-libre': JSON.parse(new Buffer(transactionData['texte-libre'], 'base64').toString('ascii')),
			'code-retour': transactionData['code-retour'],
			cvx: transactionData.cvx,
			vld: transactionData.vld,
			brand: transactionData.brand,
			status3ds: transactionData.status3ds,
			numauto: transactionData.numauto,
			originecb: transactionData.originecb,
			bincb: transactionData.bincb,
			hpancb: transactionData.hpancb,
			ipclient: transactionData.ipclient,
			oririnetr: transactionData.originetr,
			veres: transactionData.veres,
			pares: transactionData.pares,
			montantech: transactionData.montantech,
			cbenregistree: transactionData.cbenregistree,
			cbmasquee: transactionData.cbmasquee
		};
	} else {
		return {
			status: false,
			date: transactionData.date,
			TPE : transactionData.TPE,
			montant: transactionData.montant,
			reference: transactionData.reference,
			'texte-libre': JSON.parse(new Buffer(transactionData['texte-libre'], 'base64').toString('ascii')),
			'code-retour': transactionData['code-retour'],
			cvx: transactionData.cvx,
			vld: transactionData.vld,
			brand: transactionData.brand,
			status3ds: transactionData.status3ds,
			numauto: transactionData.numauto,
			motifrefus: transactionData.motifrefus,
			originecb: transactionData.originecb,
			bincb: transactionData.bincb,
			hpancb: transactionData.hpancb,
			ipclient: transactionData.ipclient,
			oririnetr: transactionData.originetr,
			veres: transactionData.veres,
			pares: transactionData.pares,
			montantech: transactionData.montantech,
			filtragecause: transactionData.filtragecause,
			filtragevaleur: transactionData.filtragevaleur,
			cbenregistree: transactionData.cbenregistree,
			cbmasquee: transactionData.cbmasquee
		};
	}
};

/**
* Transation method
*/

CMCIC.prototype.transaction = function (tpe, transactionData) {
	this.tpe = tpe;
	this.data = {};

	this.init(transactionData);
};

CMCIC.prototype.transaction.prototype.init = function (transactionData) {
	this.data = {
		date				: "",
		amount				: "",
		reference			: "",
		texteLibre			: {},
		email				: "",
		NbrEch				: "",
		DateEcheance1		: "",
		MontantEcheance1	: "",
		DateEcheance2		: "",
		MontantEcheance2	: "",
		DateEcheance3		: "",
		MontantEcheance3	: "",
		DateEcheance4		: "",
		MontantEcheance4	: "",
		options				: ""
	};
	_.extend(this.data, transactionData);
};

CMCIC.prototype.transaction.prototype.dataToSend = function(data) {
	if (!data) {
		data = this.data;
	}
	return this.tpe.tpe.CMCIC_TPE+
		'*' + data.date+
		'*' + data.amount + this.tpe.tpe.CMCIC_CURRENCY+
		'*' + data.reference+
		'*' + data.texteLibre+
		'*' + this.tpe.tpe.CMCIC_VERSION+
		'*' + this.tpe.tpe.CMCIC_LNG+
		'*' + this.tpe.tpe.CMCIC_CODESOCIETE+
		'*' + data.email+
		'*' + data.NbrEch+
		'*' + data.DateEcheance1+
		'*' + data.MontantEcheance1+
		'*' + data.DateEcheance2+
		'*' + data.MontantEcheance2+
		'*' + data.DateEcheance3+
		'*' + data.MontantEcheance3+
		'*' + data.DateEcheance4+
		'*' + data.MontantEcheance4+
		'*' + data.options;
};

CMCIC.prototype.transaction.prototype.getDate = function() {
	var d = new Date();

	var day = (d.getDate() < 10) ? '0' + d.getDate() : d.getDate();
	var month = ( (d.getMonth() + 1) < 10) ? '0'+(d.getMonth()+1) : d.getMonth()+1;
	var year = d.getFullYear();
	var hour = (d.getHours() < 10) ? '0' + d.getHours() : d.getHours();
	var minute = (d.getMinutes() < 10) ? '0' + d.getMinutes() : d.getMinutes();
	var second = (d.getSeconds() < 10) ? '0' + d.getSeconds() : d.getSeconds();
	if (this.data.date === '') {
		this.data.date = day + "/" + month + "/" + year + ":" + hour + ":" + minute + ":" + second;
	}
};

CMCIC.prototype.transaction.prototype.form = function(id, autosubmit) {
	this.getDate();
	this.data.texteLibre = new Buffer(JSON.stringify(this.data.texteLibre)).toString('base64');
	var mac = CMCIC.calculateMAC(this.dataToSend(), this.tpe.tpe.CMCIC_CLE),
	result = '<form method="post" id="'+id+'" action='+this.tpe.tpe.CMCIC_SERVEUR+'>'+
		'<input type="hidden" name="version" value="'+this.tpe.tpe.CMCIC_VERSION+'">'+
		'<input type="hidden" name="TPE" value="'+this.tpe.tpe.CMCIC_TPE+'">'+
		'<input type="hidden" name="MAC" value="'+mac+'">'+
		'<input type="hidden" name="url_retour" value="'+this.tpe.tpe.CMCIC_URL_RETOUR+'">'+
		'<input type="hidden" name="url_retour_ok" value="'+this.tpe.tpe.CMCIC_URLOK+'">'+
		'<input type="hidden" name="url_retour_err" value="'+this.tpe.tpe.CMCIC_URLKO+'">'+
		'<input type="hidden" name="lgue" value="'+this.tpe.tpe.CMCIC_LNG+'">'+
		'<input type="hidden" name="societe" value="'+this.tpe.tpe.CMCIC_CODESOCIETE+'">'+
		'<input type="hidden" name="date" value="'+this.data.date+'">'+
		'<input type="hidden" name="montant" value="'+this.data.amount+this.tpe.tpe.CMCIC_CURRENCY+'">'+
		'<input type="hidden" name="reference" value="'+this.data.reference+'">'+
		'<input type="hidden" name="mail" value="'+this.data.email+'">'+
		'<input type="hidden" name="texte-libre" value="'+this.data.texteLibre+'">'+
		'
'+
		'<input type="submit" name="bouton" value="">'+
		'
</form>';
	if (autosubmit === true) {
		result += '';
	}
	return result;
};

module.exports = new CMCIC();
<commit_msg>default value for 'numauto'<commit_after>var crypto = require('crypto'),
_ = require('underscore');

var banks = {
	"CIC": "https://ssl.paiement.cic-banques.fr",
	"CM" : "https://paiement.creditmutuel.fr",
	"OBC": "https://ssl.paiement.banque-obc.fr"
};

var CMCIC = function() {};

CMCIC.calculateMAC = function(data, key) {
	return crypto.createHmac('sha1', CMCIC.getHashKey(key)).update(data).digest('hex');
};

CMCIC.getHashKey = function(key) {
	var hexStrkey = key.slice(0, 38),
	hexFinal = '' + key.slice(38) + '00',
	cca0 = hexFinal.charCodeAt(0);

	if (cca0  > 70 && cca0 < 97){
		hexStrkey += String.fromCharCode(cca0-23) + hexFinal.charAt(1);
	} else {
		if (hexFinal.charAt(1) == 'M'){
			hexStrkey += hexFinal.charAt(0) + '0';
		} else {
			hexStrkey += hexFinal.slice(0, 2);
		}
	}

	var r = "";
	for (var i = 0; i < hexStrkey.length / 2; i++) {
		var hex = hexStrkey[i*2] + hexStrkey[i*2 + 1];
		hexPack = parseInt(hex, 16);
		r +=  String.fromCharCode(hexPack);
	}
	return r;
};

/**
* TPE method
*/

CMCIC.prototype.tpe = function(config) {
	var tpe = {};
	this.init(config);
};

CMCIC.prototype.tpe.prototype.init = function(config) {
	this.tpe = {
		CMCIC_TPE			: '',
		CMCIC_CODESOCIETE	: '',
		CMCIC_CLE			: '',
		CMCIC_BANK			: 'CIC',
		CMCIC_VERSION		: '3.0',
		CMCIC_LNG			: 'FR',
		CMCIC_CURRENCY		: 'EUR',
		CMCIC_SERVEUR		: 'https://ssl.paiement.cic-banques.fr',
		CMCIC_URL_RETOUR	: "",
		CMCIC_URLOK			: "",
		CMCIC_URLKO			: "",
		test				: false
	};
	this.postOptions = {
			  host: '',
			  path: '',
			  method: 'POST'
	};
	if (config) {
		_.extend(this.tpe, config);
	}
	this.setServer(this.tpe.CMCIC_BANK);
};

CMCIC.prototype.tpe.prototype.configure = function(cmcic) {
	if (cmcic) {
		_.extend(this.tpe, cmcic);
	}
	this.setServer(this.tpe.CMCIC_BANK);
};

CMCIC.prototype.tpe.prototype.setServer = function(bankName) {
	var server = banks[bankName];
	this.postOptions.host = server.replace('https://', '');
	if (this.tpe.test) {
		server += "/test";
		this.postOptions.path = '/test/paiement.cgi';
	}
	if (!this.tpe.test) {
		this.postOptions.path = '/paiement.cgi';
	}
	server += "/paiement.cgi";
	this.tpe.CMCIC_SERVEUR = server;
};

CMCIC.prototype.tpe.prototype.checkTransactionReturn = function(transactionData) {
	if (!transactionData.motifrefus) {
		transactionData.motifrefus = '';
	}
	var data =  transactionData.TPE +
		'*' + transactionData.date +
		'*' + transactionData.montant +
		'*' + transactionData.reference +
		'*' + transactionData['texte-libre'] +
		'*' + this.tpe.CMCIC_VERSION +
		'*' + transactionData['code-retour'] +
		'*' + transactionData.cvx +
		'*' + transactionData.vld +
		'*' + transactionData.brand +
		'*' + transactionData.status3ds +
		'*' + (transactionData.numauto || '') +
		'*' + transactionData.motifrefus +
		'*' + transactionData.originecb +
		'*' + transactionData.bincb +
		'*' + transactionData.hpancb +
		'*' + transactionData.ipclient +
		'*' + transactionData.originetr +
		'*' + transactionData.veres +
		'*' + transactionData.pares +
		'*';
	var mac = CMCIC.calculateMAC(data, this.tpe.CMCIC_CLE);
	if (mac.toUpperCase() === transactionData.MAC.toUpperCase() && (transactionData['code-retour'] === 'paiement' ||  transactionData['code-retour'] === 'payetest')) {
		return {
			'status': true,
			'date': transactionData.date,
			'TPE' : transactionData.TPE,
			'montant': transactionData.montant,
			'reference': transactionData.reference,
			'texte-libre': JSON.parse(new Buffer(transactionData['texte-libre'], 'base64').toString('ascii')),
			'code-retour': transactionData['code-retour'],
			'cvx': transactionData.cvx,
			'vld': transactionData.vld,
			'brand': transactionData.brand,
			'status3ds': transactionData.status3ds,
			'numauto': transactionData.numauto,
			'originecb': transactionData.originecb,
			'bincb': transactionData.bincb,
			'hpancb': transactionData.hpancb,
			'ipclient': transactionData.ipclient,
			'oririnetr': transactionData.originetr,
			'veres': transactionData.veres,
			'pares': transactionData.pares,
			'montantech': transactionData.montantech,
			'cbenregistree': transactionData.cbenregistree,
			'cbmasquee': transactionData.cbmasquee
		};
	} else {
		return {
			'status': false,
			'date': transactionData.date,
			'TPE' : transactionData.TPE,
			'montant': transactionData.montant,
			'reference': transactionData.reference,
			'texte-libre': JSON.parse(new Buffer(transactionData['texte-libre'], 'base64').toString('ascii')),
			'code-retour': transactionData['code-retour'],
			'cvx': transactionData.cvx,
			'vld': transactionData.vld,
			'brand': transactionData.brand,
			'status3ds': transactionData.status3ds,
			'numauto': transactionData.numauto,
			'motifrefus': transactionData.motifrefus,
			'originecb': transactionData.originecb,
			'bincb': transactionData.bincb,
			'hpancb': transactionData.hpancb,
			'ipclient': transactionData.ipclient,
			'oririnetr': transactionData.originetr,
			'veres': transactionData.veres,
			'pares': transactionData.pares,
			'montantech': transactionData.montantech,
			'filtragecause': transactionData.filtragecause,
			'filtragevaleur': transactionData.filtragevaleur,
			'cbenregistree': transactionData.cbenregistree,
			'cbmasquee': transactionData.cbmasquee
		};
	}
};

/**
* Transation method
*/

CMCIC.prototype.transaction = function (tpe, transactionData) {
	this.tpe = tpe;
	this.data = {};

	this.init(transactionData);
};

CMCIC.prototype.transaction.prototype.init = function (transactionData) {
	this.data = {
		date				: "",
		amount				: "",
		reference			: "",
		texteLibre			: {},
		email				: "",
		NbrEch				: "",
		DateEcheance1		: "",
		MontantEcheance1	: "",
		DateEcheance2		: "",
		MontantEcheance2	: "",
		DateEcheance3		: "",
		MontantEcheance3	: "",
		DateEcheance4		: "",
		MontantEcheance4	: "",
		options				: ""
	};
	_.extend(this.data, transactionData);
};

CMCIC.prototype.transaction.prototype.dataToSend = function(data) {
	if (!data) {
		data = this.data;
	}
	return this.tpe.tpe.CMCIC_TPE+
		'*' + data.date+
		'*' + data.amount + this.tpe.tpe.CMCIC_CURRENCY+
		'*' + data.reference+
		'*' + data.texteLibre+
		'*' + this.tpe.tpe.CMCIC_VERSION+
		'*' + this.tpe.tpe.CMCIC_LNG+
		'*' + this.tpe.tpe.CMCIC_CODESOCIETE+
		'*' + data.email+
		'*' + data.NbrEch+
		'*' + data.DateEcheance1+
		'*' + data.MontantEcheance1+
		'*' + data.DateEcheance2+
		'*' + data.MontantEcheance2+
		'*' + data.DateEcheance3+
		'*' + data.MontantEcheance3+
		'*' + data.DateEcheance4+
		'*' + data.MontantEcheance4+
		'*' + data.options;
};

CMCIC.prototype.transaction.prototype.getDate = function() {
	var d = new Date();

	var day = (d.getDate() < 10) ? '0' + d.getDate() : d.getDate();
	var month = ( (d.getMonth() + 1) < 10) ? '0'+(d.getMonth()+1) : d.getMonth()+1;
	var year = d.getFullYear();
	var hour = (d.getHours() < 10) ? '0' + d.getHours() : d.getHours();
	var minute = (d.getMinutes() < 10) ? '0' + d.getMinutes() : d.getMinutes();
	var second = (d.getSeconds() < 10) ? '0' + d.getSeconds() : d.getSeconds();
	if (this.data.date === '') {
		this.data.date = day + "/" + month + "/" + year + ":" + hour + ":" + minute + ":" + second;
	}
};

CMCIC.prototype.transaction.prototype.form = function(id, autosubmit) {
	this.getDate();
	this.data.texteLibre = new Buffer(JSON.stringify(this.data.texteLibre)).toString('base64');
	var mac = CMCIC.calculateMAC(this.dataToSend(), this.tpe.tpe.CMCIC_CLE),
	result = '<form method="post" id="'+id+'" action='+this.tpe.tpe.CMCIC_SERVEUR+'>'+
		'<input type="hidden" name="version" value="'+this.tpe.tpe.CMCIC_VERSION+'">'+
		'<input type="hidden" name="TPE" value="'+this.tpe.tpe.CMCIC_TPE+'">'+
		'<input type="hidden" name="MAC" value="'+mac+'">'+
		'<input type="hidden" name="url_retour" value="'+this.tpe.tpe.CMCIC_URL_RETOUR+'">'+
		'<input type="hidden" name="url_retour_ok" value="'+this.tpe.tpe.CMCIC_URLOK+'">'+
		'<input type="hidden" name="url_retour_err" value="'+this.tpe.tpe.CMCIC_URLKO+'">'+
		'<input type="hidden" name="lgue" value="'+this.tpe.tpe.CMCIC_LNG+'">'+
		'<input type="hidden" name="societe" value="'+this.tpe.tpe.CMCIC_CODESOCIETE+'">'+
		'<input type="hidden" name="date" value="'+this.data.date+'">'+
		'<input type="hidden" name="montant" value="'+this.data.amount+this.tpe.tpe.CMCIC_CURRENCY+'">'+
		'<input type="hidden" name="reference" value="'+this.data.reference+'">'+
		'<input type="hidden" name="mail" value="'+this.data.email+'">'+
		'<input type="hidden" name="texte-libre" value="'+this.data.texteLibre+'">'+
		'
'+
		'<input type="submit" name="bouton" value="">'+
		'
</form>';
	if (autosubmit === true) {
		result += '';
	}
	return result;
};

module.exports = new CMCIC();
<|endoftext|>


<commit_before>var Promise = require('bluebird'),
    _ = require('lodash'),
    findByTagName = require('../findBy/tagname'),
    findByUI = require('../findBy/ui'),
    findByManifest = require('../findBy/manifest'),
    findByListing = require('../findBy/listing'),
    findByCode = require('../findBy/code'),
    mongoConnection = require('../db/connection')

function DB() {
}

DB.prototype.init = function () {
    this.env = {}
    var self = this
    return Promise.join(
        findByTagName.init(this.env),
        findByUI.init(this.env),
        findByListing.init(this.env),
        findByManifest.init(this.env),
        findByCode.init(this.env),
        mongoConnection
    ).then(function (results) {
            self.mongo = results[5]
            return self
        })
        .error(function (e) {
            console.error('Failed to initialize the database. Reason: ' + e.message)
        })
}

function _apply_projection(env, results, projection) {

    // e.g.,
    // projection = {id: true, packageName: true}

    return results.map(function (id) {
        var app = env.apps.get(id, projection)
        return app
    })
}

DB.prototype.find = function (query) {

    var mongo = this.mongo
    var env = this.env
    var options = {
        limit: query.limit,
        scope: _.range(0, 60)
    }
    return findByListing.find(env, query.listing, mongo, options)
        .then(function (results) {
            options.scope = results
            return findByManifest.find(env, query.manifest, options)
        })
        .then(function (results) {
            options.scope = results
            return findByCode.find(env, query.code, options)
        })
        .then(function (results) {
            options.scope = results
            return findByTagName.find(env, query.ui, options);
        })
        .then(function (results) {
            options.scope = results
            return findByUI.find(env, query.ui, options)
        })
        .then(function (results) {
            return _apply_projection(env, results, options.projection)
        })
        .catch(function (e) {
            console.error(e)
        });
}

module.exports = DB<commit_msg>initialize scope<commit_after>var Promise = require('bluebird'),
    _ = require('lodash'),
    findByTagName = require('../findBy/tagname'),
    findByUI = require('../findBy/ui'),
    findByManifest = require('../findBy/manifest'),
    findByListing = require('../findBy/listing'),
    findByCode = require('../findBy/code'),
    mongoConnection = require('../db/connection')

function DB() {
}

DB.prototype.init = function () {
    this.env = {}
    var self = this
    return Promise.join(
        findByTagName.init(this.env),
        findByUI.init(this.env),
        findByListing.init(this.env),
        findByManifest.init(this.env),
        findByCode.init(this.env),
        mongoConnection
    ).then(function (results) {
            self.mongo = results[5]
            return self
        })
        .error(function (e) {
            console.error('Failed to initialize the database. Reason: ' + e.message)
        })
}

function _apply_projection(env, results, projection) {

    // e.g.,
    // projection = {id: true, packageName: true}

    return results.map(function (id) {
        var app = env.apps.get(id, projection)
        return app
    })
}

DB.prototype.find = function (query) {

    var mongo = this.mongo
    var env = this.env
    var options = {
        limit: query.limit,
        scope: undefined
    }
    return findByListing.find(env, query.listing, mongo, options)
        .then(function (results) {
            options.scope = results
            return findByManifest.find(env, query.manifest, options)
        })
        .then(function (results) {
            options.scope = results
            return findByCode.find(env, query.code, options)
        })
        .then(function (results) {
            options.scope = results
            return findByTagName.find(env, query.ui, options);
        })
        .then(function (results) {
            options.scope = results
            return findByUI.find(env, query.ui, options)
        })
        .then(function (results) {
            return _apply_projection(env, results, options.projection)
        })
        .catch(function (e) {
            console.error(e)
        });
}

module.exports = DB<|endoftext|>


<commit_before>
/*!
 * debug
 * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Expose `debug()` as the module.
 */

module.exports = debug;

/**
 * Library version.
 */

exports.version = '0.0.1';

/**
 * Enabled debuggers.
 */

var names = (process.env.DEBUG || '').split(/[\s,]+/);

/**
 * Colors.
 */

var colors = [6, 2, 3, 4, 5, 1];

/**
 * Previously assigned color.
 */

var prevColor = 0;

/**
 * Is stderr a TTY? Colored output is disabled when `true`.
 */

var isTTY = 'isTTY' in process.stderr
          ? process.stderr.isTTY
          : process.binding('stdio').isatty(process.stderr.fd || 2)

/**
 * Select a color.
 *
 * @return {Number}
 * @api private
 */

function color() {
  return colors[prevColor++ % colors.length];
}

/**
 * Create a debugger with the given `name`.
 *
 * @param {String} name
 * @return {Type}
 * @api public
 */

function debug(name) {
  if (!~names.indexOf(name)) return function(){};
  var c = color();
  return isTTY ?
  function(fmt){
    fmt = '  \033[3' + c + 'm' + name + '\033[90m ' + fmt + '\033[0m';
    console.error.apply(this, arguments);
  } :
  function(fmt){
    fmt = '  ' + name + ' ' + fmt;
    console.error.apply(this, arguments);
  }
}
<commit_msg>tweak previous commit<commit_after>
/*!
 * debug
 * Copyright(c) 2011 TJ Holowaychuk <tj@vision-media.ca>
 * MIT Licensed
 */

/**
 * Expose `debug()` as the module.
 */

module.exports = debug;

/**
 * Library version.
 */

exports.version = '0.0.1';

/**
 * Enabled debuggers.
 */

var names = (process.env.DEBUG || '').split(/[\s,]+/);

/**
 * Colors.
 */

var colors = [6, 2, 3, 4, 5, 1];

/**
 * Previously assigned color.
 */

var prevColor = 0;

/**
 * Is stderr a TTY? Colored output is disabled when `true`.
 */

var isatty = require('tty').isatty(process.stderr.fd || 2);

/**
 * Select a color.
 *
 * @return {Number}
 * @api private
 */

function color() {
  return colors[prevColor++ % colors.length];
}

/**
 * Create a debugger with the given `name`.
 *
 * @param {String} name
 * @return {Type}
 * @api public
 */

function debug(name) {
  if (!~names.indexOf(name)) return function(){};
  var c = color();
  return isatty ?
  function(fmt){
    fmt = '  \033[3' + c + 'm' + name + '\033[90m ' + fmt + '\033[0m';
    console.error.apply(this, arguments);
  } :
  function(fmt){
    fmt = '  ' + name + ' ' + fmt;
    console.error.apply(this, arguments);
  }
}
<|endoftext|>


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

function getFile(fullPath) {
  return function(fn){
    fs.stat(fullPath, function(err, stats){
      if (err) return fn(err);
      fn(null, {"name": path.basename(fullPath), "path":fullPath, "type": ((stats.isDirectory()) ? 'directory': 'file'), "stats": stats});
    });
  };
}

function getDirectory(fullPath) {
  return function(fn){
    fs.readdir(fullPath, function(err, files){
      if (err) return fn(err);
      fn(null, {"directory":fullPath, "files": files});
    });
  };
}

function *file(fullPath){
  return yield getFile(fullPath);
}

function *directory(fullPath){
  return yield getDirectory(fullPath);
}

function testFilter(str, filters) {
  var i;
  if(filters) {
    try {
      filters = (typeof filters === 'string') ? filters.split(',') : filters;
      for (i=0; i<filters.length; i++) {
        if (str.match(filters[i])){
          return true;
        }
      }
      return false;
    } catch(e) {
      return false;
    }
  } else {
    return true;
  }
}

function *get(rootPath, options, level) {
  //parameter level is for internal use only!
  options = options || { };
  options.depth = (typeof options.depth !== 'undefined') ? options.depth : -1;
  options.stats = (typeof options.stats !== 'undefined') ? options.stats : true;
  options.flat = (typeof options.flat !== 'undefined') ? options.flat : false;
  options.filters = (typeof options.filters !== 'undefined') ? options.filters : false; //Flters make more sense with flat option ist true
  level = level || 0;

  var fsNode = yield file(rootPath)
  , currentDir
  , dirItem
  , fullPath
  , files = []
  , tmp
  , stats = {}
  , children
  , i;

  if ( fsNode.stats.isDirectory() ) {
    currentDir = yield directory(rootPath);
    for (i=0; i<currentDir.files.length; i++) {
      dirItem = {};
      children = null;
      stats = {};
      children = [];
      fullPath = path.join(currentDir.directory, currentDir.files[i]);
      dirItem = yield file(fullPath);
      if(dirItem.stats.isDirectory() && (options.depth === -1 || options.depth >= level)) {
        children = yield get( dirItem.path , options, level+1);
        if(options.flat) {
          files = files.concat(children)
        } else {
          dirItem.children = children;
        }
      }
       if (options.stats !== true){
        if (typeof options.stats === 'string'){
          stats[options.stats] = dirItem.stats[options.stats];
          dirItem.stats = stats;
        } else {
          delete dirItem.stats;
        }
      }
      if(testFilter(dirItem.name, options.filters)) {
        files.push(dirItem);
      }
    }
  }
  return yield files;
}

var dirco = function(rootPath, options, cb) {
  cb = (typeof cb !== 'undefined') ? cb : options;
  options = (cb !== options) ? options : {};
  co(function *(){
    var result = yield get(rootPath, options);
    cb(null,result);
  })();
};

module.exports = dirco;
<commit_msg>jshint options added<commit_after>/*jshint laxcomma: true, node: true, indent: 4, esnext: true*/
var fs = require('fs')
, co = require('co')
, path = require('path')
;

function getFile(fullPath) {
  return function(fn){
    fs.stat(fullPath, function(err, stats){
      if (err) return fn(err);
      fn(null, {"name": path.basename(fullPath), "path":fullPath, "type": ((stats.isDirectory()) ? 'directory': 'file'), "stats": stats});
    });
  };
}

function getDirectory(fullPath) {
  return function(fn){
    fs.readdir(fullPath, function(err, files){
      if (err) return fn(err);
      fn(null, {"directory":fullPath, "files": files});
    });
  };
}

function *file(fullPath){
  return yield getFile(fullPath);
}

function *directory(fullPath){
  return yield getDirectory(fullPath);
}

function testFilter(str, filters) {
  var i;
  if(filters) {
    try {
      filters = (typeof filters === 'string') ? filters.split(',') : filters;
      for (i=0; i<filters.length; i++) {
        if (str.match(filters[i])){
          return true;
        }
      }
      return false;
    } catch(e) {
      return false;
    }
  } else {
    return true;
  }
}

function *get(rootPath, options, level) {
  //parameter level is for internal use only!
  options = options || { };
  options.depth = (typeof options.depth !== 'undefined') ? options.depth : -1;
  options.stats = (typeof options.stats !== 'undefined') ? options.stats : true;
  options.flat = (typeof options.flat !== 'undefined') ? options.flat : false;
  options.filters = (typeof options.filters !== 'undefined') ? options.filters : false; //Flters make more sense with flat option ist true
  level = level || 0;

  var fsNode = yield file(rootPath)
  , currentDir
  , dirItem
  , fullPath
  , files = []
  , tmp
  , stats = {}
  , children
  , i;

  if ( fsNode.stats.isDirectory() ) {
    currentDir = yield directory(rootPath);
    for (i=0; i<currentDir.files.length; i++) {
      dirItem = {};
      children = null;
      stats = {};
      children = [];
      fullPath = path.join(currentDir.directory, currentDir.files[i]);
      dirItem = yield file(fullPath);
      if(dirItem.stats.isDirectory() && (options.depth === -1 || options.depth >= level)) {
        children = yield get( dirItem.path , options, level+1);
        if(options.flat) {
          files = files.concat(children);
        } else {
          dirItem.children = children;
        }
      }
       if (options.stats !== true){
        if (typeof options.stats === 'string'){
          stats[options.stats] = dirItem.stats[options.stats];
          dirItem.stats = stats;
        } else {
          delete dirItem.stats;
        }
      }
      if(testFilter(dirItem.name, options.filters)) {
        files.push(dirItem);
      }
    }
  }
  return yield files;
}

var dirco = function(rootPath, options, cb) {
  cb = (typeof cb !== 'undefined') ? cb : options;
  options = (cb !== options) ? options : {};
  co(function *(){
    var result = yield get(rootPath, options);
    cb(null,result);
  })();
};

module.exports = dirco;
<|endoftext|>


<commit_before>var
  dirty = exports,
  sys = require('sys'),
  events = require('events'),
  fs = require('fs');

dirty.uuid = function() {
  var uuid = '', i;
  for (i = 0; i < 32; i++) {
    uuid += Math.floor(Math.random() * 16).toString(16);
  }
  return uuid;
};

var Dirty = dirty.Dirty = function(filePath, options) {
  process.EventEmitter.call(this);

  options = process.mixin({
    flushInterval: 10,
    flushLimit: 1000,
  }, options || {});

  var
    self = this,
    docs = {},
    log = [],
    loading = false,
    flushing = false,
    readStream = fs.createReadStream(filePath),
    writeStream = fs.createWriteStream(filePath, {flags: 'a+'}),
    readBuffer = '',
    timer;

  readStream
    .addListener('error', function(err) {
      // No such file or directory
      if (err.errno == 2) {
        self.emit('load');
        return;
      }
      self.emit('error', err);
    })
    .addListener('data', function(chunk) {
      var
        offset,
        chunk,
        doc;

      readBuffer += chunk;

      while ((offset = readBuffer.indexOf("\n")) > -1) {
        chunk = readBuffer.substr(0, offset);
        readBuffer = readBuffer.substr(offset+1);

        try {
          doc = JSON.parse(chunk);
        } catch (e) {
          continue;
        }

        if (doc.deleted) {
          delete docs[doc.id];
        } else {
          docs[doc.id] = doc.value;
        }
      }
    })
    .addListener('end', function() {
      self.emit('load');
    });

  writeStream
    .addListener('drain', function() {
      if (!log.length) {
        self.emit('drain');
      }
    })
    .addListener('error', function(err) {
      self.emit('error', err);
    });

  this.add = function(doc, cb) {
    var id = dirty.uuid();
    this.set(id, doc, cb);
    return id;
  };

  this.set = function(id, doc, cb) {
    if (doc !== undefined) {
      docs[id] = doc;
    } else {
      delete docs[id];
    }

    log.push(!cb ? id : [id, cb]);

    if (loading === true) {
      // Do not flush while loading
    } else if (options.flushLimit && !flushing && log.length >= options.flushLimit) {
      this.flush();
      if (timer) {
        clearTimeout(timer);
      }
    } else if (options.flushInterval && !flushing && !timer) {
      timer = setTimeout(function() {
        self.flush();
        timer = null;
      }, options.flushInterval);
    }
  };

  this.get = function(id) {
    return docs[id];
  };

  this.remove = function(id, cb) {
    this.set(id, undefined, cb);
  };

  this.flush = function(flushCb) {
    flushing = true;

    var
      chunkCallbacks = [],
      chunk = '',
      id;

    while (true) {
      id = log.shift();
      if (id === undefined) {
        break;
      }

      if (id instanceof Array) {
        chunkCallbacks.push(id[1]);
        id = id[0];
      }

      if (id in docs) {
        chunk += JSON.stringify({id: id, value: docs[id]})+"\n";
      } else {
        chunk += JSON.stringify({id: id, deleted: true})+"\n";
      }

      if (chunk.length < 16 * 1024 && log.length) {
        continue;
      }

      writeStream.write(chunk, function(err) {
        chunkCallbacks.forEach(function(cb) {
          cb(err);
        });
        callbacks = [];

        if (err) {
          if (flushCb) {
            flushCb(err);
          }
          self.emit('error', err);
        }

        flushing = false;

        if (log.length) {
          self.flush();
        } else if (flushCb) {
          cb(null);
        }
      });
    }
  };
};
sys.inherits(Dirty, events.EventEmitter);

// Dirty.prototype.load = function() {
//   var
//     self = this,
//     promise = new process.Promise(),
//     buffer = '',
//     offset = 0,
//     read = function() {
//       self.file.read(16*1024).addCallback(function(chunk) {
//         if (!chunk) {
//           return promise.emitSuccess();
//         }
//
//         buffer += chunk;
//         while ((offset = buffer.indexOf("\n")) !== -1) {
//           var doc = JSON.parse(buffer.substr(0, offset));
//           if (!(doc._id in self._ids) && !doc._deleted) {
//             self.length++;
//           }
//           if (doc._deleted) {
//             if (doc._id in self._ids) {
//               self._docs.splice(self._ids[doc._id], 1);
//               delete self._ids[doc._id];
//             }
//           } else {
//             self._ids[doc._id] = (self._docs.push(doc)-1);
//           }
//           buffer = buffer.substr(offset+1);
//         }
//         read();
//       })
//       .addErrback(function() {
//         promise.emitError(new Error('could not read from '+self.file.filename));
//       });
//     }
//
//   read();
//   return promise;
// };

// Dirty.prototype.close = function() {
//   clearTimeout(this.flushTimer);
//   return this.file.close();
// };

// Dirty.prototype.add = function(doc, cb) {
//   var uuid = dirty.uuid();
//   this.set(uuid, doc, cb);
//   return uuid;
// };

// Dirty.prototype.set = function(id, doc, cb) {
//   doc._id = id;
//
//   if (this._ids[id] === undefined && !doc._deleted) {
//     this.length++;
//   }
//   this._ids[id] = (this._docs.push(doc)-1);
//   if (!this.file) {
//     process.nextTick(function() {
//       cb(doc);
//     });
//     return;
//   }
//
//   this._memoryIds.push(id);
//   this.memoryQueueLength++;
//
//   if (this.memoryQueueLength === this.flushLimit) {
//     this.flush().addCallback(function() {
//       if (cb) {
//         cb(doc);
//       }
//     });
//   } else if (cb) {
//     this.flushCallbacks.push(function() {
//       cb(doc);
//     });
//   }
//
//   // Start new flushTimer if needed
//   if (
//     (!this.flushTimer)
//     && (this.flushInterval)
//     && (this.memoryQueueLength !== this.flushLimit)
//   ) {
//     var self = this;
//     this.flushTimer = setTimeout(function() {
//       self.flush();
//     }, this.flushInterval);
//   }
// };

// Dirty.prototype.empty = function() {
//   this._ids = {};
//   this._docs = [];
// };
//
// Dirty.prototype.flush = function() {
//   var promise = new process.Promise();
//   if (this.memoryQueueLength === 0 || !this.file) {
//     promise.emitSuccess();
//     return promise;
//   }
//
//   var
//     self = this,
//     chunk = '',
//     length = this._memoryIds.length,
//     writePromises = 0,
//     dupes = {};
//
//   this.flushQueueLength += length;
//
//   this._memoryIds.forEach(function(id, i) {
//     if (!(id in dupes)) {
//       chunk += JSON.stringify(self._docs[self._ids[id]])+"\n";
//     }
//     dupes[id] = true;
//
//     if (chunk.length < 16*1024 && i < (length-1)) {
//       return;
//     }
//
//     writePromises++;
//     self.file.write(chunk).addCallback(function() {
//       writePromises--;
//       if (writePromises === 0) {
//         self.flushQueueLength -= length;
//         self.flushCallbacks.forEach(function(cb) {
//           cb();
//         });
//         self.flushCallbacks = [];
//         promise.emitSuccess();
//       }
//
//       // If memory === disk, emit the flush event
//       if (self.flushQueueLength === 0 && self.memoryQueueLength === 0) {
//         // Clear flushTimer so the event loop can exit when idle
//         clearTimeout(self.flushTimer);
//         self.flushTimer = null;
//
//         self.emit('flush');
//       }
//     });
//
//     chunk = '';
//   });
//   this._memoryIds = [];
//   this.memoryQueueLength = 0;
//
//   return promise;
// };
//
// Dirty.prototype.get = function(id) {
//   var doc = this._docs[this._ids[id]];
//   return (doc && doc._deleted)
//     ? undefined
//     : doc;
// };
//
// Dirty.prototype.remove = function(id, cb) {
//   var self = this;
//
//   delete this._docs[this._ids[id]];
//
//   this.length--;
//   this.set(id, {_deleted: true}, function() {
//     delete self._docs[self._ids[id]];
//     delete(self._ids[id]);
//
//     if (cb) {
//       cb();
//     }
//   });
// };
//
// Dirty.prototype.filter = function(fn) {
//   return this._docs.filter(fn);
// };<commit_msg>Cleanup<commit_after>var
  dirty = exports,
  sys = require('sys'),
  events = require('events'),
  fs = require('fs');

dirty.uuid = function() {
  var uuid = '', i;
  for (i = 0; i < 32; i++) {
    uuid += Math.floor(Math.random() * 16).toString(16);
  }
  return uuid;
};

var Dirty = dirty.Dirty = function(filePath, options) {
  process.EventEmitter.call(this);

  options = process.mixin({
    flushInterval: 10,
    flushLimit: 1000,
  }, options || {});

  var
    self = this,
    docs = {},
    log = [],
    loading = false,
    flushing = false,
    readStream = fs.createReadStream(filePath),
    writeStream = fs.createWriteStream(filePath, {flags: 'a+'}),
    readBuffer = '',
    timer;

  readStream
    .addListener('error', function(err) {
      // No such file or directory
      if (err.errno == 2) {
        self.emit('load');
        return;
      }
      self.emit('error', err);
    })
    .addListener('data', function(chunk) {
      var
        offset,
        chunk,
        doc;

      readBuffer += chunk;

      while ((offset = readBuffer.indexOf("\n")) > -1) {
        chunk = readBuffer.substr(0, offset);
        readBuffer = readBuffer.substr(offset+1);

        try {
          doc = JSON.parse(chunk);
        } catch (e) {
          continue;
        }

        if (doc.deleted) {
          delete docs[doc.id];
        } else {
          docs[doc.id] = doc.value;
        }
      }
    })
    .addListener('end', function() {
      self.emit('load');
    });

  writeStream
    .addListener('drain', function() {
      if (!log.length) {
        self.emit('drain');
      }
    })
    .addListener('error', function(err) {
      self.emit('error', err);
    });

  this.add = function(doc, cb) {
    var id = dirty.uuid();
    this.set(id, doc, cb);
    return id;
  };

  this.set = function(id, doc, cb) {
    if (doc !== undefined) {
      docs[id] = doc;
    } else {
      delete docs[id];
    }

    log.push(!cb ? id : [id, cb]);

    if (loading === true) {
      // Do not flush while loading
    } else if (options.flushLimit && !flushing && log.length >= options.flushLimit) {
      this.flush();
      if (timer) {
        clearTimeout(timer);
      }
    } else if (options.flushInterval && !flushing && !timer) {
      timer = setTimeout(function() {
        self.flush();
        timer = null;
      }, options.flushInterval);
    }
  };

  this.get = function(id) {
    return docs[id];
  };

  this.remove = function(id, cb) {
    this.set(id, undefined, cb);
  };

  this.flush = function(flushCb) {
    flushing = true;

    var
      chunkCallbacks = [],
      chunk = '',
      id;

    while (true) {
      id = log.shift();
      if (id === undefined) {
        break;
      }

      if (id instanceof Array) {
        chunkCallbacks.push(id[1]);
        id = id[0];
      }

      if (id in docs) {
        chunk += JSON.stringify({id: id, value: docs[id]})+"\n";
      } else {
        chunk += JSON.stringify({id: id, deleted: true})+"\n";
      }

      if (chunk.length < 16 * 1024 && log.length) {
        continue;
      }

      writeStream.write(chunk, function(err) {
        chunkCallbacks.forEach(function(cb) {
          cb(err);
        });
        callbacks = [];

        if (err) {
          if (flushCb) {
            flushCb(err);
          }
          self.emit('error', err);
        }

        flushing = false;

        if (log.length) {
          self.flush();
        } else if (flushCb) {
          cb(null);
        }
      });
    }
  };
};
sys.inherits(Dirty, events.EventEmitter);<|endoftext|>