module Helpema::Piper
Public Class Methods
run_command(cmd, options={}, script:nil, usage:nil, synonyms:nil, mode:'r', exception:nil, forward_pass:nil, **popt, &blk)
click to toggle source
Assume caller knows what it’s doing(no dummy proofing here)
# File lib/helpema/piper.rb, line 78 def Piper.run_command(cmd, options={}, script:nil, usage:nil, synonyms:nil, mode:'r', exception:nil, forward_pass:nil, **popt, &blk) args,ret = options.to_args(usage:usage,synonyms:synonyms),nil $stderr.puts "#{cmd} #{args.join(' ')}" if $DEBUG IO.popen([cmd, *args], mode, **popt) do |pipe| pipe.write script if script if forward_pass ret = forward_pass.call(pipe, options, blk) elsif blk ret = blk.call(pipe, options) elsif mode=='r' ret = pipe.read elsif mode=='w+' pipe.close_write ret = pipe.read end end # False exception instead of nil or "an error message" # flags the expected behavior as defined: success = ($?.exitstatus==0) raise(exception) if exception and not success return success if exception==false return ret end
to_arg(key,value)
click to toggle source
# File lib/helpema/piper.rb, line 63 def Piper.to_arg(key,value) # keep only keys with value(no false or nil) return nil unless value # assume nil0/--long/-short key = key.to_flag if key return key if value==true # a flag return "#{key}#{value}" if key[-1]=='=' # joined key=value return [key,value.to_s] end # It's a Nth arg, like arg0... return value.to_s end
validate_command(cmd, version, flag='--version')
click to toggle source
# File lib/helpema/piper.rb, line 34 def Piper.validate_command(cmd, version, flag='--version') raise "`#{cmd} #{flag}` !~ #{version}" unless `#{cmd} #{flag}`.strip.match?(version) end
Public Instance Methods
define_command(name, cmd:name.to_s.chomp('?').chomp('!'), version:nil, v:nil, usage:nil, synonyms:nil, mode:'r', exception:nil, default:nil, **popt, &forward_pass)
click to toggle source
Note: popt is IO.popen’s options(think of it as “pipe’s options”).
# File lib/helpema/piper.rb, line 40 def define_command(name, cmd:name.to_s.chomp('?').chomp('!'), version:nil, v:nil, usage:nil, synonyms:nil, mode:'r', exception:nil, default:nil, **popt, &forward_pass) raise "bad name or cmd" unless name=~/^\w+[?!]?$/ and cmd=~/^[\w.\-]+$/ Piper.validate_command(cmd, version) if version Piper.validate_command(cmd, v, '-v') if v define_method(name) do |script=default, **options, &blk| if mode[0]=='w' raise 'need script to write' unless script or blk or forward_pass else raise 'cannot write script' if script end Piper.run_command(cmd, options, script:script, usage:usage, synonyms:synonyms, mode:mode, exception:exception, forward_pass:forward_pass, **popt, &blk) end end