Merge pull request #10 from anmol098/dev

Dev
This commit is contained in:
Anmol Pratap Singh
2020-07-26 17:28:02 +05:30
committed by GitHub
2 changed files with 103 additions and 45 deletions

View File

@@ -56,4 +56,4 @@ runs:
branding:
icon: 'activity'
color: 'orange'
color: 'orange'

146
main.py
View File

@@ -5,8 +5,11 @@ Readme Development Metrics With waka time progress
import re
import os
import base64
import sys
from pytz import timezone
import pytz
import requests
from github import Github
from github import Github, GithubException
import datetime
from string import Template
@@ -98,7 +101,7 @@ def make_list(data: list):
def make_commit_list(data: list):
'''Make List'''
data_list = []
for l in data[:5]:
for l in data[:7]:
ln = len(l['name'])
ln_text = len(l['text'])
op = f"{l['name']}{' ' * (13 - ln)}{l['text']}{' ' * (15 - ln_text)}{make_graph(l['percent'])} {l['percent']}%"
@@ -106,11 +109,12 @@ def make_commit_list(data: list):
return ' \n'.join(data_list)
def generate_commit_list():
def generate_commit_list(tz):
string = ''
result = run_query(userInfoQuery) # Execute the query
username = result["data"]["viewer"]["login"]
id = result["data"]["viewer"]["id"]
print("user {} id {}".format(username, id))
print("user {} id".format(username))
result = run_query(createContributedRepoQuery.substitute(username=username))
nodes = result["data"]["user"]["repositoriesContributedTo"]["nodes"]
@@ -121,14 +125,24 @@ def generate_commit_list():
evening = 0 # 18 - 24
night = 0 # 0 - 6
Monday = 0
Tuesday = 0
Wednesday = 0
Thursday = 0
Friday = 0
Saturday = 0
Sunday = 0
for repository in repos:
result = run_query(
createCommittedDateQuery.substitute(owner=repository["owner"]["login"], name=repository["name"], id=id))
try:
committed_dates = result["data"]["repository"]["ref"]["target"]["history"]["edges"]
for committedDate in committed_dates:
date = datetime.datetime.strptime(committedDate["node"]["committedDate"], "%Y-%m-%dT%H:%M:%SZ")
date = datetime.datetime.strptime(committedDate["node"]["committedDate"],
"%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=pytz.utc).astimezone(timezone(tz))
hour = date.hour
weekday = date.strftime('%A')
if 6 <= hour < 12:
morning += 1
if 12 <= hour < 18:
@@ -137,10 +151,26 @@ def generate_commit_list():
evening += 1
if 0 <= hour < 6:
night += 1
if weekday == "Monday":
Monday += 1
if weekday == "Tuesday":
Tuesday += 1
if weekday == "Wednesday":
Wednesday += 1
if weekday == "Thursday":
Thursday += 1
if weekday == "Friday":
Friday += 1
if weekday == "Saturday":
Saturday += 1
if weekday == "Sunday":
Sunday += 1
except Exception as ex:
print("Exception occured" + str(ex));
print("Please Ignore this exception " + str(ex))
sumAll = morning + daytime + evening + night
sum_week = Sunday + Monday + Tuesday + Friday + Saturday + Wednesday + Thursday
if morning + daytime >= evening + night:
title = "I'm an early 🐤"
else:
@@ -151,50 +181,77 @@ def generate_commit_list():
{"name": "🌃 Evening", "text": str(evening) + " commits", "percent": round((evening / sumAll) * 100, 2)},
{"name": "🌙 Night", "text": str(night) + " commits", "percent": round((night / sumAll) * 100, 2)},
]
dayOfWeek = [
{"name": "Monday", "text": str(Monday) + " commits", "percent": round((Monday / sum_week) * 100, 2)},
{"name": "Tuesday", "text": str(Tuesday) + " commits", "percent": round((Tuesday / sum_week) * 100, 2)},
{"name": "Wednesday", "text": str(Wednesday) + " commits", "percent": round((Wednesday / sum_week) * 100, 2)},
{"name": "Thursday", "text": str(Thursday) + " commits", "percent": round((Thursday / sum_week) * 100, 2)},
{"name": "Friday", "text": str(Friday) + " commits", "percent": round((Friday / sum_week) * 100, 2)},
{"name": "Saturday", "text": str(Saturday) + " commits", "percent": round((Saturday / sum_week) * 100, 2)},
{"name": "Sunday", "text": str(Sunday) + " commits", "percent": round((Sunday / sum_week) * 100, 2)},
]
return '**' + title + '** \n\n' + '```text\n' + make_commit_list(one_day) + '\n\n```\n'
max_element = {
'percent': 0
}
for day in dayOfWeek:
if day['percent'] > max_element['percent']:
max_element = day
days_title = 'I\'m Most Productive on ' + max_element['name'] + 's'
string = string + '**' + title + '** \n\n' + '```text\n' + make_commit_list(one_day) + '\n\n```\n'
string = string + '📅 **' + days_title + '** \n\n' + '```text\n' + make_commit_list(dayOfWeek) + '\n\n```\n'
return string
def get_stats():
'''Gets API data and returns markdown progress'''
stats = ''
if showCommit.lower() in ['true', '1', 't', 'y', 'yes']:
stats = stats + generate_commit_list() + '\n\n'
request = requests.get(f"https://wakatime.com/api/v1/users/current/stats/last_7_days?api_key={waka_key}")
try:
request = requests.get(
f"https://wakatime.com/api/v1/users/current/stats/last_7_days?api_key={waka_key}")
if request.status_code == 200:
data = request.json()
if showCommit.lower() in ['true', '1', 't', 'y', 'yes']:
stats = stats + generate_commit_list(tz=data['data']['timezone']) + '\n\n'
stats = stats + '📊 **This week I spent my time on** \n\n'
stats = stats + '```text\n'
if showTimeZone.lower() in ['true', '1', 't', 'y', 'yes']:
timezone = data['data']['timezone']
stats = stats + '⌚︎ Timezone: ' + timezone + '\n\n'
if request.status_code == 200:
data = request.json()
stats = stats + '📊 **This week I spent my time on** \n\n'
stats = stats + '```text\n'
if showTimeZone.lower() in ['true', '1', 't', 'y', 'yes']:
timezone = data['data']['timezone']
stats = stats + '⌚︎ Timezone: ' + timezone + '\n\n'
if showLanguage.lower() in ['true', '1', 't', 'y', 'yes']:
if showLanguage.lower() in ['true', '1', 't', 'y', 'yes']:
if len(data['data']['languages']) != 0:
lang_list = make_list(data['data']['languages'])
stats = stats + '💬 Languages: \n' + lang_list + '\n\n'
else:
lang_list = "No Activity tracked this Week"
stats = stats + '💬 Languages: \n' + lang_list + '\n\n'
if showEditors.lower() in ['true', '1', 't', 'y', 'yes']:
if showEditors.lower() in ['true', '1', 't', 'y', 'yes']:
if len(data['data']['editors']) != 0:
edit_list = make_list(data['data']['editors'])
stats = stats + '🔥 Editors: \n' + edit_list + '\n\n'
else:
edit_list = "No Activity tracked this Week"
stats = stats + '🔥 Editors: \n' + edit_list + '\n\n'
if showProjects.lower() in ['true', '1', 't', 'y', 'yes']:
if showProjects.lower() in ['true', '1', 't', 'y', 'yes']:
if len(data['data']['projects']) != 0:
project_list = make_list(data['data']['projects'])
stats = stats + '🐱‍💻 Projects: \n' + project_list + '\n\n'
else:
project_list = "No Activity tracked this Week"
stats = stats + '🐱‍💻 Projects: \n' + project_list + '\n\n'
if showOs.lower() in ['true', '1', 't', 'y', 'yes']:
if showOs.lower() in ['true', '1', 't', 'y', 'yes']:
if len(data['data']['operating_systems']) != 0:
os_list = make_list(data['data']['operating_systems'])
stats = stats + '💻 Operating Systems: \n' + os_list + '\n\n'
else:
os_list = "No Activity tracked this Week"
stats = stats + '💻 Operating Systems: \n' + os_list + '\n\n'
stats = stats + '```\n\n'
else:
print("Waka Time Api Key Not Configured Properly")
except Exception as e:
print("Waka Time Api Key Not Configured" + str(e))
stats = stats + '```\n\n'
else:
print("Error With WAKA time API returned " + str(request.status_code) + " Response " + str(request.json()))
return stats
@@ -212,16 +269,17 @@ def generate_new_readme(stats: str, readme: str):
if __name__ == '__main__':
g = Github(ghtoken)
try:
g = Github(ghtoken)
repo = g.get_repo(f"{user}/{user}")
contents = repo.get_readme()
headers = {"Authorization": "Bearer " + ghtoken}
waka_stats = get_stats()
rdmd = decode_readme(contents.content)
new_readme = generate_new_readme(stats=waka_stats, readme=rdmd)
if new_readme != rdmd:
repo.update_file(path=contents.path, message='Updated with Dev Metrics',
content=new_readme, sha=contents.sha, branch='master')
except Exception as e:
print("Exception Occurred" + str(e))
except GithubException:
print("Authentication Error. Try saving a GitHub Personal Access Token in your Repo Secrets")
sys.exit(1)
contents = repo.get_readme()
headers = {"Authorization": "Bearer " + ghtoken}
waka_stats = get_stats()
rdmd = decode_readme(contents.content)
new_readme = generate_new_readme(stats=waka_stats, readme=rdmd)
if new_readme != rdmd:
repo.update_file(path=contents.path, message='Updated with Dev Metrics',
content=new_readme, sha=contents.sha, branch='master')