How to indent textual diff output of git show command

Viewed 74

When I use git show --no-prefix -U1000, the result would be something like:

-var a = 0;
+const a = 0;

 no change

I'm wondering if there's an option to ident the line with a whitespace right after +/-, e.g.:

- var a = 0;
+ const a = 0;

  no change

I've checked the documentation here https://git-scm.com/docs/git-show, but there doesn't seem to be one.

2 Answers

You can run the output through a script that will add a space if the first character is a space, +, or -.

git diff HEAD^ | perl -pe 's{^([ +-])(.)}{$1 $2}'

Also consider using git-difftool to set up a diff viewing program to your liking.

I am not aware of a command-line flag to git show that inserts a space after the single + or - characters at the beginning of the diff (although you can change these very characters ever since 2.22.0 with --output-indicator-new=<char> or --output-indicator-old=<char>).

What you could do is pipe the output to another program (e.g. sed) to insert the space "by hand" (assuming a terminal with sufficient color support):

git show --color=always | sed 's/^\x1B\[3[12]m[+-]/& /'

Note that:

  1. The flag color=always is necessary to preserve color codes when piping to a program that does not naturally support them.
  2. We only insert a space after a single + or - character at the beginning of a line preceded by only the color codes \x1B[32m (green) or \x1B[31m (red). This is to avoid inserting unnecessary spaces in the summary lines (i.e. to prevent changing --- a/foo to - -- a/foo), in the commit message (which could theoretically begin with a + or -) or in the middle of the diff.

To avoid typing this command every time, you can define it as a Git alias my-show (Mind the leading ! character in the alias-definition to treat the subsequent as an external command rather than a Git subcommand).

git config --global alias.my-show "! git show --color=always | sed 's/^\x1B\[3[12]m[+-]/& /'"

and then invoke git my-show to get your desired output.

Related