• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Copyright (c) 2012 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5import ConfigParser
6import error
7
8
9def forgive_config_error(func):
10    """A decorator to make ConfigParser get*() functions return None on fail."""
11    def wrapper(*args, **kwargs):
12        try:
13            return func(*args, **kwargs)
14        except ConfigParser.Error:
15            return None
16        except ValueError as e:
17            raise error.MalformedConfigEntry(str(e))
18    return wrapper
19
20
21class ForgivingConfigParser(ConfigParser.SafeConfigParser):
22    """A SafeConfigParser that returns None on any error in get*().
23
24    Also implements reread(), which allows any already-read-in configs to be
25    reloaded from disk on-demand.
26
27    Note that I can't use super() here, as ConfigParser.SafeConfigParser
28    isn't a new-style class.
29
30    @var _cached_config_file_names: the names of the config files last read().
31    """
32
33
34    def __init__(self):
35        ConfigParser.SafeConfigParser.__init__(self)
36        self._cached_config_file_names = ''
37
38
39    def read(self, filenames):
40        """Caches filenames, then performs normal read() functionality.
41
42        @param filenames: string or iterable.  The files to read.
43        @return list of files that could not be read, as per super class.
44        """
45        to_return = ConfigParser.SafeConfigParser.read(self, filenames)
46        self._cached_config_file_names = filenames
47        return to_return
48
49
50    def reread(self):
51        """Clear all sections, re-read configs from disk."""
52        for section in self.sections():
53            self.remove_section(section)
54        return ConfigParser.SafeConfigParser.read(
55            self, self._cached_config_file_names)
56
57
58    @forgive_config_error
59    def getstring(self, section, option):
60        """Can't override get(), as it breaks the other getters to have get()
61        return None sometimes."""
62        return ConfigParser.SafeConfigParser.get(self, section, option)
63
64
65    @forgive_config_error
66    def getint(self, section, option):
67        return ConfigParser.SafeConfigParser.getint(self, section, option)
68
69
70    @forgive_config_error
71    def getfloat(self, section, option):
72        return ConfigParser.SafeConfigParser.getfloat(self, section, option)
73
74
75    @forgive_config_error
76    def getboolean(self, section, option):
77        return ConfigParser.SafeConfigParser.getboolean(self, section, option)
78