Skip to content

Commit 8b0200e

Browse files
frsyukik0kubun
authored andcommitted
Follow redirects during downloading
This change is optional as long as the repository is kept at sqldef/sqldef and GitHub doesn't change how it redirects but works as a nice safeguard.
1 parent c27bfa2 commit 8b0200e

File tree

1 file changed

+11
-9
lines changed

1 file changed

+11
-9
lines changed

lib/sqldef.rb

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -88,9 +88,7 @@ def download(command)
8888

8989
print("Downloading '#{command}' under '#{bin}'... ")
9090
url = build_url(command)
91-
resp = get(url, code: 302) # Latest
92-
resp = get(resp['location'], code: 302) # vX.Y.Z
93-
resp = get(resp['location'], code: 200) # Binary
91+
resp = get(url, code: 200, max_retries: 4)
9492

9593
if url.end_with?('.zip')
9694
Zip::File.open_buffer(resp.body) do |zip|
@@ -134,15 +132,19 @@ def build_url(command)
134132
end
135133

136134
# TODO: Retry transient errors
137-
def get(url, code: nil)
135+
def get(url, code: nil, max_retries:)
138136
uri = URI.parse(url)
139-
Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
137+
resp = Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https') do |http|
140138
http.get("#{uri.path}?#{uri.query}")
141-
end.tap do |resp|
142-
if code && resp.code != code.to_s
143-
raise "Expected '#{url}' to return #{code}, but got #{resp.code}: #{resp.body}"
144-
end
145139
end
140+
if resp.is_a?(Net::HTTPRedirection) && max_retries > 0
141+
# Follow redirects that lead to the current repository (if sqldef/sqldef is moved),
142+
# Latest, vX.Y.Z, and to the binary
143+
return get(resp['location'], code: code, max_retries: max_retries - 1)
144+
elsif code && resp.code != code.to_s
145+
raise "Expected '#{url}' to return #{code}, but got #{resp.code}: #{resp.body}"
146+
end
147+
resp
146148
end
147149
end
148150
end

0 commit comments

Comments
 (0)