If you want to avoid the libmagic DSL, you can implement a custom matcher by subclassing MagicTest. You must implement the test method, which performs the actual byte sequence validation.
To make the matcher active, register it with MagicMatcher.DEFAULT_INSTANCE.add().
from typing import Optional
from polyfile.magic import AbsoluteOffset, FailedTest, MagicMatcher, MagicTest, MatchedTest, TestResult, TestType
class ExampleMatcher(MagicTest):
def __init__(self):
super().__init__(
offset=AbsoluteOffset(0),
mime="application-x/example-mime",
extensions=("example",),
message="A message that will be printed when this test matches an input"
)
def subtest_type(self) -> TestType:
return TestType.BINARY
def test(self, data: bytes, absolute_offset: int, parent_match: Optional[TestResult]) -> TestResult:
if data.startswith(b"example"):
return MatchedTest(self, value=data, offset=0, length=len(data))
else:
return FailedTest(self, offset=0, message="This is not an example file!")
# Register the matcher so it always runs:
MagicMatcher.DEFAULT_INSTANCE.add(ExampleMatcher())