Search code examples
jsongitgit-log

Parse Approved-By from git log or git show


Using --pretty=format, you can format git log or git show stdout as you like.

git log \
--pretty=format:'{%n  "commit": "%H",%n  "author": "%an <%ae>",%n  "date": "%ad",%n  "message": "%f"%n},' \
$@ | \
perl -pe 'BEGIN{print "["}; END{print "]\n"}' | \
perl -pe 's/},]/}]/'

Example above parses author, commit, date, message values. How can we parse the value of Approved-by which is available when a pull-request is approved.

Even the official documentation does not mention that


Solution

  • Approved-by is not a builtin field so Git doesn't have a placeholder for it. We could use other methods to get the fields and format the output.

    Suppose the Approved-by line looks like:

    Approved-by: Someone Nice

    Here is a bash sample:

    for commit in $(git log --pretty=%H);do
      echo -e "{\n\
        \"commit\": \"$commit\",\n\
        \"author\": \"$(git log -1 $commit --pretty=%an)\",\n\
        \"date\": \"$(git log -1 $commit --pretty=%cd)\",\n\
        \"message\": \"$(git log -1 $commit --pretty=%f)\",\n\
        \"approved-by\": \"$(git log -1 $commit --pretty=%b | grep Approved-by | awk -F ': ' '{print $NF","}' | xargs echo | sed -e 's/,$//')\"\n\
    },"
    done | \
    perl -pe 'BEGIN{print "["}' | \
    sed -e '$s/},/}]/'
    

    It needs improvement to meet your real needs, especially the \"approved-by\" line. Basically it gets all the commit sha1 values first and then parse them to get the fields of each commit and then format the output.