settings.py 11 KB

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