Skip to content

Instantly share code, notes, and snippets.

@rybarix
Created August 31, 2019 18:47
Show Gist options
  • Save rybarix/2712c0e3241b3996ff1caa05014d906e to your computer and use it in GitHub Desktop.
Save rybarix/2712c0e3241b3996ff1caa05014d906e to your computer and use it in GitHub Desktop.
Reports hours spent on project from 7Am morning until now. Information about time is gathered from commit messages containing eg. `#1h20m` or `#20m` or `#1h`
const { exec } = require('child_process');
const Reset = "\x1b[0m"
const FgBlack = "\x1b[30m"
const FgRed = "\x1b[31m"
const FgGreen = "\x1b[32m"
const FgYellow = "\x1b[33m"
const FgBlue = "\x1b[34m"
const FgMagenta = "\x1b[35m"
const FgCyan = "\x1b[36m"
const FgWhite = "\x1b[37m"
//
exec(`git branch`, (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
console.log(`${stderr}`);
return;
}
const gitBranch = stdout.toString().split("\n")[0].substr(2)
exec(`git log --pretty=format:'%h -%d %s (%ad) <%an>' --date=iso`, (err, stdout, stderr) => {
if (err) {
// node couldn't execute the command
console.log(`${stderr}`);
return;
}
const gitInfo = `On branch: ${FgGreen}${gitBranch}${Reset}`
const time = totalMinutesWorked(stdout.toString())
console.log(`You've worked: ${FgYellow}${time.hours}h${time.minutes}m${Reset}\nTotal minutes: ${FgCyan}${time.totalMinutes}m${Reset}\n${gitInfo}`)
// console.log(time)
});
});
function getDateOfCommit(gitlogLine) {
const regexDate = /(\d{4})-0?(\d+)-0?(\d+)[T ]0?(\d+):0?(\d+):0?(\d+)/gmi
return regexDate.exec(gitlogLine);
}
/**
*
* @param {String} commitLog
* @returns {Object}
*/
function totalMinutesWorked(commitLog) {
const hm = /(#(?<h>\d+)h(?<m>\d+)m)/gmi
const m = /(#(?<m>\d+)m)/gmi
const h = /(#(?<h>\d+)h)/gmi
const regexes = [
{ name: 'hm', regex: hm },
{ name: 'm', regex: m },
{ name: 'h', regex: h }
]
let totalMinutes = 0
const now = new Date();
const today7Am = new Date().setHours(7); // set to 7Am
for (const line of commitLog.split('\n')) {
const commitDate = new Date(getDateOfCommit(line)[0])
if (commitDate < today7Am) {
continue;
}
for (const r of regexes) {
const o = r.regex.exec(line);
if (o !== null) {
if(r.name === 'hm') {
const hours = Number(o.groups.h)
const mins = Number(o.groups.m)
totalMinutes += hours * 60 + mins
}
else if (r.name === 'm') {
const mins = Number(o.groups.m)
totalMinutes += mins
}
else if (r.name === 'h') {
const hours = Number(o.groups.h)
totalMinutes += hours * 60
}
break;
}
}
}
function prettyFormat(minutes) {
const hours = Math.floor(minutes / 60);
return {
hours,
minutes: minutes - hours * 60
}
}
return {
totalMinutes,
...prettyFormat(totalMinutes)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment