#!/usr/bin/env bash # Exit on error. Append "|| true" if you expect an error. set -o errexit # Exit on error inside any functions or subshells. set -o errtrace # Do not allow use of undefined vars. Use ${VAR:-} to use an undefined VAR set -o nounset # Catch the error in case mysqldump fails (but gzip succeeds) in `mysqldump |gzip` set -o pipefail # Try to get PAT from environment first pat="${GITHUB_PERSONAL_ACCESS_TOKEN:-}" # If not in environment, try to get from GitHub CLI if [[ -z "${pat}" ]] || [[ "${#pat}" -lt 30 ]]; then if command -v gh &> /dev/null; then if gh auth status &> /dev/null; then pat=$(gh auth token) if [[ -n "${pat}" ]] && [[ "${#pat}" -gt 30 ]]; then # Save the token to .env file if it's valid ENV_FILE="/workspaces/finance/.devcontainer/.env" echo "# GitHub Finance Devcontainer Configuration" > "${ENV_FILE}" echo "GITHUB_PERSONAL_ACCESS_TOKEN=${pat}" >> "${ENV_FILE}" chmod 600 "${ENV_FILE}" fi fi fi fi # If still not found, try .env file if [[ -z "${pat}" ]] || [[ "${#pat}" -lt 30 ]]; then ENV_FILE="/workspaces/finance/.devcontainer/.env" if [[ -f "${ENV_FILE}" ]]; then # Try to extract PAT from .env file env_pat=$(grep -E '^GITHUB_PERSONAL_ACCESS_TOKEN=.+' "${ENV_FILE}" | cut -d'=' -f2-) # Clean up the extracted PAT env_pat="${env_pat#\"}" env_pat="${env_pat%\"}" env_pat="${env_pat#\'}" env_pat="${env_pat%\'}" env_pat="${env_pat%%[[:space:]]}" env_pat="${env_pat##[[:space:]]}" if [[ -n "${env_pat}" ]] && [[ "${#env_pat}" -gt 30 ]]; then pat="${env_pat}" fi fi fi # Export the PAT if valid if [[ -n "${pat}" ]] && [[ "${#pat}" -gt 30 ]]; then export GITHUB_PERSONAL_ACCESS_TOKEN="${pat}" echo "GitHub Personal Access Token loaded successfully" # Use return instead of exit when script is sourced if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then return 0 else exit 0 fi else echo >&2 "ERROR: Could not find valid GitHub Personal Access Token" # Use return instead of exit when script is sourced if [[ "${BASH_SOURCE[0]}" != "${0}" ]]; then return 1 else exit 1 fi fi