/
string.rb
68 lines (68 loc) · 1.59 KB
/
string.rb
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# frozen_string_literal: true
class String
# Splits text into tokens the way a shell would, handling quoted
# text as a single token. Use '\"' and "\'" to escape quotes and
# '\\' to escape a backslash.
#
# @return [Array] an array representing the tokens
def shell_split
out = [String.new("")]
state = :none
escape_next = false
quote = String.new("")
strip.split(//).each do |char|
case state
when :none, :space
case char
when /\s/
out << String.new("") unless state == :space
state = :space
escape_next = false
when "\\"
if escape_next
out.last << char
escape_next = false
else
escape_next = true
end
when '"', "'"
if escape_next
out.last << char
escape_next = false
else
state = char
quote = String.new("")
end
else
state = :none
out.last << char
escape_next = false
end
when '"', "'"
case char
when '"', "'"
if escape_next
quote << char
escape_next = false
elsif char == state
out.last << quote
state = :none
else
quote << char
end
when '\\'
if escape_next
quote << char
escape_next = false
else
escape_next = true
end
else
quote << char
escape_next = false
end
end
end
out
end
end