Last active
July 2, 2019 15:38
-
-
Save aarroyoc/79abb1f750f81ee8282f7b43f974c99a to your computer and use it in GitHub Desktop.
GitHub Sync GraphQL Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import requests | |
import os | |
import subprocess | |
url = "https://api.github.com/graphql" | |
api_token = "PERSONAL_API_TOKEN" | |
headers = {'Authorization': 'token %s' % api_token} | |
first_query = { 'query' : ''' | |
{ | |
viewer { | |
repositories(first: 30) { | |
totalCount pageInfo { | |
hasNextPage endCursor | |
} edges { | |
node { | |
name | |
sshUrl | |
} | |
} | |
} | |
} | |
} | |
''' } | |
next_query = { "query" : ''' | |
{ | |
viewer { | |
repositories(first:30, after: "%s"){ | |
totalCount pageInfo { | |
hasNextPage endCursor | |
} | |
edges { | |
node { | |
name | |
sshUrl | |
} | |
} | |
} | |
} | |
} | |
'''} | |
class RepoInfo: | |
def __init__(self,name,repo_url): | |
self.name = name | |
self.repo_url = repo_url | |
def cmd(command): | |
print(command) | |
args = command.split(" ") | |
result = subprocess.run(args,stdout=subprocess.PIPE) | |
out = result.stdout.decode("utf-8").strip() | |
print(out) | |
def generate_query(end_cursor=None): | |
if end_cursor == None: | |
return first_query | |
else: | |
query = next_query.copy() | |
query["query"] = next_query["query"] % end_cursor | |
return query | |
def repos(): | |
query = generate_query() | |
while True: | |
r = requests.post(url=url,json=query,headers=headers) | |
data = r.json()["data"]["viewer"]["repositories"] | |
for repo in data["edges"]: | |
name = repo["node"]["name"] | |
repo_url = repo["node"]["sshUrl"] | |
info = RepoInfo(name,repo_url) | |
yield info | |
if data["pageInfo"]["hasNextPage"]: | |
end_cursor = data["pageInfo"]["endCursor"] | |
else: | |
break | |
query = generate_query(end_cursor) | |
for repo in repos(): | |
print("GitHub repo: %s" % repo.name) | |
if os.path.isdir(repo.name): | |
os.chdir(repo.name) | |
cmd("git pull") | |
os.chdir("..") | |
else: | |
cmd("git clone %s %s" % (repo.repo_url, repo.name)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment