#!/usr/bin/env zsh

local filename="$1"

if [ -z "$filename" ]; then
    echo "Usage: get_coverage_totals <index.html> # from the root of an llvm-cov HTML report"
    return 1
fi

# Print the start of the JSON array
echo "["
first_entry=0
git log --follow --pretty=format:"%H|%aI" "$filename" | while IFS='|' read -r commit_hash commit_date; do
    git ls-tree -r --name-only "$commit_hash" | grep -q "$filename" && index_html="$(git show $commit_hash:$filename)" || continue
    if [ $first_entry -eq 0 ]; then; first_entry=1; else; echo "," ;fi
    json_object=$( pup 'tr:last-child pre json{}' <<<"$index_html" )
    echo $json_object | jq -r ".[1:4] | map(.text) | {\"fn\": .[0], \"line\": .[1], \"region\": .[2], \"commit\": \"$commit_hash\", \"datetime\": \"$commit_date\"}"
done

# Print the end of the JSON array
echo "]"
