-
Notifications
You must be signed in to change notification settings - Fork 7
/
github_miniapi.py
84 lines (71 loc) · 2.63 KB
/
github_miniapi.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
import csv
import sys
from io import StringIO
from datetime import datetime
import requests
import json
GITHUB_DT_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
class GithubRequest(object):
def __init__(self, token, owner=None, repo=None):
self.token = token
self.owner = owner or ''
self.repo = repo or ''
self.url_base = "https://api.github.com/"
def github_request(self, url, payload=None):
url = "%s%s" % (self.url_base, url)
url = url.format(owner=self.owner, repo=self.repo)
session = requests.Session()
session.auth = (self.token, 'x-oauth-basic')
session.headers.update({
'Accept': 'application/vnd.github.she-hulk-preview+json'})
if payload:
response = session.post(
url, data=json.dumps(payload))
else:
response = session.get(url)
response.raise_for_status()
return response.json()
def github_get_private_repos(self):
request = self.github_request('orgs/{owner}/repos?type=private&per_page=1000')
repos = []
for repo in request:
pushed_at = datetime.strptime(repo['pushed_at'], GITHUB_DT_FORMAT)
days = (datetime.now() - pushed_at).days
repos.append({
'name': repo['name'],
'last_days_modified': days,
})
return repos
def github_get_issues(self):
return self.github_request('repos/{owner}/{repo}/issues?per_page=1000')
def close_pull_request(self, pull_number):
return self.github_request(
url='repos/{owner}/{repo}/pulls/%s' % pull_number,
payload={'state': 'closed'},
)
def close_all_pull_requests(self):
issues = self.github_list_issues()
pull_requests = [pr for pr in issues if pr.get('pull_request')]
for pull_request in pull_requests:
self.close_pull_request(pull_number=pull_request['number'])
@staticmethod
def dicts2csv(datas):
if not datas:
return
csv_file = StringIO()
csv_obj = csv.DictWriter(csv_file, datas[0].keys())
csv_obj.writeheader()
csv_obj.writerows(datas)
csv_file.seek(0)
return csv_file.read()
if __name__ == '__main__':
# Create a "token" from https://github.com/settings/tokens
token = sys.argv[1]
# Use the organization name. E.g. "Vauxoo"
owner = sys.argv[2]
# payload = ast.literal_eval(sys.argv[2])
# repo = sys.argv[4]
gh_obj = GithubRequest(token, owner=owner)
repos = gh_obj.github_get_private_repos()
csv_str = GithubRequest.dicts2csv(repos)
print(csv_str)