From b9920503db6482f0d3af7e95b3cf3c71fbbd7d4f Mon Sep 17 00:00:00 2001 From: Florian Bruhin Date: Mon, 15 Aug 2022 12:36:24 +0200 Subject: Add utils.match_globs Needed for the next commit. --- qutebrowser/misc/keyhintwidget.py | 5 ++--- qutebrowser/utils/utils.py | 15 ++++++++++++++- tests/unit/utils/test_utils.py | 13 +++++++++++++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/qutebrowser/misc/keyhintwidget.py b/qutebrowser/misc/keyhintwidget.py index 93d9af09d..c93ce5d4b 100644 --- a/qutebrowser/misc/keyhintwidget.py +++ b/qutebrowser/misc/keyhintwidget.py @@ -25,7 +25,6 @@ It is intended to help discoverability of keybindings. """ import html -import fnmatch import re from PyQt5.QtWidgets import QLabel, QSizePolicy @@ -100,8 +99,8 @@ class KeyHintView(QLabel): return def blacklisted(keychain): - return any(fnmatch.fnmatchcase(keychain, glob) - for glob in config.val.keyhint.blacklist) + excluded = config.val.keyhint.blacklist + return utils.match_globs(excluded, keychain) is not None def takes_count(cmdstr): """Return true iff this command can take a count argument.""" diff --git a/qutebrowser/utils/utils.py b/qutebrowser/utils/utils.py index 77543f161..704fcdb75 100644 --- a/qutebrowser/utils/utils.py +++ b/qutebrowser/utils/utils.py @@ -26,6 +26,7 @@ import re import sys import enum import json +import fnmatch import datetime import traceback import functools @@ -33,7 +34,7 @@ import contextlib import shlex import mimetypes from typing import (Any, Callable, IO, Iterator, - Optional, Sequence, Tuple, Type, Union, + Optional, Sequence, Tuple, List, Type, Union, TypeVar, TYPE_CHECKING) try: # Protocol was added in Python 3.8 @@ -852,3 +853,15 @@ def parse_point(s: str) -> QPoint: return QPoint(x, y) except OverflowError as e: raise ValueError(e) + + +def match_globs(patterns: List[str], value: str) -> Optional[str]: + """Match a list of glob-like patterns against a value. + + Return: + The first matching pattern if there was a match, None with no match. + """ + for pattern in patterns: + if fnmatch.fnmatchcase(name=value, pat=pattern): + return pattern + return None diff --git a/tests/unit/utils/test_utils.py b/tests/unit/utils/test_utils.py index c833aa677..47b03061e 100644 --- a/tests/unit/utils/test_utils.py +++ b/tests/unit/utils/test_utils.py @@ -1084,3 +1084,16 @@ class TestParsePoint: utils.parse_point(s) except ValueError as e: print(e) + + +@pytest.mark.parametrize("patterns, value, expected", [ + ([], "test", None), # no patterns + (["TEST"], "test", None), # case sensitive + (["test"], "test", "test"), # trivial match + (["test1", "test2", "test3"], "test2", "test2"), # multiple patterns + (["test*", "other*"], "testbla", "test*"), # glob match + (["t*", "test*"], "test", "t*"), # first match + (["test*", "t*"], "test", "test*"), # first match +]) +def test_match_globs(patterns, value, expected): + assert utils.match_globs(patterns, value) == expected -- cgit v1.2.3-54-g00ecf