summaryrefslogtreecommitdiff
path: root/lib/shellwords.rb
blob: 9632f1222a446bbc2c2112f47160c4407817e474 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# shellwords.rb
# original is shellwords.pl
#
# Usage:
#       require 'shellwords.rb'
#       words = Shellwords.shellwords(line)
#
#	   or
#
#       include Shellwords
#       words = shellwords(line)

module Shellwords
  def shellwords(line)
    return '' unless line
    line.sub! /^\s+/, ''
    words = []
    while line != ''
      field = ''
      while TRUE
	if line.sub! /^"(([^"\\]|\\.)*)"/, '' then
	  snippet = $1
	  snippet.gsub! /\\(.)/, '\1'
	elsif line =~ /^"/ then
	  STDOUT.print "Unmatched double quote: $_\n"
	  exit
        elsif line.sub! /^'(([^'\\]|\\.)*)'/, '' then
	  snippet = $1
	  snippet.gsub! /\\(.)/, '\1'
	elsif line =~ /^'/ then
	  STDOUT.print "Unmatched single quote: $_\n"
	  exit
	elsif line.sub! /^\\(.)/, '' then
	  snippet = $1
	elsif line.sub! /^([^\s\\'"]+)/, '' then
	  snippet = $1
	else
	  line.sub! /^\s+/, ''
	  break
	end
	field += snippet
      end
      words += field
    end
    words
  end
  module_function :shellwords
end