packaging.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. # Copyright 2011 OpenStack Foundation
  2. # Copyright 2012-2013 Hewlett-Packard Development Company, L.P.
  3. # All Rights Reserved.
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """
  17. Utilities with minimum-depends for use in setup.py
  18. """
  19. from __future__ import unicode_literals
  20. from distutils.command import install as du_install
  21. from distutils import log
  22. import email
  23. import email.errors
  24. import os
  25. import re
  26. import sys
  27. import warnings
  28. import pkg_resources
  29. import setuptools
  30. from setuptools.command import develop
  31. from setuptools.command import easy_install
  32. from setuptools.command import egg_info
  33. from setuptools.command import install
  34. from setuptools.command import install_scripts
  35. from setuptools.command import sdist
  36. from pbr import extra_files
  37. from pbr import git
  38. from pbr import options
  39. import pbr.pbr_json
  40. from pbr import testr_command
  41. from pbr import version
  42. REQUIREMENTS_FILES = ('requirements.txt', 'tools/pip-requires')
  43. PY_REQUIREMENTS_FILES = [x % sys.version_info[0] for x in (
  44. 'requirements-py%d.txt', 'tools/pip-requires-py%d')]
  45. TEST_REQUIREMENTS_FILES = ('test-requirements.txt', 'tools/test-requires')
  46. def get_requirements_files():
  47. files = os.environ.get("PBR_REQUIREMENTS_FILES")
  48. if files:
  49. return tuple(f.strip() for f in files.split(','))
  50. # Returns a list composed of:
  51. # - REQUIREMENTS_FILES with -py2 or -py3 in the name
  52. # (e.g. requirements-py3.txt)
  53. # - REQUIREMENTS_FILES
  54. return PY_REQUIREMENTS_FILES + list(REQUIREMENTS_FILES)
  55. def append_text_list(config, key, text_list):
  56. """Append a \n separated list to possibly existing value."""
  57. new_value = []
  58. current_value = config.get(key, "")
  59. if current_value:
  60. new_value.append(current_value)
  61. new_value.extend(text_list)
  62. config[key] = '\n'.join(new_value)
  63. def _any_existing(file_list):
  64. return [f for f in file_list if os.path.exists(f)]
  65. # Get requirements from the first file that exists
  66. def get_reqs_from_files(requirements_files):
  67. existing = _any_existing(requirements_files)
  68. deprecated = [f for f in existing if f in PY_REQUIREMENTS_FILES]
  69. if deprecated:
  70. warnings.warn('Support for \'-pyN\'-suffixed requirements files is '
  71. 'deprecated in pbr 4.0 and will be removed in 5.0. '
  72. 'Use environment markers instead. Conflicting files: '
  73. '%r' % deprecated,
  74. DeprecationWarning)
  75. for requirements_file in existing:
  76. with open(requirements_file, 'r') as fil:
  77. return fil.read().split('\n')
  78. return []
  79. def parse_requirements(requirements_files=None, strip_markers=False):
  80. if requirements_files is None:
  81. requirements_files = get_requirements_files()
  82. def egg_fragment(match):
  83. # take a versioned egg fragment and return a
  84. # versioned package requirement e.g.
  85. # nova-1.2.3 becomes nova>=1.2.3
  86. return re.sub(r'([\w.]+)-([\w.-]+)',
  87. r'\1>=\2',
  88. match.groups()[-1])
  89. requirements = []
  90. for line in get_reqs_from_files(requirements_files):
  91. # Ignore comments
  92. if (not line.strip()) or line.startswith('#'):
  93. continue
  94. # Ignore index URL lines
  95. if re.match(r'^\s*(-i|--index-url|--extra-index-url).*', line):
  96. continue
  97. # Handle nested requirements files such as:
  98. # -r other-requirements.txt
  99. if line.startswith('-r'):
  100. req_file = line.partition(' ')[2]
  101. requirements += parse_requirements(
  102. [req_file], strip_markers=strip_markers)
  103. continue
  104. try:
  105. project_name = pkg_resources.Requirement.parse(line).project_name
  106. except ValueError:
  107. project_name = None
  108. # For the requirements list, we need to inject only the portion
  109. # after egg= so that distutils knows the package it's looking for
  110. # such as:
  111. # -e git://github.com/openstack/nova/master#egg=nova
  112. # -e git://github.com/openstack/nova/master#egg=nova-1.2.3
  113. if re.match(r'\s*-e\s+', line):
  114. line = re.sub(r'\s*-e\s+.*#egg=(.*)$', egg_fragment, line)
  115. # such as:
  116. # http://github.com/openstack/nova/zipball/master#egg=nova
  117. # http://github.com/openstack/nova/zipball/master#egg=nova-1.2.3
  118. elif re.match(r'\s*(https?|git(\+(https|ssh))?):', line):
  119. line = re.sub(r'\s*(https?|git(\+(https|ssh))?):.*#egg=(.*)$',
  120. egg_fragment, line)
  121. # -f lines are for index locations, and don't get used here
  122. elif re.match(r'\s*-f\s+', line):
  123. line = None
  124. reason = 'Index Location'
  125. if line is not None:
  126. line = re.sub('#.*$', '', line)
  127. if strip_markers:
  128. semi_pos = line.find(';')
  129. if semi_pos < 0:
  130. semi_pos = None
  131. line = line[:semi_pos]
  132. requirements.append(line)
  133. else:
  134. log.info(
  135. '[pbr] Excluding %s: %s' % (project_name, reason))
  136. return requirements
  137. def parse_dependency_links(requirements_files=None):
  138. if requirements_files is None:
  139. requirements_files = get_requirements_files()
  140. dependency_links = []
  141. # dependency_links inject alternate locations to find packages listed
  142. # in requirements
  143. for line in get_reqs_from_files(requirements_files):
  144. # skip comments and blank lines
  145. if re.match(r'(\s*#)|(\s*$)', line):
  146. continue
  147. # lines with -e or -f need the whole line, minus the flag
  148. if re.match(r'\s*-[ef]\s+', line):
  149. dependency_links.append(re.sub(r'\s*-[ef]\s+', '', line))
  150. # lines that are only urls can go in unmolested
  151. elif re.match(r'\s*(https?|git(\+(https|ssh))?):', line):
  152. dependency_links.append(line)
  153. return dependency_links
  154. class InstallWithGit(install.install):
  155. """Extracts ChangeLog and AUTHORS from git then installs.
  156. This is useful for e.g. readthedocs where the package is
  157. installed and then docs built.
  158. """
  159. command_name = 'install'
  160. def run(self):
  161. _from_git(self.distribution)
  162. return install.install.run(self)
  163. class LocalInstall(install.install):
  164. """Runs python setup.py install in a sensible manner.
  165. Force a non-egg installed in the manner of
  166. single-version-externally-managed, which allows us to install manpages
  167. and config files.
  168. """
  169. command_name = 'install'
  170. def run(self):
  171. _from_git(self.distribution)
  172. return du_install.install.run(self)
  173. class TestrTest(testr_command.Testr):
  174. """Make setup.py test do the right thing."""
  175. command_name = 'test'
  176. def run(self):
  177. # Can't use super - base class old-style class
  178. testr_command.Testr.run(self)
  179. class LocalRPMVersion(setuptools.Command):
  180. __doc__ = """Output the rpm *compatible* version string of this package"""
  181. description = __doc__
  182. user_options = []
  183. command_name = "rpm_version"
  184. def run(self):
  185. log.info("[pbr] Extracting rpm version")
  186. name = self.distribution.get_name()
  187. print(version.VersionInfo(name).semantic_version().rpm_string())
  188. def initialize_options(self):
  189. pass
  190. def finalize_options(self):
  191. pass
  192. class LocalDebVersion(setuptools.Command):
  193. __doc__ = """Output the deb *compatible* version string of this package"""
  194. description = __doc__
  195. user_options = []
  196. command_name = "deb_version"
  197. def run(self):
  198. log.info("[pbr] Extracting deb version")
  199. name = self.distribution.get_name()
  200. print(version.VersionInfo(name).semantic_version().debian_string())
  201. def initialize_options(self):
  202. pass
  203. def finalize_options(self):
  204. pass
  205. def have_testr():
  206. return testr_command.have_testr
  207. try:
  208. from nose import commands
  209. class NoseTest(commands.nosetests):
  210. """Fallback test runner if testr is a no-go."""
  211. command_name = 'test'
  212. description = 'DEPRECATED: Run unit tests using nose'
  213. def run(self):
  214. warnings.warn('nose integration in pbr is deprecated. Please use '
  215. 'the native nose setuptools configuration or call '
  216. 'nose directly',
  217. DeprecationWarning)
  218. # Can't use super - base class old-style class
  219. commands.nosetests.run(self)
  220. _have_nose = True
  221. except ImportError:
  222. _have_nose = False
  223. def have_nose():
  224. return _have_nose
  225. _wsgi_text = """#PBR Generated from %(group)r
  226. import threading
  227. from %(module_name)s import %(import_target)s
  228. if __name__ == "__main__":
  229. import argparse
  230. import socket
  231. import sys
  232. import wsgiref.simple_server as wss
  233. my_ip = socket.gethostbyname(socket.gethostname())
  234. parser = argparse.ArgumentParser(
  235. description=%(import_target)s.__doc__,
  236. formatter_class=argparse.ArgumentDefaultsHelpFormatter,
  237. usage='%%(prog)s [-h] [--port PORT] [--host IP] -- [passed options]')
  238. parser.add_argument('--port', '-p', type=int, default=8000,
  239. help='TCP port to listen on')
  240. parser.add_argument('--host', '-b', default='',
  241. help='IP to bind the server to')
  242. parser.add_argument('args',
  243. nargs=argparse.REMAINDER,
  244. metavar='-- [passed options]',
  245. help="'--' is the separator of the arguments used "
  246. "to start the WSGI server and the arguments passed "
  247. "to the WSGI application.")
  248. args = parser.parse_args()
  249. if args.args:
  250. if args.args[0] == '--':
  251. args.args.pop(0)
  252. else:
  253. parser.error("unrecognized arguments: %%s" %% ' '.join(args.args))
  254. sys.argv[1:] = args.args
  255. server = wss.make_server(args.host, args.port, %(invoke_target)s())
  256. print("*" * 80)
  257. print("STARTING test server %(module_name)s.%(invoke_target)s")
  258. url = "http://%%s:%%d/" %% (server.server_name, server.server_port)
  259. print("Available at %%s" %% url)
  260. print("DANGER! For testing only, do not use in production")
  261. print("*" * 80)
  262. sys.stdout.flush()
  263. server.serve_forever()
  264. else:
  265. application = None
  266. app_lock = threading.Lock()
  267. with app_lock:
  268. if application is None:
  269. application = %(invoke_target)s()
  270. """
  271. _script_text = """# PBR Generated from %(group)r
  272. import sys
  273. from %(module_name)s import %(import_target)s
  274. if __name__ == "__main__":
  275. sys.exit(%(invoke_target)s())
  276. """
  277. # the following allows us to specify different templates per entry
  278. # point group when generating pbr scripts.
  279. ENTRY_POINTS_MAP = {
  280. 'console_scripts': _script_text,
  281. 'gui_scripts': _script_text,
  282. 'wsgi_scripts': _wsgi_text
  283. }
  284. def generate_script(group, entry_point, header, template):
  285. """Generate the script based on the template.
  286. :param str group:
  287. The entry-point group name, e.g., "console_scripts".
  288. :param str header:
  289. The first line of the script, e.g., "!#/usr/bin/env python".
  290. :param str template:
  291. The script template.
  292. :returns:
  293. The templated script content
  294. :rtype:
  295. str
  296. """
  297. if not entry_point.attrs or len(entry_point.attrs) > 2:
  298. raise ValueError("Script targets must be of the form "
  299. "'func' or 'Class.class_method'.")
  300. script_text = template % dict(
  301. group=group,
  302. module_name=entry_point.module_name,
  303. import_target=entry_point.attrs[0],
  304. invoke_target='.'.join(entry_point.attrs),
  305. )
  306. return header + script_text
  307. def override_get_script_args(
  308. dist, executable=os.path.normpath(sys.executable), is_wininst=False):
  309. """Override entrypoints console_script."""
  310. header = easy_install.get_script_header("", executable, is_wininst)
  311. for group, template in ENTRY_POINTS_MAP.items():
  312. for name, ep in dist.get_entry_map(group).items():
  313. yield (name, generate_script(group, ep, header, template))
  314. class LocalDevelop(develop.develop):
  315. command_name = 'develop'
  316. def install_wrapper_scripts(self, dist):
  317. if not self.exclude_scripts:
  318. for args in override_get_script_args(dist):
  319. self.write_script(*args)
  320. class LocalInstallScripts(install_scripts.install_scripts):
  321. """Intercepts console scripts entry_points."""
  322. command_name = 'install_scripts'
  323. def _make_wsgi_scripts_only(self, dist, executable, is_wininst):
  324. header = easy_install.get_script_header("", executable, is_wininst)
  325. wsgi_script_template = ENTRY_POINTS_MAP['wsgi_scripts']
  326. for name, ep in dist.get_entry_map('wsgi_scripts').items():
  327. content = generate_script(
  328. 'wsgi_scripts', ep, header, wsgi_script_template)
  329. self.write_script(name, content)
  330. def run(self):
  331. import distutils.command.install_scripts
  332. self.run_command("egg_info")
  333. if self.distribution.scripts:
  334. # run first to set up self.outfiles
  335. distutils.command.install_scripts.install_scripts.run(self)
  336. else:
  337. self.outfiles = []
  338. ei_cmd = self.get_finalized_command("egg_info")
  339. dist = pkg_resources.Distribution(
  340. ei_cmd.egg_base,
  341. pkg_resources.PathMetadata(ei_cmd.egg_base, ei_cmd.egg_info),
  342. ei_cmd.egg_name, ei_cmd.egg_version,
  343. )
  344. bs_cmd = self.get_finalized_command('build_scripts')
  345. executable = getattr(
  346. bs_cmd, 'executable', easy_install.sys_executable)
  347. is_wininst = getattr(
  348. self.get_finalized_command("bdist_wininst"), '_is_running', False
  349. )
  350. if 'bdist_wheel' in self.distribution.have_run:
  351. # We're building a wheel which has no way of generating mod_wsgi
  352. # scripts for us. Let's build them.
  353. # NOTE(sigmavirus24): This needs to happen here because, as the
  354. # comment below indicates, no_ep is True when building a wheel.
  355. self._make_wsgi_scripts_only(dist, executable, is_wininst)
  356. if self.no_ep:
  357. # no_ep is True if we're installing into an .egg file or building
  358. # a .whl file, in those cases, we do not want to build all of the
  359. # entry-points listed for this package.
  360. return
  361. for args in override_get_script_args(dist, executable, is_wininst):
  362. self.write_script(*args)
  363. class LocalManifestMaker(egg_info.manifest_maker):
  364. """Add any files that are in git and some standard sensible files."""
  365. def _add_pbr_defaults(self):
  366. for template_line in [
  367. 'include AUTHORS',
  368. 'include ChangeLog',
  369. 'exclude .gitignore',
  370. 'exclude .gitreview',
  371. 'global-exclude *.pyc'
  372. ]:
  373. self.filelist.process_template_line(template_line)
  374. def add_defaults(self):
  375. option_dict = self.distribution.get_option_dict('pbr')
  376. sdist.sdist.add_defaults(self)
  377. self.filelist.append(self.template)
  378. self.filelist.append(self.manifest)
  379. self.filelist.extend(extra_files.get_extra_files())
  380. should_skip = options.get_boolean_option(option_dict, 'skip_git_sdist',
  381. 'SKIP_GIT_SDIST')
  382. if not should_skip:
  383. rcfiles = git._find_git_files()
  384. if rcfiles:
  385. self.filelist.extend(rcfiles)
  386. elif os.path.exists(self.manifest):
  387. self.read_manifest()
  388. ei_cmd = self.get_finalized_command('egg_info')
  389. self._add_pbr_defaults()
  390. self.filelist.include_pattern("*", prefix=ei_cmd.egg_info)
  391. class LocalEggInfo(egg_info.egg_info):
  392. """Override the egg_info command to regenerate SOURCES.txt sensibly."""
  393. command_name = 'egg_info'
  394. def find_sources(self):
  395. """Generate SOURCES.txt only if there isn't one already.
  396. If we are in an sdist command, then we always want to update
  397. SOURCES.txt. If we are not in an sdist command, then it doesn't
  398. matter one flip, and is actually destructive.
  399. However, if we're in a git context, it's always the right thing to do
  400. to recreate SOURCES.txt
  401. """
  402. manifest_filename = os.path.join(self.egg_info, "SOURCES.txt")
  403. if (not os.path.exists(manifest_filename) or
  404. os.path.exists('.git') or
  405. 'sdist' in sys.argv):
  406. log.info("[pbr] Processing SOURCES.txt")
  407. mm = LocalManifestMaker(self.distribution)
  408. mm.manifest = manifest_filename
  409. mm.run()
  410. self.filelist = mm.filelist
  411. else:
  412. log.info("[pbr] Reusing existing SOURCES.txt")
  413. self.filelist = egg_info.FileList()
  414. for entry in open(manifest_filename, 'r').read().split('\n'):
  415. self.filelist.append(entry)
  416. def _from_git(distribution):
  417. option_dict = distribution.get_option_dict('pbr')
  418. changelog = git._iter_log_oneline()
  419. if changelog:
  420. changelog = git._iter_changelog(changelog)
  421. git.write_git_changelog(option_dict=option_dict, changelog=changelog)
  422. git.generate_authors(option_dict=option_dict)
  423. class LocalSDist(sdist.sdist):
  424. """Builds the ChangeLog and Authors files from VC first."""
  425. command_name = 'sdist'
  426. def checking_reno(self):
  427. """Ensure reno is installed and configured.
  428. We can't run reno-based commands if reno isn't installed/available, and
  429. don't want to if the user isn't using it.
  430. """
  431. if hasattr(self, '_has_reno'):
  432. return self._has_reno
  433. try:
  434. # versions of reno witout this module will not have the required
  435. # feature, hence the import
  436. from reno import setup_command # noqa
  437. except ImportError:
  438. log.info('[pbr] reno was not found or is too old. Skipping '
  439. 'release notes')
  440. self._has_reno = False
  441. return False
  442. conf, output_file, cache_file = setup_command.load_config(
  443. self.distribution)
  444. if not os.path.exists(os.path.join(conf.reporoot, conf.notespath)):
  445. log.info('[pbr] reno does not appear to be configured. Skipping '
  446. 'release notes')
  447. self._has_reno = False
  448. return False
  449. self._files = [output_file, cache_file]
  450. log.info('[pbr] Generating release notes')
  451. self._has_reno = True
  452. return True
  453. sub_commands = [('build_reno', checking_reno)] + sdist.sdist.sub_commands
  454. def run(self):
  455. _from_git(self.distribution)
  456. # sdist.sdist is an old style class, can't use super()
  457. sdist.sdist.run(self)
  458. def make_distribution(self):
  459. # This is included in make_distribution because setuptools doesn't use
  460. # 'get_file_list'. As such, this is the only hook point that runs after
  461. # the commands in 'sub_commands'
  462. if self.checking_reno():
  463. self.filelist.extend(self._files)
  464. self.filelist.sort()
  465. sdist.sdist.make_distribution(self)
  466. try:
  467. from pbr import builddoc
  468. _have_sphinx = True
  469. # Import the symbols from their new home so the package API stays
  470. # compatible.
  471. LocalBuildDoc = builddoc.LocalBuildDoc
  472. except ImportError:
  473. _have_sphinx = False
  474. LocalBuildDoc = None
  475. def have_sphinx():
  476. return _have_sphinx
  477. def _get_increment_kwargs(git_dir, tag):
  478. """Calculate the sort of semver increment needed from git history.
  479. Every commit from HEAD to tag is consider for Sem-Ver metadata lines.
  480. See the pbr docs for their syntax.
  481. :return: a dict of kwargs for passing into SemanticVersion.increment.
  482. """
  483. result = {}
  484. if tag:
  485. version_spec = tag + "..HEAD"
  486. else:
  487. version_spec = "HEAD"
  488. # Get the raw body of the commit messages so that we don't have to
  489. # parse out any formatting whitespace and to avoid user settings on
  490. # git log output affecting out ability to have working sem ver headers.
  491. changelog = git._run_git_command(['log', '--pretty=%B', version_spec],
  492. git_dir)
  493. header_len = len('sem-ver:')
  494. commands = [line[header_len:].strip() for line in changelog.split('\n')
  495. if line.lower().startswith('sem-ver:')]
  496. symbols = set()
  497. for command in commands:
  498. symbols.update([symbol.strip() for symbol in command.split(',')])
  499. def _handle_symbol(symbol, symbols, impact):
  500. if symbol in symbols:
  501. result[impact] = True
  502. symbols.discard(symbol)
  503. _handle_symbol('bugfix', symbols, 'patch')
  504. _handle_symbol('feature', symbols, 'minor')
  505. _handle_symbol('deprecation', symbols, 'minor')
  506. _handle_symbol('api-break', symbols, 'major')
  507. for symbol in symbols:
  508. log.info('[pbr] Unknown Sem-Ver symbol %r' % symbol)
  509. # We don't want patch in the kwargs since it is not a keyword argument -
  510. # its the default minimum increment.
  511. result.pop('patch', None)
  512. return result
  513. def _get_revno_and_last_tag(git_dir):
  514. """Return the commit data about the most recent tag.
  515. We use git-describe to find this out, but if there are no
  516. tags then we fall back to counting commits since the beginning
  517. of time.
  518. """
  519. changelog = git._iter_log_oneline(git_dir=git_dir)
  520. row_count = 0
  521. for row_count, (ignored, tag_set, ignored) in enumerate(changelog):
  522. version_tags = set()
  523. semver_to_tag = dict()
  524. for tag in list(tag_set):
  525. try:
  526. semver = version.SemanticVersion.from_pip_string(tag)
  527. semver_to_tag[semver] = tag
  528. version_tags.add(semver)
  529. except Exception:
  530. pass
  531. if version_tags:
  532. return semver_to_tag[max(version_tags)], row_count
  533. return "", row_count
  534. def _get_version_from_git_target(git_dir, target_version):
  535. """Calculate a version from a target version in git_dir.
  536. This is used for untagged versions only. A new version is calculated as
  537. necessary based on git metadata - distance to tags, current hash, contents
  538. of commit messages.
  539. :param git_dir: The git directory we're working from.
  540. :param target_version: If None, the last tagged version (or 0 if there are
  541. no tags yet) is incremented as needed to produce an appropriate target
  542. version following semver rules. Otherwise target_version is used as a
  543. constraint - if semver rules would result in a newer version then an
  544. exception is raised.
  545. :return: A semver version object.
  546. """
  547. tag, distance = _get_revno_and_last_tag(git_dir)
  548. last_semver = version.SemanticVersion.from_pip_string(tag or '0')
  549. if distance == 0:
  550. new_version = last_semver
  551. else:
  552. new_version = last_semver.increment(
  553. **_get_increment_kwargs(git_dir, tag))
  554. if target_version is not None and new_version > target_version:
  555. raise ValueError(
  556. "git history requires a target version of %(new)s, but target "
  557. "version is %(target)s" %
  558. dict(new=new_version, target=target_version))
  559. if distance == 0:
  560. return last_semver
  561. new_dev = new_version.to_dev(distance)
  562. if target_version is not None:
  563. target_dev = target_version.to_dev(distance)
  564. if target_dev > new_dev:
  565. return target_dev
  566. return new_dev
  567. def _get_version_from_git(pre_version=None):
  568. """Calculate a version string from git.
  569. If the revision is tagged, return that. Otherwise calculate a semantic
  570. version description of the tree.
  571. The number of revisions since the last tag is included in the dev counter
  572. in the version for untagged versions.
  573. :param pre_version: If supplied use this as the target version rather than
  574. inferring one from the last tag + commit messages.
  575. """
  576. git_dir = git._run_git_functions()
  577. if git_dir:
  578. try:
  579. tagged = git._run_git_command(
  580. ['describe', '--exact-match'], git_dir,
  581. throw_on_error=True).replace('-', '.')
  582. target_version = version.SemanticVersion.from_pip_string(tagged)
  583. except Exception:
  584. if pre_version:
  585. # not released yet - use pre_version as the target
  586. target_version = version.SemanticVersion.from_pip_string(
  587. pre_version)
  588. else:
  589. # not released yet - just calculate from git history
  590. target_version = None
  591. result = _get_version_from_git_target(git_dir, target_version)
  592. return result.release_string()
  593. # If we don't know the version, return an empty string so at least
  594. # the downstream users of the value always have the same type of
  595. # object to work with.
  596. try:
  597. return unicode()
  598. except NameError:
  599. return ''
  600. def _get_version_from_pkg_metadata(package_name):
  601. """Get the version from package metadata if present.
  602. This looks for PKG-INFO if present (for sdists), and if not looks
  603. for METADATA (for wheels) and failing that will return None.
  604. """
  605. pkg_metadata_filenames = ['PKG-INFO', 'METADATA']
  606. pkg_metadata = {}
  607. for filename in pkg_metadata_filenames:
  608. try:
  609. pkg_metadata_file = open(filename, 'r')
  610. except (IOError, OSError):
  611. continue
  612. try:
  613. pkg_metadata = email.message_from_file(pkg_metadata_file)
  614. except email.errors.MessageError:
  615. continue
  616. # Check to make sure we're in our own dir
  617. if pkg_metadata.get('Name', None) != package_name:
  618. return None
  619. return pkg_metadata.get('Version', None)
  620. def get_version(package_name, pre_version=None):
  621. """Get the version of the project.
  622. First, try getting it from PKG-INFO or METADATA, if it exists. If it does,
  623. that means we're in a distribution tarball or that install has happened.
  624. Otherwise, if there is no PKG-INFO or METADATA file, pull the version
  625. from git.
  626. We do not support setup.py version sanity in git archive tarballs, nor do
  627. we support packagers directly sucking our git repo into theirs. We expect
  628. that a source tarball be made from our git repo - or that if someone wants
  629. to make a source tarball from a fork of our repo with additional tags in it
  630. that they understand and desire the results of doing that.
  631. :param pre_version: The version field from setup.cfg - if set then this
  632. version will be the next release.
  633. """
  634. version = os.environ.get(
  635. "PBR_VERSION",
  636. os.environ.get("OSLO_PACKAGE_VERSION", None))
  637. if version:
  638. return version
  639. version = _get_version_from_pkg_metadata(package_name)
  640. if version:
  641. return version
  642. version = _get_version_from_git(pre_version)
  643. # Handle http://bugs.python.org/issue11638
  644. # version will either be an empty unicode string or a valid
  645. # unicode version string, but either way it's unicode and needs to
  646. # be encoded.
  647. if sys.version_info[0] == 2:
  648. version = version.encode('utf-8')
  649. if version:
  650. return version
  651. raise Exception("Versioning for this project requires either an sdist"
  652. " tarball, or access to an upstream git repository."
  653. " It's also possible that there is a mismatch between"
  654. " the package name in setup.cfg and the argument given"
  655. " to pbr.version.VersionInfo. Project name {name} was"
  656. " given, but was not able to be found.".format(
  657. name=package_name))
  658. # This is added because pbr uses pbr to install itself. That means that
  659. # any changes to the egg info writer entrypoints must be forward and
  660. # backward compatible. This maintains the pbr.packaging.write_pbr_json
  661. # path.
  662. write_pbr_json = pbr.pbr_json.write_pbr_json