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=f
"only {name} matching this pattern will be included. Pattern is case insensitive")
47 self.
_args_args.add_argument(
"-e",
"--exclude", default=
None, type=str,
48 help=f
"{name} matching this pattern will be excluded. Pattern is case insensitive")
49 self.
_args_args.add_argument(
"-r",
"--regex", action=
"store_true", default=
False,
50 help=
"if given, --filter or --exclude options will be "
51 "interpreted as a python regular expression "
52 "(see https://docs.python.org/3/library/re.html)")
56 Convert to a text representation of the form ' [regex filter=TERM exclude=TERM]'.
58 The space in the beginning is intentional to allow easy adding to a
59 description without extra spaces
61 If no filtering is performed an empty string is returned. If the
62 patterns are non-regex (without --regex), the regex will be missing in
63 the string. If one of the --filter/--exclude option was not given, that
64 part is removed from the string
67 for attribute
in [
"filter",
"exclude"]:
68 term = getattr(self.
_args_args, attribute,
None)
70 text.append(f
"{attribute}={term}")
73 if getattr(self.
_args_args,
"regex",
False):
74 text.insert(0,
"regex")
76 return f
" [{' '.join(text)}]"
80 Check if the arguments are valid (only if --regex is given) and compile into
81 regular expressions. If False is returned there was an error with the
84 for attribute
in [
"filter",
"exclude"]:
85 term = getattr(self.
_args_args, attribute,
None)
88 if not getattr(self.
_args_args,
"regex",
False):
89 term = re.escape(term)
90 setattr(self,
"_"+attribute, re.compile(term, re.IGNORECASE))
91 except Exception
as e:
92 B2ERROR(f
"--{attribute}: '{term}' is not a valid regular expression: {e}'")
98 Check an item. True is returned if it should be kept, False if it is
99 filtered out or excluded.
102 item: item to be filtered
104 if self.
_filter_filter
is not None and not self.
_filter_filter.search(item):
106 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)