1
0
mirror of https://github.com/mikf/gallery-dl.git synced 2024-11-22 10:42:34 +01:00

implement 'contains()' (#2446)

and add it to globals() in compiled expressions for --filter etc
This commit is contained in:
Mike Fährmann 2022-03-30 10:36:52 +02:00
parent ecee315bbf
commit 413b77757b
No known key found for this signature in database
GPG Key ID: 5680CA389D365A88
2 changed files with 36 additions and 0 deletions

View File

@ -71,6 +71,24 @@ def unique_sequence(iterable):
yield element
def contains(values, elements):
"""Returns True if at least one of 'elements' is contained in 'values'"""
if not isinstance(elements, (tuple, list)):
elements = (elements,)
if isinstance(values, str):
fmt = r"\b{}\b".format
for e in elements:
if re.search(fmt(e), values):
return True
else:
for e in elements:
if e in values:
return True
return False
def raises(cls):
"""Returns a function that raises 'cls' as exception"""
def wrap(*args):
@ -429,6 +447,7 @@ WINDOWS = (os.name == "nt")
SENTINEL = object()
SPECIAL_EXTRACTORS = {"oauth", "recursive", "test"}
GLOBALS = {
"contains" : contains,
"parse_int": text.parse_int,
"urlsplit" : urllib.parse.urlsplit,
"datetime" : datetime.datetime,

View File

@ -319,6 +319,23 @@ class TestOther(unittest.TestCase):
self.assertSequenceEqual(
list(util.unique_sequence([1, 2, 1, 3, 2, 1])), [1, 2, 1, 3, 2, 1])
def test_contains(self):
c = [1, "2", 3, 4, "5", "foo"]
self.assertTrue(util.contains(c, 1))
self.assertTrue(util.contains(c, "foo"))
self.assertTrue(util.contains(c, [1, 3, "5"]))
self.assertTrue(util.contains(c, ["a", "b", "5"]))
self.assertFalse(util.contains(c, "bar"))
self.assertFalse(util.contains(c, [2, 5, "bar"]))
s = "1, 2, 3, asd, qwe, yxc, foo, bar"
self.assertTrue(util.contains(s, 2))
self.assertTrue(util.contains(s, "asd"))
self.assertTrue(util.contains(s, ["asd", "qwe", "yxc"]))
self.assertTrue(util.contains(s, ["sdf", "dfg", "qwe"]))
self.assertFalse(util.contains(s, "tag1"))
self.assertFalse(util.contains(s, ["tag1", "tag2", "tag3"]))
def test_raises(self):
func = util.raises(Exception)
with self.assertRaises(Exception):