Instantly share code, notes, and snippets.

Embed
What would you like to do?
A short Ruby script to run tests from `.gitlab-ci.yml` using Docker
#!/usr/bin/env ruby
# frozen_string_literal: true
require 'yaml'
GITLAB_CI_YML = File.expand_path('.gitlab-ci.yml')
puts "Using #{GITLAB_CI_YML}"
def sys(cmd)
puts cmd
system(cmd)
end
def safe_run_job(h, services, variables)
links = services.map { |_image_name, _tag, name| "--link #{name}" }
script = (['cd /src'] + h['script']).join(' && ')
cmd = %w[docker run --rm -it -v $(pwd):/src] + links + variables + [h['image']] + %w[bash -c] + [%('#{script}')]
ok = sys(cmd.join(' '))
rescue
services.each do |_image_name, _tag, name|
sys %(docker stop #{name} && docker rm #{name})
end
end
# rubocop:disable Metrics/BlockLength
YAML.load_file(GITLAB_CI_YML).values.each do |h|
# rubocop:enable Metrics/BlockLength
next unless h.is_a?(Hash) && h.key?('stage') && h['stage'] == 'test'
services = h.fetch('services', []).map do |s|
case s
when String
name, tag = s.split(':')
[name, tag, name]
when Hash
name, tag = s['name'].split(':')
[name, tag, s['alias']]
else
raise "Don't know how to handle a (#{s.class}): #{s.inspect}"
end
end
variables = h.fetch('variables', []).map do |var, val|
"-e #{var}='#{val}'"
end
services.each do |image_name, tag, name|
puts "image_name, tag, name => #{image_name}, #{tag}, #{name}"
image = "#{image_name}:#{tag}"
sys %(docker images --format '{{.Repository}}:{{.Tag}}'|grep ^#{image}$ || docker pull #{image})
sys %(docker run -d --name #{name} #{variables.join(' ')} #{image})
end
exit 1 unless safe_run_job(h, services, variables)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment