Belle II Software development
cli_utils.py
1#!/usr/bin/env python3
2
3
10
11"""
12Utility functions for the ConditionsDB command line interface
13"""
14
15import re
16from basf2 import B2ERROR
17
18
20 """
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.
23
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`.
26 """
27
28 def __init__(self, args):
29 """initialization, just remember the arguments or parser"""
30
32 self._args = args
33
34 self._filter = None
35
36 self._exclude = None
37
38 def add_arguments(self, name):
39 """
40 Add arguments to the parser
41
42 Parameters:
43 name: Name of the objects to be filtered in the help text
44 """
45 self._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.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.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)")
53
54 def __str__(self):
55 """
56 Convert to a text representation of the form ' [regex filter=TERM exclude=TERM]'.
57
58 The space in the beginning is intentional to allow easy adding to a
59 description without extra spaces
60
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
65 """
66 text = []
67 for attribute in ["filter", "exclude"]:
68 term = getattr(self._args, attribute, None)
69 if term is not None:
70 text.append(f"{attribute}={term}")
71 if not text:
72 return ""
73 if getattr(self._args, "regex", False):
74 text.insert(0, "regex")
75
76 return f" [{' '.join(text)}]"
77
78 def check_arguments(self):
79 """
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
82 regular expressions.
83 """
84 for attribute in ["filter", "exclude"]:
85 term = getattr(self._args, attribute, None)
86 if term is not None:
87 try:
88 if not getattr(self._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}'")
93 return False
94 return True
95
96 def check(self, item):
97 """
98 Check an item. True is returned if it should be kept, False if it is
99 filtered out or excluded.
100
101 Parameters:
102 item: item to be filtered
103 """
104 if self._filter is not None and not self._filter.search(item):
105 return False
106 if self._exclude is not None and self._exclude.search(item):
107 return False
108 return True
_args
arguments, either :class:argparse.ArgumentParser on initialization or :class:argparse....
Definition: cli_utils.py:32
_filter
regular expression for filtering items which don't match
Definition: cli_utils.py:34
_exclude
regular expression for excluding items which match
Definition: cli_utils.py:36