Skip to content

Commit

Permalink
Merge branch 'master' into master
Browse files Browse the repository at this point in the history
  • Loading branch information
txtxj committed Dec 3, 2023
2 parents 4b535ba + dbb6bd8 commit 577e21e
Show file tree
Hide file tree
Showing 6 changed files with 36 additions and 23 deletions.
3 changes: 2 additions & 1 deletion sources/graphics_chart_drawer.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ async def create_loc_graph(yearly_data: Dict, save_path: str):
:param save_path: Path to save the graph file.
"""
colors = await DM.get_remote_yaml("linguist")

if colors is None:
colors = dict()
years = len(yearly_data.keys())
year_indexes = arange(years)

Expand Down
4 changes: 2 additions & 2 deletions sources/graphics_list_formatter.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,7 @@ async def make_commit_day_time_list(time_zone: str, repositories: Dict, commit_d
day_times = [0] * 4 # 0 - 6, 6 - 12, 12 - 18, 18 - 24
week_days = [0] * 7 # Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday

for repository in [d for d in repositories["data"]["user"]["repositories"]["nodes"]]:
for repository in repositories:
if repository["name"] not in commit_dates.keys():
continue

Expand Down Expand Up @@ -128,7 +128,7 @@ def make_language_per_repo_list(repositories: Dict) -> str:
:returns: string representation of statistics.
"""
language_count = dict()
repos_with_language = [repo for repo in repositories["data"]["user"]["repositories"]["nodes"] if repo["primaryLanguage"] is not None]
repos_with_language = [repo for repo in repositories if repo["primaryLanguage"] is not None]
for repo in repos_with_language:
language = repo["primaryLanguage"]["name"]
language_count[language] = language_count.get(language, {"count": 0})
Expand Down
19 changes: 14 additions & 5 deletions sources/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ async def get_waka_time_stats(repositories: Dict, commit_dates: Dict) -> str:

data = await DM.get_remote_json("waka_latest")
summary_data = await DM.get_remote_json("waka_summary")
if data is None:
DBM.p("WakaTime data unavailable!")
return stats
if EM.SHOW_COMMIT or EM.SHOW_DAYS_OF_WEEK: # if any on flag is turned on then we need to calculate the data and print accordingly
DBM.i("Adding user commit day time info...")
stats += f"{await make_commit_day_time_list(data['data']['timezone'], repositories, commit_dates)}\n\n"
Expand Down Expand Up @@ -95,6 +98,9 @@ async def get_short_github_info() -> str:
stats += f"> 📦 {disk_usage} \n > \n"

data = await DM.get_remote_json("github_stats")
if data is None:
DBM.p("GitHub contributions data unavailable!")
return stats
DBM.i("Adding contributions info...")
if len(data["years"]) > 0:
contributions = FM.t("Contributions in the year") % (intcomma(data["years"][0]["total"]), data["years"][0]["year"])
Expand Down Expand Up @@ -135,15 +141,15 @@ async def collect_user_repositories() -> Dict:
"""
DBM.i("Getting user repositories list...")
repositories = await DM.get_remote_graphql("user_repository_list", username=GHM.USER.login, id=GHM.USER.node_id)
repo_names = [repo["name"] for repo in repositories["data"]["user"]["repositories"]["nodes"]]
repo_names = [repo["name"] for repo in repositories]
DBM.g("\tUser repository list collected!")

contributed = await DM.get_remote_graphql("repos_contributed_to", username=GHM.USER.login)
contributed_nodes = [r for r in contributed["data"]["user"]["repositoriesContributedTo"]["nodes"] if r["name"] not in repo_names and not r["isFork"]]

contributed_nodes = [repo for repo in contributed if repo is not None and repo["name"] not in repo_names and not repo["isFork"]]
DBM.g("\tUser contributed to repository list collected!")

repositories["data"]["user"]["repositories"]["nodes"] += contributed_nodes
return repositories
return repositories + contributed_nodes


async def get_stats() -> str:
Expand All @@ -167,7 +173,10 @@ async def get_stats() -> str:
if EM.SHOW_TOTAL_CODE_TIME:
DBM.i("Adding total code time info...")
data = await DM.get_remote_json("waka_all")
stats += f"![Code Time](http://img.shields.io/badge/{quote('Code Time')}-{quote(str(data['data']['text']))}-blue)\n\n"
if data is None:
DBM.p("WakaTime data unavailable!")
else:
stats += f"![Code Time](http://img.shields.io/badge/{quote('Code Time')}-{quote(str(data['data']['text']))}-blue)\n\n"

if EM.SHOW_PROFILE_VIEWS:
DBM.i("Adding profile views info...")
Expand Down
18 changes: 11 additions & 7 deletions sources/manager_download.py
Original file line number Diff line number Diff line change
Expand Up @@ -167,15 +167,15 @@ async def close_remote_resources():
await resource

@staticmethod
async def _get_remote_resource(resource: str, convertor: Optional[Callable[[bytes], Dict]]) -> Dict:
async def _get_remote_resource(resource: str, convertor: Optional[Callable[[bytes], Dict]]) -> Dict or None:
"""
Receive execution result of static query, wait for it if necessary.
If the query wasn't cached previously, cache it.
NB! Caching is done before response parsing - to throw exception on accessing cached erroneous response.
:param resource: Static query identifier.
:param convertor: Optional function to convert `response.contents` to dict.
By default `response.json()` is used.
:return: Response dictionary.
:return: Response dictionary or None.
"""
DBM.i(f"\tMaking a remote API query named '{resource}'...")
if isinstance(DownloadManager._REMOTE_RESOURCES_CACHE[resource], Awaitable):
Expand All @@ -190,11 +190,17 @@ async def _get_remote_resource(resource: str, convertor: Optional[Callable[[byte
return res.json()
else:
return convertor(res.content)
elif res.status_code == 201:
DBM.w(f"\tQuery '{resource}' returned 201 status code")
return None
elif res.status_code == 202:
DBM.w(f"\tQuery '{resource}' returned 202 status code")
return None
else:
raise Exception(f"Query '{res.url}' failed to run by returning code of {res.status_code}: {res.json()}")

@staticmethod
async def get_remote_json(resource: str) -> Dict:
async def get_remote_json(resource: str) -> Dict or None:
"""
Shortcut for `_get_remote_resource` to return JSON response data.
:param resource: Static query identifier.
Expand All @@ -203,7 +209,7 @@ async def get_remote_json(resource: str) -> Dict:
return await DownloadManager._get_remote_resource(resource, None)

@staticmethod
async def get_remote_yaml(resource: str) -> Dict:
async def get_remote_yaml(resource: str) -> Dict or None:
"""
Shortcut for `_get_remote_resource` to return YAML response data.
:param resource: Static query identifier.
Expand Down Expand Up @@ -272,9 +278,7 @@ async def _fetch_graphql_paginated(query: str, **kwargs) -> Dict:
query_response = await DownloadManager._fetch_graphql_query(query, **kwargs, pagination=pagination)
new_page_list, page_info = DownloadManager._find_pagination_and_data_list(query_response)
page_list += new_page_list
_, page_info = DownloadManager._find_pagination_and_data_list(initial_query_response)
page_info.clear()
return initial_query_response
return page_list

@staticmethod
async def get_remote_graphql(query: str, **kwargs) -> Dict:
Expand Down
2 changes: 1 addition & 1 deletion sources/translation.json
Original file line number Diff line number Diff line change
Expand Up @@ -168,7 +168,7 @@
"operating system": "操作系统",
"Projects": "项目",
"Timezone": "时区",
"Contributions in the year": "%s 年贡献了 %s ",
"Contributions in the year": "%s 个贡献,在 %s ",
"Used in GitHub's Storage": " 使用了 %s GitHub 存储空间",
"Opted to Hire": "开放招聘",
"Not Opted to Hire": "不开放招聘",
Expand Down
13 changes: 6 additions & 7 deletions sources/yearly_commit_calculator.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,11 +30,10 @@ async def calculate_commit_data(repositories: Dict) -> Tuple[Dict, Dict]:

yearly_data = dict()
date_data = dict()
total = len(repositories["data"]["user"]["repositories"]["nodes"])
for ind, repo in enumerate(repositories["data"]["user"]["repositories"]["nodes"]):
for ind, repo in enumerate(repositories):
if repo["name"] not in EM.IGNORED_REPOS:
repo_name = "[private]" if repo["isPrivate"] else f"{repo['owner']['login']}/{repo['name']}"
DBM.i(f"\t{ind + 1}/{total} Retrieving repo: {repo_name}")
DBM.i(f"\t{ind + 1}/{len(repositories)} Retrieving repo: {repo_name}")
await update_data_with_commit_stats(repo, yearly_data, date_data)
DBM.g("Commit data calculated!")

Expand All @@ -56,13 +55,13 @@ async def update_data_with_commit_stats(repo_details: Dict, yearly_data: Dict, d
"""
owner = repo_details["owner"]["login"]
branch_data = await DM.get_remote_graphql("repo_branch_list", owner=owner, name=repo_details["name"])
if branch_data["data"]["repository"] is None:
DBM.w(f"\t\tSkipping repo: {repo_details['name']}")
if len(branch_data) == 0:
DBM.w("\t\tSkipping repo.")
return

for branch in branch_data["data"]["repository"]["refs"]["nodes"]:
for branch in branch_data:
commit_data = await DM.get_remote_graphql("repo_commit_list", owner=owner, name=repo_details["name"], branch=branch["name"], id=GHM.USER.node_id)
for commit in commit_data["data"]["repository"]["ref"]["target"]["history"]["nodes"]:
for commit in commit_data:
date = search(r"\d+-\d+-\d+", commit["committedDate"]).group()
curr_year = datetime.fromisoformat(date).year
quarter = (datetime.fromisoformat(date).month - 1) // 3 + 1
Expand Down

0 comments on commit 577e21e

Please sign in to comment.