Using webhooks with sourcehut.

My whole website is tracked in a git repository that I host privately on sourcehut. A clone of this repository exists on my web host from which this site is served. To synchronize both repositorries I use webhooks.

A webhook is basically a callback URL. My web host offers a webhook URL which I need to register with sourcehut with post-update events. Whenever I push to my sourcehut repository, sourcehut then sends a POST request to my web host’s webhook URL which in turn will pull from the sourcehut repository. With netcup.de you can find the webhook URL via the managmeent console under the respective domain’s settings, git, git settings.

Setting up a webhook on sourcehut

Webhooks can be configured via sourcehut’s api. First, we need to be able to authenticate against sourcehut. Here, I simply create a personal access token via sourcehut’s settings: settings -> oauth -> generate new token - see the docs for details. Never give this token to anyone else - for programmatic access you should use OAuth clients.

With the access token we can already check if access is working (this example uses httpie):

http https://git.sr.ht/api/user Authorization:'token <personal-access-token>'

Which should return something like the following:

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 126
Content-Type: application/json
Date: Sun, 05 Jul 2020 19:33:38 GMT
Server: nginx

{
    "bio": null,
    "canonical_name": "~myusername",
    "email": "myusername@whatever.nz",
    "location": null,
    "name": "myusername",
    "url": null
}

Time to create the post-update webhook on our repository myreponame - make sure to prepend the tilde character to your user name:

http POST https://git.sr.ht/api/~myusername/repos/myreponame/webhooks \
    Authorization:'token <personal-access-token>' \
    url=<webhook-url-from-whoever-will-receive-the-events> \
    events:='["repo:post-update"]'

By sending a GET request to the same url we can list all configured webhooks:

http https://git.sr.ht/api/~myusername/repos/myreponame/webhooks \
    Authorization:'token <personal-access-token>'

Which will return something like:

HTTP/1.1 200 OK
Connection: keep-alive
Content-Length: 263
Content-Type: application/json
Date: Sun, 05 Jul 2020 19:37:18 GMT
Server: nginx

{
    "next": null,
    "results": [
        {
            "created": "2020-07-05T19:16:11+00:00",
            "events": [
                "repo:post-update"
            ],
            "id": 2615,
            "url": "https://the-webhook-url-from-whoever-wants-to-be-notified.com"
        }
    ],
    "results_per_page": 50,
    "total": 1
}

To delete a webhook, first list the available webhooks with the previous request and note the respective id. Then call:

http DELETE https://git.sr.ht/api/~myusername/repos/myreponame/webhooks/webhook-id-integer \
    Authorization:'token <personal-access-token>'

For more details regarding sourcehut’s API see its git api docs.