How to get git log -p as json

Viewed 344

I want to run git log -p and get the results as JSON. I couldn't find a way to do it from the pretty format documentation, but I am probably missing something.

The desired result I have in mind will be something like:

[{
  "commit": SHA,
  "author": AUTHOR,
  "date": DATE,
  "commit_message": COMMIT_MSG,
  "full_diff": FULL_DIFF
}]
1 Answers

It's impossible to implement with git log because there is no format for diff. It's possible to script using plumbing commands:

echo '['
git rev-list HEAD | while read sha1; do
    full_diff="$(git show --format='' $sha1 | sed 's/\"/\\\"/g')"
    git --no-pager show --format="{%n  \"commit\": \"%H\",%n  \"author\": \"%an\",%n  \"date\": \"%ad\",%n  \"commit_message\": \"%s\",%n  \"full_diff\": \"$full_diff\"%n}," -s $sha1
    done
echo ']'

A few notes:

git rev-list HEAD | while read sha1; do…done

Means "run through all commits, read every hash into variable sha1".

full_diff="$(…)"

Extract the full diff for the commit. Replace " with \" to avoid generating broken JSON.

git show --format="…" -s $sha1

Print information about the commit in the given format. Add the full diff separately.

Related