Skip to content

Commit

Permalink
Fix wildcards and add a test for them
Browse files Browse the repository at this point in the history
  • Loading branch information
msm-code committed Aug 23, 2024
1 parent b41b7d0 commit 45c036b
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 7 deletions.
16 changes: 9 additions & 7 deletions karton/core/query.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import fnmatch
import re

from collections.abc import Mapping, Sequence
from typing import Dict, Type

Expand Down Expand Up @@ -303,13 +305,13 @@ def __repr__(self):
return f"<Query({self._definition})>"


def toregex(x):
"""Naive/PoC wildcard-to-regex conversion"""
if not isinstance(x, str):
raise QueryError(f"Unexpected value in the regex conversion: {x}")
if "?" in x or "*" in x or "[" in x:
return {"$regex": "^" + x.replace("?", ".?").replace("*", ".*") + "$"}
return x
def toregex(wildcard):
if not isinstance(wildcard, str):
raise QueryError(f"Unexpected value in the regex conversion: {wildcard}")
# If is not neessary, but we avoid unnecessary regular expressions.
if any(c in wildcard for c in "?*[]!"):
return {"$regex": fnmatch.translate(wildcard)}
return wildcard


def convert(filters):
Expand Down
14 changes: 14 additions & 0 deletions tests/test_task_filters.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,3 +508,17 @@ def test_newstyle_flip(self):
}
)
self.assertFalse(task_sample.matches_filters(filters))

def test_oldstyle_wildcards(self):
# Old-style wildcards, except negative filters, don't mix
filters = [{"foo": "ba[!rz]"}]

task_sample = Task(headers={
"foo": "bar",
})
self.assertFalse(task_sample.matches_filters(filters))

task_sample = Task(headers={
"foo": "bat",
})
self.assertTrue(task_sample.matches_filters(filters))

0 comments on commit 45c036b

Please sign in to comment.