Last active
January 17, 2018 15:18
-
-
Save aisrael/7a8267a2fe7e27ed873180d59ff5cf33 to your computer and use it in GitHub Desktop.
A short Ruby script to run tests from `.gitlab-ci.yml` using Docker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/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