Show number of changed lines per author in git
Asked Answered
R

6

45

I want to see the number of removed/added line, grouped by author for a given branch in Git history. There is git shortlog -s which shows me the number of commits per author. Is there anything similar to get an overall diffstat?

Rackley answered 7/5, 2010 at 8:41 Comment(3)
Would #1265540 help? As in git shortlog abranch --numbered --summaryUnthrone
@VonC, i git shortlog --numbered --summary is the same as git shortlog -s -n, it will only show the number of commits, not the changed linesRackley
I use 'git shortlog -sn' instead of 'git shortlog -s' --- it allows me to sort authors by counts amountAutography
T
57

It's an old post but if someone is still looking for it:

install git extras

brew install git-extras

then

git summary --line

https://github.com/tj/git-extras

Teleprinter answered 11/11, 2014 at 14:7 Comment(6)
apt-get install git-extras for Linux usersLarner
fatal: unrecognized argument: --line I think they've removed the option in the newest releaseRubierubiginous
@M2X, it looks like that git line-summary works, though it is said in the docs, that its deprecated in favor of --line github.com/tj/git-extras/blob/master/…Bischoff
I liked the output of this tool. Nice one.Resistant
@Larner you for people whose distribution uses apt to manage packets... :)Aestival
Is there a way to make the line version of the command show only changes from a certain commit onward? The help shows it allows only <committish> without --line.Alcuin
R
47

one line code(support time range selection):

git log --since=4.weeks --numstat --pretty="%ae %H" | sed 's/@.*//g' | awk '{ if (NF == 1){ name = $1}; if(NF == 3) {plus[name] += $1; minus[name] += $2}} END { for (name in plus) {print name": +"plus[name]" -"minus[name]}}' | sort -k2 -gr

explain:

git log --since=4.weeks --numstat --pretty="%ae %H" \
    | sed 's/@.*//g'  \
    | awk '{ if (NF == 1){ name = $1}; if(NF == 3) {plus[name] += $1; minus[name] += $2}} END { for (name in plus) {print name": +"plus[name]" -"minus[name]}}' \
    | sort -k2 -gr

# query log by time range
# get author email prefix
# count plus / minus lines
# sort result

output:

user-a: +5455 -3471
user-b: +5118 -1934

Update: maybe somebody will like my little script: https://github.com/alswl/.oOo./blob/master/local/bin/git-code-numbers-by-authors

Reagent answered 14/11, 2018 at 9:10 Comment(1)
I've visited this answer every time I need to ask this question for the entire life of the repo; all I do is change 4.weeks to 10.yearsMaurits
U
19

Since the SO question "How to count total lines changed by a specific author in a Git repository?" is not completely satisfactory, commandlinefu has alternatives (albeit not per branch):

git ls-files | while read i; do git blame $i | sed -e 's/^[^(]*(//' -e 's/^\([^[:digit:]]*\)[[:space:]]\+[[:digit:]].*/\1/'; done | sort | uniq -ic | sort -nr

It includes binary files, which is not good, so you could (to remove really random binary files):

git ls-files | grep -v "\.\(pdf\|psd\|tif\)$"

(Note: as commented by trcarden, a -x or --exclude option wouldn't work.
From git ls-files man page, git ls-files -x "*pdf" ... would only excluded untracked content, if --others or --ignored were added to the git ls-files command.)

Or:

git ls-files "*.py" "*.html" "*.css" 

to only include specific file types.


Still, a "git log"-based solution should be better, like:

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

but again, this is for one path (here 2 commits), not for all branches per branches.

Unthrone answered 7/5, 2010 at 11:17 Comment(3)
git log is the only thing that doesn't barf for me, nice suggestion!Dunseath
You actually can't ignore binary files via the method specified. the -x command on ls-files is only available for "untracked files" Common error.Magnolia
@Magnolia Very good point. I have edited the answer and proposed an alternative way of excluding binaries.Unthrone
D
3

This script here will do it. Put it into authorship.sh, chmod +x it, and you're all set.

#!/bin/sh
declare -A map
while read line; do
    if grep "^[a-zA-Z]" <<< "$line" > /dev/null; then
        current="$line"
        if [ -z "${map[$current]}" ]; then 
            map[$current]=0
        fi
    elif grep "^[0-9]" <<<"$line" >/dev/null; then
        for i in $(cut -f 1,2 <<< "$line"); do
            map[$current]=$((map[$current] + $i))
        done
    fi
done <<< "$(git log --numstat --pretty="%aN")"

for i in "${!map[@]}"; do
    echo -e "$i:${map[$i]}"
done | sort -nr -t ":" -k 2 | column -t -s ":"
Dicta answered 11/12, 2011 at 19:39 Comment(6)
Getting this on both Mac OS X 10.6.8 and Debian Linux 5.0.8: /Users/slippyd/Desktop/git-authorship: line 3: declare: -A: invalid option declare: usage: declare [-afFirtx] [-p] [name[=value] ...]Diminutive
getting same error as slipp on a mac, i changed the -A to -a (as specified in the error message), but the script fails anyway, apparently it does't handle spaces in names (like the space between the first and last name), still looking of a solution that works, you might think that this is something many people need, to get promotion :), apparently not. well, i will just say 90% boss !Roving
Use #!/bin/bash instead of #!/bin/sh if it complains about that declare error.Niggard
@DonatasOlsevičius bash still doesnt help on mac, and I am getting same problem as Pizzaiola, I think, space related errorsJeaninejeanlouis
I have no idea what's the problem with mac. Maybe there's no bash and it uses a different shell instead?Niggard
This script requires bash 4.0, which I don't think mac has. It should really run under /bin/bash, because on debian /bin/sh is linked to a lightweight posix-compliant shell without bash-specific extensions.Cornelie
D
2

On my repos I've gotten a lot of trash output from the one-liners floating around, so here is a Python script to do it right:

import subprocess
import collections
import sys


def get_lines_from_call(command):
    return subprocess.check_output(command).splitlines()

def get_files(paths=()):
    command = ['git', 'ls-files']
    command.extend(paths)
    return get_lines_from_call(command)

def get_blame(path):
    return get_lines_from_call(['git', 'blame', path])


def extract_name(line):
    """
    Extract the author from a line of a standard git blame
    """
    return line.split('(', 1)[1].split(')', 1)[0].rsplit(None, 4)[0]


def get_file_authors(path):
    return [extract_name(line) for line in get_blame(path)]


def blame_stats(paths=()):
    counter = collections.Counter()
    for filename in get_files(paths):
        counter.update(get_file_authors(filename))
    return counter


def main():
    counter = blame_stats(sys.argv[1:])
    max_width = len(str(counter.most_common(1)[0][1]))
    for name, count in reversed(counter.most_common()):
        print('%s %s' % (str(count).rjust(max_width), name))

if __name__ == '__main__':
    main()

Note that the arguments to the script will be passed to git ls-files, so if you only want to show Python files: blame_stats.py '**/*.py'

If you only want to show files in one subdirectory:blame_stats.py some_dir

And so on.

Diamagnet answered 22/10, 2015 at 15:2 Comment(0)
C
0

From How to count total lines changed by a specific author in a Git repository?

The output of the following command should be reasonably easy to send to script to add up the totals:

git log --author="<authorname>" --oneline --shortstat

This gives stats for all commits on the current HEAD. If you want to add up stats in other branches you will have to supply them as arguments to git log.

Commercial answered 23/10, 2014 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.