12 Utility functions for the ConditionsDB command line interface
16 from basf2
import B2ERROR
21 Class to filter a list of tags/payloads/iovs with a common interface, that
22 is same set of parameters and easy handling of checking.
24 This class defines -f,--filter/-e,--exclude/-r/--regex parameters which will
25 be added to a :class:`argparse.ArgumentParser` when calling `add_arguments`.
29 """initialization, just remember the arguments or parser"""
40 Add arguments to the parser
43 name: Name of the objects to be filtered in the help text
45 self.
_args_args.add_argument(
"-f",
"--filter", metavar=
"SEARCHTERM",
46 help=
"only {} matching this pattern will be "
47 "included. Pattern is case insensitive".format(name))
48 self.
_args_args.add_argument(
"-e",
"--exclude", default=
None, type=str,
49 help=
"{} matching this pattern will be excluded. "
50 "Pattern is case insensitive".format(name))
51 self.
_args_args.add_argument(
"-r",
"--regex", action=
"store_true", default=
False,
52 help=
"if given, --filter or --exclude options will be "
53 "interpreted as a python regular expression "
54 "(see https://docs.python.org/3/library/re.html)")
58 Convert to a text representation of the form ' [regex filter=TERM exclude=TERM]'.
60 The space in the beginning is intentional to allow easy adding to a
61 description without extra spaces
63 If no filtering is performed an empty string is returned. If the
64 patterns are non-regex (without --regex), the regex will be missing in
65 the string. If one of the --filter/--exclude option was not given, that
66 part is removed from the string
69 for attribute
in [
"filter",
"exclude"]:
70 term = getattr(self.
_args_args, attribute,
None)
72 text.append(f
"{attribute}={term}")
75 if getattr(self.
_args_args,
"regex",
False):
76 text.insert(0,
"regex")
78 return " [{}]".format(
" ".join(text))
82 Check if the arguments are valid (only if --regex is given) and compile into
83 regular expressions. If False is returned there was an error with the
86 for attribute
in [
"filter",
"exclude"]:
87 term = getattr(self.
_args_args, attribute,
None)
90 if not getattr(self.
_args_args,
"regex",
False):
91 term = re.escape(term)
92 setattr(self,
"_"+attribute, re.compile(term, re.IGNORECASE))
93 except Exception
as e:
94 B2ERROR(f
"--{attribute}: '{term}' is not a valid regular expression: {e}'")
100 Check an item. True is returned if it should be kept, False if it is
101 filtered out or excluded.
104 item: item to be filtered
106 if self.
_filter_filter
is not None and not self.
_filter_filter.search(item):
108 if self.
_exclude_exclude
is not None and self.
_exclude_exclude.search(item):
_args
arguments, either :class:argparse.ArgumentParser on initialization or :class:argparse....
def add_arguments(self, name)
_filter
regular expression for filtering items which don't match
_exclude
regular expression for excluding items which match
def check_arguments(self)