#!/bin/sh
#
# ---
# see: https://github.com/dandavison/tools/blob/main/bash/rg-blame

exists_in_git() {
  git ls-tree -r HEAD -- "$1" | rg . >/dev/null
}

# TODO: blame --show-name and add delta handling

rg --json "$@" \
  | jq --raw-output 'select(.type == "match") | .data.path.text + ":" + (.data.line_number | tostring)' \
  | while IFS=: read -r file line; do
    exists_in_git "${file}" && git blame -L "${line}","${line}" "${file}"
  done \
  | rg -r '$1 $0' '.+(20[12][0-9]-[01][0-9]-[123][0-9]).+' \
  | sort -k 1 \
  | cut -d ' ' -f 2- \
  | delta
