#!/usr/bin/env python3

import subprocess
import sys
import os

from typing import List, Dict, Any

DataLine = Dict[Any, Any]


def grab_blame_data() -> List[DataLine]:
    p = subprocess.check_output(
        ["git", "blame", "--line-porcelain"] + sys.argv[1:],
        encoding='utf-8',
    )
    data = []
    cur = {}
    p = str(p)
    in_segment = False
    for line in p.splitlines():
        l = line.rstrip()
        if len(l) == 0:
            continue
        if l[0] == '\t':
            cur["data"] = l[1:]
            data.append(cur)
            cur = {}
            in_segment = False
            continue
        d = l.split()
        if not in_segment:
            cur["sha"] = d[0]
            cur["sha8"] = d[0][:8]
            in_segment = True
        else:
            cur[d[0]] = " ".join(d[1:])

    assert in_segment is False
    return data


FIELDS = ["sha8", "author", "summary", "data"]


def main() -> None:
    d = grab_blame_data()
    lens = {}
    for f in FIELDS:
        maxn = 0
        for x in d:
            if len(x[f]) > maxn:
                maxn = len(x[f])
        lens[f] = maxn
    for x in d:
        s = ""
        for f in FIELDS:
            s = s + x[f].ljust(lens[f]) + ' '
        print(s)


if __name__ == "__main__":
    main()
