summaryrefslogtreecommitdiffstats
path: root/index.js
blob: 51856b4b876c5b0f79587a37acd3266c14d422c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
#!/usr/bin/env node

var fs = require('fs');

var Promise = require('bluebird');
var git = require('nodegit');
var program = require('commander');
var _ = require('lodash');

var exec = Promise.promisify(require('child_process').exec);

var config = {
    // Maximum time diff between 2 subsequent commits in minutes which are
    // counted to be in the same coding "session"
    maxCommitDiffInMinutes: 2 * 60,

    // How many minutes should be added for the first commit of coding session
    firstCommitAdditionInMinutes: 2 * 60
};

function main() {
    parseArgs();
    config = mergeDefaultsWithArgs(config);

    commits('.').then(function(commits) {
        var work = {
            total: {
                hours: estimateHours(_.pluck(commits, 'date')),
                commits: commits.length
            }
        };

        console.log(JSON.stringify(work, undefined, 2));
    }).catch(function(e) {
        console.error(e.stack);
    });
}

function parseArgs() {
    function list(val) {
        return val.split(',');
    }

    function int(val) {
        return parseInt(val, 10);
    }

    program
        .version(require('./package.json').version)
        .usage('[options]')
        .option(
            '-b, --branches [branches]',
            'list of branches to calculate commits from e.g. master,dev. Default: all local branches',
            list
        )
        .option(
            '-d, --max-commit-diff [max-commit-diff]',
            'maximum difference in minutes between commits counted to one session. Default: ' + config.maxCommitDiffInMinutes,
            int
        )
        .option(
            '-a, --first-commit-add [first-commit-add]',
            'how many minutes first commit of session should add to total. Default: ' + config.firstCommitAdditionInMinutes,
            int
        );

    program.on('--help', function() {
        console.log('  Examples:');
        console.log('');
        console.log('   - Estimate hours of project');
        console.log('');
        console.log('       $ githours');
        console.log('');
        console.log('   - Estimate hours of development branch');
        console.log('');
        console.log('       $ githours --branches development');
        console.log('');
        console.log('   - Estimate hours in repository where developers commit more seldom: they might have 4h(240min) pause between commits');
        console.log('');
        console.log('       $ githours --max-commit-diff 240');
        console.log('');
        console.log('   - Estimate hours in repository where developer works 5 hours before first commit in day');
        console.log('');
        console.log('       $ githours --first-commit-add 300');
        console.log('');
        console.log('  For more details, visit https://github.com/kimmobrunfeldt/githours');
        console.log('');
    });

    program.parse(process.argv);
}

function mergeDefaultsWithArgs(config) {
    return {
        branches: program.branches || [],
        maxCommitDiffInMinutes: program.maxCommitDiff || config.maxCommitDiffInMinutes,
        firstCommitAdditionInMinutes: program.firstCommitAdd || config.firstCommitAdditionInMinutes
    };
}

// Estimates spent working hours based on commit dates
function estimateHours(dates) {
    if (dates.length < 2) {
        return 0;
    }

    // Oldest commit first, newest last
    var sortedDates = dates.sort(function(a, b) {
        return a - b;
    });
    var allButLast = _.take(sortedDates, sortedDates.length - 1);

    var hours = _.reduce(allButLast, function(hours, date, index) {
        var nextDate = sortedDates[index + 1];
        var diffInMinutes = (nextDate - date) / 1000 / 60;

        // Check if commits are counted to be in same coding session
        if (diffInMinutes < config.maxCommitDiffInMinutes) {
            return hours + (diffInMinutes / 60);
        }

        // The date difference is too big to be inside single coding session
        // The work of first commit of a session cannot be seen in git history,
        // so we make a blunt estimate of it
        return hours + (config.firstCommitAdditionInMinutes / 60);

    }, 0);

    return Math.round(hours);
}

// Promisify nodegit's API of getting all commits in repository
function commits(gitPath) {
    // Promisifing nodegit did not work.
    return new Promise(function(resolve, reject) {
        git.Repo.open(gitPath, function(err, repo) {
            if (err) {
                reject(err);
                return;
            }

            var branchNames = config.branches;
            if (_.isEmpty(branchNames)) {
                // If no command line parameters set, get all branches
                branchNames = getBranchNames(gitPath);
            }

            Promise.map(branchNames, function(branchName) {
                return getBranch(repo, branchName);
            }).map(function(branch) {
                return getBranchCommits(branch);
            }).reduce(function(allCommits, branchCommits) {
                _.each(branchCommits, function(commit) {
                    allCommits.push(commit);
                });

                return allCommits;
            }, []).then(function(commits) {
                var uniqueCommits = _.uniq(commits, function(item, key, a) {
                    return item.sha;
                });

                resolve(uniqueCommits);
            }).catch(reject);
        });
    });
}

function getBranchNames(gitPath) {
    var cmd = "git branch --no-color | awk -F ' +' '! /\\(no branch\\)/ {print $2}'";
    return new Promise(function(resolve, reject) {
        exec(cmd, {cwd: gitPath}, function(err, stdout, stderr) {
            if (err) {
                reject(err);
            }

            resolve(stdout
                    .split('\n')
                    .filter(function(e) { return e; })  // Remove empty
                    .map(function(str) { return str.trim(); })  // Trim whitespace
            );
        });
    });
}

function getBranches(repo, names) {
    var branches = [];
    for (var i = 0; i < names.length; ++i) {
        branches.push(getBranch(repo, names[i]));
    }

    return Promise.all(branches);
}

function getBranch(repo, name) {
    return new Promise(function(resolve, reject) {
        repo.getBranch(name, function(err, branch) {
            if (err) {
                reject(err);
                return;
            }

            resolve(branch);
        });
    });
}

function getBranchCommits(branch) {
    return new Promise(function(resolve, reject) {
        var history = branch.history();
        var commits = [];

        history.on("commit", function(commit) {
            var author = null;
            if (!_.isNull(commit.author())) {
                author = {
                    name: commit.author().name(),
                    email: commit.author().email()
                };
            }

            var commitData = {
                sha: commit.sha(),
                date: commit.date(),
                message: commit.message(),
                author: author
            };

            commits.push(commitData);
        });

        history.on("end", function() {
            resolve(commits);
        });

        history.on("error", function(err) {
            reject(err);
        });

        // Start emitting events.
        history.start();
    });
}

main();