#!/usr/bin/env bash
# Patronus AI: repository facts. Read-only. Point it at one repository, or at a folder that holds several:
#   bash repo-facts.sh /path/to/repo > repo-facts.csv
#   bash repo-facts.sh /path/to/folder-of-repos > repo-facts.csv
# With no path it uses the current folder. Prints a header and one line per repository: size, history, team, tests.
# It reads git history and file contents locally and runs nothing from the repository. Nothing is uploaded; send us the CSV.
echo "repo,source_lines,commits,merged_prs,contributors,first_commit,last_commit,years,test_files,ci,languages,root_commit"
SKIP='node_modules/|vendor/|dist/|build/|\.min\.|\.lock$|package-lock|yarn\.lock|\.(png|jpg|jpeg|gif|svg|ico|pdf|zip|gz|bin|woff2?|ttf|mp4|csv|json|md|txt)$'

facts() {
  (
  cd "$1" || exit 0
  name=$(basename "$(pwd)")
  commits=$(git rev-list --count HEAD 2>/dev/null || echo 0)
  # GitHub "Merge pull request", Bitbucket "Merged in … (pull request #n)", squash "(#n)", GitLab "See merge request group/project!n"
  prs=$(git log --format=%B 2>/dev/null | grep -ciE "merge pull request|merged in .*pull request|\(#[0-9]+\)$|see merge request"); prs=${prs:-0}
  contributors=$(git shortlog -sne HEAD 2>/dev/null | wc -l | tr -d ' ')
  first=$(git log --reverse --format=%ad --date=short 2>/dev/null | head -1)
  last=$(git log -1 --format=%ad --date=short 2>/dev/null)
  years=$(FIRST="$first" LAST="$last" python3 -c "import os;from datetime import date;a,b=os.environ['FIRST'],os.environ['LAST'];print(round((date.fromisoformat(b)-date.fromisoformat(a)).days/365.25,1) if a and b else 0)" 2>/dev/null || echo 0)
  files=$(git ls-files 2>/dev/null)
  # File names are passed as data (NUL-separated), never through a shell.
  src=$(git ls-files -z 2>/dev/null | tr '\0' '\n' | grep -viE "$SKIP" | tr '\n' '\0' | xargs -0 cat -- 2>/dev/null | wc -l | tr -d ' ')
  tests=$(echo "$files" | grep -ciE "(^|/)(tests?|spec|__tests__)/|[._-](test|spec)\.[a-z]+$"); tests=${tests:-0}
  ci=$(echo "$files" | grep -qiE "^\.github/workflows/|^\.gitlab-ci|^Jenkinsfile|^\.circleci/|azure-pipelines|^bitbucket-pipelines" && echo yes || echo no)
  langs=$(echo "$files" | grep -oE "\.[A-Za-z0-9]+$" | grep -viE "\.(md|txt|json|lock|yml|yaml|png|jpg|svg|csv)$" | sort | uniq -c | sort -rn | head -4 | awk '{printf "%s:%s ", $2, $1}')
  root=$(git rev-list --max-parents=0 HEAD 2>/dev/null | tail -1)
  echo "${name//,/ },$src,$commits,$prs,$contributors,$first,$last,$years,$tests,$ci,$langs,$root"
  )
}

for target in "${@:-.}"; do
  if [ -e "$target/.git" ]; then
    facts "$target"
  else
    for d in "$target"/*/; do
      [ -e "$d/.git" ] && facts "$d"
    done
  fi
done
