Skip to content

Instantly share code, notes, and snippets.

@seven1m
Created March 28, 2017 03:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seven1m/e4f53b1277471356570a5ae0bde3cb34 to your computer and use it in GitHub Desktop.
Save seven1m/e4f53b1277471356570a5ae0bde3cb34 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# Run several commands for different directories at the same time and multiplex their output with color-coded app labels.
#
# Usage:
#
# ruby parallel.rb "foo:$HOME/projects/foo:bundle exec rake db:migrate" "bar:$HOME/projects/bar:bundle exec rake db:migrate"
#
# The output will look something like this (but the prefix labels will have different colors):
#
# foo == 20170310111111 Foo: migrating ==============================================
# foo bla bla bla
# foo == 20170310111111 Foo: migrated (0.0000s) =====================================
# bar == 20170320222222 Bar: migrating ==============================================
# bar yada yada yada
# bar == 20170320222222 Bar: migrated (0.0000s) =====================================
require 'open3'
COLORS = {
red: '0;31',
green: '0;32',
yellow: '0;33',
blue: '0;34',
magenta: '0;35',
cyan: '0;36',
bright_red: '1;31',
bright_green: '1;32',
bright_yellow: '1;33',
bright_blue: '1;34',
bright_magenta: '1;35',
bright_cyan: '1;36'
}
threads = []
use_rvm = ARGV.delete('--rvm')
ARGV.each_with_index do |command, index|
(app, path, command) = command.split(':', 3)
color = COLORS.values[index % COLORS.values.size]
cmd = [
"cd #{path}",
use_rvm ? "rvm use $(cat .ruby-version)" : nil,
command
].compact.join(' && ')
cmd = "bash -lc #{cmd.inspect}".gsub(/\$/, "\\$")
threads << Thread.new do
(_, out, wait_thr) = Open3.popen2e(cmd)
puts "\e[#{color}m#{app.ljust(18)[0...18]}\e[0m#{out.gets}" until out.eof?
out.close
code = wait_thr.value.exitstatus
exit code unless code.zero?
end
end
threads.each(&:join)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment