Skip to content
line.rb 2.26 KiB
Newer Older
module Gitlab
  module Diff
    class Line
      SERIALIZE_KEYS = %i(line_code rich_text text type index old_pos new_pos).freeze
      attr_reader :line_code, :type, :index, :old_pos, :new_pos
      attr_writer :rich_text
      attr_accessor :text
      def initialize(text, type, index, old_pos, new_pos, parent_file: nil, line_code: nil, rich_text: nil)
        @text, @type, @index = text, type, index
        @old_pos, @new_pos = old_pos, new_pos
Sean McGivern's avatar
Sean McGivern committed
        @parent_file = parent_file

        # When line code is not provided from cache store we build it
        # using the parent_file(Diff::File or Conflict::File).
        @line_code = line_code || calculate_line_code
      def self.init_from_hash(hash)
        new(hash[:text], hash[:type], hash[:index], hash[:old_pos], hash[:new_pos], line_code: hash[:line_code], rich_text: hash[:rich_text])
        SERIALIZE_KEYS.each { |key| hash[key] = send(key) } # rubocop:disable GitlabSecurity/PublicSend
      def old_line
        old_pos unless added? || meta?
      end

      def new_line
        new_pos unless removed? || meta?
      end

        %w[new new-nonewline].include?(type)
        %w[old old-nonewline].include?(type)
        %w[match new-nonewline old-nonewline].include?(type)
        @parent_file.try(:highlight_lines!) if @parent_file && !@rich_text
      def meta_positions
        return unless meta?

        {
          old_pos: old_pos,
          new_pos: new_pos
        }
      end

      def as_json(opts = nil)
        {
          line_code: line_code,
          type: type,
          old_line: old_line,
          new_line: new_line,
          text: text,
          meta_data: meta_positions

      private

      def calculate_line_code
        @parent_file&.line_code(self)
      end