This commit is contained in:
pseusys
2023-02-26 08:01:04 +01:00
parent 030fb4d03f
commit 80967953cf
4 changed files with 32 additions and 48 deletions

View File

@@ -2,7 +2,7 @@ name: REVIEW_PULL_REQUEST
on: on:
pull_request: pull_request:
types: [ opened, edited, reopened, synchronize ] types: [ review_requested ]
paths: paths:
- 'sources/**' - 'sources/**'
- 'requirements.txt' - 'requirements.txt'
@@ -15,6 +15,7 @@ concurrency:
jobs: jobs:
publish-server-image: publish-server-image:
name: Run Test and Review PR name: Run Test and Review PR
if: ${{ github.event.requested_reviewer.login == 'anmol098'}}
runs-on: ubuntu-latest runs-on: ubuntu-latest
steps: steps:
@@ -36,9 +37,7 @@ jobs:
env: env:
INPUT_GH_TOKEN: ${{ secrets.INPUT_GITHUB_TOKEN }} INPUT_GH_TOKEN: ${{ secrets.INPUT_GITHUB_TOKEN }}
INPUT_WAKATIME_API_KEY: ${{ secrets.WAKATIME_API_KEY }} INPUT_WAKATIME_API_KEY: ${{ secrets.WAKATIME_API_KEY }}
CURRENT_GITHUB_ACTION_TOKEN: ${{ secrets.GITHUB_TOKEN }} # This is for testing purpose only not for production INPUT_SHOW_TIMEZONE: True
PR_NUMBER: ${{ github.event.number }} # This is for testing purpose only not for production
INPUT_SHOW_TIMEZONE: true
INPUT_SHOW_PROJECTS: True INPUT_SHOW_PROJECTS: True
INPUT_SHOW_EDITORS: True INPUT_SHOW_EDITORS: True
INPUT_SHOW_OS: True INPUT_SHOW_OS: True
@@ -56,7 +55,5 @@ jobs:
INPUT_COMMIT_BY_ME: True INPUT_COMMIT_BY_ME: True
INPUT_DEBUG_LOGGING: True # This is for testing purpose only not for production INPUT_DEBUG_LOGGING: True # This is for testing purpose only not for production
DEBUG_RUN: True # This is for testing purpose only not for production DEBUG_RUN: True # This is for testing purpose only not for production
PR_NUMBER: ${{ github.event.number }} # This is for testing purpose only not for production
run: python3 sources/main.py run: python3 sources/main.py

View File

@@ -190,12 +190,8 @@ async def main():
if GHM.update_readme(stats): if GHM.update_readme(stats):
DBM.g("Readme updated!") DBM.g("Readme updated!")
else: else:
DBM.i("Commenting PR...") GHM.push_to_pr(stats)
pr_data = await DM.get_remote_graphql("get_pr_id", pr_number=EM.PR_NUMBER, use_github_action=True) DBM.g("Debug run, readme not updated. Check the latest comment for the generated stats.")
pr_id = pr_data["data"]["repository"]["pullRequest"]["id"]
await DM.get_remote_graphql("add_pr_comment", pr_id=pr_id, comment=stats, use_github_action=True)
DBM.g("PR commented!")
DBM.g("Debug run, readme not updated. check the latest comment for the generated stats.")
await DM.close_remote_resources() await DM.close_remote_resources()

View File

@@ -11,7 +11,6 @@ from manager_environment import EnvironmentManager as EM
from manager_github import GitHubManager as GHM from manager_github import GitHubManager as GHM
from manager_debug import DebugManager as DBM from manager_debug import DebugManager as DBM
GITHUB_API_QUERIES = { GITHUB_API_QUERIES = {
# Query to collect info about all user repositories, including: is it a fork, name and owner login. # Query to collect info about all user repositories, including: is it a fork, name and owner login.
# NB! Query includes information about recent repositories only (apparently, contributed within a year). # NB! Query includes information about recent repositories only (apparently, contributed within a year).
@@ -121,26 +120,6 @@ GITHUB_API_QUERIES = {
} }
} }
""", """,
# Query to collect current PR ID
# NOTE: Only to be used for PR review not to be used with actual action
"get_pr_id": """
{
repository(owner: "anmol098", name: "waka-readme-stats") {
pullRequest(number: $pr_number) {
id
}
}
}
""",
"add_pr_comment": """
mutation {
addComment(input: {subjectId: "$pr_id", body: "$comment"}) {
subject {
id
}
}
}
""",
} }
@@ -151,12 +130,10 @@ async def init_download_manager():
- Launch static queries in background. - Launch static queries in background.
""" """
await DownloadManager.load_remote_resources( await DownloadManager.load_remote_resources(
{ linguist="https://cdn.jsdelivr.net/gh/github/linguist@master/lib/linguist/languages.yml",
"linguist": "https://cdn.jsdelivr.net/gh/github/linguist@master/lib/linguist/languages.yml", waka_latest=f"https://wakatime.com/api/v1/users/current/stats/last_7_days?api_key={EM.WAKATIME_API_KEY}",
"waka_latest": f"https://wakatime.com/api/v1/users/current/stats/last_7_days?api_key={EM.WAKATIME_API_KEY}", waka_all=f"https://wakatime.com/api/v1/users/current/all_time_since_today?api_key={EM.WAKATIME_API_KEY}",
"waka_all": f"https://wakatime.com/api/v1/users/current/all_time_since_today?api_key={EM.WAKATIME_API_KEY}", github_stats=f"https://github-contributions.vercel.app/api/v1/{GHM.USER.login}",
"github_stats": f"https://github-contributions.vercel.app/api/v1/{GHM.USER.login}",
}
) )
@@ -176,11 +153,10 @@ class DownloadManager:
_REMOTE_RESOURCES_CACHE = dict() _REMOTE_RESOURCES_CACHE = dict()
@staticmethod @staticmethod
async def load_remote_resources(resources: Dict[str, str]): async def load_remote_resources(**resources: str):
""" """
Prepare DownloadManager to launch GitHub API queries and launch all static queries. Prepare DownloadManager to launch GitHub API queries and launch all static queries.
:param resources: Dictionary of static queries, "IDENTIFIER": "URL". :param resources: Static queries, formatted like "IDENTIFIER"="URL".
:param github_headers: Dictionary of headers for GitHub API queries.
""" """
for resource, url in resources.items(): for resource, url in resources.items():
DownloadManager._REMOTE_RESOURCES_CACHE[resource] = DownloadManager._client.get(url) DownloadManager._REMOTE_RESOURCES_CACHE[resource] = DownloadManager._client.get(url)
@@ -243,14 +219,15 @@ class DownloadManager:
return await DownloadManager._get_remote_resource(resource, safe_load) return await DownloadManager._get_remote_resource(resource, safe_load)
@staticmethod @staticmethod
async def _fetch_graphql_query(query: str, **kwargs) -> Dict: async def _fetch_graphql_query(query: str, use_github_action: bool = False, **kwargs) -> Dict:
""" """
Execute GitHub GraphQL API simple query. Execute GitHub GraphQL API simple query.
:param query: Dynamic query identifier. :param query: Dynamic query identifier.
:param use_github_action: Whether to perform query using CURRENT_GITHUB_ACTION_TOKEN.
:param kwargs: Parameters for substitution of variables in dynamic query. :param kwargs: Parameters for substitution of variables in dynamic query.
:return: Response JSON dictionary. :return: Response JSON dictionary.
""" """
headers = {"Authorization": f"Bearer {EM.GH_TOKEN if not kwargs.get('use_github_action', False) else EM.CURRENT_GITHUB_ACTION_TOKEN}"} headers = {"Authorization": f"Bearer {EM.GH_TOKEN if not use_github_action else EM.CURRENT_GITHUB_ACTION_TOKEN}"}
res = await DownloadManager._client.post( res = await DownloadManager._client.post(
"https://api.github.com/graphql", json={"query": Template(GITHUB_API_QUERIES[query]).substitute(kwargs)}, headers=headers "https://api.github.com/graphql", json={"query": Template(GITHUB_API_QUERIES[query]).substitute(kwargs)}, headers=headers
) )

View File

@@ -17,6 +17,7 @@ def init_github_manager():
class GitHubManager: class GitHubManager:
_GITHUB: Github
USER: AuthenticatedUser USER: AuthenticatedUser
REPO: Repository REPO: Repository
_README: ContentFile _README: ContentFile
@@ -35,9 +36,9 @@ class GitHubManager:
- README.md file of this repo. - README.md file of this repo.
- Parsed contents of the file. - Parsed contents of the file.
""" """
github = Github(EM.GH_TOKEN) GitHubManager._GITHUB = Github(EM.GH_TOKEN)
GitHubManager.USER = github.get_user() GitHubManager.USER = GitHubManager._GITHUB.get_user()
GitHubManager.REPO = github.get_repo(f"{GitHubManager.USER.login}/{GitHubManager.USER.login}") GitHubManager.REPO = GitHubManager._GITHUB.get_repo(f"{GitHubManager.USER.login}/{GitHubManager.USER.login}")
GitHubManager._README = GitHubManager.REPO.get_readme() GitHubManager._README = GitHubManager.REPO.get_readme()
GitHubManager._README_CONTENTS = str(b64decode(GitHubManager._README.content), "utf-8") GitHubManager._README_CONTENTS = str(b64decode(GitHubManager._README.content), "utf-8")
@@ -81,6 +82,7 @@ class GitHubManager:
Updates readme with given data if necessary. Updates readme with given data if necessary.
Uses commit author, commit message and branch name specified by environmental variables. Uses commit author, commit message and branch name specified by environmental variables.
:param stats: Readme stats to be pushed.
:returns: whether the README.md file was updated or not. :returns: whether the README.md file was updated or not.
""" """
DBM.i("Updating README...") DBM.i("Updating README...")
@@ -100,6 +102,18 @@ class GitHubManager:
DBM.w("README update not needed!") DBM.w("README update not needed!")
return False return False
@staticmethod
def push_to_pr(stats: str):
"""
Pushes readme data to current PR body instead of committing it.
:param stats: Readme stats to be pushed.
"""
DBM.i("Commenting PR...")
pull_request = GitHubManager._GITHUB.get_repo("anmol098/waka-readme-stats").get_pull(EM.PR_NUMBER)
pull_request.create_issue_comment(stats)
DBM.g("PR commented!")
@staticmethod @staticmethod
def update_chart(chart_path: str): def update_chart(chart_path: str):
""" """