9

I want to post process the output of git log and have been playing with the --pretty settings. When I e.g. do

--pretty=format:'{"sha":"%h","message":"%B","author":"%aN <%aE>","commit":"%cE","date":"%cD"}

I get some JSON-like output; when I put in a { or } or even a " into the commit message this messes up my output.

Is there a way to tell git log to escape those chars e.g. by prepending a \?

There are two similar questions Git log output to XML, JSON or YAML and Git log output preferably as XML, but they both do not address the escaping of the special chars (e.g. if in the XML case I put <foo> in my commit message, the resulting XML will be broken).

1
  • You should use git rev-list for scripting Commented Feb 21, 2012 at 11:59

2 Answers 2

6

Escaping strings isn't Git's job; git log doesn't have anything that'll help you do that. To achieve what you're after, you'll need something like sed to do the string editing for you.

Try this (should work in most shells, but I've only checked in Cygwin bash):

function escape_chars {
    sed -r 's/(\{\}")/\\\1/g'
}
function format {
    sha=$(git log -n1 --pretty=format:%h $1 | escape_chars)
    message=$(git log -n1 --pretty=format:%B $1 | escape_chars)
    author=$(git log -n1 --pretty=format:'%aN <%aE>' $1 | escape_chars)
    commit=$(git log -n1 --pretty=format:%cE $1 | escape_chars)
    date=$(git log -n1 --pretty=format:%cD $1 | escape_chars)
    echo "{\"sha\":\"$sha\",\"message\":\"$message\",\"author\":\"$author\",\"commit\":\"$commit\",\"date\":\"$date\"}"
}

for hash in $(git rev-list)
do
  format $hash
done

The above will escape { and } and not \, although from JSON.org both \{ and \} are invalid escapes; only \ and " need to be escaped. (Replace the sed expression with sed -r 's/("\\)/\\\1/g' for true JSON output.)

I've also left the "commit" value as it is in your example, although the %cE command actually gives the commiter's email address; I'm not sure if that's what you intended.

(This now includes a correct but rejected edit by macrobug. Thanks!)

Sign up to request clarification or add additional context in comments.

2 Comments

More recent versions of git require git rev-list --all
rev-list doesn't escape either
0

I don't know how this could be done using git log only but a simple other solution would be to use git log to generate a CSV-like output (with tab-separated field) and pipe this output into a python script which handles the JSON generation with correct quote.

1 Comment

Wouldn't a , in CSV also need to be escaped? Or will git log do that?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.