Coverage for netbox_interface_name_rules / regex_safety.py: 100.00%
12 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-16 10:13 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-10-16 10:13 +0000
1# SPDX-License-Identifier: Apache-2.0
2# Copyright (C) 2025 Marcin Zieba <marcinpsk@gmail.com>
3"""Compile stored rule patterns with a bounded regular-expression engine."""
5import re2
6from django.core.exceptions import ValidationError
8_OPTIONS = re2.Options()
9_OPTIONS.log_errors = False
12def _error_detail(exc):
13 """Return RE2's parser error as text without its bytes representation."""
14 detail = exc.args[0] if exc.args else str(exc)
15 return detail.decode(errors="replace") if isinstance(detail, bytes) else str(detail)
18def compile_module_type_pattern(pattern):
19 """Compile a stored rule pattern with RE2, or raise a field validation error."""
20 try:
21 return re2.compile(pattern, options=_OPTIONS)
22 except re2.error as exc:
23 raise ValidationError({"module_type_pattern": f"Invalid RE2 pattern: {_error_detail(exc)}"}) from exc