--- a/build/mach_bootstrap.py
+++ b/build/mach_bootstrap.py
@@ -63,16 +63,17 @@ SEARCH_PATHS = [
'python/configobj',
'python/futures',
'python/jsmin',
'python/psutil',
'python/which',
'python/pystache',
'python/pyyaml/lib',
'python/requests',
+ 'python/semantic_version',
'python/slugid',
'build',
'config',
'dom/bindings',
'dom/bindings/parser',
'dom/media/test/external',
'layout/tools/reftest',
'other-licenses/ply',
--- a/python/mach_commands.py
+++ b/python/mach_commands.py
@@ -7,28 +7,37 @@ from __future__ import absolute_import,
import argparse
import logging
import mozpack.path as mozpath
import os
import platform
import subprocess
import sys
import which
+import json
from distutils.version import LooseVersion
+import semantic_version
from mozbuild.base import (
MachCommandBase,
)
from mach.decorators import (
CommandArgument,
CommandProvider,
Command,
)
+ESLINT_PACKAGES = {
+ "eslint": "^2.7.0",
+ "eslint-plugin-react": "^4.2.3",
+ "eslint-plugin-html": "^1.4.0",
+ "eslint-plugin-mozilla": "^0.0.0"
+}
+
ESLINT_NOT_FOUND_MESSAGE = '''
Could not find eslint! We looked at the --binary option, at the ESLINT
environment variable, and then at your path. Install eslint and needed plugins
with
mach eslint --setup
and try again.
@@ -44,16 +53,24 @@ Valid installation paths:
NPM_NOT_FOUND_MESSAGE = '''
Node Package Manager (npm) is either not installed or installed to a
non-standard path. Please install npm from https://nodejs.org (it comes as an
option in the node installation) and try again.
Valid installation paths:
'''.strip()
+NPM_ERROR_MESSAGE = '''
+Node Package Manager (npm) returned an error when run.
+'''.strip()
+
+MISSING_PACKAGES_MESSAGE = '''
+The expected npm packages weren't installed, you may see unexpected errors from
+eslint. You can run "mach eslint --setup" to correct this.
+'''.strip()
@CommandProvider
class MachCommands(MachCommandBase):
@Command('python', category='devenv',
description='Run Python.')
@CommandArgument('args', nargs=argparse.REMAINDER)
def python(self, args):
# Avoid logging the command
@@ -167,16 +184,18 @@ class MachCommands(MachCommandBase):
binary = which.which('eslint')
except which.WhichError:
pass
if not binary:
print(ESLINT_NOT_FOUND_MESSAGE)
return 1
+ self.check_node_modules(ESLINT_PACKAGES)
+
self.log(logging.INFO, 'eslint', {'binary': binary, 'args': args},
'Running {binary}')
args = args or ['.']
cmd_args = [binary,
# Enable the HTML plugin.
# We can't currently enable this in the global config file
@@ -191,56 +210,89 @@ class MachCommands(MachCommandBase):
ensure_exit_code=False, # Don't throw on non-zero exit code.
require_unix_environment=True # eslint is not a valid Win32 binary.
)
self.log(logging.INFO, 'eslint', {'msg': ('No errors' if success == 0 else 'Errors')},
'Finished eslint. {msg} encountered.')
return success
+ def check_node_modules(self, expected):
+ npmPath = self.getNodeOrNpmPath("npm")
+ if not npmPath:
+ print(NPM_NOT_FOUND_MESSAGE)
+ return 1
+
+ try:
+ json_str = subprocess.check_output([npmPath, "ls", "-g", "--json", "true", "--depth", "0"],
+ stderr=subprocess.STDOUT)
+ except (subprocess.CalledProcessError, WindowsError):
+ print(NPM_ERROR_MESSAGE)
+ return 1
+
+ not_seen = expected.keys()
+ warned = False
+
+ data = json.loads(json_str)
+ if "dependencies" not in data:
+ return 1
+
+ for (name, package) in data["dependencies"].iteritems():
+ if name in expected:
+ not_seen.remove(name)
+ version = semantic_version.Version(package["version"])
+ spec = semantic_version.Spec(expected[name])
+
+ if not spec.match(version):
+ if not warned:
+ warned = True
+ print(MISSING_PACKAGES_MESSAGE)
+ print("The expected version of %s wasn't found. You have version %s installed but we expected version %s." %
+ (name, package["version"], expected[name]))
+
+ if len(not_seen) > 0:
+ if not warned:
+ warned = True
+ print(MISSING_PACKAGES_MESSAGE)
+ for name in not_seen:
+ print("The package %s isn't installed and may be needed." % (name))
+
+
+ def install_node_modules(self, npmPath, modules):
+ for (name, version) in modules.iteritems():
+ success = self.callProcess(name,
+ [npmPath, "install", "%s@%s" % (name, version), "-g"])
+ if not success:
+ return 1
+
def eslint_setup(self, update_only=False):
"""Ensure eslint is optimally configured.
This command will inspect your eslint configuration and
guide you through an interactive wizard helping you configure
eslint for optimal use on Mozilla projects.
"""
sys.path.append(os.path.dirname(__file__))
npmPath = self.getNodeOrNpmPath("npm")
if not npmPath:
return 1
- # Install eslint 1.10.3.
- # Note that that's the version currently compatible with the mozilla
- # eslint plugin.
- success = self.callProcess("eslint",
- [npmPath, "install", "eslint@1.10.3", "-g"])
- if not success:
- return 1
+ modules = dict(ESLINT_PACKAGES)
+ # The Mozilal plugin is linked directly
+ del modules["eslint-plugin-mozilla"]
+ self.install_node_modules(npmPath, modules)
# Install eslint-plugin-mozilla.
success = self.callProcess("eslint-plugin-mozilla",
[npmPath, "link"],
"testing/eslint-plugin-mozilla")
if not success:
return 1
- # Install eslint-plugin-html.
- success = self.callProcess("eslint-plugin-html",
- [npmPath, "install", "eslint-plugin-html", "-g"])
- if not success:
- return 1
-
- # Install eslint-plugin-react.
- success = self.callProcess("eslint-plugin-react",
- [npmPath, "install", "eslint-plugin-react", "-g"])
- if not success:
- return 1
-
print("\nESLint and approved plugins installed successfully!")
def callProcess(self, name, cmd, cwd=None):
print("\nInstalling %s using \"%s\"..." % (name, " ".join(cmd)))
try:
with open(os.devnull, "w") as fnull:
subprocess.check_call(cmd, cwd=cwd, stdout=fnull)
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/.gitignore
@@ -0,0 +1,15 @@
+# Temporary files
+.*.swp
+*.pyc
+*.pyo
+
+# Build-related files
+docs/_build/
+auto_dev_requirements*.txt
+.coverage
+*.egg-info
+*.egg
+build/
+dist/
+htmlcov/
+MANIFEST
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/.travis.yml
@@ -0,0 +1,20 @@
+language: python
+
+python:
+ - "2.7"
+ - "3.4"
+ - "3.5"
+env:
+ - DJANGO_VERSION=1.7
+ - DJANGO_VERSION=1.8
+ - DJANGO_VERSION=1.9
+
+script:
+ - python setup.py test
+
+install:
+ - make install-deps
+
+notifications:
+ email: false
+ irc: "irc.freenode.org#xelnext"
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/CREDITS
@@ -0,0 +1,55 @@
+Credits
+=======
+
+
+Maintainers
+-----------
+
+The ``python-semanticversion`` project is operated and maintained by:
+
+* Raphaël Barrois <raphael.barrois+semver@polytechnique.org> (https://github.com/rbarrois)
+
+
+.. _contributors:
+
+Contributors
+------------
+
+The project has received contributions from (in alphabetical order):
+
+* Raphaël Barrois <raphael.barrois+semver@polytechnique.org> (https://github.com/rbarrois)
+* Rick Eyre <rick.eyre@outlook.com> (https://github.com/rickeyre)
+* Hugo Rodger-Brown <hugo@yunojuno.com> (https://github.com/yunojuno)
+* Michael Hrivnak <mhrivnak@hrivnak.org> (https://github.com/mhrivnak)
+* William Minchin <w_minchin@hotmail.com> (https://github.com/minchinweb)
+* Dave Hall <skwadhd@gmail.com> (https://github.com/skwashd)
+
+
+Contributor license agreement
+-----------------------------
+
+.. note:: This agreement is required to allow redistribution of submitted contributions.
+ See http://oss-watch.ac.uk/resources/cla for an explanation.
+
+Any contributor proposing updates to the code or documentation of this project *MUST*
+add its name to the list in the :ref:`contributors` section, thereby "signing" the
+following contributor license agreement:
+
+They accept and agree to the following terms for their present end future contributions
+submitted to the ``python-semanticversion`` project:
+
+* They represent that they are legally entitled to grant this license, and that their
+ contributions are their original creation
+
+* They grant the ``python-semanticversion`` project a perpetual, worldwide, non-exclusive,
+ no-charge, royalty-free, irrevocable copyright license to reproduce,
+ prepare derivative works of, publicly display, sublicense and distribute their contributions
+ and such derivative works.
+
+* They are not expected to provide support for their contributions, except to the extent they
+ desire to provide support.
+
+
+.. note:: The above agreement is inspired by the Apache Contributor License Agreement.
+
+.. vim:set ft=rst:
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/ChangeLog
@@ -0,0 +1,176 @@
+ChangeLog
+=========
+
+2.5.0 (2016-02-12)
+------------------
+
+*Bugfix:*
+
+ `#18 <https://github.com/rbarrois/python-semanticversion/issues/18>`_: According to SemVer 2.0.0, build numbers aren't ordered.
+
+ * Remove specs of the ``Spec('<1.1.3+')`` form
+ * Comparing ``Version('0.1.0')`` to ``Version('0.1.0+bcd')`` has new
+ rules::
+
+ >>> Version('0.1.0+1') == Version('0.1.0+bcd')
+ False
+ >>> Version('0.1.0+1') != Version('0.1.0+bcd')
+ True
+ >>> Version('0.1.0+1') < Version('0.1.0+bcd')
+ False
+ >>> Version('0.1.0+1') > Version('0.1.0+bcd')
+ False
+ >>> Version('0.1.0+1') <= Version('0.1.0+bcd')
+ False
+ >>> Version('0.1.0+1') >= Version('0.1.0+bcd')
+ False
+ >>> compare(Version('0.1.0+1'), Version('0.1.0+bcd'))
+ NotImplemented
+
+ * :func:`semantic_version.compare` returns ``NotImplemented`` when its
+ parameters differ only by build metadata
+ * ``Spec('<=1.3.0')`` now matches ``Version('1.3.0+abde24fe883')``
+
+ * `#24 <https://github.com/rbarrois/python-semanticversion/issues/24>`_: Fix handling of bumping pre-release versions, thanks to @minchinweb.
+ * `#30 <https://github.com/rbarrois/python-semanticversion/issues/30>`_: Add support for NPM-style ``^1.2.3`` and ``~2.3.4`` specs, thanks to @skwashd
+
+2.4.2 (2015-07-02)
+------------------
+
+*Bugfix:*
+
+ * Fix tests for Django 1.7+, thanks to @mhrivnak.
+
+2.4.1 (2015-04-01)
+------------------
+
+*Bugfix:*
+
+ * Fix packaging metadata (advertise Python 3.4 support)
+
+2.4.0 (2015-04-01)
+------------------
+
+*New:*
+
+ * `#16 <https://github.com/rbarrois/python-semanticversion/issues/16>`_: Add an API for bumping versions,
+ by @RickEyre.
+
+2.3.1 (2014-09-24)
+------------------
+
+*Bugfix:*
+
+ * `#13 <https://github.com/rbarrois/python-semanticversion/issues/13>`_: Fix handling of files encoding
+ in ``setup.py``.
+
+2.3.0 (2014-03-16)
+------------------
+
+*New:*
+
+ * Handle the full ``semver-2.0.0`` specifications (instead of the ``2.0.0-rc2`` of previous releases)
+ * `#8 <https://github.com/rbarrois/python-semanticversion/issues/8>`_: Allow ``'*'`` as a valid version spec
+
+
+2.2.2 (2013-12-23)
+------------------
+
+*Bugfix:*
+
+ * `#5 <https://github.com/rbarrois/python-semanticversion/issues/5>`_: Fix packaging (broken
+ symlinks, old-style distutils, etc.)
+
+2.2.1 (2013-10-29)
+------------------
+
+*Bugfix:*
+
+ * `#2 <https://github.com/rbarrois/python-semanticversion/issues/2>`_: Properly expose
+ :func:`~semantic_version.validate` as a top-level module function.
+
+2.2.0 (2013-03-22)
+------------------
+
+*Bugfix:*
+
+ * `#1 <https://github.com/rbarrois/python-semanticversion/issues/1>`_: Allow partial
+ versions without minor or patch level
+
+*New:*
+
+ * Add the :meth:`Version.coerce <semantic_version.Version.coerce>` class method to
+ :class:`~semantic_version.Version` class for mapping arbitrary version strings to
+ semver.
+ * Add the :func:`~semantic_version.validate` method to validate a version
+ string against the SemVer rules.
+ * Full Python3 support
+
+2.1.2 (2012-05-22)
+------------------
+
+*Bugfix:*
+
+ * Properly validate :class:`~semantic_version.django_fields.VersionField` and
+ :class:`~semantic_version.django_fields.SpecField`.
+
+2.1.1 (2012-05-22)
+------------------
+
+*New:*
+
+ * Add introspection rules for south
+
+2.1.0 (2012-05-22)
+------------------
+
+*New:*
+
+ * Add :func:`semantic_version.Spec.filter` (filter a list of :class:`~semantic_version.Version`)
+ * Add :func:`semantic_version.Spec.select` (select the highest
+ :class:`~semantic_version.Version` from a list)
+ * Update :func:`semantic_version.Version.__repr__`
+
+2.0.0 (2012-05-22)
+------------------
+
+*Backwards incompatible changes:*
+
+ * Removed "loose" specification support
+ * Cleanup :class:`~semantic_version.Spec` to be more intuitive.
+ * Merge Spec and SpecList into :class:`~semantic_version.Spec`.
+ * Remove :class:`~semantic_version.django_fields.SpecListField`
+
+1.2.0 (2012-05-18)
+------------------
+
+*New:*
+
+ * Allow split specifications when instantiating a
+ :class:`~semantic_version.SpecList`::
+
+ >>> SpecList('>=0.1.1', '!=0.1.3') == SpecList('>=0.1.1,!=0.1.3')
+ True
+
+1.1.0 (2012-05-18)
+------------------
+
+*New:*
+
+ * Improved "loose" specification support (``>~``, ``<~``, ``!~``)
+ * Introduced "not equal" specifications (``!=``, ``!~``)
+ * :class:`~semantic_version.SpecList` class combining many :class:`~semantic_version.Spec`
+ * Add :class:`~semantic_version.django_fields.SpecListField` to store a :class:`~semantic_version.SpecList`.
+
+1.0.0 (2012-05-17)
+------------------
+
+First public release.
+
+*New:*
+
+ * :class:`~semantic_version.Version` and :class:`~semantic_version.Spec` classes
+ * Related django fields: :class:`~semantic_version.django_fields.VersionField`
+ and :class:`~semantic_version.django_fields.SpecField`
+
+.. vim:et:ts=4:sw=4:tw=79:ft=rst:
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/LICENSE
@@ -0,0 +1,22 @@
+Copyright (c) The python-semanticversion project
+All rights reserved.
+
+Redistribution and use in source and binary forms, with or without
+modification, are permitted provided that the following conditions are met:
+
+1. Redistributions of source code must retain the above copyright notice, this
+ list of conditions and the following disclaimer.
+2. Redistributions in binary form must reproduce the above copyright notice,
+ this list of conditions and the following disclaimer in the documentation
+ and/or other materials provided with the distribution.
+
+THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
+ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
+ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/MANIFEST.in
@@ -0,0 +1,9 @@
+include CREDITS
+include ChangeLog
+include LICENSE
+include README.rst
+include docs/Makefile
+recursive-include docs *.py *.rst
+include docs/_static/.keep_dir
+prune docs/_build
+recursive-include tests *.py
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/Makefile
@@ -0,0 +1,56 @@
+PACKAGE=semantic_version
+TESTS_DIR=tests
+DOC_DIR=docs
+
+# Use current python binary instead of system default.
+COVERAGE = python $(shell which coverage)
+
+# Dependencies
+DJANGO_VERSION ?= 1.9
+PYTHON_VERSION := $(shell python --version)
+NEXT_DJANGO_VERSION=$(shell python -c "v='$(DJANGO_VERSION)'; parts=v.split('.'); parts[-1]=str(int(parts[-1])+1); print('.'.join(parts))")
+
+
+all: default
+
+
+default:
+
+
+install-deps: auto_dev_requirements_django_$(DJANGO_VERSION).txt
+ pip install --upgrade pip setuptools
+ pip install --upgrade -r $<
+ pip freeze
+
+auto_dev_requirements_%.txt: dev_requirements.txt requirements.txt
+ grep --no-filename "^[^#-]" $^ | grep -v "^Django" > $@
+ echo "Django>=$(DJANGO_VERSION),<$(NEXT_DJANGO_VERSION)" >> $@
+
+clean:
+ find . -type f -name '*.pyc' -delete
+ find . -type f -path '*/__pycache__/*' -delete
+ find . -type d -empty -delete
+ @rm -f auto_dev_requirements_*
+ @rm -rf tmp_test/
+
+
+test: install-deps
+ python -W default setup.py test
+
+pylint:
+ pylint --rcfile=.pylintrc --report=no $(PACKAGE)/
+
+coverage: install-deps
+ $(COVERAGE) erase
+ $(COVERAGE) run "--include=$(PACKAGE)/*.py,$(TESTS_DIR)/*.py" --branch setup.py test
+ $(COVERAGE) report "--include=$(PACKAGE)/*.py,$(TESTS_DIR)/*.py"
+ $(COVERAGE) html "--include=$(PACKAGE)/*.py,$(TESTS_DIR)/*.py"
+
+coverage-xml-report: coverage
+ $(COVERAGE) xml "--include=$(PACKAGE)/*.py,$(TESTS_DIR)/*.py"
+
+doc:
+ $(MAKE) -C $(DOC_DIR) html
+
+
+.PHONY: all default clean coverage doc install-deps pylint test
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/README.rst
@@ -0,0 +1,334 @@
+python-semanticversion
+======================
+
+This small python library provides a few tools to handle `SemVer`_ in Python.
+It follows strictly the 2.0.0 version of the SemVer scheme.
+
+.. image:: https://secure.travis-ci.org/rbarrois/python-semanticversion.png?branch=master
+ :target: http://travis-ci.org/rbarrois/python-semanticversion/
+
+.. image:: https://img.shields.io/pypi/v/semantic_version.svg
+ :target: http://python-semanticversion.readthedocs.org/en/latest/changelog.html
+ :alt: Latest Version
+
+.. image:: https://img.shields.io/pypi/pyversions/semantic_version.svg
+ :target: https://pypi.python.org/pypi/semantic_version/
+ :alt: Supported Python versions
+
+.. image:: https://img.shields.io/pypi/wheel/semantic_version.svg
+ :target: https://pypi.python.org/pypi/semantic_version/
+ :alt: Wheel status
+
+.. image:: https://img.shields.io/pypi/l/semantic_version.svg
+ :target: https://pypi.python.org/pypi/semantic_version/
+ :alt: License
+
+Links
+-----
+
+- Package on `PyPI`_: http://pypi.python.org/pypi/semantic_version/
+- Doc on `ReadTheDocs <http://readthedocs.org/>`_: http://readthedocs.org/docs/python-semanticversion/
+- Source on `GitHub <http://github.com/>`_: http://github.com/rbarrois/python-semanticversion/
+- Build on `Travis CI <http://travis-ci.org/>`_: http://travis-ci.org/rbarrois/python-semanticversion/
+- Semantic Version specification: `SemVer`_
+
+
+Getting started
+===============
+
+Install the package from `PyPI`_, using pip:
+
+.. code-block:: sh
+
+ pip install semantic_version
+
+Or from GitHub:
+
+.. code-block:: sh
+
+ $ git clone git://github.com/rbarrois/python-semanticversion.git
+
+
+Import it in your code:
+
+
+.. code-block:: python
+
+ import semantic_version
+
+
+.. currentmodule:: semantic_version
+
+This module provides two classes to handle semantic versions:
+
+- :class:`Version` represents a version number (``0.1.1-alpha+build.2012-05-15``)
+- :class:`Spec` represents a requirement specification (``>=0.1.1,<0.3.0``)
+
+Versions
+--------
+
+Defining a :class:`Version` is quite simple:
+
+
+.. code-block:: pycon
+
+ >>> import semantic_version
+ >>> v = semantic_version.Version('0.1.1')
+ >>> v.major
+ 0
+ >>> v.minor
+ 1
+ >>> v.patch
+ 1
+ >>> v.prerelease
+ []
+ >>> v.build
+ []
+ >>> list(v)
+ [0, 1, 1, [], []]
+
+If the provided version string is invalid, a :exc:`ValueError` will be raised:
+
+.. code-block:: pycon
+
+ >>> semantic_version.Version('0.1')
+ Traceback (most recent call last):
+ File "<stdin>", line 1, in <module>
+ File "/Users/rbarrois/dev/semantic_version/src/semantic_version/base.py", line 64, in __init__
+ major, minor, patch, prerelease, build = self.parse(version_string, partial)
+ File "/Users/rbarrois/dev/semantic_version/src/semantic_version/base.py", line 86, in parse
+ raise ValueError('Invalid version string: %r' % version_string)
+ ValueError: Invalid version string: '0.1'
+
+In order to define "relaxed" version strings, you must pass in ``partial=True``:
+
+.. code-block:: pycon
+
+ >>> v = semantic_version.Version('0.1', partial=True)
+ >>> list(v)
+ [0, 1, None, None, None]
+
+
+Obviously, :class:`Versions <Version>` can be compared:
+
+
+.. code-block:: pycon
+
+ >>> semantic_version.Version('0.1.1') < semantic_version.Version('0.1.2')
+ True
+ >>> semantic_version.Version('0.1.1') > semantic_version.Version('0.1.1-alpha')
+ True
+ >>> semantic_version.Version('0.1.1') <= semantic_version.Version('0.1.1-alpha')
+ False
+
+You can also get a new version that represents a bump in one of the version levels:
+
+.. code-block:: pycon
+
+ >>> v = semantic_version.Version('0.1.1-pre+build')
+ >>> new_v = v.next_major()
+ >>> str(new_v)
+ '1.0.0'
+ >>> v = semantic_version.Version('1.1.1-pre+build')
+ >>> new_v = v.next_minor()
+ >>> str(new_v)
+ '1.2.0'
+ >>> v = semantic_version.Version('1.1.1-pre+build')
+ >>> new_v = v.next_patch()
+ >>> str(new_v)
+ '1.1.2'
+
+It is also possible to check whether a given string is a proper semantic version string:
+
+
+.. code-block:: pycon
+
+ >>> semantic_version.validate('0.1.3')
+ True
+ >>> semantic_version.validate('0a2')
+ False
+
+
+Requirement specification
+-------------------------
+
+The :class:`Spec` object describes a range of accepted versions:
+
+
+.. code-block:: pycon
+
+ >>> s = Spec('>=0.1.1') # At least 0.1.1
+ >>> s.match(Version('0.1.1'))
+ True
+ >>> s.match(Version('0.1.1-alpha1')) # pre-release satisfy version spec
+ True
+ >>> s.match(Version('0.1.0'))
+ False
+
+Simpler test syntax is also available using the ``in`` keyword:
+
+.. code-block:: pycon
+
+ >>> s = Spec('==0.1.1')
+ >>> Version('0.1.1-alpha1') in s
+ True
+ >>> Version('0.1.2') in s
+ False
+
+
+Combining specifications can be expressed in two ways:
+
+- Components separated by commas in a single string:
+
+ .. code-block:: pycon
+
+ >>> Spec('>=0.1.1,<0.3.0')
+
+- Components given as different arguments:
+
+ .. code-block:: pycon
+
+ >>> Spec('>=0.1.1', '<0.3.0')
+
+- A mix of both versions:
+
+ .. code-block:: pycon
+
+ >>> Spec('>=0.1.1', '!=0.2.4-alpha,<0.3.0')
+
+
+Using a specification
+"""""""""""""""""""""
+
+The :func:`Spec.filter` method filters an iterable of :class:`Version`:
+
+.. code-block:: pycon
+
+ >>> s = Spec('>=0.1.0,<0.4.0')
+ >>> versions = (Version('0.%d.0' % i) for i in range(6))
+ >>> for v in s.filter(versions):
+ ... print v
+ 0.1.0
+ 0.2.0
+ 0.3.0
+
+It is also possible to select the 'best' version from such iterables:
+
+
+.. code-block:: pycon
+
+ >>> s = Spec('>=0.1.0,<0.4.0')
+ >>> versions = (Version('0.%d.0' % i) for i in range(6))
+ >>> s.select(versions)
+ Version('0.3.0')
+
+
+Coercing an arbitrary version string
+""""""""""""""""""""""""""""""""""""
+
+Some user-supplied input might not match the semantic version scheme.
+For such cases, the :meth:`Version.coerce` method will try to convert any
+version-like string into a valid semver version:
+
+.. code-block:: pycon
+
+ >>> Version.coerce('0')
+ Version('0.0.0')
+ >>> Version.coerce('0.1.2.3.4')
+ Version('0.1.2+3.4')
+ >>> Version.coerce('0.1.2a3')
+ Version('0.1.2-a3')
+
+
+Including pre-release identifiers in specifications
+"""""""""""""""""""""""""""""""""""""""""""""""""""
+
+When testing a :class:`Version` against a :class:`Spec`, comparisons are only
+performed for components defined in the :class:`Spec`; thus, a pre-release
+version (``1.0.0-alpha``), while not strictly equal to the non pre-release
+version (``1.0.0``), satisfies the ``==1.0.0`` :class:`Spec`.
+
+Pre-release identifiers will only be compared if included in the :class:`Spec`
+definition or (for the empty pre-release number) if a single dash is appended
+(``1.0.0-``):
+
+
+.. code-block:: pycon
+
+ >>> Version('0.1.0-alpha') in Spec('>=0.1.0') # No pre-release identifier
+ True
+ >>> Version('0.1.0-alpha') in Spec('>=0.1.0-') # Include pre-release in checks
+ False
+
+
+Including build metadata in specifications
+""""""""""""""""""""""""""""""""""""""""""
+
+Build metadata has no ordering; thus, the only meaningful comparison including
+build metadata is equality.
+
+
+.. code-block:: pycon
+
+ >>> Version('1.0.0+build2') in Spec('<=1.0.0') # Build metadata ignored
+ True
+ >>> Version('1.0.0+build2') in Spec('==1.0.0+build2') # Include build in checks
+ False
+
+
+Using with Django
+=================
+
+The :mod:`semantic_version.django_fields` module provides django fields to
+store :class:`Version` or :class:`Spec` objects.
+
+More documentation is available in the :doc:`django` section.
+
+
+Contributing
+============
+
+In order to contribute to the source code:
+
+- Open an issue on `GitHub`_: https://github.com/rbarrois/python-semanticversion/issues
+- Fork the `repository <https://github.com/rbarrois/python-semanticversion>`_
+ and submit a pull request on `GitHub`_
+- Or send me a patch (mailto:raphael.barrois+semver@polytechnique.org)
+
+When submitting patches or pull requests, you should respect the following rules:
+
+- Coding conventions are based on :pep:`8`
+- The whole test suite must pass after adding the changes
+- The test coverage for a new feature must be 100%
+- New features and methods should be documented in the :doc:`reference` section
+ and included in the :doc:`changelog`
+- Include your name in the :ref:`contributors` section
+
+.. note:: All files should contain the following header::
+
+ # -*- encoding: utf-8 -*-
+ # Copyright (c) The python-semanticversion project
+
+
+Contents
+========
+
+.. toctree::
+ :maxdepth: 2
+
+ reference
+ django
+ changelog
+ credits
+
+
+.. _SemVer: http://semver.org/
+.. _PyPI: http://pypi.python.org/
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/dev_requirements.txt
@@ -0,0 +1,2 @@
+Django
+coverage
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/docs/Makefile
@@ -0,0 +1,153 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS =
+SPHINXBUILD = sphinx-build
+PAPER =
+BUILDDIR = _build
+
+# Internal variables.
+PAPEROPT_a4 = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+# the i18n builder cannot share the environment and doctrees with the others
+I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
+
+.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
+
+help:
+ @echo "Please use \`make <target>' where <target> is one of"
+ @echo " html to make standalone HTML files"
+ @echo " dirhtml to make HTML files named index.html in directories"
+ @echo " singlehtml to make a single large HTML file"
+ @echo " pickle to make pickle files"
+ @echo " json to make JSON files"
+ @echo " htmlhelp to make HTML files and a HTML help project"
+ @echo " qthelp to make HTML files and a qthelp project"
+ @echo " devhelp to make HTML files and a Devhelp project"
+ @echo " epub to make an epub"
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+ @echo " latexpdf to make LaTeX files and run them through pdflatex"
+ @echo " text to make text files"
+ @echo " man to make manual pages"
+ @echo " texinfo to make Texinfo files"
+ @echo " info to make Texinfo files and run them through makeinfo"
+ @echo " gettext to make PO message catalogs"
+ @echo " changes to make an overview of all changed/added/deprecated items"
+ @echo " linkcheck to check all external links for integrity"
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
+
+clean:
+ -rm -rf $(BUILDDIR)/*
+
+html:
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+dirhtml:
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+singlehtml:
+ $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
+ @echo
+ @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
+
+pickle:
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+ @echo
+ @echo "Build finished; now you can process the pickle files."
+
+json:
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
+ @echo
+ @echo "Build finished; now you can process the JSON files."
+
+htmlhelp:
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+ @echo
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
+ ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+qthelp:
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+ @echo
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/python-semanticversion.qhcp"
+ @echo "To view the help file:"
+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/python-semanticversion.qhc"
+
+devhelp:
+ $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
+ @echo
+ @echo "Build finished."
+ @echo "To view the help file:"
+ @echo "# mkdir -p $$HOME/.local/share/devhelp/python-semanticversion"
+ @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/python-semanticversion"
+ @echo "# devhelp"
+
+epub:
+ $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
+ @echo
+ @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
+
+latex:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo
+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+ @echo "Run \`make' in that directory to run these through (pdf)latex" \
+ "(use \`make latexpdf' here to do that automatically)."
+
+latexpdf:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo "Running LaTeX files through pdflatex..."
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+text:
+ $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
+ @echo
+ @echo "Build finished. The text files are in $(BUILDDIR)/text."
+
+man:
+ $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
+ @echo
+ @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
+
+texinfo:
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+ @echo
+ @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
+ @echo "Run \`make' in that directory to run these through makeinfo" \
+ "(use \`make info' here to do that automatically)."
+
+info:
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+ @echo "Running Texinfo files through makeinfo..."
+ make -C $(BUILDDIR)/texinfo info
+ @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
+
+gettext:
+ $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
+ @echo
+ @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
+
+changes:
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+ @echo
+ @echo "The overview file is in $(BUILDDIR)/changes."
+
+linkcheck:
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+ @echo
+ @echo "Link check complete; look for any errors in the above output " \
+ "or in $(BUILDDIR)/linkcheck/output.txt."
+
+doctest:
+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+ @echo "Testing of doctests in the sources finished, look at the " \
+ "results in $(BUILDDIR)/doctest/output.txt."
new file mode 120000
--- /dev/null
+++ b/python/semantic_version/docs/changelog.rst
@@ -0,0 +1,1 @@
+../ChangeLog
\ No newline at end of file
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/docs/conf.py
@@ -0,0 +1,251 @@
+# -*- coding: utf-8 -*-
+#
+# python-semanticversion documentation build configuration file, created by
+# sphinx-quickstart on Wed May 16 10:41:34 2012.
+#
+# This file is execfile()d with the current directory set to its containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys, os
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#sys.path.insert(0, os.path.abspath('.'))
+
+# -- General configuration -----------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be extensions
+# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
+extensions = []
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix of source filenames.
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'index'
+
+# General information about the project.
+project = u'python-semanticversion'
+copyright = u'2012-2014, The python-semanticversion project'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+root_dir = os.path.abspath(os.path.dirname(__file__))
+def get_version():
+ import re
+ version_re = re.compile(r"^__version__ = '([\w_.-]+)'$")
+ with open(os.path.join(root_dir, os.pardir, 'semantic_version', '__init__.py')) as f:
+ for line in f:
+ match = version_re.match(line[:-1])
+ if match:
+ return match.groups()[0]
+ return '0.0.0'
+
+release = get_version()
+version = '.'.join(release.split('.')[:2])
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+exclude_patterns = ['_build']
+
+# The reST default role (used for this markup: `text`) to use for all documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+
+# -- Options for HTML output ---------------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+html_theme = 'default'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents. If None, it defaults to
+# "<project> v<release> documentation".
+#html_title = None
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (within the static path) to use as favicon of the
+# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
+# using the given strftime format.
+#html_last_updated_fmt = '%b %d, %Y'
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+#html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'python-semanticversiondoc'
+
+
+# -- Options for LaTeX output --------------------------------------------------
+
+latex_elements = {
+# The paper size ('letterpaper' or 'a4paper').
+#'papersize': 'letterpaper',
+
+# The font size ('10pt', '11pt' or '12pt').
+#'pointsize': '10pt',
+
+# Additional stuff for the LaTeX preamble.
+#'preamble': '',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title, author, documentclass [howto/manual]).
+latex_documents = [
+ ('index', 'python-semanticversion.tex', u'python-semanticversion Documentation',
+ u'Raphaël Barrois', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output --------------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ ('index', 'python-semanticversion', u'python-semanticversion Documentation',
+ [u'Raphaël Barrois'], 1)
+]
+
+# If true, show URL addresses after external links.
+#man_show_urls = False
+
+
+# -- Options for Texinfo output ------------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+# dir menu entry, description, category)
+texinfo_documents = [
+ ('index', 'python-semanticversion', u'python-semanticversion Documentation',
+ u'Raphaël Barrois', 'python-semanticversion', 'One line description of project.',
+ 'Miscellaneous'),
+]
+
+# Documents to append as an appendix to all manuals.
+#texinfo_appendices = []
+
+# If false, no module index is generated.
+#texinfo_domain_indices = True
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+#texinfo_show_urls = 'footnote'
new file mode 120000
--- /dev/null
+++ b/python/semantic_version/docs/credits.rst
@@ -0,0 +1,1 @@
+../CREDITS
\ No newline at end of file
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/docs/django.rst
@@ -0,0 +1,31 @@
+Interaction with Django
+=======================
+
+.. module:: semantic_version.django_fields
+
+The ``python-semanticversion`` package provides two custom fields for Django:
+
+- :class:`VersionField`: stores a :class:`semantic_version.Version` object
+- :class:`SpecField`: stores a :class:`semantic_version.Spec` object
+
+Those fields are :class:`django.db.models.CharField` subclasses,
+with their :attr:`~django.db.models.CharField.max_length` defaulting to 200.
+
+
+.. class:: VersionField
+
+ Stores a :class:`semantic_version.Version` as its string representation.
+
+ .. attribute:: partial
+
+ Boolean; whether :attr:`~semantic_version.Version.partial` versions are allowed.
+
+ .. attribute:: coerce
+
+ Boolean; whether passed in values should be coerced into a semver string
+ before storing.
+
+
+.. class:: SpecField
+
+ Stores a :class:`semantic_version.Spec` as its comma-separated string representation.
new file mode 120000
--- /dev/null
+++ b/python/semantic_version/docs/index.rst
@@ -0,0 +1,1 @@
+../README.rst
\ No newline at end of file
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/docs/make.bat
@@ -0,0 +1,190 @@
+@ECHO OFF
+
+REM Command file for Sphinx documentation
+
+if "%SPHINXBUILD%" == "" (
+ set SPHINXBUILD=sphinx-build
+)
+set BUILDDIR=_build
+set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% .
+set I18NSPHINXOPTS=%SPHINXOPTS% .
+if NOT "%PAPER%" == "" (
+ set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS%
+ set I18NSPHINXOPTS=-D latex_paper_size=%PAPER% %I18NSPHINXOPTS%
+)
+
+if "%1" == "" goto help
+
+if "%1" == "help" (
+ :help
+ echo.Please use `make ^<target^>` where ^<target^> is one of
+ echo. html to make standalone HTML files
+ echo. dirhtml to make HTML files named index.html in directories
+ echo. singlehtml to make a single large HTML file
+ echo. pickle to make pickle files
+ echo. json to make JSON files
+ echo. htmlhelp to make HTML files and a HTML help project
+ echo. qthelp to make HTML files and a qthelp project
+ echo. devhelp to make HTML files and a Devhelp project
+ echo. epub to make an epub
+ echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter
+ echo. text to make text files
+ echo. man to make manual pages
+ echo. texinfo to make Texinfo files
+ echo. gettext to make PO message catalogs
+ echo. changes to make an overview over all changed/added/deprecated items
+ echo. linkcheck to check all external links for integrity
+ echo. doctest to run all doctests embedded in the documentation if enabled
+ goto end
+)
+
+if "%1" == "clean" (
+ for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i
+ del /q /s %BUILDDIR%\*
+ goto end
+)
+
+if "%1" == "html" (
+ %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The HTML pages are in %BUILDDIR%/html.
+ goto end
+)
+
+if "%1" == "dirhtml" (
+ %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml.
+ goto end
+)
+
+if "%1" == "singlehtml" (
+ %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml.
+ goto end
+)
+
+if "%1" == "pickle" (
+ %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can process the pickle files.
+ goto end
+)
+
+if "%1" == "json" (
+ %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can process the JSON files.
+ goto end
+)
+
+if "%1" == "htmlhelp" (
+ %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can run HTML Help Workshop with the ^
+.hhp project file in %BUILDDIR%/htmlhelp.
+ goto end
+)
+
+if "%1" == "qthelp" (
+ %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; now you can run "qcollectiongenerator" with the ^
+.qhcp project file in %BUILDDIR%/qthelp, like this:
+ echo.^> qcollectiongenerator %BUILDDIR%\qthelp\python-semanticversion.qhcp
+ echo.To view the help file:
+ echo.^> assistant -collectionFile %BUILDDIR%\qthelp\python-semanticversion.ghc
+ goto end
+)
+
+if "%1" == "devhelp" (
+ %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished.
+ goto end
+)
+
+if "%1" == "epub" (
+ %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The epub file is in %BUILDDIR%/epub.
+ goto end
+)
+
+if "%1" == "latex" (
+ %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished; the LaTeX files are in %BUILDDIR%/latex.
+ goto end
+)
+
+if "%1" == "text" (
+ %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The text files are in %BUILDDIR%/text.
+ goto end
+)
+
+if "%1" == "man" (
+ %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The manual pages are in %BUILDDIR%/man.
+ goto end
+)
+
+if "%1" == "texinfo" (
+ %SPHINXBUILD% -b texinfo %ALLSPHINXOPTS% %BUILDDIR%/texinfo
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The Texinfo files are in %BUILDDIR%/texinfo.
+ goto end
+)
+
+if "%1" == "gettext" (
+ %SPHINXBUILD% -b gettext %I18NSPHINXOPTS% %BUILDDIR%/locale
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Build finished. The message catalogs are in %BUILDDIR%/locale.
+ goto end
+)
+
+if "%1" == "changes" (
+ %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.The overview file is in %BUILDDIR%/changes.
+ goto end
+)
+
+if "%1" == "linkcheck" (
+ %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Link check complete; look for any errors in the above output ^
+or in %BUILDDIR%/linkcheck/output.txt.
+ goto end
+)
+
+if "%1" == "doctest" (
+ %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest
+ if errorlevel 1 exit /b 1
+ echo.
+ echo.Testing of doctests in the sources finished, look at the ^
+results in %BUILDDIR%/doctest/output.txt.
+ goto end
+)
+
+:end
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/docs/reference.rst
@@ -0,0 +1,570 @@
+Reference
+=========
+
+
+.. module:: semantic_version
+
+
+Module-level functions
+----------------------
+
+.. function:: compare(v1, v2)
+
+ Compare two version strings, and return a result similar to that of :func:`cmp`::
+
+ >>> compare('0.1.1', '0.1.2')
+ -1
+ >>> compare('0.1.1', '0.1.1')
+ 0
+ >>> compare('0.1.1', '0.1.1-alpha')
+ 1
+
+ :param str v1: The first version to compare
+ :param str v2: The second version to compare
+ :raises: :exc:`ValueError`, if any version string is invalid
+ :rtype: ``int``, -1 / 0 / 1 as for a :func:`cmp` comparison;
+ ``NotImplemented`` if versions only differ by build metadata
+
+
+.. warning:: Since build metadata has no ordering,
+ ``compare(Version('0.1.1'), Version('0.1.1+3'))`` returns ``NotImplemented``
+
+
+.. function:: match(spec, version)
+
+ Check whether a version string matches a specification string::
+
+ >>> match('>=0.1.1', '0.1.2')
+ True
+ >>> match('>=0.1.1', '0.1.1-alpha')
+ False
+ >>> match('~0.1.1', '0.1.1-alpha')
+ True
+
+ :param str spec: The specification to use, as a string
+ :param str version: The version string to test against the spec
+ :raises: :exc:`ValueError`, if the ``spec`` or the ``version`` is invalid
+ :rtype: ``bool``
+
+
+.. function:: validate(version)
+
+ Check whether a version string complies with the `SemVer`_ rules.
+
+ .. code-block:: pycon
+
+ >>> semantic_version.validate('1.1.1')
+ True
+ >>> semantic_version.validate('1.2.3a4')
+ False
+
+ :param str version: The version string to validate
+ :rtype: ``bool``
+
+
+Representing a version (the Version class)
+------------------------------------------
+
+.. class:: Version(version_string[, partial=False])
+
+ Object representation of a `SemVer`_-compliant version.
+
+ Constructed from a textual version string::
+
+ >>> Version('1.1.1')
+ Version('1.1.1')
+ >>> str(Version('1.1.1'))
+ '1.1.1'
+
+
+ .. rubric:: Attributes
+
+
+ .. attribute:: partial
+
+ ``bool``, whether this is a 'partial' or a complete version number.
+ Partial version number may lack :attr:`minor` or :attr:`patch` version numbers.
+
+ .. attribute:: major
+
+ ``int``, the major version number
+
+ .. attribute:: minor
+
+ ``int``, the minor version number.
+
+ May be ``None`` for a :attr:`partial` version number in a ``<major>`` format.
+
+ .. attribute:: patch
+
+ ``int``, the patch version number.
+
+ May be ``None`` for a :attr:`partial` version number in a ``<major>`` or ``<major>.<minor>`` format.
+
+ .. attribute:: prerelease
+
+ ``tuple`` of ``strings``, the prerelease component.
+
+ It contains the various dot-separated identifiers in the prerelease component.
+
+ May be ``None`` for a :attr:`partial` version number in a ``<major>``, ``<major>.<minor>`` or ``<major>.<minor>.<patch>`` format.
+
+ .. attribute:: build
+
+ ``tuple`` of ``strings``, the build metadata.
+
+ It contains the various dot-separated identifiers in the build metadata.
+
+ May be ``None`` for a :attr:`partial` version number in a ``<major>``, ``<major>.<minor>``,
+ ``<major>.<minor>.<patch>`` or ``<major>.<minor>.<patch>-<prerelease>`` format.
+
+
+ .. rubric:: Methods
+
+
+ .. method:: __iter__(self)
+
+ Iterates over the version components (:attr:`major`, :attr:`minor`,
+ :attr:`patch`, :attr:`prerelease`, :attr:`build`)::
+
+ >>> list(Version('0.1.1'))
+ [0, 1, 1, [], []]
+
+ .. note:: This may pose some subtle bugs when iterating over a single version
+ while expecting an iterable of versions -- similar to::
+
+ >>> list('abc')
+ ['a', 'b', 'c']
+ >>> list(('abc',))
+ ['abc']
+
+
+ .. method:: __cmp__(self, other)
+
+ Provides comparison methods with other :class:`Version` objects.
+
+ The rules are:
+
+ - For non-:attr:`partial` versions, compare using the `SemVer`_ scheme
+ - If any compared object is :attr:`partial`:
+ - Begin comparison using the `SemVer`_ scheme
+ - If a component (:attr:`minor`, :attr:`patch`, :attr:`prerelease` or :attr:`build`)
+ was absent from the :attr:`partial` :class:`Version` -- represented with :obj:`None`
+ --, consider both versions equal.
+
+ For instance, ``Version('1.0', partial=True)`` means "any version beginning in ``1.0``".
+
+ ``Version('1.0.1-alpha', partial=True)`` means "The ``1.0.1-alpha`` version or any
+ any release differing only in build metadata": ``1.0.1-alpha+build3`` matches, ``1.0.1-alpha.2`` doesn't.
+
+ Examples::
+
+ >>> Version('1.0', partial=True) == Version('1.0.1')
+ True
+ >>> Version('1.0.1-rc1.1') == Version('1.0.1-rc1', partial=True)
+ False
+ >>> Version('1.0.1-rc1+build345') == Version('1.0.1-rc1')
+ False
+ >>> Version('1.0.1-rc1+build345') == Version('1.0.1-rc1', partial=True)
+ True
+
+
+ .. method:: __str__(self)
+
+ Returns the standard text representation of the version::
+
+ >>> v = Version('0.1.1-rc2+build4.4')
+ >>> v
+ Version('0.1.1-rc2+build4.4')
+ >>> str(v)
+ '0.1.1-rc2+build4.4'
+
+
+ .. method:: __hash__(self)
+
+ Provides a hash based solely on the components.
+
+ Allows using a :class:`Version` as a dictionary key.
+
+ .. note:: A fully qualified :attr:`partial` :class:`Version`
+
+ (up to the :attr:`build` component) will hash the same as the
+ equally qualified, non-:attr:`partial` :class:`Version`::
+
+ >>> hash(Version('1.0.1+build4')) == hash(Version('1.0.1+build4', partial=True))
+ True
+
+
+ .. rubric:: Class methods
+
+
+ .. classmethod:: parse(cls, version_string[, partial=False])
+
+ Parse a version string into a ``(major, minor, patch, prerelease, build)`` tuple.
+
+ :param str version_string: The version string to parse
+ :param bool partial: Whether this should be considered a :attr:`partial` version
+ :raises: :exc:`ValueError`, if the :attr:`version_string` is invalid.
+ :rtype: (major, minor, patch, prerelease, build)
+
+ .. classmethod:: coerce(cls, version_string[, partial=False])
+
+ Try to convert an arbitrary version string into a :class:`Version` instance.
+
+ Rules are:
+
+ - If no minor or patch component, and :attr:`partial` is :obj:`False`,
+ replace them with zeroes
+ - Any character outside of ``a-zA-Z0-9.+-`` is replaced with a ``-``
+ - If more than 3 dot-separated numerical components, everything from the
+ fourth component belongs to the :attr:`build` part
+ - Any extra ``+`` in the :attr:`build` part will be replaced with dots
+
+ Examples:
+
+ .. code-block:: pycon
+
+ >>> Version.coerce('02')
+ Version('2.0.0')
+ >>> Version.coerce('1.2.3.4')
+ Version('1.2.3+4')
+ >>> Version.coerce('1.2.3.4beta2')
+ Version('1.2.3+4beta2')
+ >>> Version.coerce('1.2.3.4.5_6/7+8+9+10')
+ Version('1.2.3+4.5-6-7.8.9.10')
+
+ :param str version_string: The version string to coerce
+ :param bool partial: Whether to allow generating a :attr:`partial` version
+ :raises: :exc:`ValueError`, if the :attr:`version_string` is invalid.
+ :rtype: :class:`Version`
+
+
+Version specifications (the Spec class)
+---------------------------------------
+
+
+Version specifications describe a 'range' of accepted versions:
+older than, equal, similar to, …
+
+The main issue with representing version specifications is that the usual syntax
+does not map well onto `SemVer`_ precedence rules:
+
+* A specification of ``<1.3.4`` is not expected to allow ``1.3.4-rc2``, but strict `SemVer`_ comparisons allow it ;
+ prereleases has the issue of excluding ``1.3.3+build3`` ;
+* It may be necessary to exclude either all variations on a patch-level release
+ (``!=1.3.3``) or specifically one build-level release (``1.3.3-build.434``).
+
+
+In order to have version specification behave naturally, the rules are the following:
+
+* If no pre-release number was included in the specification, pre-release numbers
+ are ignored when deciding whether a version satisfies a specification.
+* If no build metadata was included in the specification, build metadata is ignored
+ when deciding whether a version satisfies a specification.
+
+This means that::
+
+ >>> Version('1.1.1-rc1') in Spec('<1.1.1')
+ False
+ >>> Version('1.1.1-rc1') in Spec('<1.1.1-rc4')
+ True
+ >>> Version('1.1.1-rc1+build4') in Spec('<=1.1.1-rc1')
+ True
+ >>> Version('1.1.1-rc1+build4') in Spec('==1.1.1-rc1+build2')
+ False
+
+
+.. note:: python-semanticversion also accepts ``"*"`` as a version spec,
+ that matches all (valid) version strings.
+
+.. note:: python-semanticversion includes support for NPM-style specs:
+
+ * ``~1.2.3`` means "Any release between 1.2.3 and 1.3.0"
+ * ``^1.3.4`` means "Any release between 1.3.4 and 2.0.0"
+
+In order to force matches to *strictly* compare version numbers, these additional
+rules apply:
+
+* Setting a pre-release separator without a pre-release identifier (``<=1.1.1-``)
+ forces match to take into account pre-release version::
+
+ >>> Version('1.1.1-rc1') in Spec('<1.1.1')
+ False
+ >>> Version('1.1.1-rc1') in Spec('<1.1.1-')
+ True
+
+* Setting a build metadata separator without build metadata (``<=1.1.1+``)
+ forces matches "up to the build metadata"; use this to include/exclude a
+ release lacking build metadata while excluding/including all other builds
+ of that release
+
+ >>> Version('1.1.1') in Spec('==1.1.1+')
+ True
+ >>> Version('1.1.1+2') in Spec('==1.1.1+')
+ False
+
+
+.. warning:: As stated in the `SemVer`_ specification, the ordering of build metadata is *undefined*.
+ Thus, a :class:`Spec` string can only mention build metadata to include or exclude a specific version:
+
+ * ``==1.1.1+b1234`` includes this specific build
+ * ``!=1.1.1+b1234`` excludes it (but would match ``1.1.1+b1235``
+ * ``<1.1.1+b1`` is invalid
+
+
+
+.. class:: Spec(spec_string[, spec_string[, ...]])
+
+ Stores a list of :class:`SpecItem` and matches any :class:`Version` against all
+ contained :class:`specs <SpecItem>`.
+
+ It is built from a comma-separated list of version specifications::
+
+ >>> Spec('>=1.0.0,<1.2.0,!=1.1.4')
+ <Spec: (
+ <SpecItem: >= Version('1.0.0', partial=True)>,
+ <SpecItem: < Version('1.2.0', partial=True)>,
+ <SpecItem: != Version('1.1.4', partial=True)>
+ )>
+
+ Version specifications may also be passed in separated arguments::
+
+ >>> Spec('>=1.0.0', '<1.2.0', '!=1.1.4,!=1.1.13')
+ <Spec: (
+ <SpecItem: >= Version('1.0.0', partial=True)>,
+ <SpecItem: < Version('1.2.0', partial=True)>,
+ <SpecItem: != Version('1.1.4', partial=True)>,
+ <SpecItem: != Version('1.1.13', partial=True)>,
+ )>
+
+
+ .. rubric:: Attributes
+
+
+ .. attribute:: specs
+
+ Tuple of :class:`SpecItem`, the included specifications.
+
+
+ .. rubric:: Methods
+
+
+ .. method:: match(self, version)
+
+ Test whether a given :class:`Version` matches all included :class:`SpecItem`::
+
+ >>> Spec('>=1.1.0,<1.1.2').match(Version('1.1.1'))
+ True
+
+ :param version: The version to test against the specs
+ :type version: :class:`Version`
+ :rtype: ``bool``
+
+
+ .. method:: filter(self, versions)
+
+ Extract all compatible :class:`versions <Version>` from an iterable of
+ :class:`Version` objects.
+
+ :param versions: The versions to filter
+ :type versions: iterable of :class:`Version`
+ :yield: :class:`Version`
+
+
+ .. method:: select(self, versions)
+
+ Select the highest compatible version from an iterable of :class:`Version`
+ objects.
+
+ .. sourcecode:: pycon
+
+ >>> s = Spec('>=0.1.0')
+ >>> s.select([])
+ None
+ >>> s.select([Version('0.1.0'), Version('0.1.3'), Version('0.1.1')])
+ Version('0.1.3')
+
+ :param versions: The versions to filter
+ :type versions: iterable of :class:`Version`
+ :rtype: The highest compatible :class:`Version` if at least one of the
+ given versions is compatible; :class:`None` otherwise.
+
+
+ .. method:: __contains__(self, version)
+
+ Alias of the :func:`match` method;
+ allows the use of the ``version in speclist`` syntax::
+
+ >>> Version('1.1.1-alpha') in Spec('>=1.1.0,<1.1.1')
+ True
+
+
+ .. method:: __str__(self)
+
+ Converting a :class:`Spec` returns the initial description string::
+
+ >>> str(Spec('>=0.1.1,!=0.1.2'))
+ '>=0.1.1,!=0.1.2'
+
+ .. method:: __iter__(self)
+
+ Returns an iterator over the contained specs::
+
+ >>> for spec in Spec('>=0.1.1,!=0.1.2'):
+ ... print spec
+ >=0.1.1
+ !=0.1.2
+
+ .. method:: __hash__(self)
+
+ Provides a hash based solely on the hash of contained specs.
+
+ Allows using a :class:`Spec` as a dictionary key.
+
+
+ .. rubric:: Class methods
+
+
+ .. classmethod:: parse(self, specs_string)
+
+ Retrieve a ``(*specs)`` tuple from a string.
+
+ :param str requirement_string: The textual description of the specifications
+ :raises: :exc:`ValueError`: if the ``requirement_string`` is invalid.
+ :rtype: ``(*spec)`` tuple
+
+
+.. class:: SpecItem(spec_string)
+
+ .. note:: This class belong to the private python-semanticversion API.
+
+ Stores a version specification, defined from a string::
+
+ >>> SpecItem('>=0.1.1')
+ <SpecItem: >= Version('0.1.1', partial=True)>
+
+ This allows to test :class:`Version` objects against the :class:`SpecItem`::
+
+ >>> SpecItem('>=0.1.1').match(Version('0.1.1-rc1')) # pre-release satisfy conditions
+ True
+ >>> Version('0.1.1+build2') in SpecItem('>=0.1.1') # build metadata is ignored when checking for precedence
+ True
+ >>>
+ >>> # Use the '-' marker to include the pre-release component in checks
+ >>> SpecItem('>=0.1.1-').match(Version('0.1.1-rc1')
+ False
+ >>> # Use the '+' marker to include the build metadata in checks
+ >>> SpecItem('==0.1.1+').match(Version('0.1.1+b1234')
+ False
+ >>>
+
+
+ .. rubric:: Attributes
+
+
+ .. attribute:: kind
+
+ One of :data:`KIND_LT`, :data:`KIND_LTE`, :data:`KIND_EQUAL`, :data:`KIND_GTE`,
+ :data:`KIND_GT` and :data:`KIND_NEQ`.
+
+ .. attribute:: spec
+
+ :class:`Version` in the :class:`SpecItem` description.
+
+ It is alway a :attr:`~Version.partial` :class:`Version`.
+
+
+ .. rubric:: Class methods
+
+
+ .. classmethod:: parse(cls, requirement_string)
+
+ Retrieve a ``(kind, version)`` tuple from a string.
+
+ :param str requirement_string: The textual description of the specification
+ :raises: :exc:`ValueError`: if the ``requirement_string`` is invalid.
+ :rtype: (``kind``, ``version``) tuple
+
+
+ .. rubric:: Methods
+
+
+ .. method:: match(self, version)
+
+ Test whether a given :class:`Version` matches this :class:`SpecItem`::
+
+ >>> SpecItem('>=0.1.1').match(Version('0.1.1-alpha'))
+ True
+ >>> SpecItem('>=0.1.1-').match(Version('0.1.1-alpha'))
+ False
+
+ :param version: The version to test against the spec
+ :type version: :class:`Version`
+ :rtype: ``bool``
+
+
+ .. method:: __str__(self)
+
+ Converting a :class:`SpecItem` to a string returns the initial description string::
+
+ >>> str(SpecItem('>=0.1.1'))
+ '>=0.1.1'
+
+
+ .. method:: __hash__(self)
+
+ Provides a hash based solely on the current kind and the specified version.
+
+ Allows using a :class:`SpecItem` as a dictionary key.
+
+
+ .. rubric:: Class attributes
+
+
+ .. data:: KIND_LT
+
+ The kind of 'Less than' specifications::
+
+ >>> Version('1.0.0-alpha') in Spec('<1.0.0')
+ False
+
+ .. data:: KIND_LTE
+
+ The kind of 'Less or equal to' specifications::
+
+ >>> Version('1.0.0-alpha1+build999') in Spec('<=1.0.0-alpha1')
+ True
+
+ .. data:: KIND_EQUAL
+
+ The kind of 'equal to' specifications::
+
+ >>> Version('1.0.0+build3.3') in Spec('==1.0.0')
+ True
+
+ .. data:: KIND_GTE
+
+ The kind of 'Greater or equal to' specifications::
+
+ >>> Version('1.0.0') in Spec('>=1.0.0')
+ True
+
+ .. data:: KIND_GT
+
+ The kind of 'Greater than' specifications::
+
+ >>> Version('1.0.0+build667') in Spec('>1.0.1')
+ False
+
+ .. data:: KIND_NEQ
+
+ The kind of 'Not equal to' specifications::
+
+ >>> Version('1.0.1') in Spec('!=1.0.1')
+ False
+
+ The kind of 'Almost equal to' specifications
+
+
+
+.. _SemVer: http://semver.org/
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/requirements.txt
@@ -0,0 +1,1 @@
+# No hard external requirements.
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/semantic_version/__init__.py
@@ -0,0 +1,10 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+
+__author__ = "Raphaël Barrois <raphael.barrois+semver@polytechnique.org>"
+__version__ = '2.5.0'
+
+
+from .base import compare, match, validate, Spec, SpecItem, Version
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/semantic_version/base.py
@@ -0,0 +1,549 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+from __future__ import unicode_literals
+
+import functools
+import re
+
+
+from .compat import base_cmp
+
+def _to_int(value):
+ try:
+ return int(value), True
+ except ValueError:
+ return value, False
+
+def _has_leading_zero(value):
+ return (value
+ and value[0] == '0'
+ and value.isdigit()
+ and value != '0')
+
+
+def identifier_cmp(a, b):
+ """Compare two identifier (for pre-release/build components)."""
+
+ a_cmp, a_is_int = _to_int(a)
+ b_cmp, b_is_int = _to_int(b)
+
+ if a_is_int and b_is_int:
+ # Numeric identifiers are compared as integers
+ return base_cmp(a_cmp, b_cmp)
+ elif a_is_int:
+ # Numeric identifiers have lower precedence
+ return -1
+ elif b_is_int:
+ return 1
+ else:
+ # Non-numeric identifers are compared lexicographically
+ return base_cmp(a_cmp, b_cmp)
+
+
+def identifier_list_cmp(a, b):
+ """Compare two identifier list (pre-release/build components).
+
+ The rule is:
+ - Identifiers are paired between lists
+ - They are compared from left to right
+ - If all first identifiers match, the longest list is greater.
+
+ >>> identifier_list_cmp(['1', '2'], ['1', '2'])
+ 0
+ >>> identifier_list_cmp(['1', '2a'], ['1', '2b'])
+ -1
+ >>> identifier_list_cmp(['1'], ['1', '2'])
+ -1
+ """
+ identifier_pairs = zip(a, b)
+ for id_a, id_b in identifier_pairs:
+ cmp_res = identifier_cmp(id_a, id_b)
+ if cmp_res != 0:
+ return cmp_res
+ # alpha1.3 < alpha1.3.1
+ return base_cmp(len(a), len(b))
+
+
+class Version(object):
+
+ version_re = re.compile(r'^(\d+)\.(\d+)\.(\d+)(?:-([0-9a-zA-Z.-]+))?(?:\+([0-9a-zA-Z.-]+))?$')
+ partial_version_re = re.compile(r'^(\d+)(?:\.(\d+)(?:\.(\d+))?)?(?:-([0-9a-zA-Z.-]*))?(?:\+([0-9a-zA-Z.-]*))?$')
+
+ def __init__(self, version_string, partial=False):
+ major, minor, patch, prerelease, build = self.parse(version_string, partial)
+
+ self.major = major
+ self.minor = minor
+ self.patch = patch
+ self.prerelease = prerelease
+ self.build = build
+
+ self.partial = partial
+
+ @classmethod
+ def _coerce(cls, value, allow_none=False):
+ if value is None and allow_none:
+ return value
+ return int(value)
+
+ def next_major(self):
+ if self.prerelease and self.minor is 0 and self.patch is 0:
+ return Version('.'.join(str(x) for x in [self.major, self.minor, self.patch]))
+ else:
+ return Version('.'.join(str(x) for x in [self.major + 1, 0, 0]))
+
+ def next_minor(self):
+ if self.prerelease and self.patch is 0:
+ return Version('.'.join(str(x) for x in [self.major, self.minor, self.patch]))
+ else:
+ return Version(
+ '.'.join(str(x) for x in [self.major, self.minor + 1, 0]))
+
+ def next_patch(self):
+ if self.prerelease:
+ return Version('.'.join(str(x) for x in [self.major, self.minor, self.patch]))
+ else:
+ return Version(
+ '.'.join(str(x) for x in [self.major, self.minor, self.patch + 1]))
+
+ @classmethod
+ def coerce(cls, version_string, partial=False):
+ """Coerce an arbitrary version string into a semver-compatible one.
+
+ The rule is:
+ - If not enough components, fill minor/patch with zeroes; unless
+ partial=True
+ - If more than 3 dot-separated components, extra components are "build"
+ data. If some "build" data already appeared, append it to the
+ extra components
+
+ Examples:
+ >>> Version.coerce('0.1')
+ Version(0, 1, 0)
+ >>> Version.coerce('0.1.2.3')
+ Version(0, 1, 2, (), ('3',))
+ >>> Version.coerce('0.1.2.3+4')
+ Version(0, 1, 2, (), ('3', '4'))
+ >>> Version.coerce('0.1+2-3+4_5')
+ Version(0, 1, 0, (), ('2-3', '4-5'))
+ """
+ base_re = re.compile(r'^\d+(?:\.\d+(?:\.\d+)?)?')
+
+ match = base_re.match(version_string)
+ if not match:
+ raise ValueError("Version string lacks a numerical component: %r"
+ % version_string)
+
+ version = version_string[:match.end()]
+ if not partial:
+ # We need a not-partial version.
+ while version.count('.') < 2:
+ version += '.0'
+
+ if match.end() == len(version_string):
+ return Version(version, partial=partial)
+
+ rest = version_string[match.end():]
+
+ # Cleanup the 'rest'
+ rest = re.sub(r'[^a-zA-Z0-9+.-]', '-', rest)
+
+ if rest[0] == '+':
+ # A 'build' component
+ prerelease = ''
+ build = rest[1:]
+ elif rest[0] == '.':
+ # An extra version component, probably 'build'
+ prerelease = ''
+ build = rest[1:]
+ elif rest[0] == '-':
+ rest = rest[1:]
+ if '+' in rest:
+ prerelease, build = rest.split('+', 1)
+ else:
+ prerelease, build = rest, ''
+ elif '+' in rest:
+ prerelease, build = rest.split('+', 1)
+ else:
+ prerelease, build = rest, ''
+
+ build = build.replace('+', '.')
+
+ if prerelease:
+ version = '%s-%s' % (version, prerelease)
+ if build:
+ version = '%s+%s' % (version, build)
+
+ return cls(version, partial=partial)
+
+ @classmethod
+ def parse(cls, version_string, partial=False, coerce=False):
+ """Parse a version string into a Version() object.
+
+ Args:
+ version_string (str), the version string to parse
+ partial (bool), whether to accept incomplete input
+ coerce (bool), whether to try to map the passed in string into a
+ valid Version.
+ """
+ if not version_string:
+ raise ValueError('Invalid empty version string: %r' % version_string)
+
+ if partial:
+ version_re = cls.partial_version_re
+ else:
+ version_re = cls.version_re
+
+ match = version_re.match(version_string)
+ if not match:
+ raise ValueError('Invalid version string: %r' % version_string)
+
+ major, minor, patch, prerelease, build = match.groups()
+
+ if _has_leading_zero(major):
+ raise ValueError("Invalid leading zero in major: %r" % version_string)
+ if _has_leading_zero(minor):
+ raise ValueError("Invalid leading zero in minor: %r" % version_string)
+ if _has_leading_zero(patch):
+ raise ValueError("Invalid leading zero in patch: %r" % version_string)
+
+ major = int(major)
+ minor = cls._coerce(minor, partial)
+ patch = cls._coerce(patch, partial)
+
+ if prerelease is None:
+ if partial and (build is None):
+ # No build info, strip here
+ return (major, minor, patch, None, None)
+ else:
+ prerelease = ()
+ elif prerelease == '':
+ prerelease = ()
+ else:
+ prerelease = tuple(prerelease.split('.'))
+ cls._validate_identifiers(prerelease, allow_leading_zeroes=False)
+
+ if build is None:
+ if partial:
+ build = None
+ else:
+ build = ()
+ elif build == '':
+ build = ()
+ else:
+ build = tuple(build.split('.'))
+ cls._validate_identifiers(build, allow_leading_zeroes=True)
+
+ return (major, minor, patch, prerelease, build)
+
+ @classmethod
+ def _validate_identifiers(cls, identifiers, allow_leading_zeroes=False):
+ for item in identifiers:
+ if not item:
+ raise ValueError("Invalid empty identifier %r in %r"
+ % (item, '.'.join(identifiers)))
+ if item[0] == '0' and item.isdigit() and item != '0' and not allow_leading_zeroes:
+ raise ValueError("Invalid leading zero in identifier %r" % item)
+
+ def __iter__(self):
+ return iter((self.major, self.minor, self.patch, self.prerelease, self.build))
+
+ def __str__(self):
+ version = '%d' % self.major
+ if self.minor is not None:
+ version = '%s.%d' % (version, self.minor)
+ if self.patch is not None:
+ version = '%s.%d' % (version, self.patch)
+
+ if self.prerelease or (self.partial and self.prerelease == () and self.build is None):
+ version = '%s-%s' % (version, '.'.join(self.prerelease))
+ if self.build or (self.partial and self.build == ()):
+ version = '%s+%s' % (version, '.'.join(self.build))
+ return version
+
+ def __repr__(self):
+ return 'Version(%r%s)' % (
+ str(self),
+ ', partial=True' if self.partial else '',
+ )
+
+ @classmethod
+ def _comparison_functions(cls, partial=False):
+ """Retrieve comparison methods to apply on version components.
+
+ This is a private API.
+
+ Args:
+ partial (bool): whether to provide 'partial' or 'strict' matching.
+
+ Returns:
+ 5-tuple of cmp-like functions.
+ """
+
+ def prerelease_cmp(a, b):
+ """Compare prerelease components.
+
+ Special rule: a version without prerelease component has higher
+ precedence than one with a prerelease component.
+ """
+ if a and b:
+ return identifier_list_cmp(a, b)
+ elif a:
+ # Versions with prerelease field have lower precedence
+ return -1
+ elif b:
+ return 1
+ else:
+ return 0
+
+ def build_cmp(a, b):
+ """Compare build metadata.
+
+ Special rule: there is no ordering on build metadata.
+ """
+ if a == b:
+ return 0
+ else:
+ return NotImplemented
+
+ def make_optional(orig_cmp_fun):
+ """Convert a cmp-like function to consider 'None == *'."""
+ @functools.wraps(orig_cmp_fun)
+ def alt_cmp_fun(a, b):
+ if a is None or b is None:
+ return 0
+ return orig_cmp_fun(a, b)
+
+ return alt_cmp_fun
+
+ if partial:
+ return [
+ base_cmp, # Major is still mandatory
+ make_optional(base_cmp),
+ make_optional(base_cmp),
+ make_optional(prerelease_cmp),
+ make_optional(build_cmp),
+ ]
+ else:
+ return [
+ base_cmp,
+ base_cmp,
+ base_cmp,
+ prerelease_cmp,
+ build_cmp,
+ ]
+
+ def __compare(self, other):
+ field_pairs = zip(self, other)
+ comparison_functions = self._comparison_functions(partial=self.partial or other.partial)
+ comparisons = zip(comparison_functions, self, other)
+
+ for cmp_fun, self_field, other_field in comparisons:
+ cmp_res = cmp_fun(self_field, other_field)
+ if cmp_res != 0:
+ return cmp_res
+
+ return 0
+
+ def __hash__(self):
+ return hash((self.major, self.minor, self.patch, self.prerelease, self.build))
+
+ def __cmp__(self, other):
+ if not isinstance(other, self.__class__):
+ return NotImplemented
+ return self.__compare(other)
+
+ def __compare_helper(self, other, condition, notimpl_target):
+ """Helper for comparison.
+
+ Allows the caller to provide:
+ - The condition
+ - The return value if the comparison is meaningless (ie versions with
+ build metadata).
+ """
+ if not isinstance(other, self.__class__):
+ return NotImplemented
+
+ cmp_res = self.__cmp__(other)
+ if cmp_res is NotImplemented:
+ return notimpl_target
+
+ return condition(cmp_res)
+
+ def __eq__(self, other):
+ return self.__compare_helper(other, lambda x: x == 0, notimpl_target=False)
+
+ def __ne__(self, other):
+ return self.__compare_helper(other, lambda x: x != 0, notimpl_target=True)
+
+ def __lt__(self, other):
+ return self.__compare_helper(other, lambda x: x < 0, notimpl_target=False)
+
+ def __le__(self, other):
+ return self.__compare_helper(other, lambda x: x <= 0, notimpl_target=False)
+
+ def __gt__(self, other):
+ return self.__compare_helper(other, lambda x: x > 0, notimpl_target=False)
+
+ def __ge__(self, other):
+ return self.__compare_helper(other, lambda x: x >= 0, notimpl_target=False)
+
+
+class SpecItem(object):
+ """A requirement specification."""
+
+ KIND_ANY = '*'
+ KIND_LT = '<'
+ KIND_LTE = '<='
+ KIND_EQUAL = '=='
+ KIND_SHORTEQ = '='
+ KIND_EMPTY = ''
+ KIND_GTE = '>='
+ KIND_GT = '>'
+ KIND_NEQ = '!='
+ KIND_CARET = '^'
+ KIND_TILDE = '~'
+
+ # Map a kind alias to its full version
+ KIND_ALIASES = {
+ KIND_SHORTEQ: KIND_EQUAL,
+ KIND_EMPTY: KIND_EQUAL,
+ }
+
+ re_spec = re.compile(r'^(<|<=||=|==|>=|>|!=|\^|~)(\d.*)$')
+
+ def __init__(self, requirement_string):
+ kind, spec = self.parse(requirement_string)
+ self.kind = kind
+ self.spec = spec
+
+ @classmethod
+ def parse(cls, requirement_string):
+ if not requirement_string:
+ raise ValueError("Invalid empty requirement specification: %r" % requirement_string)
+
+ # Special case: the 'any' version spec.
+ if requirement_string == '*':
+ return (cls.KIND_ANY, '')
+
+ match = cls.re_spec.match(requirement_string)
+ if not match:
+ raise ValueError("Invalid requirement specification: %r" % requirement_string)
+
+ kind, version = match.groups()
+ if kind in cls.KIND_ALIASES:
+ kind = cls.KIND_ALIASES[kind]
+
+ spec = Version(version, partial=True)
+ if spec.build is not None and kind not in (cls.KIND_EQUAL, cls.KIND_NEQ):
+ raise ValueError(
+ "Invalid requirement specification %r: build numbers have no ordering."
+ % requirement_string)
+ return (kind, spec)
+
+ def match(self, version):
+ if self.kind == self.KIND_ANY:
+ return True
+ elif self.kind == self.KIND_LT:
+ return version < self.spec
+ elif self.kind == self.KIND_LTE:
+ return version <= self.spec
+ elif self.kind == self.KIND_EQUAL:
+ return version == self.spec
+ elif self.kind == self.KIND_GTE:
+ return version >= self.spec
+ elif self.kind == self.KIND_GT:
+ return version > self.spec
+ elif self.kind == self.KIND_NEQ:
+ return version != self.spec
+ elif self.kind == self.KIND_CARET:
+ return self.spec <= version < self.spec.next_major()
+ return self.caret_compare(version)
+ elif self.kind == self.KIND_TILDE:
+ return self.spec <= version < self.spec.next_minor()
+ else: # pragma: no cover
+ raise ValueError('Unexpected match kind: %r' % self.kind)
+
+ def __str__(self):
+ return '%s%s' % (self.kind, self.spec)
+
+ def __repr__(self):
+ return '<SpecItem: %s %r>' % (self.kind, self.spec)
+
+ def __eq__(self, other):
+ if not isinstance(other, SpecItem):
+ return NotImplemented
+ return self.kind == other.kind and self.spec == other.spec
+
+ def __hash__(self):
+ return hash((self.kind, self.spec))
+
+
+class Spec(object):
+ def __init__(self, *specs_strings):
+ subspecs = [self.parse(spec) for spec in specs_strings]
+ self.specs = sum(subspecs, ())
+
+ @classmethod
+ def parse(self, specs_string):
+ spec_texts = specs_string.split(',')
+ return tuple(SpecItem(spec_text) for spec_text in spec_texts)
+
+ def match(self, version):
+ """Check whether a Version satisfies the Spec."""
+ return all(spec.match(version) for spec in self.specs)
+
+ def filter(self, versions):
+ """Filter an iterable of versions satisfying the Spec."""
+ for version in versions:
+ if self.match(version):
+ yield version
+
+ def select(self, versions):
+ """Select the best compatible version among an iterable of options."""
+ options = list(self.filter(versions))
+ if options:
+ return max(options)
+ return None
+
+ def __contains__(self, version):
+ if isinstance(version, Version):
+ return self.match(version)
+ return False
+
+ def __iter__(self):
+ return iter(self.specs)
+
+ def __str__(self):
+ return ','.join(str(spec) for spec in self.specs)
+
+ def __repr__(self):
+ return '<Spec: %r>' % (self.specs,)
+
+ def __eq__(self, other):
+ if not isinstance(other, Spec):
+ return NotImplemented
+
+ return set(self.specs) == set(other.specs)
+
+ def __hash__(self):
+ return hash(self.specs)
+
+
+def compare(v1, v2):
+ return base_cmp(Version(v1), Version(v2))
+
+
+def match(spec, version):
+ return Spec(spec).match(Version(version))
+
+
+def validate(version_string):
+ """Validates a version string againt the SemVer specification."""
+ try:
+ Version.parse(version_string)
+ return True
+ except ValueError:
+ return False
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/semantic_version/compat.py
@@ -0,0 +1,15 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+
+def base_cmp(x, y):
+ if x == y:
+ return 0
+ elif x > y:
+ return 1
+ elif x < y:
+ return -1
+ else:
+ # Fix Py2's behavior: cmp(x, y) returns -1 for unorderable types
+ return NotImplemented
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/semantic_version/django_fields.py
@@ -0,0 +1,100 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+from __future__ import unicode_literals
+
+from django.db import models
+from django.utils.translation import ugettext_lazy as _
+
+from . import base
+
+
+class BaseSemVerField(models.CharField):
+ __metaclass__ = models.SubfieldBase
+
+ def __init__(self, *args, **kwargs):
+ kwargs.setdefault('max_length', 200)
+ super(BaseSemVerField, self).__init__(*args, **kwargs)
+
+ def get_prep_value(self, obj):
+ return None if obj is None else str(obj)
+
+ def get_db_prep_value(self, value, connection, prepared=False):
+ if not prepared:
+ value = self.get_prep_value(value)
+ return value
+
+ def value_to_string(self, obj):
+ value = self.to_python(self._get_val_from_obj(obj))
+ return str(value)
+
+ def run_validators(self, value):
+ return super(BaseSemVerField, self).run_validators(str(value))
+
+
+# Py2 and Py3-compatible metaclass
+SemVerField = models.SubfieldBase(
+ str('SemVerField'), (BaseSemVerField, models.CharField), {})
+
+
+class VersionField(SemVerField):
+ default_error_messages = {
+ 'invalid': _("Enter a valid version number in X.Y.Z format."),
+ }
+ description = _("Version")
+
+ def __init__(self, *args, **kwargs):
+ self.partial = kwargs.pop('partial', False)
+ self.coerce = kwargs.pop('coerce', False)
+ super(VersionField, self).__init__(*args, **kwargs)
+
+ def to_python(self, value):
+ """Converts any value to a base.Version field."""
+ if value is None or value == '':
+ return value
+ if isinstance(value, base.Version):
+ return value
+ if self.coerce:
+ return base.Version.coerce(value, partial=self.partial)
+ else:
+ return base.Version(value, partial=self.partial)
+
+
+class SpecField(SemVerField):
+ default_error_messages = {
+ 'invalid': _("Enter a valid version number spec list in ==X.Y.Z,>=A.B.C format."),
+ }
+ description = _("Version specification list")
+
+ def to_python(self, value):
+ """Converts any value to a base.Spec field."""
+ if value is None or value == '':
+ return value
+ if isinstance(value, base.Spec):
+ return value
+ return base.Spec(value)
+
+
+def add_south_rules():
+ from south.modelsinspector import add_introspection_rules
+
+ add_introspection_rules([
+ (
+ (VersionField,),
+ [],
+ {
+ 'partial': ('partial', {'default': False}),
+ 'coerce': ('coerce', {'default': False}),
+ },
+ ),
+ ], ["semantic_version\.django_fields"])
+
+
+try: # pragma: no cover
+ import south
+except ImportError: # pragma: no cover
+ south = None
+
+if south: # pragma: no cover
+ add_south_rules()
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/setup.py
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+
+
+import codecs
+import os
+import re
+import sys
+
+from setuptools import setup
+
+root_dir = os.path.abspath(os.path.dirname(__file__))
+
+
+def get_version(package_name):
+ version_re = re.compile(r"^__version__ = [\"']([\w_.-]+)[\"']$")
+ package_components = package_name.split('.')
+ init_path = os.path.join(root_dir, *(package_components + ['__init__.py']))
+ with codecs.open(init_path, 'r', 'utf-8') as f:
+ for line in f:
+ match = version_re.match(line[:-1])
+ if match:
+ return match.groups()[0]
+ return '0.1.0'
+
+
+def clean_readme(fname):
+ """Cleanup README.rst for proper PyPI formatting."""
+ with codecs.open(fname, 'r', 'utf-8') as f:
+ return ''.join(
+ re.sub(r':\w+:`([^`]+?)( <[^<>]+>)?`', r'``\1``', line)
+ for line in f
+ if not (line.startswith('.. currentmodule') or line.startswith('.. toctree'))
+ )
+
+
+PACKAGE = 'semantic_version'
+
+
+setup(
+ name=PACKAGE,
+ version=get_version(PACKAGE),
+ author="Raphaël Barrois",
+ author_email="raphael.barrois+semver@polytechnique.org",
+ description="A library implementing the 'SemVer' scheme.",
+ long_description=clean_readme('README.rst'),
+ license='BSD',
+ keywords=['semantic version', 'versioning', 'version'],
+ url='https://github.com/rbarrois/python-semanticversion',
+ download_url='http://pypi.python.org/pypi/semantic_version/',
+ packages=['semantic_version'],
+ setup_requires=[
+ 'setuptools>=0.8',
+ ],
+ classifiers=[
+ 'Development Status :: 5 - Production/Stable',
+ 'Intended Audience :: Developers',
+ 'License :: OSI Approved :: BSD License',
+ 'Topic :: Software Development :: Libraries :: Python Modules',
+ 'Operating System :: OS Independent',
+ 'Programming Language :: Python',
+ 'Programming Language :: Python :: 2',
+ 'Programming Language :: Python :: 2.7',
+ 'Programming Language :: Python :: 3',
+ 'Programming Language :: Python :: 3.4',
+ 'Programming Language :: Python :: 3.5',
+ 'Topic :: Software Development :: Libraries :: Python Modules'
+ ],
+ test_suite='tests',
+)
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/tests/compat.py
@@ -0,0 +1,14 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+import sys
+
+is_python2 = (sys.version_info[0] == 2)
+
+
+try: # pragma: no cover
+ import unittest2 as unittest
+except ImportError: # pragma: no cover
+ import unittest
+
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/tests/django_test_app/__init__.py
@@ -0,0 +1,30 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+try: # pragma: no cover
+ import django
+ from django.conf import settings
+ django_loaded = True
+except ImportError: # pragma: no cover
+ django_loaded = False
+
+
+if django_loaded: # pragma: no cover
+ if not settings.configured:
+ settings.configure(
+ DATABASES={
+ 'default': {
+ 'ENGINE': 'django.db.backends.sqlite3',
+ 'NAME': 'tests/db/test.sqlite',
+ }
+ },
+ INSTALLED_APPS=[
+ 'tests.django_test_app',
+ ],
+ MIDDLEWARE_CLASSES=[],
+ )
+ # https://docs.djangoproject.com/en/dev/releases/1.7/#app-loading-changes
+ if django.VERSION >= (1, 7):
+ from django.apps import apps
+ apps.populate(settings.INSTALLED_APPS)
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/tests/django_test_app/models.py
@@ -0,0 +1,28 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+
+try:
+ from django.db import models
+ django_loaded = True
+except ImportError:
+ django_loaded = False
+
+
+if django_loaded:
+ from semantic_version import django_fields as semver_fields
+
+
+ class VersionModel(models.Model):
+ version = semver_fields.VersionField(verbose_name='my version')
+ spec = semver_fields.SpecField(verbose_name='my spec')
+
+
+ class PartialVersionModel(models.Model):
+ partial = semver_fields.VersionField(partial=True, verbose_name='partial version')
+ optional = semver_fields.VersionField(verbose_name='optional version', blank=True, null=True)
+ optional_spec = semver_fields.SpecField(verbose_name='optional spec', blank=True, null=True)
+
+
+ class CoerceVersionModel(models.Model):
+ version = semver_fields.VersionField(verbose_name='my version', coerce=True)
+ partial = semver_fields.VersionField(verbose_name='partial version', coerce=True, partial=True)
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/tests/test_base.py
@@ -0,0 +1,709 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+"""Test the various functions from 'base'."""
+
+from .compat import unittest, is_python2
+
+from semantic_version import base
+
+class ComparisonTestCase(unittest.TestCase):
+ def test_identifier_cmp(self):
+ cases = [
+ # Integers
+ ('1', '1', 0),
+ ('1', '2', -1),
+ ('11', '2', 1),
+ ('3333', '40', 1),
+
+ # Text
+ ('aa', 'ab', -1),
+ ('aa', 'aa', 0),
+ ('ab', 'aa', 1),
+ ('aaa', 'ab', -1),
+
+ # Mixed
+ ('10', '1a', -1),
+ ('1a', '10', 1),
+ ('ab1', '42', 1),
+ ]
+
+ for a, b, expected in cases:
+ result = base.identifier_cmp(a, b)
+ self.assertEqual(expected, result,
+ "identifier_cmp(%r, %r) returned %d instead of %d" % (
+ a, b, result, expected))
+
+ def test_identifier_list_cmp(self):
+ cases = [
+ # Same length
+ (['1', '2', '3'], ['1', '2', '3'], 0),
+ (['1', '2', '3'], ['1', '3', '2'], -1),
+ (['1', '2', '4'], ['1', '2', '3'], 1),
+
+ # Mixed lengths
+ (['1', 'a'], ['1', 'a', '0'], -1),
+ (['1', 'a', '0'], ['1', 'a'], 1),
+ (['1', 'b'], ['1', 'a', '1000'], 1),
+ ]
+
+ for a, b, expected in cases:
+ result = base.identifier_list_cmp(a, b)
+ self.assertEqual(expected, result,
+ "identifier_list_cmp(%r, %r) returned %d instead of %d" % (
+ a, b, result, expected))
+
+
+class TopLevelTestCase(unittest.TestCase):
+ """Test module-level functions."""
+
+ versions = (
+ ('0.1.0', '0.1.1', -1),
+ ('0.1.1', '0.1.1', 0),
+ ('0.1.1', '0.1.0', 1),
+ ('0.1.0-alpha', '0.1.0', -1),
+ ('0.1.0-alpha+2', '0.1.0-alpha', NotImplemented),
+ )
+
+ def test_compare(self):
+ for a, b, expected in self.versions:
+ result = base.compare(a, b)
+ self.assertEqual(expected, result,
+ "compare(%r, %r) should be %r instead of %r" % (a, b, expected, result))
+
+ matches = (
+ ('>=0.1.1', '0.1.2'),
+ ('>=0.1.1', '0.1.1'),
+ ('>=0.1.1', '0.1.1-alpha'),
+ ('>=0.1.1,!=0.2.0', '0.2.1'),
+ )
+
+ def test_match(self):
+ for spec, version in self.matches:
+ self.assertTrue(base.match(spec, version),
+ "%r should accept %r" % (spec, version))
+
+ valid_strings = (
+ '1.0.0-alpha',
+ '1.0.0-alpha.1',
+ '1.0.0-beta.2',
+ '1.0.0-beta.11',
+ '1.0.0-rc.1',
+ '1.0.0-rc.1+build.1',
+ '1.0.0',
+ '1.0.0+0.3.7',
+ '1.3.7+build',
+ '1.3.7+build.2.b8f12d7',
+ '1.3.7+build.11.e0f985a',
+ '1.1.1',
+ '1.1.2',
+ '1.1.3-rc4.5',
+ '1.1.3-rc42.3-14-15.24+build.2012-04-13.223',
+ '1.1.3+build.2012-04-13.HUY.alpha-12.1',
+ )
+
+ def test_validate_valid(self):
+ for version in self.valid_strings:
+ self.assertTrue(base.validate(version),
+ "%r should be a valid version" % (version,))
+
+ invalid_strings = (
+ '1',
+ 'v1',
+ '1.2.3.4',
+ '1.2',
+ '1.2a3',
+ '1.2.3a4',
+ 'v12.34.5',
+ '1.2.3+4+5',
+ )
+
+ def test_validate_invalid(self):
+ for version in self.invalid_strings:
+ self.assertFalse(base.validate(version),
+ "%r should not be a valid version" % (version,))
+
+
+class VersionTestCase(unittest.TestCase):
+ versions = {
+ '1.0.0-alpha': (1, 0, 0, ('alpha',), ()),
+ '1.0.0-alpha.1': (1, 0, 0, ('alpha', '1'), ()),
+ '1.0.0-beta.2': (1, 0, 0, ('beta', '2'), ()),
+ '1.0.0-beta.11': (1, 0, 0, ('beta', '11'), ()),
+ '1.0.0-rc.1': (1, 0, 0, ('rc', '1'), ()),
+ '1.0.0-rc.1+build.1': (1, 0, 0, ('rc', '1'), ('build', '1')),
+ '1.0.0': (1, 0, 0, (), ()),
+ '1.0.0+0.3.7': (1, 0, 0, (), ('0', '3', '7')),
+ '1.3.7+build': (1, 3, 7, (), ('build',)),
+ '1.3.7+build.2.b8f12d7': (1, 3, 7, (), ('build', '2', 'b8f12d7')),
+ '1.3.7+build.11.e0f985a': (1, 3, 7, (), ('build', '11', 'e0f985a')),
+ '1.1.1': (1, 1, 1, (), ()),
+ '1.1.2': (1, 1, 2, (), ()),
+ '1.1.3-rc4.5': (1, 1, 3, ('rc4', '5'), ()),
+ '1.1.3-rc42.3-14-15.24+build.2012-04-13.223':
+ (1, 1, 3, ('rc42', '3-14-15', '24'), ('build', '2012-04-13', '223')),
+ '1.1.3+build.2012-04-13.HUY.alpha-12.1':
+ (1, 1, 3, (), ('build', '2012-04-13', 'HUY', 'alpha-12', '1')),
+ }
+
+ def test_parsing(self):
+ for text, expected_fields in self.versions.items():
+ version = base.Version(text)
+ actual_fields = (version.major, version.minor, version.patch,
+ version.prerelease, version.build)
+ self.assertEqual(expected_fields, actual_fields)
+
+ def test_str(self):
+ for text in self.versions:
+ version = base.Version(text)
+ self.assertEqual(text, str(version))
+ self.assertEqual("Version('%s')" % text, repr(version))
+
+ def test_compare_to_self(self):
+ for text in self.versions:
+ self.assertEqual(base.Version(text), base.Version(text))
+ self.assertNotEqual(text, base.Version(text))
+
+ partial_versions = {
+ '1.1': (1, 1, None, None, None),
+ '2': (2, None, None, None, None),
+ '1.0.0-alpha': (1, 0, 0, ('alpha',), None),
+ '1.0.0-alpha.1': (1, 0, 0, ('alpha', '1'), None),
+ '1.0.0-beta.2': (1, 0, 0, ('beta', '2'), None),
+ '1.0.0-beta.11': (1, 0, 0, ('beta', '11'), None),
+ '1.0.0-rc.1': (1, 0, 0, ('rc', '1'), None),
+ '1.0.0': (1, 0, 0, None, None),
+ '1.1.1': (1, 1, 1, None, None),
+ '1.1.2': (1, 1, 2, None, None),
+ '1.1.3-rc4.5': (1, 1, 3, ('rc4', '5'), None),
+ '1.0.0-': (1, 0, 0, (), None),
+ '1.0.0-rc.1+build.1': (1, 0, 0, ('rc', '1'), ('build', '1')),
+ '1.0.0+0.3.7': (1, 0, 0, (), ('0', '3', '7')),
+ '1.3.7+build': (1, 3, 7, (), ('build',)),
+ '1.3.7+build.2.b8f12d7': (1, 3, 7, (), ('build', '2', 'b8f12d7')),
+ '1.3.7+build.11.e0f985a': (1, 3, 7, (), ('build', '11', 'e0f985a')),
+ '1.1.3-rc42.3-14-15.24+build.2012-04-13.223':
+ (1, 1, 3, ('rc42', '3-14-15', '24'), ('build', '2012-04-13', '223')),
+ '1.1.3+build.2012-04-13.HUY.alpha-12.1':
+ (1, 1, 3, (), ('build', '2012-04-13', 'HUY', 'alpha-12', '1')),
+ }
+
+ def test_parsing_partials(self):
+ for text, expected_fields in self.partial_versions.items():
+ version = base.Version(text, partial=True)
+ actual_fields = (version.major, version.minor, version.patch,
+ version.prerelease, version.build)
+ self.assertEqual(expected_fields, actual_fields)
+ self.assertTrue(version.partial, "%r should have partial=True" % version)
+
+ def test_str_partials(self):
+ for text in self.partial_versions:
+ version = base.Version(text, partial=True)
+ self.assertEqual(text, str(version))
+ self.assertEqual("Version('%s', partial=True)" % text, repr(version))
+
+ def test_compare_partial_to_self(self):
+ for text in self.partial_versions:
+ self.assertEqual(
+ base.Version(text, partial=True),
+ base.Version(text, partial=True))
+ self.assertNotEqual(text, base.Version(text, partial=True))
+
+ def test_hash(self):
+ self.assertEqual(1,
+ len(set([base.Version('0.1.0'), base.Version('0.1.0')])))
+
+ self.assertEqual(2,
+ len(set([base.Version('0.1.0'), base.Version('0.1.0', partial=True)])))
+
+ # A fully-defined 'partial' version isn't actually partial.
+ self.assertEqual(1,
+ len(set([
+ base.Version('0.1.0-a1+34'),
+ base.Version('0.1.0-a1+34', partial=True)
+ ]))
+ )
+
+ @unittest.skipIf(is_python2, "Comparisons to other objects are broken in Py2.")
+ def test_invalid_comparisons(self):
+ v = base.Version('0.1.0')
+ with self.assertRaises(TypeError):
+ v < '0.1.0'
+ with self.assertRaises(TypeError):
+ v <= '0.1.0'
+ with self.assertRaises(TypeError):
+ v > '0.1.0'
+ with self.assertRaises(TypeError):
+ v >= '0.1.0'
+
+ self.assertTrue(v != '0.1.0')
+ self.assertFalse(v == '0.1.0')
+
+ def test_bump_clean_versions(self):
+ # We Test each property explicitly as the == comparator for versions
+ # does not distinguish between prerelease or builds for equality.
+
+ v = base.Version('1.0.0+build')
+ v = v.next_major()
+ self.assertEqual(v.major, 2)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.0+build')
+ v = v.next_minor()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 1)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.0+build')
+ v = v.next_patch()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 1)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.1.0+build')
+ v = v.next_major()
+ self.assertEqual(v.major, 2)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.1.0+build')
+ v = v.next_minor()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 2)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.1.0+build')
+ v = v.next_patch()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 1)
+ self.assertEqual(v.patch, 1)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.1+build')
+ v = v.next_major()
+ self.assertEqual(v.major, 2)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.1+build')
+ v = v.next_minor()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 1)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.1+build')
+ v = v.next_patch()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 2)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ def test_bump_prerelease_versions(self):
+ # We Test each property explicitly as the == comparator for versions
+ # does not distinguish between prerelease or builds for equality.
+
+ v = base.Version('1.0.0-pre+build')
+ v = v.next_major()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.0-pre+build')
+ v = v.next_minor()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.0-pre+build')
+ v = v.next_patch()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.1.0-pre+build')
+ v = v.next_major()
+ self.assertEqual(v.major, 2)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.1.0-pre+build')
+ v = v.next_minor()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 1)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.1.0-pre+build')
+ v = v.next_patch()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 1)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.1-pre+build')
+ v = v.next_major()
+ self.assertEqual(v.major, 2)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.1-pre+build')
+ v = v.next_minor()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 1)
+ self.assertEqual(v.patch, 0)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+ v = base.Version('1.0.1-pre+build')
+ v = v.next_patch()
+ self.assertEqual(v.major, 1)
+ self.assertEqual(v.minor, 0)
+ self.assertEqual(v.patch, 1)
+ self.assertEqual(v.prerelease, ())
+ self.assertEqual(v.build, ())
+
+
+class SpecItemTestCase(unittest.TestCase):
+ invalids = [
+ '<=0.1.1+build3',
+ '<=0.1.1+',
+ '>0.2.3-rc2+',
+ ]
+
+ def test_invalids(self):
+ for invalid in self.invalids:
+ with self.assertRaises(ValueError, msg="SpecItem(%r) should be invalid" % invalid):
+ _v = base.SpecItem(invalid)
+
+ components = {
+ '==0.1.0': (base.SpecItem.KIND_EQUAL, 0, 1, 0, None, None),
+ '==0.1.2-rc3': (base.SpecItem.KIND_EQUAL, 0, 1, 2, ('rc3',), None),
+ '==0.1.2+build3.14': (base.SpecItem.KIND_EQUAL, 0, 1, 2, (), ('build3', '14')),
+ '<=0.1.1': (base.SpecItem.KIND_LTE, 0, 1, 1, None, None),
+ '<0.1.1': (base.SpecItem.KIND_LT, 0, 1, 1, None, None),
+ '<=0.1.1': (base.SpecItem.KIND_LTE, 0, 1, 1, None, None),
+ '!=0.1.1+': (base.SpecItem.KIND_NEQ, 0, 1, 1, (), ()),
+ '<=0.1.1-': (base.SpecItem.KIND_LTE, 0, 1, 1, (), None),
+ '>=0.2.3-rc2': (base.SpecItem.KIND_GTE, 0, 2, 3, ('rc2',), None),
+ '>=2.0.0': (base.SpecItem.KIND_GTE, 2, 0, 0, None, None),
+ '!=0.1.1+rc3': (base.SpecItem.KIND_NEQ, 0, 1, 1, (), ('rc3',)),
+ '!=0.3.0': (base.SpecItem.KIND_NEQ, 0, 3, 0, None, None),
+ '=0.3.0': (base.SpecItem.KIND_EQUAL, 0, 3, 0, None, None),
+ '0.3.0': (base.SpecItem.KIND_EQUAL, 0, 3, 0, None, None),
+ '~0.1.2': (base.SpecItem.KIND_TILDE, 0, 1, 2, None, None),
+ '^0.1.3': (base.SpecItem.KIND_CARET, 0, 1, 3, None, None),
+ }
+
+ def test_components(self):
+ for spec_text, components in self.components.items():
+ kind, major, minor, patch, prerelease, build = components
+ spec = base.SpecItem(spec_text)
+
+ self.assertEqual(kind, spec.kind)
+ self.assertEqual(major, spec.spec.major)
+ self.assertEqual(minor, spec.spec.minor)
+ self.assertEqual(patch, spec.spec.patch)
+ self.assertEqual(prerelease, spec.spec.prerelease)
+ self.assertEqual(build, spec.spec.build)
+
+ matches = {
+ '==0.1.0': (
+ ['0.1.0', '0.1.0-rc1', '0.1.0+build1', '0.1.0-rc1+build2'],
+ ['0.0.1', '0.2.0', '0.1.1'],
+ ),
+ '=0.1.0': (
+ ['0.1.0', '0.1.0-rc1', '0.1.0+build1', '0.1.0-rc1+build2'],
+ ['0.0.1', '0.2.0', '0.1.1'],
+ ),
+ '0.1.0': (
+ ['0.1.0', '0.1.0-rc1', '0.1.0+build1', '0.1.0-rc1+build2'],
+ ['0.0.1', '0.2.0', '0.1.1'],
+ ),
+ '==0.1.2-rc3': (
+ ['0.1.2-rc3+build1', '0.1.2-rc3+build4.5'],
+ ['0.1.2-rc4', '0.1.2', '0.1.3'],
+ ),
+ '==0.1.2+build3.14': (
+ ['0.1.2+build3.14'],
+ ['0.1.2-rc+build3.14', '0.1.2+build3.15'],
+ ),
+ '<=0.1.1': (
+ ['0.0.0', '0.1.1-alpha1', '0.1.1', '0.1.1+build2'],
+ ['0.1.2'],
+ ),
+ '<0.1.1': (
+ ['0.1.0', '0.0.0'],
+ ['0.1.1', '0.1.1-zzz+999', '1.2.0', '0.1.1+build3'],
+ ),
+ '<=0.1.1': (
+ ['0.1.1+build4', '0.1.1-alpha', '0.1.0'],
+ ['0.2.3', '1.1.1', '0.1.2'],
+ ),
+ '<0.1.1-': (
+ ['0.1.0', '0.1.1-alpha', '0.1.1-alpha+4'],
+ ['0.2.0', '1.0.0', '0.1.1', '0.1.1+build1'],
+ ),
+ '>=0.2.3-rc2': (
+ ['0.2.3-rc3', '0.2.3', '0.2.3+1', '0.2.3-rc2', '0.2.3-rc2+1'],
+ ['0.2.3-rc1', '0.2.2'],
+ ),
+ '==0.2.3+': (
+ ['0.2.3'],
+ ['0.2.3+rc1', '0.2.4', '0.2.3-rc2'],
+ ),
+ '!=0.2.3-rc2+12': (
+ ['0.2.3-rc3', '0.2.3', '0.2.3-rc2+1', '0.2.4', '0.2.3-rc3+12'],
+ ['0.2.3-rc2+12'],
+ ),
+ '==2.0.0+b1': (
+ ['2.0.0+b1'],
+ ['2.1.1', '1.9.9', '1.9.9999', '2.0.0', '2.0.0-rc4'],
+ ),
+ '!=0.1.1': (
+ ['0.1.2', '0.1.0', '1.4.2'],
+ ['0.1.1', '0.1.1-alpha', '0.1.1+b1'],
+ ),
+ '!=0.3.4-': (
+ ['0.4.0', '1.3.0', '0.3.4-alpha', '0.3.4-alpha+b1'],
+ ['0.3.4', '0.3.4+b1'],
+ ),
+ '~1.1.2': (
+ ['1.1.3', '1.1.2-alpha', '1.1.2-alpha+b1'],
+ ['1.1.1', '1.2.1', '2.1.0'],
+ ),
+ '^1.1.2': (
+ ['1.1.3', '1.2.1', '1.1.2-alpha', '1.1.2-alpha+b1'],
+ ['1.1.1', '2.1.0'],
+ ),
+ }
+
+ def test_matches(self):
+ for spec_text, versions in self.matches.items():
+ spec = base.SpecItem(spec_text)
+ matching, failing = versions
+
+ for version_text in matching:
+ version = base.Version(version_text)
+ self.assertTrue(spec.match(version), "%r should match %r" % (version, spec))
+
+ for version_text in failing:
+ version = base.Version(version_text)
+ self.assertFalse(spec.match(version),
+ "%r should not match %r" % (version, spec))
+
+ def test_equality(self):
+ spec1 = base.SpecItem('==0.1.0')
+ spec2 = base.SpecItem('==0.1.0')
+ self.assertEqual(spec1, spec2)
+ self.assertFalse(spec1 == '==0.1.0')
+
+ def test_to_string(self):
+ spec = base.SpecItem('==0.1.0')
+ self.assertEqual('==0.1.0', str(spec))
+ self.assertEqual(base.SpecItem.KIND_EQUAL, spec.kind)
+
+ def test_hash(self):
+ self.assertEqual(1,
+ len(set([base.SpecItem('==0.1.0'), base.SpecItem('==0.1.0')])))
+
+
+class CoerceTestCase(unittest.TestCase):
+ examples = {
+ # Dict of target: [list of equivalents]
+ '0.0.0': ('0', '0.0', '0.0.0', '0.0.0+', '0-'),
+ '0.1.0': ('0.1', '0.1+', '0.1-', '0.1.0'),
+ '0.1.0+2': ('0.1.0+2', '0.1.0.2'),
+ '0.1.0+2.3.4': ('0.1.0+2.3.4', '0.1.0+2+3+4', '0.1.0.2+3+4'),
+ '0.1.0+2-3.4': ('0.1.0+2-3.4', '0.1.0+2-3+4', '0.1.0.2-3+4', '0.1.0.2_3+4'),
+ '0.1.0-a2.3': ('0.1.0-a2.3', '0.1.0a2.3', '0.1.0_a2.3'),
+ '0.1.0-a2.3+4.5-6': ('0.1.0-a2.3+4.5-6', '0.1.0a2.3+4.5-6', '0.1.0a2.3+4.5_6', '0.1.0a2.3+4+5/6'),
+ }
+
+ def test_coerce(self):
+ for equivalent, samples in self.examples.items():
+ target = base.Version(equivalent)
+ for sample in samples:
+ v_sample = base.Version.coerce(sample)
+ self.assertEqual(target, v_sample)
+
+ def test_invalid(self):
+ self.assertRaises(ValueError, base.Version.coerce, 'v1')
+
+
+class SpecTestCase(unittest.TestCase):
+ examples = {
+ '>=0.1.1,<0.1.2': ['>=0.1.1', '<0.1.2'],
+ '>=0.1.0,!=0.1.3-rc1,<0.1.3': ['>=0.1.0', '!=0.1.3-rc1', '<0.1.3'],
+ }
+
+ def test_parsing(self):
+ for spec_list_text, specs in self.examples.items():
+ spec_list = base.Spec(spec_list_text)
+
+ self.assertEqual(spec_list_text, str(spec_list))
+ self.assertNotEqual(spec_list_text, spec_list)
+ self.assertEqual(specs, [str(spec) for spec in spec_list])
+
+ for spec_text in specs:
+ self.assertTrue(repr(base.SpecItem(spec_text)) in repr(spec_list))
+
+ split_examples = {
+ ('>=0.1.1', '<0.1.2', '!=0.1.1+build1'): ['>=0.1.1', '<0.1.2', '!=0.1.1+build1'],
+ ('>=0.1.0', '!=0.1.3-rc1,<0.1.3'): ['>=0.1.0', '!=0.1.3-rc1', '<0.1.3'],
+ }
+
+ def test_parsing_split(self):
+ for spec_list_texts, specs in self.split_examples.items():
+ spec_list = base.Spec(*spec_list_texts)
+
+ self.assertEqual(','.join(spec_list_texts), str(spec_list))
+ self.assertEqual(specs, [str(spec) for spec in spec_list])
+ self.assertEqual(spec_list, base.Spec(','.join(spec_list_texts)))
+
+ for spec_text in specs:
+ self.assertTrue(repr(base.SpecItem(spec_text)) in repr(spec_list))
+
+ matches = {
+ # At least 0.1.1 including pre-releases, less than 0.1.2 excluding pre-releases
+ '>=0.1.1,<0.1.2': (
+ ['0.1.1', '0.1.1+4', '0.1.1-alpha'],
+ ['0.1.2-alpha', '0.1.2', '1.3.4'],
+ ),
+ # At least 0.1.0 without pre-releases, less than 0.1.4 excluding pre-releases,
+ # neither 0.1.3-rc1 nor any build of that version,
+ # not 0.1.0+b3 precisely
+ '>=0.1.0-,!=0.1.3-rc1,!=0.1.0+b3,<0.1.4': (
+ ['0.1.1', '0.1.0+b4', '0.1.2', '0.1.3-rc2'],
+ ['0.0.1', '0.1.0+b3', '0.1.4', '0.1.4-alpha', '0.1.3-rc1+4',
+ '0.1.0-alpha', '0.2.2', '0.1.4-rc1'],
+ ),
+ }
+
+ def test_matches(self):
+ for spec_list_text, versions in self.matches.items():
+ spec_list = base.Spec(spec_list_text)
+ matching, failing = versions
+
+ for version_text in matching:
+ version = base.Version(version_text)
+ self.assertTrue(version in spec_list,
+ "%r should be in %r" % (version, spec_list))
+ self.assertTrue(spec_list.match(version),
+ "%r should match %r" % (version, spec_list))
+
+ for version_text in failing:
+ version = base.Version(version_text)
+ self.assertFalse(version in spec_list,
+ "%r should not be in %r" % (version, spec_list))
+ self.assertFalse(spec_list.match(version),
+ "%r should not match %r" % (version, spec_list))
+
+ def test_equality(self):
+ for spec_list_text in self.examples:
+ slist1 = base.Spec(spec_list_text)
+ slist2 = base.Spec(spec_list_text)
+ self.assertEqual(slist1, slist2)
+ self.assertFalse(slist1 == spec_list_text)
+
+ def test_filter_empty(self):
+ s = base.Spec('>=0.1.1')
+ res = tuple(s.filter(()))
+ self.assertEqual((), res)
+
+ def test_filter_incompatible(self):
+ s = base.Spec('>=0.1.1,!=0.1.4')
+ res = tuple(s.filter([
+ base.Version('0.1.0'),
+ base.Version('0.1.4'),
+ base.Version('0.1.4-alpha'),
+ ]))
+ self.assertEqual((), res)
+
+ def test_filter_compatible(self):
+ s = base.Spec('>=0.1.1,!=0.1.4,<0.2.0')
+ res = tuple(s.filter([
+ base.Version('0.1.0'),
+ base.Version('0.1.1'),
+ base.Version('0.1.5'),
+ base.Version('0.1.4-alpha'),
+ base.Version('0.1.2'),
+ base.Version('0.2.0-rc1'),
+ base.Version('3.14.15'),
+ ]))
+
+ expected = (
+ base.Version('0.1.1'),
+ base.Version('0.1.5'),
+ base.Version('0.1.2'),
+ )
+
+ self.assertEqual(expected, res)
+
+ def test_select_empty(self):
+ s = base.Spec('>=0.1.1')
+ self.assertIsNone(s.select(()))
+
+ def test_select_incompatible(self):
+ s = base.Spec('>=0.1.1,!=0.1.4')
+ res = s.select([
+ base.Version('0.1.0'),
+ base.Version('0.1.4'),
+ base.Version('0.1.4-alpha'),
+ ])
+ self.assertIsNone(res)
+
+ def test_select_compatible(self):
+ s = base.Spec('>=0.1.1,!=0.1.4,<0.2.0')
+ res = s.select([
+ base.Version('0.1.0'),
+ base.Version('0.1.1'),
+ base.Version('0.1.5'),
+ base.Version('0.1.4-alpha'),
+ base.Version('0.1.2'),
+ base.Version('0.2.0-rc1'),
+ base.Version('3.14.15'),
+ ])
+
+ self.assertEqual(base.Version('0.1.5'), res)
+
+ def test_contains(self):
+ self.assertFalse('ii' in base.Spec('>=0.1.1'))
+
+ def test_hash(self):
+ self.assertEqual(1,
+ len(set([base.Spec('>=0.1.1'), base.Spec('>=0.1.1')])))
+
+
+if __name__ == '__main__': # pragma: no cover
+ unittest.main()
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/tests/test_django.py
@@ -0,0 +1,250 @@
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+from __future__ import unicode_literals
+
+try: # pragma: no cover
+ import unittest2 as unittest
+except ImportError: # pragma: no cover
+ import unittest
+
+import semantic_version
+
+try: # pragma: no cover
+ import django
+ from django.conf import settings
+ from .django_test_app import models
+ from django.core import serializers
+ django_loaded = True
+except ImportError: # pragma: no cover
+ django_loaded = False
+
+south = None
+# south has reached end of life, and it does not work with django 1.7 and newer
+if django_loaded and django.VERSION < (1, 7): # pragma: no cover
+ try:
+ import south
+ import south.creator.freezer
+ import south.modelsinspector
+ except ImportError:
+ pass
+
+# the refresh_from_db method only came in with 1.8, so in order to make this
+# work will all supported versions we have our own function.
+def save_and_refresh(obj):
+ """Saves an object, and refreshes from the database."""
+ obj.save()
+ obj = obj.__class__.objects.get(id=obj.id)
+
+
+@unittest.skipIf(not django_loaded, "Django not installed")
+class DjangoFieldTestCase(unittest.TestCase):
+ def test_version(self):
+ obj = models.VersionModel(version='0.1.1', spec='==0.1.1,!=0.1.1-alpha')
+
+ self.assertEqual(semantic_version.Version('0.1.1'), obj.version)
+ self.assertEqual(semantic_version.Spec('==0.1.1,!=0.1.1-alpha'), obj.spec)
+
+ alt_obj = models.VersionModel(version=obj.version, spec=obj.spec)
+
+ self.assertEqual(semantic_version.Version('0.1.1'), alt_obj.version)
+ self.assertEqual(semantic_version.Spec('==0.1.1,!=0.1.1-alpha'), alt_obj.spec)
+ self.assertEqual(obj.spec, alt_obj.spec)
+ self.assertEqual(obj.version, alt_obj.version)
+
+ obj.full_clean()
+
+ def test_version_save(self):
+ """Test saving object with a VersionField."""
+ # first test with a null value
+ obj = models.PartialVersionModel()
+ self.assertIsNone(obj.id)
+ self.assertIsNone(obj.optional)
+ save_and_refresh(obj)
+ self.assertIsNotNone(obj.id)
+ self.assertIsNone(obj.optional_spec)
+
+ # now set to something that is not null
+ spec = semantic_version.Spec('==0,!=0.2')
+ obj.optional_spec = spec
+ save_and_refresh(obj)
+ self.assertEqual(obj.optional_spec, spec)
+
+ def test_spec_save(self):
+ """Test saving object with a SpecField."""
+ # first test with a null value
+ obj = models.PartialVersionModel()
+ self.assertIsNone(obj.id)
+ self.assertIsNone(obj.optional_spec)
+ save_and_refresh(obj)
+ self.assertIsNotNone(obj.id)
+ self.assertIsNone(obj.optional_spec)
+
+ # now set to something that is not null
+ spec = semantic_version.Spec('==0,!=0.2')
+ obj.optional_spec = spec
+ save_and_refresh(obj)
+ self.assertEqual(obj.optional_spec, spec)
+
+ def test_partial_spec(self):
+ obj = models.VersionModel(version='0.1.1', spec='==0,!=0.2')
+ self.assertEqual(semantic_version.Version('0.1.1'), obj.version)
+ self.assertEqual(semantic_version.Spec('==0,!=0.2'), obj.spec)
+
+ def test_coerce(self):
+ obj = models.CoerceVersionModel(version='0.1.1a+2', partial='23')
+ self.assertEqual(semantic_version.Version('0.1.1-a+2'), obj.version)
+ self.assertEqual(semantic_version.Version('23', partial=True), obj.partial)
+
+ obj2 = models.CoerceVersionModel(version='23', partial='0.1.2.3.4.5/6')
+ self.assertEqual(semantic_version.Version('23.0.0'), obj2.version)
+ self.assertEqual(semantic_version.Version('0.1.2+3.4.5-6', partial=True), obj2.partial)
+
+ def test_invalid_input(self):
+ self.assertRaises(ValueError, models.VersionModel,
+ version='0.1.1', spec='blah')
+ self.assertRaises(ValueError, models.VersionModel,
+ version='0.1', spec='==0.1.1,!=0.1.1-alpha')
+
+ def test_partial(self):
+ obj = models.PartialVersionModel(partial='0.1.0')
+
+ self.assertEqual(semantic_version.Version('0.1.0', partial=True), obj.partial)
+ self.assertIsNone(obj.optional)
+ self.assertIsNone(obj.optional_spec)
+
+ # Copy values to another model
+ alt_obj = models.PartialVersionModel(
+ partial=obj.partial,
+ optional=obj.optional,
+ optional_spec=obj.optional_spec,
+ )
+
+ self.assertEqual(semantic_version.Version('0.1.0', partial=True), alt_obj.partial)
+ self.assertEqual(obj.partial, alt_obj.partial)
+ self.assertIsNone(obj.optional)
+ self.assertIsNone(obj.optional_spec)
+
+ obj.full_clean()
+
+ def test_serialization(self):
+ o1 = models.VersionModel(version='0.1.1', spec='==0.1.1,!=0.1.1-alpha')
+ o2 = models.VersionModel(version='0.4.3-rc3+build3',
+ spec='<=0.1.1-rc2,!=0.1.1-rc1')
+
+ data = serializers.serialize('json', [o1, o2])
+
+ obj1, obj2 = serializers.deserialize('json', data)
+ self.assertEqual(o1.version, obj1.object.version)
+ self.assertEqual(o1.spec, obj1.object.spec)
+ self.assertEqual(o2.version, obj2.object.version)
+ self.assertEqual(o2.spec, obj2.object.spec)
+
+ def test_serialization_partial(self):
+ o1 = models.PartialVersionModel(partial='0.1.1', optional='0.2.4-rc42',
+ optional_spec=None)
+ o2 = models.PartialVersionModel(partial='0.4.3-rc3+build3', optional='',
+ optional_spec='==0.1.1,!=0.1.1-alpha')
+
+ data = serializers.serialize('json', [o1, o2])
+
+ obj1, obj2 = serializers.deserialize('json', data)
+ self.assertEqual(o1.partial, obj1.object.partial)
+ self.assertEqual(o1.optional, obj1.object.optional)
+ self.assertEqual(o2.partial, obj2.object.partial)
+ self.assertEqual(o2.optional, obj2.object.optional)
+
+
+@unittest.skipIf(not django_loaded or south is None, "Couldn't import south and django")
+class SouthTestCase(unittest.TestCase):
+ def test_freezing_version_model(self):
+ frozen = south.modelsinspector.get_model_fields(models.VersionModel)
+
+ self.assertEqual(frozen['version'],
+ ('semantic_version.django_fields.VersionField', [], {'max_length': '200'}))
+
+ self.assertEqual(frozen['spec'],
+ ('semantic_version.django_fields.SpecField', [], {'max_length': '200'}))
+
+ def test_freezing_partial_version_model(self):
+ frozen = south.modelsinspector.get_model_fields(models.PartialVersionModel)
+
+ self.assertEqual(frozen['partial'],
+ ('semantic_version.django_fields.VersionField', [], {'max_length': '200', 'partial': 'True'}))
+
+ self.assertEqual(frozen['optional'],
+ ('semantic_version.django_fields.VersionField', [], {'max_length': '200', 'blank': 'True', 'null': 'True'}))
+
+ self.assertEqual(frozen['optional_spec'],
+ ('semantic_version.django_fields.SpecField', [], {'max_length': '200', 'blank': 'True', 'null': 'True'}))
+
+ def test_freezing_coerce_version_model(self):
+ frozen = south.modelsinspector.get_model_fields(models.CoerceVersionModel)
+
+ self.assertEqual(frozen['version'],
+ ('semantic_version.django_fields.VersionField', [], {'max_length': '200', 'coerce': 'True'}))
+
+ self.assertEqual(frozen['partial'],
+ ('semantic_version.django_fields.VersionField', [], {'max_length': '200', 'partial': 'True', 'coerce': 'True'}))
+
+ def test_freezing_app(self):
+ frozen = south.creator.freezer.freeze_apps('django_test_app')
+
+ # Test VersionModel
+ self.assertEqual(frozen['django_test_app.versionmodel']['version'],
+ ('semantic_version.django_fields.VersionField', [], {'max_length': '200'}))
+
+ self.assertEqual(frozen['django_test_app.versionmodel']['spec'],
+ ('semantic_version.django_fields.SpecField', [], {'max_length': '200'}))
+
+ # Test PartialVersionModel
+ self.assertEqual(frozen['django_test_app.partialversionmodel']['partial'],
+ ('semantic_version.django_fields.VersionField', [], {'max_length': '200', 'partial': 'True'}))
+
+ self.assertEqual(frozen['django_test_app.partialversionmodel']['optional'],
+ ('semantic_version.django_fields.VersionField', [], {'max_length': '200', 'blank': 'True', 'null': 'True'}))
+
+ self.assertEqual(frozen['django_test_app.partialversionmodel']['optional_spec'],
+ ('semantic_version.django_fields.SpecField', [], {'max_length': '200', 'blank': 'True', 'null': 'True'}))
+
+ # Test CoerceVersionModel
+ self.assertEqual(frozen['django_test_app.coerceversionmodel']['version'],
+ ('semantic_version.django_fields.VersionField', [], {'max_length': '200', 'coerce': 'True'}))
+
+ self.assertEqual(frozen['django_test_app.coerceversionmodel']['partial'],
+ ('semantic_version.django_fields.VersionField', [], {'max_length': '200', 'partial': 'True', 'coerce': 'True'}))
+
+
+if django_loaded:
+ from django.test import TestCase
+ if django.VERSION[:2] < (1, 6):
+ from django.test.simple import DjangoTestSuiteRunner as TestRunner
+ else:
+ from django.test.runner import DiscoverRunner as TestRunner
+
+ class DbInteractingTestCase(TestCase):
+
+ @classmethod
+ def setUpClass(cls):
+ cls.old_state = TestRunner().setup_databases()
+
+ @classmethod
+ def tearDownClass(cls):
+ TestRunner().teardown_databases(cls.old_state)
+
+ def test_db_interaction(self):
+ o1 = models.VersionModel(version='0.1.1', spec='<0.2.4-rc42')
+ o2 = models.VersionModel(version='0.4.3-rc3+build3', spec='==0.4.3')
+
+ o1.save()
+ o2.save()
+
+ obj1 = models.VersionModel.objects.get(pk=o1.pk)
+ self.assertEqual(o1.version, obj1.version)
+
+ obj2 = models.VersionModel.objects.get(pk=o2.pk)
+ self.assertEqual(o2.version, obj2.version)
+
+else: # pragma: no cover
+ pass
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/tests/test_match.py
@@ -0,0 +1,164 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+import unittest
+
+import semantic_version
+
+
+class MatchTestCase(unittest.TestCase):
+ invalid_specs = [
+ '',
+ '!0.1',
+ '<=0.1.4a',
+ '>0.1.1.1',
+ '<0.1.2-rc1.3-14.15+build.2012-01-01.11h34',
+ ]
+
+ valid_specs = [
+ '*',
+ '==0.1.0',
+ '=0.1.0',
+ '0.1.0',
+ '<=0.1.1',
+ '<0.1',
+ '1',
+ '>0.1.2-rc1',
+ '>=0.1.2-rc1.3.4',
+ '==0.1.2+build42-12.2012-01-01.12h23',
+ '!=0.1.2-rc1.3-14.15+build.2012-01-01.11h34',
+ '^0.1.2',
+ '~0.1.2',
+ ]
+
+ matches = {
+ '*': [
+ '0.1.1',
+ '0.1.1+build4.5',
+ '0.1.2-rc1',
+ '0.1.2-rc1.3',
+ '0.1.2-rc1.3.4',
+ '0.1.2+build42-12.2012-01-01.12h23',
+ '0.1.2-rc1.3-14.15+build.2012-01-01.11h34',
+ '0.2.0',
+ '1.0.0',
+ ],
+ '==0.1.2': [
+ '0.1.2-rc1',
+ '0.1.2-rc1.3.4',
+ '0.1.2+build42-12.2012-01-01.12h23',
+ '0.1.2-rc1.3-14.15+build.2012-01-01.11h34',
+ ],
+ '=0.1.2': [
+ '0.1.2-rc1',
+ '0.1.2-rc1.3.4',
+ '0.1.2+build42-12.2012-01-01.12h23',
+ '0.1.2-rc1.3-14.15+build.2012-01-01.11h34',
+ ],
+ '0.1.2': [
+ '0.1.2-rc1',
+ '0.1.2-rc1.3.4',
+ '0.1.2+build42-12.2012-01-01.12h23',
+ '0.1.2-rc1.3-14.15+build.2012-01-01.11h34',
+ ],
+ '<=0.1.2': [
+ '0.1.1',
+ '0.1.2-rc1',
+ '0.1.2-rc1.3.4',
+ '0.1.2',
+ '0.1.2+build4',
+ ],
+ '!=0.1.2+': [
+ '0.1.2+1',
+ '0.1.2-rc1',
+ ],
+ '!=0.1.2-': [
+ '0.1.1',
+ '0.1.2-rc1',
+ ],
+ '!=0.1.2+345': [
+ '0.1.1',
+ '0.1.2-rc1+345',
+ '0.1.2+346',
+ '0.2.3+345',
+ ],
+ '>=0.1.1': [
+ '0.1.1',
+ '0.1.1+build4.5',
+ '0.1.2-rc1.3',
+ '0.2.0',
+ '1.0.0',
+ ],
+ '>0.1.1': [
+ '0.1.2+build4.5',
+ '0.1.2-rc1.3',
+ '0.2.0',
+ '1.0.0',
+ ],
+ '<0.1.1-': [
+ '0.1.1-alpha',
+ '0.1.1-rc4',
+ '0.1.0+12.3',
+ ],
+ '^0.1.2': [
+ '0.1.2',
+ '0.1.2+build4.5',
+ '0.1.3-rc1.3',
+ '0.2.0',
+ ],
+ '~0.1.2': [
+ '0.1.2',
+ '0.1.2+build4.5',
+ '0.1.3-rc1.3',
+ ],
+ }
+
+ def test_invalid(self):
+ for invalid in self.invalid_specs:
+ with self.assertRaises(ValueError, msg="Spec(%r) should be invalid" % invalid):
+ semantic_version.Spec(invalid)
+
+ def test_simple(self):
+ for valid in self.valid_specs:
+ spec = semantic_version.SpecItem(valid)
+ normalized = str(spec)
+ self.assertEqual(spec, semantic_version.SpecItem(normalized))
+
+ def test_match(self):
+ for spec_txt, versions in self.matches.items():
+ spec = semantic_version.Spec(spec_txt)
+ self.assertNotEqual(spec, spec_txt)
+ for version_txt in versions:
+ version = semantic_version.Version(version_txt)
+ self.assertTrue(spec.match(version), "%r does not match %r" % (version, spec))
+ self.assertTrue(semantic_version.match(spec_txt, version_txt))
+ self.assertTrue(version in spec, "%r not in %r" % (version, spec))
+
+ def test_contains(self):
+ spec = semantic_version.Spec('<=0.1.1')
+ self.assertFalse('0.1.0' in spec, "0.1.0 should not be in %r" % spec)
+
+ version = semantic_version.Version('0.1.1+4.2')
+ self.assertTrue(version in spec, "%r should be in %r" % (version, spec))
+
+ version = semantic_version.Version('0.1.1-rc1+4.2')
+ self.assertTrue(version in spec, "%r should be in %r" % (version, spec))
+
+ def test_prerelease_check(self):
+ strict_spec = semantic_version.Spec('>=0.1.1-')
+ lax_spec = semantic_version.Spec('>=0.1.1')
+ version = semantic_version.Version('0.1.1-rc1+4.2')
+ self.assertTrue(version in lax_spec, "%r should be in %r" % (version, lax_spec))
+ self.assertFalse(version in strict_spec, "%r should not be in %r" % (version, strict_spec))
+
+ def test_build_check(self):
+ spec = semantic_version.Spec('<=0.1.1-rc1')
+ version = semantic_version.Version('0.1.1-rc1+4.2')
+ self.assertTrue(version in spec, "%r should be in %r" % (version, spec))
+
+
+if __name__ == '__main__': # pragma: no cover
+ unittest.main()
+
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/tests/test_parsing.py
@@ -0,0 +1,99 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+import itertools
+import unittest
+
+import semantic_version
+
+
+class ParsingTestCase(unittest.TestCase):
+ invalids = [
+ None,
+ '',
+ '0',
+ '0.1',
+ '0.1.4a',
+ '0.1.1.1',
+ '0.1.2-rc23,1',
+ ]
+
+ valids = [
+ '0.1.1',
+ '0.1.2-rc1',
+ '0.1.2-rc1.3.4',
+ '0.1.2+build42-12.2012-01-01.12h23',
+ '0.1.2-rc1.3-14.15+build.2012-01-01.11h34',
+ ]
+
+ def test_invalid(self):
+ for invalid in self.invalids:
+ self.assertRaises(ValueError, semantic_version.Version, invalid)
+
+ def test_simple(self):
+ for valid in self.valids:
+ version = semantic_version.Version(valid)
+ self.assertEqual(valid, str(version))
+
+
+class ComparisonTestCase(unittest.TestCase):
+ order = [
+ '1.0.0-alpha',
+ '1.0.0-alpha.1',
+ '1.0.0-beta.2',
+ '1.0.0-beta.11',
+ '1.0.0-rc.1',
+ '1.0.0',
+ '1.3.7+build',
+ ]
+
+ def test_comparisons(self):
+ for i, first in enumerate(self.order):
+ first_ver = semantic_version.Version(first)
+ for j, second in enumerate(self.order):
+ second_ver = semantic_version.Version(second)
+ if i < j:
+ self.assertTrue(first_ver < second_ver, '%r !< %r' % (first_ver, second_ver))
+ elif i == j:
+ self.assertTrue(first_ver == second_ver, '%r != %r' % (first_ver, second_ver))
+ else:
+ self.assertTrue(first_ver > second_ver, '%r !> %r' % (first_ver, second_ver))
+
+ cmp_res = -1 if i < j else (1 if i > j else 0)
+ self.assertEqual(cmp_res, semantic_version.compare(first, second))
+
+ unordered = [
+ [
+ '1.0.0-rc.1',
+ '1.0.0-rc.1+build.1',
+ ],
+ [
+ '1.0.0',
+ '1.0.0+0.3.7',
+ ],
+ [
+ '1.3.7',
+ '1.3.7+build',
+ '1.3.7+build.2.b8f12d7',
+ '1.3.7+build.11.e0f985a',
+ ],
+ ]
+
+ def test_unordered(self):
+ for group in self.unordered:
+ for a, b in itertools.combinations(group, 2):
+ v1 = semantic_version.Version(a)
+ v2 = semantic_version.Version(b)
+ self.assertTrue(v1 == v1, "%r != %r" % (v1, v1))
+ self.assertFalse(v1 != v1, "%r != %r" % (v1, v1))
+ self.assertFalse(v1 == v2, "%r == %r" % (v1, v2))
+ self.assertTrue(v1 != v2, "%r !!= %r" % (v1, v2))
+ self.assertFalse(v1 < v2, "%r !< %r" % (v1, v2))
+ self.assertFalse(v1 <= v2, "%r !<= %r" % (v1, v2))
+ self.assertFalse(v2 > v1, "%r !> %r" % (v2, v1))
+ self.assertFalse(v2 >= v1, "%r !>= %r" % (v2, v1))
+
+if __name__ == '__main__': # pragma: no cover
+ unittest.main()
new file mode 100755
--- /dev/null
+++ b/python/semantic_version/tests/test_spec.py
@@ -0,0 +1,156 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+# Copyright (c) The python-semanticversion project
+# This code is distributed under the two-clause BSD License.
+
+"""Test conformance to the specs."""
+
+from .compat import unittest, is_python2
+
+import semantic_version
+
+# shortcut
+Version = semantic_version.Version
+
+
+class FormatTests(unittest.TestCase):
+ """Tests proper version validation."""
+
+ def test_major_minor_patch(self):
+ ### SPEC:
+ # A normal version number MUST take the form X.Y.Z
+
+ with self.assertRaises(ValueError):
+ Version('1')
+ with self.assertRaises(ValueError):
+ Version('1.1')
+ # Doesn't raise
+ Version('1.2.3')
+ with self.assertRaises(ValueError):
+ Version('1.2.3.4')
+
+ ### SPEC:
+ # Where X, Y, and Z are non-negative integers,
+
+ with self.assertRaises(ValueError):
+ Version('1.2.A')
+ with self.assertRaises(ValueError):
+ Version('1.-2.3')
+ # Valid
+ v = Version('1.2.3')
+ self.assertEqual(1, v.major)
+ self.assertEqual(2, v.minor)
+ self.assertEqual(3, v.patch)
+
+
+ ### Spec:
+ # And MUST NOT contain leading zeroes
+ with self.assertRaises(ValueError):
+ Version('1.2.01')
+ with self.assertRaises(ValueError):
+ Version('1.02.1')
+ with self.assertRaises(ValueError):
+ Version('01.2.1')
+ # Valid
+ v = Version('0.0.0')
+ self.assertEqual(0, v.major)
+ self.assertEqual(0, v.minor)
+ self.assertEqual(0, v.patch)
+
+ def test_prerelease(self):
+ ### SPEC:
+ # A pre-release version MAY be denoted by appending a hyphen and a
+ # series of dot separated identifiers immediately following the patch
+ # version.
+
+ with self.assertRaises(ValueError):
+ Version('1.2.3 -23')
+ # Valid
+ v = Version('1.2.3-23')
+ self.assertEqual(('23',), v.prerelease)
+
+ ### SPEC:
+ # Identifiers MUST comprise only ASCII alphanumerics and hyphen.
+ # Identifiers MUST NOT be empty
+ with self.assertRaises(ValueError):
+ Version('1.2.3-a,')
+ with self.assertRaises(ValueError):
+ Version('1.2.3-..')
+
+ ### SPEC:
+ # Numeric identifiers MUST NOT include leading zeroes.
+
+ with self.assertRaises(ValueError):
+ Version('1.2.3-a0.01')
+ with self.assertRaises(ValueError):
+ Version('1.2.3-00')
+ # Valid
+ v = Version('1.2.3-0a.0.000zz')
+ self.assertEqual(('0a', '0', '000zz'), v.prerelease)
+
+ def test_build(self):
+ ### SPEC:
+ # Build metadata MAY be denoted by appending a plus sign and a series of
+ # dot separated identifiers immediately following the patch or
+ # pre-release version
+
+ v = Version('1.2.3')
+ self.assertEqual((), v.build)
+ with self.assertRaises(ValueError):
+ Version('1.2.3 +4')
+
+ ### SPEC:
+ # Identifiers MUST comprise only ASCII alphanumerics and hyphen.
+ # Identifiers MUST NOT be empty
+ with self.assertRaises(ValueError):
+ Version('1.2.3+a,')
+ with self.assertRaises(ValueError):
+ Version('1.2.3+..')
+
+ # Leading zeroes allowed
+ v = Version('1.2.3+0.0a.01')
+ self.assertEqual(('0', '0a', '01'), v.build)
+
+ def test_precedence(self):
+ ### SPEC:
+ # Precedence is determined by the first difference when comparing from
+ # left to right as follows: Major, minor, and patch versions are always
+ # compared numerically.
+ # Example: 1.0.0 < 2.0.0 < 2.1.0 < 2.1.1
+ self.assertLess(Version('1.0.0'), Version('2.0.0'))
+ self.assertLess(Version('2.0.0'), Version('2.1.0'))
+ self.assertLess(Version('2.1.0'), Version('2.1.1'))
+
+ ### SPEC:
+ # When major, minor, and patch are equal, a pre-release version has
+ # lower precedence than a normal version.
+ # Example: 1.0.0-alpha < 1.0.0
+ self.assertLess(Version('1.0.0-alpha'), Version('1.0.0'))
+
+ ### SPEC:
+ # Precedence for two pre-release versions with the same major, minor,
+ # and patch version MUST be determined by comparing each dot separated
+ # identifier from left to right until a difference is found as follows:
+ # identifiers consisting of only digits are compared numerically
+ self.assertLess(Version('1.0.0-1'), Version('1.0.0-2'))
+
+ # and identifiers with letters or hyphens are compared lexically in
+ # ASCII sort order.
+ self.assertLess(Version('1.0.0-aa'), Version('1.0.0-ab'))
+
+ # Numeric identifiers always have lower precedence than
+ # non-numeric identifiers.
+ self.assertLess(Version('1.0.0-9'), Version('1.0.0-a'))
+
+ # A larger set of pre-release fields has a higher precedence than a
+ # smaller set, if all of the preceding identifiers are equal.
+ self.assertLess(Version('1.0.0-a.b.c'), Version('1.0.0-a.b.c.0'))
+
+ # Example: 1.0.0-alpha < 1.0.0-alpha.1 < 1.0.0-alpha.beta < 1.0.0-beta < 1.0.0-beta.2 < 1.0.0-beta.11 < 1.0.0-rc.1 < 1.0.0.
+ self.assertLess(Version('1.0.0-alpha'), Version('1.0.0-alpha.1'))
+ self.assertLess(Version('1.0.0-alpha.1'), Version('1.0.0-alpha.beta'))
+ self.assertLess(Version('1.0.0-alpha.beta'), Version('1.0.0-beta'))
+ self.assertLess(Version('1.0.0-beta'), Version('1.0.0-beta.2'))
+ self.assertLess(Version('1.0.0-beta.2'), Version('1.0.0-beta.11'))
+ self.assertLess(Version('1.0.0-beta.11'), Version('1.0.0-rc.1'))
+ self.assertLess(Version('1.0.0-rc.1'), Version('1.0.0'))