Home | History | Annotate | Download | only in tko
      1 import os
      2 
      3 class PreconfigManager(object):
      4     _preconfigs = {}
      5     _is_init = False
      6 
      7     def _get_preconfig_path(self, suffix):
      8         """\
      9         Get the absolute path to a prefix directory or file.
     10 
     11         suffix: list of suffixes after the 'preconfigs' directory to navigate to
     12             E.g., ['metrics', 'abc'] gives the path to
     13             <tko>/preconfigs/metrics/abc
     14         """
     15         rel_path = os.path.join(os.path.dirname(__file__), 'preconfigs',
     16                                 *suffix)
     17         return os.path.abspath(rel_path)
     18 
     19 
     20     def _init_preconfigs(self):
     21         """\
     22         Read the names of all the preconfigs from disk and store them in the
     23         _preconfigs dictionary.
     24         """
     25         if not self._is_init:
     26             # Read the data
     27             self._preconfigs['metrics'] = dict.fromkeys(
     28                 os.listdir(self._get_preconfig_path(['metrics'])))
     29             self._preconfigs['qual'] = dict.fromkeys(
     30                 os.listdir(self._get_preconfig_path(['qual'])))
     31             self._is_init = True
     32 
     33     def _read_preconfig(self, name, type):
     34         """\
     35         Populate the _preconfigs dictionary entry for the preconfig described
     36         by the given parameters.  If the preconfig has already been loaded,
     37         do nothing.
     38 
     39         name: specific name of the preconfig
     40         type: 'metrics' or 'qual'
     41         """
     42         if self._preconfigs[type][name] is not None:
     43             return
     44 
     45         self._preconfigs[type][name] = {}
     46         path = self._get_preconfig_path([type, name])
     47         config = open(path)
     48         try:
     49             for line in config:
     50                 parts = line.split(':')
     51                 self._preconfigs[type][name][parts[0]] = parts[1].strip()
     52         finally:
     53             config.close()
     54 
     55 
     56     def get_preconfig(self, name, type):
     57         self._init_preconfigs()
     58         self._read_preconfig(name, type)
     59         return self._preconfigs[type][name]
     60 
     61 
     62     def all_preconfigs(self):
     63         self._init_preconfigs()
     64         return dict(self._preconfigs)
     65 
     66 
     67 manager = PreconfigManager()
     68