Skip to content

Instantly share code, notes, and snippets.

@robmiller
Created October 27, 2015 12:43
Show Gist options
  • Save robmiller/c8d64cdacb1d772a707a to your computer and use it in GitHub Desktop.
Save robmiller/c8d64cdacb1d772a707a to your computer and use it in GitHub Desktop.
Clones a GitHub repository locally, and then deletes it from GitHub. Useful for cleaning up no-longer-needed private repos. Usage: archive-github OWNER REPO_NAME
#!/usr/bin/env ruby
#
# archive-github
#
# Author: Rob Miller <r@robm.me.uk>
#
# Clones a GitHub repository locally, and then deletes it from GitHub.
# Useful for cleaning up no-longer-needed private repos.
#
# Assumes you have an OAuth token stored in an environment variable
# called GITHUB_ARCHIVE_KEY. This token needs to have the "delete_repo",
# "public_repo", and "repo" privileges.
#
# Usage:
#
# GITHUB_ARCHIVE_KEY="abc123abc123" archive-github OWNER REPO_NAME
require "net/http"
require "json"
def api_response(request)
http = Net::HTTP.new("api.github.com", 443)
http.use_ssl = true
request["Accept"] = "application/vnd.github.v3+json"
request["Authorization"] = "token #{API_KEY}"
response = http.request(request)
unless response.is_a?(Net::HTTPSuccess)
$stderr.puts "API request to GitHub failed"
exit 10
end
if response.body
JSON.parse(response.body)
else
true
end
end
API_KEY = ENV.fetch("GITHUB_ARCHIVE_KEY").freeze
unless API_KEY.length > 0
$stderr.puts "Environment variable GITHUB_ARCHIVE_KEY must be set"
exit 1
end
owner, slug = ARGV[0], ARGV[1]
unless owner && slug
$stderr.puts "Usage: #{$0} OWNER REPOSITORY"
exit 2
end
puts "Looking up repository on GitHub..."
request = Net::HTTP::Get.new("/repos/#{owner}/#{slug}")
repo_info = api_response(request)
puts "Cloning repository..."
fork do
exec "git", "clone", repo_info["ssh_url"]
end
Process.wait
unless $?.success?
$stderr.puts "Couldn't clone the repo"
exit 3
end
puts "Deleting repository from GitHub..."
request = Net::HTTP::Delete.new("/repos/#{owner}/#{slug}")
api_response(request)
puts "Done."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment