From 09a043b39355f8fb0d5b219199f2933dbd01a7fd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 26 Feb 2019 13:50:35 +0100 Subject: [PATCH 1/9] =?UTF-8?q?=F0=9F=90=9B=20tracking:=20fix=20handling?= =?UTF-8?q?=20of=20missing=20print=20time?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit See also #3063 --- src/octoprint/plugins/tracking/__init__.py | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/src/octoprint/plugins/tracking/__init__.py b/src/octoprint/plugins/tracking/__init__.py index 93a0fabbd..1aa8d91c6 100644 --- a/src/octoprint/plugins/tracking/__init__.py +++ b/src/octoprint/plugins/tracking/__init__.py @@ -302,15 +302,17 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, track_event = "print_started" elif event == Events.PRINT_DONE: try: - elapsed = int(payload.get(b"time")) - args[b"elapsed"] = elapsed + elapsed = int(payload.get(b"time", 0)) + if elapsed: + args[b"elapsed"] = elapsed except ValueError: pass track_event = "print_done" elif event == Events.PRINT_FAILED: try: - elapsed = int(payload.get(b"time")) - args[b"elapsed"] = elapsed + elapsed = int(payload.get(b"time", 0)) + if elapsed: + args[b"elapsed"] = elapsed except ValueError: pass args[b"reason"] = payload.get(b"reason", "unknown") @@ -321,8 +323,9 @@ class TrackingPlugin(octoprint.plugin.SettingsPlugin, track_event = "print_failed" elif event == Events.PRINT_CANCELLED: try: - elapsed = int(payload.get(b"time")) - args[b"elapsed"] = elapsed + elapsed = int(payload.get(b"time", 0)) + if elapsed: + args[b"elapsed"] = elapsed except ValueError: pass track_event = "print_cancelled" From 253a38c32d3f3cf00744a979147eedc27f144a32 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Tue, 26 Feb 2019 15:31:22 +0100 Subject: [PATCH 2/9] =?UTF-8?q?=E2=99=BB=20gcode=20=3D>=20printables?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/events.py | 2 +- src/octoprint/static/js/app/viewmodels/files.js | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/octoprint/events.py b/src/octoprint/events.py index 30f141f84..a5fe562ba 100644 --- a/src/octoprint/events.py +++ b/src/octoprint/events.py @@ -230,7 +230,7 @@ class EventManager(object): if event == Events.UPDATED_FILES and "type" in payload and payload["type"] == "printables": # when sending UpdatedFiles with type "printables", also send another event with deprecated type "gcode" - # TODO v1.3.0 Remove again + # TODO v1.4.0 Remove again import copy legacy_payload = copy.deepcopy(payload) legacy_payload["type"] = "gcode" diff --git a/src/octoprint/static/js/app/viewmodels/files.js b/src/octoprint/static/js/app/viewmodels/files.js index 88823ba7f..d88ebd778 100644 --- a/src/octoprint/static/js/app/viewmodels/files.js +++ b/src/octoprint/static/js/app/viewmodels/files.js @@ -902,7 +902,7 @@ $(function() { return; } - if (payload.type !== "gcode") { + if (payload.type !== "printables") { return; } From aacd59ae78b21e80c71af7c4559597a7c2d631ea Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 27 Feb 2019 13:43:01 +0100 Subject: [PATCH 3/9] =?UTF-8?q?=E2=98=94=20Log=20exceptions=20while=20pars?= =?UTF-8?q?ing=20the=20AST?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/plugin/core.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index b97a6742d..fff58ef16 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -576,7 +576,7 @@ class PluginInfo(object): break except Exception: - # TODO: really ignore all errors? + self._logger.exception("Error while parsing AST for {}".format(self.key)) pass return result From 334f2c35f932c0e3d42703794406a0f0277ad24d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 27 Feb 2019 14:28:35 +0100 Subject: [PATCH 4/9] =?UTF-8?q?=E2=9C=A8=20Allow=20to=20ignore=20compatibi?= =?UTF-8?q?lity=20for=20plugins?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adding a plugin's identifier to the list plugins._forcedCompatible in config.yaml will make OctoPrint ignore its python compatibility status, e.g. plugins: _forcedCompatible: - myplugin This might be helpful for plugin authors during development but should NOT be used in production! See also #2722 --- docs/configuration/config_yaml.rst | 5 +++++ src/octoprint/__init__.py | 5 ++++- src/octoprint/plugin/__init__.py | 7 +++++-- src/octoprint/plugin/core.py | 12 ++++++++++-- src/octoprint/settings.py | 3 ++- 5 files changed, 26 insertions(+), 6 deletions(-) diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 2266cc0a7..6cab21aac 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -670,6 +670,11 @@ plugins are tracked: _disabled: - ... + # Identifiers of plugins for which python compatibility information will be ignored and + # the plugin considered compatible in any case. Only for development, do NOT use in production. + _forceCompatible: + - ... + # The rest are individual plugin settings, each tracked by their identifier, e.g.: some_plugin: some_setting: true diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 02f7d0c74..356d876ed 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -365,13 +365,16 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti return True plugin_validators.append(validator) + compatibility_ignored_list = settings.get(["plugins", "_forcedCompatible"]) + from octoprint.plugin import plugin_manager pm = plugin_manager(init=True, plugin_folders=plugin_folders, plugin_entry_points=plugin_entry_points, plugin_disabled_list=plugin_disabled_list, plugin_blacklist=plugin_blacklist, - plugin_validators=plugin_validators) + plugin_validators=plugin_validators, + compatibility_ignored_list=compatibility_ignored_list) settings_overlays = dict() disabled_from_overlays = dict() diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index d8be4121e..8adc357de 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -38,7 +38,7 @@ def _validate_plugin(phase, plugin_info): def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_entry_points=None, plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, plugin_obsolete_hooks=None, - plugin_validators=None): + plugin_validators=None, compatibility_ignored_list=None): """ Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` singleton. @@ -64,6 +64,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=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. + compatibility_ignored_list (list): A list of plugin keys for which it will be ignored if they are flagged as + incompatible. This is for development purposes only and should not be used in production. Returns: PluginManager: A fully initialized :class:`~octoprint.plugin.core.PluginManager` instance to be used for plugin @@ -106,7 +108,8 @@ def plugin_manager(init=False, plugin_folders=None, plugin_bases=None, plugin_en plugin_blacklist=plugin_blacklist, plugin_restart_needing_hooks=plugin_restart_needing_hooks, plugin_obsolete_hooks=plugin_obsolete_hooks, - plugin_validators=plugin_validators) + plugin_validators=plugin_validators, + compatibility_ignored_list=compatibility_ignored_list) else: raise ValueError("Plugin Manager not initialized yet") return _instance diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index fff58ef16..c0a301d07 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -592,7 +592,7 @@ class PluginManager(object): def __init__(self, plugin_folders, plugin_bases, plugin_entry_points, logging_prefix=None, plugin_disabled_list=None, plugin_blacklist=None, plugin_restart_needing_hooks=None, - plugin_obsolete_hooks=None, plugin_validators=None): + plugin_obsolete_hooks=None, plugin_validators=None, compatibility_ignored_list=None): self.logger = logging.getLogger(__name__) if logging_prefix is None: @@ -607,6 +607,8 @@ class PluginManager(object): plugin_disabled_list = [] if plugin_blacklist is None: plugin_blacklist = [] + if compatibility_ignored_list is None: + compatibility_ignored_list = [] self.plugin_folders = plugin_folders self.plugin_bases = plugin_bases @@ -617,6 +619,7 @@ class PluginManager(object): self.plugin_obsolete_hooks = plugin_obsolete_hooks self.plugin_validators = plugin_validators self.logging_prefix = logging_prefix + self.compatibility_ignored_list = compatibility_ignored_list self.enabled_plugins = dict() self.disabled_plugins = dict() @@ -875,7 +878,7 @@ class PluginManager(object): plugin.blacklisted = True python_version = get_python_version_string() - if not is_python_compatible(plugin.pythoncompat) and not plugin.bundled: + if self._is_plugin_incompatible(key, plugin): self.logger.warning("Plugin {} is not compatible to Python {} (compatibility string: {}).".format(plugin, python_version, plugin.pythoncompat)) plugin.incompatible = True @@ -918,6 +921,11 @@ class PluginManager(object): def _is_plugin_blacklisted(self, key): return key in self.plugin_blacklist + def _is_plugin_incompatible(self, key, plugin): + return not plugin.bundled \ + and not is_python_compatible(plugin.pythoncompat) \ + and key not in self.compatibility_ignored_list + def _is_plugin_version_blacklisted(self, key, version): def matches_plugin(entry): if isinstance(entry, (tuple, list)) and len(entry) == 2: diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py index d25fccb99..4b42668ed 100644 --- a/src/octoprint/settings.py +++ b/src/octoprint/settings.py @@ -367,7 +367,8 @@ default_settings = { { "name": "Suppress wait responses", "regex": "Recv: wait"} ], "plugins": { - "_disabled": [] + "_disabled": [], + "_forcedCompatible": [] }, "scripts": { "gcode": { From dde99736e40dda8a01dc112971ef9ce72caca8b0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 27 Feb 2019 14:32:37 +0100 Subject: [PATCH 5/9] =?UTF-8?q?=F0=9F=93=9D=20Fix=20an=20error=20in=20the?= =?UTF-8?q?=20docs?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- docs/configuration/config_yaml.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/configuration/config_yaml.rst b/docs/configuration/config_yaml.rst index 6cab21aac..59cdbbd35 100644 --- a/docs/configuration/config_yaml.rst +++ b/docs/configuration/config_yaml.rst @@ -672,7 +672,7 @@ plugins are tracked: # Identifiers of plugins for which python compatibility information will be ignored and # the plugin considered compatible in any case. Only for development, do NOT use in production. - _forceCompatible: + _forcedCompatible: - ... # The rest are individual plugin settings, each tracked by their identifier, e.g.: From 1ed67304001c4976acc931587d912c9aa05abf01 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Wed, 27 Feb 2019 16:11:00 +0100 Subject: [PATCH 6/9] =?UTF-8?q?=F0=9F=94=8A=20Improved=20logging=20in=20ca?= =?UTF-8?q?se=20of=20plugin=20syntax=20errors?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/plugin/core.py | 20 +++++++++++++------- 1 file changed, 13 insertions(+), 7 deletions(-) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index c0a301d07..d23433160 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -166,6 +166,7 @@ class PluginInfo(object): self.loaded = False self.managable = True self.needs_restart = False + self.invalid_syntax = False self._name = name self._version = version @@ -177,12 +178,14 @@ class PluginInfo(object): self._logger = logging.getLogger(__name__) self._cached_parsed_metadata = parsed_metadata + if self._cached_parsed_metadata is None: + self._cached_parsed_metadata = self._parse_metadata() def validate(self, phase, additional_validators=None): result = True if phase == "before_import": - result = not self.forced_disabled and not self.blacklisted and not self.incompatible and result + result = not self.forced_disabled and not self.blacklisted and not self.incompatible and not self.invalid_syntax and result elif phase == "before_load": # if the plugin still uses __plugin_init__, log a deprecation warning and move it to __plugin_load__ @@ -524,8 +527,6 @@ class PluginInfo(object): @property def parsed_metadata(self): - if self._cached_parsed_metadata is None: - self._cached_parsed_metadata = self._parse_metadata() return self._cached_parsed_metadata def _parse_metadata(self): @@ -551,7 +552,7 @@ class PluginInfo(object): import ast with io.open(path, 'rb') as f: - root = ast.parse(f.read()) + root = ast.parse(f.read(), filename=path) assignments = list(filter(lambda x: isinstance(x, ast.Assign) and x.targets, root.body)) @@ -575,9 +576,11 @@ class PluginInfo(object): result[key] = a.value.args[0].s break + except SyntaxError: + self._logger.exception("Invalid syntax in {} for plugin {}".format(path, self.key)) + self.invalid_syntax = True except Exception: - self._logger.exception("Error while parsing AST for {}".format(self.key)) - pass + self._logger.exception("Error while parsing AST from {} for plugin {}".format(path, self.key)) return result @@ -879,7 +882,10 @@ class PluginManager(object): python_version = get_python_version_string() if self._is_plugin_incompatible(key, plugin): - self.logger.warning("Plugin {} is not compatible to Python {} (compatibility string: {}).".format(plugin, python_version, plugin.pythoncompat)) + if plugin.invalid_syntax: + self.logger.warning("Plugin {} can't be compiled under Python {} due to invalid syntax".format(plugin, python_version)) + else: + self.logger.warning("Plugin {} is not compatible to Python {} (compatibility string: {}).".format(plugin, python_version, plugin.pythoncompat)) plugin.incompatible = True if not plugin.validate("before_import", additional_validators=self.plugin_validators): From 1b3a8acf0d1db649c4f6a0da6e18b57ed858a4f0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 28 Feb 2019 16:07:07 +0100 Subject: [PATCH 7/9] =?UTF-8?q?=E2=99=BB=20Work=20around=20deprecation=20o?= =?UTF-8?q?f=20imp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit After two days of trying to make the plugin loading work completely, including loading bundled templates etc, using only native importlib methods, I've finally given up and bundled the (deprecated) imp module for Python 3+ which relies on importlib but does some magic I've yet to figure out which makes stuff just work. Replacing imp completely with something more slim is something for another day, for now we want to get stuff to work under Py3 with as little warnings as possible. --- src/octoprint/plugin/core.py | 52 ++++-- src/octoprint/vendor/imp.py | 331 +++++++++++++++++++++++++++++++++++ 2 files changed, 370 insertions(+), 13 deletions(-) create mode 100644 src/octoprint/vendor/imp.py diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index d23433160..f9a43b2c7 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -22,18 +22,17 @@ way and could be extracted into a separate Python module in the future. """ -__author__ = "Gina Häußge " __license__ = 'GNU Affero General Public License http://www.gnu.org/licenses/agpl.html' __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License" import os import io -import imp from collections import defaultdict, namedtuple, OrderedDict import logging import fnmatch import inspect +import sys import pkg_resources import pkginfo @@ -48,6 +47,30 @@ try: except ImportError: from scandir import scandir + +if sys.version_info[0] == 2: + # noinspection PyDeprecation + import imp +else: + # deprecated in Python 3.4+ and hence vendored for now + import octoprint.vendor.imp as imp + + +# noinspection PyDeprecation +def _find_module(name, path=None): + if path is not None: + spec = imp.find_module(name, [path]) + else: + spec = imp.find_module(name) + return spec[1], spec + + +# noinspection PyDeprecation +def _load_module(name, spec): + f, filename, details = spec + return imp.load_module(name, f, filename, details) + + EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version") FolderOrigin = namedtuple("FolderOrigin", "type, folder") @@ -858,17 +881,17 @@ class PluginManager(object): # TODO error handling try: if folder: - module = imp.find_module(key, [folder]) + location, spec = _find_module(key, path=folder) elif module_name: - module = imp.find_module(module_name) + location, spec = _find_module(module_name) else: return None except Exception: - self.logger.warn("Could not locate plugin {key}".format(key=key)) + self.logger.exception("Could not locate plugin {key}".format(key=key)) return None # Create a simple dummy entry first ... - plugin = PluginInfo(key, module[1], None, name=name, version=version, description=summary, author=author, + plugin = PluginInfo(key, location, None, name=name, version=version, description=summary, author=author, url=url, license=license) plugin.bundled = bundled @@ -892,17 +915,19 @@ class PluginManager(object): return plugin # ... then create and return the real one - return self._import_plugin(key, *module, - module_name=module_name, name=name, version=version, summary=summary, author=author, url=url, - license=license, bundled=bundled, parsed_metadata=plugin.parsed_metadata) + return self._import_plugin(key, spec, + module_name=module_name, name=name, location=plugin.location, version=version, + summary=summary, author=author, url=url, license=license, bundled=bundled, + parsed_metadata=plugin.parsed_metadata) - def _import_plugin(self, key, f, filename, description, module_name=None, name=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None): + def _import_plugin(self, key, spec, module_name=None, name=None, location=None, version=None, summary=None, author=None, url=None, license=None, bundled=False, parsed_metadata=None): try: if module_name: - instance = imp.load_module(module_name, f, filename, description) + module = _load_module(module_name, spec) else: - instance = imp.load_module(key, f, filename, description) - plugin = PluginInfo(key, filename, instance, + module = _load_module(key, spec) + + plugin = PluginInfo(key, location, module, name=name, version=version, description=summary, @@ -910,6 +935,7 @@ class PluginManager(object): url=url, license=license, parsed_metadata=parsed_metadata) + plugin.bundled = bundled except Exception: self.logger.exception("Error loading plugin {key}".format(key=key)) diff --git a/src/octoprint/vendor/imp.py b/src/octoprint/vendor/imp.py new file mode 100644 index 000000000..921445ce4 --- /dev/null +++ b/src/octoprint/vendor/imp.py @@ -0,0 +1,331 @@ +"""This module provides the components needed to build your own __import__ +function. Undocumented functions are obsolete. + +In most cases it is preferred you consider using the importlib module's +functionality over this module. + +Taken from CPython 3.7.0 and vendored to still have it when it gets +completely removed. + +Licensed under the PSF LICENSE AGREEMENT +""" + +import sys +assert sys.version_info[0] == 3 and sys.version_info[1] >= 5 # this only works on Python 3.5+ + +# (Probably) need to stay in _imp +# noinspection PyCompatibility +from _imp import (lock_held, acquire_lock, release_lock, + get_frozen_object, is_frozen_package, + init_frozen, is_builtin, is_frozen, + _fix_co_filename) +try: + # noinspection PyCompatibility + from _imp import create_dynamic +except ImportError: + # Platform doesn't support dynamic loading. + create_dynamic = None + +# noinspection PyCompatibility,PyProtectedMember +from importlib._bootstrap import _ERR_MSG, _exec, _load, _builtin_from_name + +# noinspection PyCompatibility,PyProtectedMember +from importlib._bootstrap_external import SourcelessFileLoader + +# noinspection PyCompatibility +from importlib import machinery +# noinspection PyCompatibility +from importlib import util +import importlib +import os +import sys +import tokenize +import types +import warnings + +SEARCH_ERROR = 0 +PY_SOURCE = 1 +PY_COMPILED = 2 +C_EXTENSION = 3 +PY_RESOURCE = 4 +PKG_DIRECTORY = 5 +C_BUILTIN = 6 +PY_FROZEN = 7 +PY_CODERESOURCE = 8 +IMP_HOOK = 9 + + +def new_module(name): + """Create a new module. + + The module is not entered into sys.modules. + + """ + # noinspection PyUnresolvedReferences + return types.ModuleType(name) + + +def get_magic(): + """Return the magic number for .pyc files. + """ + return util.MAGIC_NUMBER + + +def get_tag(): + """Return the magic tag for .pyc files.""" + return sys.implementation.cache_tag + + +def cache_from_source(path, debug_override=None): + """Given the path to a .py file, return the path to its .pyc file. + + The .py file does not need to exist; this simply returns the path to the + .pyc file calculated as if the .py file were imported. + + If debug_override is not None, then it must be a boolean and is used in + place of sys.flags.optimize. + + If sys.implementation.cache_tag is None then NotImplementedError is raised. + + """ + with warnings.catch_warnings(): + warnings.simplefilter('ignore') + return util.cache_from_source(path, debug_override) + + +def source_from_cache(path): + """Given the path to a .pyc. file, return the path to its .py file. + + The .pyc file does not need to exist; this simply returns the path to + the .py file calculated to correspond to the .pyc file. If path does + not conform to PEP 3147 format, ValueError will be raised. If + sys.implementation.cache_tag is None then NotImplementedError is raised. + + """ + return util.source_from_cache(path) + + +def get_suffixes(): + extensions = [(s, 'rb', C_EXTENSION) for s in machinery.EXTENSION_SUFFIXES] + source = [(s, 'r', PY_SOURCE) for s in machinery.SOURCE_SUFFIXES] + bytecode = [(s, 'rb', PY_COMPILED) for s in machinery.BYTECODE_SUFFIXES] + + return extensions + source + bytecode + + +class NullImporter: + + """Null import object.""" + + def __init__(self, path): + if path == '': + raise ImportError('empty pathname', path='') + elif os.path.isdir(path): + raise ImportError('existing directory', path=path) + + def find_module(self, fullname): + """Always returns None.""" + return None + + +# noinspection PyCompatibility,PyUnresolvedReferences +class _HackedGetData: + + """Compatibility support for 'file' arguments of various load_*() + functions.""" + + def __init__(self, fullname, path, file=None): + super().__init__(fullname, path) + self.file = file + + def get_data(self, path): + """Gross hack to contort loader to deal w/ load_*()'s bad API.""" + if self.file and path == self.path: + if not self.file.closed: + file = self.file + else: + self.file = file = open(self.path, 'r') + + with file: + # Technically should be returning bytes, but + # SourceLoader.get_code() just passed what is returned to + # compile() which can handle str. And converting to bytes would + # require figuring out the encoding to decode to and + # tokenize.detect_encoding() only accepts bytes. + return file.read() + else: + return super().get_data(path) + + +class _LoadSourceCompatibility(_HackedGetData, machinery.SourceFileLoader): + + """Compatibility support for implementing load_source().""" + + +def load_source(name, pathname, file=None): + loader = _LoadSourceCompatibility(name, pathname, file) + spec = util.spec_from_file_location(name, pathname, loader=loader) + if name in sys.modules: + module = _exec(spec, sys.modules[name]) + else: + module = _load(spec) + # To allow reloading to potentially work, use a non-hacked loader which + # won't rely on a now-closed file object. + module.__loader__ = machinery.SourceFileLoader(name, pathname) + module.__spec__.loader = module.__loader__ + return module + + +class _LoadCompiledCompatibility(_HackedGetData, SourcelessFileLoader): + + """Compatibility support for implementing load_compiled().""" + + +def load_compiled(name, pathname, file=None): + """**DEPRECATED**""" + loader = _LoadCompiledCompatibility(name, pathname, file) + spec = util.spec_from_file_location(name, pathname, loader=loader) + if name in sys.modules: + module = _exec(spec, sys.modules[name]) + else: + module = _load(spec) + # To allow reloading to potentially work, use a non-hacked loader which + # won't rely on a now-closed file object. + module.__loader__ = SourcelessFileLoader(name, pathname) + module.__spec__.loader = module.__loader__ + return module + + +def load_package(name, path): + if os.path.isdir(path): + extensions = (machinery.SOURCE_SUFFIXES[:] + + machinery.BYTECODE_SUFFIXES[:]) + for extension in extensions: + init_path = os.path.join(path, '__init__' + extension) + if os.path.exists(init_path): + path = init_path + break + else: + raise ValueError('{!r} is not a package'.format(path)) + spec = util.spec_from_file_location(name, path, + submodule_search_locations=[]) + if name in sys.modules: + return _exec(spec, sys.modules[name]) + else: + return _load(spec) + + +def load_module(name, file, filename, details): + """Load a module, given information returned by find_module(). + + The module name must include the full package name, if any. + + """ + suffix, mode, type_ = details + if mode and (not mode.startswith(('r', 'U')) or '+' in mode): + raise ValueError('invalid file open mode {!r}'.format(mode)) + elif file is None and type_ in {PY_SOURCE, PY_COMPILED}: + msg = 'file object required for import (type code {})'.format(type_) + raise ValueError(msg) + elif type_ == PY_SOURCE: + return load_source(name, filename, file) + elif type_ == PY_COMPILED: + return load_compiled(name, filename, file) + elif type_ == C_EXTENSION and load_dynamic is not None: + if file is None: + with open(filename, 'rb') as opened_file: + return load_dynamic(name, filename, opened_file) + else: + return load_dynamic(name, filename, file) + elif type_ == PKG_DIRECTORY: + return load_package(name, filename) + elif type_ == C_BUILTIN: + return init_builtin(name) + elif type_ == PY_FROZEN: + return init_frozen(name) + else: + msg = "Don't know how to import {} (type code {})".format(name, type_) + raise ImportError(msg, name=name) + + +def find_module(name, path=None): + """Search for a module. + + If path is omitted or None, search for a built-in, frozen or special + module and continue search in sys.path. The module name cannot + contain '.'; to search for a submodule of a package, pass the + submodule name and the package's __path__. + + """ + if not isinstance(name, str): + raise TypeError("'name' must be a str, not {}".format(type(name))) + elif not isinstance(path, (type(None), list)): + # Backwards-compatibility + raise RuntimeError("'path' must be None or a list, " + "not {}".format(type(path))) + + if path is None: + if is_builtin(name): + return None, None, ('', '', C_BUILTIN) + elif is_frozen(name): + return None, None, ('', '', PY_FROZEN) + else: + path = sys.path + + for entry in path: + package_directory = os.path.join(entry, name) + for suffix in ['.py', machinery.BYTECODE_SUFFIXES[0]]: + package_file_name = '__init__' + suffix + file_path = os.path.join(package_directory, package_file_name) + if os.path.isfile(file_path): + return None, package_directory, ('', '', PKG_DIRECTORY) + for suffix, mode, type_ in get_suffixes(): + file_name = name + suffix + file_path = os.path.join(entry, file_name) + if os.path.isfile(file_path): + break + else: + continue + break # Break out of outer loop when breaking out of inner loop. + else: + raise ImportError(_ERR_MSG.format(name), name=name) + + encoding = None + if 'b' not in mode: + with open(file_path, 'rb') as file: + encoding = tokenize.detect_encoding(file.readline)[0] + file = open(file_path, mode, encoding=encoding) + return file, file_path, (suffix, mode, type_) + + +def reload(module): + """Reload the module and return it. + + The module must have been successfully imported before. + + """ + return importlib.reload(module) + + +def init_builtin(name): + """Load and return a built-in module by name, or None is such module doesn't exist""" + try: + return _builtin_from_name(name) + except ImportError: + return None + + +if create_dynamic: + def load_dynamic(name, path, file=None): + """Load an extension module.""" + import importlib.machinery + loader = importlib.machinery.ExtensionFileLoader(name, path) + + # Issue #24748: Skip the sys.modules check in _load_module_shim; + # always load new extension + spec = importlib.machinery.ModuleSpec( + name=name, loader=loader, origin=path) + return _load(spec) + +else: + load_dynamic = None From 0f157d37478918afefa3432c0db0cd177ac0988a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 28 Feb 2019 16:37:09 +0100 Subject: [PATCH 8/9] =?UTF-8?q?=E2=99=BB=20Load=20bundled=20plugins=20unde?= =?UTF-8?q?r=20octoprint.plugins.*?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Makes more sense than putting them into sys.modules as , which also can cause conflicts (e.g. in the case of octoprint.plugins .logging which then suddenly gets found instead of the built-in crucial logging module). --- src/octoprint/__init__.py | 5 ++++- src/octoprint/plugin/core.py | 15 +++++++++++++-- src/octoprint/plugins/__init__.py | 3 ++- 3 files changed, 19 insertions(+), 4 deletions(-) diff --git a/src/octoprint/__init__.py b/src/octoprint/__init__.py index 73a994f49..0776420b8 100644 --- a/src/octoprint/__init__.py +++ b/src/octoprint/__init__.py @@ -343,9 +343,12 @@ def init_pluginsystem(settings, safe_mode=False, ignore_blacklist=True, connecti import os + # we need this so that octoprint.plugins is in sys.modules and no warnings are caused when loading bundled plugins + import octoprint.plugins + logger = log.getLogger(__name__ + ".startup") - plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), True), + plugin_folders = [(os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), "plugins")), "octoprint.plugins", True), settings.getBaseFolder("plugins")] plugin_entry_points = ["octoprint.plugin"] plugin_disabled_list = settings.get(["plugins", "_disabled"]) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index d605ebb16..a269c9dc4 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -48,6 +48,7 @@ except ImportError: EntryPointOrigin = namedtuple("EntryPointOrigin", "type, entry_point, module_name, package_name, package_version") FolderOrigin = namedtuple("FolderOrigin", "type, folder") +ModuleOrigin = namedtuple("PackageOrigin", "type, module_name, folder") class PluginInfo(object): """ @@ -678,9 +679,12 @@ class PluginManager(object): for folder in folders: try: flagged_readonly = False + package = None if isinstance(folder, (list, tuple)): if len(folder) == 2: folder, flagged_readonly = folder + elif len(folder) == 3: + folder, package, flagged_readonly = folder else: continue actual_readonly = not os.access(folder, os.W_OK) @@ -718,9 +722,16 @@ class PluginManager(object): bundled = flagged_readonly - plugin = self._import_plugin_from_module(key, folder=folder, bundled=bundled) + module_name = None + if package: + module_name = "{}.{}".format(package, key) + + plugin = self._import_plugin_from_module(key, module_name=module_name, folder=folder, bundled=bundled) if plugin: - plugin.origin = FolderOrigin("folder", folder) + if module_name: + plugin.origin = ModuleOrigin("module", module_name, folder) + else: + plugin.origin = FolderOrigin("folder", folder) plugin.managable = not flagged_readonly and not actual_readonly plugin.enabled = False added[key] = plugin diff --git a/src/octoprint/plugins/__init__.py b/src/octoprint/plugins/__init__.py index 1b0510c60..092cd3e34 100644 --- a/src/octoprint/plugins/__init__.py +++ b/src/octoprint/plugins/__init__.py @@ -1 +1,2 @@ -# make our plugins testable +# -*- coding: utf-8 -*- +from __future__ import absolute_import, division, print_function, unicode_literals From cf16392e180946849aecc3745fb03d89113f0b49 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 28 Feb 2019 17:05:13 +0100 Subject: [PATCH 9/9] =?UTF-8?q?=F0=9F=92=9A=20Ignore=20vendor=20path=20for?= =?UTF-8?q?=20tests=20&=20fix=202.7=20tests?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pytest.ini | 1 + 1 file changed, 1 insertion(+) diff --git a/pytest.ini b/pytest.ini index b6cad3962..597e09bdb 100644 --- a/pytest.ini +++ b/pytest.ini @@ -2,3 +2,4 @@ testpaths = src tests addopts = --doctest-modules --doctest-repr=octoprint.util:pp + --ignore=src/octoprint/vendor