module GitHubRepoDeleter

Don’t use this. Apparently you can delete them with the v2 API.

A simple module with a single method, GitHubRepoDeleter.delete_repo

Use this if you need to programatically delete a GitHub repository, since that functionality is not yet exposed through their API. This module uses RestClient to make the requests, and it handles the details of the session cookies and XSRF/CSRF protection for you. It took me enough time to work out the details that I hope maybe this saves someone else the trouble some day.

Example:

GitHubRepoDeleter.delete_repo('yourgithubusername', 'yourgithubpassword',
                              'nameofrepotodelete')
#=> true

Because this relies on “faking” a web browser, it could stop working any time GitHub makes changes to their website. I wouldn’t use this in any production context.

Also, THIS DELETES THE REPOSITORY FROM GITHUB! USE AT YOUR OWN RISK. I AM NOT RESPONSIBLE IF YOU DO SOMETHING STUPID.

Public Class Methods

delete_repo(login, password, repo_name) click to toggle source
# File lib/github_repo_deleter.rb, line 28
def delete_repo(login, password, repo_name)
  raise "Don't use this. Use the GitHub V2 API instead. :-("
  cookies = {}
  auth_token = get_with_cookies('https://github.com/login', cookies)
  post_with_cookies('https://github.com/session',
                    {:login => login,
                     :password => password,
                     :commit => 'Log in',
                     :authenticity_token => auth_token},
                    cookies)
  repo_admin_url = "https://github.com/#{login}/#{repo_name}/admin"
  auth_token = get_with_cookies(repo_admin_url, cookies)
  post_with_cookies(repo_admin_url + '/delete',
                    {:_method => 'delete', :authenticity_token => auth_token},
                    cookies)
  return true
end

Private Class Methods

get_with_cookies(url, cookies) click to toggle source
# File lib/github_repo_deleter.rb, line 48
def get_with_cookies(url, cookies)
  response = RestClient.get(url, :cookies => cookies)
  cookies.merge!(response.cookies)
  parse_auth_token(response.body)
end
parse_auth_token(html) click to toggle source
# File lib/github_repo_deleter.rb, line 64
def parse_auth_token(html)
  doc = Nokogiri::HTML(html)
  element = doc.xpath('.//input[@name="authenticity_token"]').first
  element.attribute('value').value
end
post_with_cookies(url, params, cookies) click to toggle source
# File lib/github_repo_deleter.rb, line 54
def post_with_cookies(url, params, cookies)
  RestClient.post(url, params, :cookies => cookies) do |response, &block|
    if (200..399).include? response.code
      cookies.merge!(response.cookies)
    else
      response.return! &block
    end
  end
end