From 59e7522fe36b370a6eaf54dfdc6751948befa1be Mon Sep 17 00:00:00 2001 From: Devon Blandin Date: Mon, 6 Jun 2016 12:11:50 -0400 Subject: [PATCH] Use git hash-object for blob id if available This commit updates file blob_id generation by first shelling out to `git hash-object`. If `git` or the file is unavailable, we'll fallback to our `sha1` computation. --- formatter.js | 2 +- git_info.js | 31 ++++++++++++++++++++++++------- 2 files changed, 25 insertions(+), 8 deletions(-) diff --git a/formatter.js b/formatter.js index 370464b..e95f5d3 100644 --- a/formatter.js +++ b/formatter.js @@ -94,7 +94,7 @@ Formatter.prototype.sourceFiles = function(data) { source_files.push({ name: fileName, - blob_id: git.calculateBlobId(content), + blob_id: git.blobId(elem.file, content), coverage: JSON.stringify(coverage) }); }); diff --git a/git_info.js b/git_info.js index eb80c17..e34a8dc 100644 --- a/git_info.js +++ b/git_info.js @@ -1,6 +1,14 @@ var crypto = require('crypto'); var childProcess = require('child_process'); +function calculateBlobId(content) { + var header = 'blob ' + content.length + '\0'; + var store = header + content; + var shasum = crypto.createHash('sha1'); + shasum.update(store); + return shasum.digest("hex"); +} + module.exports = { head: function(cb) { @@ -41,12 +49,21 @@ module.exports = { }); }, - calculateBlobId: function(content) { - var header = 'blob ' + content.length + '\0'; - var store = header + content; - var shasum = crypto.createHash('sha1'); - shasum.update(store); - return shasum.digest("hex"); - } + calculateBlobId: calculateBlobId, + + blobId: function(path, content) { + var stdout, returnBlobId = null; + try { + stdout = childProcess.execSync("git hash-object " + path, { stdio: [0, "pipe", "ignore"] }); + } catch (e) { } + + if (stdout) { + returnBlobId = stdout.toString().trim(); + } else { + returnBlobId = calculateBlobId(content); + } + + return returnBlobId; + } };