config.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  1. # vim: set fileencoding=utf-8 :
  2. #
  3. # (C) 2006,2007,2010-2012,2015 Guido Guenther <agx@sigxcpu.org>
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, please see
  16. # <http://www.gnu.org/licenses/>
  17. """handles command line and config file option parsing for the gbp commands"""
  18. from optparse import OptionParser, OptionGroup, Option, OptionValueError
  19. from six.moves import configparser
  20. from copy import copy
  21. import errno
  22. import os.path
  23. import sys
  24. try:
  25. from gbp.version import gbp_version
  26. except ImportError:
  27. gbp_version = "[Unknown version]"
  28. import gbp.tristate
  29. import gbp.log
  30. from gbp.git import GitRepositoryError, GitRepository
  31. no_upstream_branch_msg = """
  32. Repository does not have branch '%s' for upstream sources. If there is none see
  33. file:///usr/share/doc/git-buildpackage/manual-html/gbp.import.html#GBP.IMPORT.CONVERT
  34. on howto create it otherwise use --upstream-branch to specify it.
  35. """
  36. def expand_path(option, opt, value):
  37. value = os.path.expandvars(value)
  38. return os.path.expanduser(value)
  39. def check_tristate(option, opt, value):
  40. try:
  41. val = gbp.tristate.Tristate(value)
  42. except TypeError:
  43. raise OptionValueError(
  44. "option %s: invalid value: %r" % (opt, value))
  45. else:
  46. return val
  47. def safe_option(f):
  48. def _decorator(self, *args, **kwargs):
  49. obj = self
  50. option_name = kwargs.get('option_name')
  51. if not option_name and len(args):
  52. option_name = args[0]
  53. # We're decorating GbpOption not GbpOptionParser
  54. if not hasattr(obj, 'valid_options'):
  55. if not hasattr(obj, 'parser'):
  56. raise ValueError("Can only decorete GbpOptionParser and GbpOptionGroup not %s" % obj)
  57. else:
  58. obj = obj.parser
  59. if option_name and not option_name.startswith('no-'):
  60. obj.valid_options.append(option_name)
  61. return f(self, *args, **kwargs)
  62. return _decorator
  63. class GbpOption(Option):
  64. TYPES = Option.TYPES + ('path', 'tristate')
  65. TYPE_CHECKER = copy(Option.TYPE_CHECKER)
  66. TYPE_CHECKER['path'] = expand_path
  67. TYPE_CHECKER['tristate'] = check_tristate
  68. class GbpOptionParser(OptionParser):
  69. """
  70. Handles commandline options and parsing of config files
  71. @ivar command: the gbp command we store the options for
  72. @type command: string
  73. @ivar prefix: prefix to prepend to all commandline options
  74. @type prefix: string
  75. @ivar config: current configuration parameters
  76. @type config: dict
  77. @cvar defaults: defaults value of an option if not in the config file or
  78. given on the command line
  79. @type defaults: dict
  80. @cvar help: help messages
  81. @type help: dict
  82. @cvar def_config_files: config files we parse
  83. @type def_config_files: dict (type, path)
  84. """
  85. defaults = { 'debian-branch' : 'master',
  86. 'upstream-branch' : 'upstream',
  87. 'upstream-tree' : 'TAG',
  88. 'pristine-tar' : 'False',
  89. 'pristine-tar-commit': 'False',
  90. 'filter-pristine-tar' : 'False',
  91. 'sign-tags' : 'False',
  92. 'force-create' : 'False',
  93. 'no-create-orig' : 'False',
  94. 'cleaner' : '/bin/true',
  95. 'keyid' : '',
  96. 'posttag' : '',
  97. 'postbuild' : '',
  98. 'prebuild' : '',
  99. 'postexport' : '',
  100. 'postimport' : '',
  101. 'hooks' : 'True',
  102. 'debian-tag' : 'debian/%(version)s',
  103. 'debian-tag-msg' : '%(pkg)s Debian release %(version)s',
  104. 'upstream-tag' : 'upstream/%(version)s',
  105. 'import-msg' : 'Imported Upstream version %(version)s',
  106. 'commit-msg' : 'Update changelog for %(version)s release',
  107. 'filter' : [],
  108. 'snapshot-number' : 'snapshot + 1',
  109. 'git-log' : '--no-merges',
  110. 'export' : 'HEAD',
  111. 'export-dir' : '',
  112. 'overlay' : 'False',
  113. 'tarball-dir' : '',
  114. 'ignore-new' : 'False',
  115. 'ignore-branch' : 'False',
  116. 'meta' : 'True',
  117. 'meta-closes' : 'Closes|LP',
  118. 'meta-closes-bugnum' : r'(?:bug|issue)?\#?\s?\d+',
  119. 'full' : 'False',
  120. 'id-length' : '0',
  121. 'git-author' : 'False',
  122. 'ignore-regex' : '',
  123. 'compression' : 'auto',
  124. 'compression-level': '9',
  125. 'remote-url-pattern' : 'ssh://git.debian.org/git/collab-maint/%(pkg)s.git',
  126. 'multimaint' : 'True',
  127. 'multimaint-merge': 'False',
  128. 'pbuilder' : 'False',
  129. 'qemubuilder' : 'False',
  130. 'dist' : 'sid',
  131. 'arch' : '',
  132. 'interactive' : 'True',
  133. 'color' : 'auto',
  134. 'color-scheme' : '',
  135. 'customizations' : '',
  136. 'spawn-editor' : 'release',
  137. 'patch-numbers' : 'True',
  138. 'patch-num-format': '%04d-',
  139. 'renumber' : 'False',
  140. 'notify' : 'auto',
  141. 'merge' : 'True',
  142. 'merge-mode' : 'merge',
  143. 'track' : 'True',
  144. 'author-is-committer': 'False',
  145. 'author-date-is-committer-date': 'False',
  146. 'create-missing-branches': 'False',
  147. 'submodules' : 'False',
  148. 'time-machine' : 1,
  149. 'pbuilder-autoconf' : 'True',
  150. 'pbuilder-options': '',
  151. 'template-dir': '',
  152. 'remote-config': '',
  153. 'allow-unauthenticated': 'False',
  154. 'symlink-orig': 'True',
  155. 'purge': 'True',
  156. 'drop': 'False',
  157. 'commit': 'False',
  158. 'upstream-vcs-tag': '',
  159. }
  160. help = {
  161. 'debian-branch':
  162. ("Branch the Debian package is being developed on, "
  163. "default is '%(debian-branch)s'"),
  164. 'upstream-branch':
  165. "Upstream branch, default is '%(upstream-branch)s'",
  166. 'upstream-tree':
  167. ("Where to generate the upstream tarball from "
  168. "(tag or branch), default is '%(upstream-tree)s'"),
  169. 'debian-tag':
  170. ("Format string for debian tags, "
  171. "default is '%(debian-tag)s'"),
  172. 'debian-tag-msg':
  173. ("Format string for signed debian-tag messages, "
  174. "default is '%(debian-tag-msg)s'"),
  175. 'upstream-tag':
  176. ("Format string for upstream tags, "
  177. "default is '%(upstream-tag)s'"),
  178. 'sign-tags':
  179. "Whether to sign tags, default is '%(sign-tags)s'",
  180. 'keyid':
  181. "GPG keyid to sign tags with, default is '%(keyid)s'",
  182. 'import-msg':
  183. ("Format string for commit message used to commit "
  184. "the upstream tarball, default is '%(import-msg)s'"),
  185. 'commit-msg':
  186. ("Format string for commit messag used to commit, "
  187. "the changelog, default is '%(commit-msg)s'"),
  188. 'pristine-tar':
  189. ("Use pristine-tar to create orig tarball, "
  190. "default is '%(pristine-tar)s'"),
  191. 'pristine-tar-commit':
  192. ("When generating a tarball commit it to the pristine-tar branch '%(pristine-tar-commit)s' "
  193. "default is '%(pristine-tar-commit)s'"),
  194. 'filter-pristine-tar':
  195. "Filter pristine-tar when filter option is used, default is '%(filter-pristine-tar)s'",
  196. 'filter':
  197. "Files to filter out during import (can be given multiple times), default is %(filter)s",
  198. 'git-author':
  199. "Use name and email from git-config for changelog trailer, default is '%(git-author)s'",
  200. 'full':
  201. "Include the full commit message instead of only the first line, default is '%(full)s'",
  202. 'meta':
  203. "Parse meta tags in commit messages, default is '%(meta)s'",
  204. 'meta-closes':
  205. "Meta tags for the bts close commands, default is '%(meta-closes)s'",
  206. 'meta-closes-bugnum':
  207. "Meta bug number format, default is '%(meta-closes-bugnum)s'",
  208. 'ignore-new':
  209. "Build with uncommited changes in the source tree, default is '%(ignore-new)s'",
  210. 'ignore-branch':
  211. ("Build although debian-branch != current branch, "
  212. "default is '%(ignore-branch)s'"),
  213. 'overlay':
  214. ("extract orig tarball when using export-dir option, "
  215. "default is '%(overlay)s'"),
  216. 'remote-url-pattern':
  217. ("Remote url pattern to create the repo at, "
  218. "default is '%(remote-url-pattern)s'"),
  219. 'multimaint':
  220. "Note multiple maintainers, default is '%(multimaint)s'",
  221. 'multimaint-merge':
  222. ("Merge commits by maintainer, "
  223. "default is '%(multimaint-merge)s'"),
  224. 'pbuilder':
  225. ("Invoke git-pbuilder for building, "
  226. "default is '%(pbuilder)s'"),
  227. 'dist':
  228. ("Build for this distribution when using git-pbuilder, "
  229. "default is '%(dist)s'"),
  230. 'arch':
  231. ("Build for this architecture when using git-pbuilder, "
  232. "default is '%(arch)s'"),
  233. 'qemubuilder':
  234. ("Invoke git-pbuilder with qemubuilder for building, "
  235. "default is '%(qemubuilder)s'"),
  236. 'interactive':
  237. "Run command interactively, default is '%(interactive)s'",
  238. 'color':
  239. "Whether to use colored output, default is '%(color)s'",
  240. 'color-scheme':
  241. ("Colors to use in output (when color is enabled), format "
  242. "is '<debug>:<info>:<warning>:<error>', e.g. "
  243. "'cyan:34::'. Numerical values and color names are "
  244. "accepted, empty fields indicate using the default."),
  245. 'spawn-editor':
  246. ("Whether to spawn an editor after adding the "
  247. "changelog entry, default is '%(spawn-editor)s'"),
  248. 'patch-numbers':
  249. ("Whether to number patch files, "
  250. "default is %(patch-numbers)s"),
  251. 'patch-num-format':
  252. ("The format specifier for patch number prefixes, "
  253. "default is %(patch-num-format)s"),
  254. 'renumber':
  255. ("Whether to renumber patches exported from patch queues, "
  256. "instead of preserving the number specified in "
  257. "'Gbp-Pq: Name' tags, default is %(renumber)s"),
  258. 'notify':
  259. ("Whether to send a desktop notification after the build, "
  260. "default is '%(notify)s'"),
  261. 'merge':
  262. ("After the import merge the result to the debian branch, "
  263. "default is '%(merge)s'"),
  264. 'merge-mode':
  265. ("Howto merge the new upstream sources onto the debian branch"
  266. "default is '%(merge-mode)s'"),
  267. 'track':
  268. ("Set up tracking for remote branches, "
  269. "default is '%(track)s'"),
  270. 'author-is-committer':
  271. ("Use the authors's name also as the committer's name, "
  272. "default is '%(author-is-committer)s'"),
  273. 'author-date-is-committer-date':
  274. ("Use the authors's date as the committer's date, "
  275. "default is '%(author-date-is-committer-date)s'"),
  276. 'create-missing-branches':
  277. ("Create missing branches automatically, "
  278. "default is '%(create-missing-branches)s'"),
  279. 'submodules':
  280. ("Transparently handle submodules in the upstream tree, "
  281. "default is '%(submodules)s'"),
  282. 'postimport':
  283. ("hook run after a successful import, "
  284. "default is '%(postimport)s'"),
  285. 'hooks':
  286. ("Enable running all hooks, default is %(hooks)s"),
  287. 'time-machine':
  288. ("don't try head commit only to apply the patch queue "
  289. "but look TIME_MACHINE commits back, "
  290. "default is '%(time-machine)d'"),
  291. 'pbuilder-autoconf':
  292. ("Wheter to configure pbuilder automatically, "
  293. "default is '%(pbuilder-autoconf)s'"),
  294. 'pbuilder-options':
  295. ("Options to pass to pbuilder, "
  296. "default is '%(pbuilder-options)s'"),
  297. 'template-dir':
  298. ("Template directory used by git init, "
  299. "default is '%(template-dir)s'"),
  300. 'remote-config':
  301. ("Remote defintion in gbp.conf used to create the remote "
  302. "repository, default is '%(remote-config)s'"),
  303. 'allow-unauthenticated':
  304. ("Don't verify integrity of downloaded source, "
  305. "default is '%(allow-unauthenticated)s'"),
  306. 'symlink-orig':
  307. ("Whether to creat a symlink from the upstream tarball "
  308. "to the orig.tar.gz if needed, default is "
  309. "'%(symlink-orig)s'"),
  310. 'purge':
  311. "Purge exported package build directory. Default is '%(purge)s'",
  312. 'drop':
  313. ("In case of 'export' drop the patch-queue branch "
  314. "after export. Default is '%(drop)s'"),
  315. 'commit':
  316. "commit changes after export, Default is '%(commit)s'",
  317. }
  318. def_config_files = {'/etc/git-buildpackage/gbp.conf': 'system',
  319. '~/.gbp.conf': 'global',
  320. '%(top_dir)s/.gbp.conf': None,
  321. '%(top_dir)s/debian/gbp.conf': 'debian',
  322. '%(git_dir)s/gbp.conf': None}
  323. @classmethod
  324. def get_config_files(klass, no_local=False):
  325. """
  326. Get list of config files from the I{GBP_CONF_FILES} environment
  327. variable.
  328. @param no_local: don't return the per-repo configuration files
  329. @type no_local: C{bool}
  330. @return: list of config files we need to parse
  331. @rtype: C{list}
  332. >>> conf_backup = os.getenv('GBP_CONF_FILES')
  333. >>> if conf_backup is not None: del os.environ['GBP_CONF_FILES']
  334. >>> homedir = os.path.expanduser("~")
  335. >>> files = GbpOptionParser.get_config_files()
  336. >>> files_mangled = [file.replace(homedir, 'HOME') for file in files]
  337. >>> sorted(files_mangled)
  338. ['%(git_dir)s/gbp.conf', '%(top_dir)s/.gbp.conf', '%(top_dir)s/debian/gbp.conf', '/etc/git-buildpackage/gbp.conf', 'HOME/.gbp.conf']
  339. >>> files = GbpOptionParser.get_config_files(no_local=True)
  340. >>> files_mangled = [file.replace(homedir, 'HOME') for file in files]
  341. >>> sorted(files_mangled)
  342. ['/etc/git-buildpackage/gbp.conf', 'HOME/.gbp.conf']
  343. >>> os.environ['GBP_CONF_FILES'] = 'test1:test2'
  344. >>> GbpOptionParser.get_config_files()
  345. ['test1', 'test2']
  346. >>> del os.environ['GBP_CONF_FILES']
  347. >>> if conf_backup is not None: os.environ['GBP_CONF_FILES'] = conf_backup
  348. """
  349. envvar = os.environ.get('GBP_CONF_FILES')
  350. files = envvar.split(':') if envvar else klass.def_config_files.keys()
  351. files = [os.path.expanduser(fname) for fname in files]
  352. if no_local:
  353. files = [fname for fname in files if fname.startswith('/')]
  354. return files
  355. def _read_config_file(self, parser, repo, filename):
  356. """Read config file"""
  357. str_fields = {}
  358. if repo:
  359. str_fields['git_dir'] = repo.git_dir
  360. if not repo.bare:
  361. str_fields['top_dir'] = repo.path
  362. try:
  363. filename = filename % str_fields
  364. except KeyError:
  365. # Skip if filename wasn't expanded, i.e. we're not in git repo
  366. return
  367. parser.read(filename)
  368. def _warn_old_config_section(self, oldcmd, cmd):
  369. if not os.getenv("GBP_DISABLE_SECTION_DEPRECTATION"):
  370. gbp.log.warn("Old style config section [%s] found "
  371. "please rename to [%s]" % (oldcmd, cmd))
  372. def parse_config_files(self):
  373. """
  374. Parse the possible config files and set appropriate values
  375. default values
  376. """
  377. parser = configparser.SafeConfigParser()
  378. # Fill in the built in values
  379. self.config = dict(self.__class__.defaults)
  380. # Update with the values from the defaults section. This is needed
  381. # in case the config file doesn't have a [<command>] section at all
  382. config_files = self.get_config_files()
  383. try:
  384. repo = GitRepository(".")
  385. except GitRepositoryError:
  386. repo = None
  387. # Read all config files
  388. for filename in config_files:
  389. self._read_config_file(parser, repo, filename)
  390. self.config.update(dict(parser.defaults()))
  391. # Make sure we read any legacy sections prior to the real subcommands
  392. # section i.e. read [gbp-pull] prior to [pull]
  393. if (self.command.startswith('gbp-') or
  394. self.command.startswith('git-')):
  395. cmd = self.command[4:]
  396. oldcmd = self.command
  397. if parser.has_section(oldcmd):
  398. self.config.update(dict(parser.items(oldcmd, raw=True)))
  399. self._warn_old_config_section(oldcmd, cmd)
  400. else:
  401. cmd = self.command
  402. for prefix in ['gbp', 'git']:
  403. oldcmd = '%s-%s' % (prefix, self.command)
  404. if parser.has_section(oldcmd):
  405. self.config.update(dict(parser.items(oldcmd, raw=True)))
  406. self._warn_old_config_section(oldcmd, cmd)
  407. # Update with command specific settings
  408. if parser.has_section(cmd):
  409. # Don't use items() until we got rid of the compat sections
  410. # since this pulls in the defaults again
  411. self.config.update(dict(parser._sections[cmd].items()))
  412. for section in self.sections:
  413. if parser.has_section(section):
  414. self.config.update(dict(parser._sections[section].items()))
  415. else:
  416. raise configparser.NoSectionError(
  417. "Mandatory section [%s] does not exist." % section)
  418. # filter can be either a list or a string, always build a list:
  419. if self.config['filter']:
  420. if self.config['filter'].startswith('['):
  421. self.config['filter'] = eval(self.config['filter'])
  422. else:
  423. self.config['filter'] = [ self.config['filter'] ]
  424. else:
  425. self.config['filter'] = []
  426. def __init__(self, command, prefix='', usage=None, sections=[]):
  427. """
  428. @param command: the command to build the config parser for
  429. @type command: C{str}
  430. @param prefix: A prefix to add to all command line options
  431. @type prefix: C{str}
  432. @param usage: a usage description
  433. @type usage: C{str}
  434. @param sections: additional (non optional) config file sections
  435. to parse
  436. @type sections: C{list} of C{str}
  437. """
  438. self.command = command
  439. self.sections = sections
  440. self.prefix = prefix
  441. self.config = {}
  442. self.parse_config_files()
  443. self.valid_options = []
  444. if self.command.startswith('git-') or self.command.startswith('gbp-'):
  445. prog = self.command
  446. else:
  447. prog = "gbp %s" % self.command
  448. OptionParser.__init__(self, option_class=GbpOption,
  449. prog=prog,
  450. usage=usage, version='%s %s' % (self.command,
  451. gbp_version))
  452. def _is_boolean(self, dummy, *unused, **kwargs):
  453. """is option_name a boolean option"""
  454. ret = False
  455. try:
  456. if kwargs['action'] in [ 'store_true', 'store_false' ]:
  457. ret=True
  458. except KeyError:
  459. ret=False
  460. return ret
  461. def _get_bool_default(self, option_name):
  462. """
  463. get default for boolean options
  464. this way we can handle no-foo=True and foo=False
  465. """
  466. if option_name.startswith('no-'):
  467. pos = option_name[3:]
  468. neg = option_name
  469. else:
  470. pos = option_name
  471. neg = "no-%s" % option_name
  472. try:
  473. default = self.config[pos]
  474. except KeyError:
  475. default = self.config[neg]
  476. if default.lower() in ["true", "1" ]:
  477. val = 'True'
  478. elif default.lower() in ["false", "0" ]:
  479. val = 'False'
  480. else:
  481. raise ValueError("Boolean options must be True or False")
  482. return eval(val)
  483. def get_default(self, option_name, **kwargs):
  484. """get the default value"""
  485. if self._is_boolean(self, option_name, **kwargs):
  486. default = self._get_bool_default(option_name)
  487. else:
  488. default = self.config[option_name]
  489. return default
  490. @safe_option
  491. def add_config_file_option(self, option_name, dest, help=None, **kwargs):
  492. """
  493. set a option for the command line parser, the default is read from the config file
  494. param option_name: name of the option
  495. type option_name: string
  496. param dest: where to store this option
  497. type dest: string
  498. param help: help text
  499. type help: string
  500. """
  501. if not help:
  502. help = self.help[option_name]
  503. OptionParser.add_option(self, "--%s%s" % (self.prefix, option_name), dest=dest,
  504. default=self.get_default(option_name, **kwargs),
  505. help=help % self.config, **kwargs)
  506. def add_boolean_config_file_option(self, option_name, dest):
  507. self.add_config_file_option(option_name=option_name, dest=dest, action="store_true")
  508. neg_help = "negates '--%s%s'" % (self.prefix, option_name)
  509. self.add_config_file_option(option_name="no-%s" % option_name, dest=dest, help=neg_help, action="store_false")
  510. def get_config_file_value(self, option_name):
  511. """
  512. Query a single interpolated config file value.
  513. @param option_name: the config file option to look up
  514. @type option_name: string
  515. @returns: The config file option value or C{None} if it doesn't exist
  516. @rtype: C{str} or C{None}
  517. """
  518. return self.config.get(option_name)
  519. def print_help(self, file=None):
  520. """
  521. Print an extended help message, listing all options and any
  522. help text provided with them, to 'file' (default stdout).
  523. """
  524. if file is None:
  525. file = sys.stdout
  526. encoding = self._get_encoding(file)
  527. try:
  528. file.write(self.format_help().encode(encoding, "replace"))
  529. except IOError as e:
  530. if e.errno != errno.EPIPE:
  531. raise
  532. @classmethod
  533. def _name_to_filename(cls, name):
  534. """
  535. Translate a name like 'system' to a config file name
  536. >>> GbpOptionParser._name_to_filename('foo')
  537. >>> GbpOptionParser._name_to_filename('system')
  538. '/etc/git-buildpackage/gbp.conf'
  539. >>> GbpOptionParser._name_to_filename('global')
  540. '~/.gbp.conf'
  541. >>> GbpOptionParser._name_to_filename('debian')
  542. '%(top_dir)s/debian/gbp.conf'
  543. """
  544. for k, v in cls.def_config_files.items():
  545. if name == v:
  546. return k
  547. else:
  548. return None
  549. @classmethod
  550. def _set_config_file_value(cls, section, option, value, name=None, filename=None):
  551. """
  552. Write a config value to a file creating it if needed
  553. On errors a ConfigParserError is raised
  554. """
  555. if not name and not filename:
  556. raise configparser.Error("Either 'name' or 'filename' must be given")
  557. if not filename:
  558. filename = os.path.expanduser(cls._name_to_filename(name))
  559. # Create e new config parser since we only operate on a single file
  560. cfg = configparser.RawConfigParser()
  561. cfg.read(filename)
  562. if not cfg.has_section(section):
  563. cfg.add_section(section)
  564. cfg.set(section, option, value)
  565. with open(filename, 'w') as fp:
  566. cfg.write(fp)
  567. class GbpOptionGroup(OptionGroup):
  568. @safe_option
  569. def add_config_file_option(self, option_name, dest, help=None, **kwargs):
  570. """
  571. set a option for the command line parser, the default is read from the config file
  572. param option_name: name of the option
  573. type option_name: string
  574. param dest: where to store this option
  575. type dest: string
  576. param help: help text
  577. type help: string
  578. """
  579. if not help:
  580. help = self.parser.help[option_name]
  581. OptionGroup.add_option(self, "--%s%s" % (self.parser.prefix, option_name), dest=dest,
  582. default=self.parser.get_default(option_name, **kwargs),
  583. help=help % self.parser.config, **kwargs)
  584. def add_boolean_config_file_option(self, option_name, dest):
  585. self.add_config_file_option(option_name=option_name, dest=dest, action="store_true")
  586. neg_help = "negates '--%s%s'" % (self.parser.prefix, option_name)
  587. self.add_config_file_option(option_name="no-%s" % option_name, dest=dest, help=neg_help, action="store_false")
  588. class GbpOptionParserDebian(GbpOptionParser):
  589. """
  590. Handles commandline options and parsing of config files for Debian tools
  591. """
  592. defaults = dict(GbpOptionParser.defaults)
  593. defaults.update( {
  594. 'builder' : 'debuild -i -I',
  595. } )
  596. class GbpOptionParserRpm(GbpOptionParser):
  597. """
  598. Handles commandline options and parsing of config files for rpm tools
  599. """
  600. defaults = dict(GbpOptionParser.defaults)
  601. defaults.update({
  602. 'tmp-dir' : '/var/tmp/gbp/',
  603. 'vendor' : 'Downstream',
  604. 'packaging-branch' : 'master',
  605. 'packaging-dir' : '',
  606. 'packaging-tag-msg' : ('%(pkg)s (vendor)s release '
  607. '%(version)s'),
  608. 'packaging-tag' : 'packaging/%(version)s',
  609. 'export-sourcedir' : 'SOURCES',
  610. 'export-specdir' : 'SPECS',
  611. 'export-dir' : '../rpmbuild',
  612. 'builder' : 'rpmbuild',
  613. 'spec-file' : '',
  614. 'mock' : 'False',
  615. 'dist' : '',
  616. 'arch' : '',
  617. 'mock-root' : '',
  618. 'mock-options' : '',
  619. 'native' : 'auto',
  620. })
  621. help = dict(GbpOptionParser.help)
  622. help.update({
  623. 'tmp-dir':
  624. "Base directory under which temporary directories are "
  625. "created, default is '%(tmp-dir)s'",
  626. 'vendor':
  627. "Distribution vendor name, default is '%(vendor)s'",
  628. 'packaging-branch':
  629. "Branch the packaging is being maintained on, rpm counterpart "
  630. "of the 'debian-branch' option, default is "
  631. "'%(packaging-branch)s'",
  632. 'packaging-dir':
  633. "Subdir for RPM packaging files, default is "
  634. "'%(packaging-dir)s'",
  635. 'packaging-tag':
  636. "Format string for packaging tags, RPM counterpart of the "
  637. "'debian-tag' option, default is '%(packaging-tag)s'",
  638. 'packaging-tag-msg':
  639. ("Format string for packaging tag messages, "
  640. "default is '%(packaging-tag-msg)s'"),
  641. 'spec-file':
  642. "Spec file to use, causes the packaging-dir option to be "
  643. "ignored, default is '%(spec-file)s'",
  644. 'export-sourcedir':
  645. "Subdir (under EXPORT_DIR) where packaging sources (other than "
  646. "the spec file) are exported, default is "
  647. "'%(export-sourcedir)s'",
  648. 'export-specdir':
  649. "Subdir (under EXPORT_DIR) where package spec file is "
  650. "exported default is '%(export-specdir)s'",
  651. 'mock':
  652. ("Invoke mock for building using gbp-builder-mock, "
  653. "default is '%(mock)s'"),
  654. 'dist':
  655. ("Build for this distribution when using mock. E.g.: epel-6, "
  656. "default is '%(dist)s'"),
  657. 'arch':
  658. ("Build for this architecture when using mock, "
  659. "default is '%(arch)s'"),
  660. 'mock-root':
  661. ("The mock root (-r) name for building with mock: <dist>-<arch>, "
  662. "default is '%(mock-root)s'"),
  663. 'mock-options':
  664. ("Options to pass to mock, "
  665. "default is '%(mock-options)s'"),
  666. 'native':
  667. "Treat this package as native, default is '%(native)s'",
  668. })
  669. # vim:et:ts=4:sw=4:et:sts=4:ai:set list listchars=tab\:»·,trail\:·: