#!/bin/bash

# eslintblame
# Parse eslint output into git-blame to unveil the offenders

# Store eslint report from stdin
report=$(cat)
# Get list of files with errors
files=$(echo "$report" | grep "$PWD")
while read -r file
do
    # Escape slashes from file paths to use inside sed regular expression
    escaped=$(echo "$file" | sed -e 's#/#\\\/#g')
    # Extract text, from file path to next empty line with sed (inclusive)
    # and then remove file path and empty line with head and tail
    errors=$(echo "$report" | sed -n -e "/$escaped/,/^\s*$/p" | head -n -1 | tail -n +2)
    # Print out filename
    echo "$file"
    # For each error in a given file, print the error with its author
    while read -r error
    do
        # Get error line number to be passed to git blame
        line=$(echo "$error" | cut -d : -f 1 | sed 's/\s//g')
        # Store git blame result
        blame=$(git blame --porcelain -L "$line","$line" -- "$file")
        # Extract commit hash
        shasum=$(echo "$blame" | head -1 | cut -d ' ' -f 1)
        # Extract commit author
        author=$(echo "$blame" | grep 'author ' | cut -d ' ' -f2-)
        # Print eslint error, using a tab to align with next line
        printf "\t%s\n" "$(echo "$error" | sed 's/^\s*//')"
        # Then print commit hash and author
        printf "\t%s\t%s\n\n" "$shasum" "$author"
    done < <(echo "$errors")
    echo
done < <(echo "$files")
