Last active
May 11, 2017 14:47
-
-
Save sardemff7/8770751 to your computer and use it in GitHub Desktop.
GitHub WebHook trivial implementation in Bash
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #! /bin/bash | |
| pusher=${GL_USER:-${USER:-git}} | |
| repository=${GL_REPO} | |
| if [[ -z "${repository}" ]]; then | |
| repository=$(basename ${PWD}) | |
| [[ ${repository} == ".git" ]] && repository=$(basename $(dirname ${PWD})) | |
| fi | |
| repository_url_format="$(git config --get webhook.repository-url)" | |
| branch_url_format="$(git config --get webhook.branch-url)" | |
| commit_url_format="$(git config --get webhook.commit-url)" | |
| diff_url_format="$(git config --get webhook.diff-url)" | |
| post_url="$(git config --get webhook.post-url)" | |
| file=/tmp/.webhook-${repository} | |
| printf -v commit_url_format "\"url\":\"${commit_url_format}\"" ${repository} '%H' | |
| commit_format='{' | |
| commit_format+='"author":{"email":"%aE","name":"%aN"},' | |
| commit_format+='"id":"%H","message":"%s",' | |
| commit_format+="${commit_url_format}" | |
| commit_format+='}' | |
| function handle_ref() { | |
| local before=$1 after=$2 ref=$3 list diff_url | |
| case "${ref}" in | |
| refs/heads/*) | |
| branch=${ref#refs/heads/} | |
| event=push | |
| created=false | |
| deleted=false | |
| if [[ ${before} == 0000000000000000000000000000000000000000 ]]; then | |
| created=true | |
| list=${after} | |
| elif [[ ${after} == 0000000000000000000000000000000000000000 ]]; then | |
| deleted=true | |
| list=${before}~1..${before} | |
| else | |
| list=${before}..${after} | |
| fi | |
| printf -v repository_url "${repository_url_format}" ${repository} | |
| printf -v diff_url "${diff_url_format}" ${repository} ${before} ${after} | |
| { | |
| echo -n '{' | |
| echo -n '"commits":[' | |
| git log --pretty="format:${commit_format}" ${list} | tr '\n' ',' | |
| echo -n '],' | |
| printf '"compare":"%s",' "${diff_url}" | |
| printf '"pusher":{"name":"%s"},"sender":{"login":"%s","url":"https://api.github.com/users/%s"},' "${pusher}" "${pusher}" "${pusher}" | |
| printf '"ref":"%s","created":%s,"deleted":%s,' "${ref}" "${created}" "${deleted}" | |
| printf '"repository":{"name":"%s","url":"%s"}' "${repository}" "${repository_url}" | |
| echo -n '}' | |
| } > ${file} | |
| ;; | |
| refs/tags/*) | |
| return | |
| ;; | |
| *) return ;; | |
| esac | |
| curl --silent --user-agent 'GitHub-Hookshot/stub' -H "X-GitHub-Event: ${event}" --request POST --data-urlencode payload@${file} "${post_url}" | |
| cat ${file} | |
| rm -f ${file} | |
| } | |
| while read line; do | |
| handle_ref $line | |
| done | |
| exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment