Class: Homebrew::DevCmd::Contributions Private

Inherits:
AbstractCommand show all
Includes:
SystemCommand::Mixin
Defined in:
dev-cmd/contributions.rb,
sorbet/rbi/dsl/homebrew/dev_cmd/contributions.rbi

This class is part of a private API. This class may only be used in the Homebrew/brew repository. Third parties should avoid using this class if possible, as it may be removed or changed without warning.

Defined Under Namespace

Classes: Args

Constant Summary collapse

PRIMARY_REPOS =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

%w[
  Homebrew/brew
  Homebrew/homebrew-core
  Homebrew/homebrew-cask
].freeze
CONTRIBUTION_TYPES =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

T.let({
  merged_pr_author:   "merged PRs authored",
  merged_pr_merger:   "PRs merged",
  merged_pr:          "qualifying merged PRs",
  approved_pr_review: "approved-review search matches",
  coauthor:           "co-authored commits",
}.freeze, T::Hash[Symbol, String])
MAX_PR_SEARCH =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

100
MAINTAINER_ACTIVITY_THRESHOLD =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

https://docs.brew.sh/Homebrew-Governance#maintainer

50
LEAD_REPOSITORY_ACTIVITY_THRESHOLD =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

https://docs.brew.sh/Homebrew-Governance#lead-maintainer

25
MAX_CONTRIBUTIONS =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

T.let(MAINTAINER_ACTIVITY_THRESHOLD * 10, Integer)
QUALIFYING_CONTRIBUTION_TYPES =

This constant is part of a private API. This constant may only be used in the Homebrew/brew repository. Third parties should avoid using this constant if possible, as it may be removed or changed without warning.

[:merged_pr, :approved_pr_review, :coauthor].freeze

Instance Method Summary collapse

Methods included from SystemCommand::Mixin

#system_command, #system_command!

Methods inherited from AbstractCommand

command, command_name, dev_cmd?, #initialize, parser, ruby_cmd?

Methods included from Utils::Output::Mixin

#issue_reporting_message, #odebug, #odeprecated, #odie, #odisabled, #ofail, #oh1, #oh1_title, #ohai, #ohai_title, #onoe, #opoo, #opoo_outside_github_actions, #opoo_without_github_actions_annotation, #pretty_deprecated, #pretty_disabled, #pretty_duration, #pretty_install_status, #pretty_installed, #pretty_uninstalled, #pretty_unmarked, #pretty_upgradable, #pretty_warning

Constructor Details

This class inherits a constructor from Homebrew::AbstractCommand

Instance Method Details

#argsHomebrew::DevCmd::Contributions::Args

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



10
# File 'sorbet/rbi/dsl/homebrew/dev_cmd/contributions.rbi', line 10

def args; end

#github_search_with_rate_limit(cache_key, to:, &block) ⇒ Array<Hash{String => T.untyped}>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
# File 'dev-cmd/contributions.rb', line 497

def github_search_with_rate_limit(cache_key, to:, &block)
  cache_path = if Date.iso8601(to) <= Date.today
    HOMEBREW_CACHE/"contributions--#{Digest::SHA256.hexdigest("1\0#{cache_key}")}.json"
  end
  if cache_path&.file?
    begin
      cached_results = JSON.parse(cache_path.read)
      return cached_results if cached_results.is_a?(Array)
    rescue JSON::ParserError, Errno::ENOENT
      nil
    end
    cache_path.unlink if cache_path.exist?
  end

  results = yield
  if cache_path
    HOMEBREW_CACHE.mkpath
    cache_path.atomic_write(JSON.generate(results))
  end
  results
rescue GitHub::API::RateLimitExceededError => e
  sleep_seconds = [e.reset - Time.now.to_i, 1].max
  opoo "GitHub rate limit exceeded, sleeping for #{sleep_seconds} seconds..."
  sleep sleep_seconds
  retry
end

#github_username_for(user, to:) ⇒ String?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
# File 'dev-cmd/contributions.rb', line 470

def github_username_for(user, to:)
  return user unless user.include?("@")
  if user.end_with?("@users.noreply.github.com")
    return user.delete_suffix("@users.noreply.github.com").sub(/\A\d+\+/,
                                                               "")
  end

  cache_key = ["public-email", user].join("\0")
  matches = github_search_with_rate_limit(cache_key, to:) do
    GitHub.search("users", "\"#{user}\" in:email").fetch("items", [])
  end
  if matches.one?
     = matches.fetch(0)["login"]
    return  if .is_a?(String)
  end

  opoo "Could not find a unique public GitHub account for #{user}; skipping GitHub PR searches."
  nil
rescue GitHub::API::ValidationFailedError
  opoo "Could not search for a public GitHub account for #{user}; skipping GitHub PR searches."
  nil
end

#maintainer_report_users(repository_refs, to) ⇒ Array<(Hash{String => String}, Hash{String => Boolean}, Hash{String => String, nil})>

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
# File 'dev-cmd/contributions.rb', line 240

def maintainer_report_users(repository_refs, to)
  brew_path, brew_ref = repository_refs.fetch("Homebrew/brew")
  require "utils/git"
  quarter_end_ref = Utils.safe_popen_read(
    Utils::Git.git, "-C", brew_path, "rev-list", "-1", "--before=#{to}", brew_ref, "--", "README.md"
  ).strip
  odie "Could not find Homebrew/brew's README at the end of the reporting quarter." if quarter_end_ref.empty?

  user_names = T.let({}, T::Hash[String, String])
  lead_maintainers = T.let({}, T::Hash[String, T::Boolean])
  Utils.safe_popen_read(Utils::Git.git, "-C", brew_path, "show", "#{quarter_end_ref}:README.md")
       .dup.force_encoding(Encoding::UTF_8).each_line do |line|
    lead = line.start_with?("Homebrew's [Lead Maintainers]")
    next if !lead &&
            !line.start_with?("Homebrew's other Maintainers") &&
            !line.start_with?("Homebrew's maintainers are")

    line.scan(%r{\[([^\]]+)\]\(https://github\.com/([A-Za-z\d-]+)\)}).each do |match|
      next unless match.is_a?(Array)

      name = match.fetch(0)
      user = match.fetch(1)
      user_names[user] = name
      lead_maintainers[user.downcase] = true if lead
    end
  end
  odie "Could not read the maintainers from Homebrew/brew's README." if user_names.empty?

  if (users = args.user.presence)
    requested_usernames = users.to_h do |user|
      [user, github_username_for(user, to:)&.downcase]
    end
    unresolved_users = requested_usernames.filter_map { |user, username| user if username.nil? }
    odie "Could not resolve GitHub usernames for: #{unresolved_users.to_sentence}." if unresolved_users.present?

    maintainer_usernames = user_names.keys.map(&:downcase)
    non_maintainers = requested_usernames.filter_map do |user, username|
      user if username && maintainer_usernames.exclude?(username)
    end
    unless non_maintainers.empty?
      odie "Not listed as #{Utils.pluralize("Maintainer", non_maintainers.length)} at the end of the " \
           "reporting quarter: #{non_maintainers.to_sentence}."
    end

    selected_usernames = requested_usernames.values.compact
    user_names.select! { |user| selected_usernames.include?(user.downcase) }
  end

  maintainer_count = Utils.pluralize("maintainer", user_names.length, include_count: true)
  $stderr.puts "Scanning contributions for #{maintainer_count}..."
  maintainer_since_dates = user_names.to_h do |user, name|
    [user, maintainer_since(brew_path, quarter_end_ref, user, name)]
  end
  [user_names, lead_maintainers, maintainer_since_dates]
end

#maintainer_since(repository_path, ref, user, name) ⇒ String?

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
# File 'dev-cmd/contributions.rb', line 297

def maintainer_since(repository_path, ref, user, name)
  require "utils/git"

  candidates = ["https://github.com/#{user}", name].flat_map do |identity|
    Utils.safe_popen_read(
      Utils::Git.git, "-C", repository_path, "log", ref, "--fixed-strings",
      "-S#{identity}", "--format=%H%x1f%cs", "--", "README.md"
    ).lines(chomp: true)
  end
  candidates.uniq!
  candidates.sort_by! { |candidate| candidate.split("\x1f", 2).fetch(1) }
  candidates.each do |candidate|
    commit, date = candidate.split("\x1f", 2)
    next if date.nil?

    readme = Utils.safe_popen_read(Utils::Git.git, "-C", repository_path, "show", "#{commit}:README.md")
    parent_readme = system_command(Utils::Git.git,
                                   args:         ["-C", repository_path, "show", "#{commit}^:README.md"],
                                   print_stderr: false).stdout
    return date if readme_mentions?(readme, user, name) && !readme_mentions?(parent_readme, user, name)
  end

  nil
end

#parse_git_log(output, users, authored_pull_requests: nil, merged_pull_requests: nil) ⇒ Hash{String => Hash{Symbol => Integer}}

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
# File 'dev-cmd/contributions.rb', line 533

def parse_git_log(output, users, authored_pull_requests: nil, merged_pull_requests: nil)
  counts = users.to_h do |user, _|
    [user, CONTRIBUTION_TYPES.keys.to_h { |type| [type, 0] }]
  end
  identity_users = T.let({}, T::Hash[String, String])
  users.each do |user, name|
    identity_users[user.downcase] = user
    identity_users[name.downcase] = user
    identity_users[user.split("@").first.to_s.sub(/\A\d+\+/, "").downcase] = user
  end
  records = output.split("\x1e").filter_map do |record|
    fields = record.strip.split("\x1f", 5)
    fields if fields.length == 5
  end
  record_identities = records.to_h do |fields|
    [fields.fetch(0), [fields.fetch(2), fields.fetch(3)]]
  end
  records.each do |fields|
    parents = fields.fetch(1).split
    source_owner = fields.fetch(4)[%r{\AMerge pull request #\d+ from ([^/\s]+)/}, 1]
    next if parents.length < 2 || source_owner.nil?

    user = identity_users[source_owner.downcase]
    source_identity = record_identities[parents.fetch(1)]
    next if user.nil? || source_identity.nil?

    name, email = source_identity
    identity_users[name.strip.downcase] ||= user
    identity_users[email.downcase] ||= user
    identity_users[email.split("@").first.to_s.sub(/\A\d+\+/, "").downcase] ||= user
  end
  commit_authors = T.let(records.to_h do |fields|
    sha = fields.fetch(0)
    author_name = fields.fetch(2)
    author_email = fields.fetch(3)
    [sha, user_for_git_identity(author_name, author_email, identity_users)]
  end, T::Hash[String, T.nilable(String)])

  records.each do |fields|
    parents_string = fields.fetch(1)
    author_name = fields.fetch(2)
    author_email = fields.fetch(3)
    body = fields.fetch(4)
    coauthors = body.scan(/^Co-authored-by:\s*(.*?)\s*<([^>]+)>/i).filter_map do |match|
      next unless match.is_a?(Array)

      user_for_git_identity(match.fetch(0), match.fetch(1), identity_users)
    end
    coauthors.uniq.each do |user|
      increment_contribution_count(counts.fetch(user), :coauthor)
    end

    parents = parents_string.split
    pull_request = body.match(%r{\AMerge pull request #(\d+) from ([^/\s]+)/})
    next if parents.length < 2 || pull_request.nil?

    merger = user_for_git_identity(author_name, author_email, identity_users)
    pull_request_id = pull_request[1]
    source_owner = pull_request[2]
    next if pull_request_id.nil? || source_owner.nil?

    author = identity_users[source_owner.downcase] || commit_authors[parents.fetch(1)]
    if author
      increment_contribution_count(counts.fetch(author), :merged_pr_author)
      authored_pull_requests&.fetch(author)&.add(pull_request_id)
    end
    increment_contribution_count(counts.fetch(merger), :merged_pr_merger) if merger
    [author, merger].compact.uniq.each do |user|
      increment_contribution_count(counts.fetch(user), :merged_pr)
      merged_pull_requests&.fetch(user)&.add(pull_request_id)
    end
  end

  counts
end

#runvoid

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

This method returns an undefined value.



97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
# File 'dev-cmd/contributions.rb', line 97

def run
  maintainer_report_csv = args.maintainer_report_csv
  requested_users = args.user || []
  odie "`--user` must not contain empty values." if requested_users.compact.length != requested_users.length

  odie "Cannot get contributions as `$HOMEBREW_NO_GITHUB_API` is set!" if Homebrew::EnvConfig.no_github_api?
  Homebrew.install_bundler_gems!(groups: ["contributions"]) if args.csv? || maintainer_report_csv

  if maintainer_report_csv
    odie "`--maintainer-report-csv` must be in YEAR-QUARTER format." unless maintainer_report_csv.match?(
      /\A\d{4}-[1-4]\z/,
    )
    quarter_parts = maintainer_report_csv.split("-")
    from, to = reporting_quarter_dates(quarter_parts.fetch(1).to_i, quarter_parts.fetch(0).to_i)
    $stderr.puts "Maintainer report dates: #{from}-to-#{to}"
  else
    quarter = args.quarter.presence.to_i
    odie "Value for `--quarter` must be between 1 and 4." if args.quarter.present? && !quarter.between?(1, 4)
    quarter_dates = reporting_quarter_dates(quarter) unless quarter.zero?
    from = args.from.presence || quarter_dates&.first || Date.today.prev_year.iso8601
    to = args.to.presence || quarter_dates&.last || (Date.today + 1).iso8601
    puts "Date range is #{time_period(from:, to:)}." if args.verbose?
  end

  require "utils/github"

  organisation = T.let(nil, T.nilable(String))
  users = if maintainer_report_csv
    []
  elsif (team = args.team.presence)
    team_sections = team.split("/")
    organisation = team_sections.first.presence
    team_name = team_sections.last.presence
    if team_sections.length != 2 || organisation.nil? || team_name.nil?
      odie "Team must be in the format `organisation/team`!"
    end

    puts "Getting members for #{organisation}/#{team_name}..." if args.verbose?
    GitHub.members_by_team(organisation, team_name).keys
  elsif requested_users.present?
    requested_users
  else
    puts "Getting members for Homebrew/maintainers..." if args.verbose?
    GitHub.members_by_team("Homebrew", "maintainers").keys
  end
  user_names = users.to_h { |user| [user, user] }

  repositories = if maintainer_report_csv
    organisation = "Homebrew"
    PRIMARY_REPOS
  elsif (org = organisation.presence) || (org = args.organisation.presence)
    organisation = org
    puts "Getting repositories for #{organisation}..." if args.verbose?
    GitHub.organisation_repositories(organisation, from, to, args.verbose?)
  elsif (repos = args.repositories.presence) && repos.length == 1 && (first_repository = repos.first)
    case first_repository
    when "primary"
      PRIMARY_REPOS
    else
      Array(first_repository)
    end
  elsif (repos = args.repositories.presence)
    organisations = repos.map { |repository| repository.split("/").first }.uniq
    odie "All repositories must be under the same user or organisation!" if organisations.length > 1

    repos
  else
    PRIMARY_REPOS
  end
  organisation ||= repositories.fetch(0).split("/").fetch(0)
  repository_refs = prepare_contribution_repositories(repositories, required: maintainer_report_csv.present?)

  lead_maintainers = T.let({}, T::Hash[String, T::Boolean])
  maintainer_since_dates = T.let({}, T::Hash[String, T.nilable(String)])
  if maintainer_report_csv
    user_names, lead_maintainers, maintainer_since_dates = maintainer_report_users(repository_refs, to)
  end

  results = scan_contributions(
    organisation, repositories, repository_refs, user_names, from:, to:,
    skip_reviews_if_lead_met: maintainer_report_csv.present?,
    progress:                 maintainer_report_csv.present? || args.verbose?
  )
  grand_totals = results.transform_values { |user_results| total(user_results) }

  if maintainer_report_csv
    csv = generate_maintainer_report_csv(
      results, grand_totals, user_names, lead_maintainers, maintainer_since_dates, to
    )
    filename = "brew-contributions-#{from}-to-#{to}"
    filename += "-#{user_names.keys.map(&:downcase).sort.join("-")}" if requested_users.present?
    File.write("#{filename}.csv", csv)
    puts csv
    return
  end

  user_names.each_key do |username|
    grand_total = grand_totals.fetch(username)
    greater_than_total = T.let(grand_total.fetch(:merged_pr_author_hit_cap, 0).positive?, T::Boolean)
    contributions = CONTRIBUTION_TYPES.keys.filter_map do |type|
      type_count = grand_total[type]
      next if type_count.nil? || type_count.zero?

      count_prefix = ""
      if ([:merged_pr_author, :merged_pr].include?(type) && grand_total.fetch(:merged_pr_author_hit_cap,
                                                                              0).positive?) ||
         (type == :approved_pr_review && type_count >= MAX_PR_SEARCH) || type_count >= MAX_CONTRIBUTIONS
        greater_than_total ||= true
        count_prefix = ">="
      end

      pretty_type = CONTRIBUTION_TYPES.fetch(type)
      "#{count_prefix}#{Utils.pluralize("time", type_count, include_count: true)} (#{pretty_type})"
    end
    qualifying_total = contribution_count(
      grand_total.slice(*QUALIFYING_CONTRIBUTION_TYPES),
    )
    total = Utils.pluralize("time", qualifying_total, include_count: true)
    total_prefix = ">=" if greater_than_total
    contributions << "#{total_prefix}#{total} (total)"

    contributions_string = [
      "#{username} contributed",
      *contributions.to_sentence,
      "#{time_period(from:, to:)}.",
    ].join(" ")
    if args.csv?
      $stderr.puts contributions_string
    else
      puts contributions_string
    end
  end

  return unless args.csv?

  $stderr.puts
  puts generate_csv(grand_totals)
end

#scan_contributions(organisation, repositories, repository_refs, users, from:, to:, skip_reviews_if_lead_met:, progress:) ⇒ Hash{String => Hash{String => Hash{Symbol => Integer}}}

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.

Parameters:

Returns:



334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
# File 'dev-cmd/contributions.rb', line 334

def scan_contributions(organisation, repositories, repository_refs, users, from:, to:,
                       skip_reviews_if_lead_met:, progress:)
  results = users.to_h do |user, _|
    user_results = repositories.to_h do |repository|
      [repository, CONTRIBUTION_TYPES.keys.to_h { |type| [type, 0] }]
    end
    [user, user_results]
  end

  require "utils/github"
  github_users = users.keys.to_h { |user| [user, github_username_for(user, to:)] }
  git_authored_pull_requests = users.keys.to_h do |user|
    [user, repositories.to_h { |repository| [repository, Set.new] }]
  end
  git_merged_pull_requests = users.keys.to_h do |user|
    [user, repositories.to_h { |repository| [repository, Set.new] }]
  end
  repository_refs.each do |repository, (repository_path, ref)|
    require "utils/git"
    output = Utils.safe_popen_read(
      Utils::Git.git, "-C", repository_path, "log", ref, "--since=#{from}", "--before=#{to}",
      "--format=%H%x1f%P%x1f%an%x1f%ae%x1f%B%x1e"
    )
    authored_pull_requests = users.keys.to_h { |user| [user, Set.new] }
    merged_pull_requests = users.keys.to_h { |user| [user, Set.new] }
    parse_git_log(output, users, authored_pull_requests:, merged_pull_requests:).each do |user, counts|
      results.fetch(user)[repository] = counts
      git_authored_pull_requests.fetch(user)[repository] = authored_pull_requests.fetch(user)
      git_merged_pull_requests.fetch(user)[repository] = merged_pull_requests.fetch(user)
    end
  end

  merged_range = "#{from}..#{Date.iso8601(to).prev_day.iso8601}"
  users.each_key do |user|
    github_user = github_users.fetch(user)
    next if github_user.nil?

    cache_key = ["merged-at", organisation, github_user, merged_range].join("\0")
    merged_pull_requests = github_search_with_rate_limit(cache_key, to:) do
      GitHub.search_issues("", is: "merged", user: organisation, author: github_user, merged: merged_range)
    rescue GitHub::API::ValidationFailedError
      opoo "Couldn't search GitHub for PRs authored by #{github_user}. Their profile might be private. " \
           "Defaulting to 0."
      []
    end
    capped_merged_pull_requests = merged_pull_requests.length >= MAX_PR_SEARCH
    if capped_merged_pull_requests
      results.fetch(user).fetch(repositories.fetch(0))[:merged_pr_author_hit_cap] =
        1
    end
    merged_pull_requests.each do |pull_request|
      repository = pull_request.fetch("repository_url").delete_prefix("#{GitHub::API_URL}/repos/")
      next unless repositories.include?(repository)

      authored_pull_requests = git_authored_pull_requests.fetch(user).fetch(repository)
      merged_pull_request_ids = git_merged_pull_requests.fetch(user).fetch(repository)
      add_merged_pull_request_id(pull_request, authored_pull_requests, merged_pull_request_ids)
    end
    repositories.each do |repository|
      counts = results.fetch(user).fetch(repository)
      authored_pull_requests = git_authored_pull_requests.fetch(user).fetch(repository)
      merged_pull_request_ids = git_merged_pull_requests.fetch(user).fetch(repository)
      update_merged_pull_request_counts(counts, authored_pull_requests, merged_pull_request_ids)
    end
    next unless skip_reviews_if_lead_met
    next unless capped_merged_pull_requests
    next if lead_activity_met?(results.fetch(user))

    repositories.each do |repository|
      break if lead_activity_met?(results.fetch(user))

      repository_counts = results.fetch(user).fetch(repository)
      repository_total = contribution_count(repository_counts.slice(*QUALIFYING_CONTRIBUTION_TYPES))
      qualifying_total = contribution_count(total(results.fetch(user)).slice(*QUALIFYING_CONTRIBUTION_TYPES))
      next if repository_total >= LEAD_REPOSITORY_ACTIVITY_THRESHOLD &&
              qualifying_total >= MAINTAINER_ACTIVITY_THRESHOLD

      $stderr.puts "Querying merged-PR search for #{user} in #{repository}..." if progress
      cache_key = ["merged-at", repository, github_user, merged_range].join("\0")
      repository_pull_requests = github_search_with_rate_limit(cache_key, to:) do
        GitHub.search_issues("", is: "merged", repo: repository, author: github_user, merged: merged_range)
      end
      authored_pull_requests = git_authored_pull_requests.fetch(user).fetch(repository)
      merged_pull_request_ids = git_merged_pull_requests.fetch(user).fetch(repository)
      repository_pull_requests.each do |pull_request|
        add_merged_pull_request_id(pull_request, authored_pull_requests, merged_pull_request_ids)
      end
      update_merged_pull_request_counts(repository_counts, authored_pull_requests, merged_pull_request_ids)
    end
  end

  review_users = github_users.filter_map { |user, github_user| [user, github_user] if github_user }
  review_users.reject! { |user, _| lead_activity_met?(results.fetch(user)) } if skip_reviews_if_lead_met
  review_users.each_with_index do |(user, github_user), index|
    if progress
      $stderr.puts "Querying approved-review search for #{user} (#{index + 1}/#{review_users.length})..."
    end
    cache_key = ["approved", organisation, github_user, from, to].join("\0")
    approved_reviews = github_search_with_rate_limit(cache_key, to:) do
      GitHub.search_approved_pull_requests_in_user_or_organisation(organisation, github_user, from:, to:)
    end
    capped_reviews = approved_reviews.length >= MAX_PR_SEARCH
    results.fetch(user).fetch(repositories.fetch(0))[:approved_pr_review_hit_cap] = 1 if capped_reviews
    approved_reviews.each do |pull_request|
      repository = pull_request.fetch("repository_url").delete_prefix("#{GitHub::API_URL}/repos/")
      next unless repositories.include?(repository)

      increment_contribution_count(results.fetch(user).fetch(repository), :approved_pr_review)
    end
    next unless skip_reviews_if_lead_met
    next unless capped_reviews
    next if lead_activity_met?(results.fetch(user))

    repositories.each do |repository|
      break if lead_activity_met?(results.fetch(user))

      repository_counts = results.fetch(user).fetch(repository)
      repository_total = contribution_count(repository_counts.slice(*QUALIFYING_CONTRIBUTION_TYPES))
      qualifying_total = contribution_count(total(results.fetch(user)).slice(*QUALIFYING_CONTRIBUTION_TYPES))
      next if repository_total >= LEAD_REPOSITORY_ACTIVITY_THRESHOLD &&
              qualifying_total >= MAINTAINER_ACTIVITY_THRESHOLD

      $stderr.puts "Querying approved-review search for #{user} in #{repository}..." if progress
      cache_key = ["approved", repository, github_user, from, to].join("\0")
      repository_reviews = github_search_with_rate_limit(cache_key, to:) do
        GitHub.search_issues("", is: "pr", review: "approved", repo: repository, reviewed_by: github_user,
                             from:, to:)
      end
      repository_counts[:approved_pr_review] = repository_reviews.length
    end
  end

  results
end