Can I escape characters in git log output?

I want to publish a git log output process and played with the --pretty settings. When I, for example, do

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

I get JSON-like output; when I put in the message { or } or even " in the commit message, this will ruin my output.

Is there a way to tell git log to avoid these characters, for example. adding \ ?

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

+6
source share
2 answers

String exclusion is not performed by Git; git log has nothing to help you with this. To achieve what you need, you will need something like sed to do line editing.

Try this (should work in most shells, but I 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 exit from { and } , not \ , although from JSON.org both \{ and \} are invalid screens; only \ and " should be escaped. (Replace sed expression with sed -r 's/("\\)/\\\1/g' for true JSON output.)

I also left the value "commit" as in your example, although the %cE does indeed give the commiter email address; I'm not sure what you intended.

(Now this includes the correct but rejected macrobug change . Thanks!)

+4
source

I don't know how this could only be done using git log , but a simple other solution would be to use git log to create a CSV-like output (with a field separated by fields), and pass that output to a python script that processes the JSON generation with the correct quote.

0
source

Source: https://habr.com/ru/post/908558/


All Articles