#!/bin/sh
###########################################################################
# git-whodaman 2024-07-13-aa51e6d
# (https://www.fabiankeil.de/gehacktes/git-whodaman/)
#
# Subcommand for git to figure out who "da man" is. Obviously "da man"
# is the human who made the most commits. The type of human is gathered
# from the script name so you can symlink the script to git-whodafemale
# or git-whodamaster etc. if you're gathering statistics for a
# repository where this is more appropriate.
#
# Copyright (c) 2013-2024 Fabian Keil <fk@fabiankeil.de>
#
# Permission to use, copy, modify, and distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
############################################################################

get_commit_stats() {
    local branch="${1}"

    export LC_ALL=C

    git shortlog -sn $branch | awk '
    {
        # XXX: Kinda dumb way to build the name
        name = $2" "$3" "$4" "$5
        commits[name] = $1;
        total += $1;
    } 
    END {
        for (committer in commits) {
            c = commits[committer];
            print c " " c / total * 100 "% " total " " committer;
        }
     }' | sort -r -n
}

branch_exists() {
    local branch="${1}"
    git show-ref --quiet "refs/heads/${branch}"
}

who_da_man() {
    local branch \
          da_man commiter_rank type_of_human

    if [ -z "$1" ]; then
        if branch_exists "master"; then
            branch="master"
        else
            branch="main"
        fi
    else
        branch="${1}"
    fi

    if ! branch_exists "${branch}"; then
        echo "Branch '${branch}' does not exist"
        exit 1
    fi

    type_of_human=${0#*git-whoda}

    commiter_rank=0
    get_commit_stats $branch | while read commits percentage commits_total name; do
        if [ -z "$da_man" ]; then
            da_man=$name;
            printf "%s is da ${type_of_human} (branch: %s; commits in branch: $commits_total)\n\n" "$name" "$branch"
        fi
        commiter_rank=$((commiter_rank+1))
        printf "%4d %s made %s commits (%s).\n" "${commiter_rank}" "${name}" "${commits}" "$percentage"
    done
}

main() {
    who_da_man $1
}

main $1
