.sh
Shell
(text/x-sh)
#!/bin/bash
set -euo pipefail

GIT_DIR="$(git rev-parse --git-dir 2>/dev/null || echo .)"

# try to get pusher info from environment (SSH/HTTP vary)
PUSHER="${GIT_AUTHOR_NAME:-${USER:-unknown}}"
PUSHER_EMAIL="${GIT_AUTHOR_EMAIL:-}"

timestamp() { date -u +"%Y-%m-%dT%H:%M:%SZ"; }

while read -r old new ref; do
  # determine ref type
  if [[ "$ref" == refs/heads/* ]]; then
    ref_type="branch"
    ref_name="${ref#refs/heads/}"
  elif [[ "$ref" == refs/tags/* ]]; then
    ref_type="tag"
    ref_name="${ref#refs/tags/}"
  else
    ref_type="other"
    ref_name="$ref"
  fi

  # commit info (may be empty on deletes where new == 0000000...)
  if [[ "$new" =~ ^0+$ ]]; then
    commit_sha=""
  else
    commit_sha="$new"
  fi

  # collect more details where available
  repo_path="$(pwd)"
  repo_name="$(basename "$repo_path" .git)"
  org_name="$(basename "$(dirname "$repo_path")")"
  pusher_ip="${SSH_CONNECTION%% *}" || pusher_ip=""

  payload_args=(
    "--repo" "$org_name/$repo_name"
    "--ref" "$ref"
    "--ref-type" "$ref_type"
    "--ref-name" "$ref_name"
    "--old" "$old"
    "--new" "$new"
    "--commit" "$commit_sha"
    "--pusher" "$PUSHER"
    "--pusher-email" "$PUSHER_EMAIL"
    "--pusher-ip" "$pusher_ip"
    "--git-dir" "$GIT_DIR"
    "--timestamp" "$(timestamp)"
  )

  # call asynchronously so push isn't blocked
  # echo "gitfoss-ci-runner trigger \"${payload_args[@]}\"\n"
  # echo "gitfoss-ci-runner trigger \"${payload_args[@]}\"\n" >> /var/log/gitfoss/ci.log
  # /usr/bin/gitfoss-ci-runner trigger "${payload_args[@]}";

  # Minimal safe post-receive snippet: build JSON from payload_args array and POST with curl
  # Requires: bash, curl, jq (jq recommended for correctness)
  CI_HOST="https://gitfoss.dev"
  AUTH_TOKEN="REPLACE_WITH_TOKEN"
  ORG="${org_name:-org}"
  repo_name="${repo_name%.git}"
  REPO="${repo_name:-repo}"

  # payload_args is assumed to be an array like:
  # payload_args=( "--repo" "org/repo" "--ref" "refs/heads/main" "--ref-type" "branch" ... )

  # Build JSON robustly using jq
  json=$(
    # convert --key value pairs into null-separated key and value list, then jq to object
    printf '%s\n' "${payload_args[@]}" |
      awk 'NR%2{key=$0; getline; val=$0; sub(/^--/,"",key); printf "%s\0%s\0", key, val}' |
      jq -Rn '
        [inputs | split("\u0000")[]] as $a |
        ($a | length) as $n |
        reduce range(0; $n/2 | floor) as $i ({}; . + { ($a[$i*2]) : $a[$i*2+1] })
      '
  )

  # POST to endpoint
  curl -s -X POST "${CI_HOST}/${ORG}/${REPO}/pipelines/trigger" \
    -H "Authorization: Bearer ${AUTH_TOKEN}" \
    -H "Content-Type: application/json" \
    -d "$json"

done

exit 0