# frozen_string_literal: true module GitlabQuality module TestTooling module Report module Concerns module IssueReports JOB_URL_REGEX = %r{(?https://(?[\w.]+)/(?[\w\-./]+)/-/jobs/\d+)} FAILED_JOB_DESCRIPTION_REGEX = /First happened in #{JOB_URL_REGEX}\./m REPORT_ITEM_REGEX = /^1\. \d{4}-\d{2}-\d{2}: #{JOB_URL_REGEX} \((?.+)\)$/ def initial_reports_section(test) <<~REPORTS ### Reports (1) #{report_list_item(test)} REPORTS end def add_report_to_issue_description(issue, test) issue_description = issue.description # We include the number of reports in the header, for visibility. new_issue_description = if issue_description.include?('### Reports') # We count the number of existing reports. reports_count = issue_description .scan(REPORT_ITEM_REGEX) .size.to_i + 1 issue_description.sub(/^### Reports.*$/, "### Reports (#{reports_count})") else # For issue with the legacy format, we add the Reports section update_legacy_issue_description(issue_description) end [new_issue_description, report_list_item(test)].join("\n") end def failed_issue_job_url(issue) job_urls_from_description(issue.description, REPORT_ITEM_REGEX).last || # Legacy format job_urls_from_description(issue.description, FAILED_JOB_DESCRIPTION_REGEX).last end def failed_issue_job_urls(issue) job_urls_from_description(issue.description, REPORT_ITEM_REGEX) + # Legacy format job_urls_from_description(issue.description, FAILED_JOB_DESCRIPTION_REGEX) end private def report_list_item(test) "1. #{Time.new.utc.strftime('%F')}: #{test.ci_job_url} (#{ENV.fetch('CI_PIPELINE_URL', 'pipeline url is missing')})" end def job_urls_from_description(issue_description, regex) issue_description.lines.filter_map do |line| match = line.match(regex) match[:job_url] if match end end def update_legacy_issue_description(issue_description) test_captures = issue_description.scan(JOB_URL_REGEX) reports_count = test_captures.size.to_i + 1 updated_description = "#{issue_description}\n\n### Reports (#{reports_count})\n" updated_description = [updated_description, *test_captures_to_report_items(test_captures)].join("\n") unless test_captures.empty? updated_description end def test_captures_to_report_items(test_captures) test_captures.map do |ci_job_url, _, _| report_list_item(GitlabQuality::TestTooling::TestResult::JsonTestResult.new( 'ci_job_url' => ci_job_url )) end end end end end end end