forked from customink/stoplight
/
provider.rb
84 lines (69 loc) · 2.77 KB
/
provider.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#
# This is a base provider that all providers must inherit from
#
require 'httparty'
require 'rack/commonlogger'
require 'uri'
# Provider is an abstract class that all providers inherit from. It requires that a specified format be returned. This way, stoplight
# doesn't care who it's talking to, as long as it guarantees certain information.
module Stoplight::Providers
class Provider
include HTTParty
require 'digest/md5'
attr_reader :options, :response
# Initializes a hash `@options` of default options
def initialize(options = {})
if options['url'].nil?
raise ArgumentError, "'url' must be supplied as an option to the Provider. Please add 'url' => '...' to your hash."
end
@options = options
# load the data
@response = load_server_data
end
# `projects` must return an array of Stoplight::Project
# see Stoplight::Project for more information on the spec
def projects
raise Stoplight::Exceptions::NoParserError.new "No projects parser provided. All Stoplight providers must provide a projects method!"
end
# The default "all builds" path for a given provider
def builds_path
@options['builds_path'] || '/'
end
protected
# Makes a request to the given server `url` and assigns an instance variable
# `@response` to the result. It only returns a string. The `result` method is
# responsible for parsing the string into a usable hash.
#
# Valid options include:
# - `path`: the URL path (after base)
# - `url_options`: additional URL options, such as querystrings
# - `method`: the HTTP method (get, post, put, etc)
def load_server_data(options = {})
url = @options['url'].chomp('/') + '/' + (options[:path] || builds_path).chomp('/').reverse.chomp('/').reverse
url_options = {}
if @options['username'] || @options['password']
url_options[:basic_auth] = {
:username => @options['username'],
:password => @options['password']
}
end
if @options['owner_name']
url_options[:query] = {
:owner_name => @options['owner_name']
}
end
url_options[:http_proxyaddr] ||= @options['http_proxyaddr']
url_options[:http_proxyport] ||= @options['http_proxyport']
url_options[:http_proxyuser] ||= @options['http_proxyuser']
url_options[:http_proxypass] ||= @options['http_proxypass']
# merge with any additional options provided
url_options.merge(options[:url_options]) if options[:url_options]
url_options.delete_if { |k,v| v.nil? }
http_method = options[:method] || 'get'
return HTTParty.send(http_method.downcase.to_sym, url, url_options)
rescue Exception => e
$logger.error "#{e.to_s}: `#{url}`"
nil
end
end
end