Skip to content

Commit

Permalink
Fix datetime formatting
Browse files Browse the repository at this point in the history
  • Loading branch information
Eclipse-Dominator committed Jun 1, 2023
1 parent 3b02e5f commit eefc642
Show file tree
Hide file tree
Showing 6 changed files with 52 additions and 12 deletions.
5 changes: 5 additions & 0 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@ inputs:
description: 'directory to save the digest setting file, defaults to .github/digests'
required: false
default: ".github/digests"
timezone:
description: 'Timezone to use for the digest, defaults to UTC'
required: false
default: "UTC"

branding:
icon: 'align-justify'
Expand All @@ -40,6 +44,7 @@ runs:
GIT_SECRET: ${{ inputs.secret }}
GIT_REPO: ${{ inputs.repo || env.GITHUB_REPOSITORY }}
DIGEST_SAVE_DIR: ${{ inputs.save }}
TIMEZONE: ${{ inputs.timezone }}
run: |
python ${{ github.action_path }}/app.py
shell: bash
Expand Down
12 changes: 6 additions & 6 deletions digest_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__(self, target_repo:str, local_repo:str, target_issue:str, ignore_num
self.target_issue = target_issue
self.complete = False
self.ignore_numbers = ignore_numbers
self.last_update_time = datetime.now() - timedelta(days=1)
self.last_update_time = helper.get_now() - timedelta(days=1)
self.create_issue()
self.update_last_change_date()

Expand All @@ -45,7 +45,7 @@ def run_query(self, additional_queries: list[str] = []) -> dict:
additional_queries.append(
self.query.partial_query(
self.target_repo,
self.last_update_time.strftime("%Y-%m-%dT%H:%M:%SZ"),
helper.format_to_utc(self.last_update_time),
self.cursor)
)
res = run_queries(additional_queries)
Expand All @@ -66,22 +66,22 @@ def get_result(self) -> list[GitIssue]:
ret[key].read_paginated_comments(ret[key].comments_query.read_result(res))

return [ret[key] for key in ret]

def update_cursor(self, graphqlResult: dict):
self.cursor = graphqlResult["endCursor"]
self.complete = not graphqlResult["hasNextPage"]

def convert_data(self, graphqlResult: dict, ret: dict[str, GitIssue]):
for raw_issue in graphqlResult:
if (raw_issue and raw_issue["number"] not in self.ignore_numbers):
issue = GitIssue(raw_issue, (self.last_update_time, datetime.now()))
issue = GitIssue(raw_issue, (self.last_update_time, helper.get_now()))
ret[issue.id] = issue

def send_data(self, issues: list[GitIssue]):
r1 = UpdateIssue("update_issue").partial_query(self.target_issue, digest_content)
r2 = AddComment("new_digest").partial_query(self.target_issue, digest_header.format(
time_start=self.last_update_time.strftime("%Y-%m-%d %H:%M:%S"),
time_end=datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ"),
time_start=helper.format_local(self.last_update_time),
time_end=helper.format_local(helper.get_now()),
all_changes=sum([issue.total_changes for issue in issues]),
issues_changed=len(issues),
body='\n'.join([issue.to_markdown() for issue in issues])
Expand Down
4 changes: 2 additions & 2 deletions git_structures.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def to_markdown(self):
return comment_template.format(
author=self.last_change_author,
link=self.source_link,
date=helper.format_date(self.last_change_date),
date=helper.format_local(self.last_change_date),
body=helper.trim_and_format(self.body),
status=self.get_status_str(self.time_range)
)
Expand Down Expand Up @@ -111,7 +111,7 @@ def to_markdown(self) -> str:
temp = issue_template
header += temp.format(
author=self.last_change_author,
date=helper.format_date(self.last_change_date),
date=helper.format_local(self.last_change_date),
status=self.get_status_str(self.time_range),
body=helper.trim_and_format(self.body)
)
Expand Down
23 changes: 22 additions & 1 deletion gql_queries.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from os import environ
from datetime import datetime
import sys
import helper
import requests
from string import Template
Expand All @@ -8,18 +9,36 @@
try:
API_KEY = environ["GIT_SECRET"]
except KeyError:
API_KEY = "Token not available!"
print("Token not available!", file=sys.stderr)
exit(1)

url = "https://api.github.com/graphql"
headers = {
"Authorization": f"token {API_KEY}",
}

def handle_errors(response: requests.Response) -> None:
"""
If query fails, print the error message and exit the program
"""
if response.status_code != 200:
print("Query failed to run by returning code of {}. {}".format(response.status_code, response.text), file=sys.stderr)
exit(1)

data = response.json()

if 'errors' in data:
errors = data["errors"]
for error in errors:
print("Error: {}".format(error["message"]), file=sys.stderr)
exit(1)

def run_queries(queries: list[str]) -> dict:
payload = {
"query": f"{{{','.join([q for q in queries])}}}"
}
response = requests.post(url, json=payload, headers=headers)
handle_errors(response)
return response.json()["data"]

def run_mutations(queries: list[str]) -> dict:
Expand All @@ -28,6 +47,7 @@ def run_mutations(queries: list[str]) -> dict:
}

response = requests.post(url, json=payload, headers=headers)
handle_errors(response)
return response.json()["data"]

class GithubQuery:
Expand All @@ -46,6 +66,7 @@ def run(self, **kwargs) -> dict:
}

response = requests.post(url, json=payload, headers=headers)
handle_errors(response)
return response.json()["data"]

def partial_query(self, **kwargs) -> str:
Expand Down
19 changes: 16 additions & 3 deletions helper.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
from datetime import datetime, timedelta
import pytz
from os import environ

convertToDateTime = lambda x: datetime.strptime(x, "%Y-%m-%dT%H:%M:%SZ")
utc = pytz.utc
localtz = pytz.timezone(environ["TIMEZONE"])

format_date = lambda x: x.strftime("%Y-%m-%d %H:%M:%S")
get_now = lambda :datetime.now(utc)

def convertToDateTime(x: str) -> datetime:
dt = datetime.strptime(x, "%Y-%m-%dT%H:%M:%SZ")
return dt.replace(tzinfo=utc)

def format_local(dt: datetime) -> str:
return dt.astimezone(localtz).strftime("%Y-%m-%d %H:%M:%S")

def format_to_utc(dt: datetime) -> str:
return dt.astimezone(utc).strftime("%Y-%m-%dT%H:%M:%SZ")

def trim_and_format(x: str) -> str:
if len(x) > 200:
x = x[:200] + "..."
return ">" + x.strip().replace("\n", "\n> ")

def get_n_day_prior(n: int) -> datetime:
return datetime.now() - timedelta(days=n)
return datetime.now(utc) - timedelta(days=n)
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,3 +4,4 @@ charset-normalizer==3.1.0
idna==3.4
requests==2.28.2
urllib3==1.26.15
pytz==2023.3

0 comments on commit eefc642

Please sign in to comment.