settings.py 12 KB

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