gh-env.sh 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. #!/usr/bin/env bash
  2. # GitHub environment detection helper for Hermes Agent skills.
  3. #
  4. # Usage (via terminal tool):
  5. # source skills/github/github-auth/scripts/gh-env.sh
  6. #
  7. # After sourcing, these variables are set:
  8. # GH_AUTH_METHOD - "gh", "curl", or "none"
  9. # GITHUB_TOKEN - personal access token (set if method is "curl")
  10. # GH_USER - GitHub username
  11. # GH_OWNER - repo owner (only if inside a git repo with a github remote)
  12. # GH_REPO - repo name (only if inside a git repo with a github remote)
  13. # GH_OWNER_REPO - owner/repo (only if inside a git repo with a github remote)
  14. # --- Auth detection ---
  15. GH_AUTH_METHOD="none"
  16. GITHUB_TOKEN="${GITHUB_TOKEN:-}"
  17. GH_USER=""
  18. if command -v gh &>/dev/null && gh auth status &>/dev/null 2>&1; then
  19. GH_AUTH_METHOD="gh"
  20. GH_USER=$(gh api user --jq '.login' 2>/dev/null)
  21. elif [ -n "$GITHUB_TOKEN" ]; then
  22. GH_AUTH_METHOD="curl"
  23. elif _hermes_env="${HERMES_HOME:-$HOME/.hermes}/.env"; [ -f "$_hermes_env" ] && grep -q "^GITHUB_TOKEN=" "$_hermes_env" 2>/dev/null; then
  24. GITHUB_TOKEN=$(grep "^GITHUB_TOKEN=" "$_hermes_env" | head -1 | cut -d= -f2 | tr -d '\n\r')
  25. if [ -n "$GITHUB_TOKEN" ]; then
  26. GH_AUTH_METHOD="curl"
  27. fi
  28. elif [ -f "$HOME/.git-credentials" ]; then
  29. GITHUB_TOKEN=$(uv run python3 "${HERMES_HOME:-$HOME/.hermes}/skills/github/github-auth/scripts/git-credential-token.py")
  30. if [ -n "$GITHUB_TOKEN" ]; then
  31. GH_AUTH_METHOD="curl"
  32. fi
  33. fi
  34. # Resolve username for curl method
  35. if [ "$GH_AUTH_METHOD" = "curl" ] && [ -z "$GH_USER" ]; then
  36. GH_USER=$(curl -s -H "Authorization: token $GITHUB_TOKEN" \
  37. https://api.github.com/user 2>/dev/null \
  38. | python3 -c "import sys,json; print(json.load(sys.stdin).get('login',''))" 2>/dev/null)
  39. fi
  40. # --- Repo detection (if inside a git repo with a GitHub remote) ---
  41. GH_OWNER=""
  42. GH_REPO=""
  43. GH_OWNER_REPO=""
  44. _remote_url=$(git remote get-url origin 2>/dev/null)
  45. if [ -n "$_remote_url" ] && echo "$_remote_url" | grep -q "github.com"; then
  46. GH_OWNER_REPO=$(echo "$_remote_url" | sed -E 's|.*github\.com[:/]||; s|\.git$||')
  47. GH_OWNER=$(echo "$GH_OWNER_REPO" | cut -d/ -f1)
  48. GH_REPO=$(echo "$GH_OWNER_REPO" | cut -d/ -f2)
  49. fi
  50. unset _remote_url
  51. # --- Summary ---
  52. echo "GitHub Auth: $GH_AUTH_METHOD"
  53. [ -n "$GH_USER" ] && echo "User: $GH_USER"
  54. [ -n "$GH_OWNER_REPO" ] && echo "Repo: $GH_OWNER_REPO"
  55. [ "$GH_AUTH_METHOD" = "none" ] && echo "⚠ Not authenticated — see github-auth skill"
  56. export GH_AUTH_METHOD GITHUB_TOKEN GH_USER GH_OWNER GH_REPO GH_OWNER_REPO