Skip to content

Instantly share code, notes, and snippets.

@logandk
Created June 11, 2009 13:02
Show Gist options
  • Save logandk/127880 to your computer and use it in GitHub Desktop.
Save logandk/127880 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
#
# GitHub raw file download
# -------------------------------
# Provides a "get_blob" method for downloading the raw contents of a
# file in a GitHub repository. Useful in cases where only the Ruby core
# is available (i.e. for setting up new EC2 instances automatically)
#
# Usage:
# data = get_blob("user", "repository", "/path/to/file")
#
# -------------------------------
# Written by Logan Raarup (http://github.com/logandk)
# Released under the MIT license, 2009
require 'yaml'
require 'pathname'
require 'net/http'
require 'net/https'
# Configuration settings
HOSTNAME = "github.com"
USERNAME = "" # GitHub Username
API_TOKEN = "" # GitHub API Token
def api_request(url)
$transport ||= Net::HTTP.new(HOSTNAME, URI::HTTPS::DEFAULT_PORT)
$transport.use_ssl = true
req = Net::HTTP::Post.new(url)
req.set_form_data({ :login => USERNAME, :token => API_TOKEN }, '&')
response = $transport.request(req)
data = YAML::load(response.body)
end
def get_blob(user, repo, path)
data = api_request("/api/v2/yaml/commits/list/#{user}/#{repo}/master")
tree_sha = data['commits'].first['tree']
path = Pathname.new(path)
path.each_filename do |segment|
if segment == path.basename.to_s
data = api_request("/api/v2/yaml/blob/show/#{user}/#{repo}/#{tree_sha}/#{segment}")
return data['blob']['data']
else
data = api_request("/api/v2/yaml/tree/show/#{user}/#{repo}/#{tree_sha}")
tree_sha = data['tree'].select { |tree| tree['name'] == segment }.first['sha']
end
end
return nil
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment