lib/gitlab/qa/report/update_screenshot_path.rb



# frozen_string_literal: true

require 'nokogiri'
require 'json'
require 'active_support/core_ext/object/blank'

module Gitlab
  module QA
    module Report
      class UpdateScreenshotPath
        def initialize(files:)
          @files = files
        end

        REGEX = %r{(?<gitlab_qa_run>gitlab-qa-run-.*?(?=\/))\/(?<gitlab_ce_ee_qa>gitlab-(ee|ce)-qa-.*?(?=\/))}
        CONTAINER_PATH = File.join(Docker::Volumes::QA_CONTAINER_WORKDIR, 'tmp').freeze

        def invoke!
          Dir.glob(@files).each do |rspec_report_file|
            match_data = rspec_report_file.match(REGEX)
            artifact_path = "#{match_data[:gitlab_qa_run]}/#{match_data[:gitlab_ce_ee_qa]}"

            xml_report = rewrite_each_xml_screenshot_path(rspec_report_file, artifact_path)

            File.write(rspec_report_file, xml_report)

            puts "Saved #{rspec_report_file}"

            json_rspec_report_file = rspec_report_file.gsub('.xml', '.json')
            json_report = rewrite_each_json_screenshot_path(json_rspec_report_file, artifact_path)

            File.write(json_rspec_report_file, json_report)

            puts "Saved #{json_rspec_report_file}"
          end
        end

        private

        def rewrite_each_xml_screenshot_path(rspec_report_file, artifact_path)
          report = Nokogiri::XML(File.open(rspec_report_file))

          report.xpath('//system-out').each do |system_out|
            system_out.content = system_out.content.gsub(CONTAINER_PATH, artifact_path)
          end

          report.to_s
        end

        def rewrite_each_json_screenshot_path(json_rspec_report_file, artifact_path)
          report = JSON.parse(File.read(json_rspec_report_file))
          examples = report['examples']

          examples.each do |example|
            example['screenshot']['image'] = example['screenshot']['image'].gsub(CONTAINER_PATH, artifact_path) if example['screenshot'].present?
          end

          JSON.pretty_generate(report)
        end
      end
    end
  end
end