Skip to content

Instantly share code, notes, and snippets.

@rolebi
Last active December 30, 2016 09:45
Show Gist options
  • Save rolebi/ba8bbcb19b4847ddd8a8d98e4c1a5487 to your computer and use it in GitHub Desktop.
Save rolebi/ba8bbcb19b4847ddd8a8d98e4c1a5487 to your computer and use it in GitHub Desktop.
Keep only one build up for each PR in travis
env:
global:
# TRAVIS_ACCESS_TOKEN used to access travis API from within builds
- secure: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX"
cache:
bundler: true
before_install:
- bundle install
- bundle exec travis_build_killer.rb
#!/usr/bin/env ruby
# Highly inspirated by https://github.com/ManageIQ/miq_bot/blob/master/app/workers/travis_build_killer.rb
require 'rubygems'
require 'bundler/setup'
require 'travis'
logger = Logger.new(STDOUT)
Travis::Pro.access_token = ENV['TRAVIS_ACCESS_TOKEN']
travis_repo = Travis::Pro::Repository.find(ENV['TRAVIS_REPO_SLUG'])
pending_builds = travis_repo.builds.take_while { |b| b.pending? || b.canceled? }.reject(&:canceled?)
logger.info "Found #{pending_builds.count} builds in queue"
out_dated_builds = pending_builds.group_by { |b| b.pull_request_number || b.branch_info }.flat_map { |_key, builds| builds[1..-1] }
out_dated_builds.each do |b|
if b.pull_request?
logger.info "Canceling Travis build ##{b.number} for PR ##{b.pull_request_number}"
b.cancel
elsif b.running?
logger.info "Skipping currently running Travis build ##{b.number} for merge commit"
else
logger.info "Canceling Travis build ##{b.number} for merge commit"
b.cancel
end
end
long_running_jobs = pending_builds.select(&:running?).flat_map { |b| b.jobs.select { |j| j.running? && (Time.now.getlocal - j.started_at) >= 3600 } }
logger.info "Found #{long_running_jobs.count} long running jobs"
long_running_jobs.each do |b|
logger.info " - canceling long running Travis build ##{b.number}, something must be wrong."
b.cancel
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment