You've already forked wakapi-readme-stats
Update main.py
This commit is contained in:
487
main.py
487
main.py
@@ -1,58 +1,57 @@
|
|||||||
'''
|
"""
|
||||||
Readme Development Metrics With waka time progress
|
Readme Development Metrics With waka time progress
|
||||||
'''
|
"""
|
||||||
import re
|
|
||||||
import os
|
|
||||||
import base64
|
import base64
|
||||||
from pytz import timezone
|
import datetime
|
||||||
|
import json
|
||||||
|
import math
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import traceback
|
||||||
|
from string import Template
|
||||||
|
from urllib.parse import quote
|
||||||
|
|
||||||
|
import humanize
|
||||||
import pytz
|
import pytz
|
||||||
import requests
|
import requests
|
||||||
from github import Github, GithubException, InputGitAuthor
|
|
||||||
import datetime
|
|
||||||
from string import Template
|
|
||||||
from loc import LinesOfCode
|
|
||||||
import time
|
|
||||||
import traceback
|
|
||||||
import humanize
|
|
||||||
from urllib.parse import quote
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
from datetime import date
|
|
||||||
import math
|
|
||||||
|
|
||||||
from dotenv import load_dotenv
|
from dotenv import load_dotenv
|
||||||
|
from github import Github, InputGitAuthor
|
||||||
|
from pytz import timezone
|
||||||
|
|
||||||
|
from loc import LinesOfCode
|
||||||
|
|
||||||
load_dotenv()
|
load_dotenv()
|
||||||
|
|
||||||
START_COMMENT = '<!--START_SECTION:waka-->'
|
START_COMMENT = "<!--START_SECTION:waka-->"
|
||||||
END_COMMENT = '<!--END_SECTION:waka-->'
|
END_COMMENT = "<!--END_SECTION:waka-->"
|
||||||
listReg = f"{START_COMMENT}[\\s\\S]+{END_COMMENT}"
|
listReg = f"{START_COMMENT}[\\s\\S]+{END_COMMENT}"
|
||||||
|
|
||||||
waka_key = os.getenv('INPUT_WAKATIME_API_KEY')
|
waka_key = os.getenv("INPUT_WAKATIME_API_KEY")
|
||||||
ghtoken = os.getenv('INPUT_GH_TOKEN')
|
ghtoken = os.getenv("INPUT_GH_TOKEN")
|
||||||
showTimeZone = os.getenv('INPUT_SHOW_TIMEZONE')
|
showTimeZone = os.getenv("INPUT_SHOW_TIMEZONE", "True")
|
||||||
showProjects = os.getenv('INPUT_SHOW_PROJECTS')
|
showProjects = os.getenv("INPUT_SHOW_PROJECTS", "False")
|
||||||
showEditors = os.getenv('INPUT_SHOW_EDITORS')
|
showEditors = os.getenv("INPUT_SHOW_EDITORS", "True")
|
||||||
showOs = os.getenv('INPUT_SHOW_OS')
|
showOs = os.getenv("INPUT_SHOW_OS", "True")
|
||||||
showCommit = os.getenv('INPUT_SHOW_COMMIT')
|
showCommit = os.getenv("INPUT_SHOW_COMMIT", "True")
|
||||||
showLanguage = os.getenv('INPUT_SHOW_LANGUAGE')
|
showLanguage = os.getenv("INPUT_SHOW_LANGUAGE", "True")
|
||||||
show_loc = os.getenv('INPUT_SHOW_LINES_OF_CODE')
|
show_loc = os.getenv("INPUT_SHOW_LINES_OF_CODE", "False")
|
||||||
show_days_of_week = os.getenv('INPUT_SHOW_DAYS_OF_WEEK')
|
show_days_of_week = os.getenv("INPUT_SHOW_DAYS_OF_WEEK", "True")
|
||||||
showLanguagePerRepo = os.getenv('INPUT_SHOW_LANGUAGE_PER_REPO')
|
showLanguagePerRepo = os.getenv("INPUT_SHOW_LANGUAGE_PER_REPO", "True")
|
||||||
showLocChart = os.getenv('INPUT_SHOW_LOC_CHART')
|
showLocChart = os.getenv("INPUT_SHOW_LOC_CHART", "False")
|
||||||
show_profile_view = os.getenv('INPUT_SHOW_PROFILE_VIEWS')
|
show_profile_view = os.getenv("INPUT_SHOW_PROFILE_VIEWS", "True")
|
||||||
show_short_info = os.getenv('INPUT_SHOW_SHORT_INFO')
|
show_short_info = os.getenv("INPUT_SHOW_SHORT_INFO", "False")
|
||||||
locale = os.getenv('INPUT_LOCALE')
|
locale = os.getenv("INPUT_LOCALE", "en")
|
||||||
commit_by_me = os.getenv('INPUT_COMMIT_BY_ME')
|
commit_by_me = os.getenv("INPUT_COMMIT_BY_ME", "True")
|
||||||
ignored_repos_name = str(os.getenv('INPUT_IGNORED_REPOS') or '').replace(' ', '').split(',')
|
ignored_repos_name = str(os.getenv("INPUT_IGNORED_REPOS", "") or "").replace(" ", "").split(",")
|
||||||
show_updated_date = os.getenv('INPUT_SHOW_UPDATED_DATE')
|
show_updated_date = os.getenv("INPUT_SHOW_UPDATED_DATE", "True")
|
||||||
updated_date_format = os.getenv('INPUT_UPDATED_DATE_FORMAT')
|
updated_date_format = os.getenv("INPUT_UPDATED_DATE_FORMAT", "%d/%m/%Y %H:%M:%S")
|
||||||
commit_message = os.getenv('INPUT_COMMIT_MESSAGE', 'sync')
|
commit_message = os.getenv("INPUT_COMMIT_MESSAGE", "sync")
|
||||||
commit_username = os.getenv('INPUT_COMMIT_USERNAME')
|
commit_username = os.getenv("INPUT_COMMIT_USERNAME", "")
|
||||||
commit_email = os.getenv('INPUT_COMMIT_EMAIL')
|
commit_email = os.getenv("INPUT_COMMIT_EMAIL", "")
|
||||||
show_total_code_time = os.getenv('INPUT_SHOW_TOTAL_CODE_TIME')
|
show_total_code_time = os.getenv("INPUT_SHOW_TOTAL_CODE_TIME", "True")
|
||||||
symbol_version = os.getenv('INPUT_SYMBOL_VERSION').strip()
|
symbol_version = os.getenv("INPUT_SYMBOL_VERSION", "1").strip()
|
||||||
show_waka_stats = 'y'
|
time_zone = os.getenv("INPUT_TIME_ZONE", "+7")
|
||||||
|
show_waka_stats = "y"
|
||||||
# The GraphQL query to get commit data.
|
# The GraphQL query to get commit data.
|
||||||
userInfoQuery = """
|
userInfoQuery = """
|
||||||
{
|
{
|
||||||
@@ -63,7 +62,8 @@ userInfoQuery = """
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
"""
|
"""
|
||||||
createContributedRepoQuery = Template("""query {
|
createContributedRepoQuery = Template(
|
||||||
|
"""query {
|
||||||
user(login: "$username") {
|
user(login: "$username") {
|
||||||
repositoriesContributedTo(last: 100, includeUserRepositories: true) {
|
repositoriesContributedTo(last: 100, includeUserRepositories: true) {
|
||||||
nodes {
|
nodes {
|
||||||
@@ -76,8 +76,10 @@ createContributedRepoQuery = Template("""query {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
""")
|
"""
|
||||||
createCommittedDateQuery = Template("""
|
)
|
||||||
|
createCommittedDateQuery = Template(
|
||||||
|
"""
|
||||||
query {
|
query {
|
||||||
repository(owner: "$owner", name: "$name") {
|
repository(owner: "$owner", name: "$name") {
|
||||||
defaultBranchRef {
|
defaultBranchRef {
|
||||||
@@ -95,25 +97,29 @@ query {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
""")
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
get_loc_url = Template("""/repos/$owner/$repo/stats/code_frequency""")
|
get_loc_url = Template("""/repos/$owner/$repo/stats/code_frequency""")
|
||||||
get_profile_view = Template("""/repos/$owner/$repo/traffic/views?per=week""")
|
get_profile_view = Template("""/repos/$owner/$repo/traffic/views?per=week""")
|
||||||
get_profile_traffic = Template("""/repos/$owner/$repo/traffic/popular/referrers""")
|
get_profile_traffic = Template("""/repos/$owner/$repo/traffic/popular/referrers""")
|
||||||
truthy = ['true', '1', 't', 'y', 'yes']
|
truthy = ["true", "1", "t", "y", "yes"]
|
||||||
|
|
||||||
|
|
||||||
def run_v3_api(query):
|
def run_v3_api(query):
|
||||||
request = requests.get('https://api.github.com' + query, headers=headers)
|
request = requests.get("https://api.github.com" + query, headers=headers)
|
||||||
if request.status_code == 200:
|
if request.status_code == 200:
|
||||||
return request.json()
|
return request.json()
|
||||||
else:
|
else:
|
||||||
raise Exception(
|
raise Exception(
|
||||||
"Query failed to run by returning code of {}. {},... {}".format(request.status_code, query,
|
"Query failed to run by returning code of {}. {},... {}".format(
|
||||||
str(request.json())))
|
request.status_code, query, str(request.json())
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
repositoryListQuery = Template("""
|
repositoryListQuery = Template(
|
||||||
|
"""
|
||||||
{
|
{
|
||||||
user(login: "$username") {
|
user(login: "$username") {
|
||||||
repositories(orderBy: {field: CREATED_AT, direction: ASC}, last: 100, affiliations: [OWNER, COLLABORATOR, ORGANIZATION_MEMBER], isFork: false) {
|
repositories(orderBy: {field: CREATED_AT, direction: ASC}, last: 100, affiliations: [OWNER, COLLABORATOR, ORGANIZATION_MEMBER], isFork: false) {
|
||||||
@@ -153,22 +159,20 @@ repositoryListQuery = Template("""
|
|||||||
name
|
name
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
""")
|
"""
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
def millify(n):
|
def millify(n):
|
||||||
millnames = ['', ' Thousand', ' Million', ' Billion', ' Trillion']
|
millnames = ["", " Thousand", " Million", " Billion", " Trillion"]
|
||||||
n = float(n)
|
n = float(n)
|
||||||
millidx = max(0, min(len(millnames) - 1,
|
millidx = max(0, min(len(millnames) - 1, int(math.floor(0 if n == 0 else math.log10(abs(n)) / 3))))
|
||||||
int(math.floor(0
|
|
||||||
if n == 0
|
|
||||||
else math.log10(abs(n)) / 3))))
|
|
||||||
|
|
||||||
return '{:.0f}{}'.format(n / 10 ** (3 * millidx), millnames[millidx])
|
return "{:.0f}{}".format(n / 10 ** (3 * millidx), millnames[millidx])
|
||||||
|
|
||||||
|
|
||||||
def run_query(query):
|
def run_query(query):
|
||||||
request = requests.post('https://api.github.com/graphql', json={'query': query}, headers=headers)
|
request = requests.post("https://api.github.com/graphql", json={"query": query}, headers=headers)
|
||||||
if request.status_code == 200:
|
if request.status_code == 200:
|
||||||
return request.json()
|
return request.json()
|
||||||
else:
|
else:
|
||||||
@@ -176,48 +180,50 @@ def run_query(query):
|
|||||||
|
|
||||||
|
|
||||||
def make_graph(percent: float):
|
def make_graph(percent: float):
|
||||||
'''Make progress graph from API graph'''
|
"""Make progress graph from API graph"""
|
||||||
if (symbol_version == '1'): # version 1
|
if symbol_version == "1": # version 1
|
||||||
done_block = '█'
|
done_block = "█"
|
||||||
empty_block = '░'
|
empty_block = "░"
|
||||||
elif (symbol_version == '2'): # version 2
|
elif symbol_version == "2": # version 2
|
||||||
done_block = '⣿'
|
done_block = "⣿"
|
||||||
empty_block = '⣀'
|
empty_block = "⣀"
|
||||||
elif (symbol_version == '3'): # version 3
|
elif symbol_version == "3": # version 3
|
||||||
done_block = '⬛'
|
done_block = "⬛"
|
||||||
empty_block = '⬜'
|
empty_block = "⬜"
|
||||||
else:
|
else:
|
||||||
done_block = '█' # default is version 1
|
done_block = "█" # default is version 1
|
||||||
empty_block = '░'
|
empty_block = "░"
|
||||||
|
|
||||||
pc_rnd = round(percent)
|
pc_rnd = round(percent)
|
||||||
return f"{done_block * int(pc_rnd / 4)}{empty_block * int(25 - int(pc_rnd / 4))}"
|
return f"{done_block * int(pc_rnd / 4)}{empty_block * int(25 - int(pc_rnd / 4))}"
|
||||||
|
|
||||||
|
|
||||||
def make_list(data: list):
|
def make_list(data: list):
|
||||||
'''Make List'''
|
"""Make List"""
|
||||||
data_list = []
|
data_list = []
|
||||||
for l in data[:5]:
|
for l in data[:5]:
|
||||||
ln = len(l['name'])
|
ln = len(l["name"])
|
||||||
ln_text = len(l['text'])
|
ln_text = len(l["text"])
|
||||||
op = f"{l['name'][:25]}{' ' * (25 - ln)}{l['text']}{' ' * (20 - ln_text)}{make_graph(l['percent'])} {l['percent']}%"
|
op = f"{l['name'][:25]}{' ' * (25 - ln)}{l['text']}{' ' * (20 - ln_text)}{make_graph(l['percent'])} {l['percent']}%"
|
||||||
data_list.append(op)
|
data_list.append(op)
|
||||||
return ' \n'.join(data_list)
|
return " \n".join(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[:7]:
|
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']}%"
|
||||||
|
)
|
||||||
data_list.append(op)
|
data_list.append(op)
|
||||||
return ' \n'.join(data_list)
|
return " \n".join(data_list)
|
||||||
|
|
||||||
|
|
||||||
def generate_commit_list(tz):
|
def generate_commit_list(tz):
|
||||||
string = ''
|
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"]
|
||||||
@@ -225,7 +231,7 @@ def generate_commit_list(tz):
|
|||||||
|
|
||||||
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"]
|
||||||
repos = [d for d in nodes if d['isFork'] is False]
|
repos = [d for d in nodes if d["isFork"] is False]
|
||||||
|
|
||||||
morning = 0 # 6 - 12
|
morning = 0 # 6 - 12
|
||||||
daytime = 0 # 12 - 18
|
daytime = 0 # 12 - 18
|
||||||
@@ -242,15 +248,18 @@ def generate_commit_list(tz):
|
|||||||
|
|
||||||
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"]["defaultBranchRef"]["target"]["history"]["edges"]
|
committed_dates = result["data"]["repository"]["defaultBranchRef"]["target"]["history"]["edges"]
|
||||||
for committedDate in committed_dates:
|
for committedDate in committed_dates:
|
||||||
date = datetime.datetime.strptime(committedDate["node"]["committedDate"],
|
date = (
|
||||||
"%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=pytz.utc).astimezone(
|
datetime.datetime.strptime(committedDate["node"]["committedDate"], "%Y-%m-%dT%H:%M:%SZ")
|
||||||
timezone(tz))
|
.replace(tzinfo=pytz.utc)
|
||||||
|
.astimezone(timezone(tz))
|
||||||
|
)
|
||||||
hour = date.hour
|
hour = date.hour
|
||||||
weekday = date.strftime('%A')
|
weekday = date.strftime("%A")
|
||||||
if 6 <= hour < 12:
|
if 6 <= hour < 12:
|
||||||
morning += 1
|
morning += 1
|
||||||
if 12 <= hour < 18:
|
if 12 <= hour < 18:
|
||||||
@@ -280,51 +289,72 @@ def generate_commit_list(tz):
|
|||||||
|
|
||||||
sumAll = morning + daytime + evening + night
|
sumAll = morning + daytime + evening + night
|
||||||
sum_week = Sunday + Monday + Tuesday + Friday + Saturday + Wednesday + Thursday
|
sum_week = Sunday + Monday + Tuesday + Friday + Saturday + Wednesday + Thursday
|
||||||
title = translate['I am an Early'] if morning + daytime >= evening + night else translate['I am a Night']
|
title = translate["I am an Early"] if morning + daytime >= evening + night else translate["I am a Night"]
|
||||||
one_day = [
|
one_day = [
|
||||||
{"name": "🌞 " + translate['Morning'], "text": str(morning) + " commits",
|
{
|
||||||
"percent": round((morning / sumAll) * 100, 2)},
|
"name": "🌞 " + translate["Morning"],
|
||||||
{"name": "🌆 " + translate['Daytime'], "text": str(daytime) + " commits",
|
"text": str(morning) + " commits",
|
||||||
"percent": round((daytime / sumAll) * 100, 2)},
|
"percent": round((morning / sumAll) * 100, 2),
|
||||||
{"name": "🌃 " + translate['Evening'], "text": str(evening) + " commits",
|
},
|
||||||
"percent": round((evening / sumAll) * 100, 2)},
|
{
|
||||||
{"name": "🌙 " + translate['Night'], "text": str(night) + " commits",
|
"name": "🌆 " + translate["Daytime"],
|
||||||
"percent": round((night / sumAll) * 100, 2)},
|
"text": str(daytime) + " commits",
|
||||||
|
"percent": round((daytime / sumAll) * 100, 2),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "🌃 " + translate["Evening"],
|
||||||
|
"text": str(evening) + " commits",
|
||||||
|
"percent": round((evening / sumAll) * 100, 2),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "🌙 " + translate["Night"],
|
||||||
|
"text": str(night) + " commits",
|
||||||
|
"percent": round((night / sumAll) * 100, 2),
|
||||||
|
},
|
||||||
]
|
]
|
||||||
dayOfWeek = [
|
dayOfWeek = [
|
||||||
{"name": translate['Monday'], "text": str(Monday) + " commits", "percent": round((Monday / sum_week) * 100, 2)},
|
{"name": translate["Monday"], "text": str(Monday) + " commits", "percent": round((Monday / sum_week) * 100, 2)},
|
||||||
{"name": translate['Tuesday'], "text": str(Tuesday) + " commits",
|
{
|
||||||
"percent": round((Tuesday / sum_week) * 100, 2)},
|
"name": translate["Tuesday"],
|
||||||
{"name": translate['Wednesday'], "text": str(Wednesday) + " commits",
|
"text": str(Tuesday) + " commits",
|
||||||
"percent": round((Wednesday / sum_week) * 100, 2)},
|
"percent": round((Tuesday / sum_week) * 100, 2),
|
||||||
{"name": translate['Thursday'], "text": str(Thursday) + " commits",
|
},
|
||||||
"percent": round((Thursday / sum_week) * 100, 2)},
|
{
|
||||||
{"name": translate['Friday'], "text": str(Friday) + " commits", "percent": round((Friday / sum_week) * 100, 2)},
|
"name": translate["Wednesday"],
|
||||||
{"name": translate['Saturday'], "text": str(Saturday) + " commits",
|
"text": str(Wednesday) + " commits",
|
||||||
"percent": round((Saturday / sum_week) * 100, 2)},
|
"percent": round((Wednesday / sum_week) * 100, 2),
|
||||||
{"name": translate['Sunday'], "text": str(Sunday) + " commits", "percent": round((Sunday / sum_week) * 100, 2)},
|
},
|
||||||
|
{
|
||||||
|
"name": translate["Thursday"],
|
||||||
|
"text": str(Thursday) + " commits",
|
||||||
|
"percent": round((Thursday / sum_week) * 100, 2),
|
||||||
|
},
|
||||||
|
{"name": translate["Friday"], "text": str(Friday) + " commits", "percent": round((Friday / sum_week) * 100, 2)},
|
||||||
|
{
|
||||||
|
"name": translate["Saturday"],
|
||||||
|
"text": str(Saturday) + " commits",
|
||||||
|
"percent": round((Saturday / sum_week) * 100, 2),
|
||||||
|
},
|
||||||
|
{"name": translate["Sunday"], "text": str(Sunday) + " commits", "percent": round((Sunday / sum_week) * 100, 2)},
|
||||||
]
|
]
|
||||||
|
|
||||||
string = string + '**' + title + '** \n\n' + '```text\n' + make_commit_list(one_day) + '\n\n```\n'
|
string = string + "**" + title + "** \n\n" + "```text\n" + make_commit_list(one_day) + "\n\n```\n"
|
||||||
|
|
||||||
if show_days_of_week.lower() in truthy:
|
if show_days_of_week.lower() in truthy:
|
||||||
max_element = {
|
max_element = {"percent": 0}
|
||||||
'percent': 0
|
|
||||||
}
|
|
||||||
|
|
||||||
for day in dayOfWeek:
|
for day in dayOfWeek:
|
||||||
if day['percent'] > max_element['percent']:
|
if day["percent"] > max_element["percent"]:
|
||||||
max_element = day
|
max_element = day
|
||||||
days_title = translate['I am Most Productive on'] % max_element['name']
|
days_title = translate["I am Most Productive on"] % max_element["name"]
|
||||||
string = string + '📅 **' + days_title + '** \n\n' + '```text\n' + make_commit_list(dayOfWeek) + '\n\n```\n'
|
string = string + "📅 **" + days_title + "** \n\n" + "```text\n" + make_commit_list(dayOfWeek) + "\n\n```\n"
|
||||||
|
|
||||||
return string
|
return string
|
||||||
|
|
||||||
|
|
||||||
def get_waka_time_stats():
|
def get_waka_time_stats():
|
||||||
stats = ''
|
stats = ""
|
||||||
request = requests.get(
|
request = requests.get(f"https://wakatime.com/api/v1/users/current/stats/last_7_days?api_key={waka_key}")
|
||||||
f"https://wakatime.com/api/v1/users/current/stats/last_7_days?api_key={waka_key}")
|
|
||||||
no_activity = translate["No Activity Tracked This Week"]
|
no_activity = translate["No Activity Tracked This Week"]
|
||||||
|
|
||||||
if request.status_code == 401:
|
if request.status_code == 401:
|
||||||
@@ -332,49 +362,55 @@ def get_waka_time_stats():
|
|||||||
else:
|
else:
|
||||||
data = request.json()
|
data = request.json()
|
||||||
if showCommit.lower() in truthy:
|
if showCommit.lower() in truthy:
|
||||||
stats = stats + generate_commit_list(tz=data['data']['timezone']) + '\n\n'
|
stats = stats + generate_commit_list(tz=data["data"]["timezone"]) + "\n\n"
|
||||||
|
|
||||||
if showTimeZone.lower() in truthy or showLanguage.lower() in truthy or showEditors.lower() in truthy or \
|
if (
|
||||||
showProjects.lower() in truthy or showOs.lower() in truthy:
|
showTimeZone.lower() in truthy
|
||||||
stats += '📊 **' + translate['This Week I Spend My Time On'] + '** \n\n'
|
or showLanguage.lower() in truthy
|
||||||
stats += '```text\n'
|
or showEditors.lower() in truthy
|
||||||
|
or showProjects.lower() in truthy
|
||||||
|
or showOs.lower() in truthy
|
||||||
|
):
|
||||||
|
stats += "📊 **" + translate["This Week I Spend My Time On"] + "** \n\n"
|
||||||
|
stats += "```text\n"
|
||||||
|
|
||||||
if showTimeZone.lower() in truthy:
|
if showTimeZone.lower() in truthy:
|
||||||
tzone = data['data']['timezone']
|
tzone = data["data"]["timezone"]
|
||||||
stats = stats + '⌚︎ ' + translate['Timezone'] + ': ' + tzone + '\n\n'
|
stats = stats + "⌚︎ " + translate["Timezone"] + ": " + tzone + "\n\n"
|
||||||
|
|
||||||
if showLanguage.lower() in truthy:
|
if showLanguage.lower() in truthy:
|
||||||
if len(data['data']['languages']) == 0:
|
if len(data["data"]["languages"]) == 0:
|
||||||
lang_list = no_activity
|
lang_list = no_activity
|
||||||
else:
|
else:
|
||||||
lang_list = make_list(data['data']['languages'])
|
lang_list = make_list(data["data"]["languages"])
|
||||||
stats = stats + '💬 ' + translate['Languages'] + ': \n' + lang_list + '\n\n'
|
stats = stats + "💬 " + translate["Languages"] + ": \n" + lang_list + "\n\n"
|
||||||
|
|
||||||
if showEditors.lower() in truthy:
|
if showEditors.lower() in truthy:
|
||||||
if len(data['data']['editors']) == 0:
|
if len(data["data"]["editors"]) == 0:
|
||||||
edit_list = no_activity
|
edit_list = no_activity
|
||||||
else:
|
else:
|
||||||
edit_list = make_list(data['data']['editors'])
|
edit_list = make_list(data["data"]["editors"])
|
||||||
stats = stats + '🔥 ' + translate['Editors'] + ': \n' + edit_list + '\n\n'
|
stats = stats + "🔥 " + translate["Editors"] + ": \n" + edit_list + "\n\n"
|
||||||
|
|
||||||
if showProjects.lower() in truthy:
|
if showProjects.lower() in truthy:
|
||||||
if len(data['data']['projects']) == 0:
|
if len(data["data"]["projects"]) == 0:
|
||||||
project_list = no_activity
|
project_list = no_activity
|
||||||
else:
|
else:
|
||||||
# Re-order the project list by percentage
|
# Re-order the project list by percentage
|
||||||
data['data']['projects'] = sorted(data['data']['projects'], key=lambda x: x["percent"],
|
data["data"]["projects"] = sorted(
|
||||||
reverse=True)
|
data["data"]["projects"], key=lambda x: x["percent"], reverse=True
|
||||||
project_list = make_list(data['data']['projects'])
|
)
|
||||||
stats = stats + '🐱💻 ' + translate['Projects'] + ': \n' + project_list + '\n\n'
|
project_list = make_list(data["data"]["projects"])
|
||||||
|
stats = stats + "🐱💻 " + translate["Projects"] + ": \n" + project_list + "\n\n"
|
||||||
|
|
||||||
if showOs.lower() in truthy:
|
if showOs.lower() in truthy:
|
||||||
if len(data['data']['operating_systems']) == 0:
|
if len(data["data"]["operating_systems"]) == 0:
|
||||||
os_list = no_activity
|
os_list = no_activity
|
||||||
else:
|
else:
|
||||||
os_list = make_list(data['data']['operating_systems'])
|
os_list = make_list(data["data"]["operating_systems"])
|
||||||
stats = stats + '💻 ' + translate['operating system'] + ': \n' + os_list + '\n\n'
|
stats = stats + "💻 " + translate["operating system"] + ": \n" + os_list + "\n\n"
|
||||||
|
|
||||||
stats += '```\n\n'
|
stats += "```\n\n"
|
||||||
|
|
||||||
return stats
|
return stats
|
||||||
|
|
||||||
@@ -382,35 +418,31 @@ def get_waka_time_stats():
|
|||||||
def generate_language_per_repo(result):
|
def generate_language_per_repo(result):
|
||||||
language_count = {}
|
language_count = {}
|
||||||
total = 0
|
total = 0
|
||||||
for repo in result['data']['user']['repositories']['edges']:
|
for repo in result["data"]["user"]["repositories"]["edges"]:
|
||||||
if repo['node']['primaryLanguage'] is None:
|
if repo["node"]["primaryLanguage"] is None:
|
||||||
continue
|
continue
|
||||||
language = repo['node']['primaryLanguage']['name']
|
language = repo["node"]["primaryLanguage"]["name"]
|
||||||
color_code = repo['node']['primaryLanguage']['color']
|
color_code = repo["node"]["primaryLanguage"]["color"]
|
||||||
total += 1
|
total += 1
|
||||||
if language not in language_count.keys():
|
if language not in language_count.keys():
|
||||||
language_count[language] = {}
|
language_count[language] = {}
|
||||||
language_count[language]['count'] = 1
|
language_count[language]["count"] = 1
|
||||||
else:
|
else:
|
||||||
language_count[language]['count'] = language_count[language]['count'] + 1
|
language_count[language]["count"] = language_count[language]["count"] + 1
|
||||||
language_count[language]['color'] = color_code
|
language_count[language]["color"] = color_code
|
||||||
data = []
|
data = []
|
||||||
sorted_labels = list(language_count.keys())
|
sorted_labels = list(language_count.keys())
|
||||||
sorted_labels.sort(key=lambda x: language_count[x]['count'], reverse=True)
|
sorted_labels.sort(key=lambda x: language_count[x]["count"], reverse=True)
|
||||||
most_language_repo = sorted_labels[0]
|
most_language_repo = sorted_labels[0]
|
||||||
for label in sorted_labels:
|
for label in sorted_labels:
|
||||||
percent = round(language_count[label]['count'] / total * 100, 2)
|
percent = round(language_count[label]["count"] / total * 100, 2)
|
||||||
extension = " repos"
|
extension = " repos"
|
||||||
if language_count[label]['count'] == 1:
|
if language_count[label]["count"] == 1:
|
||||||
extension = " repo"
|
extension = " repo"
|
||||||
data.append({
|
data.append({"name": label, "text": str(language_count[label]["count"]) + extension, "percent": percent})
|
||||||
"name": label,
|
|
||||||
"text": str(language_count[label]['count']) + extension,
|
|
||||||
"percent": percent
|
|
||||||
})
|
|
||||||
|
|
||||||
title = translate['I Mostly Code in'] % most_language_repo
|
title = translate["I Mostly Code in"] % most_language_repo
|
||||||
return '**' + title + '** \n\n' + '```text\n' + make_list(data) + '\n\n```\n'
|
return "**" + title + "** \n\n" + "```text\n" + make_list(data) + "\n\n```\n"
|
||||||
|
|
||||||
|
|
||||||
def get_yearly_data():
|
def get_yearly_data():
|
||||||
@@ -427,27 +459,32 @@ def get_line_of_code():
|
|||||||
loc = LinesOfCode(id, username, ghtoken, repositoryList, ignored_repos_name)
|
loc = LinesOfCode(id, username, ghtoken, repositoryList, ignored_repos_name)
|
||||||
yearly_data = loc.calculateLoc()
|
yearly_data = loc.calculateLoc()
|
||||||
total_loc = sum(
|
total_loc = sum(
|
||||||
[yearly_data[year][quarter][lang] for year in yearly_data for quarter in yearly_data[year] for lang in
|
[
|
||||||
yearly_data[year][quarter]])
|
yearly_data[year][quarter][lang]
|
||||||
|
for year in yearly_data
|
||||||
|
for quarter in yearly_data[year]
|
||||||
|
for lang in yearly_data[year][quarter]
|
||||||
|
]
|
||||||
|
)
|
||||||
return millify(int(total_loc))
|
return millify(int(total_loc))
|
||||||
|
|
||||||
|
|
||||||
def get_short_info(github):
|
def get_short_info(github):
|
||||||
string = '**🐱 ' + translate['My GitHub Data'] + '** \n\n'
|
string = "**🐱 " + translate["My GitHub Data"] + "** \n\n"
|
||||||
user_info = github.get_user()
|
user_info = github.get_user()
|
||||||
if user_info.disk_usage is None:
|
if user_info.disk_usage is None:
|
||||||
disk_usage = humanize.naturalsize(0)
|
disk_usage = humanize.naturalsize(0)
|
||||||
print("Please add new github personal access token with user permission")
|
print("Please add new github personal access token with user permission")
|
||||||
else:
|
else:
|
||||||
disk_usage = humanize.naturalsize(user_info.disk_usage)
|
disk_usage = humanize.naturalsize(user_info.disk_usage)
|
||||||
request = requests.get('https://github-contributions.now.sh/api/v1/' + user_info.login)
|
request = requests.get("https://github-contributions.now.sh/api/v1/" + user_info.login)
|
||||||
if request.status_code == 200:
|
if request.status_code == 200:
|
||||||
data = request.json()
|
data = request.json()
|
||||||
total = data['years'][0]['total']
|
total = data["years"][0]["total"]
|
||||||
year = data['years'][0]['year']
|
year = data["years"][0]["year"]
|
||||||
string += '> 🏆 ' + translate['Contributions in the year'] % (humanize.intcomma(total), year) + '\n > \n'
|
string += "> 🏆 " + translate["Contributions in the year"] % (humanize.intcomma(total), year) + "\n > \n"
|
||||||
|
|
||||||
string += '> 📦 ' + translate["Used in GitHub's Storage"] % disk_usage + ' \n > \n'
|
string += "> 📦 " + translate["Used in GitHub's Storage"] % disk_usage + " \n > \n"
|
||||||
is_hireable = user_info.hireable
|
is_hireable = user_info.hireable
|
||||||
public_repo = user_info.public_repos
|
public_repo = user_info.public_repos
|
||||||
private_repo = user_info.owned_private_repos
|
private_repo = user_info.owned_private_repos
|
||||||
@@ -458,20 +495,26 @@ def get_short_info(github):
|
|||||||
else:
|
else:
|
||||||
string += "> 🚫 " + translate["Not Opted to Hire"] + "\n > \n"
|
string += "> 🚫 " + translate["Not Opted to Hire"] + "\n > \n"
|
||||||
|
|
||||||
string += '> 📜 '
|
string += "> 📜 "
|
||||||
string += translate['public repositories'] % public_repo + " " + '\n > \n' if public_repo != 1 else translate[
|
string += (
|
||||||
'public repository'] % public_repo + " " + '\n > \n'
|
translate["public repositories"] % public_repo + " " + "\n > \n"
|
||||||
string += '> 🔑 '
|
if public_repo != 1
|
||||||
string += translate['private repositories'] % private_repo + " " + ' \n > \n' if private_repo != 1 else translate[
|
else translate["public repository"] % public_repo + " " + "\n > \n"
|
||||||
'private repository'] % private_repo + " " + '\n > \n'
|
)
|
||||||
|
string += "> 🔑 "
|
||||||
|
string += (
|
||||||
|
translate["private repositories"] % private_repo + " " + " \n > \n"
|
||||||
|
if private_repo != 1
|
||||||
|
else translate["private repository"] % private_repo + " " + "\n > \n"
|
||||||
|
)
|
||||||
|
|
||||||
return string
|
return string
|
||||||
|
|
||||||
|
|
||||||
def get_stats(github):
|
def get_stats(github):
|
||||||
'''Gets API data and returns markdown progress'''
|
"""Gets API data and returns markdown progress"""
|
||||||
|
|
||||||
stats = ''
|
stats = ""
|
||||||
repositoryList = run_query(repositoryListQuery.substitute(username=username, id=id))
|
repositoryList = run_query(repositoryListQuery.substitute(username=username, id=id))
|
||||||
|
|
||||||
if show_loc.lower() in truthy or showLocChart.lower() in truthy:
|
if show_loc.lower() in truthy or showLocChart.lower() in truthy:
|
||||||
@@ -479,27 +522,41 @@ def get_stats(github):
|
|||||||
yearly_data = get_yearly_data()
|
yearly_data = get_yearly_data()
|
||||||
|
|
||||||
if show_total_code_time.lower() in truthy:
|
if show_total_code_time.lower() in truthy:
|
||||||
request = requests.get(
|
request = requests.get(f"https://wakatime.com/api/v1/users/current/all_time_since_today?api_key={waka_key}")
|
||||||
f"https://wakatime.com/api/v1/users/current/all_time_since_today?api_key={waka_key}")
|
|
||||||
if request.status_code == 401:
|
if request.status_code == 401:
|
||||||
print("Error With WAKA time API returned " + str(request.status_code) + " Response " + str(request.json()))
|
print("Error With WAKA time API returned " + str(request.status_code) + " Response " + str(request.json()))
|
||||||
elif "text" not in request.json()["data"]:
|
elif "text" not in request.json()["data"]:
|
||||||
print("User stats are calculating. Try again later.")
|
print("User stats are calculating. Try again later.")
|
||||||
else:
|
else:
|
||||||
data = request.json()
|
data = request.json()
|
||||||
stats += ') + '-' + quote(str(
|
") + '-blue)\n\n'
|
+ quote(str("Code Time"))
|
||||||
|
+ "-"
|
||||||
|
+ quote(str(data["data"]["text"]))
|
||||||
|
+ "-blue)\n\n"
|
||||||
|
)
|
||||||
|
|
||||||
if show_profile_view.lower() in truthy:
|
if show_profile_view.lower() in truthy:
|
||||||
data = run_v3_api(get_profile_view.substitute(owner=username, repo=username))
|
data = run_v3_api(get_profile_view.substitute(owner=username, repo=username))
|
||||||
stats += ') + '-' + str(
|
stats += (
|
||||||
data['count']) + '-blue)\n\n'
|
")
|
||||||
|
+ "-"
|
||||||
|
+ str(data["count"])
|
||||||
|
+ "-blue)\n\n"
|
||||||
|
)
|
||||||
|
|
||||||
if show_loc.lower() in truthy:
|
if show_loc.lower() in truthy:
|
||||||
stats += ') + '-' + quote(
|
")) + '%20' + quote(str(translate['Lines of code'])) + '-blue)\n\n'
|
+ quote(str(translate["From Hello World I have written"]))
|
||||||
|
+ "-"
|
||||||
|
+ quote(str(get_line_of_code()))
|
||||||
|
+ "%20"
|
||||||
|
+ quote(str(translate["Lines of code"]))
|
||||||
|
+ "-blue)\n\n"
|
||||||
|
)
|
||||||
|
|
||||||
if show_short_info.lower() in truthy:
|
if show_short_info.lower() in truthy:
|
||||||
stats += get_short_info(github)
|
stats += get_short_info(github)
|
||||||
@@ -508,17 +565,26 @@ def get_stats(github):
|
|||||||
stats += get_waka_time_stats()
|
stats += get_waka_time_stats()
|
||||||
|
|
||||||
if showLanguagePerRepo.lower() in truthy:
|
if showLanguagePerRepo.lower() in truthy:
|
||||||
stats = stats + generate_language_per_repo(repositoryList) + '\n\n'
|
stats = stats + generate_language_per_repo(repositoryList) + "\n\n"
|
||||||
|
|
||||||
if showLocChart.lower() in truthy:
|
if showLocChart.lower() in truthy:
|
||||||
stats += '**' + translate['Timeline'] + '**\n\n'
|
stats += "**" + translate["Timeline"] + "**\n\n"
|
||||||
branch_name = github.get_repo(f'{username}/{username}').default_branch
|
branch_name = github.get_repo(f"{username}/{username}").default_branch
|
||||||
stats = stats + ' \n\n'
|
stats = (
|
||||||
|
stats
|
||||||
|
+ " \n\n"
|
||||||
|
)
|
||||||
|
|
||||||
if show_updated_date.lower() in truthy:
|
if show_updated_date.lower() in truthy:
|
||||||
now = datetime.datetime.utcnow()
|
now = datetime.datetime.utcnow() + datetime.timedelta(hours=float(time_zone))
|
||||||
d1 = now.strftime(updated_date_format)
|
d1 = now.strftime(updated_date_format)
|
||||||
stats = stats + "\n Last Updated on " + d1 + " UTC"
|
stats = stats + "\n Last Updated on " + d1 + " UTC" + time_zone
|
||||||
|
|
||||||
return stats
|
return stats
|
||||||
|
|
||||||
@@ -528,22 +594,22 @@ def get_stats(github):
|
|||||||
|
|
||||||
|
|
||||||
def decode_readme(data: str):
|
def decode_readme(data: str):
|
||||||
'''Decode the contents of old readme'''
|
"""Decode the contents of old readme"""
|
||||||
decoded_bytes = base64.b64decode(data)
|
decoded_bytes = base64.b64decode(data)
|
||||||
return str(decoded_bytes, 'utf-8')
|
return str(decoded_bytes, "utf-8")
|
||||||
|
|
||||||
|
|
||||||
def generate_new_readme(stats: str, readme: str):
|
def generate_new_readme(stats: str, readme: str):
|
||||||
'''Generate a new Readme.md'''
|
"""Generate a new Readme.md"""
|
||||||
stats_in_readme = f"{START_COMMENT}\n{stats}\n{END_COMMENT}"
|
stats_in_readme = f"{START_COMMENT}\n{stats}\n{END_COMMENT}"
|
||||||
return re.sub(listReg, stats_in_readme, readme)
|
return re.sub(listReg, stats_in_readme, readme)
|
||||||
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
if __name__ == "__main__":
|
||||||
try:
|
try:
|
||||||
start_time = datetime.datetime.now().timestamp() * 1000
|
start_time = datetime.datetime.now().timestamp() * 1000
|
||||||
if ghtoken is None:
|
if ghtoken is None:
|
||||||
raise Exception('Token not available')
|
raise Exception("Token not available")
|
||||||
g = Github(ghtoken)
|
g = Github(ghtoken)
|
||||||
headers = {"Authorization": "Bearer " + ghtoken}
|
headers = {"Authorization": "Bearer " + ghtoken}
|
||||||
user_data = run_query(userInfoQuery) # Execute the query
|
user_data = run_query(userInfoQuery) # Execute the query
|
||||||
@@ -554,12 +620,12 @@ if __name__ == '__main__':
|
|||||||
repo = g.get_repo(f"{username}/{username}")
|
repo = g.get_repo(f"{username}/{username}")
|
||||||
contents = repo.get_readme()
|
contents = repo.get_readme()
|
||||||
try:
|
try:
|
||||||
with open(os.path.join(os.path.dirname(__file__), 'translation.json'), encoding='utf-8') as config_file:
|
with open(os.path.join(os.path.dirname(__file__), "translation.json"), encoding="utf-8") as config_file:
|
||||||
data = json.load(config_file)
|
data = json.load(config_file)
|
||||||
translate = data[locale]
|
translate = data[locale]
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print("Cannot find the Locale choosing default to english")
|
print("Cannot find the Locale choosing default to english")
|
||||||
translate = data['en']
|
translate = data["en"]
|
||||||
waka_stats = get_stats(g)
|
waka_stats = get_stats(g)
|
||||||
# star_me()
|
# star_me()
|
||||||
rdmd = decode_readme(contents.content)
|
rdmd = decode_readme(contents.content)
|
||||||
@@ -568,18 +634,27 @@ if __name__ == '__main__':
|
|||||||
committer = InputGitAuthor(username or commit_username, email or commit_email)
|
committer = InputGitAuthor(username or commit_username, email or commit_email)
|
||||||
else:
|
else:
|
||||||
committer = InputGitAuthor(
|
committer = InputGitAuthor(
|
||||||
commit_username or 'readme-bot',
|
commit_username or "readme-bot", commit_email or "41898282+github-actions[bot]@users.noreply.github.com"
|
||||||
commit_email or '41898282+github-actions[bot]@users.noreply.github.com'
|
|
||||||
)
|
)
|
||||||
if new_readme != rdmd:
|
if new_readme != rdmd:
|
||||||
try:
|
try:
|
||||||
repo.update_file(path=contents.path, message=commit_message,
|
repo.update_file(
|
||||||
content=new_readme, sha=contents.sha, branch='master',
|
path=contents.path,
|
||||||
committer=committer)
|
message=commit_message,
|
||||||
|
content=new_readme,
|
||||||
|
sha=contents.sha,
|
||||||
|
branch="master",
|
||||||
|
committer=committer,
|
||||||
|
)
|
||||||
except:
|
except:
|
||||||
repo.update_file(path=contents.path, message=commit_message,
|
repo.update_file(
|
||||||
content=new_readme, sha=contents.sha, branch='main',
|
path=contents.path,
|
||||||
committer=committer)
|
message=commit_message,
|
||||||
|
content=new_readme,
|
||||||
|
sha=contents.sha,
|
||||||
|
branch="main",
|
||||||
|
committer=committer,
|
||||||
|
)
|
||||||
print("Readme updated")
|
print("Readme updated")
|
||||||
end_time = datetime.datetime.now().timestamp() * 1000
|
end_time = datetime.datetime.now().timestamp() * 1000
|
||||||
print("Program processed in {} miliseconds.".format(round(end_time - start_time, 0)))
|
print("Program processed in {} miliseconds.".format(round(end_time - start_time, 0)))
|
||||||
|
|||||||
Reference in New Issue
Block a user