Development of an internal social media platform with personalised dashboards for students
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

config.py 32KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855
  1. # -*- coding: utf-8 -*-
  2. # Copyright (c) 2006-2010, 2012-2014 LOGILAB S.A. (Paris, FRANCE) <contact@logilab.fr>
  3. # Copyright (c) 2008 pyves@crater.logilab.fr <pyves@crater.logilab.fr>
  4. # Copyright (c) 2010 Julien Jehannet <julien.jehannet@logilab.fr>
  5. # Copyright (c) 2013 Google, Inc.
  6. # Copyright (c) 2013 John McGehee <jmcgehee@altera.com>
  7. # Copyright (c) 2014-2017 Claudiu Popa <pcmanticore@gmail.com>
  8. # Copyright (c) 2014 Brett Cannon <brett@python.org>
  9. # Copyright (c) 2014 Arun Persaud <arun@nubati.net>
  10. # Copyright (c) 2015 Aru Sahni <arusahni@gmail.com>
  11. # Copyright (c) 2015 John Kirkham <jakirkham@gmail.com>
  12. # Copyright (c) 2015 Ionel Cristian Maries <contact@ionelmc.ro>
  13. # Copyright (c) 2016 Erik <erik.eriksson@yahoo.com>
  14. # Copyright (c) 2016 Alexander Todorov <atodorov@otb.bg>
  15. # Copyright (c) 2016 Moises Lopez <moylop260@vauxoo.com>
  16. # Copyright (c) 2017 hippo91 <guillaume.peillex@gmail.com>
  17. # Copyright (c) 2017 ahirnish <ahirnish@gmail.com>
  18. # Copyright (c) 2017 Łukasz Rogalski <rogalski.91@gmail.com>
  19. # Copyright (c) 2017 Ville Skyttä <ville.skytta@iki.fi>
  20. # Licensed under the GPL: https://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  21. # For details: https://github.com/PyCQA/pylint/blob/master/COPYING
  22. """utilities for Pylint configuration :
  23. * pylintrc
  24. * pylint.d (PYLINTHOME)
  25. """
  26. from __future__ import print_function
  27. # TODO(cpopa): this module contains the logic for the
  28. # configuration parser and for the command line parser,
  29. # but it's really coupled to optparse's internals.
  30. # The code was copied almost verbatim from logilab.common,
  31. # in order to not depend on it anymore and it will definitely
  32. # need a cleanup. It could be completely reengineered as well.
  33. import contextlib
  34. import collections
  35. import copy
  36. import io
  37. import optparse
  38. import os
  39. import pickle
  40. import re
  41. import sys
  42. import time
  43. import configparser
  44. from six.moves import range
  45. from pylint import utils
  46. USER_HOME = os.path.expanduser('~')
  47. if 'PYLINTHOME' in os.environ:
  48. PYLINT_HOME = os.environ['PYLINTHOME']
  49. if USER_HOME == '~':
  50. USER_HOME = os.path.dirname(PYLINT_HOME)
  51. elif USER_HOME == '~':
  52. PYLINT_HOME = ".pylint.d"
  53. else:
  54. PYLINT_HOME = os.path.join(USER_HOME, '.pylint.d')
  55. def _get_pdata_path(base_name, recurs):
  56. base_name = base_name.replace(os.sep, '_')
  57. return os.path.join(PYLINT_HOME, "%s%s%s"%(base_name, recurs, '.stats'))
  58. def load_results(base):
  59. data_file = _get_pdata_path(base, 1)
  60. try:
  61. with open(data_file, _PICK_LOAD) as stream:
  62. return pickle.load(stream)
  63. except Exception: # pylint: disable=broad-except
  64. return {}
  65. if sys.version_info < (3, 0):
  66. _PICK_DUMP, _PICK_LOAD = 'w', 'r'
  67. else:
  68. _PICK_DUMP, _PICK_LOAD = 'wb', 'rb'
  69. def save_results(results, base):
  70. if not os.path.exists(PYLINT_HOME):
  71. try:
  72. os.mkdir(PYLINT_HOME)
  73. except OSError:
  74. print('Unable to create directory %s' % PYLINT_HOME, file=sys.stderr)
  75. data_file = _get_pdata_path(base, 1)
  76. try:
  77. with open(data_file, _PICK_DUMP) as stream:
  78. pickle.dump(results, stream)
  79. except (IOError, OSError) as ex:
  80. print('Unable to create file %s: %s' % (data_file, ex), file=sys.stderr)
  81. def find_pylintrc():
  82. """search the pylint rc file and return its path if it find it, else None
  83. """
  84. # is there a pylint rc file in the current directory ?
  85. if os.path.exists('pylintrc'):
  86. return os.path.abspath('pylintrc')
  87. if os.path.exists('.pylintrc'):
  88. return os.path.abspath('.pylintrc')
  89. if os.path.isfile('__init__.py'):
  90. curdir = os.path.abspath(os.getcwd())
  91. while os.path.isfile(os.path.join(curdir, '__init__.py')):
  92. curdir = os.path.abspath(os.path.join(curdir, '..'))
  93. if os.path.isfile(os.path.join(curdir, 'pylintrc')):
  94. return os.path.join(curdir, 'pylintrc')
  95. if os.path.isfile(os.path.join(curdir, '.pylintrc')):
  96. return os.path.join(curdir, '.pylintrc')
  97. if 'PYLINTRC' in os.environ and os.path.exists(os.environ['PYLINTRC']):
  98. pylintrc = os.environ['PYLINTRC']
  99. else:
  100. user_home = os.path.expanduser('~')
  101. if user_home == '~' or user_home == '/root':
  102. pylintrc = ".pylintrc"
  103. else:
  104. pylintrc = os.path.join(user_home, '.pylintrc')
  105. if not os.path.isfile(pylintrc):
  106. pylintrc = os.path.join(user_home, '.config', 'pylintrc')
  107. if not os.path.isfile(pylintrc):
  108. if os.path.isfile('/etc/pylintrc'):
  109. pylintrc = '/etc/pylintrc'
  110. else:
  111. pylintrc = None
  112. return pylintrc
  113. PYLINTRC = find_pylintrc()
  114. ENV_HELP = '''
  115. The following environment variables are used:
  116. * PYLINTHOME
  117. Path to the directory where the persistent for the run will be stored. If
  118. not found, it defaults to ~/.pylint.d/ or .pylint.d (in the current working
  119. directory).
  120. * PYLINTRC
  121. Path to the configuration file. See the documentation for the method used
  122. to search for configuration file.
  123. ''' % globals()
  124. class UnsupportedAction(Exception):
  125. """raised by set_option when it doesn't know what to do for an action"""
  126. def _multiple_choice_validator(choices, name, value):
  127. values = utils._check_csv(value)
  128. for csv_value in values:
  129. if csv_value not in choices:
  130. msg = "option %s: invalid value: %r, should be in %s"
  131. raise optparse.OptionValueError(msg % (name, csv_value, choices))
  132. return values
  133. def _choice_validator(choices, name, value):
  134. if value not in choices:
  135. msg = "option %s: invalid value: %r, should be in %s"
  136. raise optparse.OptionValueError(msg % (name, value, choices))
  137. return value
  138. # pylint: disable=unused-argument
  139. def _csv_validator(_, name, value):
  140. return utils._check_csv(value)
  141. # pylint: disable=unused-argument
  142. def _regexp_validator(_, name, value):
  143. if hasattr(value, 'pattern'):
  144. return value
  145. return re.compile(value)
  146. # pylint: disable=unused-argument
  147. def _regexp_csv_validator(_, name, value):
  148. return [_regexp_validator(_, name, val) for val in _csv_validator(_, name, value)]
  149. def _yn_validator(opt, _, value):
  150. if isinstance(value, int):
  151. return bool(value)
  152. if value in ('y', 'yes'):
  153. return True
  154. if value in ('n', 'no'):
  155. return False
  156. msg = "option %s: invalid yn value %r, should be in (y, yes, n, no)"
  157. raise optparse.OptionValueError(msg % (opt, value))
  158. def _non_empty_string_validator(opt, _, value):
  159. if not value:
  160. msg = "indent string can't be empty."
  161. raise optparse.OptionValueError(msg)
  162. return utils._unquote(value)
  163. VALIDATORS = {
  164. 'string': utils._unquote,
  165. 'int': int,
  166. 'regexp': re.compile,
  167. 'regexp_csv': _regexp_csv_validator,
  168. 'csv': _csv_validator,
  169. 'yn': _yn_validator,
  170. 'choice': lambda opt, name, value: _choice_validator(opt['choices'], name, value),
  171. 'multiple_choice': lambda opt, name, value: _multiple_choice_validator(opt['choices'],
  172. name, value),
  173. 'non_empty_string': _non_empty_string_validator,
  174. }
  175. def _call_validator(opttype, optdict, option, value):
  176. if opttype not in VALIDATORS:
  177. raise Exception('Unsupported type "%s"' % opttype)
  178. try:
  179. return VALIDATORS[opttype](optdict, option, value)
  180. except TypeError:
  181. try:
  182. return VALIDATORS[opttype](value)
  183. except Exception:
  184. raise optparse.OptionValueError('%s value (%r) should be of type %s' %
  185. (option, value, opttype))
  186. def _validate(value, optdict, name=''):
  187. """return a validated value for an option according to its type
  188. optional argument name is only used for error message formatting
  189. """
  190. try:
  191. _type = optdict['type']
  192. except KeyError:
  193. # FIXME
  194. return value
  195. return _call_validator(_type, optdict, name, value)
  196. def _level_options(group, outputlevel):
  197. return [option for option in group.option_list
  198. if (getattr(option, 'level', 0) or 0) <= outputlevel
  199. and option.help is not optparse.SUPPRESS_HELP]
  200. def _expand_default(self, option):
  201. """Patch OptionParser.expand_default with custom behaviour
  202. This will handle defaults to avoid overriding values in the
  203. configuration file.
  204. """
  205. if self.parser is None or not self.default_tag:
  206. return option.help
  207. optname = option._long_opts[0][2:]
  208. try:
  209. provider = self.parser.options_manager._all_options[optname]
  210. except KeyError:
  211. value = None
  212. else:
  213. optdict = provider.get_option_def(optname)
  214. optname = provider.option_attrname(optname, optdict)
  215. value = getattr(provider.config, optname, optdict)
  216. value = utils._format_option_value(optdict, value)
  217. if value is optparse.NO_DEFAULT or not value:
  218. value = self.NO_DEFAULT_VALUE
  219. return option.help.replace(self.default_tag, str(value))
  220. @contextlib.contextmanager
  221. def _patch_optparse():
  222. orig_default = optparse.HelpFormatter
  223. try:
  224. optparse.HelpFormatter.expand_default = _expand_default
  225. yield
  226. finally:
  227. optparse.HelpFormatter.expand_default = orig_default
  228. def _multiple_choices_validating_option(opt, name, value):
  229. return _multiple_choice_validator(opt.choices, name, value)
  230. class Option(optparse.Option):
  231. TYPES = optparse.Option.TYPES + ('regexp', 'regexp_csv', 'csv', 'yn',
  232. 'multiple_choice',
  233. 'non_empty_string')
  234. ATTRS = optparse.Option.ATTRS + ['hide', 'level']
  235. TYPE_CHECKER = copy.copy(optparse.Option.TYPE_CHECKER)
  236. TYPE_CHECKER['regexp'] = _regexp_validator
  237. TYPE_CHECKER['regexp_csv'] = _regexp_csv_validator
  238. TYPE_CHECKER['csv'] = _csv_validator
  239. TYPE_CHECKER['yn'] = _yn_validator
  240. TYPE_CHECKER['multiple_choice'] = _multiple_choices_validating_option
  241. TYPE_CHECKER['non_empty_string'] = _non_empty_string_validator
  242. def __init__(self, *opts, **attrs):
  243. optparse.Option.__init__(self, *opts, **attrs)
  244. if hasattr(self, "hide") and self.hide:
  245. self.help = optparse.SUPPRESS_HELP
  246. def _check_choice(self):
  247. if self.type in ("choice", "multiple_choice"):
  248. if self.choices is None:
  249. raise optparse.OptionError(
  250. "must supply a list of choices for type 'choice'", self)
  251. elif not isinstance(self.choices, (tuple, list)):
  252. raise optparse.OptionError(
  253. "choices must be a list of strings ('%s' supplied)"
  254. % str(type(self.choices)).split("'")[1], self)
  255. elif self.choices is not None:
  256. raise optparse.OptionError(
  257. "must not supply choices for type %r" % self.type, self)
  258. optparse.Option.CHECK_METHODS[2] = _check_choice
  259. def process(self, opt, value, values, parser):
  260. # First, convert the value(s) to the right type. Howl if any
  261. # value(s) are bogus.
  262. value = self.convert_value(opt, value)
  263. if self.type == 'named':
  264. existent = getattr(values, self.dest)
  265. if existent:
  266. existent.update(value)
  267. value = existent
  268. # And then take whatever action is expected of us.
  269. # This is a separate method to make life easier for
  270. # subclasses to add new actions.
  271. return self.take_action(
  272. self.action, self.dest, opt, value, values, parser)
  273. class OptionParser(optparse.OptionParser):
  274. def __init__(self, option_class, *args, **kwargs):
  275. optparse.OptionParser.__init__(self, option_class=Option, *args, **kwargs)
  276. def format_option_help(self, formatter=None):
  277. if formatter is None:
  278. formatter = self.formatter
  279. outputlevel = getattr(formatter, 'output_level', 0)
  280. formatter.store_option_strings(self)
  281. result = []
  282. result.append(formatter.format_heading("Options"))
  283. formatter.indent()
  284. if self.option_list:
  285. result.append(optparse.OptionContainer.format_option_help(self, formatter))
  286. result.append("\n")
  287. for group in self.option_groups:
  288. if group.level <= outputlevel and (
  289. group.description or _level_options(group, outputlevel)):
  290. result.append(group.format_help(formatter))
  291. result.append("\n")
  292. formatter.dedent()
  293. # Drop the last "\n", or the header if no options or option groups:
  294. return "".join(result[:-1])
  295. def _match_long_opt(self, opt):
  296. """Disable abbreviations."""
  297. if opt not in self._long_opt:
  298. raise optparse.BadOptionError(opt)
  299. return opt
  300. # pylint: disable=abstract-method; by design?
  301. class _ManHelpFormatter(optparse.HelpFormatter):
  302. def __init__(self, indent_increment=0, max_help_position=24,
  303. width=79, short_first=0):
  304. optparse.HelpFormatter.__init__(
  305. self, indent_increment, max_help_position, width, short_first)
  306. def format_heading(self, heading):
  307. return '.SH %s\n' % heading.upper()
  308. def format_description(self, description):
  309. return description
  310. def format_option(self, option):
  311. try:
  312. optstring = option.option_strings
  313. except AttributeError:
  314. optstring = self.format_option_strings(option)
  315. if option.help:
  316. help_text = self.expand_default(option)
  317. help = ' '.join([l.strip() for l in help_text.splitlines()])
  318. else:
  319. help = ''
  320. return '''.IP "%s"
  321. %s
  322. ''' % (optstring, help)
  323. def format_head(self, optparser, pkginfo, section=1):
  324. long_desc = ""
  325. try:
  326. pgm = optparser._get_prog_name()
  327. except AttributeError:
  328. # py >= 2.4.X (dunno which X exactly, at least 2)
  329. pgm = optparser.get_prog_name()
  330. short_desc = self.format_short_description(pgm, pkginfo.description)
  331. if hasattr(pkginfo, "long_desc"):
  332. long_desc = self.format_long_description(pgm, pkginfo.long_desc)
  333. return '%s\n%s\n%s\n%s' % (self.format_title(pgm, section),
  334. short_desc, self.format_synopsis(pgm),
  335. long_desc)
  336. @staticmethod
  337. def format_title(pgm, section):
  338. date = '-'.join(str(num) for num in time.localtime()[:3])
  339. return '.TH %s %s "%s" %s' % (pgm, section, date, pgm)
  340. @staticmethod
  341. def format_short_description(pgm, short_desc):
  342. return '''.SH NAME
  343. .B %s
  344. \\- %s
  345. ''' % (pgm, short_desc.strip())
  346. @staticmethod
  347. def format_synopsis(pgm):
  348. return '''.SH SYNOPSIS
  349. .B %s
  350. [
  351. .I OPTIONS
  352. ] [
  353. .I <arguments>
  354. ]
  355. ''' % pgm
  356. @staticmethod
  357. def format_long_description(pgm, long_desc):
  358. long_desc = '\n'.join(line.lstrip()
  359. for line in long_desc.splitlines())
  360. long_desc = long_desc.replace('\n.\n', '\n\n')
  361. if long_desc.lower().startswith(pgm):
  362. long_desc = long_desc[len(pgm):]
  363. return '''.SH DESCRIPTION
  364. .B %s
  365. %s
  366. ''' % (pgm, long_desc.strip())
  367. @staticmethod
  368. def format_tail(pkginfo):
  369. tail = '''.SH SEE ALSO
  370. /usr/share/doc/pythonX.Y-%s/
  371. .SH BUGS
  372. Please report bugs on the project\'s mailing list:
  373. %s
  374. .SH AUTHOR
  375. %s <%s>
  376. ''' % (getattr(pkginfo, 'debian_name', pkginfo.modname),
  377. pkginfo.mailinglist, pkginfo.author, pkginfo.author_email)
  378. if hasattr(pkginfo, "copyright"):
  379. tail += '''
  380. .SH COPYRIGHT
  381. %s
  382. ''' % pkginfo.copyright
  383. return tail
  384. class OptionsManagerMixIn(object):
  385. """Handle configuration from both a configuration file and command line options"""
  386. def __init__(self, usage, config_file=None, version=None, quiet=0):
  387. self.config_file = config_file
  388. self.reset_parsers(usage, version=version)
  389. # list of registered options providers
  390. self.options_providers = []
  391. # dictionary associating option name to checker
  392. self._all_options = collections.OrderedDict()
  393. self._short_options = {}
  394. self._nocallback_options = {}
  395. self._mygroups = {}
  396. # verbosity
  397. self.quiet = quiet
  398. self._maxlevel = 0
  399. def reset_parsers(self, usage='', version=None):
  400. # configuration file parser
  401. self.cfgfile_parser = configparser.ConfigParser(inline_comment_prefixes=('#', ';'))
  402. # command line parser
  403. self.cmdline_parser = OptionParser(Option, usage=usage, version=version)
  404. self.cmdline_parser.options_manager = self
  405. self._optik_option_attrs = set(self.cmdline_parser.option_class.ATTRS)
  406. def register_options_provider(self, provider, own_group=True):
  407. """register an options provider"""
  408. assert provider.priority <= 0, "provider's priority can't be >= 0"
  409. for i in range(len(self.options_providers)):
  410. if provider.priority > self.options_providers[i].priority:
  411. self.options_providers.insert(i, provider)
  412. break
  413. else:
  414. self.options_providers.append(provider)
  415. non_group_spec_options = [option for option in provider.options
  416. if 'group' not in option[1]]
  417. groups = getattr(provider, 'option_groups', ())
  418. if own_group and non_group_spec_options:
  419. self.add_option_group(provider.name.upper(), provider.__doc__,
  420. non_group_spec_options, provider)
  421. else:
  422. for opt, optdict in non_group_spec_options:
  423. self.add_optik_option(provider, self.cmdline_parser, opt, optdict)
  424. for gname, gdoc in groups:
  425. gname = gname.upper()
  426. goptions = [option for option in provider.options
  427. if option[1].get('group', '').upper() == gname]
  428. self.add_option_group(gname, gdoc, goptions, provider)
  429. def add_option_group(self, group_name, _, options, provider):
  430. # add option group to the command line parser
  431. if group_name in self._mygroups:
  432. group = self._mygroups[group_name]
  433. else:
  434. group = optparse.OptionGroup(self.cmdline_parser,
  435. title=group_name.capitalize())
  436. self.cmdline_parser.add_option_group(group)
  437. group.level = provider.level
  438. self._mygroups[group_name] = group
  439. # add section to the config file
  440. if group_name != "DEFAULT" and \
  441. group_name not in self.cfgfile_parser._sections:
  442. self.cfgfile_parser.add_section(group_name)
  443. # add provider's specific options
  444. for opt, optdict in options:
  445. self.add_optik_option(provider, group, opt, optdict)
  446. def add_optik_option(self, provider, optikcontainer, opt, optdict):
  447. args, optdict = self.optik_option(provider, opt, optdict)
  448. option = optikcontainer.add_option(*args, **optdict)
  449. self._all_options[opt] = provider
  450. self._maxlevel = max(self._maxlevel, option.level or 0)
  451. def optik_option(self, provider, opt, optdict):
  452. """get our personal option definition and return a suitable form for
  453. use with optik/optparse
  454. """
  455. optdict = copy.copy(optdict)
  456. if 'action' in optdict:
  457. self._nocallback_options[provider] = opt
  458. else:
  459. optdict['action'] = 'callback'
  460. optdict['callback'] = self.cb_set_provider_option
  461. # default is handled here and *must not* be given to optik if you
  462. # want the whole machinery to work
  463. if 'default' in optdict:
  464. if ('help' in optdict
  465. and optdict.get('default') is not None
  466. and optdict['action'] not in ('store_true', 'store_false')):
  467. optdict['help'] += ' [current: %default]'
  468. del optdict['default']
  469. args = ['--' + str(opt)]
  470. if 'short' in optdict:
  471. self._short_options[optdict['short']] = opt
  472. args.append('-' + optdict['short'])
  473. del optdict['short']
  474. # cleanup option definition dict before giving it to optik
  475. for key in list(optdict.keys()):
  476. if key not in self._optik_option_attrs:
  477. optdict.pop(key)
  478. return args, optdict
  479. def cb_set_provider_option(self, option, opt, value, parser):
  480. """optik callback for option setting"""
  481. if opt.startswith('--'):
  482. # remove -- on long option
  483. opt = opt[2:]
  484. else:
  485. # short option, get its long equivalent
  486. opt = self._short_options[opt[1:]]
  487. # trick since we can't set action='store_true' on options
  488. if value is None:
  489. value = 1
  490. self.global_set_option(opt, value)
  491. def global_set_option(self, opt, value):
  492. """set option on the correct option provider"""
  493. self._all_options[opt].set_option(opt, value)
  494. def generate_config(self, stream=None, skipsections=(), encoding=None):
  495. """write a configuration file according to the current configuration
  496. into the given stream or stdout
  497. """
  498. options_by_section = {}
  499. sections = []
  500. for provider in self.options_providers:
  501. for section, options in provider.options_by_section():
  502. if section is None:
  503. section = provider.name
  504. if section in skipsections:
  505. continue
  506. options = [(n, d, v) for (n, d, v) in options
  507. if d.get('type') is not None
  508. and not d.get('deprecated')]
  509. if not options:
  510. continue
  511. if section not in sections:
  512. sections.append(section)
  513. alloptions = options_by_section.setdefault(section, [])
  514. alloptions += options
  515. stream = stream or sys.stdout
  516. encoding = utils._get_encoding(encoding, stream)
  517. printed = False
  518. for section in sections:
  519. if printed:
  520. print('\n', file=stream)
  521. utils.format_section(stream, section.upper(),
  522. sorted(options_by_section[section]),
  523. encoding)
  524. printed = True
  525. def generate_manpage(self, pkginfo, section=1, stream=None):
  526. with _patch_optparse():
  527. _generate_manpage(self.cmdline_parser, pkginfo,
  528. section, stream=stream or sys.stdout,
  529. level=self._maxlevel)
  530. def load_provider_defaults(self):
  531. """initialize configuration using default values"""
  532. for provider in self.options_providers:
  533. provider.load_defaults()
  534. def read_config_file(self, config_file=None):
  535. """read the configuration file but do not load it (i.e. dispatching
  536. values to each options provider)
  537. """
  538. helplevel = 1
  539. while helplevel <= self._maxlevel:
  540. opt = '-'.join(['long'] * helplevel) + '-help'
  541. if opt in self._all_options:
  542. break # already processed
  543. # pylint: disable=unused-argument
  544. def helpfunc(option, opt, val, p, level=helplevel):
  545. print(self.help(level))
  546. sys.exit(0)
  547. helpmsg = '%s verbose help.' % ' '.join(['more'] * helplevel)
  548. optdict = {'action': 'callback', 'callback': helpfunc,
  549. 'help': helpmsg}
  550. provider = self.options_providers[0]
  551. self.add_optik_option(provider, self.cmdline_parser, opt, optdict)
  552. provider.options += ((opt, optdict),)
  553. helplevel += 1
  554. if config_file is None:
  555. config_file = self.config_file
  556. if config_file is not None:
  557. config_file = os.path.expanduser(config_file)
  558. if not os.path.exists(config_file):
  559. raise IOError("The config file {:s} doesn't exist!".format(config_file))
  560. use_config_file = config_file and os.path.exists(config_file)
  561. if use_config_file:
  562. parser = self.cfgfile_parser
  563. # Use this encoding in order to strip the BOM marker, if any.
  564. with io.open(config_file, 'r', encoding='utf_8_sig') as fp:
  565. parser.read_file(fp)
  566. # normalize sections'title
  567. for sect, values in list(parser._sections.items()):
  568. if not sect.isupper() and values:
  569. parser._sections[sect.upper()] = values
  570. if self.quiet:
  571. return
  572. if use_config_file:
  573. msg = 'Using config file {0}'.format(os.path.abspath(config_file))
  574. else:
  575. msg = 'No config file found, using default configuration'
  576. print(msg, file=sys.stderr)
  577. def load_config_file(self):
  578. """dispatch values previously read from a configuration file to each
  579. options provider)
  580. """
  581. parser = self.cfgfile_parser
  582. for section in parser.sections():
  583. for option, value in parser.items(section):
  584. try:
  585. self.global_set_option(option, value)
  586. except (KeyError, optparse.OptionError):
  587. # TODO handle here undeclared options appearing in the config file
  588. continue
  589. def load_configuration(self, **kwargs):
  590. """override configuration according to given parameters"""
  591. return self.load_configuration_from_config(kwargs)
  592. def load_configuration_from_config(self, config):
  593. for opt, opt_value in config.items():
  594. opt = opt.replace('_', '-')
  595. provider = self._all_options[opt]
  596. provider.set_option(opt, opt_value)
  597. def load_command_line_configuration(self, args=None):
  598. """Override configuration according to command line parameters
  599. return additional arguments
  600. """
  601. with _patch_optparse():
  602. if args is None:
  603. args = sys.argv[1:]
  604. else:
  605. args = list(args)
  606. (options, args) = self.cmdline_parser.parse_args(args=args)
  607. for provider in self._nocallback_options:
  608. config = provider.config
  609. for attr in config.__dict__.keys():
  610. value = getattr(options, attr, None)
  611. if value is None:
  612. continue
  613. setattr(config, attr, value)
  614. return args
  615. def add_help_section(self, title, description, level=0):
  616. """add a dummy option section for help purpose """
  617. group = optparse.OptionGroup(self.cmdline_parser,
  618. title=title.capitalize(),
  619. description=description)
  620. group.level = level
  621. self._maxlevel = max(self._maxlevel, level)
  622. self.cmdline_parser.add_option_group(group)
  623. def help(self, level=0):
  624. """return the usage string for available options """
  625. self.cmdline_parser.formatter.output_level = level
  626. with _patch_optparse():
  627. return self.cmdline_parser.format_help()
  628. class OptionsProviderMixIn(object):
  629. """Mixin to provide options to an OptionsManager"""
  630. # those attributes should be overridden
  631. priority = -1
  632. name = 'default'
  633. options = ()
  634. level = 0
  635. def __init__(self):
  636. self.config = optparse.Values()
  637. self.load_defaults()
  638. def load_defaults(self):
  639. """initialize the provider using default values"""
  640. for opt, optdict in self.options:
  641. action = optdict.get('action')
  642. if action != 'callback':
  643. # callback action have no default
  644. if optdict is None:
  645. optdict = self.get_option_def(opt)
  646. default = optdict.get('default')
  647. self.set_option(opt, default, action, optdict)
  648. def option_attrname(self, opt, optdict=None):
  649. """get the config attribute corresponding to opt"""
  650. if optdict is None:
  651. optdict = self.get_option_def(opt)
  652. return optdict.get('dest', opt.replace('-', '_'))
  653. def option_value(self, opt):
  654. """get the current value for the given option"""
  655. return getattr(self.config, self.option_attrname(opt), None)
  656. def set_option(self, optname, value, action=None, optdict=None):
  657. """method called to set an option (registered in the options list)"""
  658. if optdict is None:
  659. optdict = self.get_option_def(optname)
  660. if value is not None:
  661. value = _validate(value, optdict, optname)
  662. if action is None:
  663. action = optdict.get('action', 'store')
  664. if action == 'store':
  665. setattr(self.config, self.option_attrname(optname, optdict), value)
  666. elif action in ('store_true', 'count'):
  667. setattr(self.config, self.option_attrname(optname, optdict), 0)
  668. elif action == 'store_false':
  669. setattr(self.config, self.option_attrname(optname, optdict), 1)
  670. elif action == 'append':
  671. optname = self.option_attrname(optname, optdict)
  672. _list = getattr(self.config, optname, None)
  673. if _list is None:
  674. if isinstance(value, (list, tuple)):
  675. _list = value
  676. elif value is not None:
  677. _list = []
  678. _list.append(value)
  679. setattr(self.config, optname, _list)
  680. elif isinstance(_list, tuple):
  681. setattr(self.config, optname, _list + (value,))
  682. else:
  683. _list.append(value)
  684. elif action == 'callback':
  685. optdict['callback'](None, optname, value, None)
  686. else:
  687. raise UnsupportedAction(action)
  688. def get_option_def(self, opt):
  689. """return the dictionary defining an option given its name"""
  690. assert self.options
  691. for option in self.options:
  692. if option[0] == opt:
  693. return option[1]
  694. raise optparse.OptionError('no such option %s in section %r'
  695. % (opt, self.name), opt)
  696. def options_by_section(self):
  697. """return an iterator on options grouped by section
  698. (section, [list of (optname, optdict, optvalue)])
  699. """
  700. sections = {}
  701. for optname, optdict in self.options:
  702. sections.setdefault(optdict.get('group'), []).append(
  703. (optname, optdict, self.option_value(optname)))
  704. if None in sections:
  705. yield None, sections.pop(None)
  706. for section, options in sorted(sections.items()):
  707. yield section.upper(), options
  708. def options_and_values(self, options=None):
  709. if options is None:
  710. options = self.options
  711. for optname, optdict in options:
  712. yield (optname, optdict, self.option_value(optname))
  713. class ConfigurationMixIn(OptionsManagerMixIn, OptionsProviderMixIn):
  714. """basic mixin for simple configurations which don't need the
  715. manager / providers model
  716. """
  717. def __init__(self, *args, **kwargs):
  718. if not args:
  719. kwargs.setdefault('usage', '')
  720. kwargs.setdefault('quiet', 1)
  721. OptionsManagerMixIn.__init__(self, *args, **kwargs)
  722. OptionsProviderMixIn.__init__(self)
  723. if not getattr(self, 'option_groups', None):
  724. self.option_groups = []
  725. for _, optdict in self.options:
  726. try:
  727. gdef = (optdict['group'].upper(), '')
  728. except KeyError:
  729. continue
  730. if gdef not in self.option_groups:
  731. self.option_groups.append(gdef)
  732. self.register_options_provider(self, own_group=False)
  733. def _generate_manpage(optparser, pkginfo, section=1,
  734. stream=sys.stdout, level=0):
  735. formatter = _ManHelpFormatter()
  736. formatter.output_level = level
  737. formatter.parser = optparser
  738. print(formatter.format_head(optparser, pkginfo, section), file=stream)
  739. print(optparser.format_option_help(formatter), file=stream)
  740. print(formatter.format_tail(pkginfo), file=stream)