Skip to content

Commit

Permalink
Merge pull request #699 from lucatrv/update-version-sourcing-example
Browse files Browse the repository at this point in the history
Update version sourcing example from pip setup.py
  • Loading branch information
di committed Apr 10, 2020
2 parents 06902b5 + f3d4c2b commit 89f8968
Showing 1 changed file with 15 additions and 17 deletions.
32 changes: 15 additions & 17 deletions source/guides/single-sourcing-package-version.rst
Original file line number Diff line number Diff line change
Expand Up @@ -8,33 +8,31 @@ Single-sourcing the package version
There are many techniques to maintain a single source of truth for the version
number of your project:

#. Read the file in :file:`setup.py` and parse the version with a regex.
Example ( from `pip setup.py
<https://github.com/pypa/pip/blob/master/setup.py#L12>`_)::
#. Read the file in :file:`setup.py` and get the version. Example (from `pip setup.py
<https://github.com/pypa/pip/blob/master/setup.py#L11>`_)::

here = os.path.abspath(os.path.dirname(__file__))
import codecs
import os.path

def read(*parts):
with codecs.open(os.path.join(here, *parts), 'r') as fp:
def read(rel_path):
here = os.path.abspath(os.path.dirname(__file__))
with codecs.open(os.path.join(here, rel_path), 'r') as fp:
return fp.read()

def find_version(*file_paths):
version_file = read(*file_paths)
version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
version_file, re.M)
if version_match:
return version_match.group(1)
raise RuntimeError("Unable to find version string.")
def get_version(rel_path):
for line in read(rel_path).splitlines():
if line.startswith('__version__'):
delim = '"' if '"' in line else "'"
return line.split(delim)[1]
else:
raise RuntimeError("Unable to find version string.")

setup(
...
version=find_version("package", "__init__.py")
version=get_version("package/__init__.py")
...
)

.. note::

This technique has the disadvantage of having to deal with complexities of regular expressions.

#. Use an external build tool that either manages updating both locations, or
offers an API that both locations can use.
Expand Down

0 comments on commit 89f8968

Please sign in to comment.