Created
February 24, 2016 20:39
-
-
Save ivarvong/ce0fdd50cf7561753fcb to your computer and use it in GitHub Desktop.
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
# https://confluence.atlassian.com/bitbucket/repository-resource-423626331.html | |
class BitbucketAPI | |
include HTTParty | |
base_uri 'https://api.bitbucket.org/2.0' | |
attr_reader :access_token | |
attr_reader :repo | |
attr_reader :owner | |
def initialize(repo: nil) | |
get_access_token | |
@repo = repo | |
@owner = ENV['OWNER'] | |
end | |
def headers | |
{ | |
"Authorization" => "Bearer #{access_token}", | |
"Accept" => "application/json" | |
} | |
end | |
def get_access_token | |
response = HTTParty.post( | |
"https://bitbucket.org/site/oauth2/access_token", | |
basic_auth: { | |
username: ENV['CLIENT_ID'], | |
password: ENV['CLIENT_SECRET'] | |
}, | |
body: { | |
grant_type: 'client_credentials' | |
} | |
) | |
data = JSON.parse(response.body) | |
@access_token = data['access_token'] | |
end | |
def repos | |
get("/repositories/#{owner}?sort=-updated_on")['values'] | |
end | |
def summary | |
get("/repositories/#{owner}/#{repo}")['values'] | |
end | |
def commits | |
get("/repositories/#{owner}/#{repo}/commits")['values'] | |
end | |
def commit revision | |
get "/repositories/#{owner}/#{repo}/commit/#{revision}" | |
end | |
def download revision | |
file = File.join(Rails.root, 'tmp', "#{repo}-#{revision}.zip") | |
url = "https://bitbucket.org/#{owner}/#{repo}/get/#{revision}.zip" | |
auth = "-H 'Authorization: Bearer #{access_token}'" | |
command =[ | |
"curl -s -L #{auth} -o '#{file}' #{url}", | |
"unzip -o '#{file}'" | |
].join(" && ") | |
logs = `#{command}` | |
return { | |
file: file, | |
logs: logs | |
} | |
end | |
private | |
def get path | |
puts "GET #{path}" | |
raw = self.class.get(path, headers: headers).body | |
puts "raw: #{raw}" | |
JSON.parse(raw) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment