Skip to content

Fix #210: Add classmethod VersionInfo.coerce #211

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Closed
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
1 change: 1 addition & 0 deletions CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ Features
* :gh:`201` (:pr:`202`): Reformatted source code with black
* :gh:`208` (:pr:`209`): Introduce new function :func:`semver.VersionInfo.isvalid`
and extend :command:`pysemver` with :command:`check` subcommand
* :gh:`210` (:pr:`211`): Added classmethod :func:`semver.VersionInfo.coerce`


Bug Fixes
Expand Down
29 changes: 29 additions & 0 deletions docs/usage.rst
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,35 @@ Depending which function you call, you get different types
{'major': 3, 'minor': 4, 'patch': 5, 'prerelease': None, 'build': None}


Parsing Incomplete Versions
---------------------------

If a version is incomplete (some parts are missing) this would lead to an
exception during the parsing process. As such, you cannot get a valid
:class:`semver.VersionInfo` instance.

To avoid such situations, such incomplete version strings can still be parsed
with the :func:`semver.VersionInfo.coerce` function. This function applies
the following rules:

* Tries to detect a "basic" version string (``major.minor.patch``).
* If not enough components can be found, missing components are
set to zero to obtain a valid semver version.

It expects a version string and returns a tuple. The first item of the tuple
is either a :class:`VersionInfo` instance or ``None`` if the function cannot
extract a version. The second item is the rest of the string:

.. code-block:: python

>>> semver.VersionInfo.coerce("v1.2")
(VersionInfo(major=1, minor=2, patch=0, prerelease=None, build=None), '')
>>> semver.VersionInfo.coerce("v1.2-abc")
(VersionInfo(major=1, minor=2, patch=0, prerelease=None, build=None), '-abc')
>>> semver.VersionInfo.coerce("abc")
(None, 'abc')


Increasing Parts of a Version
-----------------------------

Expand Down
41 changes: 41 additions & 0 deletions semver.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,19 @@
__maintainer__ = "Sebastien Celles"
__maintainer_email__ = "s.celles@gmail.com"

_BASEVERSION = re.compile(
r"""[vV]?
(?P<major>0|[1-9]\d*)
(\.
(?P<minor>0|[1-9]\d*)
(\.
(?P<patch>0|[1-9]\d*)
)?
)?
""",
re.VERBOSE,
)

_REGEX = re.compile(
r"""
^
Expand Down Expand Up @@ -336,6 +349,34 @@ def isvalid(cls, version):
except ValueError:
return False

@classmethod
def coerce(cls, version):
"""
Convert an incomplete version string into a semver-compatible VersionInfo
object

* Tries to detect a "basic" version string (``major.minor.patch``).
* If not enough components can be found, missing components are
set to zero to obtain a valid semver version.

:param str version: the version string to convert
:return: a tuple with a :class:`VersionInfo` instance (or ``None``
if it's not a version) and the rest of the string which doesn't
belong to a basic version.
:rtype: tuple(:class:`VersionInfo` | None, str)
"""
match = _BASEVERSION.search(version)
if not match:
return (None, version)

ver = {
key: 0 if value is None else value
for key, value in match.groupdict().items()
}
ver = cls(**ver)
rest = match.string[match.end() :] # noqa: E203
return ver, rest


def _to_dict(obj):
if isinstance(obj, VersionInfo):
Expand Down
18 changes: 18 additions & 0 deletions test_semver.py
Original file line number Diff line number Diff line change
Expand Up @@ -841,3 +841,21 @@ def test_replace_raises_ValueError_for_non_numeric_values():
def test_should_versioninfo_isvalid():
assert VersionInfo.isvalid("1.0.0") is True
assert VersionInfo.isvalid("foo") is False


@pytest.mark.parametrize(
"version,expected",
[
("v1", ("1.0.0", "")),
("v1.1", ("1.1.0", "")),
("v1.1.1", ("1.1.1", "")),
("v1.1.1-abc", ("1.1.1", "-abc")),
("not-semver", (None, "not-semver")),
("1-2-3", ("1.0.0", "-2-3")),
],
)
def test_should_versioninfo_coerce(version, expected):
ver = list(VersionInfo.coerce(version))
if ver[0] is not None:
ver[0] = str(ver[0])
assert tuple(ver) == expected
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy