Belle II Software  release-08-01-10
cli_utils.py
1 #!/usr/bin/env python3
2 
3 
10 
11 """
12 Utility functions for the ConditionsDB command line interface
13 """
14 
15 import re
16 from basf2 import B2ERROR
17 
18 
19 class ItemFilter:
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 = args
33 
34  self._filter_filter = None
35 
36  self._exclude_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_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)")
55 
56  def __str__(self):
57  """
58  Convert to a text representation of the form ' [regex filter=TERM exclude=TERM]'.
59 
60  The space in the beginning is intentional to allow easy adding to a
61  description without extra spaces
62 
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
67  """
68  text = []
69  for attribute in ["filter", "exclude"]:
70  term = getattr(self._args_args, attribute, None)
71  if term is not None:
72  text.append(f"{attribute}={term}")
73  if not text:
74  return ""
75  if getattr(self._args_args, "regex", False):
76  text.insert(0, "regex")
77 
78  return " [{}]".format(" ".join(text))
79 
80  def check_arguments(self):
81  """
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
84  regular expressions.
85  """
86  for attribute in ["filter", "exclude"]:
87  term = getattr(self._args_args, attribute, None)
88  if term is not None:
89  try:
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}'")
95  return False
96  return True
97 
98  def check(self, item):
99  """
100  Check an item. True is returned if it should be kept, False if it is
101  filtered out or excluded.
102 
103  Parameters:
104  item: item to be filtered
105  """
106  if self._filter_filter is not None and not self._filter_filter.search(item):
107  return False
108  if self._exclude_exclude is not None and self._exclude_exclude.search(item):
109  return False
110  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