|
| 1 | +# Hook example for notifying an administrator in a repository by creating an issue when a repository is deleted. |
| 2 | +# |
| 3 | +# Needs the following environment variables |
| 4 | +# GITHUB_HOST - the domain of the GitHub Enterprise instance. e.g. github.example.com |
| 5 | +# GITHUB_API_TOKEN - a Personal Access Token that has the ability to create an issue in the notification repository. |
| 6 | +# GITHUB_NOTIFICATION_REPOSITORY - the repository in which to create the nofication issue. e.g. |
| 7 | +# |
| 8 | +# Dependencies: |
| 9 | +# octokit - https://github.com/octokit/octokit.rb |
| 10 | +# sinatrarb - http://www.sinatrarb.com/ |
| 11 | + |
| 12 | +require 'octokit' |
| 13 | +require 'sinatra' |
| 14 | +require 'json' |
| 15 | + |
| 16 | +enable :logging |
| 17 | +github_api_token = ENV['GITHUB_API_TOKEN'] |
| 18 | +github_notification_repository = ENV['GITHUB_NOTIFICATION_REPOSITORY'] |
| 19 | +github_host_fqdn = ENV['GITHUB_HOST'] |
| 20 | +github_api_endpoint = "https://#{github_host_fqdn}/api/v3" |
| 21 | + |
| 22 | +Octokit.configure do |c| |
| 23 | + c.api_endpoint = github_api_endpoint |
| 24 | + c.access_token = github_api_token |
| 25 | +end |
| 26 | + |
| 27 | +# Needed so that the webhook setup passes |
| 28 | +post '/' do |
| 29 | + 200 |
| 30 | +end |
| 31 | + |
| 32 | +# When receiving a webhook for repository deletion (https://developer.github.com/v3/activity/events/types/#repositoryevent) |
| 33 | +# create an issue in the `github_notification_repository` set by environment variable |
| 34 | +post '/delete-repository-event' do |
| 35 | + begin |
| 36 | + github_event = request.env['HTTP_X_GITHUB_EVENT'] |
| 37 | + if github_event == "repository" |
| 38 | + request.body.rewind |
| 39 | + parsed = JSON.parse(request.body.read) |
| 40 | + action = parsed['action'] |
| 41 | + |
| 42 | + if action == 'deleted' |
| 43 | + # create a new issue in the repository configured above |
| 44 | + full_name = parsed['repository']['full_name'] |
| 45 | + purgatory_link = "https://#{github_host_fqdn}/stafftools/users/#{parsed['repository']['owner']['login']}/purgatory" |
| 46 | + client = Octokit::Client.new |
| 47 | + client.create_issue(github_notification_repository, "Repository deleted: #{full_name}", "[Restore the repository](#{purgatory_link})\n```json\n#{JSON.pretty_generate(parsed)}\n```") |
| 48 | + |
| 49 | + return 201,"Repository deleted: #{full_name}, notification created in #{github_notification_repository}" |
| 50 | + end |
| 51 | + end |
| 52 | + return 418, "No such teapot" |
| 53 | + rescue => e |
| 54 | + status 500 |
| 55 | + "exception encountered #{e}" |
| 56 | + end |
| 57 | +end |
0 commit comments