Compare commits

...
Author SHA1 Message Date
Gina Häußge b94e513960 Merge remote-tracking branch 'origin/fix/betterPluginDependencyTracking' into fix/betterPluginDependencyTracking 2017-07-05 12:42:27 +02:00
Gina Häußge 875f69ea50 Fixed a unit test 2017-07-05 12:41:17 +02:00
Gina Häußge 5b7639590c Minor refactoring 2017-07-05 12:30:15 +02:00
Gina Häußge 2cd627ec6a Merge branch 'maintenance' into fix/betterPluginDependencyTracking
# Conflicts:
#	src/octoprint/plugin/__init__.py
#	src/octoprint/plugin/core.py
#	src/octoprint/plugins/pluginmanager/__init__.py
#	src/octoprint/plugins/softwareupdate/version_checks/github_release.py
2017-07-05 11:35:54 +02:00
Gina Häußge 2aa74866ac Match OctoPrint version against required one from plugin setup.py requires 2016-01-20 17:42:20 +01:00
Gina Häußge 3764eec9eb Allow defining required OctoPrint versions in setup_requires 2016-01-20 17:18:45 +01:00
Gina Häußge 083601c978 Extracted version matching against specs into utility methods
Adjusted plugin manager and software update plugin to utilize new methods in
octoprint.util.version
2016-01-20 16:59:46 +01:00
7 changed files with 347 additions and 87 deletions

No files matched your search

+9 -2
View File
@@ -45,7 +45,8 @@ def _validate_plugin(phase, plugin_info):
return True
def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_entry_points=None, plugin_disabled_list=None,
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None):
plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, plugin_validators=None,
plugin_checked_module_dependencies=None):
"""
Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager`
singleton.
@@ -71,6 +72,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
plugin_obsolete_hooks (list): A list of hooks that have been declared obsolete. Plugins implementing them will
not be enabled since they might depend on functionality that is no longer available.
plugin_validators (list): A list of additional plugin validators through which to process each plugin.
plugin_checked_module_dependencies (dict): A dictionary of package name-version-pairs for which to enable
dependency checking during plugin loading.
Returns:
PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin
@@ -114,6 +117,9 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
plugin_validators = [_validate_plugin]
else:
plugin_validators.append(_validate_plugin)
if plugin_checked_module_dependencies is None:
from octoprint import __version__ as octoprint_version
plugin_checked_module_dependencies = dict(octoprint=octoprint_version)
_instance = PluginManager(plugin_folders,
plugin_types,
@@ -122,7 +128,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_types=None, plugin_en
plugin_disabled_list=plugin_disabled_list,
plugin_restart_needing_hooks=plugin_restart_needing_hooks,
plugin_obsolete_hooks=plugin_obsolete_hooks,
plugin_validators=plugin_validators)
plugin_validators=plugin_validators,
plugin_checked_module_dependencies=plugin_checked_module_dependencies)
else:
raise ValueError("Plugin Manager not initialized yet")
return _instance
+20 -2
View File
@@ -41,6 +41,8 @@ try:
except ImportError:
from scandir import scandir
from octoprint.util.version import version_matches_spec
EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version")
FolderOrigin = namedtuple("FolderOrigin", "type, folder")
@@ -464,7 +466,7 @@ class PluginManager(object):
def __init__(self, plugin_folders, plugin_types, plugin_entry_points, logging_prefix=None,
plugin_disabled_list=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None,
plugin_validators=None):
plugin_validators=None, plugin_checked_module_dependencies=None):
self.logger = logging.getLogger(__name__)
if logging_prefix is None:
@@ -485,6 +487,7 @@ class PluginManager(object):
self.plugin_restart_needing_hooks = plugin_restart_needing_hooks
self.plugin_obsolete_hooks = plugin_obsolete_hooks
self.plugin_validators = plugin_validators
self.plugin_dependency_checks = plugin_checked_module_dependencies
self.logging_prefix = logging_prefix
self.enabled_plugins = dict()
@@ -619,6 +622,20 @@ class PluginManager(object):
module_name = entry_point.module_name
version = entry_point.dist.version
if self.plugin_dependency_checks:
requires = entry_point.dist.requires()
missing_requirements = []
for require in requires:
if require.key in self.plugin_dependency_checks:
available_version = self.plugin_dependency_checks[require.key]
spec = str(require.specifier)
if not version_matches_spec(available_version, spec, package=require.key, base=True):
missing_requirements.append("{}{}".format(require.key, spec))
if missing_requirements:
self.logger.warn("Plugin \"{}\" is missing requirements, skipping it: {}".format(key, ", ".join(missing_requirements)))
continue
if key in existing or key in result or (ignore_uninstalled and key in self.marked_plugins["uninstalled"]):
# plugin is already defined or marked as uninstalled, ignore it
continue
@@ -661,7 +678,8 @@ class PluginManager(object):
return result
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None):
def _import_plugin_from_module(self, key, folder=None, module_name=None, name=None, version=None, summary=None,
author=None, url=None, license=None):
# TODO error handling
try:
if folder:
+18 -45
View File
@@ -14,6 +14,7 @@ from octoprint.settings import valid_boolean_trues
from octoprint.server.util.flask import restricted_access, with_revalidation_checking, check_etag
from octoprint.server import admin_permission, VERSION
from octoprint.util.pip import LocalPipCaller, UnknownPip
from octoprint.util.version import parse_version, version_matches_any_spec
from flask import jsonify, make_response
from flask.ext.babel import gettext
@@ -723,7 +724,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
return False
current_os = self._get_os()
octoprint_version = self._get_octoprint_version(base=True)
parsed_octoprint_version = self._get_octoprint_version()
def map_repository_entry(entry):
result = copy.deepcopy(entry)
@@ -738,7 +739,7 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
if "compatibility" in entry:
if "octoprint" in entry["compatibility"] and entry["compatibility"]["octoprint"] is not None and isinstance(entry["compatibility"]["octoprint"], (list, tuple)) 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 isinstance(entry["compatibility"]["os"], (list, tuple)) and len(entry["compatibility"]["os"]):
result["is_compatible"]["os"] = self._is_os_compatible(current_os, entry["compatibility"]["os"])
@@ -817,20 +818,15 @@ 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:
try:
if not any(octo_compat.startswith(c) for c in ("<", "<=", "!=", "==", ">=", ">", "~=", "===")):
octo_compat = ">={}".format(octo_compat)
spec_matcher = ("<", "<=", "!=", "==", ">=", ">", "~=", "===")
specs = map(lambda x: x if any(x.startswith(c) for c in spec_matcher) else ">={}".format(x),
compatibility_entries)
s = next(pkg_resources.parse_requirements("OctoPrint" + octo_compat))
if octoprint_version in s:
break
except:
self._logger.exception("Something is wrong with this compatibility string for OctoPrint: {}".format(octo_compat))
else:
return False
return True
try:
return version_matches_any_spec(octoprint_version, specs, package="OctoPrint", base=True)
except:
self._logger.exception("Something is wrong with these compatibility specs: {!r}".format(specs))
return False
@staticmethod
def _is_os_compatible(current_os, compatibility_entries):
@@ -864,38 +860,15 @@ class PluginManagerPlugin(octoprint.plugin.SimpleApiPlugin,
else:
return "unmapped"
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)
# A leading v is common in github release tags and old setuptools doesn't remove it. While OctoPrint's
# versions should never contains such a prefix, we'll make sure to have stuff behave the same
# regardless of setuptools version anyhow.
if octoprint_version and isinstance(octoprint_version, tuple) and octoprint_version[0].lower() == "*v":
octoprint_version = octoprint_version[1:]
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)
@staticmethod
def _get_octoprint_version_string():
from octoprint import __version__ as octoprint_version
return octoprint_version
@staticmethod
def _get_octoprint_version(base=False):
return parse_version(PluginManagerPlugin._get_octoprint_version_string(), base=base)
@property
def _reconnect_hooks(self):
reconnect_hooks = self.__class__.RECONNECT_HOOKS
@@ -8,6 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import requests
import logging
from octoprint.util.version import parse_version
RELEASE_URL = "https://api.github.com/repos/{user}/{repo}/releases"
logger = logging.getLogger("octoprint.plugins.softwareupdate.version_checks.github_release")
@@ -139,44 +141,8 @@ def _get_sanitized_version(version_string):
return version_string
def _get_base_from_version_tuple(version_tuple):
"""
Reduces version tuple to base version.
Tests:
>>> _get_base_from_version_tuple(("1", "2", "15"))
('1', '2', '15')
>>> _get_base_from_version_tuple(("1", "2", "15", "*", "dev12"))
('1', '2', '15')
"""
base_version = []
for part in version_tuple:
if part.startswith("*"):
break
base_version.append(part)
return tuple(base_version)
def _get_comparable_version_pkg_resources(version_string, force_base=True):
import pkg_resources
version = pkg_resources.parse_version(version_string)
# A leading v is common in github release tags and old setuptools doesn't remove it.
if version and isinstance(version, tuple) and version[0].lower() == "*v":
version = version[1:]
if force_base:
if isinstance(version, tuple):
# old setuptools
version = _get_base_from_version_tuple(version)
else:
# new setuptools
version = pkg_resources.parse_version(version.base_version)
return version
return parse_version(version_string, base=force_base)
def _get_comparable_version_semantic(version_string, force_base=True):
+189
View File
@@ -0,0 +1,189 @@
# coding=utf-8
from __future__ import absolute_import, unicode_literals
__author__ = "Gina Häußge <gina@octoprint.org>"
__license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html'
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
import pkg_resources
from past.builtins import basestring
def _get_base_from_version_tuple(version_tuple):
"""
Reduces the version tuple to base version.
Example::
>>> _get_base_from_version_tuple((b"1", b"2", b"5"))
('1', '2', '5', '*final')
>>> _get_base_from_version_tuple((b"1", b"2", b"15", b"*", b"dev12"))
('1', '2', '15', '*final')
Args:
version_tuple (tuple): the version tuple to reduce to the base version
Returns:
(tuple): a version tuple reduced to base version
"""
assert len(version_tuple) > 0
base_version = []
for part in version_tuple:
if part.startswith("*"):
break
base_version.append(part)
if base_version and base_version[-1] != b'*final':
base_version.append(b'*final')
return tuple(base_version)
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))
# A leading v is common in github release tags and old setuptools doesn't remove it.
if version and isinstance(version, tuple) and version[0].lower() == "*v":
version = version[1:]
if base:
if isinstance(version, tuple):
# old setuptools
version = _get_base_from_version_tuple(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", base=True)
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)
+5 -1
View File
@@ -480,7 +480,11 @@ def create_plugin_setup_parameters(identifier="todo", name="TODO", version="0.1"
requires = ["OctoPrint"]
if not isinstance(requires, list):
raise ValueError("requires must be a list")
if "OctoPrint" not in requires:
for require in requires:
requirement = pkg_resources.Requirement.parse(require)
if requirement.key == "octoprint":
break
else:
requires = ["OctoPrint"] + list(requires)
if extra_requires is None:
+103
View File
@@ -0,0 +1,103 @@
# 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) 2017 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"),
("v1.1.0", False, "v1.1.0", ("*v", "00000001", "00000001", "00000000", "*final"), ("00000001", "00000001", "00000000", "*final"), "1.1.0"),
("V1.2.0.dev.123", True, "V1.2.0.dev.123", ("*V", "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, method, 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:
method(*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, method(*args, **kwargs))