Skip to content

Instantly share code, notes, and snippets.

@gremerritt
Last active April 5, 2017 04:15
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 gremerritt/a36377319f57cdeaf141e329d63de2c0 to your computer and use it in GitHub Desktop.
Save gremerritt/a36377319f57cdeaf141e329d63de2c0 to your computer and use it in GitHub Desktop.
Run permutations of a program
#!/usr/bin/ruby
require 'pty'
def generate_permutations cmd_template, lists, vars=[]
if lists.empty?
cmd = String.new(cmd_template)
vars.each_with_index { |var, i| cmd.gsub! "{#{i}}", var }
if $preview
puts cmd
else
PTY.spawn(cmd) do |output, input|
begin
output.each { |line| puts line }
rescue Errno::EIO
# do nothing
end
end
end
else
lists[0].each do |elem|
vars.push(elem)
generate_permutations cmd_template, lists[1..-1], vars
vars.pop
end
end
end
def generate_permutation_lists params
lists = Array.new
file_index = params.index "-f"
while file_index
if file_index == params.length - 1
params.delete "-f"
break
elsif params[file_index + 1] == "-f"
params.delete_at file_index
else
begin
filepath = params[file_index + 1]
from_file = File.read(filepath).split("\n")
lists.push(from_file)
2.times { params.delete_at file_index }
file_index = params.index "-f"
rescue StandardError => err
puts "Unable to read from file: #{filepath} (#{err})"
return
end
end
end
return lists
end
def main params
$preview = false
if params.include? "--preview" or params.include? "-p"
$preview = true
params.delete "--preview"
params.delete "-p"
end
lists = generate_permutation_lists params
cmd = params.join(" ")
generate_permutations cmd, lists
end
main ARGV
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment