class TmuxERBParser::Parser

Public Class Methods

new(input, type = :erb) click to toggle source
# File lib/tmux-erb-parser/parser.rb, line 15
def initialize(input, type = :erb)
  @input = case input
           when IO     then input.read
           when Array  then input.join("\n")
           when String then input
           else raise ArgumentError
           end
  @type = type
end

Public Instance Methods

parse(strip_comments = false) click to toggle source
# File lib/tmux-erb-parser/parser.rb, line 25
def parse(strip_comments = false)
  parse_string(@input, @type).map do |line|
    line = replace_source_file(line)
    line = strip_comment(line) if strip_comments
    line
  end
end

Private Instance Methods

parse_string(input, type) click to toggle source
# File lib/tmux-erb-parser/parser.rb, line 35
def parse_string(input, type)
  erb_result = ERB.new(input).result(TmuxERBParser::Helpers.binding)

  case type
  when :json
    Converter.convert(JSON.parse(erb_result))
  when :yml, :yaml
    if RUBY_VERSION.to_f < 2.6
      Converter.convert(YAML.safe_load(erb_result, [], [], true))
    else
      Converter.convert(YAML.safe_load(erb_result, aliases: true))
    end
  else
    # rubocop:disable Layout/LineLength
    erb_result
      .gsub(/(\R){3,}/) { Regexp.last_match(1) * 2 } # reduce continuity blankline
      .each_line(chomp: true)
    # rubocop:enable Layout/LineLength
  end
end
replace_source_file(line) click to toggle source
# File lib/tmux-erb-parser/parser.rb, line 56
def replace_source_file(line)
  # source file -> run-shell "parser --inline file"
  if line =~ /source/ && line !~ /run(-shell)?/
    line = line.gsub(/"source(-file)?( -q)?\s([^\s\\;]+)"/) do
      %("run-shell \\"#{PARSER_CMD} --inline #{Regexp.last_match(3)}\\"")
    end
    line = line.gsub(/source(-file)?( -q)?\s([^\s\\;]+)/) do
      %(run-shell "#{PARSER_CMD} --inline #{Regexp.last_match(3)}")
    end
  end
  line
end
strip_comment(str) click to toggle source
# File lib/tmux-erb-parser/parser.rb, line 69
def strip_comment(str)
  return '' if str.empty? || str.lstrip.start_with?('#')

  strip_eol_comment(str)
end
strip_eol_comment(str) click to toggle source
# File lib/tmux-erb-parser/parser.rb, line 75
def strip_eol_comment(str)
  flags = {}
  str = str.each_char.inject(+'') do |result, char|
    flags = update_flags(flags, char)
    break result if char == '#' && flags.values.none?

    result << char
  end
  str.rstrip
end
update_flags(current_flags, char) click to toggle source
# File lib/tmux-erb-parser/parser.rb, line 86
def update_flags(current_flags, char)
  result = current_flags.dup
  result.delete(:'\\')

  case char
  when '\\'
    result[char.to_sym] = !current_flags[char.to_sym]
  when '\'', '"'
    result[char.to_sym] =
      current_flags.delete(char.to_sym) ^ current_flags.values.none?
  end
  result
end