Last active
September 1, 2016 07:53
-
-
Save neerajt/4f04f3d7dd93b51dabbcac5e4a0b0456 to your computer and use it in GitHub Desktop.
`git log` in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fs = require('fs'); | |
// get and parse the HEAD | |
var HEAD = fs.readFileSync("./.git/HEAD").toString(); | |
HEAD = HEAD.replace(/(\r\n|\n|\r)/gm,""); | |
HEAD = HEAD.split(": ")[1] | |
var HEADpath = fs.readFileSync('./.git/' + HEAD).toString().replace(/\n/, ""); | |
// function to print pretty output | |
var exec = require('child_process').execSync; | |
printPretty = function(hash){ | |
// make author pretty | |
pretty = exec("git cat-file -p " + hash).toString(); | |
pretty = pretty.replace(/parent .*\n/,""); | |
pretty = pretty.replace(/tree .*\n/,""); | |
pretty = pretty.replace(/committer .*\n/,""); | |
pretty = pretty.replace(/author/, "Author:") | |
// make time pretty | |
time = pretty.split('\n')[0].replace(/Author: .*\> /, ""); | |
time = new Date(time.split(' ')[0] * 1000) | |
date = time.toDateString(); | |
time = time.toTimeString(); | |
pretty = pretty.replace(/\> .*\n/g,"\>\n"); | |
//make message pretty | |
message = pretty.split('\n').slice(-2, -1)[0]; | |
pretty = pretty.replace(message, " " + message); | |
// color commit line | |
console.log('\x1b[33m%s\x1b[0m', "commit " + hash); | |
console.log("Date: " + date + " " + time); | |
console.log(pretty); | |
} | |
// recursive function to traverse tree | |
// follows `parent` until `parent` | |
// is no longer found | |
getParent = function(hash){ | |
re = new RegExp('parent'); | |
var commit = exec("git cat-file -p " + hash).toString(); | |
parent = commit.split("\n")[1]; | |
if(re.test(parent)){ | |
parent = parent.split(" ")[1]; | |
printPretty(hash); | |
getParent(parent); | |
} | |
else{ | |
printPretty(hash); | |
} | |
} | |
// run | |
getParent(HEADpath); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment