2018-06-25 20:06:10 +00:00
|
|
|
module BitbucketServer
|
|
|
|
class Connection
|
2018-07-05 21:09:01 +00:00
|
|
|
include ActionView::Helpers::SanitizeHelper
|
|
|
|
|
2018-06-25 20:06:10 +00:00
|
|
|
DEFAULT_API_VERSION = '1.0'.freeze
|
|
|
|
|
|
|
|
attr_reader :api_version, :base_uri, :username, :token
|
|
|
|
|
2018-07-13 05:33:36 +00:00
|
|
|
ConnectionError = Class.new(StandardError)
|
|
|
|
|
2018-06-25 20:06:10 +00:00
|
|
|
def initialize(options = {})
|
|
|
|
@api_version = options.fetch(:api_version, DEFAULT_API_VERSION)
|
|
|
|
@base_uri = options[:base_uri]
|
2018-07-01 12:13:15 +00:00
|
|
|
@username = options[:user]
|
2018-06-26 05:40:11 +00:00
|
|
|
@token = options[:password]
|
2018-06-25 20:06:10 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def get(path, extra_query = {})
|
|
|
|
response = Gitlab::HTTP.get(build_url(path),
|
|
|
|
basic_auth: auth,
|
2018-07-06 04:11:16 +00:00
|
|
|
query: extra_query)
|
2018-07-05 21:09:01 +00:00
|
|
|
|
|
|
|
check_errors!(response)
|
2018-07-13 05:33:36 +00:00
|
|
|
|
2018-06-25 20:06:10 +00:00
|
|
|
response.parsed_response
|
|
|
|
end
|
|
|
|
|
2018-07-03 23:37:17 +00:00
|
|
|
def post(path, body)
|
2018-07-05 21:09:01 +00:00
|
|
|
response = Gitlab::HTTP.post(build_url(path),
|
2018-07-03 23:37:17 +00:00
|
|
|
basic_auth: auth,
|
|
|
|
headers: post_headers,
|
|
|
|
body: body)
|
2018-07-05 21:09:01 +00:00
|
|
|
|
|
|
|
check_errors!(response)
|
2018-07-13 05:33:36 +00:00
|
|
|
|
2018-07-13 06:17:05 +00:00
|
|
|
response.parsed_response
|
2018-07-03 23:37:17 +00:00
|
|
|
end
|
|
|
|
|
2018-06-25 20:06:10 +00:00
|
|
|
private
|
|
|
|
|
2018-07-05 21:09:01 +00:00
|
|
|
def check_errors!(response)
|
2018-07-13 06:17:05 +00:00
|
|
|
return if response.code == 200
|
|
|
|
|
|
|
|
details =
|
|
|
|
if response.parsed_response && response.parsed_response.is_a?(Hash)
|
|
|
|
sanitize(response.parsed_response.dig('errors', 0, 'message'))
|
|
|
|
end
|
|
|
|
|
|
|
|
message = "Error #{response.code}"
|
|
|
|
message += ": #{details}" if details
|
|
|
|
raise ConnectionError, message
|
2018-07-05 21:09:01 +00:00
|
|
|
end
|
|
|
|
|
2018-07-03 23:37:17 +00:00
|
|
|
def auth
|
|
|
|
@auth ||= { username: username, password: token }
|
|
|
|
end
|
|
|
|
|
|
|
|
def post_headers
|
|
|
|
@post_headers ||= { 'Content-Type' => 'application/json' }
|
|
|
|
end
|
|
|
|
|
2018-06-25 20:06:10 +00:00
|
|
|
def build_url(path)
|
|
|
|
return path if path.starts_with?(root_url)
|
|
|
|
|
|
|
|
"#{root_url}#{path}"
|
|
|
|
end
|
|
|
|
|
|
|
|
def root_url
|
|
|
|
"#{base_uri}/rest/api/#{api_version}"
|
|
|
|
end
|
|
|
|
end
|
|
|
|
end
|