Belle II Software  release-05-02-19
cli_utils.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 
4 """
5 Utility functions for the ConditionsDB command line interface
6 """
7 
8 import re
9 from basf2 import B2ERROR
10 from . import PayloadInformation
11 
12 
13 class ItemFilter:
14  """
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.
17 
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`.
20  """
21 
22  def __init__(self, args):
23  """initilization, just remember the arguments or parser"""
24 
26  self._args = args
27 
28  self._filter = None
29 
30  self._exclude = None
31 
32  def add_arguments(self, name):
33  """
34  Add arguments to the parser
35 
36  Parameters:
37  name: Name of the objects to be filtered in the help text
38  """
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)")
49 
50  def __str__(self):
51  """
52  Convert to a text representation of the form ' [regex filter=TERM exclude=TERM]'.
53 
54  The space in the beginnin is intentional to allow easy adding to a
55  description without extra spaces
56 
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
61  """
62  text = []
63  for attribute in ["filter", "exclude"]:
64  term = getattr(self._args, attribute, None)
65  if term is not None:
66  text.append("{}={}".format(attribute, term))
67  if not text:
68  return ""
69  if getattr(self._args, "regex", False):
70  text.insert(0, "regex")
71 
72  return " [{}]".format(" ".join(text))
73 
74  def check_arguments(self):
75  """
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
78  regular expressions.
79  """
80  for attribute in ["filter", "exclude"]:
81  term = getattr(self._args, attribute, None)
82  if term is not None:
83  try:
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))
89  return False
90  return True
91 
92  def check(self, item):
93  """
94  Check an item. True is returned if it should be kept, False if it is
95  filtered out or excluded.
96 
97  Parameters:
98  item: item to be filtered
99  """
100  if self._filter is not None and not self._filter.search(item):
101  return False
102  if self._exclude is not None and self._exclude.search(item):
103  return False
104  return True
conditions_db.cli_utils.ItemFilter.__str__
def __str__(self)
Definition: cli_utils.py:50
conditions_db.cli_utils.ItemFilter.check_arguments
def check_arguments(self)
Definition: cli_utils.py:74
conditions_db.cli_utils.ItemFilter.__init__
def __init__(self, args)
Definition: cli_utils.py:22
conditions_db.cli_utils.ItemFilter._filter
_filter
regular expression for filtering items which don't match
Definition: cli_utils.py:28
conditions_db.cli_utils.ItemFilter._args
_args
arguments, either :class:argparse.ArgumentParser on initialization or :class:argparse....
Definition: cli_utils.py:26
conditions_db.cli_utils.ItemFilter
Definition: cli_utils.py:13
conditions_db.cli_utils.ItemFilter._exclude
_exclude
regular expression for excluding items which match
Definition: cli_utils.py:30
conditions_db.cli_utils.ItemFilter.check
def check(self, item)
Definition: cli_utils.py:92
conditions_db.cli_utils.ItemFilter.add_arguments
def add_arguments(self, name)
Definition: cli_utils.py:32