Compare commits

..

No commits in common. "5ed3669dfec460e47293818e7fb94ac8c85df59d" and "393072a9f87950417e398448c7aba6f6cfcc5793" have entirely different histories.

4 changed files with 56 additions and 96 deletions

View file

@ -6,7 +6,7 @@ import tomllib
from typing import Optional from typing import Optional
from datetime import datetime, timedelta, timezone from datetime import datetime, timedelta, timezone
from time import sleep from time import sleep
from pprint import pprint from pprint import pformat
import click import click
import requests import requests
@ -149,6 +149,8 @@ def parse_seconds(text: str) -> timedelta:
"--config", "--config",
"config_path", "config_path",
type=Path, type=Path,
default=lambda: Path(os.getenv("BUILD_WORKSPACE_DIRECTORY", ""))
/ "projects/gh-unnotifier/config.toml",
) )
@click.option("--schedule", "schedule", default="30 seconds", type=parse_seconds) @click.option("--schedule", "schedule", default="30 seconds", type=parse_seconds)
def maintain(config_path: Path, schedule: timedelta): def maintain(config_path: Path, schedule: timedelta):
@ -158,32 +160,29 @@ def maintain(config_path: Path, schedule: timedelta):
client = Client(config["gh-unnotifier"]["api_key"]) client = Client(config["gh-unnotifier"]["api_key"])
org_shitlist = config["gh-unnotifier"].get("org_shitlist", []) org_shitlist = config["gh-unnotifier"].get("org_shitlist", [])
team_shitlist = config["gh-unnotifier"].get("team_shitlist", []) team_shitlist = config["gh-unnotifier"].get("team_shitlist", [])
author_shitlist = config["gh-unnotifier"].get("author_shitlist", [])
user = client.get_user() user = client.get_user()
user_teams = {it["slug"] for it in client.get_user_teams()} user_teams = {it["slug"] for it in client.get_user_teams()}
mark = savepoint = prev = None mark = None
def _resolve(notif, reason): def _resolve(notif, reason):
client.read(notif) client.read(notif)
client.unsubscribe(notif) client.unsubscribe(notif)
click.echo(f"Resolved {notif['id']} {reason} ({notif['subject']})") click.echo(f"Resolved {notif['id']} {reason} ({notif['subject']})")
def _pr(subject, notif): while True:
try:
prev = mark
mark = datetime.now(timezone.utc)
tick = mark + schedule
assert tick - schedule == mark
for notif in client.get_all_notifications(since=prev):
subject = notif["subject"]
pr = None
if subject["type"] == "PullRequest":
if notif["reason"] == "review_requested":
pr = client.get_pr(url=subject["url"]) pr = client.get_pr(url=subject["url"])
if pr.get("merged", False):
_resolve(notif, "Merged")
return
if pr.get("state") == "closed":
_resolve(notif, "Closed")
return
if pr["user"]["login"] in author_shitlist:
_resolve(notif, "Ignoring PR by author")
return
if notif["reason"] == "review_requested":
reviewers = client.get_pr_reviewers(pr) reviewers = client.get_pr_reviewers(pr)
if ( if (
any(org in subject["url"] for org in org_shitlist) any(org in subject["url"] for org in org_shitlist)
@ -198,12 +197,9 @@ def maintain(config_path: Path, schedule: timedelta):
) )
): ):
_resolve(notif, "Reviewed") _resolve(notif, "Reviewed")
return continue
print("Oustanding PR notification") elif notif["reason"] == "team_mention":
pprint({"subject": subject, "notif": notif, "pr": pr})
def _mention(subject, notif):
pr = client.get_pr(url=subject["url"]) pr = client.get_pr(url=subject["url"])
reviewers = client.get_pr_reviewers(pr) reviewers = client.get_pr_reviewers(pr)
@ -220,11 +216,10 @@ def maintain(config_path: Path, schedule: timedelta):
) )
): ):
_resolve(notif, "Ignoring team mention") _resolve(notif, "Ignoring team mention")
return continue
def _issue(subject, notif): elif subject["type"] == "Issue":
issue = client.get_issue(url=subject["url"]) issue = client.get_issue(url=subject["url"])
if issue["state"] == "closed": if issue["state"] == "closed":
comments = client.get_comments(url=issue["comments_url"]) comments = client.get_comments(url=issue["comments_url"])
if not any( if not any(
@ -232,34 +227,6 @@ def maintain(config_path: Path, schedule: timedelta):
): ):
_resolve(notif, "Unengaged issue closed") _resolve(notif, "Unengaged issue closed")
if issue["user"]["login"] in author_shitlist:
_resolve(notif, "Ignoring issue by author")
while True:
try:
savepoint = prev
prev = mark
mark = datetime.now(timezone.utc)
tick = mark + schedule
assert tick - schedule == mark
for notif in client.get_all_notifications(since=prev):
notif_timestamp = datetime.fromisoformat(notif["updated_at"])
if (mark - notif_timestamp).days > 3:
_resolve(notif, "More than 3 days old")
continue
subject = notif["subject"]
match subject["type"].lower():
case "pullrequest":
_pr(subject, notif)
case "mention":
_mention(subject, notif)
case "issue":
_issue(subject, notif)
duration = (tick - datetime.now(timezone.utc)).total_seconds() duration = (tick - datetime.now(timezone.utc)).total_seconds()
if duration > 0: if duration > 0:
sleep(duration) sleep(duration)
@ -267,11 +234,6 @@ def maintain(config_path: Path, schedule: timedelta):
except KeyboardInterrupt: except KeyboardInterrupt:
break break
except requests.exceptions.HTTPError as e:
print("Encoutered exception", e, "backing off")
prev = savepoint
sleep(schedule.total_seconds())
if __name__ == "__main__": if __name__ == "__main__":
cli() cli()

View file

@ -117,7 +117,7 @@ def poll_printers(app: App, db: Db) -> None:
if mapped_job: if mapped_job:
db.start_job(jid=mapped_job.id) db.start_job(jid=mapped_job.id)
elif printer_job.get("state", "").lower() == "connecting": elif printer_job.get("state").lower() == "connecting":
_set_status("connecting") _set_status("connecting")
elif printer_state.get("ready"): elif printer_state.get("ready"):
@ -172,7 +172,7 @@ def assign_jobs(app: App, db: Db) -> None:
log.info(f"Mapped job {job.id} to printer {printer.id}") log.info(f"Mapped job {job.id} to printer {printer.id}")
break break
else: else:
log.info(f"Could not map job {job!r}") print("Could not map\n", job, "\n", printer)
def push_jobs(app: App, db: Db) -> None: def push_jobs(app: App, db: Db) -> None:
@ -307,8 +307,7 @@ def analyze_files(app: App, db: Db):
for file in db.list_unanalyzed_files(): for file in db.list_unanalyzed_files():
p = Path(file.path) p = Path(file.path)
if not p.is_file(): if not p.is_file():
log.error(f"Deleting missing file {file.id}!") log.error(f"Invalid file {file.id}!")
db.delete_file(uid=file.user_id, fid=file.id)
continue continue
record = analyze_gcode_file(p) record = analyze_gcode_file(p)

View file

@ -54,4 +54,3 @@ unify
yamllint yamllint
yaspin yaspin
pytimeparse pytimeparse
git+https://github.com/arrdem/jaraco.text.git@0dd8d0b25a93c3fad896f3a92d11caff61ff273d#egg=jaraco.text

View file

@ -42,7 +42,7 @@ itsdangerous==2.1.2
jaraco.collections==4.3.0 jaraco.collections==4.3.0
jaraco.context==4.3.0 jaraco.context==4.3.0
jaraco.functools==3.8.0 jaraco.functools==3.8.0
jaraco.text @ git+https://github.com/arrdem/jaraco.text.git@0dd8d0b25a93c3fad896f3a92d11caff61ff273d jaraco.text==3.11.1
jedi==0.18.2 jedi==0.18.2
Jinja2==3.1.2 Jinja2==3.1.2
jsonschema==4.18.4 jsonschema==4.18.4