Merge pull request #9 from anmol098/alpha

Alpha
This commit is contained in:
Anmol Pratap Singh
2020-07-26 17:26:34 +05:30
committed by GitHub
4 changed files with 114 additions and 50 deletions

View File

@@ -1,6 +1,6 @@
The MIT License (MIT) The MIT License (MIT)
Copyright (c) 2020 ATHUL CYRIAC AJAY Copyright (c) 2020 ANMOL PRATAP SINGH
Permission is hereby granted, free of charge, to any person obtaining a copy of Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in this software and associated documentation files (the "Software"), to deal in

View File

@@ -1,10 +1,10 @@
# Dev Metrics in Readme with added feature flags 🎌 # Dev Metrics in Readme with added feature flags 🎌
![Project Preview](https://user-images.githubusercontent.com/15426564/88030180-8e1c4780-cb58-11ea-8a8b-b3576dd73652.png) ![Project Preview](https://user-images.githubusercontent.com/25841814/79395484-5081ae80-7fac-11ea-9e27-ac91472e31dd.png)
<p align="center"> <p align="center">
![Project Preview](https://user-images.githubusercontent.com/25841814/79395484-5081ae80-7fac-11ea-9e27-ac91472e31dd.png) ![Project Preview](https://user-images.githubusercontent.com/15426564/88030180-8e1c4780-cb58-11ea-8a8b-b3576dd73652.png)
<h3 align="center">📌✨Awesome Readme Stats</h3> <h3 align="center">📌✨Awesome Readme Stats</h3>
</p> </p>
@@ -28,6 +28,12 @@
Let's check out in your profile readme! Let's check out in your profile readme!
</p> </p>
<p align="center">
<a href="https://github.com/anmol098/waka-readme-stats/issues">Report Bug</a>
·
<a href="https://github.com/anmol098/waka-readme-stats/issues">Request Feature</a>
</p>
## Prep Work ## Prep Work
1. You need to update the markdown file(.md) with 2 comments. You can refer [here](#update-your-readme) for updating it. 1. You need to update the markdown file(.md) with 2 comments. You can refer [here](#update-your-readme) for updating it.

View File

@@ -1,6 +1,6 @@
name: 'Waka -- Readme Stats' name: 'Profile Readme Development Stats'
author: Anmol Pratap Singh author: Anmol Pratap Singh
description: 'Add a Wakatime Coding Activity graph in your Readme' description: 'Are you an early 🐤 or a night 🦉? When are you most productive during the day? Let''s check out in your readme!'
inputs: inputs:
GH_TOKEN: GH_TOKEN:

146
main.py
View File

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