1 | module.exports = version;
|
2 | module.exports.pin = pin;
|
3 |
|
4 | var fs = require('fs');
|
5 | var path = require('path');
|
6 | var exec = require('child_process').exec;
|
7 | var root = null;
|
8 |
|
9 | function pin() {
|
10 | return version().then(function (v) {
|
11 | version.pinned = v;
|
12 | });
|
13 | }
|
14 |
|
15 | function version(callback) {
|
16 |
|
17 | var promise = findPackage(path.dirname(module.parent.filename))
|
18 | .then(function (dir) {
|
19 |
|
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 |
|
29 |
|
30 | var promises = [
|
31 | branch().catch(function () { return 'master'; }),
|
32 | commit().catch(function () { return '<none>'; }),
|
33 | dirty().catch(function () { return 0; }),
|
34 | ];
|
35 |
|
36 |
|
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 |
|
62 | function 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 |
|
77 | function 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 |
|
89 | function commit() {
|
90 | return command('git rev-parse HEAD');
|
91 | }
|
92 |
|
93 | function branch() {
|
94 | return command('git rev-parse --abbrev-ref HEAD');
|
95 | }
|
96 |
|
97 | function dirty() {
|
98 | return command('expr $(git status --porcelain 2>/dev/null| ' +
|
99 | 'egrep "^(M| M)" | wc -l)');
|
100 | }
|