#!/usr/bin/env bash
# cleat: {"name":"GitHub Repos","keyword":"gh","icon":"arrow.triangle.branch","subtitle":"Open one of your repositories","version":"1.1.1","requires":["gh"],"examples":["gh cleat"]}
#
# Lists your GitHub repositories (needs the gh CLI, logged in) and opens the
# selected one in the browser. Type after "gh " to filter.
set -euo pipefail

if [ "${1:-}" = "--run" ]; then
    open "$2"
    exit 0
fi

if ! command -v gh >/dev/null; then
    echo "gh CLI not installed. brew install gh && gh auth login" >&2
    exit 1
fi

# The filter runs inside jq, on the name and description as plain text.
# grep on the JSON line matched its keys ("title" found every repo) and
# treated the query as a regex ("[" found none).
query="${1:-}"
escaped="${query//\\/\\\\}"
escaped="${escaped//\"/\\\"}"
gh repo list --limit 100 --json nameWithOwner,description,url \
    --jq ".[] | {title: .nameWithOwner, subtitle: (.description // \"\"), arg: .url}
          | select((.title + \" \" + .subtitle | ascii_downcase) | contains(\"$escaped\" | ascii_downcase))"
