Add read-only colorful Cockatrice deck checklist
Cockatrice assets CI A checkout, check, build, archive, or publication step failed. See the Jenkins log; publication may be incomplete.
Gitea/cockatrice-custom-tokens/pipeline/head There was a failure building this commit Details

This commit is contained in:
Dandaedre 2026-11-10 12:37:38 +01:00
parent cd85353e1e
commit 4acb8c105f
Signed by: Dandaedre
GPG Key ID: 440C6592E8A26D99
5 changed files with 374 additions and 0 deletions

View File

@ -491,6 +491,60 @@ Pipeline Linter (`<JENKINS_URL>/pipeline-model-converter/validate`). Groovy comp
alone does not validate plugin availability or Declarative semantics. Publication
is not live until Jenkins parses this file and successfully builds `main`.
## Check your deck collection
The read-only checklist scans Cockatrice `.cod` files recursively and displays
one row per deck with color-coded checks for **description, format, tags, banner
card**, and **Command Zone token for Commander decks**. It does not modify decks.
Install the optional terminal-display dependencies into the existing build venv:
```sh
uv pip install --python .venv/bin/python --require-hashes -r requirements-tools.lock
.venv/bin/python scripts/check_decks.py
```
Without uv, use `.venv/bin/python -m pip install --require-hashes -r requirements-tools.lock`.
If you have no environment yet, create one with `python3 -m venv .venv` first.
Rich is optional tooling, separate from the Pillow build dependency; the CI tests
exercise deck analysis without needing Rich or access to your private decks.
By default, the script discovers native/XDG, Flatpak, and macOS Cockatrice data
folders (and `LOCALAPPDATA` on Windows), honoring each `settings/paths.ini` decks
path. Multiple discovered collections are scanned together and duplicate files
are checked once. Explicit paths override discovery:
```sh
.venv/bin/python scripts/check_decks.py /path/to/decks --missing-only
.venv/bin/python scripts/check_decks.py /path/to/one.cod /path/to/another.cod
.venv/bin/python scripts/check_decks.py --no-color
.venv/bin/python scripts/check_decks.py --json > /tmp/deck-checklist.json
.venv/bin/python scripts/check_decks.py --strict
```
The table uses green `✓` for present, red `✗` for missing, gray `—` for not
applicable, and yellow `?` for an unknown check. Wider terminals include a
missing-items/notes column. Colors are automatically disabled for redirected
output; `--no-color` disables them explicitly. `--json` requires only Python's
standard library. Descriptions come from `<comments>`, tags from nonempty
`<tags><tag>` entries, and the banner from the nonempty `<bannerCard>` card name.
This checks metadata presence, not card legality or whether a banner printing
exists in your card database.
Commander/EDH/cEDH and Duel Commander/1v1 Commander labels are recognized without
case sensitivity. Add a custom exact format label using
`--commander-format "My Commander Format"` (repeatable). Commander decks pass the
token check when a card named `Command Zone` with a positive quantity appears in
any deck zone, including tokens or sideboard. Card-name comparison ignores case,
hyphens/underscores, and repeated whitespace. Merely having a commander card does
not satisfy this check. Missing format yields `?` for the token requirement; the
script does not guess a format from deck contents.
Malformed/unreadable decks are reported individually so the rest of the collection
can still be checked. Exit status is `0` for a successful report, `1` with
`--strict` when anything is incomplete, and `2` for file/parse/configuration errors
or no decks found. `--missing-only` filters display, not summary counts or exit
status. Non-`.cod` files are ignored during directory scans.
## Servatrice configuration backup
[config/servatrice/README.md](config/servatrice/README.md) records sanitized snapshots

18
requirements-tools.lock Normal file
View File

@ -0,0 +1,18 @@
# This file was autogenerated by uv via the following command:
# uv pip compile requirements-tools.txt --generate-hashes --output-file requirements-tools.lock
markdown-it-py==4.2.0 \
--hash=sha256:04a21681d6fbb623de53f6f364d352309d4094dd4194040a10fd51833e418d49 \
--hash=sha256:9f7ebbcd14fe59494226453aed97c1070d83f8d24b6fc3a3bcf9a38092641c4a
# via rich
mdurl==0.1.2 \
--hash=sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8 \
--hash=sha256:bb413d29f5eea38f31dd4754dd7377d4465116fb207585f97bf925588687c1ba
# via markdown-it-py
pygments==2.21.0 \
--hash=sha256:2363c69b61c4a97c838da3b130dcd6468f4848992b21a82f2a63ec34377137d9 \
--hash=sha256:610ca751c9bc2492b38eb9a38a7fbc93edbbb2d7182edaf34e66ae493dee5c8c
# via rich
rich==14.2.0 \
--hash=sha256:73ff50c7c0c1c77c8243079283f4edb376f0f6442433aecb8ce7e6d0b92d1fe4 \
--hash=sha256:76bc51fe2e57d2b1be1f96c524b890b816e334ab4c1e45888799bfaab0021edd
# via -r requirements-tools.txt

2
requirements-tools.txt Normal file
View File

@ -0,0 +1,2 @@
# Optional local deck-checklist display; not required by the token installer.
rich==14.2.0

207
scripts/check_decks.py Normal file
View File

@ -0,0 +1,207 @@
#!/usr/bin/env python3
"""Read-only checklist for Cockatrice deck metadata and Commander reminder tokens."""
import argparse
import configparser
from dataclasses import asdict, dataclass
import json
import os
from pathlib import Path
import re
import sys
import xml.etree.ElementTree as ET
FIELDS = ('Description', 'Format', 'Tags', 'Banner', 'Command Zone')
COMMANDER_FORMATS = {'commander', 'edh', 'cedh', 'duel commander', 'commander 1v1', '1v1 commander'}
def normalized(value):
return ' '.join(value.casefold().replace('_', ' ').replace('-', ' ').split())
@dataclass
class DeckResult:
path: str
label: str
name: str
format: str
checks: dict
error: str = ''
@property
def missing(self):
return [field for field, state in self.checks.items() if state == 'missing']
@property
def complete(self):
return not self.error and all(state in ('ok', 'na') for state in self.checks.values())
def inspect_deck(path, label=None, commander_formats=None):
result = DeckResult(str(path), label or path.name, path.stem, '', {field: 'unknown' for field in FIELDS})
try:
if path.stat().st_size > 16 * 1024 * 1024:
raise ValueError('Deck exceeds the 16 MiB safety limit')
data = path.read_bytes()
if len(data) > 16 * 1024 * 1024:
raise ValueError('Deck exceeds the 16 MiB safety limit')
if b'<!DOCTYPE' in data.upper() or b'<!ENTITY' in data.upper():
raise ValueError('XML entity/DOCTYPE declarations are not supported')
root = ET.fromstring(data)
if root.tag != 'cockatrice_deck':
raise ValueError('Not a Cockatrice deck XML file')
result.name = (root.findtext('deckname') or path.stem).strip()
result.format = (root.findtext('format') or '').strip()
description = (root.findtext('comments') or '').strip()
# Treat empty rich-text placeholders as missing too.
description = re.sub(r'<[^>]+>', '', description).replace('&nbsp;', ' ').replace('\xa0', ' ').strip()
values = {'Description': bool(description), 'Format': bool(result.format),
'Tags': any((tag.text or '').strip() for tag in root.findall('./tags/tag')),
'Banner': bool((root.findtext('bannerCard') or '').strip())}
result.checks.update({key: 'ok' if value else 'missing' for key, value in values.items()})
formats = COMMANDER_FORMATS | {normalized(f) for f in (commander_formats or [])}
if not result.format:
result.checks['Command Zone'] = 'unknown'
elif normalized(result.format) not in formats:
result.checks['Command Zone'] = 'na'
else:
present = False
for card in root.findall('.//zone/card'):
if normalized(card.get('name', '')) != 'command zone':
continue
try:
present |= int(card.get('number', '0')) > 0
except ValueError:
raise ValueError('Command Zone card has an invalid quantity') from None
result.checks['Command Zone'] = 'ok' if present else 'missing'
except (OSError, ValueError, ET.ParseError) as error:
result.error = str(error)
return result
def default_directories(home, environment):
xdg = Path(environment.get('XDG_DATA_HOME') or home / '.local/share')
bases = [xdg / 'Cockatrice/Cockatrice', home / '.local/share/Cockatrice/Cockatrice',
home / '.var/app/io.cockatrice.Cockatrice/data/Cockatrice/Cockatrice',
home / 'Library/Application Support/Cockatrice/Cockatrice',
home / 'Library/Application Support/Cockatrice']
if environment.get('LOCALAPPDATA'):
bases.append(Path(environment['LOCALAPPDATA']) / 'Cockatrice/Cockatrice')
found = []
for base in dict.fromkeys(bases):
if not base.is_dir():
continue
directory = base / 'decks'
settings = base / 'settings/paths.ini'
if settings.is_file():
config = configparser.ConfigParser(interpolation=None)
config.read_string(settings.read_text())
configured = config.get('paths', 'decks', fallback='').strip()
if configured:
directory = Path(configured).expanduser()
if not directory.is_absolute():
raise ValueError(f'Relative configured deck directory in {settings}; pass the directory explicitly')
if not directory.is_dir():
raise ValueError(f'Cockatrice deck directory is missing: {directory}')
found.append(directory.resolve())
return list(dict.fromkeys(found))
def collect(paths):
files = {}
multiple = len(paths) > 1
for path in paths:
path = path.expanduser().absolute()
if not path.exists():
raise ValueError(f'Path does not exist: {path}')
if path.is_file():
if path.suffix.lower() != '.cod':
raise ValueError(f'Expected a .cod deck file: {path}')
files.setdefault(path.resolve(), path.name)
else:
for item in sorted(path.rglob('*')):
if item.is_file() and item.suffix.lower() == '.cod':
label = str(item) if multiple else item.relative_to(path).as_posix()
files.setdefault(item.resolve(), label)
return sorted(files.items(), key=lambda item: item[1].casefold())
def display(results, paths, missing_only=False, no_color=False):
try:
from rich.console import Console
from rich.table import Table
from rich.text import Text
except ImportError:
raise ValueError('Color display requires Rich: uv pip install --python .venv/bin/python --require-hashes -r requirements-tools.lock (or use --json)') from None
console = Console(no_color=no_color, highlight=False)
console.print(Text('COCKATRICE · DECK CHECKLIST', style='bold cyan'))
for path in paths:
console.print(Text(str(path), style='dim'))
console.print('')
table = Table(header_style='bold cyan', show_lines=False, expand=True)
table.add_column('Deck file', ratio=3, overflow='fold')
headers = ('Desc.', 'Format', 'Tags', 'Banner', 'C.Zone')
for header in headers:
table.add_column(header, justify='center', no_wrap=True)
detailed = console.width >= 110
if detailed:
table.add_column('Missing / notes', ratio=2, overflow='fold')
symbols = {'ok': ('✓', 'green'), 'missing': ('✗', 'bold red'),
'na': ('—', 'dim'), 'unknown': ('?', 'yellow')}
for result in results:
if missing_only and result.complete:
continue
notes = 'ERROR: ' + result.error if result.error else ', '.join(result.missing)
if not result.error and result.checks['Command Zone'] == 'unknown':
notes += '; set format to check Command Zone'
cells = [Text(result.label), *(Text(*symbols[state]) for state in result.checks.values())]
if detailed:
cells.append(Text(notes or 'Complete', style='red' if result.error else ('green' if result.complete else 'yellow')))
table.add_row(*cells)
console.print(table)
if not detailed:
for result in results:
if result.error:
console.print(Text(f'ERROR — {result.label}: {result.error}', style='bold red'))
complete = sum(r.complete for r in results)
errors = sum(bool(r.error) for r in results)
console.print(Text(f'\n{len(results)} decks · {complete} complete · {len(results) - complete - errors} need attention · {errors} errors', style='bold'))
counts = ' | '.join(f'{field}: {sum(r.checks[field] == "missing" for r in results if not r.error)} missing' for field in FIELDS)
console.print(Text(counts, style='yellow'))
console.print(Text('✓ present ✗ missing — not applicable ? unknown (format missing or unreadable deck)', style='dim'))
console.print(Text('Read-only: no deck files changed.', style='dim'))
def main(argv=None):
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('paths', nargs='*', type=Path, help='Deck directories (recursive) or .cod files; default: detected Cockatrice decks')
parser.add_argument('--missing-only', action='store_true', help='Hide complete decks')
parser.add_argument('--no-color', action='store_true', help='Disable terminal colors')
parser.add_argument('--json', action='store_true', help='Machine-readable report (no Rich dependency)')
parser.add_argument('--strict', action='store_true', help='Exit 1 if any metadata or required token is missing')
parser.add_argument('--commander-format', action='append', default=[], metavar='NAME', help='Also treat this exact format label as Commander (repeatable)')
args = parser.parse_args(argv)
try:
paths = args.paths or default_directories(Path.home(), os.environ)
if not paths:
raise ValueError('No Cockatrice deck directory found; pass a directory or .cod file explicitly')
files = collect(paths)
if not files:
raise ValueError('No .cod deck files found in the selected paths')
results = [inspect_deck(path, label, args.commander_format) for path, label in files]
if args.json:
visible = [r for r in results if not args.missing_only or not r.complete]
print(json.dumps({'total': len(results), 'complete': sum(r.complete for r in results),
'errors': sum(bool(r.error) for r in results),
'decks': [dict(asdict(r), missing=r.missing, complete=r.complete) for r in visible]}, indent=2, ensure_ascii=False))
else:
display(results, paths, args.missing_only, args.no_color)
if any(r.error for r in results):
return 2
return 1 if args.strict and any(not r.complete for r in results) else 0
except (OSError, ValueError, configparser.Error) as error:
print(f'ERROR: {error}', file=sys.stderr)
return 2
if __name__ == '__main__':
sys.exit(main())

93
tests/test_check_decks.py Normal file
View File

@ -0,0 +1,93 @@
import contextlib
import importlib.util
import io
from pathlib import Path
import tempfile
import unittest
SPEC = importlib.util.spec_from_file_location('check_decks', Path(__file__).resolve().parents[1] / 'scripts/check_decks.py')
checker = importlib.util.module_from_spec(SPEC)
# dataclasses looks up its module while processing annotations.
import sys
sys.modules[SPEC.name] = checker
SPEC.loader.exec_module(checker)
DECK = '''<cockatrice_deck version="1"><deckname>Example</deckname>
<comments>A deck description</comments><format>commander</format>
<tags><tag>Control</tag></tags><bannerCard providerId="abc">Commander</bannerCard>
<zone name="tokens"><card number="1" name="Command Zone"/></zone></cockatrice_deck>'''
class DeckChecklistTests(unittest.TestCase):
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
self.root = Path(self.temp.name)
self.path = self.root / 'deck.cod'
self.path.write_text(DECK)
def check(self, contents=DECK):
self.path.write_text(contents)
return checker.inspect_deck(self.path)
def test_complete_deck_and_read_only(self):
before = self.path.read_bytes(), self.path.stat().st_mtime_ns
self.assertTrue(checker.inspect_deck(self.path).complete)
self.assertEqual(before, (self.path.read_bytes(), self.path.stat().st_mtime_ns))
def test_empty_metadata_is_missing_and_unknown_format_does_not_guess(self):
result = self.check('<cockatrice_deck><comments>&lt;p&gt;&lt;br&gt;&lt;/p&gt;</comments><format> </format><tags><tag> </tag></tags><bannerCard providerId="abc"/></cockatrice_deck>')
self.assertEqual(result.missing, ['Description', 'Format', 'Tags', 'Banner'])
self.assertEqual(result.checks['Command Zone'], 'unknown')
def test_commander_aliases_and_positive_quantities(self):
for label in ('Commander', 'EDH', 'cEDH', 'Duel Commander', 'commander_1v1'):
with self.subTest(label=label):
self.assertEqual(self.check(DECK.replace('commander</format>', label + '</format>')).checks['Command Zone'], 'ok')
for quantity in ('0', '-1'):
self.assertEqual(self.check(DECK.replace('number="1"', f'number="{quantity}"')).checks['Command Zone'], 'missing')
self.assertTrue(self.check(DECK.replace('number="1"', 'number="bad"')).error)
def test_no_false_positive_for_commander_card_or_plan(self):
self.assertEqual(self.check(DECK.replace('name="Command Zone"', 'name="Commander"')).checks['Command Zone'], 'missing')
self.assertEqual(self.check(DECK.replace('<zone name="tokens">', '<sideboard_plan>').replace('</zone>', '</sideboard_plan>')).checks['Command Zone'], 'missing')
def test_non_commander_and_custom_alias(self):
content = DECK.replace('commander</format>', 'modern</format>').replace('name="Command Zone"', 'name="Other"')
self.assertEqual(self.check(content).checks['Command Zone'], 'na')
self.path.write_text(content)
self.assertEqual(checker.inspect_deck(self.path, commander_formats=['modern']).checks['Command Zone'], 'missing')
def test_malformed_xml_and_wrong_root_are_reported(self):
for contents in ('<broken', '<other/>', '<!DOCTYPE x><cockatrice_deck/>'):
self.assertTrue(self.check(contents).error)
def test_recursive_collection_deduplicates_and_handles_case(self):
nested = self.root / 'Ideas'
nested.mkdir()
(nested / 'other.COD').write_text(DECK)
(nested / 'ignored.txt').write_text('anything')
self.assertEqual(len(checker.collect([self.root, self.path])), 2)
with self.assertRaises(ValueError):
checker.collect([self.root / 'missing'])
def test_configured_directory_is_respected(self):
home = self.root / 'home'
settings = home / '.local/share/Cockatrice/Cockatrice/settings'
settings.mkdir(parents=True)
(settings / 'paths.ini').write_text(f'[paths]\ndecks={self.root}\n')
self.assertEqual(checker.default_directories(home, {}), [self.root])
def test_json_and_exit_codes(self):
with contextlib.redirect_stdout(io.StringIO()), contextlib.redirect_stderr(io.StringIO()):
self.assertEqual(checker.main([str(self.path), '--json', '--strict']), 0)
self.path.write_text(DECK.replace('<comments>A deck description</comments>', '<comments/>'))
self.assertEqual(checker.main([str(self.path), '--json']), 0)
self.assertEqual(checker.main([str(self.path), '--json', '--strict']), 1)
self.path.write_text('<broken')
self.assertEqual(checker.main([str(self.path), '--json']), 2)
self.assertEqual(checker.main([str(self.root / 'missing'), '--json']), 2)
if __name__ == '__main__':
unittest.main()