-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathGenerateREADME.py
305 lines (240 loc) · 10.1 KB
/
GenerateREADME.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
# Python: 3.8.x
# System Imports
from os import getenv
from datetime import datetime
from traceback import print_exc
# Third Party Imports
from github import Github
from dotenv import load_dotenv
import humanize
from pytz import utc, timezone
# Custom Imports
from githubQuery import *
from ReadmeMaker import ReadmeGenerator
from utility import makeCommitList, makeLanguageList
# Load Environment Variables
load_dotenv()
# Get TOKEN
ghtoken = getenv('INPUT_GH_TOKEN')
def getDailyCommitData(repositoryList: list) -> str:
print("Generating Daily Commit Data... ")
if getenv('INPUT_TIMEZONE') == None:
tz = "Asia/Kolkata"
else:
tz = getenv('INPUT_TIMEZONE')
morning = 0 # 4 - 10
daytime = 0 # 10 - 16
evening = 0 # 16 - 22
nighttime = 0 # 0 - 4
for repository in repositoryList:
result = Query.runGithubGraphqlQuery(
createCommittedDateQuery.substitute(owner=repository["owner"]["login"], name=repository["name"], id=id))
try:
commitedDates = result["data"]["repository"]["ref"]["target"]["history"]["edges"]
for committedDate in commitedDates:
date = datetime.strptime(committedDate["node"]["committedDate"],
"%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=utc).astimezone(
timezone(tz))
hour = date.hour
if 6 <= hour < 12:
morning += 1
if 12 <= hour < 18:
daytime += 1
if 18 <= hour < 24:
evening += 1
if 0 <= hour < 6:
nighttime += 1
except Exception:
print("ERROR", repository["name"], "is private!")
totalCommits = morning + daytime + evening + nighttime
if morning + daytime >= evening + nighttime:
title = "I'm an early 🐤"
else:
title = "I'm a night 🦉"
eachDay = [
{"name": "🌞 Morning", "text": str(
morning) + " commits", "percent": round((morning / totalCommits) * 100, 2)},
{"name": "🌆 Daytime", "text": str(
daytime) + " commits", "percent": round((daytime / totalCommits) * 100, 2)},
{"name": "🌃 Evening", "text": str(
evening) + " commits", "percent": round((evening / totalCommits) * 100, 2)},
{"name": "🌙 Night", "text": str(
nighttime) + " commits", "percent": round((nighttime / totalCommits) * 100, 2)},
]
print("Daily Commit Data created!")
return "**" + title + "** \n" + """
| | | | |
| --- | --- | --- | --- |
""" + makeCommitList(eachDay) + """
| | | | |\n"""
def getWeeklyCommitData(repositoryList: list) -> str:
print("Generating Weekly Commit Data... ")
tz = getenv('INPUT_TIMEZONE')
weekdays = [0, 0, 0, 0, 0, 0, 0]
for repository in repositoryList:
result = Query.runGithubGraphqlQuery(
createCommittedDateQuery.substitute(owner=username, name=repository["name"], id=id))
try:
commitedDates = result["data"]["repository"]["ref"]["target"]["history"]["edges"]
for committedDate in commitedDates:
date = datetime.strptime(committedDate["node"]["committedDate"],
"%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=utc).astimezone(
timezone(tz))
weekday = date.strftime('%A')
if weekday == "Monday":
weekdays[0] += 1
if weekday == "Tuesday":
weekdays[1] += 1
if weekday == "Wednesday":
weekdays[2] += 1
if weekday == "Thursday":
weekdays[3] += 1
if weekday == "Friday":
weekdays[4] += 1
if weekday == "Saturday":
weekdays[5] += 1
if weekday == "Sunday":
weekdays[6] += 1
except Exception as exception:
print("ERROR", repository["name"])
totalCommits = sum(weekdays)
dayOfWeek = [
{"name": "Monday", "text": str(
weekdays[0]) + " commits", "percent": round((weekdays[0] / totalCommits) * 100, 2)},
{"name": "Tuesday", "text": str(
weekdays[1]) + " commits", "percent": round((weekdays[1] / totalCommits) * 100, 2)},
{"name": "Wednesday", "text": str(
weekdays[2]) + " commits", "percent": round((weekdays[2] / totalCommits) * 100, 2)},
{"name": "Thursday", "text": str(
weekdays[3]) + " commits", "percent": round((weekdays[3] / totalCommits) * 100, 2)},
{"name": "Friday", "text": str(
weekdays[4]) + " commits", "percent": round((weekdays[4] / totalCommits) * 100, 2)},
{"name": "Saturday", "text": str(
weekdays[5]) + " commits", "percent": round((weekdays[5] / totalCommits) * 100, 2)},
{"name": "Sunday", "text": str(
weekdays[6]) + " commits", "percent": round((weekdays[6] / totalCommits) * 100, 2)},
]
max_element = {
'percent': 0
}
for day in dayOfWeek:
if day['percent'] > max_element['percent']:
max_element = day
print("Weekly Commit Data created!")
title = 'I\'m Most Productive on ' + max_element['name'] + 's'
return "📅 **" + title + "** \n"+"""
| | | | |
| --- | --- | --- | --- |
""" + makeCommitList(dayOfWeek) + """
| | | | |\n"""
def getLanguagesPerRepo() -> str:
print("Generating Most used Language... ", end="")
language_count = {}
total = 0
result = Query.runGithubGraphqlQuery(
repositoryListQuery.substitute(username=username, id=id))
for repo in result['data']['user']['repositories']['edges']:
if repo['node']['primaryLanguage'] is None:
continue
language = repo['node']['primaryLanguage']['name']
color_code = repo['node']['primaryLanguage']['color']
total += 1
if language not in language_count.keys():
language_count[language] = {}
language_count[language]['count'] = 1
else:
language_count[language]['count'] = language_count[language]['count'] + 1
language_count[language]['color'] = color_code
data = []
sorted_labels = list(language_count.keys())
sorted_labels.sort(key=lambda x: language_count[x]['count'], reverse=True)
most_language_repo = sorted_labels[0]
for label in sorted_labels:
percent = round(language_count[label]['count'] / total * 100, 2)
data.append({
"name": label,
"text": str(language_count[label]['count']) + " repos",
"percent": percent
})
print("Done")
title = "My 💖 languages " + most_language_repo
return "**" + title + "** \n" + """
| | | | |
| --- | --- | --- | --- |
""" + makeLanguageList(data) + """
| | | | |\n"""
def getProfileViews() -> str:
data = Query.runGithubAPIQuery(getProfileViewQuery.substitute(
owner=username, repo=username))
return ('**✨ ' + str(data["count"]) + ' people were here!**\n\n')
def getLinesOfCode(repositoryList):
print("Generating Lines Of Code... ", end="")
totalLOC = 0
for repository in repositoryList:
try:
# time.sleep(0.7)
datas = Query.runGithubAPIQuery(getLinesOfCodeQuery.substitute(
owner=repository["owner"]["login"], repo=repository["name"]))
for data in datas:
totalLOC += (data[1] - data[2])
except Exception as execption:
print(execption)
print("Done")
return ("**From Hello World I have written " + humanize.intword(int(totalLOC)) + " Lines of Code ✍️**\n\n")
def getTotalContributions():
data = Query.runGithubContributionsQuery(username)
total = data['years'][0]['total']
year = data['years'][0]['year']
return "**🏆 " + humanize.intcomma(total) + " Contributions in year " + year + "**\n\n"
def generateData() -> str:
stats = ""
print("Generating new README Data... ")
ReadmeMaker = ReadmeGenerator(readme.content)
result = Query.runGithubGraphqlQuery(
createContributedRepoQuery.substitute(username=username))
nodes = result["data"]["user"]["repositoriesContributedTo"]["nodes"]
repos = [d for d in nodes if d['isFork'] is False]
if getenv('INPUT_SHOW_TOTAL_CONTRIBUTIONS') == 'True':
stats = getTotalContributions()
ReadmeMaker.generateTotalContributions(stats)
if getenv("INPUT_SHOW_LINES_OF_CODE") == 'True':
stats = getLinesOfCode(repos)
ReadmeMaker.generateLinesOfCodeStats(stats)
if getenv("INPUT_SHOW_PROFILE_VIEWS") == 'True':
stats = getProfileViews()
ReadmeMaker.generateProfileViewsStats(stats)
if getenv("INPUT_SHOW_DAILY_COMMIT") == 'True':
stats = getDailyCommitData(repos)
ReadmeMaker.generateDailyStats(stats)
if getenv("INPUT_SHOW_WEEKLY_COMMIT") == 'True':
stats = getWeeklyCommitData(repos)
ReadmeMaker.generateWeeklyStats(stats)
if getenv("INPUT_SHOW_LANGUAGE") == 'True':
stats = getLanguagesPerRepo()
ReadmeMaker.generateMostUsedLanguage(stats)
print("README data created!")
newREADME = ReadmeMaker.getREADME()
return newREADME
if __name__ == "__main__":
try:
if ghtoken is None:
raise Exception("Token not available")
# Strart the Calculation
githubObject = Github(ghtoken)
headers = {"Authorization": "Bearer " + ghtoken}
Query = RunQuery(headers)
# Execute the query
user_data = Query.runGithubGraphqlQuery(userInfoQuery)
username = user_data["data"]["viewer"]["login"]
id = user_data["data"]["viewer"]["id"]
print("Running task for... ", username)
# Get user repository
repo = githubObject.get_repo(f"{username}/{username}")
readme = repo.get_readme()
# Running task now ...
newREADME = generateData()
repo.update_file(path=readme.path, message="⤴ Auto Updated README",
content=newREADME, sha=readme.sha, branch='master')
except Exception as e:
print_exc()
print("ERROR:: ", str(e))