Class: CommandTest::Parser
- Inherits:
-
Object
- Object
- CommandTest::Parser
- Defined in:
- lib/command_test/parser.rb
Instance Method Summary collapse
- #extract_word(line) ⇒ Object
- #extract_word_skipping_redirects(line) ⇒ Object
-
#parse(line) ⇒ Object
Parse the given command line into words.
Instance Method Details
#extract_word(line) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/command_test/parser.rb', line 37 def extract_word(line) return nil if line.empty? word = '' loop do if line.sub!(/\A"(([^"\\]|\\.)*)"/, '') chunk = $1.gsub(/\\(.)/, '\1') elsif line =~ /\A"/ raise ArgumentError, "unmatched double quote: #{line}" elsif line.sub!(/\A'([^']*)'/, '') chunk = $1 elsif line =~ /\A'/ raise ArgumentError, "unmatched single quote: #{line}" elsif line.sub!(/\A\\(.)?/, '') chunk = $1 || '' elsif line.sub!(/\A([^\s\\'"<>]+)/, '') chunk = $1 else line.lstrip! break end word << chunk end word end |
#extract_word_skipping_redirects(line) ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/command_test/parser.rb', line 19 def extract_word_skipping_redirects(line) while true if line.sub!(/\A\d*>>?(&\d+)?\s*/, '') if $1.nil? extract_word(line) or raise ArgumentError, "missing redirection target: #{line}" end next elsif line.sub!(/\A\d*<\s*/, '') extract_word(line) or raise ArgumentError, "missing redirection source: #{line}" next end return extract_word(line) end end |
#parse(line) ⇒ Object
Parse the given command line into words.
Supports backslash escaping, single quoting, double quoting, and redirects, a la bash.
9 10 11 12 13 14 15 16 17 |
# File 'lib/command_test/parser.rb', line 9 def parse(line) # Implementation heavily inspired by Ruby's Shellwords. line = line.lstrip words = [] while (word = extract_word_skipping_redirects(line)) words << word end words end |