From 5d13491c326c7c1554cb26f6bac90edd2a2c829a Mon Sep 17 00:00:00 2001 From: Garrett LeSage Date: Wed, 9 Aug 2023 12:10:52 +0200 Subject: [PATCH] scripts: Handle redirects in image URLs --- _scripts/generate-release-notes.rb | 31 ++++++++++++++++++------------ 1 file changed, 19 insertions(+), 12 deletions(-) diff --git a/_scripts/generate-release-notes.rb b/_scripts/generate-release-notes.rb index 1a54cd1d..0ecb56d0 100755 --- a/_scripts/generate-release-notes.rb +++ b/_scripts/generate-release-notes.rb @@ -178,19 +178,26 @@ def build_frontmatter }.to_yaml.gsub(/^:/, '') end -# Download the image from GitHub and save locally -def download_image(url, basename) - extension = url.split('.').last - filename = "#{basename}.#{extension}" - - # Download and save file - image = Net::HTTP.get(URI(url)) - File.write("images/#{filename}", image) - - @files_images.push("images/#{filename}") +# Download the image from a GitHub and save locally +def download_image(url, basename, limit = 3) + raise ArgumentError, 'too many HTTP redirects' if limit == 0 + + uri = URI(url) + response = Net::HTTP.get_response(uri) + + case response + when Net::HTTPRedirection + new_url = response['location'] + download_image(new_url, basename, limit - 1) + when Net::HTTPSuccess + extension = File.extname(uri.path) + local_file = "#{basename}#{extension}" + File.write("images/#{local_file}", response.body) + @files_images << local_file + end - # Return filename (with extension) - filename +rescue StandardError => e + warn "Error downloading the image: #{e.message}" end def process_images(notes)