Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Find GitHub team PR counts
# frozen_string_literal: true
# https://gist.github.com/borischerkasky/7acc8b19e7b5c6b044bf92ab6f467126
require 'awesome_print'
require 'httparty'
class TeamPrStatistics
attr_accessor :stats
class Stat
attr_accessor :titles
attr_reader :name
def initialize(name)
@name = name
@titles = []
end
end
def initialize
@owner = 'org'
@repos = %w[repo]
@stats = {}
uname = 'IanVaughan'
token = 'f36c1....' # Create a personal token on github, don't forget to SSO Enable it
@auth = { username: uname, password: token }
@headers = { 'User-Agent' => 'Httparty', 'Accept' => 'application/vnd.github.mockingbird-preview' }
end
def run_statistics
@repos.each do |repo_name|
statistics_for_repo(repo_name)
end
@stats
end
def statistics_for_repo(repo_name)
puts ">>> Running statistics for repo: #{repo_name} <<<"
url = "https://api.github.com/repos/#{@owner}/#{repo_name}/pulls?per_page=100&state=all"
loop do
puts "url:#{url.inspect}"
return @stats if url == '' || url.nil?
puts "*** fetching #{url}"
res = HTTParty.get(url, basic_auth: @auth, headers: @headers)
bodies = JSON.parse(res.body)
puts "got #{bodies.size} prs..."
done = count_prs(bodies, repo_name)
return @stats if done
url = get_next_page(res)
end
end
private
def get_next_page(res)
res.headers['link']&.split(',')&.select { |x| x.include? 'next' }&.first&.split(';')&.first&.gsub(/[ ><]/, '')
end
def count_prs(current_pr_bodies, repo_name)
current_pr_bodies.each do |pr|
reviewers = get_reviewers(pr['number'], repo_name)
count_reviewers(pr['title'], reviewers)
end
false
end
def get_reviewers(pr_number, repo)
reviewers = []
url = "https://api.github.com/repos/#{@owner}/#{repo}/issues/#{pr_number}/timeline"
puts "getting reviewers for: #{url}"
res = HTTParty.get(url, basic_auth: @auth, headers: @headers)
bodies = JSON.parse(res.body)
review_requested_event = bodies.select { |x| x['event'] == 'review_requested' }
review_requested_event.each do |event|
reviewers << event['requested_reviewer']['login']
end
reviewers.uniq
end
def count_reviewers(title, reviewers)
reviewers.each do |reviewer|
@stats[reviewer] = Stat.new(reviewer) if @stats[reviewer].nil?
@stats[reviewer].titles << title
end
end
end
puts 'Starting...'
foo = TeamPrStatistics.new
puts 'Running...'
stats = foo.run_statistics
puts 'Getting...'
stats.each { |k, v| ap "#{k} - #{v.titles.size}" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment