Build and publish eventLabs WordPress updates from Gitea
All checks were successful
WordPress release / release (push) Successful in 5s

This commit is contained in:
josh
2026-11-11 22:00:42 -05:00
parent 986f11aeb2
commit 91a81e761b
8 changed files with 425 additions and 5 deletions

View File

@@ -0,0 +1,27 @@
name: WordPress release
on:
push:
tags:
- 'v*'
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- name: Check out the tagged source
env:
TAG: ${{ gitea.ref_name }}
COMMIT: ${{ gitea.sha }}
run: |
git clone --depth 1 --branch "$TAG" https://git.labs.casa/josh/eventLabs.git source
test "$(git -C source rev-parse HEAD)" = "$(git -C source rev-parse "$COMMIT^{commit}")"
- name: Build and publish the WordPress ZIP
working-directory: source
env:
TAG: ${{ gitea.ref_name }}
EVENTLABS_RELEASE_TOKEN: ${{ secrets.GITEA_TOKEN }}
run: python3 scripts/release.py "$TAG" --publish

2
.gitignore vendored Normal file
View File

@@ -0,0 +1,2 @@
/dist/
__pycache__/

View File

@@ -4,15 +4,19 @@
Publish an events calendar, design single-event pages in Elementor, and sync club events from burnWorks. eventLabs manages schedules, venues, organizers, and series in WordPress and provides its own versioned REST API. Publish an events calendar, design single-event pages in Elementor, and sync club events from burnWorks. eventLabs manages schedules, venues, organizers, and series in WordPress and provides its own versioned REST API.
[Download the latest release](https://git.labs.casa/josh/eventLabs/releases/latest) · [API reference](docs/API.md) · [Release guide](docs/RELEASING.md)
![Month calendar with a multi-day event, category colors, and an event preview](docs/images/calendar.webp) ![Month calendar with a multi-day event, category colors, and an event preview](docs/images/calendar.webp)
## Get started ## Get started
1. Install this directory in `wp-content/plugins/burn-events/` and activate **eventLabs** under **Plugins**. Requires WordPress 6.9+ and PHP 8.1+. The Elementor builder and widgets use Elementor Free. 1. Download `eventlabs-vX.Y.Z.zip` from the [latest release](https://git.labs.casa/josh/eventLabs/releases/latest). Upload it through **Plugins → Add Plugin → Upload Plugin**, then activate **eventLabs**. Requires WordPress 6.9+ and PHP 8.1+. The Elementor builder and widgets use Elementor Free.
2. Open **Events → Add Event**. Set the schedule, link a venue, and publish. Use **Events → Settings → View calendar** to open the public calendar. 2. Open **Events → Add Event**. Set the schedule, link a venue, and publish. Use **Events → Settings → View calendar** to open the public calendar.
3. Use **Events → Single Event Templates → Create starter template** to design a single-event layout. Publish it, then assign it to an event or choose **Use as default**. 3. Use **Events → Single Event Templates → Create starter template** to design a single-event layout. Publish it, then assign it to an event or choose **Use as default**.
4. Add **Event Calendar** or **Event List** from the **eventLabs** widget category in Elementor. You can also embed a calendar with `[burn_events view="month"]`. 4. Add **Event Calendar** or **Event List** from the **eventLabs** widget category in Elementor. You can also embed a calendar with `[burn_events view="month"]`.
Starting with **0.5.2**, the active plugin checks Gitea for stable releases and shows updates in WordPress. If you installed **0.5.1** or earlier, upload the latest release ZIP once and choose **Replace current with uploaded** to get the updater. An install mounted from the development checkout should be updated through Git.
## Calendar and publishing ## Calendar and publishing
- **Calendar views** include List, Month, Week, Day, Photo, Map, and Summary. In Month and Week, multi-day bars span their dates and show event previews on hover and keyboard focus. Set a custom color under **Events → Event Categories**. - **Calendar views** include List, Month, Week, Day, Photo, Map, and Summary. In Month and Week, multi-day bars span their dates and show event previews on hover and keyboard focus. Set a custom color under **Events → Event Categories**.

View File

@@ -1,13 +1,14 @@
<?php <?php
/** /**
* Plugin Name: eventLabs * Plugin Name: eventLabs
* Plugin URI: https://git.labs.casa/josh/eventLabs
* Description: Calendars, recurring events, community submissions, and a Single Event template builder for Elementor. * Description: Calendars, recurring events, community submissions, and a Single Event template builder for Elementor.
* Version: 0.5.1 * Version: 0.5.2
* Requires at least: 6.9 * Requires at least: 6.9
* Requires PHP: 8.1 * Requires PHP: 8.1
* Author: hostLabs * Author: hostLabs
* Text Domain: burn-events * Text Domain: burn-events
* Update URI: false * Update URI: https://git.labs.casa/josh/eventLabs
*/ */
declare(strict_types=1); declare(strict_types=1);
@@ -15,9 +16,9 @@ declare(strict_types=1);
defined( 'ABSPATH' ) || exit; defined( 'ABSPATH' ) || exit;
define( 'BURN_EVENTS_FILE', __FILE__ ); define( 'BURN_EVENTS_FILE', __FILE__ );
define( 'BURN_EVENTS_VERSION', '0.5.1' ); define( 'BURN_EVENTS_VERSION', '0.5.2' );
foreach ( [ 'schedule', 'maps', 'events', 'admin', 'map-view', 'calendar-grid', 'calendar', 'community', 'transfer', 'single-event-templates', 'api', 'burnworks', 'clubs', 'legacy-migration', 'platform' ] as $module ) { foreach ( [ 'schedule', 'maps', 'events', 'admin', 'map-view', 'calendar-grid', 'calendar', 'community', 'transfer', 'single-event-templates', 'api', 'burnworks', 'clubs', 'legacy-migration', 'updates', 'platform' ] as $module ) {
require_once __DIR__ . '/includes/class-' . $module . '.php'; require_once __DIR__ . '/includes/class-' . $module . '.php';
} }

31
docs/RELEASING.md Normal file
View File

@@ -0,0 +1,31 @@
# Build and release eventLabs
Build from the plugin repository root with Git and Python 3.9 or newer:
```sh
python3 scripts/release.py
```
The script packages the committed files at `HEAD`. Pass a Git ref, such as `v0.5.2`, to build that revision instead. `dist/` contains `eventlabs-vX.Y.Z.zip` and `eventlabs-update.json`. The ZIP contains `burn-events/burn-events.php` and its runtime files so WordPress installs or replaces the existing plugin directory. The manifest records the version, WordPress and PHP requirements, source commit, ZIP size, and SHA-256.
To publish, update the `Version` header and `BURN_EVENTS_VERSION` together in `burn-events.php`, commit the release, and push a matching tag:
```sh
git push origin main
git tag vX.Y.Z
git push origin vX.Y.Z
```
The [Gitea release workflow](../.gitea/workflows/release.yml) runs on an `ubuntu-latest` runner with Git and Python 3. It builds the tagged commit, uploads both assets to a draft, then publishes and verifies the public downloads. The job uses Gitea's built-in token with release write access. Check the **Actions** tab for the result.
If a runner is unavailable, run the same release command after pushing the tag:
```sh
python3 scripts/release.py vX.Y.Z --publish
```
The command uses `EVENTLABS_RELEASE_TOKEN` if set, or your configured Git credentials for `git.labs.casa`. Keep credentials out of the repository and release files. If an upload stops partway through, rerun the command for the same tag to finish the draft. Publish changes to a new version rather than replacing an existing release ZIP.
The installed plugin uses WordPress's [external update hook](https://developer.wordpress.org/reference/hooks/update_plugins_hostname/) and Gitea's [latest stable release API](https://docs.gitea.com/api/operations/repo-get-latest-release/). WordPress downloads the attached ZIP over HTTPS and eventLabs verifies its size and checksum. Sites can use **Dashboard → Updates → Check again** to refresh the update list. WordPress's normal auto-update setting controls whether updates install automatically.
Keep the release downloads public for sites to receive updates without a Gitea account. Installations older than **0.5.2** need the first ZIP uploaded manually. Use a normal plugin installation to test the WordPress upgrade; the Docker development site's bind mount is updated through the Git checkout.

View File

@@ -31,6 +31,7 @@ final class Platform {
add_filter( 'plugin_action_links_' . plugin_basename( BURN_EVENTS_FILE ), [ self::class, 'links' ] ); add_filter( 'plugin_action_links_' . plugin_basename( BURN_EVENTS_FILE ), [ self::class, 'links' ] );
Admin::register(); Admin::register();
Single_Event_Templates::register(); Single_Event_Templates::register();
Updates::register();
} }
public static function activate(): void { public static function activate(): void {

156
includes/class-updates.php Normal file
View File

@@ -0,0 +1,156 @@
<?php
namespace BurnEvents;
defined( 'ABSPATH' ) || exit;
final class Updates {
private const REPO = 'https://git.labs.casa/josh/eventLabs';
private const LATEST = 'https://git.labs.casa/api/v1/repos/josh/eventLabs/releases/latest';
private const MANIFEST = 'eventlabs-update.json';
private const SLUG = 'burn-events';
private const VERSION = '(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)';
private const MAX_ZIP_BYTES = 32 * 1024 * 1024;
public static function register(): void {
add_filter( 'update_plugins_git.labs.casa', [ self::class, 'update' ], 10, 3 );
add_filter( 'plugins_api', [ self::class, 'details' ], 10, 3 );
add_filter( 'upgrader_pre_download', [ self::class, 'download' ], 10, 2 );
}
public static function update( $update, array $headers, string $plugin_file ) {
if ( false !== $update || plugin_basename( BURN_EVENTS_FILE ) !== $plugin_file || self::REPO !== ( $headers['UpdateURI'] ?? '' ) ) {
return $update;
}
return self::latest() ?? $update;
}
public static function details( $result, string $action, object $args ) {
if ( false !== $result || 'plugin_information' !== $action || self::SLUG !== ( $args->slug ?? '' ) ) {
return $result;
}
$release = self::latest();
if ( ! $release ) {
return $result;
}
return (object) [
'name' => 'eventLabs',
'slug' => self::SLUG,
'author' => 'hostLabs',
'version' => $release['version'],
'requires' => $release['requires'],
'requires_php' => $release['requires_php'],
'homepage' => self::REPO,
'download_link' => $release['package'],
'sections' => [
'description' => '<p>' . esc_html__( 'Calendars, recurring events, and a Single Event template builder for Elementor.', 'burn-events' ) . '</p>',
'changelog' => '<p><a href="' . esc_url( $release['url'] ) . '">' . esc_html__( 'Read the eventLabs release notes', 'burn-events' ) . '</a></p>',
],
];
}
private static function latest(): ?array {
// WordPress caches the update response. Reuse it within the request without delaying “Check again.”
static $loaded = false;
static $update = null;
if ( $loaded ) {
return $update;
}
$loaded = true;
$release = self::json( self::LATEST );
$tag = $release['tag_name'] ?? null;
if ( ! is_string( $tag ) || ! preg_match( '/^v' . self::VERSION . '$/D', $tag ) || false !== ( $release['draft'] ?? null ) || false !== ( $release['prerelease'] ?? null ) || ! is_array( $release['assets'] ?? null ) ) {
return null;
}
$names = array_column( $release['assets'], 'name' );
if ( ! in_array( self::archive_name( $tag ), $names, true ) || ! in_array( self::MANIFEST, $names, true ) ) {
return null;
}
$manifest = self::manifest( $tag );
if ( ! $manifest ) {
return null;
}
$update = [
'slug' => self::SLUG,
'version' => $manifest['version'],
'requires' => $manifest['requires'],
'requires_php' => $manifest['requires_php'],
'url' => self::REPO . '/releases/tag/' . $tag,
'package' => self::asset_url( $tag, self::archive_name( $tag ) ),
];
return $update;
}
public static function download( $reply, $package ) {
$base = preg_quote( self::REPO . '/releases/download/', '~' );
if ( false !== $reply || ! is_string( $package ) || ! preg_match( '~^' . $base . '(v' . self::VERSION . ')/eventlabs-\1\.zip$~D', $package, $match ) ) {
return $reply;
}
$manifest = self::manifest( $match[1] );
if ( ! $manifest ) {
return new \WP_Error( 'eventlabs_update_manifest', __( 'The eventLabs release manifest is unavailable or invalid.', 'burn-events' ) );
}
require_once ABSPATH . 'wp-admin/includes/file.php';
$file = wp_tempnam( self::archive_name( $match[1] ) );
if ( ! $file ) {
return new \WP_Error( 'eventlabs_update_file', __( 'WordPress could not create a temporary file for the eventLabs update.', 'burn-events' ) );
}
$response = wp_safe_remote_get( $package, [
'timeout' => 60,
'redirection' => 2,
'user-agent' => 'eventLabs/' . BURN_EVENTS_VERSION,
'stream' => true,
'filename' => $file,
'limit_response_size' => $manifest['size'] + 1,
] );
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
wp_delete_file( $file );
return new \WP_Error( 'eventlabs_update_download', __( 'WordPress could not download the eventLabs release ZIP.', 'burn-events' ) );
}
clearstatcache( true, $file );
if ( $manifest['size'] !== filesize( $file ) || $manifest['sha256'] !== hash_file( 'sha256', $file ) ) {
wp_delete_file( $file );
return new \WP_Error( 'eventlabs_update_checksum', __( 'The eventLabs download did not match the release checksum.', 'burn-events' ) );
}
return $file;
}
private static function manifest( string $tag ): ?array {
$manifest = self::json( self::asset_url( $tag, self::MANIFEST ) );
if ( ! $manifest || substr( $tag, 1 ) !== ( $manifest['version'] ?? null ) || self::archive_name( $tag ) !== ( $manifest['package'] ?? null ) ) {
return null;
}
foreach ( [ 'requires', 'requires_php' ] as $key ) {
if ( ! is_string( $manifest[ $key ] ?? null ) || ! preg_match( '/^[0-9]+\.[0-9]+(?:\.[0-9]+)?$/D', $manifest[ $key ] ) ) {
return null;
}
}
if ( ! is_string( $manifest['sha256'] ?? null ) || ! preg_match( '/^[a-f0-9]{64}$/D', $manifest['sha256'] ) || ! is_int( $manifest['size'] ?? null ) || $manifest['size'] < 1 || $manifest['size'] > self::MAX_ZIP_BYTES ) {
return null;
}
return $manifest;
}
private static function json( string $url ): ?array {
$response = wp_safe_remote_get( $url, [
'timeout' => 8,
'redirection' => 2,
'user-agent' => 'eventLabs/' . BURN_EVENTS_VERSION,
'headers' => [ 'Accept' => 'application/json' ],
'limit_response_size' => 128 * 1024,
] );
if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
return null;
}
$data = json_decode( wp_remote_retrieve_body( $response ), true );
return is_array( $data ) ? $data : null;
}
private static function archive_name( string $tag ): string {
return 'eventlabs-' . $tag . '.zip';
}
private static function asset_url( string $tag, string $name ): string {
return self::REPO . '/releases/download/' . $tag . '/' . $name;
}
}

198
scripts/release.py Normal file
View File

@@ -0,0 +1,198 @@
#!/usr/bin/env python3
"""Build an installable eventLabs ZIP, and optionally publish its tag to Gitea."""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import sys
from urllib.error import HTTPError, URLError
from urllib.parse import urlencode
from urllib.request import HTTPRedirectHandler, Request, build_opener
from uuid import uuid4
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parent.parent
HOST = 'https://git.labs.casa'
REPO = '/josh/eventLabs'
API = HOST + '/api/v1/repos' + REPO
PACKAGE_DIR = 'burn-events/'
MANIFEST = 'eventlabs-update.json'
VERSION = r'(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)'
REQUIREMENT = r'[0-9]+\.[0-9]+(?:\.[0-9]+)?'
RUNTIME = ('burn-events.php', 'assets', 'includes', 'templates')
MAX_ZIP_BYTES = 32 * 1024 * 1024
USER_AGENT = 'eventLabs-release'
def git(*args):
return subprocess.check_output(['git', '-C', str(ROOT), *args])
def build(ref, output):
commit = git('rev-parse', '--verify', '--end-of-options', ref + '^{commit}').decode().strip()
source = git('show', commit + ':burn-events.php').decode()
def header(name, pattern):
found = re.findall(r'^\s*\* ' + re.escape(name) + r': (' + pattern + r')\s*$', source, re.M)
if len(found) != 1:
raise ValueError(f'Expected one valid {name} header in burn-events.php.')
return found[0]
version = header('Version', VERSION)
tag = 'v' + version
constants = re.findall(r"^define\( 'BURN_EVENTS_VERSION', '([^']+)' \);$", source, re.M)
if constants != [version]:
raise ValueError('The plugin version header and BURN_EVENTS_VERSION must match.')
if (ref.startswith('refs/tags/') or re.fullmatch('v' + VERSION, ref)) and ref.removeprefix('refs/tags/') != tag:
raise ValueError(f'Release tag must match the plugin version: {tag}.')
archive_name = f'eventlabs-{tag}.zip'
data = {
'version': version,
'requires': header('Requires at least', REQUIREMENT),
'requires_php': header('Requires PHP', REQUIREMENT),
'package': archive_name,
'commit': commit,
}
if header('Update URI', r'\S+') != HOST + REPO:
raise ValueError('The plugin Update URI must point to the eventLabs release repository.')
output.mkdir(parents=True, exist_ok=True)
archive = output / archive_name
temporary = output / (archive_name + '.tmp')
try:
subprocess.run(
['git', '-C', str(ROOT), 'archive', '--format=zip', '-9', '--prefix=' + PACKAGE_DIR,
'--output=' + str(temporary.resolve()), commit, '--', *RUNTIME],
check=True, env={**os.environ, 'TZ': 'UTC'},
)
data['size'] = temporary.stat().st_size
if not 0 < data['size'] <= MAX_ZIP_BYTES:
raise ValueError('The WordPress release ZIP must be at most 32 MiB.')
with ZipFile(temporary) as package:
if package.read(PACKAGE_DIR + 'burn-events.php').decode() != source or package.testzip() is not None:
raise ValueError('The release ZIP is incomplete or corrupt.')
data['sha256'] = hashlib.sha256(temporary.read_bytes()).hexdigest()
temporary.replace(archive)
finally:
temporary.unlink(missing_ok=True)
manifest = output / MANIFEST
manifest.write_text(json.dumps(data, indent=2) + '\n', encoding='utf-8')
print(f'Built {archive} and {manifest}', flush=True)
return tag, data, archive, manifest
class NoRedirect(HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
# API write requests must never forward a repository credential to a redirect target.
return None
def authorization():
token = os.environ.get('EVENTLABS_RELEASE_TOKEN', '').strip()
if token:
return 'token ' + token
result = subprocess.run(
['git', '-C', str(ROOT), 'credential', 'fill'],
input=f'protocol=https\nhost=git.labs.casa\npath={REPO[1:]}.git\n\n',
capture_output=True, text=True, env={**os.environ, 'GIT_TERMINAL_PROMPT': '0'},
)
fields = dict(line.split('=', 1) for line in result.stdout.splitlines() if '=' in line)
if result.returncode or not fields.get('username') or not fields.get('password'):
raise ValueError('Set EVENTLABS_RELEASE_TOKEN or configure Git credentials for git.labs.casa.')
encoded = base64.b64encode((fields['username'] + ':' + fields['password']).encode()).decode()
return 'Basic ' + encoded
def publish(tag, data, archive, manifest):
auth = authorization()
opener = build_opener(NoRedirect())
def api(method, path, *, payload=None, attachment=None, missing=False):
headers = {'Authorization': auth, 'User-Agent': USER_AGENT, 'Accept': 'application/json'}
body = None
if payload is not None:
body = json.dumps(payload).encode()
headers['Content-Type'] = 'application/json'
if attachment is not None:
boundary = uuid4().hex
headers['Content-Type'] = 'multipart/form-data; boundary=' + boundary
body = (
f'--{boundary}\r\nContent-Disposition: form-data; name="attachment"; filename="{attachment.name}"\r\n'
'Content-Type: application/octet-stream\r\n\r\n'
).encode() + attachment.read_bytes() + f'\r\n--{boundary}--\r\n'.encode()
path += '?' + urlencode({'name': attachment.name})
request = Request(API + path, method=method, data=body, headers=headers)
try:
with opener.open(request, timeout=90) as response:
return json.load(response)
except HTTPError as error:
if missing and error.code == 404:
return None
raise ValueError(f'Gitea {method} {path} returned HTTP {error.code}.') from None
remote_tag = api('GET', '/tags/' + tag)
if remote_tag.get('commit', {}).get('sha') != data['commit']:
raise ValueError(f'Push {tag} for this exact commit before publishing.')
marker = f"SHA-256: `{data['sha256']}`"
release = api('GET', '/releases/tags/' + tag, missing=True)
if release is None:
release = api('POST', '/releases', payload={
'tag_name': tag, 'target_commitish': data['commit'], 'name': f'eventLabs {tag}',
'draft': True, 'prerelease': False,
'body': f"Install `{archive.name}` through Plugins → Add Plugin → Upload Plugin.\n\n"
f"Source commit: `{data['commit']}`\n\n{marker}",
})
if release.get('tag_name') != tag or release.get('prerelease') or marker not in (release.get('body') or ''):
raise ValueError(f'An existing release for {tag} does not match this package. Check it on Gitea.')
attachments = {asset['name']: asset['size'] for asset in release.get('assets') or []}
if release.get('draft'):
path = '/releases/' + str(int(release['id']))
for file in (archive, manifest):
size = file.stat().st_size
if file.name in attachments:
if attachments[file.name] != size:
raise ValueError(f'Existing draft attachment has the wrong size: {file.name}.')
continue
uploaded = api('POST', path + '/assets', attachment=file)
if uploaded.get('name') != file.name or uploaded.get('size') != size:
raise ValueError(f'Gitea did not store the complete attachment: {file.name}.')
api('PATCH', path, payload={'draft': False})
# Confirm the same anonymous download URLs WordPress will use.
download = HOST + REPO + '/releases/download/' + tag + '/'
for file in (archive, manifest):
request = Request(download + file.name, headers={'User-Agent': USER_AGENT})
with build_opener().open(request, timeout=45) as response:
expected = file.read_bytes()
if response.read(len(expected) + 1) != expected:
raise ValueError(f'Public release download does not match the build: {file.name}.')
print(HOST + REPO + '/releases/tag/' + tag)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('ref', nargs='?', default='HEAD', help='Git ref to package; default HEAD')
parser.add_argument('--out', type=Path, default=ROOT / 'dist')
parser.add_argument('--publish', action='store_true', help='Publish both assets to the already pushed tag')
args = parser.parse_args()
if args.publish and not re.fullmatch('v' + VERSION, args.ref):
parser.error('--publish requires a stable tag like v0.5.2')
ref = 'refs/tags/' + args.ref if args.publish else args.ref
try:
release = build(ref, args.out)
if args.publish:
publish(*release)
except (ValueError, OSError, subprocess.CalledProcessError, URLError) as error:
print(f'Release failed: {error}', file=sys.stderr)
return 1
return 0
if __name__ == '__main__':
sys.exit(main())