|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require 'octokit' |
| 4 | +require 'rspec/core' |
| 5 | +require 'rspec/core/formatters/base_formatter' |
| 6 | + |
| 7 | +module RSpec |
| 8 | + module Github |
| 9 | + class Annotator < RSpec::Core::Formatters::BaseFormatter |
| 10 | + RSpec::Core::Formatters.register self, :start, :dump_failures, :dump_pending, :close |
| 11 | + |
| 12 | + REQUIRED_ENV_VARIABLES = %w[OCTOKIT_ACCESS_TOKEN GITHUB_REPOSITORY GITHUB_SHA] |
| 13 | + |
| 14 | + def start(notification) |
| 15 | + missing_env_variables = REQUIRED_ENV_VARIABLES - ENV.keys |
| 16 | + raise "Missing environment variables: #{missing_env_variables}" if missing_env_variables.any? |
| 17 | + |
| 18 | + # Call check_run to create the pending check run |
| 19 | + check_run |
| 20 | + end |
| 21 | + |
| 22 | + def dump_failures(examples_notification) |
| 23 | + @failures = examples_notification.failure_notifications |
| 24 | + end |
| 25 | + |
| 26 | + def dump_pending(examples_notification) |
| 27 | + @pending = examples_notification.pending_notifications |
| 28 | + end |
| 29 | + |
| 30 | + def close(null_notification) |
| 31 | + annotations.each_slice(50) do |annotations_group| |
| 32 | + octokit_client.update_check_run( |
| 33 | + ENV.fetch('GITHUB_REPOSITORY'), |
| 34 | + check_run.id, |
| 35 | + status: 'completed', |
| 36 | + conclusion: conclusion, |
| 37 | + output: { |
| 38 | + title: 'RSpec output', |
| 39 | + summary: 'RSpec output', |
| 40 | + annotations: annotations_group |
| 41 | + }, |
| 42 | + accept: Octokit::Preview::PREVIEW_TYPES[:checks] |
| 43 | + ) |
| 44 | + end |
| 45 | + end |
| 46 | + |
| 47 | + private |
| 48 | + |
| 49 | + def conclusion |
| 50 | + return 'failure' if @failures.any? |
| 51 | + return 'neutral' if @pending.any? |
| 52 | + |
| 53 | + 'success' |
| 54 | + end |
| 55 | + |
| 56 | + def annotations |
| 57 | + (@failures + @pending).map do |notification| |
| 58 | + NotificationDecorator.new(notification) |
| 59 | + end |
| 60 | + end |
| 61 | + |
| 62 | + def check_run |
| 63 | + @check_run ||= octokit_client.create_check_run( |
| 64 | + ENV.fetch('GITHUB_REPOSITORY'), |
| 65 | + 'RSpec', |
| 66 | + ENV.fetch('GITHUB_SHA'), |
| 67 | + status: 'in_progress', |
| 68 | + accept: Octokit::Preview::PREVIEW_TYPES[:checks] |
| 69 | + ) |
| 70 | + end |
| 71 | + |
| 72 | + def octokit_client |
| 73 | + @octokit_client ||= Octokit::Client.new |
| 74 | + end |
| 75 | + end |
| 76 | + end |
| 77 | +end |
0 commit comments