Skip to content

Commit

Permalink
Refactor the commiter json saving code into its own reusable module
Browse files Browse the repository at this point in the history
  • Loading branch information
robarnold committed Jun 3, 2011
1 parent 2383142 commit 2cf20bc
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 27 deletions.
31 changes: 4 additions & 27 deletions committers.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
var fs = require("fs");

var kDatabase = 'committers.json';
var config = require("./jsondb")(kDatabase);

var committers = config.db;

var committers = JSON.parse(fs.readFileSync(kDatabase, 'utf8'));
exports.lookup = function lookup(email, certain, guess)
{
if (committers.hasOwnProperty(email)) {
Expand All @@ -15,30 +15,7 @@ exports.lookup = function lookup(email, certain, guess)
return guess(undefined);
};

var saveInProgress = false;
var dbDirty = false;

function saveDatabase() {
saveInProgress = true;
var count = Object.keys(committers).length;
fs.writeFile(kDatabase, JSON.stringify(committers), 'utf8', function (err) {
if (err) {
console.error("Got error trying to save committer database: " + e);
} else {
console.log("Saved new version of committers database with " + count + " entries");
}
saveInProgress = false;
if (dbDirty) {
saveDatabase();
}
});
dbDirty = false;
}

exports.add = function add(email, nick) {
committers[email] = nick;
dbDirty = true;
if (saveInProgress)
return;
saveDatabase();
config.markDirty();
};
38 changes: 38 additions & 0 deletions jsondb.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
var fs = require("fs");

function Config(path)
{
this.path = path;
this.db = JSON.parse(fs.readFileSync(path, 'utf8'));
}

Config.prototype = {
isDirty: false,
saveInProgress: false,
markDirty: function () {
this.isDirty = true;
if (!this.saveInProgress)
this.save();
},
save: function () {
this.saveInProgress = true;
var count = Object.keys(this.db).length;
fs.writeFile(this.path, JSON.stringify(this.db), 'utf8', this._saveComplete.bind(this, count));
this.isDirty = false;
},
_saveComplete: function (count, err) {
if (err) {
console.error("Got error trying to save database to " + this.path + ": " + e);
} else {
console.log("Saved new version of database to " + this.path + " with " + count + " entries");
}
this.saveInProgress = false;
if (this.isDirty) {
this.save();
}
}
};

module.exports = function (path) {
return new Config(path);
}

0 comments on commit 2cf20bc

Please sign in to comment.