settings.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. # Copyright (c) 2011 The Chromium OS Authors.
  2. #
  3. # See file CREDITS for list of people who contributed to this
  4. # project.
  5. #
  6. # This program is free software; you can redistribute it and/or
  7. # modify it under the terms of the GNU General Public License as
  8. # published by the Free Software Foundation; either version 2 of
  9. # the License, or (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  19. # MA 02111-1307 USA
  20. #
  21. import ConfigParser
  22. import os
  23. import re
  24. import command
  25. import gitutil
  26. """Default settings per-project.
  27. These are used by _ProjectConfigParser. Settings names should match
  28. the "dest" of the option parser from patman.py.
  29. """
  30. _default_settings = {
  31. "u-boot": {},
  32. "linux": {
  33. "process_tags": "False",
  34. }
  35. }
  36. class _ProjectConfigParser(ConfigParser.SafeConfigParser):
  37. """ConfigParser that handles projects.
  38. There are two main goals of this class:
  39. - Load project-specific default settings.
  40. - Merge general default settings/aliases with project-specific ones.
  41. # Sample config used for tests below...
  42. >>> import StringIO
  43. >>> sample_config = '''
  44. ... [alias]
  45. ... me: Peter P. <likesspiders@example.com>
  46. ... enemies: Evil <evil@example.com>
  47. ...
  48. ... [sm_alias]
  49. ... enemies: Green G. <ugly@example.com>
  50. ...
  51. ... [sm2_alias]
  52. ... enemies: Doc O. <pus@example.com>
  53. ...
  54. ... [settings]
  55. ... am_hero: True
  56. ... '''
  57. # Check to make sure that bogus project gets general alias.
  58. >>> config = _ProjectConfigParser("zzz")
  59. >>> config.readfp(StringIO.StringIO(sample_config))
  60. >>> config.get("alias", "enemies")
  61. 'Evil <evil@example.com>'
  62. # Check to make sure that alias gets overridden by project.
  63. >>> config = _ProjectConfigParser("sm")
  64. >>> config.readfp(StringIO.StringIO(sample_config))
  65. >>> config.get("alias", "enemies")
  66. 'Green G. <ugly@example.com>'
  67. # Check to make sure that settings get merged with project.
  68. >>> config = _ProjectConfigParser("linux")
  69. >>> config.readfp(StringIO.StringIO(sample_config))
  70. >>> sorted(config.items("settings"))
  71. [('am_hero', 'True'), ('process_tags', 'False')]
  72. # Check to make sure that settings works with unknown project.
  73. >>> config = _ProjectConfigParser("unknown")
  74. >>> config.readfp(StringIO.StringIO(sample_config))
  75. >>> sorted(config.items("settings"))
  76. [('am_hero', 'True')]
  77. """
  78. def __init__(self, project_name):
  79. """Construct _ProjectConfigParser.
  80. In addition to standard SafeConfigParser initialization, this also loads
  81. project defaults.
  82. Args:
  83. project_name: The name of the project.
  84. """
  85. self._project_name = project_name
  86. ConfigParser.SafeConfigParser.__init__(self)
  87. # Update the project settings in the config based on
  88. # the _default_settings global.
  89. project_settings = "%s_settings" % project_name
  90. if not self.has_section(project_settings):
  91. self.add_section(project_settings)
  92. project_defaults = _default_settings.get(project_name, {})
  93. for setting_name, setting_value in project_defaults.iteritems():
  94. self.set(project_settings, setting_name, setting_value)
  95. def get(self, section, option, *args, **kwargs):
  96. """Extend SafeConfigParser to try project_section before section.
  97. Args:
  98. See SafeConfigParser.
  99. Returns:
  100. See SafeConfigParser.
  101. """
  102. try:
  103. return ConfigParser.SafeConfigParser.get(
  104. self, "%s_%s" % (self._project_name, section), option,
  105. *args, **kwargs
  106. )
  107. except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
  108. return ConfigParser.SafeConfigParser.get(
  109. self, section, option, *args, **kwargs
  110. )
  111. def items(self, section, *args, **kwargs):
  112. """Extend SafeConfigParser to add project_section to section.
  113. Args:
  114. See SafeConfigParser.
  115. Returns:
  116. See SafeConfigParser.
  117. """
  118. project_items = []
  119. has_project_section = False
  120. top_items = []
  121. # Get items from the project section
  122. try:
  123. project_items = ConfigParser.SafeConfigParser.items(
  124. self, "%s_%s" % (self._project_name, section), *args, **kwargs
  125. )
  126. has_project_section = True
  127. except ConfigParser.NoSectionError:
  128. pass
  129. # Get top-level items
  130. try:
  131. top_items = ConfigParser.SafeConfigParser.items(
  132. self, section, *args, **kwargs
  133. )
  134. except ConfigParser.NoSectionError:
  135. # If neither section exists raise the error on...
  136. if not has_project_section:
  137. raise
  138. item_dict = dict(top_items)
  139. item_dict.update(project_items)
  140. return item_dict.items()
  141. def ReadGitAliases(fname):
  142. """Read a git alias file. This is in the form used by git:
  143. alias uboot u-boot@lists.denx.de
  144. alias wd Wolfgang Denk <wd@denx.de>
  145. Args:
  146. fname: Filename to read
  147. """
  148. try:
  149. fd = open(fname, 'r')
  150. except IOError:
  151. print "Warning: Cannot find alias file '%s'" % fname
  152. return
  153. re_line = re.compile('alias\s+(\S+)\s+(.*)')
  154. for line in fd.readlines():
  155. line = line.strip()
  156. if not line or line[0] == '#':
  157. continue
  158. m = re_line.match(line)
  159. if not m:
  160. print "Warning: Alias file line '%s' not understood" % line
  161. continue
  162. list = alias.get(m.group(1), [])
  163. for item in m.group(2).split(','):
  164. item = item.strip()
  165. if item:
  166. list.append(item)
  167. alias[m.group(1)] = list
  168. fd.close()
  169. def CreatePatmanConfigFile(config_fname):
  170. """Creates a config file under $(HOME)/.patman if it can't find one.
  171. Args:
  172. config_fname: Default config filename i.e., $(HOME)/.patman
  173. Returns:
  174. None
  175. """
  176. name = gitutil.GetDefaultUserName()
  177. if name == None:
  178. name = raw_input("Enter name: ")
  179. email = gitutil.GetDefaultUserEmail()
  180. if email == None:
  181. email = raw_input("Enter email: ")
  182. try:
  183. f = open(config_fname, 'w')
  184. except IOError:
  185. print "Couldn't create patman config file\n"
  186. raise
  187. print >>f, "[alias]\nme: %s <%s>" % (name, email)
  188. f.close();
  189. def _UpdateDefaults(parser, config):
  190. """Update the given OptionParser defaults based on config.
  191. We'll walk through all of the settings from the parser
  192. For each setting we'll look for a default in the option parser.
  193. If it's found we'll update the option parser default.
  194. The idea here is that the .patman file should be able to update
  195. defaults but that command line flags should still have the final
  196. say.
  197. Args:
  198. parser: An instance of an OptionParser whose defaults will be
  199. updated.
  200. config: An instance of _ProjectConfigParser that we will query
  201. for settings.
  202. """
  203. defaults = parser.get_default_values()
  204. for name, val in config.items('settings'):
  205. if hasattr(defaults, name):
  206. default_val = getattr(defaults, name)
  207. if isinstance(default_val, bool):
  208. val = config.getboolean('settings', name)
  209. elif isinstance(default_val, int):
  210. val = config.getint('settings', name)
  211. parser.set_default(name, val)
  212. else:
  213. print "WARNING: Unknown setting %s" % name
  214. def Setup(parser, project_name, config_fname=''):
  215. """Set up the settings module by reading config files.
  216. Args:
  217. parser: The parser to update
  218. project_name: Name of project that we're working on; we'll look
  219. for sections named "project_section" as well.
  220. config_fname: Config filename to read ('' for default)
  221. """
  222. config = _ProjectConfigParser(project_name)
  223. if config_fname == '':
  224. config_fname = '%s/.patman' % os.getenv('HOME')
  225. if not os.path.exists(config_fname):
  226. print "No config file found ~/.patman\nCreating one...\n"
  227. CreatePatmanConfigFile(config_fname)
  228. config.read(config_fname)
  229. for name, value in config.items('alias'):
  230. alias[name] = value.split(',')
  231. _UpdateDefaults(parser, config)
  232. # These are the aliases we understand, indexed by alias. Each member is a list.
  233. alias = {}
  234. if __name__ == "__main__":
  235. import doctest
  236. doctest.testmod()