UNPKG

2.46 kBJavaScriptView Raw
1module.exports = version;
2module.exports.pin = pin;
3
4var fs = require('fs');
5var path = require('path');
6var exec = require('child_process').exec;
7var root = null;
8
9function pin() {
10 return version().then(function (v) {
11 version.pinned = v;
12 });
13}
14
15function version(callback) {
16 // first find the package.json as this will be our root
17 var promise = findPackage(path.dirname(module.parent.filename))
18 .then(function (dir) {
19 // now try to load the package
20 var v = require(path.resolve(dir, 'package.json')).version;
21
22 if (v && v !== '0.0.0-development') {
23 return v;
24 }
25
26 root = dir;
27
28 // else we're in development, give the commit out
29 // get the last commit and whether the working dir is dirty
30 var promises = [
31 branch().catch(function () { return 'master'; }),
32 commit().catch(function () { return '<none>'; }),
33 dirty().catch(function () { return 0; }),
34 ];
35
36 // use the cached result as the export
37 return Promise.all(promises).then(function (res) {
38 var branch = res[0];
39 var commit = res[1];
40 var dirtyCount = parseInt(res[2], 10);
41 var curr = branch + ': ' + commit;
42 if (dirtyCount !== 0) {
43 curr += ' (' + dirtyCount + ' dirty files)';
44 }
45
46 return curr;
47 });
48 }).catch(function (error) {
49 console.log(error.stack);
50 throw error;
51 });
52
53 if (callback) {
54 promise.then(function (res) {
55 callback(null, res);
56 }, callback);
57 }
58
59 return promise;
60}
61
62function findPackage(dir) {
63 if (dir === '/') {
64 return Promise.reject(new Error('package not found'));
65 }
66 return new Promise(function (resolve) {
67 fs.stat(path.resolve(dir, 'package.json'), function (error, exists) {
68 if (error || !exists) {
69 return resolve(findPackage(path.resolve(dir, '..')));
70 }
71
72 resolve(dir);
73 });
74 });
75}
76
77function command(cmd) {
78 return new Promise(function (resolve, reject) {
79 exec(cmd, { cwd: root }, function (err, stdout, stderr) {
80 var error = stderr.trim();
81 if (error) {
82 return reject(new Error(error));
83 }
84 resolve(stdout.split('\n').join(''));
85 });
86 });
87}
88
89function commit() {
90 return command('git rev-parse HEAD');
91}
92
93function branch() {
94 return command('git rev-parse --abbrev-ref HEAD');
95}
96
97function dirty() {
98 return command('expr $(git status --porcelain 2>/dev/null| ' +
99 'egrep "^(M| M)" | wc -l)');
100}