Skip to content

Instantly share code, notes, and snippets.

@wheresalice
Created January 25, 2013 17:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wheresalice/4636196 to your computer and use it in GitHub Desktop.
Save wheresalice/4636196 to your computer and use it in GitHub Desktop.
require 'net/http'
require 'json'
# We could just use localhost, but it's nice to print usable urls in debug
@jenkins = `hostname`.strip
# Get the list of jobs on the Jenkins instance
res = Net::HTTP.get_response(URI('http://'+@jenkins+'/api/json'))
jobs = JSON.parse(res.body)['jobs']
# Iterate through the jobs finding the first and last jobs
jobs.each do |job|
res = Net::HTTP.get_response(URI(job['url']+'api/json'))
data = JSON.parse(res.body)
if data['upstreamProjects'] == []
@first_project = job['url']
elsif data['downstreamProjects'] == []
@last_project = job['url']
@last_green_job = data['lastSuccessfulBuild']['url']
end
end
#puts 'Last green job was ' + @last_green_job
# @param [String] url url of a green job
# @return [Object] git sha1 hash of the the last successful pipeline build (or false if there isn't one)
def get_sha_or_false(url)
res = Net::HTTP.get_response(URI(url+'api/json'))
# Sometimes we might reference builds which Jenkins has archived off
# Return false if this is the case
if res.code != '200'
false
else
# If this has git revision numbers then use them
data = JSON.parse(res.body)
if data['actions'][1] != nil and data['actions'][1].has_key? 'lastBuiltRevision'
data['actions'][1]['lastBuiltRevision']['SHA1']
# We haven't got a git hash, ask the previous job in the pipeline if there is one
elsif data['actions'][0]['causes'][0]['upstreamUrl'] != nil
get_sha_or_false('http://'+@jenkins+'/'+data['actions'][0]['causes'][0]['upstreamUrl']+data['actions'][0]['causes'][0]['upstreamBuild'].to_s + '/')
else
# There aren't any git commit hashes in this pipeline
false
end
end
end
# Pass in the latest job of the latest green pipeline run, searching for git hashes
hash = get_sha_or_false(@last_green_job)
puts hash.to_s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment