@@ -130,28 +130,72 @@ namespace :docker do
130130 "#{ registry_name } /ruby"
131131 end
132132
133+ # Define a helper method to try different approaches with consistent error handling
134+ def try_fetch_hash ( method_name , &block )
135+ begin
136+ result = yield
137+ if result && !result . empty?
138+ p "Retrieved master head hash using #{ method_name } "
139+ return result
140+ else
141+ p "get_ruby_master_head_hash with #{ method_name } failed"
142+ return nil
143+ end
144+ rescue => e
145+ p "get_ruby_master_head_hash with #{ method_name } failed: #{ e . message } "
146+ return nil
147+ end
148+ end
149+
133150 def get_ruby_master_head_hash
134151 if ENV . key? ( "GITHUB_ACTION" ) && File . exist? ( cache_path = "/tmp/ruby-docker-images" )
135152 return File . read ( cache_path )
136153 end
137154
138- count = 5
139155 head_hash = nil
140156
141- loop do
142- head_hash = `curl -fs -H 'accept: application/vnd.github.v3.sha' https://api.github.com/repos/ruby/ruby/commits/master` . chomp
143- if $?. success? || count . zero?
144- break
145- else
146- p "get_ruby_master_head_hash failed: #{ head_hash . inspect } "
147- count -= 1
148- sleep 30
157+ # First attempt: Using curl
158+ head_hash = try_fetch_hash ( "curl" ) do
159+ result = `curl -fs -H 'accept: application/vnd.github.v3.sha' https://api.github.com/repos/ruby/ruby/commits/master` . chomp
160+ $?. success? && !result . empty? ? result : nil
161+ end
162+
163+ # Second attempt: Using Net::HTTP
164+ if head_hash . nil?
165+ sleep 30
166+
167+ head_hash = try_fetch_hash ( "Net::HTTP" ) do
168+ require "net/http"
169+ uri = URI . parse ( "https://api.github.com/repos/ruby/ruby/commits/master" )
170+ request = Net ::HTTP ::Get . new ( uri )
171+ request [ "accept" ] = "application/vnd.github.v3.sha"
172+ response = Net ::HTTP . start ( uri . hostname , uri . port , use_ssl : uri . scheme == "https" ) do |http |
173+ http . request ( request )
174+ end
175+
176+ response . is_a? ( Net ::HTTPSuccess ) ? response . body . chomp : nil
177+ end
178+ end
179+
180+ # Third attempt: Using GitHub CLI if available
181+ if head_hash . nil? && system ( "which gh > /dev/null 2>&1" )
182+ sleep 30
183+ head_hash = try_fetch_hash ( "GitHub CLI" ) do
184+ result = `gh api repos/ruby/ruby/commits/master --jq '.sha'` . chomp
185+ $?. success? ? result : nil
149186 end
150187 end
151188
152- if cache_path
189+ # If all methods failed, provide a meaningful error
190+ if head_hash . nil?
191+ p "Failed to retrieve Ruby master head hash using curl, Net::HTTP, and GitHub CLI"
192+ head_hash = "unknown"
193+ end
194+
195+ if defined? ( cache_path ) && cache_path
153196 File . write ( cache_path , head_hash )
154197 end
198+
155199 head_hash
156200 end
157201
0 commit comments