1998-01-16 15:19:09 +03:00
|
|
|
#
|
2003-01-26 13:11:30 +03:00
|
|
|
# shellwords.rb: Split text into an array of tokens a la UNIX shell
|
1998-01-16 15:19:09 +03:00
|
|
|
#
|
|
|
|
|
2003-01-26 13:11:30 +03:00
|
|
|
#
|
|
|
|
# This module is originally a port of shellwords.pl, but modified to
|
|
|
|
# conform to POSIX / SUSv3 (IEEE Std 1003.1-2001).
|
|
|
|
#
|
|
|
|
# Examples:
|
|
|
|
#
|
|
|
|
# require 'shellwords'
|
|
|
|
# words = Shellwords.shellwords(line)
|
|
|
|
#
|
|
|
|
# or
|
|
|
|
#
|
|
|
|
# require 'shellwords'
|
|
|
|
# include Shellwords
|
|
|
|
# words = shellwords(line)
|
|
|
|
#
|
1998-01-16 15:19:09 +03:00
|
|
|
module Shellwords
|
2003-01-26 13:11:30 +03:00
|
|
|
|
|
|
|
#
|
|
|
|
# Split text into an array of tokens in the same way the UNIX Bourne
|
|
|
|
# shell does.
|
|
|
|
#
|
|
|
|
# See the +Shellwords+ module documentation for an example.
|
|
|
|
#
|
1998-01-16 15:19:09 +03:00
|
|
|
def shellwords(line)
|
2003-01-26 13:11:30 +03:00
|
|
|
line = String.new(line) rescue
|
|
|
|
raise(ArgumentError, "Argument must be a string")
|
|
|
|
line.lstrip!
|
1998-01-16 15:19:09 +03:00
|
|
|
words = []
|
2003-01-26 13:11:30 +03:00
|
|
|
until line.empty?
|
1998-01-16 15:19:09 +03:00
|
|
|
field = ''
|
2003-01-26 13:11:30 +03:00
|
|
|
loop do
|
|
|
|
if line.sub!(/\A"(([^"\\]|\\.)*)"/, '') then
|
|
|
|
snippet = $1.gsub(/\\(.)/, '\1')
|
|
|
|
elsif line =~ /\A"/ then
|
2000-02-08 11:54:01 +03:00
|
|
|
raise ArgumentError, "Unmatched double quote: #{line}"
|
2003-01-26 13:11:30 +03:00
|
|
|
elsif line.sub!(/\A'([^']*)'/, '') then
|
1998-01-16 15:19:09 +03:00
|
|
|
snippet = $1
|
2003-01-26 13:11:30 +03:00
|
|
|
elsif line =~ /\A'/ then
|
2000-02-08 11:54:01 +03:00
|
|
|
raise ArgumentError, "Unmatched single quote: #{line}"
|
2000-08-01 13:25:37 +04:00
|
|
|
elsif line.sub!(/\A\\(.)/, '') then
|
1998-01-16 15:19:09 +03:00
|
|
|
snippet = $1
|
2003-01-26 13:11:30 +03:00
|
|
|
elsif line.sub!(/\A([^\s\\'"]+)/, '') then
|
1998-01-16 15:19:09 +03:00
|
|
|
snippet = $1
|
|
|
|
else
|
2003-01-26 13:11:30 +03:00
|
|
|
line.lstrip!
|
1998-01-16 15:19:09 +03:00
|
|
|
break
|
|
|
|
end
|
2000-02-08 11:54:01 +03:00
|
|
|
field.concat(snippet)
|
1998-01-16 15:19:09 +03:00
|
|
|
end
|
2000-02-08 11:54:01 +03:00
|
|
|
words.push(field)
|
1998-01-16 15:19:09 +03:00
|
|
|
end
|
|
|
|
words
|
|
|
|
end
|
2003-01-26 13:11:30 +03:00
|
|
|
|
1998-01-16 15:19:09 +03:00
|
|
|
module_function :shellwords
|
|
|
|
end
|