aboutsummaryrefslogtreecommitdiffstats
path: root/trigger_webhook.py
blob: bd5703d5af56296215a78d23ee9096743115b0e0 (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
# Copyright (C) 2024 The Qt Company Ltd.
# SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
""" This script listens for incoming webhook requests of change-merged type
    from Gerrit.
"""
import json
import asyncio
from aiohttp import web

HTTP_CALLBACK = None


async def _handle(request):
    """ Handle the incoming webhook request. """
    body = await request.text()
    data = json.loads(body)

    # make sure it's a change-merged event
    if data['type'] != 'change-merged':
        return web.Response(status=200)

    try:
        print(f'{data["change"]["number"]},{data["change"]["project"]}({data["change"]["branch"]}):'
              f'Received webhook for revision: {data["patchSet"]["revision"]}')
        # pylint: disable=W0602
        global HTTP_CALLBACK
        HTTP_CALLBACK(data['change']['project'], data['change']['branch'], data["patchSet"]["revision"])
    # pylint: disable=W0718
    except Exception as e:
        print("Error: %s", str(e))
        return web.Response(status=200)

    return web.Response(status=200)

async def _status(request):
    """ Return the status of the web server. """
    return web.Response(text="OK")

async def run_web_server(callback, port):
    """ Run the web server. """
    # pylint: disable=W0603
    global HTTP_CALLBACK
    HTTP_CALLBACK = callback
    app = web.Application()
    app.add_routes([web.get('/status', _status)])
    app.add_routes([web.post('/', _handle)])
    runner = web.AppRunner(app)
    await runner.setup()
    site = web.TCPSite(runner, '0.0.0.0', port)
    await site.start()
    print(f"Web server started on port {port}")
    while True:
        await asyncio.sleep(3600)