settings.py 10 KB

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