githubhandler

Wrappers for Github Web-API Bindings

Functions

iso_now()

Creates ISO 8601 timestamp in format YYYY-MM-DDTHH:MM:SSZ as required by Github

Classes

AiohttpGitHubHandler([token, dry_run, …])

GitHubHandler using Aiohttp for HTTP requests

CardContentType

ContentType for Project Cards

CheckRunConclusion

Conclusion of Github Check Run

CheckRunStatus

State of Github Check Run

Event(data, *, event, delivery_id)

Adds get(path) method to Github Webhook event

GitHubAppHandler(session, app_name, app_key, …)

Handles interaction with Github as App

GitHubHandler([token, dry_run, to_user, …])

Handles interaction with GitHub

IssueState

State for Github Issues

MergeMethod

Merge method

ReviewState

Pull request review state

Documentation

class bioconda_utils.githubhandler.AiohttpGitHubHandler(token=None, dry_run=False, to_user='bioconda', to_repo='bioconda-recipes', installation=None)[source]

Bases: bioconda_utils.githubhandler.GitHubHandler

GitHubHandler using Aiohttp for HTTP requests

Parameters
  • session – Aiohttp Client Session object

  • requester – Identify self (e.g. user agent)

create_api_object(session, requester, *args, **kwargs)[source]

Create API object

Return type

None

class bioconda_utils.githubhandler.CardContentType

Bases: enum.Enum

ContentType for Project Cards

class bioconda_utils.githubhandler.CheckRunConclusion

Bases: enum.Enum

Conclusion of Github Check Run

bioconda_utils.githubhandler.CheckRunStatus

State of Github Check Run

alias of bioconda_utils.githubhandler.CheckRunState

class bioconda_utils.githubhandler.Event(data, *, event, delivery_id)[source]

Bases: gidgethub.sansio.Event

Adds get(path) method to Github Webhook event

get(path, altvalue=<class 'KeyError'>)[source]

Get subkeys from even data using slash separated path

Return type

str

class bioconda_utils.githubhandler.GitHubAppHandler(session, app_name, app_key, app_id, client_id, client_secret)[source]

Bases: object

Handles interaction with Github as App

Parameters
  • session (ClientSession) – Use this session to make calls to the Github API

  • app_name (str) – The name of the App. This is also used as HTTP user agent identifier.

  • app_key (str) – A PEM key used to sign JWT to obtain temporary bearer tokens for accessing the Github API.

  • app_id (str) – This number identifies our App at Github.

  • client_id (str) – This number identifies our App at Github when logging in on behalf of users via OAUTH.

  • client_secret (str) – The secret authenticating us when logging in on behalf of users via OAUTH

ACCESS_TOKEN = '/login/oauth/access_token'

URL templete for calls to OAUTH access_token

AUTHORIZE = '/login/oauth/authorize{?client_id,client_secret,redirect_uri,state,login}'

URL template for calls to OAUTH authorize

DOMAIN = 'https://github.com'

Base URL for calls to oauth login

INSTALLATION = '/repos/{owner}/{repo}/installation'

Get installation info

INSTALLATION_TOKEN = '/app/installations/{installation_id}/access_tokens'

Github API url for creating an access token for a specific installation of an app.

JWT_RENEW_PERIOD = 600

Lifetime of JWT in seconds

app_id = None

ID of app

app_key = None

Authorization key

client_id = None

OAUTH client ID

client_secret = None

OAUTH client secret

static generate_nonce(nbytes=16)[source]

Generates a random string

Fetches nbytes of random data from os.urandom and passes them through base64 encoding.

get_app_jwt()[source]

Returns JWT authenticating as this app

Return type

str

async get_github_api(dry_run, to_user, to_repo, installation=None)[source]

Returns the GitHubHandler for the installation the event came from

Return type

GitHubHandler

async get_github_user_api(token)[source]

Returns the GitHubHandler for a user given a token

Return type

GitHubHandler

async get_installation_id(user, repo)[source]

Retrieve installation ID given user and repo

async get_installation_token(installation, name=None)[source]

Returns OAUTH token for installation referenced in event

Return type

str

name = None

Name of app

async oauth_github_user(redirect, session, params)[source]

Acquires AiohttpGitHubHandler for user via OAuth

This must be called from an aiohttp.web server with the aiohttp-session active for session management.

If the user was not yet logged in (has no token in the session), this will raise a web.HTTPFound exception to redirect the user’s browser to Github where the app can be authorized to act on the users behalf. If the user OKs this, Github redirects the user back to the URL given in redirect. The code behind that URL should call this function again, passing the parameters from Github. Using those parameters, an OAUTH token is acquired, used to create an AiohttpGitHubHandler object and that object initilized to fetch the users details (calling login to acquire user name and avatar).

Details:

Two parameters are passed through the redirect calls. The state parameter is a nonce generated to avoid cross-site request forgery. It is stored in the users session and must be passed back identically on the second call. The code parameter is the secret used to acquire the OAUTH token on the second call to this method.

Two values are stored in the user’s session. The nonce mentioned above and the OAUTH token. A short path attempts to use an existing token to re-authenticate an already logged in user.

Parameters
  • redirect – URL to redirect to for authentication callback. Usually, this is the URL from which you called this function, so that it gets called again with the parameters send by GitHub.

  • session – Session for making calls to Github API

  • params – URL parameters that were sent by GitHub.

Returns

The API client object with the user logged in.

static parse_isotime(timestr)[source]

Converts UTC ISO 8601 time stamp to seconds in epoch

Return type

int

class bioconda_utils.githubhandler.GitHubHandler(token=None, dry_run=False, to_user='bioconda', to_repo='bioconda-recipes', installation=None)[source]

Bases: object

Handles interaction with GitHub

Parameters
  • token (Optional[str]) – OAUTH token granting permissions to GH

  • dry_run (bool) – Don’t actually modify things if set

  • to_user (str) – Target User/Org for PRs

  • to_repo (str) – Target repository within to_user

STATE

alias of IssueState

api = None

Gidgethub API object

avatar_url = None

User avatar URL

async check_protections(pr_number, head_sha=None)[source]

Check whether PR meets protection requirements

Parameters
  • pr_number (int) – issue number of PR

  • head_sha (Optional[str]) – if given, check that this is still the latest sha

Return type

Tuple[Optional[bool], str]

abstract create_api_object(*args, **kwargs)[source]

Create API object

async create_check_run(name, head_sha, details_url=None, external_id=None)[source]

Create a check run

Parameters
  • name (str) – The name of the check, e.g. bioconda-test

  • head_sha (str) – The sha of the commit to check

  • details_url (Optional[str]) – URL for “View more details on <App name>” link

  • external_id (Optional[str]) – ID for us

Return type

int

Returns

The ID of the check run.

async create_comment(number, body)[source]

Create issue comment

Parameters
  • number (int) – Issue number

  • body (str) – Comment content

Return type

int

async create_pr(title, from_branch, from_user=None, to_branch='master', body=None, maintainer_can_modify=True, draft=False)[source]

Create new PR

Parameters
  • title (str) – Title of new PR

  • from_branch (str) – Name of branch from which PR asks to pull (aka head)

  • from_user (Optional[str]) – Name of user/org in from which to pull

  • to_branch (Optional[str]) – Name of branch into which to pull (aka base, default: master)

  • body (Optional[str]) – Body text of PR

  • maintainer_can_modify (bool) – Whether to allow maintainer to modify from_branch

  • draft (bool) – whether PR is draft

Return type

Dict[Any, Any]

async create_project_card(column_id, note=None, content_id=None, content_type=None, number=None)[source]

Create a new project card

In addition to column_id, you must provide either: - The note parameter for a free text note card - The content_type specifying whether the card references a PR or an Issue,

and the content_id with the id field from the PR or Issue. Note that PRs have two IDs, once as their issue baseclass and once as PR. You must use the latter for PRs.

  • The number giving either PR or Issue number. Will trigger one or two extra API calls to fill in the content_type and content_id fields.

Parameters
Return type

Dict[str, Any]

Returns

Dict describing newly created card. Empty if no card.

async delete_branch(ref)[source]

Delete a branch (ref)

Parameters

ref (str) – Name of reference/branch

Return type

None

async delete_project_card(card_id)[source]

Deletes a project card

Parameters

card_id (int) – ID of the card to delete

Return type

bool

Returns

True if the deletion succeeded

async delete_project_card_from_column(column_id, number)[source]

Deletes a project card identified by PR/Issue number from column

Parameters
  • column_id (int) – ID of project card column

  • number (int) – PR/Issue number

Return type

bool

Returns

True if the deleteion succeeded

dry_run = None

If set, no actual modifying actions are taken

for_json()[source]

Return JSON repesentation of object

async get_branch_protection(branch='master')[source]

Retrieve protection settings for branch

Parameters

branch (str) – Branch for which to get protection settings

Return type

Dict[str, Any]

Returns

Deep dict as example below. Protections not in place will not be present in dict.

required_status_checks:  # require status checks to pass
    strict: False        # require PR branch to be up to date with base
    contexts:            # list of status checks required
       - bioconda-test
    enforce_admins:      # admins, too, must follow rules
       - enabled: True
required_pull_request_reviews:          # require approving review
    required_approving_review_count: 1  # 1 - 6 valid
    dismiss_stale_reviews: False        # auto dismiss approval after push
    require_code_owner_reviews: False
    dismissal_restrictions:             # specify who may dismiss reviews
       users:
         - login: bla
       teams:
         - id: 1
         - name: Bl Ub
         - slug: bl-ub
restrictions:             # specify who may push
  users:
    - login: bla
  teams:
    - id: 1
enforce_admins:
  enabled: True  # apply to admins also

async get_check_runs(sha)[source]

List check runs for sha

Parameters

sha (str) – The commit SHA for which to search for check runs

Return type

List[Dict[str, Any]]

Returns

List of check run “objects”

async get_contents(path, ref=None)[source]

Get contents of a file in repo

Parameters
  • path (str) – file path

  • ref (Optional[str]) – git reference (branch, commit, tag)

Return type

str

Returns

The contents of the file

Raises
  • RuntimeError if the content encoding is not understood.

  • (Should always be base64)

get_file_relurl(path, branch_name='master')[source]

Format domain relative url for path on branch_name

Return type

str

async get_issue(number)[source]

Retrieve a single PR or Issue by its number

Parameters

number (int) – PR/Issue number

Return type

Dict[str, Any]

Returns

The dict will contain a ‘pull_request’ key (containing dict) if the Issue is a PR.

async get_pr_count(user)[source]

Get the number of PRs opened by user

Parameters

user – login of user to query

Return type

int

Returns

Number of PRs that user has opened so far

async get_pr_modified_files(number)[source]

Retrieve the list of files modified by the PR

Parameters

number (int) – PR issue number

Return type

List[Dict[str, Any]]

async get_pr_reviews(pr_number)[source]

Get reviews filed for a PR

Parameters

pr_number (int) – Number of PR

Return type

List[Dict[str, Any]]

Returns

List of dictionaries each having body (str), state (ReviewState), and commit_id (SHA, str) as well as a user dict.

async get_project_card(card_id)[source]

Get a project card

Parameters

card_id (int) – ID number of project card

Return type

Dict[str, Any]

Returns

Empty dict if the project card was not found

get_prs(from_branch=None, from_user=None, to_branch=None, number=None, state=None)[source]

Retrieve list of PRs matching parameters

Parameters
  • from_branch (Optional[str]) – Name of branch from which PR asks to pull

  • from_user (Optional[str]) – Name of user/org in from which to pull (default: from auth)

  • to_branch (Optional[str]) – Name of branch into which to pull (default: master)

  • number (Optional[int]) – PR number

Return type

List[Dict[Any, Any]]

async get_prs_from_sha(head_sha, only_open=False)[source]

Searches for PRs matching head_sha

Parameters
  • head_sha (str) – The head checksum to search for

  • only_open – If true, return only open PRs

Result:

List of PR numbers.

Return type

List[int]

async get_statuses(sha)[source]

List status checks for sha

Parameters

sha (str) – The commit SHA for which to find statuses

Return type

List[Dict[str, Any]]

Returns

List of status “objects”

async get_team_id(team_slug=None, team_name=None)[source]

Get the Team ID from the Team slug

If both are set, team_slug is tried first.

Parameters
  • team_slug (Optional[str]) – urlized team name, e.g. “justice-league” for “Justice League”

  • team_name (Optional[str]) – alternative, use normal name (requires extra API call internally)

Return type

Optional[int]

Returns

Team ID if found, otherwise None

async get_user()[source]

Fetches the user’s info

Return type

Dict[str, Any]

Returns

Empty dict if the request failed

async get_user_orgs()[source]

Fetches the user’s orgs

Return type

List[str]

Returns

Empty list if the request failed

installation = None

The installation ID if this instance is connected to an App

async is_member(username, team=None)[source]

Check user membership

Parameters
  • username (str) – Name of user for whom to check membership

  • team (Union[str, int, None]) – Name, Slug or ID of team to check

Return type

bool

Returns

True if the user is member of the organization, and, if team is provided, if user is member of that team.

async is_org()[source]

Check if we are operating on an organization

Return type

bool

async is_team_member(username, team)[source]

Check if user is a member of given team

Parameters
  • username (str) – Name of user to check

  • team (Union[str, int]) – ID, Slug or Name of team to check

Return type

bool

Returns

True if the user is a member of the team

async iter_comments(number)[source]

List comments for issue

Return type

List[Dict[str, Any]]

iter_pr_commits(number)[source]

Create iterator over commits in a PR

iter_teams()[source]

List organization teams

Return type

AsyncIterator[Dict[str, Any]]

Returns

Async iterator over dicts, containing id, name, slug, description, etc.

async list_project_cards(column_id)[source]

List cards in a project column

Parameters

column_id (int) – ID number of project column

Return type

List[Dict[str, Any]]

async login(*args, **kwargs)[source]

Log into API (fills username)

Return type

bool

async merge_pr(number, title=None, message=None, sha=None, method=<MergeMethod.squash: 2>)[source]

Merge a PR

Parameters
  • number (int) – PR Number

  • title (Optional[str]) – Title for the commit message

  • message (Optional[str]) – Message to append to automatic message

  • sha (Optional[str]) – SHA PR head must match

  • merge_methodMergeMethod to use. Defaults to squash.

Returns

True if successful and message

Return type

Tuple

async modify_check_run(number, status=None, conclusion=None, output_title=None, output_summary=None, output_text=None, output_annotations=None, actions=None)[source]

Modify a check runs

Parameters
  • number (int) – id number of check run

  • status (Optional[CheckRunState]) – current status

  • conclusion (Optional[CheckRunConclusion]) – result of check run, needed if status is completed

  • output_title (Optional[str]) – title string for result window

  • output_summary (Optional[str]) – subtitle/summary string for result window (reqired if title given)

  • output_text (Optional[str]) – Markdown text for result window

  • annotations – List of annotated code pieces, each has to have path, start_line and end_line, annotation_level (notice, warning, failure), and a message. May also have may have start_column and end_column (if only one line), title and raw_details.

  • actions (Optional[List[Dict[~KT, ~VT]]]) – List of up to three “actions” as dict of label, description and identifier

Return type

Dict[str, Any]

Returns

Check run “object” as dict.

async modify_issue(number, labels=None, title=None, body=None)[source]

Modify existing issue (PRs are issues)

Parameters
Return type

Dict[Any, Any]

async pr_is_merged(number)[source]

Checks whether a PR has been merged

Parameters

number – PR Number

Return type

bool

Returns

True if the PR has been merged.

async pr_update_branch(number)[source]

Updates PR branch

Merges changes to “base” into “head”

Return type

bool

property rate_limit

Last recorded rate limit data

Return type

RateLimit

repo = None

Name of the Repo

async search_issues(author=None, pr=False, issue=False, sha=None, closed=None)[source]

Search issues/PRs on our repos

Parameters
  • author – login name of user to search

  • sha – SHA of commit to search for

  • pr – whether to consider only PRs

  • issue – whether to consider only non-PR issues

  • closed – search only closed if true, only open if false

set_oauth_token(token)[source]

Update oauth token for the wrapped GitHubAPI object

Return type

None

token = None

API Bearer Token

async update_comment(number, body)[source]

Update issue comment

Parameters
  • number (int) – Comment number (NOT PR NUMBER!)

  • body (str) – Comment content

Return type

int

user = None

Owner of the Repo

username = None

Login username

var_default = None

Default variables for API calls

class bioconda_utils.githubhandler.IssueState

Bases: enum.Enum

State for Github Issues

class bioconda_utils.githubhandler.MergeMethod

Bases: enum.Enum

Merge method

class bioconda_utils.githubhandler.ReviewState

Bases: enum.Enum

Pull request review state

bioconda_utils.githubhandler.iso_now()[source]

Creates ISO 8601 timestamp in format YYYY-MM-DDTHH:MM:SSZ as required by Github

Return type

str