Search code examples
gitpretty-printtext-alignment

How to fix alignment problem in git log --graph


I'm using the following alias to render my git commit history on console if no GUI is available:

$ git config alias.treex
log --color --graph --pretty=format:'%C(cyan)%h%Creset - %C(cyan)%ad%Creset %<(80,trunc)%s   %C(cyan)%>(20,trunc)%an - %Cgreen%>(12)%cr%Creset' --date=format:'%d.%m.%Y %H:%M' --abbrev-commit --all

While the format string uses align and fixed size string formats like %<(80,trunc)%s, the graph rendered by git log --graph destroys the alignment:

Git treex result.
(click to enlarge)

How to fix the broken alignment cause by the graph itself?


Solution

  • Instead of %<(80,trunc)%s that tells git log to render the subject on 80 characters you can use %<|(110,trunc)%s that tells it to render the subject until it reaches the 110th column of the output. This way the next field after the subject starts at the 111st column and the order is restored.
    (110 is approximately the original 80 characters you want for the subject + the sizes of the columns before it (%h = 7 characters, %ad = 16 characters) and the delimiter characters you put between them.)

    Of course you can use a different value. You can also try to constraint the width of the first field (%h) to get all the other fields aligned but it won't align properly on the sections of the history that contain a lot of branches; the %s field is large and uses enough columns to accommodate two dozens of concurrent branches.

    The format is described in the documentation of git log right under the <() format and it is present in all versions of the documentation page (that unfortunately starts with 2.3.8). If you are using an older Git version, it is possible that the format is not available for you. The best advice in this situation is to update your Git to a more recent version.