Python github3.GitHub() Examples

The following are 30 code examples of github3.GitHub(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module github3 , or try the search function .
Example #1
Source File: test_core.py    From flask-githubapp with MIT License 6 votes vote down vote up
def test_events_with_actions_mapped_to_functions(app, mocker):
    github_app = GitHubApp(app)

    function_to_call = MagicMock()
    function_to_call.__name__ = 'foo'  # used to generate response
    function_to_call.return_value = 'foo'  # return data must be serializable

    github_app._hook_mappings['foo.bar'] = [function_to_call]
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({'installation': {'id': 2},
                                            'action': 'bar'}),
                           headers={
                              'X-GitHub-Event': 'foo',
                              'Content-Type': 'application/json'
                           })
        assert resp.status_code == 200
        function_to_call.assert_called_once_with() 
Example #2
Source File: file_fetcher.py    From boundary-layer with Apache License 2.0 6 votes vote down vote up
def _get_github(self):
        try:
            import github3
        except ImportError:
            raise Exception("""
            ERROR: github3.py not installed!  Please install via
              pip install boundary-layer[github]
            and try again.""")

        if self.github_url:
            return github3.GitHubEnterprise(
                url=self.github_url,
                username=self.github_username,
                password=self.github_password,
                token=self.github_token)

        return github3.GitHub(
            username=self.github_username,
            password=self.github_password,
            token=self.github_token) 
Example #3
Source File: core.py    From flask-githubapp with MIT License 6 votes vote down vote up
def _flask_view_func(self):
        functions_to_call = []
        calls = {}

        event = request.headers['X-GitHub-Event']
        action = request.json.get('action')

        self._verify_webhook()

        if event in self._hook_mappings:
            functions_to_call += self._hook_mappings[event]

        if action:
            event_action = '.'.join([event, action])
            if event_action in self._hook_mappings:
                functions_to_call += self._hook_mappings[event_action]

        if functions_to_call:
            for function in functions_to_call:
                calls[function.__name__] = function()
            status = STATUS_FUNC_CALLED
        else:
            status = STATUS_NO_FUNC_CALLED
        return jsonify({'status': status,
                        'calls': calls}) 
Example #4
Source File: github.py    From cc-utils with Apache License 2.0 6 votes vote down vote up
def github_api(
    github_cfg: 'model.GithubConfig',
    session_adapter: SessionAdapter=SessionAdapter.RETRY,
):
    github_url = github_cfg.http_url()
    github_auth_token = github_cfg.credentials().auth_token()

    verify_ssl = github_cfg.tls_validation()

    github_ctor = github_api_ctor(
        github_url=github_url, verify_ssl=verify_ssl,
        session_adapter=SessionAdapter.RETRY,
    )
    github_api = github_ctor(
        token=github_auth_token,
    )

    if not github_api:
        ci.util.fail("Could not connect to GitHub-instance {url}".format(url=github_url))

    return github_api 
Example #5
Source File: test_core.py    From flask-githubapp with MIT License 6 votes vote down vote up
def test_no_target_functions(app, mocker):
    github_app = GitHubApp(app)

    function_to_miss = MagicMock()
    function_to_miss.__name__ = 'foo'  # used to generate response

    github_app._hook_mappings['foo'] = [function_to_miss]
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({'installation': {'id': 2}}),
                           headers={
                              'X-GitHub-Event': 'bar',
                              'Content-Type': 'application/json'
                           })
        assert resp.status_code == 200
        function_to_miss.assert_not_called()
        assert resp.json['status'] == STATUS_NO_FUNC_CALLED
        assert resp.json['calls'] == {} 
Example #6
Source File: test_core.py    From flask-githubapp with MIT License 6 votes vote down vote up
def test_function_exception_raise_500_error(app, mocker):
    github_app = GitHubApp(app)

    function_to_call = MagicMock()
    function_to_call.__name__ = 'foo'  # used to generate response
    function_to_call.side_effect = Exception('foo exception')

    github_app._hook_mappings['foo'] = [function_to_call]
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({'installation': {'id': 2}}),
                           headers={
                              'X-GitHub-Event': 'foo',
                              'Content-Type': 'application/json'
                           })
        assert resp.status_code == 500
        function_to_call.assert_called_once_with() 
Example #7
Source File: github.py    From aegea with Apache License 2.0 6 votes vote down vote up
def update_user(self, name=None, email=None, blog=None,
                    company=None, location=None, hireable=False, bio=None):
        """If authenticated as this user, update the information with
        the information provided in the parameters. All parameters are
        optional.

        :param str name: e.g., 'John Smith', not login name
        :param str email: e.g., 'john.smith@example.com'
        :param str blog: e.g., 'http://www.example.com/jsmith/blog'
        :param str company: company name
        :param str location: where you are located
        :param bool hireable: defaults to False
        :param str bio: GitHub flavored markdown
        :returns: bool
        """
        user = self.user()
        return user.update(name, email, blog, company, location, hireable,
                           bio) 
Example #8
Source File: github-dork.py    From github-dorks with Apache License 2.0 6 votes vote down vote up
def search_wrapper(gen):
    while True:
        gen_back = copy(gen)
        try:
            yield next(gen)
        except StopIteration:
            return
        except github.exceptions.ForbiddenError as e:
            search_rate_limit = gh.rate_limit()['resources']['search']
            # limit_remaining = search_rate_limit['remaining']
            reset_time = search_rate_limit['reset']
            current_time = int(time.time())
            sleep_time = reset_time - current_time + 1
            stderr.write(
                'GitHub Search API rate limit reached. Sleeping for %d seconds.\n\n'
                % (sleep_time))
            time.sleep(sleep_time)
            yield next(gen_back)
        except Exception as e:
            raise e 
Example #9
Source File: github.py    From aegea with Apache License 2.0 6 votes vote down vote up
def rate_limit(self):
        """Returns a dictionary with information from /rate_limit.

        The dictionary has two keys: ``resources`` and ``rate``. In
        ``resources`` you can access information about ``core`` or ``search``.

        Note: the ``rate`` key will be deprecated before version 3 of the
        GitHub API is finalized. Do not rely on that key. Instead, make your
        code future-proof by using ``core`` in ``resources``, e.g.,

        ::

            rates = g.rate_limit()
            rates['resources']['core']  # => your normal ratelimit info
            rates['resources']['search']  # => your search ratelimit info

        .. versionadded:: 0.8

        :returns: dict
        """
        url = self._build_url('rate_limit')
        return self._json(self._get(url), 200) 
Example #10
Source File: github.py    From aegea with Apache License 2.0 6 votes vote down vote up
def login(self, username=None, password=None, token=None,
              two_factor_callback=None):
        """Logs the user into GitHub for protected API calls.

        :param str username: login name
        :param str password: password for the login
        :param str token: OAuth token
        :param func two_factor_callback: (optional), function you implement to
            provide the Two Factor Authentication code to GitHub when necessary
        """
        if username and password:
            self._session.basic_auth(username, password)
        elif token:
            self._session.token_auth(token)

        # The Session method handles None for free.
        self._session.two_factor_auth_callback(two_factor_callback) 
Example #11
Source File: xfu.py    From mi-firmware-updater with GNU General Public License v3.0 6 votes vote down vote up
def upload_fw(file, version, codename, today, variant):
    """
    Upload files to GitHub release
    """
    print("uploading: " + file)
    codename = codename.split('-')[0]
    folder = set_folder(file)
    subprocess.call(['rclone', 'copy', file, 'osdn:/storage/groups/x/xi/xiaomifirmwareupdater/'
                     + folder + '/' + version + '/' + codename + '/', '-v'])
    repository = GIT.repository('XiaomiFirmwareUpdater', f'firmware_xiaomi_{codename}')
    tag = f'{variant}-{today}'
    try:
        release = repository.release_from_tag(tag)  # release exist already
    except exceptions.NotFoundError:
        # create new release
        release = repository.create_release(tag, name=tag,
                                            body=
                                            f"Extracted Firmware from MIUI {file.split('_')[4]}",
                                            draft=False, prerelease=False)
    try:
        asset = release.upload_asset(content_type='application/binary',
                                     name=file, asset=open(file, 'rb'))
        print(f'Uploaded {asset.name} Successfully to release {release.name}')
    except exceptions.UnprocessableEntity:
        print(f'{file} is already uploaded') 
Example #12
Source File: github.py    From aegea with Apache License 2.0 6 votes vote down vote up
def feeds(self):
        """List GitHub's timeline resources in Atom format.

        :returns: dictionary parsed to include URITemplates
        """
        url = self._build_url('feeds')
        json = self._json(self._get(url), 200)
        del json['ETag']
        del json['Last-Modified']

        urls = [
            'timeline_url', 'user_url', 'current_user_public_url',
            'current_user_url', 'current_user_actor_url',
            'current_user_organization_url',
            ]

        for url in urls:
            json[url] = URITemplate(json[url])

        links = json.get('_links', {})
        for d in links.values():
            d['href'] = URITemplate(d['href'])

        return json 
Example #13
Source File: test_core.py    From flask-githubapp with MIT License 6 votes vote down vote up
def test_github_installation_client(app, mocker):
    github_app = GitHubApp(app)
    installation_id = 2
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    mock_client = mocker.patch('flask_githubapp.core.GitHubApp.client')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({'installation': {'id': installation_id}}),
                           headers={
                              'X-GitHub-Event': 'foo',
                              'Content-Type': 'application/json'
                           })
        assert resp.status_code == 200
        github_app.installation_client
        mock_client.login_as_app_installation.assert_called_once_with(github_app.key,
                                                                      github_app.id,
                                                                      installation_id) 
Example #14
Source File: test_core.py    From flask-githubapp with MIT License 6 votes vote down vote up
def test_functions_can_return_no_data(app, mocker):
    github_app = GitHubApp(app)

    function_to_call = MagicMock()
    function_to_call.__name__ = 'foo'  # used to generate response
    function_to_call.return_value = None

    github_app._hook_mappings['foo'] = [function_to_call]
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({'installation': {'id': 2}}),
                           headers={
                              'X-GitHub-Event': 'foo',
                              'Content-Type': 'application/json'
                           })
        assert resp.status_code == 200
        function_to_call.assert_called_once_with() 
Example #15
Source File: labhub_test_case.py    From corobo with MIT License 5 votes vote down vote up
def setUp(self, klasses=None):
        plugins.labhub.github3 = create_autospec(github3)

        self.mock_org = create_autospec(github3.orgs.Organization)
        self.mock_gh = create_autospec(github3.GitHub)
        self.mock_team = create_autospec(github3.orgs.Team)
        self.mock_team.name = PropertyMock()
        self.mock_team.name = 'mocked team'
        self.teams = {
            'coala newcomers': self.mock_team,
            'coala developers': self.mock_team,
            'coala maintainers': self.mock_team,
        }

        self.mock_repo = create_autospec(IGitt.GitHub.GitHub.GitHubRepository)

        plugins.labhub.github3.login.return_value = self.mock_gh
        self.mock_gh.organization.return_value = self.mock_org
        self.mock_org.teams.return_value = [self.mock_team]
        plugins.labhub.github3.organization.return_value = self.mock_org

        # patching
        plugins.labhub.GitHub = create_autospec(IGitt.GitHub.GitHub.GitHub)
        plugins.labhub.GitLab = create_autospec(IGitt.GitLab.GitLab.GitLab)
        plugins.labhub.GitHubToken = create_autospec(IGitt.GitHub.GitHubToken)
        plugins.labhub.GitLabPrivateToken = create_autospec(
            IGitt.GitLab.GitLabPrivateToken)

        if klasses:
            super().setUp(klasses) 
Example #16
Source File: test_core.py    From flask-githubapp with MIT License 5 votes vote down vote up
def test_view_returns_map_of_called_functions_and_returned_data(app, mocker):
    github_app = GitHubApp(app)

    def event_function():
        return 'foo'

    def event_action_function():
        return 'bar'

    def other_event_function():
        return 'baz'

    github_app._hook_mappings = {
        'foo': [event_function],
        'foo.bar': [event_action_function],
        'bar': [other_event_function]
    }
    mocker.patch('flask_githubapp.core.GitHubApp._verify_webhook')
    with app.test_client() as client:
        resp = client.post('/',
                           data=json.dumps({'installation': {'id': 2},
                                            'action': 'bar'}),
                           headers={
                              'X-GitHub-Event': 'foo',
                              'Content-Type': 'application/json'
                           })
        assert resp.status_code == 200
        assert resp.json == {
            'status': 'HIT',
            'calls': {
                'event_function': 'foo',
                'event_action_function': 'bar',
            }
        } 
Example #17
Source File: label_app.py    From actions-chatops with MIT License 5 votes vote down vote up
def get_app(self):
        with open(self.path, 'rb') as key_file:
            client = GitHub()
            client.login_as_app(private_key_pem=key_file.read(),
                        app_id=self.app_id)
        return client 
Example #18
Source File: label_app.py    From actions-chatops with MIT License 5 votes vote down vote up
def get_installation(self, installation_id):
        "login as app installation without requesting previously gathered data."
        with open(self.path, 'rb') as key_file:
            client = GitHub()
            client.login_as_app_installation(private_key_pem=key_file.read(),
                                             app_id=self.app_id,
                                             installation_id=installation_id)
        return client 
Example #19
Source File: update.py    From eddy with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        """
        Main worker.
        """
        update_name = None  # Store update name, i.e: Eddy v0.9.1
        update_version = self.current  # Store update version, i.e: 0.9.1
        update_url = None  # Store update HTML url, i.e: http://github.com/...
        try:
            LOGGER.info('Connecting to GitHub to retrieve update information (channel: %s)', self.channel.value)
            github = GitHub(token='6a417ccfe9a7c526598e77a74cbf1cba6e688f0e')
            repository = github.repository('danielepantaleone', 'eddy')
            for release in repository.releases():
                if self.channel is Channel.Beta or not release.prerelease:
                    try:
                        if NormalizedVersion(release.tag_name[1:]) > NormalizedVersion(update_version):
                            update_name = release.name
                            update_version = release.tag_name[1:]
                            update_url = release.html_url
                    except IrrationalVersionError as e:
                        LOGGER.warning('Failed to parse version number from TAG: %s', e)
            if update_version != self.current:
                LOGGER.info('Update available: %s', update_name)
                self.sgnUpdateAvailable.emit(update_name, update_url)
            else:
                LOGGER.info('No update available')
                self.sgnNoUpdateAvailable.emit()
        except Exception as e:
            LOGGER.warning('Failed to retrieve update data: %s', e)
            self.sgnNoUpdateDataAvailable.emit()
        self.finished.emit() 
Example #20
Source File: github.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_github_api_for_repo(keychain, owner, repo, session=None):
    gh = GitHub(
        session=session
        or GitHubSession(default_read_timeout=30, default_connect_timeout=30)
    )
    # Apply retry policy
    gh.session.mount("http://", adapter)
    gh.session.mount("https://", adapter)

    GITHUB_TOKEN = os.environ.get("GITHUB_TOKEN")
    APP_KEY = os.environ.get("GITHUB_APP_KEY", "").encode("utf-8")
    APP_ID = os.environ.get("GITHUB_APP_ID")
    if APP_ID and APP_KEY:
        installation = INSTALLATIONS.get((owner, repo))
        if installation is None:
            gh.login_as_app(APP_KEY, APP_ID, expire_in=120)
            try:
                installation = gh.app_installation_for_repository(owner, repo)
            except github3.exceptions.NotFoundError:
                raise GithubException(
                    f"Could not access {owner}/{repo} using GitHub app. "
                    "Does the app need to be installed for this repository?"
                )
            INSTALLATIONS[(owner, repo)] = installation
        gh.login_as_app_installation(APP_KEY, APP_ID, installation.id)
    elif GITHUB_TOKEN:
        gh.login(token=GITHUB_TOKEN)
    else:
        github_config = keychain.get_service("github")
        gh.login(github_config.username, github_config.password)
    return gh 
Example #21
Source File: github.py    From CumulusCI with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def validate_service(options):
    username = options["username"]
    password = options["password"]
    gh = get_github_api(username, password)
    try:
        gh.rate_limit()
    except Exception as e:
        raise GithubException(f"Could not confirm access to the GitHub API: {str(e)}") 
Example #22
Source File: github.py    From steemprojects.com with MIT License 5 votes vote down vote up
def __init__(self):
        if settings.GITHUB_TOKEN:
            self.github = login(token=settings.GITHUB_TOKEN)
        else:
            self.github = GitHub() 
Example #23
Source File: codeowners.py    From cc-utils with Apache License 2.0 5 votes vote down vote up
def __init__(self, github_api: GitHub):
        self.github_api = not_none(github_api) 
Example #24
Source File: codeowners.py    From cc-utils with Apache License 2.0 5 votes vote down vote up
def _resolve_team_members(self, github_team_name: str):
        not_none(github_team_name)
        org_name, team_name = github_team_name.split('/') # always of form 'org/name'
        organisation = self.github_api.organization(org_name)
        # unfortunately, we have to look-up the team (no api to retrieve it by name)
        team_or_none = _first(filter(lambda team: team.name == team_name, organisation.teams()))
        if not team_or_none:
            warning('failed to lookup team {t}'.format(t=team_name))
            return []
        for member in map(self.github_api.user, team_or_none.members()):
            if member.email:
                yield member.email
            else:
                warning(f'no email found for GitHub user {member}') 
Example #25
Source File: scraper.py    From pycodesuggest with MIT License 5 votes vote down vote up
def login_github(githubUser):
    password = getpass('GitHub password for {0}: '.format(githubUser))
    g = login(githubUser, password)
    return g 
Example #26
Source File: github.py    From steemprojects.com with MIT License 5 votes vote down vote up
def __init__(self):
        if settings.GITHUB_TOKEN:
            self.github = login(token=settings.GITHUB_TOKEN)
        else:
            self.github = GitHub() 
Example #27
Source File: github.py    From aegea with Apache License 2.0 5 votes vote down vote up
def __init__(self, login='', password='', token=''):
        super(GitHub, self).__init__({})
        if token:
            self.login(login, token=token)
        elif login and password:
            self.login(login, password) 
Example #28
Source File: test_helpers.py    From farcy with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def test_get_session__authenticate(self, mock_path, mock_prompt,
                                       mock_getpass, mock_authorize,
                                       mock_open):
        mock_path.isfile.return_value = False
        self.assertTrue(isinstance(helpers.get_session(), GitHub))
        self.assertTrue(mock_prompt.called)
        self.assertTrue(mock_getpass.called)
        self.assertTrue(mock_open.called) 
Example #29
Source File: github.py    From aegea with Apache License 2.0 5 votes vote down vote up
def _repr(self):
        if self._session.auth:
            return '<GitHub [{0[0]}]>'.format(self._session.auth)
        return '<GitHub at 0x{0:x}>'.format(id(self)) 
Example #30
Source File: github.py    From aegea with Apache License 2.0 5 votes vote down vote up
def authorize(self, login, password, scopes=None, note='', note_url='',
                  client_id='', client_secret=''):
        """Obtain an authorization token from the GitHub API for the GitHub
        API.

        :param str login: (required)
        :param str password: (required)
        :param list scopes: (optional), areas you want this token to apply to,
            i.e., 'gist', 'user'
        :param str note: (optional), note about the authorization
        :param str note_url: (optional), url for the application
        :param str client_id: (optional), 20 character OAuth client key for
            which to create a token
        :param str client_secret: (optional), 40 character OAuth client secret
            for which to create the token
        :returns: :class:`Authorization <Authorization>`
        """
        json = None
        # TODO: Break this behaviour in 1.0 (Don't rely on self._session.auth)
        auth = None
        if self._session.auth:
            auth = self._session.auth
        elif login and password:
            auth = (login, password)

        if auth:
            url = self._build_url('authorizations')
            data = {'note': note, 'note_url': note_url,
                    'client_id': client_id, 'client_secret': client_secret}
            if scopes:
                data['scopes'] = scopes

            with self._session.temporary_basic_auth(*auth):
                json = self._json(self._post(url, data=data), 201)

        return Authorization(json, self) if json else None