Sha256: 604f2af523c4c6223ed8ddca587d0acb94b13d83bfb8d605e6e095e772df7673

Contents?: true

Size: 1.35 KB

Versions: 57

Compression:

Stored size: 1.35 KB

Contents

class KuberKit::EnvFileReader::EnvFileParser
  # Parser is based on:
  # https://github.com/bkeepers/dotenv/blob/master/lib/dotenv/parser.rb
  LINE = /
    (?:^|\A)              # beginning of line
    \s*                   # leading whitespace
    (?:export\s+)?        # optional export
    ([\w\.]+)             # key
    (?:\s*=\s*?|:\s+?)    # separator
    (                     # optional value begin
      \s*'(?:\\'|[^'])*'  #   single quoted value
      |                   #   or
      \s*"(?:\\"|[^"])*"  #   double quoted value
      |                   #   or
      [^\#\r\n]+          #   unquoted value
    )?                    # value end
    \s*                   # trailing whitespace
    (?:\#.*)?             # optional comment
    (?:$|\z)              # end of line
  /x

  Contract String => Hash
  def call(string)
    hash = {}
    string.gsub(/\r\n?/, "\n").scan(LINE).each do |key, value|
      hash[key] = parse_value(value || "")
    end
    hash
  end

  private

  def parse_value(value)
    # Remove surrounding quotes
    value = value.strip.sub(/\A(['"])(.*)\1\z/m, '\2')

    if Regexp.last_match(1) == '"'
      value = unescape_characters(expand_newlines(value))
    end

    value
  end

  def unescape_characters(value)
    value.gsub(/\\([^$])/, '\1')
  end

  def expand_newlines(value)
    value.gsub('\n', "\n").gsub('\r', "\r")
  end
end

Version data entries

57 entries across 57 versions & 1 rubygems

Version Path
kuber_kit-1.3.9 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.3.8 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.3.7 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.1.8 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.3.6 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.1.7 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.3.5 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.3.4 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.1.6 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.3.3 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.3.2 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.1.5 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.3.1 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.3.0 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.1.4 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.2.7 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.2.6 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.2.5 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.2.4 lib/kuber_kit/env_file_reader/env_file_parser.rb
kuber_kit-1.2.2 lib/kuber_kit/env_file_reader/env_file_parser.rb