From 335918f28d6cbbac2efbc25990e97549dbd96aee Mon Sep 17 00:00:00 2001 From: Christophe Porteneuve Date: Fri, 8 Nov 2013 19:05:52 +0100 Subject: Fix step 1: for dev-local uses, properly detect local Git branch and commit --- lib/detectLocalGit.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 lib/detectLocalGit.js (limited to 'lib/detectLocalGit.js') diff --git a/lib/detectLocalGit.js b/lib/detectLocalGit.js new file mode 100644 index 0000000..2d0fba0 --- /dev/null +++ b/lib/detectLocalGit.js @@ -0,0 +1,30 @@ +var fs = require('fs'); +var path = require('path'); + +var REGEX_BRANCH = /^ref: refs\/heads\/(\w+)$/; + +module.exports = function detectLocalGit(knownCommit, knownBranch) { + var dir = process.cwd(), gitDir; + while ('/' !== dir) { + gitDir = path.join(dir, '.git'); + if (fs.existsSync(path.join(gitDir, 'HEAD'))) + break; + + dir = path.dirname(dir); + } + + if ('/' === dir) + return; + + var head = strip(fs.readFileSync(path.join(dir, '.git', 'HEAD'), 'utf-8')); + var branch = (head.match(REGEX_BRANCH) || [])[1]; + if (!branch) + return { git_commit: head }; + + var commit = strip(fs.readFileSync(path.join(dir, '.git', 'refs', 'heads', branch), 'utf-8')); + return { git_commit: commit, git_branch: branch }; +}; + +function strip(str) { + return (str || '').replace(/^\s+|\s+$/g, ''); +} -- cgit v1.2.3 From b12c8cf5f0bc11486e2b064a834ee9ff81adb0a3 Mon Sep 17 00:00:00 2001 From: Christophe Porteneuve Date: Fri, 8 Nov 2013 20:02:29 +0100 Subject: =?UTF-8?q?Ah,=20right,=20ES5=20has=20String#trim(),=20keep=20forg?= =?UTF-8?q?etting=20that=E2=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- lib/detectLocalGit.js | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) (limited to 'lib/detectLocalGit.js') diff --git a/lib/detectLocalGit.js b/lib/detectLocalGit.js index 2d0fba0..4fd8d1b 100644 --- a/lib/detectLocalGit.js +++ b/lib/detectLocalGit.js @@ -16,15 +16,11 @@ module.exports = function detectLocalGit(knownCommit, knownBranch) { if ('/' === dir) return; - var head = strip(fs.readFileSync(path.join(dir, '.git', 'HEAD'), 'utf-8')); + var head = fs.readFileSync(path.join(dir, '.git', 'HEAD'), 'utf-8').trim(); var branch = (head.match(REGEX_BRANCH) || [])[1]; if (!branch) return { git_commit: head }; - var commit = strip(fs.readFileSync(path.join(dir, '.git', 'refs', 'heads', branch), 'utf-8')); + var commit = fs.readFileSync(path.join(dir, '.git', 'refs', 'heads', branch), 'utf-8').trim(); return { git_commit: commit, git_branch: branch }; }; - -function strip(str) { - return (str || '').replace(/^\s+|\s+$/g, ''); -} -- cgit v1.2.3