-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathgithub_latest.py
executable file
·110 lines (94 loc) · 2.58 KB
/
github_latest.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
#!/usr/bin/python
import sys
import json
import requests
GITHUB_URL = 'https://api.github.com'
SEARCH_URL = GITHUB_URL+'/repos'
TOKEN = ''
TOKEN_FILE = "./token"
#TODO: Consider using PyGithub if neccesary.
# Request to GitHub
def github_request(url):
data = None
error = None
r = requests.get(url, headers={'Authorization':TOKEN})
if ((r.ok) and (len(r.text) > 2)): #work-around
data = json.loads(r.text)
else:
error = json.loads(r.text)
return data, error
# Get the created date of specific commit
def getCommitDate(commit_sha):
global urlci, TOKEN
body = None
r = requests.get(urlci+"/"+commit_sha, headers={'Authorization':TOKEN})
if (r.ok):
body = r.text
if (body):
data = json.loads(body)
return data['committer']['date']
return "N/A"
# Load the GitHub token key from file
def load_token_key(filename):
# Check token
try:
f = open(filename, "r")
except:
print >> sys.stderr, "Unable to get token key. Please get the Github API token key for your account and save it in: " + filename
print >> sys.stderr, 'Reference: https://api.github.com/authorizations'
sys.exit()
return 'token '+f.read().strip()
# Avoid UnicodeEncodeError
def ustr(s):
r = ''
if s:
r = s.encode('ascii', 'ignore')
return r
## MAIN
# Check arguments
if len(sys.argv) < 2:
print >> sys.stderr, "Usage: %s <user>:<repo>" %sys.argv[0]
sys.exit()
else:
user_repo = str(sys.argv[1])
if (user_repo.find(":") >= 0):
user = user_repo.split(":")[0]
repo = user_repo.split(":")[1]
else:
print >> sys.stderr, "%s should be in the right format <user>:<repo>" %user_repo
sys.exit()
# Formulate the request url
url = SEARCH_URL+"/"+user+"/"+repo
#urltag = url + "/tags?page=1&per_page=1"
urltag = url + "/tags"
urlrel = url + "/releases/latest"
urlci = url + "/commits"
# Token key
TOKEN = load_token_key(TOKEN_FILE)
# Request for PUBLISHED RELEASES
data, error = github_request(urlrel)
# Request for COMMITS
data_ci, error_ci = github_request(urlci)
# Print results
result = user+"," + repo
if (data):
latest_release = data[u'name']
rel_tag_name = data[u'tag_name']
rel_created_date = data[u'created_at']
rel_published_date = data[u'published_at']
result += ","+ustr(latest_release)+","+ustr(rel_published_date)
else:
result += ",,"
#print "Error: " + error["message"]
if (data_ci):
#print data_ci
#for ci in data_ci:
ci = data_ci[0]
sha = ci["sha"]
commit = ci["commit"]
ci_date = commit["committer"]["date"]
result += ","+sha+","+ci_date
else:
result += ",,"
#print "Error: " + error_ci["message"]
print result