Skip to content

Instantly share code, notes, and snippets.

@yyamano
Last active August 29, 2015 14:16
Show Gist options
  • Save yyamano/796f34a257cb1c685393 to your computer and use it in GitHub Desktop.
Save yyamano/796f34a257cb1c685393 to your computer and use it in GitHub Desktop.
ruby DSL example for command execution
#! /usr/pkg/bin/ruby
# Copyright (c) 2015 Yuji Yamano
# The BSD 2-Clause License.
require 'open3'
require 'date'
require 'stringio'
module DSL
class Command
def initialize(cmds)
@cmds = cmds
end
def append_to(file)
execute(file, append: true)
end
def redirect_to(file)
execute(file, append: false)
end
def execute(outfile, append: false)
File.open(outfile, append ? "a" : "w") do |out|
@cmds.each do |cmd|
if cmd.is_a? String
execute_cmd(cmd, out)
elsif cmd.is_a? Proc
execute_proc(cmd, out)
end
end
end
end
def execute_cmd(cmd, out)
out.puts "#{DateTime.now.to_s}: Executing '#{cmd}'..."
begin
stdout, stderr, status = Open3.capture3(cmd)
out.write stdout
out.write stderr
result = (status == 0) ?
"#{DateTime.now.to_s}: '#{cmd}' was executed successfully." :
"#{DateTime.now.to_s}: Failed to execute '#{cmd}'. status=#{status}."
out.puts result
rescue => e
out.puts "#{DateTime.now.to_s}: Failed to execute '#{cmd}': #{e.message}"
end
end
def execute_proc(proc, out)
stdout_orig = STDOUT.clone
stderr_orig = STDERR.clone
begin
out.puts "#{DateTime.now.to_s}: Executing #{proc.inspect}'..."
STDOUT.reopen(out)
STDERR.reopen(out)
proc.call
out.puts "#{DateTime.now.to_s}: #{proc.inspect} was executed successfully."
rescue => e
out.puts "#{DateTime.now.to_s}: Failed to execute #{proc.inspect}: #{e.inspect}"
out.puts e.backtrace
ensure
STDOUT.reopen(stdout_orig)
STDERR.reopen(stderr_orig)
end
end
end
def exec(*cmds)
Command.new(cmds)
end
end
include DSL
p1 = Proc.new do
puts "STDOUT!"
STDERR.puts "STDERR!"
puts "Found /tmp" if File.exist?("/tmp")
puts "Not found /path/to/file" if File.exist?("/path/to/file")
end
p2 = Proc.new do
puts "Hi again!"
raise "Raise an exception!"
end
exec('echo hey hey').redirect_to("/tmp/foo")
exec('ls', 'who').append_to("/tmp/foo")
exec('i_dont_expect_this_command_exists').append_to("/tmp/foo")
exec('cc -v').append_to("/tmp/foo")
exec('who', p1, p2, 'who').append_to("/tmp/foo")
exec('pwd; cd /; pwd; ls -l').append_to("/tmp/foo")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment