CustomConfig.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. # Copyright (C) 2003-2016 John Goerzen & contributors
  2. #
  3. # This program is free software; you can redistribute it and/or modify
  4. # it under the terms of the GNU General Public License as published by
  5. # the Free Software Foundation; either version 2 of the License, or
  6. # (at your option) any later version.
  7. #
  8. # This program is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with this program; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. import os
  17. import re
  18. from sys import exc_info
  19. from configparser import ConfigParser, Error
  20. from offlineimap.localeval import LocalEval
  21. class CustomConfigParser(ConfigParser):
  22. def __init__(self):
  23. ConfigParser.__init__(self)
  24. self.localeval = None
  25. def getdefault(self, section, option, default, *args, **kwargs):
  26. """Same as config.get, but returns the value of `default`
  27. if there is no such option specified."""
  28. if self.has_option(section, option):
  29. return self.get(*(section, option) + args, **kwargs)
  30. else:
  31. return default
  32. def getdefaultint(self, section, option, default, *args, **kwargs):
  33. """Same as config.getint, but returns the value of `default`
  34. if there is no such option specified."""
  35. if self.has_option(section, option):
  36. return self.getint(*(section, option) + args, **kwargs)
  37. else:
  38. return default
  39. def getdefaultfloat(self, section, option, default, *args, **kwargs):
  40. """Same as config.getfloat, but returns the value of `default`
  41. if there is no such option specified."""
  42. if self.has_option(section, option):
  43. return self.getfloat(*(section, option) + args, **kwargs)
  44. else:
  45. return default
  46. def getdefaultboolean(self, section, option, default, *args, **kwargs):
  47. """Same as config.getboolean, but returns the value of `default`
  48. if there is no such option specified."""
  49. if self.has_option(section, option):
  50. return self.getboolean(*(section, option) + args, **kwargs)
  51. else:
  52. return default
  53. def getlist(self, section, option, separator_re):
  54. """Parses option as the list of values separated
  55. by the given regexp."""
  56. try:
  57. val = self.get(section, option).strip()
  58. return re.split(separator_re, val)
  59. except re.error as e:
  60. raise Error("Bad split regexp '%s': %s" %
  61. (separator_re, e), exc_info()[2])
  62. def getdefaultlist(self, section, option, default, separator_re):
  63. """Same as getlist, but returns the value of `default`
  64. if there is no such option specified."""
  65. if self.has_option(section, option):
  66. return self.getlist(*(section, option, separator_re))
  67. else:
  68. return default
  69. def getmetadatadir(self):
  70. xforms = [os.path.expanduser, os.path.expandvars]
  71. d = self.getdefault("general", "metadata", "~/.offlineimap")
  72. metadatadir = self.apply_xforms(d, xforms)
  73. if not os.path.exists(metadatadir):
  74. os.mkdir(metadatadir, 0o700)
  75. return metadatadir
  76. def getlocaleval(self):
  77. # We already loaded pythonfile, so return this copy.
  78. if self.localeval is not None:
  79. return self.localeval
  80. xforms = [os.path.expanduser, os.path.expandvars]
  81. if self.has_option("general", "pythonfile"):
  82. path = self.get("general", "pythonfile")
  83. path = self.apply_xforms(path, xforms)
  84. else:
  85. path = None
  86. self.localeval = LocalEval(path)
  87. return self.localeval
  88. def getsectionlist(self, key):
  89. """Returns a list of sections that start with (str) key + " ".
  90. That is, if key is "Account", returns all section names that
  91. start with "Account ", but strips off the "Account ".
  92. For instance, for "Account Test", returns "Test"."""
  93. key = key + ' '
  94. return [x[len(key):] for x in self.sections()
  95. if x.startswith(key)]
  96. def set_if_not_exists(self, section, option, value):
  97. """Set a value if it does not exist yet.
  98. This allows to set default if the user has not explicitly
  99. configured anything."""
  100. if not self.has_option(section, option):
  101. self.set(section, option, value)
  102. def apply_xforms(self, string, transforms):
  103. """Applies set of transformations to a string.
  104. Arguments:
  105. - string: source string; if None, then no processing will
  106. take place.
  107. - transforms: iterable that returns transformation function
  108. on each turn.
  109. Returns transformed string."""
  110. if string is None:
  111. return None
  112. for f in transforms:
  113. string = f(string)
  114. return string
  115. def CustomConfigDefault():
  116. """Just a constant that won't occur anywhere else.
  117. This allows us to differentiate if the user has passed in any
  118. default value to the getconf* functions in ConfigHelperMixin
  119. derived classes."""
  120. pass
  121. class ConfigHelperMixin:
  122. """Allow comfortable retrieving of config values pertaining
  123. to a section.
  124. If a class inherits from cls:`ConfigHelperMixin`, it needs
  125. to provide 2 functions:
  126. - meth:`getconfig` (returning a CustomConfigParser object)
  127. - and meth:`getsection` (returning a string which represents
  128. the section to look up).
  129. All calls to getconf* will then return the configuration values
  130. for the CustomConfigParser object in the specific section.
  131. """
  132. def _confighelper_runner(self, option, default, defaultfunc, mainfunc, *args):
  133. """Returns configuration or default value for option
  134. that contains in section identified by getsection().
  135. Arguments:
  136. - option: name of the option to retrieve;
  137. - default: governs which function we will call.
  138. * When CustomConfigDefault is passed, we will call
  139. the mainfunc.
  140. * When any other value is passed, we will call
  141. the defaultfunc and the value of `default` will
  142. be passed as the third argument to this function.
  143. - defaultfunc and mainfunc: processing helpers.
  144. - args: additional trailing arguments that will be passed
  145. to all processing helpers.
  146. """
  147. lst = [self.getsection(), option]
  148. if default == CustomConfigDefault:
  149. return mainfunc(*(lst + list(args)))
  150. else:
  151. lst.append(default)
  152. return defaultfunc(*(lst + list(args)))
  153. def getconfig(self):
  154. """Returns CustomConfigParser object that we will use
  155. for all our actions.
  156. Must be overriden in all classes that use this mix-in."""
  157. raise NotImplementedError("ConfigHelperMixin.getconfig() "
  158. "is to be overriden")
  159. def getsection(self):
  160. """Returns name of configuration section in which our
  161. class keeps its configuration.
  162. Must be overriden in all classes that use this mix-in."""
  163. raise NotImplementedError("ConfigHelperMixin.getsection() "
  164. "is to be overriden")
  165. def getconf(self, option, default=CustomConfigDefault):
  166. """Retrieves string from the configuration.
  167. Arguments:
  168. - option: option name whose value is to be retrieved;
  169. - default: default return value if no such option
  170. exists.
  171. """
  172. return self._confighelper_runner(option, default,
  173. self.getconfig().getdefault,
  174. self.getconfig().get)
  175. def getconf_xform(self, option, xforms, default=CustomConfigDefault):
  176. """Retrieves string from the configuration transforming the result.
  177. Arguments:
  178. - option: option name whose value is to be retrieved;
  179. - xforms: iterable that returns transform functions
  180. to be applied to the value of the option,
  181. both retrieved and default one;
  182. - default: default value for string if no such option
  183. exists.
  184. """
  185. value = self.getconf(option, default)
  186. return self.getconfig().apply_xforms(value, xforms)
  187. def getconfboolean(self, option, default=CustomConfigDefault):
  188. """Retrieves boolean value from the configuration.
  189. Arguments:
  190. - option: option name whose value is to be retrieved;
  191. - default: default return value if no such option
  192. exists.
  193. """
  194. return self._confighelper_runner(option, default,
  195. self.getconfig().getdefaultboolean,
  196. self.getconfig().getboolean)
  197. def getconfint(self, option, default=CustomConfigDefault):
  198. """
  199. Retrieves integer value from the configuration.
  200. Arguments:
  201. - option: option name whose value is to be retrieved;
  202. - default: default return value if no such option
  203. exists.
  204. """
  205. return self._confighelper_runner(option, default,
  206. self.getconfig().getdefaultint,
  207. self.getconfig().getint)
  208. def getconffloat(self, option, default=CustomConfigDefault):
  209. """Retrieves floating-point value from the configuration.
  210. Arguments:
  211. - option: option name whose value is to be retrieved;
  212. - default: default return value if no such option
  213. exists.
  214. """
  215. return self._confighelper_runner(option, default,
  216. self.getconfig().getdefaultfloat,
  217. self.getconfig().getfloat)
  218. def getconflist(self, option, separator_re,
  219. default=CustomConfigDefault):
  220. """Retrieves strings from the configuration and splits it
  221. into the list of strings.
  222. Arguments:
  223. - option: option name whose value is to be retrieved;
  224. - separator_re: regular expression for separator
  225. to be used for split operation;
  226. - default: default return value if no such option
  227. exists.
  228. """
  229. return self._confighelper_runner(option, default,
  230. self.getconfig().getdefaultlist,
  231. self.getconfig().getlist, separator_re)