Sha256: 4be548c6ab5cbc39da72fb233055b80350fd2bf1ae9137c843fc239adb955e5f

Contents?: true

Size: 1.66 KB

Versions: 2

Compression:

Stored size: 1.66 KB

Contents

# 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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
yard-0.9.18 lib/yard/core_ext/string.rb
yard-0.9.17 lib/yard/core_ext/string.rb