Extracted version matching against specs into utility methods
Adjusted plugin manager and software update plugin to utilize new methods in octoprint.util.version
This commit is contained in:
1 parent
660de61997
commit
083601c978
4 files changed
+269
-40
No files matched your search
@@ -13,6 +13,7 @@ from octoprint.settings import valid_boolean_trues
|
||||
from octoprint.server.util.flask import restricted_access
|
||||
from octoprint.server import admin_permission, VERSION
|
||||
from octoprint.util.pip import PipCaller, UnknownPip
|
||||
from octoprint.util.version import parse_version, version_matches_any_spec
|
||||
|
||||
from flask import jsonify, make_response
|
||||
from flask.ext.babel import gettext
|
||||
@@ -550,7 +551,8 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
return False
|
||||
|
||||
current_os = self._get_os()
|
||||
octoprint_version = self._get_octoprint_version(base=True)
|
||||
from octoprint import __version__ as octoprint_version
|
||||
parsed_octoprint_version = parse_version(octoprint_version)
|
||||
|
||||
def map_repository_entry(entry):
|
||||
result = dict(entry)
|
||||
@@ -565,7 +567,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
|
||||
if "compatibility" in entry:
|
||||
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and len(entry["compatibility"]["octoprint"]):
|
||||
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(octoprint_version, entry["compatibility"]["octoprint"])
|
||||
result["is_compatible"]["octoprint"] = self._is_octoprint_compatible(parsed_octoprint_version, entry["compatibility"]["octoprint"])
|
||||
|
||||
if "os" in entry["compatibility"] and entry["compatibility"]["os"] is not None and len(entry["compatibility"]["os"]):
|
||||
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
|
||||
@@ -580,17 +582,10 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
Tests if the current ``octoprint_version`` is compatible to any of the provided ``compatibility_entries``.
|
||||
"""
|
||||
|
||||
for octo_compat in compatibility_entries:
|
||||
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
|
||||
octo_compat = ">={}".format(octo_compat)
|
||||
|
||||
s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat))
|
||||
if octoprint_version in s:
|
||||
break
|
||||
else:
|
||||
return False
|
||||
|
||||
return True
|
||||
spec_matcher = ("<", "<=", "!=", "==", ">=", ">", "~=", "===")
|
||||
specs = map(lambda x: x if any(x.startswith(c) for c in spec_matcher) else ">={}".format(x),
|
||||
compatibility_entries)
|
||||
return version_matches_any_spec(octoprint_version, specs, package="OctoPrint", base=True)
|
||||
|
||||
def _is_os_compatible(self, current_os, compatibility_entries):
|
||||
"""
|
||||
@@ -608,31 +603,6 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
|
||||
else:
|
||||
return "unknown"
|
||||
|
||||
def _get_octoprint_version_string(self):
|
||||
return VERSION
|
||||
|
||||
def _get_octoprint_version(self, base=False):
|
||||
octoprint_version_string = self._get_octoprint_version_string()
|
||||
|
||||
if "-" in octoprint_version_string:
|
||||
octoprint_version_string = octoprint_version_string[:octoprint_version_string.find("-")]
|
||||
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version_string)
|
||||
if base:
|
||||
if isinstance(octoprint_version, tuple):
|
||||
# old setuptools
|
||||
base_version = []
|
||||
for part in octoprint_version:
|
||||
if part.startswith("*"):
|
||||
break
|
||||
base_version.append(part)
|
||||
base_version.append("*final")
|
||||
octoprint_version = tuple(base_version)
|
||||
else:
|
||||
# new setuptools
|
||||
octoprint_version = pkg_resources.parse_version(octoprint_version.base_version)
|
||||
return octoprint_version
|
||||
|
||||
def _to_external_representation(self, plugin):
|
||||
return dict(
|
||||
key=plugin.key,
|
||||
|
||||
@@ -9,6 +9,7 @@ import requests
|
||||
import logging
|
||||
|
||||
from ..exceptions import ConfigurationInvalid
|
||||
from octoprint.util.version import parse_version
|
||||
|
||||
RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
|
||||
|
||||
@@ -95,8 +96,8 @@ def _is_current(release_information, compare_type, custom=None, force_base=True)
|
||||
|
||||
try:
|
||||
if compare_type == "python":
|
||||
local_version = _get_comparable_version_pkg_resources(sanitized_local, force_base=force_base)
|
||||
remote_version = _get_comparable_version_pkg_resources(sanitized_remote, force_base=force_base)
|
||||
local_version = parse_version(sanitized_local, base=force_base)
|
||||
remote_version = parse_version(sanitized_remote, base=force_base)
|
||||
return local_version >= remote_version
|
||||
|
||||
elif compare_type == "semantic":
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import, unicode_literals
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2016 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import pkg_resources
|
||||
|
||||
|
||||
def parse_version(version_string, base=False):
|
||||
"""
|
||||
Parses the given ``version_string`` using ``pkg_resources.parse_version``
|
||||
|
||||
If ``base`` is ``True``, the version will be reduced to the base version (e.g. ``1.2.0.dev.123`` will be reduced
|
||||
to ``1.2.0``) before returning.
|
||||
|
||||
If a ``-`` is contains in the version string, it and any following parts of the version stirng will be stripped
|
||||
(e.g. ``1.2.0-dev-123`` is turned into ``1.2.0``) to ensure the string is parsable using ``pkg_resources``.
|
||||
|
||||
Parameters:
|
||||
version_string (str, unicode): the version string to parse
|
||||
base (boolean): whether to reduce the version to the base version before returning
|
||||
|
||||
Returns:
|
||||
(tuple or object): the parsed version, as either a tuple or a ``setuptools`` version object, depending on the
|
||||
installed ``setuptools`` version
|
||||
"""
|
||||
|
||||
assert isinstance(version_string, basestring)
|
||||
|
||||
if "-" in version_string:
|
||||
version_string = version_string[:version_string.find("-")]
|
||||
|
||||
try:
|
||||
version = pkg_resources.parse_version(version_string)
|
||||
except:
|
||||
raise ValueError("Invalid version: {!r}".format(version_string))
|
||||
|
||||
if base:
|
||||
if isinstance(version, tuple):
|
||||
# old setuptools
|
||||
base_version = []
|
||||
for part in version:
|
||||
if part.startswith("*"):
|
||||
break
|
||||
base_version.append(part)
|
||||
base_version.append("*final")
|
||||
version = tuple(base_version)
|
||||
else:
|
||||
# new setuptools
|
||||
version = pkg_resources.parse_version(version.base_version)
|
||||
return version
|
||||
|
||||
|
||||
def version_matches_any_spec(version, specs, package=None, base=False):
|
||||
"""
|
||||
Checks if the supplied version matches any of the supplied specs.
|
||||
|
||||
See `Requirements Parsing <https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing>`_ for
|
||||
details on the format. The version spec does not need to start with ``package``, it will be added automatically
|
||||
if it's missing.
|
||||
|
||||
Example::
|
||||
>>> version_matches_any_spec("1.2.0", ["Foo>=1.1.0,<1.2.0", "Foo>=1.2.0,<1.3.0", "Foo>=1.3.0"])
|
||||
True
|
||||
>>> version_matches_any_spec("1.2.0", ["Foo>=1.1.0,<1.2.0", "Foo>=1.3.0"])
|
||||
False
|
||||
|
||||
Arguments:
|
||||
version (str, unicode, parsed version): version to check
|
||||
specs (list of str or unicode): version specs to check against
|
||||
package (str or unicode): name of the package to use in the spec
|
||||
base (boolean): If True, only check the base version of the version against the spec. Defaults
|
||||
to False.
|
||||
|
||||
Returns:
|
||||
(boolean) True if the version matches any of the version specs, False otherwise.
|
||||
"""
|
||||
|
||||
if isinstance(version, basestring):
|
||||
version = parse_version(version, base=base)
|
||||
|
||||
for spec in specs:
|
||||
if package is not None and not spec.lower().startswith(package.lower()):
|
||||
spec = package.lower() + spec
|
||||
|
||||
try:
|
||||
parsed_spec = next(pkg_resources.parse_requirements(spec))
|
||||
except:
|
||||
raise ValueError("Invalid spec: {!r}".format(spec))
|
||||
|
||||
if version in parsed_spec:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def version_matches_spec(version, spec, package=None, base=False):
|
||||
"""
|
||||
Checks if the supplied version matches the supplied spec.
|
||||
|
||||
See `Requirements Parsing <https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing>`_ for
|
||||
details on the format. The version spec does not need to start with ``package``, it will be added automatically
|
||||
if it's missing.
|
||||
|
||||
Example::
|
||||
>>> version_matches_spec("1.2.0", "Foo>=1.2.0,<1.3.0")
|
||||
True
|
||||
>>> version_matches_spec("1.2.0", "Foo>=1.3.0")
|
||||
False
|
||||
>>> version_matches_spec("1.2.0", ">=1.2.0,<1.3.0", package="Foo")
|
||||
True
|
||||
>>> version_matches_spec("1.2.0.dev.123", ">=1.2.0", package="Foo")
|
||||
False
|
||||
>>> version_matches_spec("1.2.0.dev.123", ">=1.2.0", package="Foo", base=True)
|
||||
True
|
||||
|
||||
Arguments:
|
||||
version (str, unicode, parsed version): version to check
|
||||
spec (str or unicode): version spec to check against
|
||||
package (str or unicode): name of the package to use in the spec
|
||||
base (boolean): If True, only check the base version of the version against the spec. Defaults
|
||||
to False.
|
||||
|
||||
Returns:
|
||||
(boolean) True if the version matches the version spec, False otherwise.
|
||||
"""
|
||||
return version_matches_any_spec(version, [spec], package=package, base=base)
|
||||
|
||||
|
||||
def octoprint_version_matches(spec, base=False):
|
||||
"""
|
||||
Checks if the current OctoPrint version matches the provided spec.
|
||||
|
||||
See `Requirements Parsing <https://pythonhosted.org/setuptools/pkg_resources.html#requirements-parsing>`_ for
|
||||
details on the format. The version spec does not need to start with "OctoPrint", it will be added automatically
|
||||
if it's missing.
|
||||
|
||||
Example::
|
||||
|
||||
octoprint_version_matches(">=1.2.0")
|
||||
|
||||
octoprint_version_matches("OctoPrint>=1.3.0", )
|
||||
|
||||
Arguments:
|
||||
spec (str or unicode): version spec to check against
|
||||
base (boolean): If True, only check the base version of the OctoPrint version against the spec. Defaults
|
||||
to False.
|
||||
|
||||
Returns:
|
||||
(boolean) True if the version matches the version spec, False otherwise.
|
||||
"""
|
||||
|
||||
from octoprint import __version__
|
||||
return version_matches_any_spec(__version__, [spec], package="OctoPrint", base=base)
|
||||
@@ -0,0 +1,101 @@
|
||||
# coding=utf-8
|
||||
from __future__ import absolute_import
|
||||
|
||||
__author__ = "Gina Häußge <osd@foosel.net>"
|
||||
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
|
||||
__copyright__ = "Copyright (C) 2015 The OctoPrint Project - Released under terms of the AGPLv3 License"
|
||||
|
||||
|
||||
import unittest
|
||||
import ddt
|
||||
import mock
|
||||
|
||||
from octoprint.util.version import version_matches_spec, version_matches_any_spec, octoprint_version_matches, parse_version
|
||||
|
||||
|
||||
@ddt.ddt
|
||||
class VersionUtilTest(unittest.TestCase):
|
||||
|
||||
@ddt.data(("1.2.0", "foo>=1.2.0,<1.3.0", None, False, True),
|
||||
("1.2.0", "foo>=1.3.0", None, False, False),
|
||||
("1.2.0-dev-405", "foo>=1.2.0", None, True, True),
|
||||
("1.2.0.dev.405", "foo>=1.2.0", None, False, False),
|
||||
("1.2.0.dev.405", "foo>=1.2.0", None, True, True),
|
||||
("1.2.0", ">=1.2.0,<1.3.0", "foo", False, True),
|
||||
("1.2.0", "FoO>=1.2.0,<1.3.0", "foo", False, True),
|
||||
("1.2.0", ">=1.2.0,<1.3.0", None, False, ValueError),
|
||||
("1.2.fnord", ">=1.2.0", None, False, ValueError)
|
||||
)
|
||||
@ddt.unpack
|
||||
def test_version_matches_spec(self, version, spec, package, base, expected):
|
||||
self.assertExpected(version_matches_spec, (version, spec), dict(package=package, base=base), expected)
|
||||
|
||||
def test_version_matches_any_spec(self):
|
||||
self.assertTrue(version_matches_any_spec("1.2.0", [">=1.1.0,<1.2.0", ">=1.2.0,<1.3.0", "==1.3.0"], package="foo"))
|
||||
|
||||
def test_version_matches_any_spec_nomatch(self):
|
||||
self.assertFalse(version_matches_any_spec("1.2.0", [">=1.1.0,<1.2.0", "==1.3.0"], package="foo"))
|
||||
|
||||
@ddt.data((">=1.2.0,<1.3.0", False, "1.2.0", True),
|
||||
(">=1.2.0,<1.3.0", False, "1.3.0.dev.123", False),
|
||||
(">=1.2.0,<1.3.0", False, "1.2.0.dev.123", False),
|
||||
(">=1.2.0,<1.3.0", True, "1.2.0.dev.123", True))
|
||||
@ddt.unpack
|
||||
def test_octoprint_version_matches(self, spec, base, mocked_version, expected):
|
||||
import octoprint
|
||||
old_version = octoprint.__version__
|
||||
try:
|
||||
octoprint.__version__ = mocked_version
|
||||
self.assertExpected(octoprint_version_matches, (spec,), dict(base=base), expected)
|
||||
finally:
|
||||
octoprint.__version__ = old_version
|
||||
|
||||
@ddt.data(("1.2.0", False, "1.2.0", ("00000001", "00000002", "00000000", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"),
|
||||
("1.2.0-dev-123", False, "1.2.0", ("00000001", "00000002", "00000000", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"),
|
||||
("1.2.0-dev-123", True, "1.2.0", ("00000001", "00000002", "00000000", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"),
|
||||
("1.2.0.dev.123", False, "1.2.0.dev.123", ("00000001", "00000002", "00000000", "*@", "00000123", "*final"), ("00000001", "00000002", "00000000", "*@", "00000123", "*final"), "1.2.0"),
|
||||
("1.2.0.dev.123", True, "1.2.0.dev.123", ("00000001", "00000002", "00000000", "*@", "00000123", "*final"), ("00000001", "00000002", "00000000", "*final"), "1.2.0"))
|
||||
@ddt.unpack
|
||||
def test_parse_version(self, version, base, stripped_version, mocked_tuple, expected_tuple, mocked_base_version):
|
||||
mocked_obj = mock.MagicMock()
|
||||
mocked_obj.base_version = mocked_base_version
|
||||
|
||||
# old setuptools return a tuple for parse_version, we simulate that here
|
||||
with mock.patch("pkg_resources.parse_version") as mocked_parse_version:
|
||||
mocked_parse_version.return_value = mocked_tuple
|
||||
|
||||
result = parse_version(version, base=base)
|
||||
self.assertEqual(expected_tuple, result)
|
||||
|
||||
mocked_parse_version.assert_called_with(stripped_version)
|
||||
|
||||
# newer setuptools return a version object, we simulate that here
|
||||
with mock.patch("pkg_resources.parse_version") as mocked_parse_version:
|
||||
mocked_parse_version.return_value = mocked_obj
|
||||
|
||||
result = parse_version(version, base=base)
|
||||
self.assertEqual(mocked_obj, result)
|
||||
|
||||
expected_calls = [mock.call(stripped_version)]
|
||||
if base:
|
||||
expected_calls.append(mock.call(mocked_base_version))
|
||||
|
||||
self.assertListEqual(expected_calls, mocked_parse_version.call_args_list)
|
||||
|
||||
def assertExpected(self, callable, args, kwargs, expected):
|
||||
"""
|
||||
Helper for checking the return value against an expected one.
|
||||
|
||||
Maybe an exception class in which case a try-catch-block is created and a test for the correct
|
||||
exception is set up.
|
||||
"""
|
||||
|
||||
if isinstance(expected, type) and issubclass(expected, Exception):
|
||||
try:
|
||||
callable(*args, **kwargs)
|
||||
self.fail("Expected {}".format(expected))
|
||||
except Exception as e:
|
||||
if not isinstance(e, expected):
|
||||
self.fail("Expected exception of type {}, got {} instead".format(expected, e.__class__.__name__))
|
||||
else:
|
||||
self.assertEqual(expected, callable(*args, **kwargs))
|
||||
Reference in new issue
Block a user