Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I calculate the number of lines changed between two commits in Git?

Tags:

git

Is there any easy way to calculate the number of lines changed between two commits in Git?

I know I can do a git diff, and count the lines, but this seems tedious. I'd also like to know how I can do this, including only my own commits in the line counts.

like image 334
Mike Avatar asked Mar 27 '10 04:03

Mike


People also ask

How do I compare changes between commits?

Git Diff Between Commits You can compare files between two Git commits by specifying the name of the ref that refers to the commits you want to compare. A ref may be a commit ID or HEAD, which refers to the current branch.

How do I show more lines in git diff?

Using the -U parameter you can change how many lines are shown above and below a changed section. E.g. git diff -U10 will show 10 lines above and below.


1 Answers

You want the --stat option of git diff, or if you're looking to parse this in a script, the --numstat option.

git diff --stat <commit-ish> <commit-ish> 

--stat produces the human-readable output you're used to seeing after merges; --numstat produces a nice table layout that scripts can easily interpret.

I somehow missed that you were looking to do this on multiple commits at the same time - that's a task for git log. Ron DeVera touches on this, but you can actually do a lot more than what he mentions. Since git log internally calls the diff machinery in order to print requested information, you can give it any of the diff stat options - not just --shortstat. What you likely want to use is:

git log --author="Your name" --stat <commit1>..<commit2> 

but you can use --numstat or --shortstat as well. git log can also select commits in a variety other ways - have a look at the documentation. You might be interested in things like --since (rather than specifying commit ranges, just select commits since last week) and --no-merges (merge commits don't actually introduce changes), as well as the pretty output options (--pretty=oneline, short, medium, full...).

Here's a one-liner to get total changes instead of per-commit changes from git log (change the commit selection options as desired - this is commits by you, from commit1 to commit2):

git log --numstat --pretty="%H" --author="Your Name" commit1..commit2 | awk 'NF==3 {plus+=$1; minus+=$2} END {printf("+%d, -%d\n", plus, minus)}' 

(you have to let git log print some identifying information about the commit; I arbitrarily chose the hash, then used awk to only pick out the lines with three fields, which are the ones with the stat information)

like image 104
Cascabel Avatar answered Oct 11 '22 12:10

Cascabel