summaryrefslogtreecommitdiff
path: root/accounts/gkleen@sif/utils/nixpkgs-pr-watch/nixpkgs_pr_watch/__main__.py
blob: 09bb865111ee83d5af352c26f0a6cf389bc2e74c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
import argparse
import re
import requests
from urllib.parse import urljoin
from xdg_base_dirs import xdg_config_home, xdg_config_dirs
import toml
import sys

from github import Github

class ApiKeyAuth(requests.auth.AuthBase):
    def __init__(self, token):
        self.token = token
    def __call__(self, r):
        r.headers["x-api-key"] = self.token
        return r

class ChangeDetectionSession(requests.Session):
    def __init__(self, base_url: str, api_token: str):
        super().__init__()
        self.base_url = base_url
        self.auth = ApiKeyAuth(api_token)

    def request(self, method, url, *args, **kwargs):
        joined_url = urljoin(urljoin(self.base_url, '/api/v1/'), url)
        return super().request(method, joined_url, *args, **kwargs)

def main():
    def pr_number(s):
        if m := re.fullmatch(r'(?:https?://github\.com/NixOS/nixpkgs/pull/)?(?P<pr>[0-9]+)(?:[^0-9].*)?', s, flags=re.I):
            return int(m.group('pr'))
        else:
            raise ValueError

    parser = argparse.ArgumentParser(prog = "nixpkgs-pr-watch")
    parser.add_argument('prs', metavar = 'PR', type = pr_number, nargs = '+')

    args = parser.parse_args()

    config = None
    for d in [xdg_config_home(), *xdg_config_dirs()]:
        try:
            config = toml.load(d / 'nixpkgs-pr-watch.toml')
            break
        except FileNotFoundError:
            pass

    for pr in args.prs:
        pr_title = None
        with Github() as g:
            pr_title = g.get_repo('NixOS/nixpkgs').get_pull(pr).title

        api = ChangeDetectionSession(
            base_url = config.get("BaseUrl"),
            api_token = config.get("ApiToken"),
        )
        try:
            api.post(
                "watch",
                headers = {
                    'Content-Type': 'application/json',
                },
                json = {
                    "url": urljoin("https://nixpkgs.molybdenum.software/api/v2/landings/", str(pr)),
                    **({ "title": pr_title } if pr_title else {}),
                    "time_between_check_use_default": False,
                    "time_between_check": { "hours": 1 },
                    "fetch_backend": "html_requests",
                },
            ).raise_for_status()
        except requests.HTTPError as e:
            print(e.response.text, file=sys.stderr)
            raise e