settings.py 11 KB

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