settings.py 8.0 KB

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