From b6233625fed92bebe2e7364d5cd0d1be5f5d0215 Mon Sep 17 00:00:00 2001 From: pseusys Date: Sun, 26 Feb 2023 11:47:09 +0100 Subject: [PATCH] saving assets on debug run --- .github/workflows/review_pr.yml | 16 +++++++ sources/graphics_list_formatter.py | 12 ++--- sources/main.py | 44 +++++++++---------- ...anager_localization.py => manager_file.py} | 24 +++++++--- sources/manager_github.py | 6 +-- sources/yearly_commit_calculator.py | 6 +++ 6 files changed, 71 insertions(+), 37 deletions(-) rename sources/{manager_localization.py => manager_file.py} (53%) diff --git a/.github/workflows/review_pr.yml b/.github/workflows/review_pr.yml index 8c13e2f..a24fc7d 100644 --- a/.github/workflows/review_pr.yml +++ b/.github/workflows/review_pr.yml @@ -62,6 +62,22 @@ jobs: DEBUG_RUN: True # This is for testing purpose only not for production run: python3 sources/main.py + - name: Save Branch Name Without Slashes 📛 + if: ${{ github.ref != 'refs/heads/master' }} + env: + BRANCH_NAME: ${{ github.head_ref || github.ref_name }} + run: | + BRANCH_NAME=${{ env.BRANCH_NAME }} + BRANCH_NAME=${BRANCH_NAME////_} + echo BRANCH_NAME=${BRANCH_NAME} >> $GITHUB_ENV + + - name: Upload Artifact 📦 + uses: actions/upload-artifact@v3 + if: ${{ github.ref != 'refs/heads/master' }} + with: + name: ${{ format('github-pages-for-branch-{0}', env.BRANCH_NAME) }} + path: assets + - name: Create Comment 💬 uses: jungwinter/comment@v1 with: diff --git a/sources/graphics_list_formatter.py b/sources/graphics_list_formatter.py index 10f4862..fd06eb5 100644 --- a/sources/graphics_list_formatter.py +++ b/sources/graphics_list_formatter.py @@ -7,7 +7,7 @@ from pytz import timezone, utc from manager_download import DownloadManager as DM from manager_environment import EnvironmentManager as EM from manager_github import GitHubManager as GHM -from manager_localization import LocalizationManager as LM +from manager_file import FileManager as FM DAY_TIME_EMOJI = ["🌞", "🌆", "🌃", "🌙"] # Emojis, representing different times of day. @@ -109,17 +109,17 @@ async def make_commit_day_time_list(time_zone: str) -> str: sum_week = sum(week_days) day_times = day_times[1:] + day_times[:1] - dt_names = [f"{DAY_TIME_EMOJI[i]} {LM.t(DAY_TIME_NAMES[i])}" for i in range(len(day_times))] + dt_names = [f"{DAY_TIME_EMOJI[i]} {FM.t(DAY_TIME_NAMES[i])}" for i in range(len(day_times))] dt_texts = [f"{day_time} commits" for day_time in day_times] dt_percents = [round((day_time / sum_day) * 100, 2) for day_time in day_times] - title = LM.t("I am an Early") if sum(day_times[0:2]) >= sum(day_times[2:4]) else LM.t("I am a Night") + title = FM.t("I am an Early") if sum(day_times[0:2]) >= sum(day_times[2:4]) else FM.t("I am a Night") stats += f"**{title}** \n\n```text\n{make_list(names=dt_names, texts=dt_texts, percents=dt_percents, top_num=7, sort=False)}\n```\n" if EM.SHOW_DAYS_OF_WEEK: - wd_names = [LM.t(week_day) for week_day in WEEK_DAY_NAMES] + wd_names = [FM.t(week_day) for week_day in WEEK_DAY_NAMES] wd_texts = [f"{week_day} commits" for week_day in week_days] wd_percents = [round((week_day / sum_week) * 100, 2) for week_day in week_days] - title = LM.t("I am Most Productive on") % wd_names[wd_percents.index(max(wd_percents))] + title = FM.t("I am Most Productive on") % wd_names[wd_percents.index(max(wd_percents))] stats += f"📅 **{title}** \n\n```text\n{make_list(names=wd_names, texts=wd_texts, percents=wd_percents, top_num=7, sort=False)}\n```\n" return stats @@ -144,5 +144,5 @@ def make_language_per_repo_list(repositories: Dict) -> str: percents = [round(language_count[lang]["count"] / len(repos_with_language) * 100, 2) for lang in names] top_language = max(list(language_count.keys()), key=lambda x: language_count[x]["count"]) - title = f"**{LM.t('I Mostly Code in') % top_language}** \n\n" if len(repos_with_language) > 0 else "" + title = f"**{FM.t('I Mostly Code in') % top_language}** \n\n" if len(repos_with_language) > 0 else "" return f"{title}```text\n{make_list(names=names, texts=texts, percents=percents)}\n```\n\n" diff --git a/sources/main.py b/sources/main.py index d760b46..92386e4 100644 --- a/sources/main.py +++ b/sources/main.py @@ -10,7 +10,7 @@ from humanize import intword, naturalsize, intcomma from manager_download import init_download_manager, DownloadManager as DM from manager_environment import EnvironmentManager as EM from manager_github import init_github_manager, GitHubManager as GHM -from manager_localization import init_localization_manager, LocalizationManager as LM +from manager_file import init_localization_manager, FileManager as FM from manager_debug import init_debug_manager, DebugManager as DBM from graphics_chart_drawer import create_loc_graph, GRAPH_PATH from yearly_commit_calculator import calculate_yearly_commit_data @@ -33,33 +33,33 @@ async def get_waka_time_stats() -> str: stats += f"{await make_commit_day_time_list(data['data']['timezone'])}\n\n" if EM.SHOW_TIMEZONE or EM.SHOW_LANGUAGE or EM.SHOW_EDITORS or EM.SHOW_PROJECTS or EM.SHOW_OS: - no_activity = LM.t("No Activity Tracked This Week") - stats += f"📊 **{LM.t('This Week I Spend My Time On')}** \n\n```text\n" + no_activity = FM.t("No Activity Tracked This Week") + stats += f"📊 **{FM.t('This Week I Spend My Time On')}** \n\n```text\n" if EM.SHOW_TIMEZONE: DBM.i("Adding user timezone info...") time_zone = data["data"]["timezone"] - stats += f"🕑︎ {LM.t('Timezone')}: {time_zone}\n\n" + stats += f"🕑︎ {FM.t('Timezone')}: {time_zone}\n\n" if EM.SHOW_LANGUAGE: DBM.i("Adding user top languages info...") lang_list = no_activity if len(data["data"]["languages"]) == 0 else make_list(data["data"]["languages"]) - stats += f"💬 {LM.t('Languages')}: \n{lang_list}\n\n" + stats += f"💬 {FM.t('Languages')}: \n{lang_list}\n\n" if EM.SHOW_EDITORS: DBM.i("Adding user editors info...") edit_list = no_activity if len(data["data"]["editors"]) == 0 else make_list(data["data"]["editors"]) - stats += f"🔥 {LM.t('Editors')}: \n{edit_list}\n\n" + stats += f"🔥 {FM.t('Editors')}: \n{edit_list}\n\n" if EM.SHOW_PROJECTS: DBM.i("Adding user projects info...") project_list = no_activity if len(data["data"]["projects"]) == 0 else make_list(data["data"]["projects"]) - stats += f"🐱‍💻 {LM.t('Projects')}: \n{project_list}\n\n" + stats += f"🐱‍💻 {FM.t('Projects')}: \n{project_list}\n\n" if EM.SHOW_OS: DBM.i("Adding user operating systems info...") os_list = no_activity if len(data["data"]["operating_systems"]) == 0 else make_list(data["data"]["operating_systems"]) - stats += f"💻 {LM.t('operating system')}: \n{os_list}\n\n" + stats += f"💻 {FM.t('operating system')}: \n{os_list}\n\n" stats = f"{stats[:-1]}```\n\n" @@ -75,20 +75,20 @@ async def get_short_github_info() -> str: :returns: String representation of the info. """ DBM.i("Adding short GitHub info...") - stats = f"**🐱 {LM.t('My GitHub Data')}** \n\n" + stats = f"**🐱 {FM.t('My GitHub Data')}** \n\n" DBM.i("Adding user disk usage info...") if GHM.USER.disk_usage is None: - disk_usage = LM.t("Used in GitHub's Storage") % "?" + disk_usage = FM.t("Used in GitHub's Storage") % "?" DBM.p("Please add new github personal access token with user permission!") else: - disk_usage = LM.t("Used in GitHub's Storage") % naturalsize(GHM.USER.disk_usage) + disk_usage = FM.t("Used in GitHub's Storage") % naturalsize(GHM.USER.disk_usage) stats += f"> 📦 {disk_usage} \n > \n" data = await DM.get_remote_json("github_stats") DBM.i("Adding contributions info...") if len(data["years"]) > 0: - contributions = LM.t("Contributions in the year") % (intcomma(data["years"][0]["total"]), data["years"][0]["year"]) + contributions = FM.t("Contributions in the year") % (intcomma(data["years"][0]["total"]), data["years"][0]["year"]) stats += f"> 🏆 {contributions}\n > \n" else: DBM.p("GitHub contributions data unavailable!") @@ -96,23 +96,23 @@ async def get_short_github_info() -> str: DBM.i("Adding opted for hire info...") opted_to_hire = GHM.USER.hireable if opted_to_hire: - stats += f"> 💼 {LM.t('Opted to Hire')}\n > \n" + stats += f"> 💼 {FM.t('Opted to Hire')}\n > \n" else: - stats += f"> 🚫 {LM.t('Not Opted to Hire')}\n > \n" + stats += f"> 🚫 {FM.t('Not Opted to Hire')}\n > \n" DBM.i("Adding public repositories info...") public_repo = GHM.USER.public_repos if public_repo != 1: - stats += f"> 📜 {LM.t('public repositories') % public_repo} \n > \n" + stats += f"> 📜 {FM.t('public repositories') % public_repo} \n > \n" else: - stats += f"> 📜 {LM.t('public repository') % public_repo} \n > \n" + stats += f"> 📜 {FM.t('public repository') % public_repo} \n > \n" DBM.i("Adding private repositories info...") private_repo = GHM.USER.owned_private_repos if GHM.USER.owned_private_repos is not None else 0 if public_repo != 1: - stats += f"> 🔑 {LM.t('private repositories') % private_repo} \n > \n" + stats += f"> 🔑 {FM.t('private repositories') % private_repo} \n > \n" else: - stats += f"> 🔑 {LM.t('private repository') % private_repo} \n > \n" + stats += f"> 🔑 {FM.t('private repository') % private_repo} \n > \n" DBM.g("Short GitHub info added!") return stats @@ -144,13 +144,13 @@ async def get_stats() -> str: if EM.SHOW_PROFILE_VIEWS: DBM.i("Adding profile views info...") data = GHM.REPO.get_views_traffic(per="week") - stats += f"![Profile Views](http://img.shields.io/badge/{quote(LM.t('Profile Views'))}-{data['count']}-blue)\n\n" + stats += f"![Profile Views](http://img.shields.io/badge/{quote(FM.t('Profile Views'))}-{data['count']}-blue)\n\n" if EM.SHOW_LINES_OF_CODE: DBM.i("Adding lines of code info...") total_loc = sum([yearly_data[y][q][d] for y in yearly_data.keys() for q in yearly_data[y].keys() for d in yearly_data[y][q].keys()]) - data = f"{intword(total_loc)} {LM.t('Lines of code')}" - stats += f"![Lines of code](https://img.shields.io/badge/{quote(LM.t('From Hello World I have written'))}-{quote(data)}-blue)\n\n" + data = f"{intword(total_loc)} {FM.t('Lines of code')}" + stats += f"![Lines of code](https://img.shields.io/badge/{quote(FM.t('From Hello World I have written'))}-{quote(data)}-blue)\n\n" if EM.SHOW_SHORT_INFO: stats += await get_short_github_info() @@ -165,7 +165,7 @@ async def get_stats() -> str: await create_loc_graph(yearly_data, GRAPH_PATH) GHM.update_chart(GRAPH_PATH) chart_path = f"{GHM.USER.login}/{GHM.USER.login}/{GHM.branch()}/{GRAPH_PATH}" - stats += f"**{LM.t('Timeline')}**\n\n![Lines of Code chart](https://raw.githubusercontent.com/{chart_path})\n\n" + stats += f"**{FM.t('Timeline')}**\n\n![Lines of Code chart](https://raw.githubusercontent.com/{chart_path})\n\n" if EM.SHOW_UPDATED_DATE: DBM.i("Adding last updated time...") diff --git a/sources/manager_localization.py b/sources/manager_file.py similarity index 53% rename from sources/manager_localization.py rename to sources/manager_file.py index 497ec2e..b6fb39d 100644 --- a/sources/manager_localization.py +++ b/sources/manager_file.py @@ -10,10 +10,10 @@ def init_localization_manager(): Initialize localization manager. Load GUI translations JSON file. """ - LocalizationManager.load_localization("translation.json") + FileManager.load_localization("translation.json") -class LocalizationManager: +class FileManager: """ Class for handling localization (and maybe other file IO in future). Stores localization in dictionary. @@ -28,9 +28,9 @@ class LocalizationManager: :param file: Localization file path, related to current file (in sources root). """ - with open(join(dirname(__file__), file), encoding="utf-8") as config_file: + with open(join("sources", file), encoding="utf-8") as config_file: data = load(config_file) - LocalizationManager._LOCALIZATION = data[EM.LOCALE] + FileManager._LOCALIZATION = data[EM.LOCALE] @staticmethod def t(key: str) -> str: @@ -40,4 +40,18 @@ class LocalizationManager: :param key: Localization key. :returns: Translation string. """ - return LocalizationManager._LOCALIZATION[key] + return FileManager._LOCALIZATION[key] + + @staticmethod + def write_file(name: str, content: str, append: bool = False, assets: bool = False): + """ + Save output file. + + :param name: File name. + :param content: File content (utf-8 string). + :param append: True for appending to file, false for rewriting. + :param assets: True for saving to 'assets' directory, false otherwise. + """ + name = join(name, "assets") if assets else name + with open(name, "a" if append else "w", encoding="utf-8") as file: + file.write(content) diff --git a/sources/manager_github.py b/sources/manager_github.py index 89cec06..0f1660e 100644 --- a/sources/manager_github.py +++ b/sources/manager_github.py @@ -7,6 +7,7 @@ from string import ascii_letters from github import Github, AuthenticatedUser, Repository, ContentFile, InputGitAuthor, UnknownObjectException from manager_environment import EnvironmentManager as EM +from manager_file import FileManager as FM from manager_debug import DebugManager as DBM @@ -117,10 +118,7 @@ class GitHubManager: prefix = "README stats current output:" eol = "".join(choice(ascii_letters) for _ in range(10)) - with open(environ["GITHUB_OUTPUT"], "a") as fh: - fh.write(f"README_CONTENT<<{eol}\n") - fh.write(f"{prefix}\n\n{stats}\n") - fh.write(f"{eol}\n") + FM.write_file(environ["GITHUB_OUTPUT"], f"README_CONTENT<<{eol}\n{prefix}\n\n{stats}\n{eol}\n", append=True) DBM.g("Action output set!") diff --git a/sources/yearly_commit_calculator.py b/sources/yearly_commit_calculator.py index 49bce72..cc52f40 100644 --- a/sources/yearly_commit_calculator.py +++ b/sources/yearly_commit_calculator.py @@ -1,3 +1,4 @@ +from json import dumps from re import search from datetime import datetime from typing import Dict @@ -5,6 +6,7 @@ from typing import Dict from manager_download import DownloadManager as DM from manager_environment import EnvironmentManager as EM from manager_github import GitHubManager as GHM +from manager_file import FileManager as FM from manager_debug import DebugManager as DBM @@ -19,12 +21,16 @@ async def calculate_yearly_commit_data(repositories: Dict) -> Dict: DBM.i("Calculating yearly commit data...") yearly_data = dict() total = len(repositories["data"]["user"]["repositories"]["nodes"]) + for ind, repo in enumerate(repositories["data"]["user"]["repositories"]["nodes"]): 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}") await update_yearly_data_with_commit_stats(repo, yearly_data) DBM.g("Yearly commit data calculated!") + + if EM.DEBUG_RUN: + FM.write_file("yearly_data.json", dumps(yearly_data), assets=True) return yearly_data