Allow Ender Pearls in Giedi Nether wilderness #55

Merged
unimatrix merged 2 commits from ops/giedi-nether-ender-pearl-20261202 into main 2026-12-02 12:03:37 +01:00
3 changed files with 226 additions and 0 deletions

View file

@ -0,0 +1,33 @@
name: Giedi Nether Ender Pearl Operations Build
on:
workflow_dispatch:
push:
branches: ['ops/giedi-nether-ender-pearl-*']
jobs:
giedi-nether-pearl:
runs-on: dune-ci
steps:
- name: Check out exact revision
shell: bash
env:
REPO_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
set -euo pipefail
git init .
git -c http.extraheader="AUTHORIZATION: basic $(printf 'x-access-token:%s' "$REPO_TOKEN" | base64 -w0)" fetch --depth=1 https://www.dunerealms.com/git/unimatrix/plugins.git "$GITHUB_SHA"
git checkout --detach FETCH_HEAD
- name: Validate and package the scoped native command
shell: bash
run: |
set -euo pipefail
python3 tools/test_giedi_nether_pearl.py -v
mkdir giedi-pearl-artifacts
cp tools/allow-giedi-nether-pearl.py giedi-pearl-artifacts/
printf '%s\n' "$(git rev-parse HEAD)" > giedi-pearl-artifacts/SOURCE_COMMIT
(cd giedi-pearl-artifacts && sha256sum -- *.py SOURCE_COMMIT > SHA256SUMS)
- uses: actions/upload-artifact@v3
with:
name: DuneRealms-Giedi-Nether-Ender-Pearl
path: giedi-pearl-artifacts/
if-no-files-found: error

View file

@ -0,0 +1,130 @@
"""Allow Ender Pearls in Giedi Prime Nether wilderness through Towny's command."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import stat
import subprocess
import time
ROOT = Path('/opt/dunerealms/servers/giedi_prime')
UNIT = 'dune-giedi_prime.service'
WORLD = 'giedi_prime_nether'
TOWNY_SHA = 'c8d7d59984eaf2606fce4192e860f7f969f3384e5a51b26b97225efbbe747c70'
WORLD_SHA = '7f335ddab1891f774f966f896b49127c2f1fe0bbfdecf3b8e3eb41933ea5a02f'
CONFIG_SHA = '7440231da22718cba4c402d8b07594484aacd840b3c01ab81c4d2a6f1fcfac1f'
IGNORE = 'unclaimedZoneIgnoreIds'
PEARL = 'ENDER_PEARL'
def sha(path):
if not path.is_file() or path.absolute() != path.resolve(strict=True):
raise ValueError(f'Expected a regular canonical file: {path}')
return hashlib.sha256(path.read_bytes()).hexdigest()
def fields(text):
result = {}
for line in text.splitlines():
if not line.strip() or line.lstrip().startswith('#'):
continue
key, separator, value = line.partition('=')
if not separator or not key or key in result:
raise ValueError('Unexpected Towny world file syntax')
result[key] = value
return result
def materials(data):
names = data.get(IGNORE, '').split(',')
if any(not re.fullmatch(r'[A-Z0-9_]+', name) for name in names) or len(set(names)) != len(names):
raise ValueError('Expected Towny to have saved a canonical list of distinct materials')
return names
def command(before):
if before.get('usingTowny') != 'true' or before.get('unclaimedZoneItemUse') != 'false':
raise ValueError('Expected the current Nether wilderness protection policy')
old = materials(before)
if PEARL in old:
raise ValueError('The Nether exception is already installed')
return f'townyworld {WORLD} set wildignore ' + ' '.join([*old, PEARL])
def verify(before, after):
if set(materials(after)) != {*materials(before), PEARL}:
raise ValueError('Towny did not save exactly the Ender Pearl exception')
if {key: value for key, value in before.items() if key != IGNORE} != {
key: value for key, value in after.items() if key != IGNORE
}:
raise ValueError('Unexpected change to another Towny world field')
def send(fifo, line):
payload = (line + '\n').encode('ascii')
fd = os.open(fifo, os.O_WRONLY | os.O_NONBLOCK | os.O_NOFOLLOW)
try:
if not stat.S_ISFIFO(os.fstat(fd).st_mode) or len(payload) > os.fpathconf(fd, 'PC_PIPE_BUF'):
raise ValueError('Expected one atomic write to the native console FIFO')
if os.write(fd, payload) != len(payload):
raise OSError('Incomplete console write')
finally:
os.close(fd)
def service(*args):
return subprocess.run(['systemctl', *args], text=True, capture_output=True, check=True).stdout.strip()
def run(apply):
if service('is-active', UNIT) != 'active' or service('show', UNIT, '--property=WorkingDirectory', '--value') != str(ROOT):
raise ValueError('Expected the active Giedi Prime server')
plugins = ROOT / 'plugins'
towny = plugins / 'Towny-0.103.2.0.jar'
config = plugins / 'Towny/settings/config.yml'
worlds = plugins / 'Towny/data/worlds'
target = worlds / f'{WORLD}.txt'
if sha(towny) != TOWNY_SHA or sha(config) != CONFIG_SHA or sha(target) != WORLD_SHA:
raise ValueError('Towny, its configuration, or the target world differs from preflight')
before = fields(target.read_text())
operation = command(before)
result = {'unit': UNIT, 'world': WORLD, 'material': PEARL, 'beforeSha256': WORLD_SHA, 'status': 'planned'}
if not apply:
return result
siblings = {path.name: sha(path) for path in worlds.glob('*.txt') if path != target}
if sha(towny) != TOWNY_SHA or sha(config) != CONFIG_SHA or sha(target) != WORLD_SHA:
raise ValueError('Towny settings changed before the console call')
send(ROOT / 'console.fifo', operation)
for _ in range(40):
time.sleep(.25)
try:
observed = sha(target)
after = fields(target.read_text())
except (FileNotFoundError, ValueError):
continue
if observed != WORLD_SHA and PEARL in after.get(IGNORE, '').split(','):
verify(before, after)
if sha(towny) != TOWNY_SHA or sha(config) != CONFIG_SHA or siblings != {
path.name: sha(path) for path in worlds.glob('*.txt') if path != target
}:
raise ValueError('Unexpected change to another Towny file')
return {**result, 'status': 'persisted', 'afterSha256': observed, 'otherWorldsVerified': len(siblings)}
raise RuntimeError('Towny save was not confirmed. Inspect native console before retrying.')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--apply', action='store_true')
options = parser.parse_args()
if options.apply:
import fcntl
with Path('/run/lock/dunerealms-giedi-nether-pearl.lock').open('a') as lock:
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
report = run(True)
else:
report = run(False)
print(json.dumps(report, indent=2))

View file

@ -0,0 +1,63 @@
import importlib.util
from pathlib import Path
from tempfile import TemporaryDirectory
import unittest
from unittest.mock import patch
spec = importlib.util.spec_from_file_location('pearl', Path(__file__).with_name('allow-giedi-nether-pearl.py'))
pearl = importlib.util.module_from_spec(spec)
spec.loader.exec_module(pearl)
BEFORE = 'usingTowny=true\nunclaimedZoneItemUse=false\nunclaimedZoneIgnoreIds=TORCH,CHORUS_FRUIT\nclaimable=false\n'
class GiediNetherPearlTests(unittest.TestCase):
def test_native_command_targets_the_nether_and_replays_the_entire_list(self):
self.assertEqual(pearl.command(pearl.fields(BEFORE)),
'townyworld giedi_prime_nether set wildignore TORCH CHORUS_FRUIT ENDER_PEARL')
with self.assertRaises(ValueError):
pearl.command(pearl.fields(BEFORE.replace('TORCH,', 'TORCH;op,')))
def test_towny_may_sort_materials_but_no_other_setting_may_change(self):
before = pearl.fields(BEFORE)
after = pearl.fields(BEFORE.replace('TORCH,CHORUS_FRUIT', 'CHORUS_FRUIT,ENDER_PEARL,TORCH'))
pearl.verify(before, after)
for field, value in [(pearl.IGNORE, 'ENDER_PEARL,TORCH'), ('unclaimedZoneItemUse', 'true')]:
with self.subTest(field=field), self.assertRaises(ValueError):
pearl.verify(before, {**after, field: value})
def test_plan_and_apply_use_only_the_reviewed_world_file(self):
with TemporaryDirectory() as temp:
root = Path(temp).resolve()
towny = root / 'plugins/Towny-0.103.2.0.jar'
config = root / 'plugins/Towny/settings/config.yml'
world = root / 'plugins/Towny/data/worlds/giedi_prime_nether.txt'
sibling = world.with_name('giedi_prime.txt')
for path, content in [(towny, 'jar'), (config, 'config'), (world, BEFORE), (sibling, 'untouched')]:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(content)
native_calls = []
def console(fifo, line):
native_calls.append((fifo, line))
world.write_text(BEFORE.replace('TORCH,CHORUS_FRUIT', 'TORCH,CHORUS_FRUIT,ENDER_PEARL'))
with patch.multiple(pearl, ROOT=root, WORLD_SHA=pearl.sha(world), CONFIG_SHA=pearl.sha(config),
TOWNY_SHA=pearl.sha(towny), send=console), patch.object(
pearl, 'service', side_effect=lambda *args: 'active' if args[0] == 'is-active' else str(root)), \
patch.object(pearl.time, 'sleep'):
self.assertEqual(pearl.run(False)['status'], 'planned')
self.assertEqual(native_calls, [])
self.assertEqual(pearl.run(True)['status'], 'persisted')
self.assertEqual(len(native_calls), 1)
self.assertEqual(native_calls[0][0], root / 'console.fifo')
self.assertEqual(sibling.read_text(), 'untouched')
with self.assertRaises(ValueError):
pearl.run(True)
self.assertEqual(len(native_calls), 1)
if __name__ == '__main__':
unittest.main()