Sha256: cdcb35b5dc4fe957d372fdc9046cd6ee804d130095db1cd5c32e9f6740455303

Contents?: true

Size: 1.68 KB

Versions: 25

Compression:

Stored size: 1.68 KB

Contents

# frozen_string_literal: true

require 'parser'

module PlatformosCheck
  class AppFileRewriter
    def initialize(name, source)
      @buffer = Parser::Source::Buffer.new(name, source:)
      @rewriter = Parser::Source::TreeRewriter.new(
        @buffer
      )
    end

    def insert_before(node, content, character_range = nil)
      @rewriter.insert_before(
        range(
          character_range&.begin || node.start_index,
          character_range&.end || node.end_index
        ),
        content
      )
    end

    def insert_after(node, content, character_range = nil)
      @rewriter.insert_after(
        range(
          character_range&.begin || node.start_index,
          character_range&.end || node.end_index
        ),
        content
      )
    end

    def remove(node)
      @rewriter.remove(
        range(node.outer_markup_start_index, node.outer_markup_end_index)
      )
    end

    def replace(node, content, character_range = nil)
      @rewriter.replace(
        range(
          character_range&.begin || node.start_index,
          character_range&.end || node.end_index
        ),
        content
      )
    end

    def replace_inner_markup(node, content)
      @rewriter.replace(
        range(node.inner_markup_start_index, node.inner_markup_end_index),
        content
      )
    end

    def wrap(node, insert_before, insert_after)
      @rewriter.wrap(
        range(node.start_index, node.end_index),
        insert_before,
        insert_after
      )
    end

    def to_s
      @rewriter.process
    end

    private

    def range(start_index, end_index)
      Parser::Source::Range.new(
        @buffer,
        start_index,
        end_index
      )
    end
  end
end

Version data entries

25 entries across 25 versions & 1 rubygems

Version Path
platformos-check-0.2.0 lib/platformos_check/app_file_rewriter.rb
platformos-check-0.1.0 lib/platformos_check/app_file_rewriter.rb
platformos-check-0.0.3 lib/platformos_check/app_file_rewriter.rb
platformos-check-0.0.2 lib/platformos_check/app_file_rewriter.rb
platformos-check-0.0.1 lib/platformos_check/app_file_rewriter.rb