Query the Github API to retrieve the needed infos.
518072
def retrieve_info(self):
        """"""

        path = urlparse(self.url).path
        path = path.split('/')[1:]

        sanity_filter = re.compile('[\da-z-_]+', re.IGNORECASE)
        self.product = sanity_filter.match(path[0]).group(0)
        self.component = sanity_filter.match(path[1]).group(0)
        self.issue_id = int(path[3])

        github_url = '%s/%s/%s/issues/%s' % (_URL_BASE,
                                             self.product,
                                             self.component,
                                             self.issue_id)

        result = requests.get(github_url)
        self.status_code = result.status_code

        if result.status_code == 200:
            result = result.json()
            self.title = result['title']
            self.reporter = result['user']['login']
            if result['assignee'] is not None:
                self.assignee = result['assignee']['login']
            self.status = result['state']
            self.created_at = result['created_at']
            self.updated_at = result['updated_at']
            self.closed_at = result['closed_at']
        elif result.status_code == 404:
            self.title = 'private issue'
1151730
def _github_count(self, url):
        
        url = self.url_api + url + "&per_page=1"
        # if we have authentication details use them as we get better
        # rate-limiting.
        if self.username and self.auth_token:
            auth = (self.username, self.auth_token)
        else:
            auth = None
        try:
            info = self.py3.request(url, auth=auth)
        except (self.py3.RequestException):
            return
        if info and info.status_code == 200:
            return int(info.json()["total_count"])
        if info.status_code == 422:
            if not self.repo_warning:
                self.py3.notify_user("Github repo cannot be found.")
                self.repo_warning = True
        return "?"
1205235
def github_repos(organization, github_url, github_token):
    """"""
    # Get github repos
    headers = {"Authorization": "token {}".format(github_token)}
    next_cursor = None

    while next_cursor is not False:
        params = {'query': query, 'variables': {
            'organization': organization, 'cursor': next_cursor}}
        response = requests.post(github_url, headers=headers, json=params)
        result = response.json()
        if response.status_code != 200 or 'errors' in result:
            raise ValueError("Github api error %s" % (
                response.content.decode('utf8'),))

        repos = jmespath.search(
            'data.organization.repositories.edges[].node', result)
        for r in repos:
            yield r
        page_info = jmespath.search(
            'data.organization.repositories.pageInfo', result)
        if page_info:
            next_cursor = (page_info['hasNextPage'] and
                           page_info['endCursor'] or False)
        else:
            next_cursor = False
81371
def read_url(url):
    """"""
    logging.debug('reading {url} ...'.format(url=url))
    token = os.environ.get("BOKEH_GITHUB_API_TOKEN")
    headers = {}
    if token:
        headers['Authorization'] = 'token %s' % token
    request = Request(url, headers=headers)
    response = urlopen(request).read()
    return json.loads(response.decode("UTF-8"))
525757
def get_files_from_github(user_and_repo, filedir, regex, prefer_tags):
    '''  '''
    github_url = f'https://api.github.com/repos/{user_and_repo}'
    args = f'?per_page={N_RESULTS}'
    results = []
    json_data = None

    # Determine the right url
    if not prefer_tags:
        url = f'{github_url}/releases{args}'
        json_data = requests.get(url).json()

    if not json_data:
        url = f'{github_url}/tags{args}'
        json_data = requests.get(url).json()

    logger.debug(f'[+] Using {url} as base url.')

    # Get all the releases/tags available
    results = json_data
    for n_page in range(2, 1000):
        logger.debug(f'[+] Requesting page {n_page} of releases/tags ..')
        json_data = requests.get(f'{url}&page={n_page}').json()
        results += json_data

        if len(json_data) < N_RESULTS:
            break

    if not results:
        raise ValueError(f'No releases/tags for {user_and_repo}')

    directories = {}
    for result in results:
        name = result['name']
        m = re.match(regex, name)
        if not m:
            continue

        name = m.groups()[0]

        logger.debug(f'[+] Downloading zip file for {name} version ..')

        # Download zip file and extract in temporary directory
        zip_url = result['zipball_url']
        zf = requests.get(zip_url, allow_redirects=True)
        z = zipfile.ZipFile(io.BytesIO(zf.content))
        output_dir = f'{filedir}/{z.namelist()[0]}'

        z.extractall(path=filedir)
        directories[name] = output_dir

    return directories
815959
def wiki(self):
        
        date = self.pull.created_at.strftime("%m/%d/%Y %H:%M")
        return "{} {} ({} [{} github])\n".format(self.pull.avatar_url, self.pull.body, date,
                                                 self.pull.html_url)
1210621
def search_repos(query)
      gitomator_context.hosting.search_repos(query).map {|r| r.full_name}
    end
1142969
def get_content(session, urls):
    

    content = ""
    for url in urls:
        try:
            logger.debug("GET changelog from {url}".format(url=url))
            if "https://api.github.com" in url and url.endswith("releases"):
                # this is a github API release page, fetch it if token is set
                if not GITHUB_API_TOKEN:
                    logger.warning("Fetching release pages requires CHANGELOGS_GITHUB_API_TOKEN "
                                   "to be set")
                    continue
                resp = session.get(url, headers={
                    "Authorization": "token {}".format(GITHUB_API_TOKEN)
                })
                if resp.status_code == 200:
                    for item in resp.json():
                        content += "\n\n{}\n{}".format(item['tag_name'], item["body"])
            else:
                resp = session.get(url)
                if resp.status_code == 200:
                    content += "\n\n" + resp.text
        except requests.ConnectionError:
            pass
    return content
688599
def get_pulls_list(project, auth=False, **params):
    """"""
    params.setdefault("state", "closed")
    url = "https://api.github.com/repos/{project}/pulls".format(project=project)
    if auth:
        headers = make_auth_header()
    else:
        headers = None
    pages = get_paged_request(url, headers=headers, **params)
    return pages
607572
def query_pending_jobs(auth, repo_name=None, return_raw=False):
    """"""
    url = '%s/pending?format=json' % HOST_ROOT
    LOG.debug('About to fetch %s' % url)
    req = requests.get(url, auth=auth, timeout=TCP_TIMEOUT)

    # If the revision doesn't exist on buildapi, that means there are
    # no builapi jobs for this revision
    if req.status_code not in [200]:
        return []

    raw = req.json()

    # If we don't want the data structure to be reduced
    if return_raw:
        return raw

    # If we only want pending jobs of a specific repo
    if repo_name and repo_name in list(raw['pending'].keys()):
        repo_list = [repo_name]
    else:
        repo_list = list(raw['pending'].keys())

    # Data structure to return
    data = {}
    for repo in repo_list:
        data[repo] = {}
        repo_jobs = raw['pending'][repo]
        for revision in repo_jobs.items():
            data[repo][revision[0]] = revision[1]

    return data
214869
def _get_github(self):
        
        from github import Github
        vms("Querying github with user '{}'.".format(self.username))
        g = Github(self.username, self.apikey)
        self._user = g.get_user()
        if self._user is None:
            raise ValueError("Can't authenticate to github with '{}'.".format(self.username))
        #The github user authenticating always has to be specified; however the user
        #may not be able to see the repo, even if it has access to it. We may need
        #to check the organization repos.
        if self.organization is not None:
            self._org = g.get_organization(self.organization)
            vms("Found github organization '{}'.".format(self._org.name), 2)

            #Next we need to find this repository in the lists available to both
            #the user *and* the organization. If they specified an organization, then we
            #should check that first/exclusively.
            for repo in self._org.get_repos():
                if repo.full_name.lower() == self.name.lower():
                    self._repo = repo
                    vms("Found organization repository '{}'.".format(self._repo.full_name), 2)
                    break
        else:
            for repo in self._user.get_repos():
                if repo.full_name.lower() == self.name.lower():
                    self._repo = repo
                    vms("Found user repository '{}'.".format(self._repo.full_name), 2)
                    break
153211
def get_branch_details(repo: GithubRepository, branch: str) -> Any:
    
    url = ("https://api.github.com/repos/{}/{}/branches/{}"
           "?access_token={}".format(repo.organization,
                                     repo.name,
                                     branch,
                                     repo.access_token))
    response = requests.get(url)

    if response.status_code != 200:
        raise RuntimeError(
            'Failed to get branch details. Code: {}. Content: {}.'.format(
                response.status_code, response.content))

    return json.JSONDecoder().decode(response.content.decode())
221382
def download_api(branch=None) -> str:
    """"""
    habitica_github_api = 'https://api.github.com/repos/HabitRPG/habitica'
    if not branch:
        branch = requests.get(habitica_github_api + '/releases/latest').json()['tag_name']
    curl = local['curl']['-sL', habitica_github_api + '/tarball/{}'.format(branch)]
    tar = local['tar'][
        'axzf', '-', '--wildcards', '*/website/server/controllers/api-v3/*', '--to-stdout']
    grep = local['grep']['@api']
    sed = local['sed']['-e', 's/^[ */]*//g', '-e', 's/  / /g', '-']
    return (curl | tar | grep | sed)()
679102
def get_release(self, id):
        
        if isinstance(id, int):
            headers, data = self._requester.requestJsonAndCheck(
                "GET",
                self.url + "/releases/" + str(id)
            )
            return github.GitRelease.GitRelease(self._requester, headers, data, completed=True)
        elif isinstance(id, (str, unicode)):
            headers, data = self._requester.requestJsonAndCheck(
                "GET",
                self.url + "/releases/tags/" + id
            )
            return github.GitRelease.GitRelease(self._requester, headers, data, completed=True)
771679
def get_gists(self, since=github.GithubObject.NotSet):
        
        assert since is github.GithubObject.NotSet or isinstance(since, datetime.datetime), since
        url_parameters = dict()
        if since is not github.GithubObject.NotSet:
            url_parameters["since"] = since.strftime("%Y-%m-%dT%H:%M:%SZ")
        return github.PaginatedList.PaginatedList(
            github.Gist.Gist,
            self._requester,
            "/gists",
            url_parameters
        )
599848
def get(path, **kwargs):
    """"""
    token = os.environ.get(BE_GITHUB_API_TOKEN)
    if token:
        kwargs["headers"] = {
            "Authorization": "token %s" % token
        }

    try:
        response = requests.get(path, verify=False, **kwargs)
        if response.status_code == 403:
            lib.echo("Patience: You can't pull more than 60 "
                     "presets per hour without an API token.\n"
                     "See https://github.com/mottosso/be/wiki"
                     "/advanced#extended-preset-access")
            sys.exit(lib.USER_ERROR)
        return response
    except Exception as e:
        if self.verbose:
            lib.echo("ERROR: %s" % e)
        else:
            lib.echo("ERROR: Something went wrong. "
                     "See --verbose for more information")
1074898
def url_for_request(query, sort_by: nil, order: nil)
      url = "https://api.github.com/search/issues?q="
      url += ERB::Util.url_encode(query)
      url += "+repo:#{repo_owner}/#{repo_name}"
      url += "&sort=#{sort_by}" if sort_by
      url += "&order=#{order}" if order

      url
    end