Skip to content

Updating GitHub Repository Branch Protection Rules #162

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
kmbhanushali opened this issue Oct 28, 2020 · 11 comments
Closed

Updating GitHub Repository Branch Protection Rules #162

kmbhanushali opened this issue Oct 28, 2020 · 11 comments
Labels
type: question or discussion Issue discussing or asking a question about gql

Comments

@kmbhanushali
Copy link

Hello!

I have been trying to integrate GitHub repo settings via Python and everything was going smoothly using the GitHub package. Unfortunately, the package does not contain any functions on creating new repo branch protection rules, so I had to switch to the gql package. I'm having a difficult time understanding the lingo surrounding this package so I was hoping to get some help here.

I have been doing independent research, but I can't seem to find anything of relevance on the subject. I emailed a member of this community and they suggested I create an issue here. Thank you for the assistance.

My code:

from gql import gql, Client, AIOHTTPTransport
import asyncio

async def main():

    transport = AIOHTTPTransport(url="myURL", headers={'Authorization': 'myToken'}) #using my url and token here

    # Using `async with` on the client will start a connection on the transport
    # and provide a `session` variable to execute queries on this connection
    async with Client(
        transport=transport,
        fetch_schema_from_transport=True,
        ) as session:

        # Execute single query
        query = gql("""
                mutation($input: CreateBranchProtectionRuleInput!) {
                    createBranchProtectionRule(input: $input) {
                        branchProtectionRule {
                          id
                        } 
                    }
                }
            """
            )

        input = {"repositoryId": "012345", "pattern": "release/*"} #using my repoID here
        result = await session.execute(query, variable_values = input)
        print(result)

asyncio.run(main())

This code results in the following error:

RuntimeError: asyncio.run() cannot be called from a running event loop

A couple things to note that may cause this error:

  • The url I am trying to reach (the repo I'm adding branch protection rules to) is a GitHub enterprise, version 2.19.21
  • I'm not sure if the AIOTTHP function is what causes the running event loop - is there a way to call a syncronous transport using a token?

Any help would be appreciated.

@leszekhanusz
Copy link
Collaborator

Are you using jupyter (IPython) ?
It seems that your environment has already an event loop running.

Instead of asyncio.run(main()) you should use await main()

@kmbhanushali
Copy link
Author

Thanks for the quick response!

I am using Spyder (Python 3.8) from Anaconda
Replacing asyncio.run(main()) with await main() gives me a yield outside function error. Not sure why

@leszekhanusz
Copy link
Collaborator

Please always send full stack traces in the bug reports so that we can help you

@kmbhanushali
Copy link
Author

Apologies, I'll send full stack traces from now on.

This is the full stack (its a syntax error):

runfile('branchProtectionRuleSetting.py', wdir='03_Github_Repo_labels')
File "branchProtectionRuleSetting.py", line 37
await main()
^
SyntaxError: 'await' outside function

@leszekhanusz
Copy link
Collaborator

OK, you should instead use:

loop = asyncio.get_running_loop()
loop.create_task(main())

@kmbhanushali
Copy link
Author

Looks like my running event loop went away!

But I have some other warnings now:

Task exception was never retrieved
future: <Task finished name='Task-13' coro=<main() done, defined at branchProtectionRuleSetting.py:6> exception=TransportProtocolError('Server did not return a GraphQL result')>
Traceback (most recent call last):
  File "C:\Users\kmb\Anaconda3\lib\site-packages\gql\transport\aiohttp.py", line 127, in execute
    result = await resp.json()
  File "C:\Users\kmb\Anaconda3\lib\site-packages\aiohttp\client_reqrep.py", line 1026, in json
    raise ContentTypeError(
aiohttp.client_exceptions.ContentTypeError: 0, message='Attempt to decode JSON with unexpected mimetype: text/html; charset=utf-8', url=URL('https://github.build.ge.com/login?return_to=https://github.build.ge.com/aeocontrolstesting')

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "branchProtectionRuleSetting.py", line 31, in main
    result = await session.execute(query, variable_values = input)
  File "C:\Users\kmb\Anaconda3\lib\site-packages\gql\client.py", line 338, in execute
    result = await self._execute(document, *args, **kwargs)
  File "C:\Users\kmb\Anaconda3\lib\site-packages\gql\client.py", line 327, in _execute
    await self.fetch_and_validate(document)
  File "C:\Users\kmb\Anaconda3\lib\site-packages\gql\client.py", line 278, in fetch_and_validate
    await self.fetch_schema()
  File "C:\Users\kmb\Anaconda3\lib\site-packages\gql\client.py", line 351, in fetch_schema
    execution_result = await self.transport.execute(
  File "C:\Users\kmb\Anaconda3\lib\site-packages\gql\transport\aiohttp.py", line 139, in execute
    raise TransportProtocolError("Server did not return a GraphQL result")
gql.transport.exceptions.TransportProtocolError: Server did not return a GraphQL result

I'm trying to connect to a GitHub enterprise, not a regular GitHub repo. Apologies in advance if this is a lot of code, I'm trying to figure out the package as I go.

@leszekhanusz
Copy link
Collaborator

Are you sure that your URL is a GraphQL endpoint? It seems to return text/html results instead of json

@leszekhanusz
Copy link
Collaborator

You could try with the latest version from master, it should show the answer in the exception.

pip install git+https://github.com/graphql-python/gql.git@master --use-feature=2020-resolver

@kmbhanushali
Copy link
Author

Looks like I have a fundamental misunderstanding of what URL I should be pointing too. My apologies on not doing the proper research there. The URL I am referencing to is my org-repo link. Do I need to take additional steps to create or point to a GraphQL endpoint? If so, can you direct me to the appropriate documentation?

Thanks

@leszekhanusz
Copy link
Collaborator

If it is using the standard GitHub API, you could check the issue #149

@leszekhanusz leszekhanusz added the type: question or discussion Issue discussing or asking a question about gql label Oct 29, 2020
@leszekhanusz
Copy link
Collaborator

I added a section in the docs (PR #165) so that it is more clear for IPython users.
If you have other questions relative to the gql package, please open another issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
type: question or discussion Issue discussing or asking a question about gql
Projects
None yet
Development

No branches or pull requests

2 participants