UNPKG

2.08 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3'use strict';
4
5const log = require('debug')('pre-git');
6
7/* jshint -W079 */
8const Promise = require('bluebird');
9
10const child = require('child_process');
11const label = 'pre-push';
12
13function failed(err) {
14 console.error(label, 'Check went wrong.');
15 console.error(label, err);
16 return process.exit(1);
17}
18
19// todo: find if there are commits to push for any remote name / any branch
20// detect current branch
21function haveCommitsToPush() {
22 return new Promise(function (resolve, reject) {
23 child.exec('git rev-parse --abbrev-ref HEAD', function (err, stdout) {
24 log('rev-parse results', err, stdout);
25 if (err) {
26 console.error('git rev-parse failed');
27 return failed(err);
28 }
29
30 var branch = 'master';
31 if (stdout.trim().length) {
32 branch = stdout.trim();
33 }
34 child.exec('git ls-remote --heads origin ' + branch, function (err, stdout) {
35 log('ls-remote results', err, stdout);
36 if (err) {
37 console.error('git ls-remote failed');
38 return failed(err);
39 }
40
41 if (!stdout.trim().length) {
42 console.log('New branch "' + branch + '", pushing...');
43 return resolve();
44 }
45
46 child.exec('git diff --name-only origin/' + branch + '..HEAD', function (err, stdout) {
47 log('diff --names-only results', err, stdout);
48 if (err) {
49 console.error('git diff failed');
50 return failed(err);
51 }
52
53 if (!stdout.trim().length) {
54 return reject();
55 }
56 console.log(label, 'Detected files in diff:', stdout.trim().split('\n').length);
57 resolve();
58 });
59 });
60 });
61 });
62}
63
64function printNothingToDo() {
65 console.log('');
66 console.log(label, 'No local commits detected, bailing out.');
67 console.log('');
68}
69
70const run = require('pre-git').run;
71const runTask = run.bind(null, label);
72
73haveCommitsToPush()
74 .then(runTask, (err) => {
75 if (err) {
76 return failed(err);
77 }
78 printNothingToDo();
79 process.exit(0);
80 })
81 .done();