Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions changelog.d/262.feature.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Added ``Version.diff(other)`` to classify valid version pairs like
node-semver 7.7.2: ``major``, ``minor``, ``patch``, ``premajor``, ``preminor``,
``prepatch``, or ``prerelease``, including its prerelease-to-release rules.
Equal precedence returns ``None`` and build metadata is ignored. It accepts
``Version``, ``str``, ``bytes``, ``dict``, ``tuple``, and ``list`` operands with
Python conversion errors. This classification does not choose a staging-branch
bump policy.
63 changes: 63 additions & 0 deletions docs/usage/compare-versions.rst
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,66 @@ If you need to convert some types into others, refer to :ref:`sec.convert.versio
The use of these comparison operators also implies that you can use builtin
functions that leverage this capability; builtins including, but not limited to: :func:`max`, :func:`min`
(for examples, see :ref:`sec_max_min`) and :func:`sorted`.

Classifying Version Differences
-------------------------------
Comment thread
tomschr marked this conversation as resolved.

Use :meth:`~semver.version.Version.diff` to classify two versions like
`node-semver 7.7.2 <https://github.com/npm/node-semver/blob/v7.7.2/functions/diff.js>`_.
It returns ``major``, ``minor``, ``patch``, ``premajor``, ``preminor``,
``prepatch``, or ``prerelease``. Versions with equal precedence return ``None``,
including versions that differ only in build metadata::

>>> Version.parse("1.0.0").diff("1.1.5")
'minor'
>>> Version.parse("1.0.0+one").diff("1.0.0+two") is None
True

The higher version determines the classification, regardless of argument order.
If it is a prerelease and a core part differs, the result has a ``pre`` prefix.
Different prereleases with the same core return ``prerelease``::

>>> Version.parse("1.2.3").diff("1.2.4-rc.1")
'prepatch'
>>> Version.parse("1.2.4-rc.1").diff("1.2.3")
'prepatch'
>>> Version.parse("1.2.3-alpha").diff("1.2.3-beta")
'prerelease'

When the lower version is a prerelease and the higher version is a release,
node-semver applies special rules. A lower version with zero minor and patch
always gives ``major``, even if the core versions differ. Otherwise, for equal
core versions, zero patch gives ``minor`` and nonzero patch gives ``patch``::

>>> Version.parse("1.0.0-alpha").diff("1.0.0")
'major'
>>> Version.parse("1.0.0-alpha").diff("1.1.1")
'major'
>>> Version.parse("1.1.0-alpha").diff("1.1.0")
'minor'
>>> Version.parse("1.0.1-rc.1").diff("1.0.1")
'patch'

``diff`` classifies version differences; it does not decide which bump to apply
on a staging branch. For example, the last pair gives ``patch``, even if your
release policy calls for a minor bump. It does not change ``next_version`` or
the bump methods.

The operand may be a ``Version`` (including a subclass), ``str``, ``bytes``,
``dict``, ``tuple``, or ``list``. Strings and bytes are parsed using the receiver's
class; collections are passed as keyword or positional constructor arguments::

>>> Version(1).diff(b"2.0.0")
'major'
>>> Version(1).diff({"major": 2})
'major'
>>> Version(1).diff((2, 0, 0))
'major'
>>> Version(1).diff([2, 0, 0])
'major'

Existing ``Version`` instances are used without reconstruction. Classification
uses SemVer precedence, including on subclass receivers. Unsupported types and
invalid constructor argument types or shapes raise ``TypeError``. Invalid
strings, byte decoding, and invalid constructor values raise ``ValueError``;
conversion errors are propagated as in Python's parsing and construction APIs.
80 changes: 80 additions & 0 deletions src/semver/version.py
Original file line number Diff line number Diff line change
Expand Up @@ -457,6 +457,86 @@ def bump_build(self, token: Optional[str] = "build") -> "Version":
build += ".0"
return cls(self._major, self._minor, self._patch, self._prerelease, build)

# Adapted from node-semver v7.7.2 functions/diff.js:
# https://github.com/npm/node-semver/blob/v7.7.2/functions/diff.js
# The ISC License
#
# Copyright (c) Isaac Z. Schlueter and Contributors
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
# IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
def diff(self, other: Comparable | bytes) -> str | None:
"""
Classify the difference between versions, matching node-semver 7.7.2.

Return ``major``, ``minor``, ``patch``, ``premajor``, ``preminor``,
``prepatch``, or ``prerelease``. Equal precedence returns ``None``;
build metadata is ignored. The higher version determines the
prerelease prefix, so swapping the operands gives the same result.
Prerelease-to-release transitions follow node-semver's special rules.
This classification does not choose a staging-branch bump policy.

:param other: a Version, str, bytes, dict, tuple, or list. Strings are
parsed and collections are passed to the constructor of type(self).
Existing Version instances, including subclasses, are used directly.
:return: the difference classification, or None for equal precedence
:raises TypeError: if other is unsupported or its constructor arguments
have invalid types or shape
:raises ValueError: if parsing, decoding, or constructor values are invalid

>>> Version.parse("1.0.0").diff("1.1.5")
'minor'
>>> Version.parse("1.2.3").diff("1.2.4-rc.1")
'prepatch'
>>> Version.parse("1.0.0-alpha").diff("1.1.1")
'major'
>>> Version.parse("1.0.0+one").diff("1.0.0+two") is None
True
"""
cls = type(self)
if isinstance(other, String.__args__): # type: ignore
other = cls.parse(other)
elif isinstance(other, dict):
other = cls(**other)
elif isinstance(other, (tuple, list)):
other = cls(*other)
elif not isinstance(other, Version):
raise TypeError(
"Expected str, bytes, dict, tuple, list, or Version instance, "
f"but got {type(other)}"
)

# Use base SemVer precedence while accepting base and sibling instances
# on subclass receivers, without invoking their custom constructors.
current = Version(self.major, self.minor, self.patch, self.prerelease)
comparison = current.compare(other)
if comparison == 0:
return None

high, low = (self, other) if comparison > 0 else (other, self)
if low.prerelease and not high.prerelease:
if not low.minor and not low.patch:
return "major"
low_core = (low.major, low.minor, low.patch)
high_core = (high.major, high.minor, high.patch)
if low_core == high_core:
return "minor" if low.minor and not low.patch else "patch"

prefix = "pre" if high.prerelease else ""
for part in ("major", "minor", "patch"):
if getattr(self, part) != getattr(other, part):
return prefix + part
return "prerelease"

def compare(self, other: Comparable) -> int:
"""
Compare self with other.
Expand Down
164 changes: 164 additions & 0 deletions tests/test_diff.py
Comment thread
tomschr marked this conversation as resolved.
Original file line number Diff line number Diff line change
@@ -0,0 +1,164 @@
# Adapted from node-semver v7.7.2 test/functions/diff.js:
# https://github.com/npm/node-semver/blob/v7.7.2/test/functions/diff.js
# The ISC License
#
# Copyright (c) Isaac Z. Schlueter and Contributors
#
# Permission to use, copy, modify, and/or distribute this software for any
# purpose with or without fee is hereby granted, provided that the above
# copyright notice and this permission notice appear in all copies.
#
# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
# IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

import pytest

from semver import Version


@pytest.mark.parametrize(
"left,right,expected",
[
("1.2.3", "0.2.3", "major"),
("0.2.3", "1.2.3", "major"),
("1.4.5", "0.2.3", "major"),
("1.2.3", "2.0.0-pre", "premajor"),
("2.0.0-pre", "1.2.3", "premajor"),
("1.2.3", "1.3.3", "minor"),
("1.0.1", "1.1.0-pre", "preminor"),
("1.2.3", "1.2.4", "patch"),
("1.2.3", "1.2.4-pre", "prepatch"),
("0.0.1", "0.0.1-pre", "patch"),
("0.0.1", "0.0.1-pre-2", "patch"),
("1.1.0", "1.1.0-pre", "minor"),
("1.1.0-pre-1", "1.1.0-pre-2", "prerelease"),
("1.0.0", "1.0.0", None),
("1.0.0-1", "1.0.0-1", None),
("0.0.2-1", "0.0.2", "patch"),
("0.0.2-1", "0.0.3", "patch"),
("0.0.2-1", "0.1.0", "minor"),
("0.0.2-1", "1.0.0", "major"),
("0.1.0-1", "0.1.0", "minor"),
("1.0.0-1", "1.0.0", "major"),
("1.0.0-1", "1.1.1", "major"),
("1.0.0-1", "2.1.1", "major"),
("1.0.1-1", "1.0.1", "patch"),
("0.0.0-1", "0.0.0", "major"),
("1.0.0-1", "2.0.0", "major"),
("1.0.0-1", "2.0.0-1", "premajor"),
("1.0.0-1", "1.1.0-1", "preminor"),
("1.0.0-1", "1.0.1-1", "prepatch"),
("1.7.2-1", "1.8.1", "minor"),
("1.1.1-pre", "2.1.1-pre", "premajor"),
("1.1.1-pre", "2.1.1", "major"),
("1.2.3-1", "1.2.3", "patch"),
("1.4.0-1", "2.3.5", "major"),
("1.6.1-5", "1.7.2", "minor"),
("2.0.0-1", "2.1.1", "major"),
("1.0.0-alpha", "1.1.1", "major"),
("1.0.1-rc.1", "1.0.1", "patch"),
("1.2.3-alpha+one", "2.3.4-beta+two", "premajor"),
("1.2.3-alpha+one", "1.3.4-beta+two", "preminor"),
("1.2.3-alpha+one", "1.2.4-beta+two", "prepatch"),
("1.2.3-alpha.2", "1.2.3-alpha.10", "prerelease"),
("1.2.3-alpha.1", "1.2.3-alpha.1.1", "prerelease"),
("1.2.3+one", "1.2.3+two", None),
("1.2.3", "1.2.3+one", None),
("1.2.3-alpha+one", "1.2.3-alpha+two", None),
],
)
def test_diff(left, right, expected):
left, right = Version.parse(left), Version.parse(right)
before = left.to_tuple(), right.to_tuple()
assert left.diff(right) == expected
assert right.diff(left) == expected
assert (left.to_tuple(), right.to_tuple()) == before


@pytest.mark.parametrize(
"other",
[Version(2), "2.0.0", b"2.0.0", {"major": "2"}, (2,), [2, 0]],
)
def test_diff_accepts_comparable(other):
assert Version(1).diff(other) == "major"


@pytest.mark.parametrize(
"other",
[
"1.2.3-rc.1+two",
b"1.2.3-rc.1+two",
{"major": 1, "minor": 2, "patch": 3, "prerelease": "rc.1", "build": "two"},
(1, 2, 3, "rc.1", "two"),
[1, 2, 3, "rc.1", "two"],
],
)
def test_diff_converts_all_parts(other):
assert Version.parse("1.2.3-rc.1+one").diff(other) is None
assert Version(1, 2, 3).diff(other) == "patch"


@pytest.mark.parametrize("other", [None, 1, 1.5, object(), {1, 2, 3}])
def test_diff_rejects_unsupported_types(other):
with pytest.raises(
TypeError, match="Expected str, bytes, dict, tuple, list, or Version"
):
Version(1).diff(other)


@pytest.mark.parametrize("other", ["bad", b"bad", "1.02.3", b"\xff"])
def test_diff_rejects_invalid_strings(other):
with pytest.raises(ValueError):
Version(1).diff(other)


@pytest.mark.parametrize(
"other",
[{}, {"unknown": 1}, (1, 2, 3, 4, 5, 6), [], [None]],
)
def test_diff_rejects_invalid_collection_shape(other):
with pytest.raises(TypeError):
Version(1).diff(other)


@pytest.mark.parametrize("other", [{"major": -1}, ("bad",), [1, -2]])
def test_diff_rejects_invalid_collection_value(other):
with pytest.raises(ValueError):
Version(1).diff(other)


def test_diff_accepts_subclasses_without_reconstructing_instances():
class DerivedVersion(Version):
def __init__(self, major, *, label):
super().__init__(major)
self.label = label

def compare(self, other):
raise AssertionError("diff must use SemVer precedence")

class SiblingVersion(Version):
pass

derived = DerivedVersion(1, label="custom")
for other in (Version(2), DerivedVersion(2, label="other"), SiblingVersion(2)):
assert derived.diff(other) == "major"
assert other.diff(derived) == "major"
assert derived.label == "custom"


def test_diff_uses_subclass_conversion_hooks():
class DerivedVersion(Version):
@classmethod
def parse(cls, version, **kwargs):
return super().parse(version[1:], **kwargs)

assert DerivedVersion(1).diff("v2.0.0") == "major"
assert DerivedVersion(1).diff(b"v2.0.0") == "major"
assert DerivedVersion(1).diff({"major": 2}) == "major"
assert DerivedVersion(1).diff((2,)) == "major"
assert DerivedVersion(1).diff([2]) == "major"
Loading