class Codeowners::GithubFetcher

Fetch teams and members from GitHub and return them in list

Constants

GITHUB_URL

Public Class Methods

get_owners(github_org, authorization_token) click to toggle source

Fetch teams and members from GitHub. authorization_token is GitHub PAT with read:org scope @return <Array> with GitHub teams and individuals belonging to a given GitHub organization

# File lib/codeowners/github_fetcher.rb, line 15
def get_owners(github_org, authorization_token)
  headers = get_headers(authorization_token)
  base_url = GITHUB_URL + '/orgs/' + github_org
  owners = []
  list_entities(base_url + '/teams', headers) { |team| owners << "@#{github_org}/#{team['slug']}" }
  list_entities(base_url + '/members', headers) { |member| owners << "@#{member['login']}" }
  owners
end

Private Class Methods

get_headers(authorization_token) click to toggle source

Helper method to get properly formatted HTTP headers

# File lib/codeowners/github_fetcher.rb, line 27
def get_headers(authorization_token)
  {
    Accept: 'application/vnd.github.v3+json',
    Authorization: "token #{authorization_token}"
  }
end
get_next_page(response) click to toggle source

Helper method to parse and get URL of the next page from 'link' response header

# File lib/codeowners/github_fetcher.rb, line 47
def get_next_page(response)
  return nil unless response.headers[:link]

  matches = response.headers[:link].match('<([^>]+)>; rel="next"')
  return matches[1] if matches
end
list_entities(first_page, headers) { |entity| ... } click to toggle source

Helper method that loops through all pages if GitHub returns a paged response

# File lib/codeowners/github_fetcher.rb, line 35
def list_entities(first_page, headers)
  next_page = first_page
  loop do
    response = RestClient.get(next_page, headers)
    response_json = JSON.parse(response.body)
    response_json.each { |entity| yield entity }
    next_page = get_next_page(response)
    break unless next_page
  end
end