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

View File

@@ -190,12 +190,8 @@ async def main():
if GHM.update_readme(stats):
DBM.g("Readme updated!")
else:
DBM.i("Commenting PR...")
pr_data = await DM.get_remote_graphql("get_pr_id", pr_number=EM.PR_NUMBER, use_github_action=True)
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.")
GHM.push_to_pr(stats)
DBM.g("Debug run, readme not updated. Check the latest comment for the generated stats.")
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_debug import DebugManager as DBM
GITHUB_API_QUERIES = {
# 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).
@@ -119,26 +118,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.
"""
await DownloadManager.load_remote_resources(
{
"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_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}",
}
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_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}",
)
@@ -176,11 +153,10 @@ class DownloadManager:
_REMOTE_RESOURCES_CACHE = dict()
@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.
:param resources: Dictionary of static queries, "IDENTIFIER": "URL".
:param github_headers: Dictionary of headers for GitHub API queries.
:param resources: Static queries, formatted like "IDENTIFIER"="URL".
"""
for resource, url in resources.items():
DownloadManager._REMOTE_RESOURCES_CACHE[resource] = DownloadManager._client.get(url)
@@ -243,14 +219,15 @@ class DownloadManager:
return await DownloadManager._get_remote_resource(resource, safe_load)
@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.
: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.
: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(
"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:
_GITHUB: Github
USER: AuthenticatedUser
REPO: Repository
_README: ContentFile
@@ -35,9 +36,9 @@ class GitHubManager:
- README.md file of this repo.
- Parsed contents of the file.
"""
github = Github(EM.GH_TOKEN)
GitHubManager.USER = github.get_user()
GitHubManager.REPO = github.get_repo(f"{GitHubManager.USER.login}/{GitHubManager.USER.login}")
GitHubManager._GITHUB = Github(EM.GH_TOKEN)
GitHubManager.USER = GitHubManager._GITHUB.get_user()
GitHubManager.REPO = GitHubManager._GITHUB.get_repo(f"{GitHubManager.USER.login}/{GitHubManager.USER.login}")
GitHubManager._README = GitHubManager.REPO.get_readme()
GitHubManager._README_CONTENTS = str(b64decode(GitHubManager._README.content), "utf-8")
@@ -81,6 +82,7 @@ class GitHubManager:
Updates readme with given data if necessary.
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.
"""
DBM.i("Updating README...")
@@ -100,6 +102,18 @@ class GitHubManager:
DBM.w("README update not needed!")
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
def update_chart(chart_path: str):
"""