Skip to content

Commit

Permalink
Require that EPD opcodes start with letter (fixes #1080)
Browse files Browse the repository at this point in the history
  • Loading branch information
niklasf committed May 4, 2024
1 parent 6af0ff4 commit 716a0b9
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
16 changes: 13 additions & 3 deletions chess/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2739,9 +2739,7 @@ def _epd_operations(self, operations: Mapping[str, Union[None, str, int, float,
first_op = True

for opcode, operand in operations.items():
assert opcode != "-", "dash (-) is not a valid epd opcode"
for blacklisted in [" ", "\n", "\t", "\r"]:
assert blacklisted not in opcode, f"invalid character {blacklisted!r} in epd opcode: {opcode!r}"
self._validate_epd_opcode(opcode)

if not first_op:
epd.append(" ")
Expand Down Expand Up @@ -2819,6 +2817,17 @@ def epd(self, *, shredder: bool = False, en_passant: EnPassantSpec = "legal", pr

return " ".join(epd)

def _validate_epd_opcode(self, opcode: str) -> None:
if not opcode:
raise ValueError("empty string is not a valid epd opcode")
if opcode == "-":
raise ValueError("dash (-) is not a valid epd opcode")
if not opcode[0].isalpha():
raise ValueError(f"expected epd opcode to start with a letter, got: {opcode!r}")
for blacklisted in [" ", "\n", "\t", "\r"]:
if blacklisted in opcode:
raise ValueError(f"invalid character {blacklisted!r} in epd opcode: {opcode!r}")

def _parse_epd_ops(self: BoardT, operation_part: str, make_board: Callable[[], BoardT]) -> Dict[str, Union[None, str, int, float, Move, List[Move]]]:
operations: Dict[str, Union[None, str, int, float, Move, List[Move]]] = {}
state = "opcode"
Expand All @@ -2832,6 +2841,7 @@ def _parse_epd_ops(self: BoardT, operation_part: str, make_board: Callable[[], B
if opcode == "-":
opcode = ""
elif opcode:
self._validate_epd_opcode(opcode)
state = "after_opcode"
elif ch is None or ch == ";":
if opcode == "-":
Expand Down
5 changes: 5 additions & 0 deletions test.py
Original file line number Diff line number Diff line change
Expand Up @@ -1143,6 +1143,11 @@ def test_eret_epd(self):
self.assertEqual(ops["id"], "ERET 001 - Entlastung")
self.assertEqual(ops["bm"], [chess.Move.from_uci("f1f4")])

def test_set_fen_as_epd(self):
board = chess.Board()
with self.assertRaises(ValueError):
board.set_epd(board.fen()) # Move numbers are not valid opcodes

def test_null_moves(self):
self.assertEqual(str(chess.Move.null()), "0000")
self.assertEqual(chess.Move.null().uci(), "0000")
Expand Down

0 comments on commit 716a0b9

Please sign in to comment.