From: Kev Jackson Date: 2005-11-07T16:20:47+09:00 Subject: [Patch] lib/shellwords.rb --------------090408030905040302080704 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Ok, here's my first patch (so be kind ;) I was looking for files to document as part of the ongoing ruby doc effort and I came across some code which I thought could do with refactoring - shellwords.rb I've attached the patch and associated testcases (Test::Unit) Hope everything is in order Kev --------------090408030905040302080704 Content-Type: text/plain; name="shellwords.rb.patch" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="shellwords.rb.patch" Index: lib/shellwords.rb =================================================================== RCS file: /src/ruby/lib/shellwords.rb,v retrieving revision 1.8 diff -u -r1.8 shellwords.rb --- lib/shellwords.rb 10 Nov 2004 07:16:24 -0000 1.8 +++ lib/shellwords.rb 4 Nov 2005 10:23:40 -0000 @@ -33,23 +33,16 @@ until line.empty? field = '' loop do - if line.sub!(/\A"(([^"\\]|\\.)*)"/, '') then - snippet = $1.gsub(/\\(.)/, '\1') - elsif line =~ /\A"/ then - raise ArgumentError, "Unmatched double quote: #{line}" - elsif line.sub!(/\A'([^']*)'/, '') then - snippet = $1 - elsif line =~ /\A'/ then - raise ArgumentError, "Unmatched single quote: #{line}" - elsif line.sub!(/\A\\(.)?/, '') then - snippet = $1 || '\\' - elsif line.sub!(/\A([^\s\\'"]+)/, '') then - snippet = $1 - else - line.lstrip! - break - end - field.concat(snippet) + case line + when line.sub!(/\A"(([^"\\]|\\.)*)"/, ''): snippet = $1.gsub(/\\(.)/,'\1') + when line =~ /\A"/: raise ArgumentError, "Unmatched double quote: #{line}" + when line =~ /\A'/: raise ArgumentError, "Unmatched single quote: #{line}" + when line.sub!(/\A\\(.)?/, ''): snippet = $1 || '\\' + when line.sub!(/\A([^\s\\'"]+)/, '') or line.sub!(/\A'([^']*)'/, ''): snippet = $1 + else line.lstrip! + break + end + field.concat(snippet) end words.push(field) end --------------090408030905040302080704 Content-Type: text/plain; name="test_shellwords.rb" Content-Transfer-Encoding: 7bit Content-Disposition: inline; filename="test_shellwords.rb" require 'test/unit' require 'shellwords' class TestShellwords < Test::Unit::TestCase include Shellwords def setup @not_string = Class.new @cmd = "ruby my_prog.rb | less" end def test_not_string assert_raises ArgumentError do shellwords(@not_string) end end def test_string assert_instance_of(Array, shellwords(@cmd)) assert_equal(4, shellwords(@cmd).length) end def test_unmatched_double_quote bad_cmd = 'one two "three' assert_raises ArgumentError do shellwords(bad_cmd) end end def test_unmatched_single_quote bad_cmd = "one two 'three" assert_raises ArgumentError do shellwords(bad_cmd) end end def test_unmatched_quotes bad_cmd = "one '"'"''""'"" assert_raises ArgumentError do shellwords(bad_cmd) end end end --------------090408030905040302080704--