5 Utility functions for the ConditionsDB command line interface
9 from basf2
import B2ERROR
10 from .
import PayloadInformation
15 Class to filter a list of tags/payloads/iovs with a common interface, that
16 is same set of parameters and easy handling of checking.
18 This class defines -f,--filter/-e,--exclude/-r/--regex parameters which will
19 be added to a :class:`argparse.ArgumentParser` when calling `add_arguments`.
23 """initilization, just remember the arguments or parser"""
34 Add arguments to the parser
37 name: Name of the objects to be filtered in the help text
39 self.
_args.add_argument(
"-f",
"--filter", metavar=
"SEARCHTERM",
40 help=
"only {} matching this pattern will be "
41 "included. Pattern is case insensitive".format(name))
42 self.
_args.add_argument(
"-e",
"--exclude", default=
None, type=str,
43 help=
"{} matching this pattern will be excluded. "
44 "Pattern is case insensitive".format(name))
45 self.
_args.add_argument(
"-r",
"--regex", action=
"store_true", default=
False,
46 help=
"if given, --filter or --exclude options will be "
47 "interpreted as a python regular expression "
48 "(see https://docs.python.org/3/library/re.html)")
52 Convert to a text representation of the form ' [regex filter=TERM exclude=TERM]'.
54 The space in the beginnin is intentional to allow easy adding to a
55 description without extra spaces
57 If no filtering is performed an empty string is returned. If the
58 patterns are non-regex (without --regex), the regex will be missing in
59 the string. If one of the --filter/--exclude option was not given, that
60 part is removed from the string
63 for attribute
in [
"filter",
"exclude"]:
64 term = getattr(self.
_args, attribute,
None)
66 text.append(
"{}={}".format(attribute, term))
69 if getattr(self.
_args,
"regex",
False):
70 text.insert(0,
"regex")
72 return " [{}]".format(
" ".join(text))
76 Check if the arguments are valid (only if --regex is given) and compile into
77 regular expressions. If False is returned there was an error with the
80 for attribute
in [
"filter",
"exclude"]:
81 term = getattr(self.
_args, attribute,
None)
84 if not getattr(self.
_args,
"regex",
False):
85 term = re.escape(term)
86 setattr(self,
"_"+attribute, re.compile(term, re.IGNORECASE))
87 except Exception
as e:
88 B2ERROR(
"--{}: '{}' is not a valid regular expression: {}'".format(attribute, term, e))
94 Check an item. True is returned if it should be kept, False if it is
95 filtered out or excluded.
98 item: item to be filtered