lib/shellwords.rb
DEFINITIONS
This source file includes following functions.
1 # shellwords.rb
2 # original is shellwords.pl
3 #
4 # Usage:
5 # require 'shellwords'
6 # words = Shellwords.shellwords(line)
7 #
8 # or
9 #
10 # require 'shellwords'
11 # include Shellwords
12 # words = shellwords(line)
13
14 module Shellwords
15 def shellwords(line)
16 unless line.kind_of?(String)
17 raise ArgumentError, "Argument must be String class object."
18 end
19 line = line.sub(/\A\s+/, '')
20 words = []
21 while line != ''
22 field = ''
23 while true
24 if line.sub!(/\A"(([^"\\]|\\.)*)"/, '') then #"
25 snippet = $1
26 snippet.gsub!(/\\(.)/, '\1')
27 elsif line =~ /\A"/ then #"
28 raise ArgumentError, "Unmatched double quote: #{line}"
29 elsif line.sub!(/\A'(([^'\\]|\\.)*)'/, '') then #'
30 snippet = $1
31 snippet.gsub!(/\\(.)/, '\1')
32 elsif line =~ /\A'/ then #'
33 raise ArgumentError, "Unmatched single quote: #{line}"
34 elsif line.sub!(/\A\\(.)/, '') then
35 snippet = $1
36 elsif line.sub!(/\A([^\s\\'"]+)/, '') then #'
37 snippet = $1
38 else
39 line.sub!(/\A\s+/, '')
40 break
41 end
42 field.concat(snippet)
43 end
44 words.push(field)
45 end
46 words
47 end
48 module_function :shellwords
49 end