-
Notifications
You must be signed in to change notification settings - Fork 2
/
github.py
93 lines (80 loc) · 2.27 KB
/
github.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
import os
import json
from sys import stdout
from urllib.request import Request, urlopen
token = os.getenv("GITHUB_TOKEN")
org_query = """
query($login: String!, $cursor: String) {
organization(login: $login) {
repositories(first: 100, after: $cursor) {
nodes {
name
sshUrl
}
pageInfo {
endCursor
startCursor
hasNextPage
}
}
}
}
"""
user_query = """
query($login: String!, $cursor: String) {
user(login: $login) {
repositories(first: 100, after: $cursor) {
nodes {
name
sshUrl
}
pageInfo {
endCursor
startCursor
hasNextPage
}
}
}
}
"""
def run_query(query, login, cursor=None):
data = {"query": query, "variables": {"login": login, "cursor": cursor}}
headers = {"Authorization": f"Bearer {token}"}
request = Request(
"https://api.github.com/graphql", json.dumps(data).encode("utf-8"), headers
)
with urlopen(request) as response:
code = response.code
body = response.read()
if code == 200:
data = json.loads(body)
if "errors" in data:
raise Exception(f'Query returned errors:\n{data["errors"]}')
return data
else:
raise Exception(
"Query failed to run by returning code of {}. {}".format(code, query)
)
def get_repos(login, type):
if type == "organization":
query = org_query
elif type == "user":
query = user_query
else:
raise RuntimeError(
f"expected type to be `user` or `organization`, but got `{type}`"
)
cursor = None
repos = []
while True:
result = run_query(query, login, cursor)
for repo in result["data"][type]["repositories"]["nodes"]:
output = f'{repo["name"]} {repo["sshUrl"]}'
repos.append(output)
print(output)
stdout.flush() # so that results show in fzf sooner
pageInfo = result["data"][type]["repositories"]["pageInfo"]
if not pageInfo["hasNextPage"]:
break
cursor = pageInfo["endCursor"]
return repos