From 8b2f915cacd540d87ce16802cd479dff1599a443 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gina=20H=C3=A4u=C3=9Fge?= Date: Thu, 13 Jul 2023 17:12:58 +0200 Subject: [PATCH] =?UTF-8?q?=F0=9F=9A=A7=20Migration=20to=20mkdocs=20&=20mk?= =?UTF-8?q?docstrings?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/octoprint/access/groups.py | 2 +- src/octoprint/access/permissions.py | 10 +- src/octoprint/cli/__init__.py | 26 +- src/octoprint/cli/dev.py | 12 +- src/octoprint/cli/plugins.py | 17 +- src/octoprint/cli/server.py | 6 +- src/octoprint/filemanager/analysis.py | 158 ++-- src/octoprint/filemanager/destinations.py | 2 + src/octoprint/filemanager/storage.py | 510 +++++++----- src/octoprint/logging/__init__.py | 38 +- src/octoprint/plugin/__init__.py | 624 ++++++++------- src/octoprint/plugin/core.py | 728 ++++++++++++------ src/octoprint/schema/__init__.py | 7 + src/octoprint/schema/config/appearance.py | 17 +- src/octoprint/schema/config/controls.py | 10 +- src/octoprint/schema/config/devel.py | 11 +- src/octoprint/schema/config/events.py | 10 +- src/octoprint/schema/config/gcode_analysis.py | 12 +- src/octoprint/schema/config/serial.py | 21 +- src/octoprint/schema/config/server.py | 11 +- src/octoprint/schema/config/webcam.py | 11 +- src/octoprint/schema/webcam/__init__.py | 10 +- src/octoprint/util/__init__.py | 2 + 23 files changed, 1322 insertions(+), 933 deletions(-) diff --git a/src/octoprint/access/groups.py b/src/octoprint/access/groups.py index 9265798e0..752c3e6ff 100644 --- a/src/octoprint/access/groups.py +++ b/src/octoprint/access/groups.py @@ -13,7 +13,7 @@ from octoprint.util import atomic_write, yaml from octoprint.vendor.flask_principal import Need, Permission GroupNeed = partial(Need, "group") -GroupNeed.__doc__ = """A need with the method preset to `"group"`.""" +GroupNeed.__doc__ = """A need with the method preset to `group`.""" class GroupPermission(Permission): diff --git a/src/octoprint/access/permissions.py b/src/octoprint/access/permissions.py index 91b3fa7bb..8f3b2bf01 100644 --- a/src/octoprint/access/permissions.py +++ b/src/octoprint/access/permissions.py @@ -80,7 +80,8 @@ class OctoPrintPermission(Permission): Overridden from Permission.allows to make sure the Identity provides ALL required needs instead of ANY required need. - :param identity: The identity + Arguments: + identity (octoprint.vendor.flask_principal.Identity): The identity to check """ if self.needs and len(self.needs.intersection(identity.provides)) != len( self.needs @@ -96,7 +97,8 @@ class OctoPrintPermission(Permission): """Create a new OctoPrintPermission with the requirements of the union of this and other. - :param other: The other permission + Arguments: + other (OctoPrintPermission): The other permission """ p = self.__class__(self._name, self._description, *self.needs.union(other.needs)) p.excludes.update(self.excludes.union(other.excludes)) @@ -144,7 +146,7 @@ class PluginOctoPrintPermission(OctoPrintPermission): class PluginIdentityContext: """Identity context for not initialized Permissions - Needed to support @Permissions.PLUGIN_X_Y.require() + Needed to support `@Permissions.PLUGIN_X_Y.require()` Will search the permission when needed """ @@ -195,7 +197,7 @@ class PluginIdentityContext: class PluginPermissionDecorator(Permission): """Decorator Class for not initialized Permissions - Needed to support @Permissions.PLUGIN_X_Y.require() + Needed to support `@Permissions.PLUGIN_X_Y.require()` """ def __init__(self, key): diff --git a/src/octoprint/cli/__init__.py b/src/octoprint/cli/__init__.py index b08415610..6f5ff5da1 100644 --- a/src/octoprint/cli/__init__.py +++ b/src/octoprint/cli/__init__.py @@ -38,15 +38,15 @@ def init_platform_for_cli(ctx): Plugin implementations will be initialized, but only with a subset of the usual property injections: - * _identifier and everything else parsed from metadata - * _logger - * _connectivity_checker - * _environment_detector - * _event_bus - * _plugin_manager - * _settings + - `_identifier` and everything else parsed from metadata + - `_logger` + - `_connectivity_checker` + - `_environment_detector` + - `_event_bus` + - `_plugin_manager` + - `_settings` - Returns: the same list of components as returned by ``init_platform`` + Returns: the same list of components as returned by `init_platform` """ from octoprint import ( @@ -112,10 +112,10 @@ class HiddenOption(click.Option): def hidden_option(*param_decls, **attrs): """Attaches a hidden option to the command. All positional arguments are - passed as parameter declarations to :class:`Option`; all keyword + passed as parameter declarations to [Option][click.Option]; all keyword arguments are forwarded unchanged. This is equivalent to creating an - :class:`Option` instance manually and attaching it to the - :attr:`Command.params` list. + [Option][click.Option] instance manually and attaching it to the + [Command.params][click.Command.params] list. """ import inspect @@ -162,7 +162,7 @@ def bulk_options(options): """ Utility decorator to decorate a function with a list of click decorators. - The provided list of ``options`` will be reversed to ensure correct + The provided list of `options` will be reversed to ensure correct processing order (inverse from what would be intuitive). """ @@ -182,7 +182,7 @@ def standard_options(hidden=False): """ Decorator to add the standard options shared among all "octoprint" commands. - If ``hidden`` is set to ``True``, the options will be available on the command but not + If `hidden` is set to `True`, the options will be available on the command but not listed in its help page. """ diff --git a/src/octoprint/cli/dev.py b/src/octoprint/cli/dev.py index b119f2abd..13e086ad7 100644 --- a/src/octoprint/cli/dev.py +++ b/src/octoprint/cli/dev.py @@ -11,7 +11,7 @@ click.disable_unicode_literals_warning = True class OctoPrintDevelCommands(click.MultiCommand): """ - Custom `click.MultiCommand `_ + Custom [click.MultiCommand][] implementation that provides commands relevant for (plugin) development based on availability of development dependencies. """ @@ -208,10 +208,12 @@ class OctoPrintDevelCommands(click.MultiCommand): """ Installs the local plugin in development mode. - Note: This can NOT be used to install plugins from remote locations - such as the plugin repository! It is strictly for local development - of plugins, to ensure the plugin is installed (editable) into the - same python environment that OctoPrint is installed under. + !!! note: + + This can NOT be used to install plugins from remote locations + such as the plugin repository! It is strictly for local development + of plugins, to ensure the plugin is installed (editable) into the + same python environment that OctoPrint is installed under. """ import os diff --git a/src/octoprint/cli/plugins.py b/src/octoprint/cli/plugins.py index a19e174c5..c7d6584df 100644 --- a/src/octoprint/cli/plugins.py +++ b/src/octoprint/cli/plugins.py @@ -30,17 +30,14 @@ LOGGING_CONFIG = { class OctoPrintPluginCommands(click.MultiCommand): """ - Custom `click.MultiCommand `_ - implementation that collects commands from the plugin hook - :ref:`octoprint.cli.commands `. + Custom [click.MultiCommand][] implementation that collects commands from the plugin hook + [octoprint.cli.commands][plugin-guide.concepts.hooks.octoprint.cli.commands]. - .. attribute:: settings - - The global :class:`~octoprint.settings.Settings` instance. - - .. attribute:: plugin_manager - - The :class:`~octoprint.plugin.core.PluginManager` instance. + Attributes: + settings (octoprint.settings.Settings): The global [Settings][octoprint.settings.Settings] + instance. + plugin_manager (octoprint.plugin.core.PluginManager): The global [PluginManager][octoprint.plugin.core.PluginManager] + instance. """ sep = ":" diff --git a/src/octoprint/cli/server.py b/src/octoprint/cli/server.py index 0a234eace..a296d8daf 100644 --- a/src/octoprint/cli/server.py +++ b/src/octoprint/cli/server.py @@ -230,8 +230,8 @@ server_options = bulk_options( ), ] ) -"""Decorator to add the options shared among the server commands: ``--host``, ``--port``, ``-4``, ``-6`` - ``--logging``, ``--iknowwhatimdoing`` and ``--debug``.""" +"""Decorator to add the options shared among the server commands: `--host`, `--port`, `-4`, `-6` + `--logging`, `--iknowwhatimdoing` and `--debug`.""" daemon_options = bulk_options( [ @@ -244,7 +244,7 @@ daemon_options = bulk_options( ) ] ) -"""Decorator to add the options for the daemon subcommand: ``--pid``.""" +"""Decorator to add the options for the daemon subcommand: `--pid`.""" # ~~ "octoprint serve" and "octoprint daemon" commands diff --git a/src/octoprint/filemanager/analysis.py b/src/octoprint/filemanager/analysis.py index 6eea16c47..c26fb2df7 100644 --- a/src/octoprint/filemanager/analysis.py +++ b/src/octoprint/filemanager/analysis.py @@ -48,18 +48,18 @@ class QueueEntry( ) ): """ - A :class:`QueueEntry` for processing through the :class:`AnalysisQueue`. Wraps the entry's properties necessary + A `QueueEntry` for processing through the [AnalysisQueue][octoprint.filemanager.analysis.AnalysisQueue]. Wraps the entry's properties necessary for processing. Arguments: name (str): Name of the file to analyze. path (str): Storage location specific path to the file to analyze. - type (str): Type of file to analyze, necessary to map to the correct :class:`AbstractAnalysisQueue` sub class. - At the moment, only ``gcode`` is supported here. + type (str): Type of file to analyze, necessary to map to the correct [AbstractAnalysisQueue][octoprint.filemanager.analysis.AbstractAnalysisQueue] sub class. + At the moment, only `gcode` is supported here. location (str): Location the file is located on. absolute_path (str): Absolute path on disk through which to access the file. - printer_profile (PrinterProfile): :class:`PrinterProfile` which to use for analysis. - analysis (dict): :class:`GcodeAnalysisQueue` results from prior analysis, or ``None`` if there is none. + printer_profile (octoprint.printer.profile.PrinterProfile): [PrinterProfile][octoprint.printer.profile.PrinterProfile] which to use for analysis. + analysis (dict): [GcodeAnalysisQueue][octoprint.filemanager.analysis.GcodeAnalysisQueue] results from prior analysis, or `None` if there is none. """ def __str__(self): @@ -74,17 +74,21 @@ class AnalysisAborted(Exception): class AnalysisQueue: """ - OctoPrint's :class:`AnalysisQueue` can manage various :class:`AbstractAnalysisQueue` implementations, mapped - by their machine code type. + OctoPrint's `AnalysisQueue` can manage various [AbstractAnalysisQueue][octoprint.filemanager.analysis.AbstractAnalysisQueue] + implementations, mapped by their machine code type. - By invoking :meth:`register_finish_callback` it is possible to register oneself as a callback to be invoked each - time the analysis of a queue entry finishes. The call parameters will be the finished queue entry as the first - and the analysis result as the second parameter. It is also possible to remove the registration again by invoking - :meth:`unregister_finish_callback`. + By invoking [register_finish_callback][octoprint.filemanager.analysis.AnalysisQueue.register_finish_callback] + it is possible to register oneself as a callback to be invoked each time the analysis + of a queue entry finishes. The call parameters will be the finished queue entry as + the first and the analysis result as the second parameter. It is also possible to + remove the registration again by invoking [unregister_finish_callback][octoprint.filemanager.analysis.AnalysisQueue.unregister_finish_callback]. - :meth:`enqueue` allows enqueuing :class:`QueueEntry` instances to analyze. If the :attr:`QueueEntry.type` is unknown - (no specific child class of :class:`AbstractAnalysisQueue` is registered for it), nothing will happen. Otherwise the - entry will be enqueued with the type specific analysis queue. + [enqueue][octoprint.filemanager.analysis.AnalysisQueue.enqueue] allows enqueuing + [QueueEntry][octoprint.filemanager.analysis.QueueEntry] instances to analyze. If the + [QueueEntry.type][octoprint.filemanager.analysis.QueueEntry.type] is unknown (no + specific child class of [AbstractAnalysisQueue][octoprint.filemanager.analysis.AbstractAnalysisQueue] + is registered for it), nothing will happen. Otherwise the entry will be enqueued + with the type specific analysis queue. """ def __init__(self, queue_factories): @@ -154,18 +158,10 @@ class AnalysisQueue: class AbstractAnalysisQueue: """ - The :class:`AbstractAnalysisQueue` is the parent class of all specific analysis queues such as the - :class:`GcodeAnalysisQueue`. It offers methods to enqueue new entries to analyze and pausing and resuming analysis + The `AbstractAnalysisQueue` is the parent class of all specific analysis queues such + as the [GcodeAnalysisQueue][octoprint.filemanager.analysis.GcodeAnalysisQueue]. It + offers methods to enqueue new entries to analyze and pausing and resuming analysis processing. - - Arguments: - finished_callback (callable): Callback that will be called upon finishing analysis of an entry in the queue. - The callback will be called with the analyzed entry as the first argument and the analysis result as - returned from the queue implementation as the second parameter. - - .. automethod:: _do_analysis - - .. automethod:: _do_abort """ LOW_PRIO = 100 @@ -174,6 +170,16 @@ class AbstractAnalysisQueue: HIGH_PRIO_ABORTED = 0 def __init__(self, finished_callback): + """ + Initializes the queue. + + Arguments: + finished_callback (callable): Callback that will be called upon finishing + analysis of an entry in the queue. The callback will be called with the + analyzed entry as the first argument and the analysis result as returned + from the queue implementation as the second parameter. + + """ self._logger = logging.getLogger(__name__) self._finished_callback = finished_callback @@ -197,15 +203,15 @@ class AbstractAnalysisQueue: def enqueue(self, entry, high_priority=False): """ - Enqueues an ``entry`` for analysis by the queue. + Enqueues an `entry` for analysis by the queue. - If ``high_priority`` is True (defaults to False), the entry will be prioritized and hence processed before + If `high_priority` is `True` (defaults to `False`), the entry will be prioritized and hence processed before other entries in the queue with normal priority. Arguments: - entry (QueueEntry): The :class:`QueueEntry` to analyze. - high_priority (boolean): Whether to process the provided entry with high priority (True) or not - (False, default) + entry (QueueEntry): The entry to analyze. + high_priority (bool): Whether to process the provided entry with high priority (`True`) or not + (`False`, default) """ if settings().get(["gcodeAnalysis", "runAt"]) == "never": @@ -340,14 +346,14 @@ class AbstractAnalysisQueue: def _do_analysis(self, high_priority=False): """ - Performs the actual analysis of the current entry which can be accessed via ``self._current``. Needs to be + Performs the actual analysis of the current entry which can be accessed via `self._current`. Needs to be overridden by sub classes. Arguments: high_priority (bool): Whether the current entry has high priority or not. Returns: - object: The result of the analysis which will be forwarded to the ``finished_callback`` provided during + object: The result of the analysis which will be forwarded to the `finished_callback` provided during construction. """ return None @@ -361,66 +367,36 @@ class AbstractAnalysisQueue: class GcodeAnalysisQueue(AbstractAnalysisQueue): """ - A queue to analyze GCODE files. Analysis results are :class:`dict` instances structured as follows: + A queue to analyze GCODE files. Analysis results are [dict][] instances structured as follows: - .. list-table:: - :widths: 25 70 - - - * **Key** - * **Description** - - * ``estimatedPrintTime`` - * Estimated time the file take to print, in seconds - - * ``filament`` - * Substructure describing estimated filament usage. Keys are ``tool0`` for the first extruder, ``tool1`` for - the second and so on. For each tool extruded length and volume (based on diameter) are provided. - - * ``filament.toolX.length`` - * The extruded length in mm - - * ``filament.toolX.volume`` - * The extruded volume in cm³ - - * ``printingArea`` - * Bounding box of the printed object in the print volume (minimum and maximum coordinates) - - * ``printingArea.minX`` - * Minimum X coordinate of the printed object - - * ``printingArea.maxX`` - * Maximum X coordinate of the printed object - - * ``printingArea.minY`` - * Minimum Y coordinate of the printed object - - * ``printingArea.maxY`` - * Maximum Y coordinate of the printed object - - * ``printingArea.minZ`` - * Minimum Z coordinate of the printed object - - * ``printingArea.maxZ`` - * Maximum Z coordinate of the printed object - - * ``dimensions`` - * Dimensions of the printed object in X, Y, Z - - * ``dimensions.width`` - * Width of the printed model along the X axis, in mm - - * ``dimensions.depth`` - * Depth of the printed model along the Y axis, in mm - - * ``dimensions.height`` - * Height of the printed model along the Z axis, in mm - - * ``travelArea`` - * Bounding box of all machine movements (minimum and maximum coordinates) - - * ``travelArea.minX`` - * Minimum X coordinate of the machine movement - - * ``travelArea.maxX`` - * Maximum X coordinate of the machine movement - - * ``travelArea.minY`` - * Minimum Y coordinate of the machine movement - - * ``travelArea.maxY`` - * Maximum Y coordinate of the machine movement - - * ``travelArea.minZ`` - * Minimum Z coordinate of the machine movement - - * ``travelArea.maxZ`` - * Maximum Z coordinate of the machine movement - - * ``travelDimensions`` - * Dimensions of the travel area in X, Y, Z - - * ``travelDimensions.width`` - * Width of the travel area along the X axis, in mm - - * ``travelDimensions.depth`` - * Depth of the travel area along the Y axis, in mm - - * ``travelDimensions.height`` - * Height of the travel area along the Z axis, in mm + | Name | Type | Description | + | ---- | ---- | ----------- | + | `estimatedPrintTime` | `int` | Estimated time the file take to print, in seconds | + | `filament.*` | `dict` | Substructure describing estimated filament usage. Keys are `tool0` for the first extruder, `tool1` for the second and so on. For each tool extruded length and volume (based on diameter) are provided. | + | `filament.toolX.length` | `float` | The extruded length in mm | + | `filament.toolX.volume` | `float` | The extruded volume in cm³ | + | `printingArea.*` | `dict` | Bounding box of the printed object in the print volume (minimum and maximum coordinates) | + | `printingArea.minX` | `float` | Minimum X coordinate of the printed object | + | `printingArea.maxX` | `float` | Maximum X coordinate of the printed object | + | `printingArea.minY` | `float` | Minimum Y coordinate of the printed object | + | `printingArea.maxY` | `float` | Maximum Y coordinate of the printed object | + | `printingArea.minZ` | `float` | Minimum Z coordinate of the printed object | + | `printingArea.maxZ` | `float` | Maximum Z coordinate of the printed object | + | `dimensions.*` | `dict` | Dimensions of the printed object in X, Y, Z | + | `dimensions.width` | `float` | Width of the printed model along the X axis, in mm | + | `dimensions.depth` | `float` | Depth of the printed model along the Y axis, in mm | + | `dimensions.height` | `float` | Height of the printed model along the Z axis, in mm | + | `travelArea.*` | `dict` | Bounding box of all machine movements (minimum and maximum coordinates) | + | `travelArea.minX` | `float` | Minimum X coordinate of the machine movements | + | `travelArea.maxX` | `float` | Maximum X coordinate of the machine movements | + | `travelArea.minY` | `float` | Minimum Y coordinate of the machine movements | + | `travelArea.maxY` | `float` | Maximum Y coordinate of the machine movements | + | `travelArea.minZ` | `float` | Minimum Z coordinate of the machine movements | + | `travelArea.maxZ` | `float` | Maximum Z coordinate of the machine movements | + | `travelDimensions.*` | `dict` | Dimensions of the travel area in X, Y, Z | + | `travelDimensions.width` | `float` | Width of the travel area along the X axis, in mm | + | `travelDimensions.depth` | `float` | Depth of the travel area along the X axis, in mm | + | `travelDimensions.height` | `float` | Height of the travel area along the X axis, in mm | """ def __init__(self, finished_callback): diff --git a/src/octoprint/filemanager/destinations.py b/src/octoprint/filemanager/destinations.py index 42f17c4ed..85e194f86 100644 --- a/src/octoprint/filemanager/destinations.py +++ b/src/octoprint/filemanager/destinations.py @@ -2,5 +2,7 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agp class FileDestinations: + """File destinations supported by the file manager.""" + SDCARD = "sdcard" LOCAL = "local" diff --git a/src/octoprint/filemanager/storage.py b/src/octoprint/filemanager/storage.py index 0d84c8b4d..f8a9de82d 100644 --- a/src/octoprint/filemanager/storage.py +++ b/src/octoprint/filemanager/storage.py @@ -32,12 +32,13 @@ class StorageInterface: @property def analysis_backlog(self): """ - Get an iterator over all items stored in the storage that need to be analysed by the :class:`~octoprint.filemanager.AnalysisQueue`. + Get an iterator over all items stored in the storage that need to be analysed by the [AnalysisQueue][octoprint.filemanager.AnalysisQueue]. The yielded elements are expected as storage specific absolute paths to the respective files. Don't forget to recurse into folders if your storage adapter supports those. - :return: an iterator yielding all un-analysed files in the storage + Returns: + (iterator): an iterator yielding all un-analysed files in the storage """ # empty generator pattern, yield is intentionally unreachable return @@ -51,40 +52,53 @@ class StorageInterface: def last_modified(self, path=None, recursive=False): """ - Get the last modification date of the specified ``path`` or ``path``'s subtree. + Get the last modification date of the specified `path` or `path`'s subtree. Args: - path (str or None): Path for which to determine the subtree's last modification date. If left out or - set to None, defatuls to storage root. - recursive (bool): Whether to determine only the date of the specified ``path`` (False, default) or - the whole ``path``'s subtree (True). + path (str | None): Path for which to determine the subtree's last modification date. If left out or + set to None, defaults to storage root. + recursive (bool): Whether to determine only the date of the specified `path` (`False`, default) or + the whole `path`'s subtree (True). - Returns: (float) The last modification date of the indicated subtree + Returns: + (float): The last modification date of the indicated subtree """ raise NotImplementedError() def file_in_path(self, path, filepath): """ - Returns whether the file indicated by ``file`` is inside ``path`` or not. - :param string path: the path to check - :param string filepath: path to the file - :return: ``True`` if the file is inside the path, ``False`` otherwise + Returns whether the file indicated by `file` is inside `path` or not. + + Arguments: + path (str): the path to check + filepath (str): path to the file + + Returns: + (bool): `True` if the file is inside the path, `False` otherwise """ return NotImplementedError() def file_exists(self, path): """ - Returns whether the file indicated by ``path`` exists or not. - :param string path: the path to check for existence - :return: ``True`` if the file exists, ``False`` otherwise + Returns whether the file indicated by `path` exists or not. + + Arguments: + path (str): the path to check for existence + + Returns: + (bool): `True` if the file exists, `False` otherwise """ raise NotImplementedError() def folder_exists(self, path): """ - Returns whether the folder indicated by ``path`` exists or not. - :param string path: the path to check for existence - :return: ``True`` if the folder exists, ``False`` otherwise + Returns whether the folder indicated by `path` exists or not. + + Arguments: + path (str): the path to check for existence + + Returns: + bool: `True` if the folder exists, `False` otherwise """ raise NotImplementedError() @@ -92,112 +106,127 @@ class StorageInterface: self, path=None, filter=None, recursive=True, level=0, force_refresh=False ): """ - List all files in storage starting at ``path``. If ``recursive`` is set to True (the default), also dives into + List all files in storage starting at `path`. If `recursive` is set to `True` (the default), also dives into subfolders. An optional filter function can be supplied which will be called with a file name and file data and which has to return True if the file is to be included in the result or False if not. The data structure of the returned result will be a dictionary mapping from file names to entry data. File nodes - will contain their metadata here, folder nodes will contain their contained files and folders. Example:: + will contain their metadata here, folder nodes will contain their contained files and folders. - { - "some_folder": { - "name": "some_folder", - "path": "some_folder", - "type": "folder", - "children": { - "some_sub_folder": { - "name": "some_sub_folder", - "path": "some_folder/some_sub_folder", - "type": "folder", - "typePath": ["folder"], - "children": { ... } - }, - "some_file.gcode": { - "name": "some_file.gcode", - "path": "some_folder/some_file.gcode", - "type": "machinecode", - "typePath": ["machinecode", "gcode"], - "hash": "", - "links": [ ... ], - ... - }, - ... - } - "test.gcode": { - "name": "test.gcode", - "path": "test.gcode", - "type": "machinecode", - "typePath": ["machinecode", "gcode"], - "hash": "", - "links": [...], - ... - }, - "test.stl": { - "name": "test.stl", - "path": "test.stl", - "type": "model", - "typePath": ["model", "stl"], - "hash": "", - "links": [...], - ... - }, - ... - } + Example: - :param string path: base path from which to recursively list all files, optional, if not supplied listing will start - from root of base folder - :param function filter: a filter that matches the files that are to be returned, may be left out in which case no - filtering will take place - :param bool recursive: will also step into sub folders for building the complete list if set to True, otherwise will only - do one step down into sub folders to be able to populate the ``children``. - :return: a dictionary mapping entry names to entry data that represents the whole file list + ``` json + { + "some_folder": { + "name": "some_folder", + "path": "some_folder", + "type": "folder", + "children": { + "some_sub_folder": { + "name": "some_sub_folder", + "path": "some_folder/some_sub_folder", + "type": "folder", + "typePath": ["folder"], + "children": { ... } + }, + "some_file.gcode": { + "name": "some_file.gcode", + "path": "some_folder/some_file.gcode", + "type": "machinecode", + "typePath": ["machinecode", "gcode"], + "hash": "", + "links": [ ... ], + ... + }, + ... + } + "test.gcode": { + "name": "test.gcode", + "path": "test.gcode", + "type": "machinecode", + "typePath": ["machinecode", "gcode"], + "hash": "", + "links": [...], + ... + }, + "test.stl": { + "name": "test.stl", + "path": "test.stl", + "type": "model", + "typePath": ["model", "stl"], + "hash": "", + "links": [...], + ... + }, + ... + } + ``` + + Arguments: + path (str): base path from which to recursively list all files, optional, if not supplied listing will start + from root of base folder + filter (function): a filter that matches the files that are to be returned, may be left out in which case no + filtering will take place + recursive (bool): will also step into sub folders for building the complete list if set to `True`, otherwise will only + do one step down into sub folders to be able to populate the `children`. + + Returns: + (dict): a nested dictionary mapping entry names to entry data that represents the whole file list """ raise NotImplementedError() def add_folder(self, path, ignore_existing=True, display=None): """ - Adds a folder as ``path`` + Adds a folder as `path` - The ``path`` will be sanitized. + The `path` will be sanitized. - :param string path: the path of the new folder - :param bool ignore_existing: if set to True, no error will be raised if the folder to be added already exists - :param str display: display name of the folder - :return: the sanitized name of the new folder to be used for future references to the folder + Arguments: + path (str): the path of the new folder + ignore_existing (bool): if set to `True`, no error will be raised if the folder to be added already exists + display (str): display name of the folder + + Returns: + (str): the sanitized name of the new folder to be used for future references to the folder """ raise NotImplementedError() def remove_folder(self, path, recursive=True): """ - Removes the folder at ``path`` + Removes the folder at `path` - :param string path: the path of the folder to remove - :param bool recursive: if set to True, contained folders and files will also be removed, otherwise an error will - be raised if the folder is not empty (apart from any metadata files) when it's to be removed + Arguments: + path (str): the path of the folder to remove + recursive (bool): if set to `True`, contained folders and files will also be removed, otherwise an error will + be raised if the folder is not empty (apart from any metadata files) when it's to be removed """ raise NotImplementedError() def copy_folder(self, source, destination): """ - Copies the folder ``source`` to ``destination`` + Copies the folder `source` to `destination` - :param string source: path to the source folder - :param string destination: path to destination + Arguments: + source (str): path to the source folder + destination (str): path to destination - :return: the path in the storage to the copy of the folder + Returns: + (str): the new path in the storage to the copy of the folder """ raise NotImplementedError() def move_folder(self, source, destination): """ - Moves the folder ``source`` to ``destination`` + Moves the folder `source` to `destination` - :param string source: path to the source folder - :param string destination: path to destination + Arguments: + source (str): path to the source folder + destination (str): path to destination - :return: the new path in the storage to the folder + Returns: + (str): the new path in the storage to the folder """ raise NotImplementedError() @@ -211,50 +240,58 @@ class StorageInterface: display=None, ): """ - Adds the file ``file_object`` as ``path`` + Adds the file `file_object` as `path` - :param string path: the file's new path, will be sanitized - :param object file_object: a file object that provides a ``save`` method which will be called with the destination path - where the object should then store its contents - :param object printer_profile: the printer profile associated with this file (if any) - :param list links: any links to add with the file - :param bool allow_overwrite: if set to True no error will be raised if the file already exists and the existing file - and its metadata will just be silently overwritten - :param str display: display name of the file - :return: the sanitized name of the file to be used for future references to it + Arguments: + path (str): the path of the new file, will be sanitized + file_object (object): a file object that provides a `save` method which will be called with the destination path + where the object should then store its contents + printer_profile (object): the printer profile associated with this file (if any) + links (list): any links to add with the file + allow_overwrite (bool): if set to `True` no error will be raised if the file already exists and the existing file + and its metadata will just be silently overwritten + display (str): display name of the file + + Returns: + (str): the sanitized name of the file to be used for future references to it """ raise NotImplementedError() def remove_file(self, path): """ - Removes the file at ``path`` + Removes the file at `path` Will also take care of deleting the corresponding entries in the metadata and deleting all links pointing to the file. - :param string path: path of the file to remove + Arguments: + path (str): path of the file to remove """ raise NotImplementedError() def copy_file(self, source, destination): """ - Copies the file ``source`` to ``destination`` + Copies the file `source` to `destination` - :param string source: path to the source file - :param string destination: path to destination + Arguments: + source (str): path to the source file + destination (str): path to destination - :return: the path in the storage to the copy of the file + Returns: + (str): the new path in the storage to the copy of the file """ raise NotImplementedError() def move_file(self, source, destination): """ - Moves the file ``source`` to ``destination`` + Moves the file `source` to `destination` - :param string source: path to the source file - :param string destination: path to destination + Arguments: + source (str): path to the source file + destination (str): path to destination - :return: the new path in the storage to the file + Returns: + (str): the new path in the storage to the file """ raise NotImplementedError() @@ -262,173 +299,212 @@ class StorageInterface: """ Returns whether the file at path has been analysed yet - :param path: virtual path to the file for which to retrieve the metadata + Arguments: + path (str): path to the file to check """ raise NotImplementedError() def get_metadata(self, path): """ - Retrieves the metadata for the file ``path``. + Retrieves the metadata for the file `path`. - :param path: virtual path to the file for which to retrieve the metadata - :return: the metadata associated with the file + Arguments: + path (str): virtual path to the file for which to retrieve the metadata + + Returns: + (dict): the metadata associated with the file """ raise NotImplementedError() def add_link(self, path, rel, data): """ - Adds a link of relation ``rel`` to file ``path`` with the given ``data``. + Adds a link of relation `rel` to file `path` with the given `data`. The following relation types are currently supported: - * ``model``: adds a link to a model from which the file was created/sliced, expected additional data is the ``name`` - and optionally the ``hash`` of the file to link to. If the link can be resolved against another file on the - current ``path``, not only will it be added to the links of ``name`` but a reverse link of type ``machinecode`` - referring to ``name`` and its hash will also be added to the linked ``model`` file - * ``machinecode``: adds a link to a file containing machine code created from the current file (model), expected - additional data is the ``name`` and optionally the ``hash`` of the file to link to. If the link can be resolved - against another file on the current ``path``, not only will it be added to the links of ``name`` but a reverse - link of type ``model`` referring to ``name`` and its hash will also be added to the linked ``model`` file. - * ``web``: adds a location on the web associated with this file (e.g. a website where to download a model), - expected additional data is a ``href`` attribute holding the website's URL and optionally a ``retrieved`` - attribute describing when the content was retrieved + - `model`: adds a link to a model from which the file was created/sliced, expected additional data is the `name` + and optionally the `hash` of the file to link to. If the link can be resolved against another file on the + current `path`, not only will it be added to the links of `name` but a reverse link of type `machinecode` + referring to `name` and its hash will also be added to the linked `model` file + - `machinecode`: adds a link to a file containing machine code created from the current file (model), expected + additional data is the `name` and optionally the `hash` of the file to link to. If the link can be resolved + against another file on the current `path`, not only will it be added to the links of `name` but a reverse + link of type `model` referring to `name` and its hash will also be added to the linked `model` file. + - `web`: adds a location on the web associated with this file (e.g. a website where to download a model), + expected additional data is a `href` attribute holding the website's URL and optionally a `retrieved` + attribute describing when the content was retrieved - Note that adding ``model`` links to files identifying as models or ``machinecode`` links to files identifying + Note that adding `model` links to files identifying as models or `machinecode` links to files identifying as machine code will be refused. - :param path: path of the file for which to add a link - :param rel: type of relation of the link to add (currently ``model``, ``machinecode`` and ``web`` are supported) - :param data: additional data of the link to add + Arguments: + path (str): path of the file for which to add a link + rel (str): type of relation of the link to add (currently `model`, `machinecode` and `web` are supported) + data (dict): additional data of the link to add """ raise NotImplementedError() def remove_link(self, path, rel, data): """ - Removes the link consisting of ``rel`` and ``data`` from file ``name`` on ``path``. + Removes the link consisting of `rel` and `data` from file `path`. - :param path: path of the file from which to remove the link - :param rel: type of relation of the link to remove (currently ``model``, ``machinecode`` and ``web`` are supported) - :param data: additional data of the link to remove, must match existing link + Arguments: + path (str): path of the file from which to remove the link + rel (str): type of relation of the link to remove (currently `model`, `machinecode` and `web` are supported) + data (dict): additional data of the link to remove, must match existing link """ raise NotImplementedError() def get_additional_metadata(self, path, key): """ - Fetches additional metadata at ``key`` from the metadata of ``path``. + Fetches additional metadata at `key` from the metadata of `path`. - :param path: the virtual path to the file for which to fetch additional metadata - :param key: key of metadata to fetch + Arguments: + path (str): virtual path to the file for which to fetch additional metadata + key (str): key of metadata to fetch """ raise NotImplementedError() def set_additional_metadata(self, path, key, data, overwrite=False, merge=False): """ - Adds additional metadata to the metadata of ``path``. Metadata in ``data`` will be saved under ``key``. + Adds additional metadata to the metadata of `path`. Metadata in `data` will be saved under `key`. - If ``overwrite`` is set and ``key`` already exists in ``name``'s metadata, the current value will be overwritten. + If `overwrite` is set and `key` already exists in `path`'s metadata, the current value will be overwritten. - If ``merge`` is set and ``key`` already exists and both ``data`` and the existing data under ``key`` are dictionaries, + If `merge` is set and `key` already exists and both `data` and the existing data under `key` are dictionaries, the two dictionaries will be merged recursively. - :param path: the virtual path to the file for which to add additional metadata - :param key: key of metadata to add - :param data: metadata to add - :param overwrite: if True and ``key`` already exists, it will be overwritten - :param merge: if True and ``key`` already exists and both ``data`` and the existing data are dictionaries, they - will be merged + Arguments: + path (str): virtual path to the file for which to add additional metadata + key (str): key of metadata to add + data (dict): metadata to add + overwrite (bool): if set to `True` and `key` already exists, it will be overwritten + merge (bool): if set to `True` and `key` already exists and both `data` and the existing data are dictionaries, + they will be merged """ raise NotImplementedError() def remove_additional_metadata(self, path, key): """ - Removes additional metadata under ``key`` for ``name`` on ``path`` + Removes additional metadata under `key` for `name` on `path` - :param path: the virtual path to the file for which to remove the metadata under ``key`` - :param key: the key to remove + Arguments: + path (str): virtual path to the file for which to remove additional metadata + key (str): key of metadata to remove """ raise NotImplementedError() def canonicalize(self, path): """ - Canonicalizes the given ``path``. The ``path`` may consist of both folder and file name, the underlying + Canonicalizes the given `path`. + + The `path` may consist of both folder and file name, the underlying implementation must separate those if necessary. - By default, this calls :func:`~octoprint.filemanager.StorageInterface.sanitize`, which also takes care + By default, this calls [StorageInterface.sanitize][octoprint.filemanager.storage.StorageInterface.sanitize], which also takes care of stripping any invalid characters. - Args: - path: the path to canonicalize + Arguments: + path (str): the path to canonicalize Returns: - a 2-tuple containing the canonicalized path and file name - + (tuple): a 2-tuple containing the canonicalized path and file name """ return self.sanitize(path) def sanitize(self, path): """ - Sanitizes the given ``path``, stripping it of all invalid characters. The ``path`` may consist of both - folder and file name, the underlying implementation must separate those if necessary and sanitize individually. + Sanitizes the given `path`, stripping it of all invalid characters. - :param string path: the path to sanitize - :return: a 2-tuple containing the sanitized path and file name + The `path` may consist of both folder and file name, the underlying + implementation must separate those if necessary and sanitize individually. + + Arguments: + path (str): the path to sanitize + + Returns: + (tuple): a 2-tuple containing the sanitized path and file name """ raise NotImplementedError() def sanitize_path(self, path): """ - Sanitizes the given folder-only ``path``, stripping it of all invalid characters. - :param string path: the path to sanitize - :return: the sanitized path + Sanitizes the given folder-only `path`, stripping it of all invalid characters. + + Arguments: + path (str): the path to sanitize + + Returns: + (str): the sanitized path """ raise NotImplementedError() def sanitize_name(self, name): """ - Sanitizes the given file ``name``, stripping it of all invalid characters. - :param string name: the file name to sanitize - :return: the sanitized name + Sanitizes the given file `name`, stripping it of all invalid characters. + + Arguments: + name (str): the file name to sanitize + + Returns: + (str): the sanitized file name """ raise NotImplementedError() def split_path(self, path): """ - Split ``path`` into base directory and file name. - :param path: the path to split - :return: a tuple (base directory, file name) + Split `path` into base directory and file name. + + Arguments: + path (str): the path to split + + Returns: + (tuple): a 2-tuple containing the base directory and file name """ raise NotImplementedError() def join_path(self, *path): """ Join path elements together - :param path: path elements to join - :return: joined representation of the path to be usable as fully qualified path for further operations + + Arguments: + path (str): the path elements to join + + Returns: + (str): joined representation of the path to be usable as fully qualified path for further operations """ raise NotImplementedError() def path_on_disk(self, path): """ - Retrieves the path on disk for ``path``. + Retrieves the path on disk for `path`. - Note: if the storage is not on disk and there exists no path on disk to refer to it, this method should - raise an :class:`io.UnsupportedOperation` + !!! note - Opposite of :func:`path_in_storage`. + If the storage is not on disk and there exists no path on disk to refer to it, this method should + raise an [io.UnsupportedOperation][] - :param string path: the virtual path for which to retrieve the path on disk - :return: the path on disk to ``path`` + Opposite of `path_in_storage`. + + Arguments: + path (str): the virtual path for which to retrieve the path on disk + + Returns: + (str): the path on disk to `path` """ raise NotImplementedError() def path_in_storage(self, path): """ - Retrieves the equivalent in the storage adapter for ``path``. + Retrieves the equivalent in the storage adapter for `path`. - Opposite of :func:`path_on_disk`. + Opposite of `path_on_disk`. - :param string path: the path for which to retrieve the storage path - :return: the path in storage to ``path`` + Arguments: + path (str): the path on disk for which to retrieve the storage path + + Returns: + (str): the path in storage to `path` """ raise NotImplementedError() @@ -455,22 +531,23 @@ class StorageError(Exception): class LocalFileStorage(StorageInterface): """ - The ``LocalFileStorage`` is a storage implementation which holds all files, folders and metadata on disk. + The `LocalFileStorage` is a storage implementation which holds all files, folders and metadata on disk. - Metadata is managed inside ``.metadata.json`` files in the respective folders, indexed by the sanitized filenames + Metadata is managed inside `.metadata.json` files in the respective folders, indexed by the sanitized filenames stored within the folder. Metadata access is managed through an LRU cache to minimize access overhead. - This storage type implements :func:`path_on_disk`. + This storage type implements `path_on_disk`. """ def __init__(self, basefolder, create=False, really_universal=False): """ - Initializes a ``LocalFileStorage`` instance under the given ``basefolder``, creating the necessary folder - if necessary and ``create`` is set to ``True``. + Initializes a `LocalFileStorage` instance under the given `basefolder`, creating the necessary folder + if necessary and `create` is set to `True`. - :param string basefolder: the path to the folder under which to create the storage - :param bool create: ``True`` if the folder should be created if it doesn't exist yet, ``False`` otherwise - :param bool really_universal: ``True`` if the file names should be forced to really universal, ``False`` otherwise + Arguments: + basefolder (str): the path to the folder under which to create the storage + create (bool): `True` if the folder should be created if it doesn't exist yet, `False` otherwise + really_universal (bool): `True` if the file names should be forced to be really universal, `False` otherwise """ self._logger = logging.getLogger(__name__) @@ -1121,18 +1198,26 @@ class LocalFileStorage(StorageInterface): def sanitize(self, path): """ - Returns a ``(path, name)`` tuple derived from the provided ``path``. + Returns a `(path, name)` tuple derived from the provided `path`. - ``path`` may be: - * a storage path - * an absolute file system path - * a tuple or list containing all individual path elements - * a string representation of the path - * with or without a file name + `path` may be: + - a storage path + - an absolute file system path + - a tuple or list containing all individual path elements + - a string representation of the path + - with or without a file name - Note that for a ``path`` without a trailing slash the last part will be considered a file name and - hence be returned at second position. If you only need to convert a folder path, be sure to - include a trailing slash for a string ``path`` or an empty last element for a list ``path``. + !!! note + + For a `path` without a trailing slash the last part will be considered a file name and + hence be returned at second position. If you only need to convert a folder path, be sure to + include a trailing slash for a string `path` or an empty last element for a list `path`. + + Arguments: + path (str | list | tuple): The path to sanitize + + Returns: + (tuple): The sanitized path and name """ path, name = self.canonicalize(path) @@ -1161,18 +1246,35 @@ class LocalFileStorage(StorageInterface): return path, name def sanitize_name(self, name): - """ - Raises a :class:`ValueError` for a ``name`` containing ``/`` or ``\\``. Otherwise - sanitizes the given ``name`` using ``octoprint.files.sanitize_filename``. Also - strips any leading ``.``. + r""" + Sanitizes the given `name` using `sanitize_filename`. + + Strips any leading `.`. + + Arguments: + name (str): The name to sanitize + + Returns: + (str): The sanitized name + + Raises: + ValueError: If the name contains `/` or `\` """ return sanitize_filename(name, really_universal=self._really_universal) def sanitize_path(self, path): """ - Ensures that the on disk representation of ``path`` is located under the configured basefolder. Resolves all - relative path elements (e.g. ``..``) and sanitizes folder names using :func:`sanitize_name`. Final path is the - absolute path including leading ``basefolder`` path. + Sanitizes the given `path`. + + Ensures that the on disk representation of `path` is located under the configured `basefolder`. + Resolves all relative path elements (e.g. `..`) and sanitizes folder names using `sanitize_name`. + The final path is the absolute path, including the leading `basefolder` path. + + Arguments: + path (str): The path to sanitize + + Returns: + (str): The sanitized path """ path = to_unicode(path) diff --git a/src/octoprint/logging/__init__.py b/src/octoprint/logging/__init__.py index 047d63e9a..9b4894b8c 100644 --- a/src/octoprint/logging/__init__.py +++ b/src/octoprint/logging/__init__.py @@ -7,10 +7,10 @@ def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args Logs to the provided handler only. Arguments: - logger: logger to log to - handler: handler to restrict logging to - level: level to log at - msg: message to log + logger (logging.Logger): logger to log to + handler (logging.Handler): handler to restrict logging to + level (int): level to log at + msg (str): message to log exc_info: optional exception info extra: optional extra data *args: log args @@ -51,18 +51,18 @@ def log_to_handler(logger, handler, level, msg, exc_info=None, extra=None, *args def get_handler(name, logger=None): """ - Retrieves the handler named ``name``. + Retrieves the handler named `name`. - If optional ``logger`` is provided, search will be + If optional `logger` is provided, search will be limited to that logger, otherwise the root logger will be searched. Arguments: - name: the name of the handler to look for - logger: (optional) the logger to search in, root logger if not provided + name (str): the name of the handler to look for + logger (logging.loggers.Logger): (optional) the logger to search in, root logger if not provided Returns: - the handler if it could be found, None otherwise + (logging.handlers.Handler | None): the handler if it could be found, `None` otherwise """ import logging @@ -116,13 +116,13 @@ def get_divider_line(c, message=None, length=78, indent=3): AssertionError: indent is not an int Arguments: - c: character to use for the line - message: message to print in the line - length: length of the line - indent: indentation of message in line + c (str): character to use for the line + message (str): message to print in the line + length (int): length of the line + indent (int): indentation of message in line Returns: - formatted divider line + (str): formatted divider line """ assert isinstance(c, str), "c is not text" @@ -143,6 +143,16 @@ def get_divider_line(c, message=None, length=78, indent=3): def prefix_multilines(text: str, prefix: str = ": ") -> str: + """ + Prefixes all lines of the given text with the given prefix. + + Arguments: + text (str): text to prefix + prefix (str): prefix to use + + Returns: + (str): prefixed text + """ from octoprint.util import to_unicode lines = text.splitlines() diff --git a/src/octoprint/plugin/__init__.py b/src/octoprint/plugin/__init__.py index 41b5359f2..5a0f200bf 100644 --- a/src/octoprint/plugin/__init__.py +++ b/src/octoprint/plugin/__init__.py @@ -1,15 +1,6 @@ """ This module represents OctoPrint's plugin subsystem. This includes management and helper methods as well as the registered plugin types. - -.. autofunction:: plugin_manager - -.. autofunction:: plugin_settings - -.. autofunction:: call_plugin - -.. autoclass:: PluginSettings - :members: """ __author__ = "Gina Häußge " @@ -48,23 +39,23 @@ def plugin_manager( compatibility_ignored_list=None, ): """ - Factory method for initially constructing and consecutively retrieving the :class:`~octoprint.plugin.core.PluginManager` + Factory method for initially constructing and consecutively retrieving the [PluginManager][octoprint.plugin.core.PluginManager] singleton. Arguments: - init (boolean): A flag indicating whether this is the initial call to construct the singleton (True) or not - (False, default). If this is set to True and the plugin manager has already been initialized, a :class:`ValueError` + init (bool): A flag indicating whether this is the initial call to construct the singleton (`True`) or not + (`False`, default). If this is set to `True` and the plugin manager has already been initialized, a [ValueError][] will be raised. The same will happen if the plugin manager has not yet been initialized and this is set to False. plugin_folders (list): A list of folders (as strings containing the absolute path to them) in which to look for - potential plugin modules. If not provided this defaults to the configured ``plugins`` base folder and - ``src/plugins`` within OctoPrint's code base. + potential plugin modules. If not provided this defaults to the configured `plugins` base folder and + `src/plugins` within OctoPrint's code base. plugin_bases (list): A list of recognized plugin base classes for which to look for provided implementations. If not - provided this defaults to :class:`~octoprint.plugin.OctoPrintPlugin`. + provided this defaults to `octoprint.plugin.types.OctoPrintPlugin`. plugin_entry_points (list): A list of entry points pointing to modules which to load as plugins. If not provided - this defaults to the entry point ``octoprint.plugin``. + this defaults to the entry point `octoprint.plugin`. plugin_disabled_list (list): A list of plugin identifiers that are currently disabled. If not provided this - defaults to all plugins for which ``enabled`` is set to ``False`` in the settings. + defaults to all plugins for which `enabled` is set to `False` in the settings. plugin_sorting_order (dict): A dict containing a custom sorting orders for plugins. The keys are plugin identifiers, mapped to dictionaries containing the sorting contexts as key and the custom sorting value as value. plugin_blacklist (list): A list of plugin identifiers/identifier-requirement tuples @@ -81,11 +72,11 @@ def plugin_manager( 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 + (octoprint.plugin.core.PluginManager): A fully initialized `PluginManager` instance to be used for plugin management tasks. Raises: - ValueError: ``init`` was True although the plugin manager was already initialized, or it was False although + ValueError: `init` was `True` although the plugin manager was already initialized, or it was `False` although the plugin manager was not yet initialized. """ @@ -145,17 +136,17 @@ def plugin_settings( settings=None, ): """ - Factory method for creating a :class:`PluginSettings` instance. + Factory method for creating a `PluginSettings` instance. Arguments: - plugin_key (string): The plugin identifier for which to create the settings instance. + plugin_key (str): The plugin identifier for which to create the settings instance. defaults (dict): The default settings for the plugin, if different from get_settings_defaults. get_preprocessors (dict): The getter preprocessors for the plugin. set_preprocessors (dict): The setter preprocessors for the plugin. settings (octoprint.settings.Settings): The settings instance to use. Returns: - PluginSettings: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's + (octoprint.plugin.PluginSettings): A fully initialized `PluginSettings` instance to be used to access the plugin's settings """ if settings is None: @@ -171,18 +162,18 @@ def plugin_settings( def plugin_settings_for_settings_plugin(plugin_key, instance, settings=None): """ - Factory method for creating a :class:`PluginSettings` instance for a given :class:`SettingsPlugin` instance. + Factory method for creating a `PluginSettings` instance for a given `SettingsPlugin` instance. - Will return `None` if the provided `instance` is not a :class:`SettingsPlugin` instance. + Will return `None` if the provided `instance` is not a [SettingsPlugin][octoprint.plugin.types.SettingsPlugin] instance. Arguments: plugin_key (string): The plugin identifier for which to create the settings instance. - implementation (octoprint.plugin.SettingsPlugin): The :class:`SettingsPlugin` instance. + instance (octoprint.plugin.types.SettingsPlugin): The `SettingsPlugin` instance. settings (octoprint.settings.Settings): The settings instance to use. Defaults to the global OctoPrint settings. Returns: - PluginSettings or None: A fully initialized :class:`PluginSettings` instance to be used to access the plugin's - settings, or `None` if the provided `instance` was not a class:`SettingsPlugin` + (octoprint.plugin.PluginSettings | None): A fully initialized `PluginSettings` instance to be used to access the plugin's + settings, or `None` if the provided `instance` was not a `SettingsPlugin` """ if not isinstance(instance, SettingsPlugin): return None @@ -215,42 +206,42 @@ def call_plugin( manager=None, ): """ - Helper method to invoke the indicated ``method`` on all registered plugin implementations implementing the - indicated ``types``. Allows providing method arguments and registering callbacks to call in case of success + Helper method to invoke the indicated `method` on all registered plugin implementations implementing the + indicated `types`. Allows providing method arguments and registering callbacks to call in case of success and/or failure of each call which can be used to return individual results to the calling code. Example: - .. sourcecode:: python + ``` python + def my_success_callback(name, plugin, result): + print("{name} was called successfully and returned {result!r}".format(**locals())) - def my_success_callback(name, plugin, result): - print("{name} was called successfully and returned {result!r}".format(**locals())) + def my_error_callback(name, plugin, exc): + print("{name} raised an exception: {exc!s}".format(**locals())) - def my_error_callback(name, plugin, exc): - print("{name} raised an exception: {exc!s}".format(**locals())) - - octoprint.plugin.call_plugin( - [octoprint.plugin.StartupPlugin], - "on_startup", - args=(my_host, my_port), - callback=my_success_callback, - error_callback=my_error_callback - ) + octoprint.plugin.call_plugin( + [octoprint.plugin.StartupPlugin], + "on_startup", + args=(my_host, my_port), + callback=my_success_callback, + error_callback=my_error_callback + ) + ``` Arguments: types (list): A list of plugin implementation types to match against. - method (string): Name of the method to call on all matching implementations. - args (tuple): A tuple containing the arguments to supply to the called ``method``. Optional. - kwargs (dict): A dictionary containing the keyword arguments to supply to the called ``method``. Optional. - callback (function): A callback to invoke after an implementation has been called successfully. Will be called - with the three arguments ``name``, ``plugin`` and ``result``. ``name`` will be the plugin identifier, - ``plugin`` the plugin implementation instance itself and ``result`` the result returned from the - ``method`` invocation. - error_callback (function): A callback to invoke after the call of an implementation resulted in an exception. - Will be called with the three arguments ``name``, ``plugin`` and ``exc``. ``name`` will be the plugin - identifier, ``plugin`` the plugin implementation instance itself and ``exc`` the caught exception. - initialized (boolean): Ignored. - manager (PluginManager or None): The plugin manager to use. If not provided, the global plugin manager + method (str): Name of the method to call on all matching implementations. + args (tuple): A tuple containing the arguments to supply to the called `method`. Optional. + kwargs (dict): A dictionary containing the keyword arguments to supply to the called `method`. Optional. + callback (callable): A callback to invoke after an implementation has been called successfully. Will be called + with the three arguments `name`, `plugin` and `result`. `name` will be the plugin identifier, + `plugin` the plugin implementation instance itself and `result` the result returned from the + `method` invocation. + error_callback (callable): A callback to invoke after the call of an implementation resulted in an exception. + Will be called with the three arguments `name`, `plugin` and `exc`. `name` will be the plugin + identifier, `plugin` the plugin implementation instance itself and `exc` the caught exception. + initialized (bool): Ignored. + manager (octoprint.plugin.core.PluginManager | None): The plugin manager to use. If not provided, the global plugin manager """ if not isinstance(types, (list, tuple)): @@ -286,107 +277,22 @@ def call_plugin( class PluginSettings: """ - The :class:`PluginSettings` class is the interface for plugins to their own or globally defined settings. + The `PluginSettings` class is the interface for plugins to their own or globally defined settings. It provides some convenience methods for directly accessing plugin settings via the regular - :class:`octoprint.settings.Settings` interfaces as well as means to access plugin specific folder locations. + [Settings][octoprint.settings.Settings] interfaces as well as means to access plugin specific folder locations. All getter and setter methods will ensure that plugin settings are stored in their correct location within the settings structure by modifying the supplied paths accordingly. Arguments: - settings (Settings): The :class:`~octoprint.settings.Settings` instance on which to operate. + settings (octoprint.settings.Settings): The `Settings` instance on which to operate. plugin_key (str): The plugin identifier of the plugin for which to create this instance. - defaults (dict): The plugin's defaults settings, will be used to determine valid paths within the plugin's - settings structure - - .. method:: get(path, merged=False, asdict=False) - - Retrieves a raw value from the settings for ``path``, optionally merging the raw value with the default settings - if ``merged`` is set to True. - - :param path: The path for which to retrieve the value. - :type path: list, tuple - :param boolean merged: Whether to merge the returned result with the default settings (True) or not (False, - default). - :returns: The retrieved settings value. - :rtype: object - - .. method:: get_int(path, min=None, max=None) - - Like :func:`get` but tries to convert the retrieved value to ``int``. If ``min`` is provided and the retrieved - value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if - the value is greater than it. - - .. method:: get_float(path, min=None, max=None) - - Like :func:`get` but tries to convert the retrieved value to ``float``. If ``min`` is provided and the retrieved - value is less than it, it will be returned instead of the value. Likewise for ``max`` - it will be returned if - the value is greater than it. - - .. method:: get_boolean(path) - - Like :func:`get` but tries to convert the retrieved value to ``boolean``. - - .. method:: set(path, value, force=False) - - Sets the raw value on the settings for ``path``. - - :param path: The path for which to retrieve the value. - :type path: list, tuple - :param object value: The value to set. - :param boolean force: If set to True, the modified configuration will even be written back to disk if - the value didn't change. - - .. method:: set_int(path, value, force=False, min=None, max=None) - - Like :func:`set` but ensures the value is an ``int`` through attempted conversion before setting it. - If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal - to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than - that, ``max`` if greater than that) will be set instead. - - .. method:: set_float(path, value, force=False, min=None, max=None) - - Like :func:`set` but ensures the value is an ``float`` through attempted conversion before setting it. - If ``min`` and/or ``max`` are provided, it will also be ensured that the value is greater than or equal - to ``min`` and less than or equal to ``max``. If that is not the case, the limit value (``min`` if less than - that, ``max`` if greater than that) will be set instead. - - .. method:: set_boolean(path, value, force=False) - - Like :func:`set` but ensures the value is an ``boolean`` through attempted conversion before setting it. - - .. method:: save(force=False, trigger_event=False) - - Saves the settings to ``config.yaml`` if there are active changes. If ``force`` is set to ``True`` the settings - will be saved even if there are no changes. Settings ``trigger_event`` to ``True`` will cause a ``SettingsUpdated`` - :ref:`event ` to get triggered. - - :param force: Force saving to ``config.yaml`` even if there are no changes. - :type force: boolean - :param trigger_event: Trigger the ``SettingsUpdated`` :ref:`event ` on save. - :type trigger_event: boolean - - .. method:: add_overlay(overlay, at_end=False, key=None) - - Adds a new config overlay for the plugin's settings. Will return the overlay's key in the map. - - :param overlay: Overlay dict to add - :type overlay: dict - :param at_end: Whether to add overlay at end or start (default) of config hierarchy - :type at_end: boolean - :param key: Key to use to identify overlay. If not set one will be built based on the overlay's hash - :type key: str - :rtype: str - - .. method:: remove_overlay(key) - - Removes an overlay from the settings based on its key. Return ``True`` if the overlay could be found and was - removed, ``False`` otherwise. - - :param key: The key of the overlay to remove - :type key: str - :rtype: boolean + defaults (dict): The plugin's defaults settings. + get_preprocessors (dict): The plugin's get preprocessors. A dict of settings paths to callables that will + be called with the value of the setting and should return the processed value. + set_preprocessors (dict): The plugin's set preprocessors. A dict of settings paths to callables that will + be called with the value of the setting and should return the processed value. """ def __init__( @@ -398,169 +304,345 @@ class PluginSettings: set_preprocessors=None, ): self.settings = settings + """ The `Settings` instance on which to operate. """ + self.plugin_key = plugin_key + """ The plugin identifier of the plugin for which this instance was created. """ + + self.defaults = None + """ The plugin's defaults settings, prefixed with the plugin's settings path. """ if defaults is not None: self.defaults = {"plugins": {}} self.defaults["plugins"][plugin_key] = defaults self.defaults["plugins"][plugin_key]["_config_version"] = None - else: - self.defaults = None + + self.get_preprocessors = {"plugins": {}} + """ The plugin's get preprocessors, prefixed with the plugin's settings path. """ if get_preprocessors is None: get_preprocessors = {} - self.get_preprocessors = {"plugins": {}} self.get_preprocessors["plugins"][plugin_key] = get_preprocessors + self.set_preprocessors = {"plugins": {}} + """ The plugin's set preprocessors, prefixed with the plugin's settings path. """ + if set_preprocessors is None: set_preprocessors = {} - self.set_preprocessors = {"plugins": {}} self.set_preprocessors["plugins"][plugin_key] = set_preprocessors - def prefix_path_in_args(args, index=0): - result = [] - if index == 0: - result.append(self._prefix_path(args[0])) - result.extend(args[1:]) - else: - args_before = args[: index - 1] - args_after = args[index + 1 :] - result.extend(args_before) - result.append(self._prefix_path(args[index])) - result.extend(args_after) - return result - - def add_getter_kwargs(kwargs): - if "defaults" not in kwargs and self.defaults is not None: - kwargs.update(defaults=self.defaults) - if "preprocessors" not in kwargs: - kwargs.update(preprocessors=self.get_preprocessors) - return kwargs - - def add_setter_kwargs(kwargs): - if "defaults" not in kwargs and self.defaults is not None: - kwargs.update(defaults=self.defaults) - if "preprocessors" not in kwargs: - kwargs.update(preprocessors=self.set_preprocessors) - return kwargs - - def wrap_overlay(args): - result = list(args) - overlay = result[0] - result[0] = {"plugins": {plugin_key: overlay}} - return result - - self.access_methods = { - "has": ("has", prefix_path_in_args, add_getter_kwargs), - "get": ("get", prefix_path_in_args, add_getter_kwargs), - "get_int": ("getInt", prefix_path_in_args, add_getter_kwargs), - "get_float": ("getFloat", prefix_path_in_args, add_getter_kwargs), - "get_boolean": ("getBoolean", prefix_path_in_args, add_getter_kwargs), - "set": ("set", prefix_path_in_args, add_setter_kwargs), - "set_int": ("setInt", prefix_path_in_args, add_setter_kwargs), - "set_float": ("setFloat", prefix_path_in_args, add_setter_kwargs), - "set_boolean": ("setBoolean", prefix_path_in_args, add_setter_kwargs), - "remove": ("remove", prefix_path_in_args, lambda x: x), - "add_overlay": ("add_overlay", wrap_overlay, lambda x: x), - "remove_overlay": ("remove_overlay", lambda x: x, lambda x: x), - } - self.deprecated_access_methods = { - "getInt": "get_int", - "getFloat": "get_float", - "getBoolean": "get_boolean", - "setInt": "set_int", - "setFloat": "set_float", - "setBoolean": "set_boolean", - } - def _prefix_path(self, path=None): if path is None: path = list() return ["plugins", self.plugin_key] + path + def _add_getter_kwargs(self, kwargs): + if "defaults" not in kwargs and self.defaults is not None: + kwargs.update(defaults=self.defaults) + if "preprocessors" not in kwargs: + kwargs.update(preprocessors=self.get_preprocessors) + return kwargs + + def _add_setter_kwargs(self, kwargs): + if "defaults" not in kwargs and self.defaults is not None: + kwargs.update(defaults=self.defaults) + if "preprocessors" not in kwargs: + kwargs.update(preprocessors=self.set_preprocessors) + return kwargs + + def _wrap_overlay(self, args): + result = list(args) + overlay = result[0] + result[0] = {"plugins": {self.plugin_key: overlay}} + return result + + def has(self, path, **kwargs): + """ + Checks whether a value for `path` is present in the settings. + + Arguments: + path (list, tuple): The path for which to check the value. + + Returns: + (bool): Whether a value for `path` is present in the settings. + """ + return self.settings.has( + self._prefix_path(path), **self._add_getter_kwargs(kwargs) + ) + + def get(self, path, **kwargs): + """ + Retrieves a raw value from the settings for `path`, optionally merging the raw value with the default settings + if `merged` is set to True. + + Arguments: + path (list, tuple): The path for which to retrieve the value. + merged (bool): Whether to merge the returned result with the default settings (True) or not (False, + default). + asdict (bool): Whether to return the result as a dictionary (True) or not (False, default). + + Returns: + (object): The retrieved settings value. + """ + return self.settings.get( + self._prefix_path(path), **self._add_getter_kwargs(kwargs) + ) + + def get_int(self, path, **kwargs): + """ + Like `get` but tries to convert the retrieved value to [int][]. If `min` is provided and the retrieved + value is less than it, it will be returned instead of the value. Likewise for `max` - it will be returned if + the value is greater than it. + + Arguments: + path (list, tuple): The path for which to retrieve the value. + min (int): The minimum value to return. + max (int): The maximum value to return. + + Returns: + (int | None): The retrieved settings value, converted to an integer, if possible, `None` otherwise + """ + return self.settings.getInt( + self._prefix_path(path), **self._add_getter_kwargs(kwargs) + ) + + def get_float(self, path, **kwargs): + """ + Like `get` but tries to convert the retrieved value to [float][]. If `min` is provided and the retrieved + value is less than it, it will be returned instead of the value. Likewise for `max` - it will be returned if + the value is greater than it. + + Arguments: + path (list, tuple): The path for which to retrieve the value. + min (float): The minimum value to return. + max (float): The maximum value to return. + + Returns: + (float | None): The retrieved settings value, converted to a float, if possible, `None` otherwise + """ + return self.settings.getFloat( + self._prefix_path(path), **self._add_getter_kwargs(kwargs) + ) + + def get_boolean(self, path, **kwargs): + """ + Like `get` but tries to convert the retrieved value to [bool][]. + + Arguments: + path (list, tuple): The path for which to retrieve the value. + + Returns: + (bool | None): The retrieved settings value, converted to a boolean, if possible, `None` otherwise + """ + return self.settings.getBoolean( + self._prefix_path(path), **self._add_getter_kwargs(kwargs) + ) + + def set(self, path, value, **kwargs): + """ + Sets the raw value on the settings for `path`. + + Arguments: + path (list, tuple): The path for which to set the value. + value (object): The value to set. + force (bool): If set to True, the modified configuration will be written back to disk even if + the value didn't change. + """ + return self.settings.set( + self._prefix_path(path), value, **self._add_setter_kwargs(kwargs) + ) + + def set_int(self, path, value, **kwargs): + """ + Like `set` but ensures the value is an [int][] through attempted conversion before setting it. + + If `min` and/or `max` are provided, it will also be ensured that the value is greater than or equal + to `min` and less than or equal to `max`. If that is not the case, the limit value (`min` if less than + that, `max` if greater than that) will be set instead. + + Arguments: + path (list, tuple): The path for which to set the value. + value (object): The value to set. + min (int): The minimum value to set. + max (int): The maximum value to set. + """ + return self.settings.setInt( + self._prefix_path(path), value, **self._add_setter_kwargs(kwargs) + ) + + def set_float(self, path, value, **kwargs): + """ + Like `set` but ensures the value is an [float][] through attempted conversion before setting it. + + If `min` and/or `max` are provided, it will also be ensured that the value is greater than or equal + to `min` and less than or equal to `max`. If that is not the case, the limit value (`min` if less than + that, `max` if greater than that) will be set instead. + + Arguments: + path (list, tuple): The path for which to set the value. + value (object): The value to set. + min (float): The minimum value to set. + max (float): The maximum value to set. + """ + return self.settings.setFloat( + self._prefix_path(path), value, **self._add_setter_kwargs(kwargs) + ) + + def set_boolean(self, path, value, **kwargs): + """ + Like `set` but ensures the value is an [bool][] through attempted conversion before setting it. + + Arguments: + path (list, tuple): The path for which to set the value. + value (object): The value to set. + """ + return self.settings.setBoolean( + self._prefix_path(path), value, **self._add_setter_kwargs(kwargs) + ) + + def remove(self, path, **kwargs): + """ + Removes the value for `path` from the settings. + + Arguments: + path (list, tuple): The path for which to remove the value. + """ + return self.settings.remove(self._prefix_path(path), **kwargs) + + def add_overlay(self, overlay, **kwargs): + """ + Adds an overlay for th plugin to the settings. + + Arguments: + overlay (dict): The overlay to add. + + Returns: + (str): The key under which the overlay was added. + """ + return self.settings.add_overlay(self._wrap_overlay(overlay), **kwargs) + + def remove_overlay(self, key): + """ + Removes an overlay from the settings by `key`. + + Arguments: + key (str): The key of the overlay to remove. + """ + return self.settings.remove_overlay(key) + def global_has(self, path, **kwargs): + """ + Checks whether the global settings structure has a value for `path`. + + Directly forwards to [octoprint.settings.Settings.has][]. + """ return self.settings.has(path, **kwargs) def global_remove(self, path, **kwargs): + """ + Removes the value for `path` from the global settings structure. + + Directly forwards to [octoprint.settings.Settings.remove][]. + """ return self.settings.remove(path, **kwargs) def global_get(self, path, **kwargs): """ - Getter for retrieving settings not managed by the plugin itself from the core settings structure. Use this - to access global settings outside of your plugin. + Gets a value from the global settings structure. - Directly forwards to :func:`octoprint.settings.Settings.get`. + Directly forwards to [octoprint.settings.Settings.get][]. See its documentation for possible + parameters. """ return self.settings.get(path, **kwargs) def global_get_int(self, path, **kwargs): """ - Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getInt`. + Gets a value from the global settings structure and tries to convert it to [int][]. + + Directly forwards to [octoprint.settings.Settings.getInt][]. See its documentation for possible + parameters. """ return self.settings.getInt(path, **kwargs) def global_get_float(self, path, **kwargs): """ - Like :func:`global_get` but directly forwards to :func:`octoprint.settings.Settings.getFloat`. + Gets a value from the global settings structure and tries to convert it to [float][]. + + Directly forwards to [octoprint.settings.Settings.getFloat][]. See its documentation for possible + parameters. """ return self.settings.getFloat(path, **kwargs) def global_get_boolean(self, path, **kwargs): """ - Like :func:`global_get` but directly orwards to :func:`octoprint.settings.Settings.getBoolean`. + Gets a value from the global settings structure and tries to convert it to [bool][]. + + Directly forwards to [octoprint.settings.Settings.getBoolean][]. See its documentation for possible + parameters. """ return self.settings.getBoolean(path, **kwargs) def global_set(self, path, value, **kwargs): """ - Setter for modifying settings not managed by the plugin itself on the core settings structure. Use this - to modify global settings outside of your plugin. + Sets a value in the global settings structure. - Directly forwards to :func:`octoprint.settings.Settings.set`. + Directly forwards to [octoprint.settings.Settings.set][]. See its documentation for possible + parameters. """ self.settings.set(path, value, **kwargs) def global_set_int(self, path, value, **kwargs): """ - Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setInt`. + Sets a value in the global settings structure and tries to convert it to [int][]. + + Directly forwards to [octoprint.settings.Settings.setInt][]. See its documentation for possible + parameters. """ self.settings.setInt(path, value, **kwargs) def global_set_float(self, path, value, **kwargs): """ - Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setFloat`. + Sets a value in the global settings structure and tries to convert it to [float][]. + + Directly forwards to [octoprint.settings.Settings.setFloat][]. See its documentation for possible + parameters. """ self.settings.setFloat(path, value, **kwargs) def global_set_boolean(self, path, value, **kwargs): """ - Like :func:`global_set` but directly forwards to :func:`octoprint.settings.Settings.setBoolean`. + Sets a value in the global settings structure and tries to convert it to [bool][]. + + Directly forwards to [octoprint.settings.Settings.setBoolean][]. See its documentation for possible + parameters. """ self.settings.setBoolean(path, value, **kwargs) def global_get_basefolder(self, folder_type, **kwargs): """ - Retrieves a globally defined basefolder of the given ``folder_type``. Directly forwards to - :func:`octoprint.settings.Settings.getBaseFolder`. + Retrieves a globally defined basefolder of the given `folder_type`. + + Directly forwards to [octoprint.settings.Settings.getBaseFolder][]. """ return self.settings.getBaseFolder(folder_type, **kwargs) def get_plugin_logfile_path(self, postfix=None): """ - Retrieves the path to a logfile specifically for the plugin. If ``postfix`` is not supplied, the logfile - will be named ``plugin_.log`` and located within the configured ``logs`` folder. If a - postfix is supplied, the name will be ``plugin__.log`` at the same location. + Retrieves the path to a logfile specifically for the plugin. - Plugins may use this for specific logging tasks. For example, a :class:`~octoprint.plugin.SlicingPlugin` might + If `postfix` is not supplied, the logfile will be named `plugin_.log` and located within the + configured `logs` folder. If a postfix is supplied, the name will be `plugin__.log` + at the same location. + + Plugins may use this for specific logging tasks. For example, a [octoprint.plugin.types.SlicerPlugin][] might want to create a log file for logging the output of the slicing engine itself if some debug flag is set. Arguments: postfix (str): Postfix of the logfile for which to create the path. If set, the file name of the log file - will be ``plugin__.log``, if not it will be - ``plugin_.log``. + will be `plugin__.log`, if not it will be `plugin_.log`. Returns: - str: Absolute path to the log file, directly usable by the plugin. + (str): Absolute path to the log file, directly usable by the plugin. """ filename = "plugin_" + self.plugin_key if postfix is not None: @@ -579,7 +661,58 @@ class PluginSettings: os.makedirs(path) return path + @deprecated( + "getInt has been renamed to get_int", + includedoc="Replaced by [octoprint.plugin.types.OctoPrintPlugin.get_int][]", + ) + def getInt(self, *args, **kwargs): + return self.get_int(*args, **kwargs) + + @deprecated( + "getFloat has been renamed to get_float", + includedoc="Replaced by [octoprint.plugin.types.OctoPrintPlugin.get_float][]", + ) + def getFloat(self, *args, **kwargs): + return self.get_float(*args, **kwargs) + + @deprecated( + "getBoolean has been renamed to get_boolean", + includedoc="Replaced by [octoprint.plugin.types.OctoPrintPlugin.get_boolean][]", + ) + def getBoolean(self, *args, **kwargs): + return self.get_boolean(*args, **kwargs) + + @deprecated( + "setInt has been renamed to set_int", + includedoc="Replaced by [octoprint.plugin.types.OctoPrintPlugin.set_int][]", + ) + def setInt(self, *args, **kwargs): + return self.set_int(*args, **kwargs) + + @deprecated( + "setFloat has been renamed to set_float", + includedoc="Replaced by [octoprint.plugin.types.OctoPrintPlugin.set_float][]", + ) + def setFloat(self, *args, **kwargs): + return self.set_float(*args, **kwargs) + + @deprecated( + "setBoolean has been renamed to set_boolean", + includedoc="Replaced by [octoprint.plugin.types.OctoPrintPlugin.set_boolean][]", + ) + def setBoolean(self, *args, **kwargs): + return self.set_boolean(*args, **kwargs) + def get_all_data(self, **kwargs): + """ + Returns all data stored for this plugin. + + Arguments: + merged (bool): Whether to merge the data with the defaults. Defaults to `True`. + asdict (bool): Whether to return the data as a dict. Defaults to `True`. + defaults (bool): Which defaults to use. Defaults to the plugin defaults. + preprocessors (list): List of preprocessors to apply to the data. Defaults to the plugin preprocessors. + """ merged = kwargs.get("merged", True) asdict = kwargs.get("asdict", True) defaults = kwargs.get("defaults", self.defaults) @@ -597,36 +730,7 @@ class PluginSettings: return self.settings.get(self._prefix_path(), **kwargs) def clean_all_data(self): + """ + Removes all data stored for this plugin. + """ self.settings.remove(self._prefix_path()) - - def __getattr__(self, item): - all_access_methods = list(self.access_methods.keys()) + list( - self.deprecated_access_methods.keys() - ) - if item in all_access_methods: - decorator = None - if item in self.deprecated_access_methods: - new = self.deprecated_access_methods[item] - decorator = deprecated( - f"{item} has been renamed to {new}", - stacklevel=2, - ) - item = new - - settings_name, args_mapper, kwargs_mapper = self.access_methods[item] - if hasattr(self.settings, settings_name) and callable( - getattr(self.settings, settings_name) - ): - orig_func = getattr(self.settings, settings_name) - if decorator is not None: - orig_func = decorator(orig_func) - - def _func(*args, **kwargs): - return orig_func(*args_mapper(args), **kwargs_mapper(kwargs)) - - _func.__name__ = item - _func.__doc__ = orig_func.__doc__ if "__doc__" in dir(orig_func) else None - - return _func - - return getattr(self.settings, item) diff --git a/src/octoprint/plugin/core.py b/src/octoprint/plugin/core.py index 297386e4a..77a74bff7 100644 --- a/src/octoprint/plugin/core.py +++ b/src/octoprint/plugin/core.py @@ -1,21 +1,5 @@ """ In this module resides the core data structures and logic of the plugin system. - -.. autoclass:: PluginManager - :members: - -.. autoclass:: PluginInfo - :members: - -.. autoclass:: Plugin - :members: - -.. autoclass:: RestartNeedingPlugin - :members: - -.. autoclass:: SortablePlugin - :members: - """ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" @@ -26,7 +10,7 @@ import fnmatch import inspect import logging import os -from collections import OrderedDict, defaultdict, namedtuple +from collections import OrderedDict, defaultdict from os import scandir import pkg_resources @@ -53,6 +37,36 @@ def _load_module(name, spec): def parse_plugin_metadata(path): + """ + Parses the plugin metadata from the plugin at the given path. + + If the provided path is a dictionary, it is assumed to be the path to a Python module with a contained `__init__.py`. + + The metadata is parsed from the AST of the plugin's Python source. If the plugin could not be parsed due to a syntax + error in its Python source, a `SyntaxError` is raised. + + Only the following control properties are attempted to be parsed from the AST: + + - `__plugin_name__` + - `__plugin_version__` + - `__plugin_author__` + - `__plugin_description__` + - `__plugin_url__` + - `__plugin_license__` + - `__plugin_pythoncompatibility__` + + This is also the list of plugin metadata available even for disabled/unloaded plugins. For all other control + properties to be available, the plugin must be loaded by OctoPrint. + + Arguments: + path (str): The path to the plugin to parse the metadata from. + + Returns: + (dict): The parsed metadata. If no metadata could be parsed, an empty dictionary is returned. + + Raises: + (SyntaxError): If the plugin could not be parsed due to a syntax error in its Python source. + """ result = {} logger = logging.getLogger(__name__) @@ -157,28 +171,28 @@ def parse_plugin_metadata(path): class ControlProperties: attr_name = "__plugin_name__" - """ Module attribute from which to retrieve the plugin's human readable name. """ + """Module attribute from which to retrieve the plugin's human readable name.""" attr_description = "__plugin_description__" - """ Module attribute from which to retrieve the plugin's description. """ + """Module attribute from which to retrieve the plugin's description.""" attr_disabling_DISCOURAGED = "__plugin_disabling_discouraged__" - """ Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True. """ + """Module attribute from which to retrieve the reason why disabling the plugin is discouraged. Only effective if ``self.bundled`` is True.""" attr_version = "__plugin_version__" - """ Module attribute from which to retrieve the plugin's version. """ + """Module attribute from which to retrieve the plugin's version.""" attr_author = "__plugin_author__" - """ Module attribute from which to retrieve the plugin's author. """ + """Module attribute from which to retrieve the plugin's author.""" attr_url = "__plugin_url__" - """ Module attribute from which to retrieve the plugin's website URL. """ + """Module attribute from which to retrieve the plugin's website URL.""" attr_license = "__plugin_license__" - """ Module attribute from which to retrieve the plugin's license. """ + """Module attribute from which to retrieve the plugin's license.""" attr_privacypolicy = "__plugin_privacypolicy__" - """ Module attribute from which to retrieve the plugin's privacy policy URL, if any. """ + """Module attribute from which to retrieve the plugin's privacy policy URL, if any.""" attr_pythoncompat = "__plugin_pythoncompat__" """ @@ -201,119 +215,105 @@ class ControlProperties: """ attr_hooks = "__plugin_hooks__" - """ Module attribute from which to retrieve the plugin's provided hooks. """ + """Module attribute from which to retrieve the plugin's provided hooks.""" attr_implementation = "__plugin_implementation__" - """ Module attribute from which to retrieve the plugin's provided mixin implementation. """ + """Module attribute from which to retrieve the plugin's provided mixin implementation.""" attr_helpers = "__plugin_helpers__" - """ Module attribute from which to retrieve the plugin's provided helpers. """ + """Module attribute from which to retrieve the plugin's provided helpers.""" attr_check = "__plugin_check__" - """ Module attribute which to call to determine if the plugin can be loaded. """ + """Module attribute which to call to determine if the plugin can be loaded.""" attr_load = "__plugin_load__" - """ Module attribute which to call when loading the plugin. """ + """Module attribute which to call when loading the plugin.""" attr_unload = "__plugin_unload__" - """ Module attribute which to call when unloading the plugin. """ + """Module attribute which to call when unloading the plugin.""" attr_enable = "__plugin_enable__" - """ Module attribute which to call when enabling the plugin. """ + """Module attribute which to call when enabling the plugin.""" attr_disable = "__plugin_disable__" - """ Module attribute which to call when disabling the plugin. """ + """Module attribute which to call when disabling the plugin.""" default_pythoncompat = ">=2.7,<3" + """Module attribute from which to retrieve the plugin's python compatibility string.""" @classmethod def all(cls): + """ + Returns a list of all recognized control properties, as defined in this class. + """ return [getattr(cls, key) for key in dir(cls) if key.startswith("attr_")] -_EntryPointOrigin = namedtuple( - "EntryPointOrigin", "type, entry_point, module_name, package_name, package_version" -) - - -class EntryPointOrigin(_EntryPointOrigin): +class EntryPointOrigin: """ Origin of a plugin registered via an entry point. - - .. attribute:: type - - Always ``entry_point``. - - .. attribute:: entry_point - - Name of the entry point, usually ``octoprint.plugin``. - - .. attribute:: module_name - - Module registered to the entry point. - - .. attribute:: package_name - - Python package containing the entry point. - - .. attribute:: package_version - - Version of the python package containing the entry point. """ + def __init__(self, type, entry_point, module_name, package_name, package_version): + self.type = type + """Always `entry_point`.""" -_FolderOrigin = namedtuple("FolderOrigin", "type, folder") + self.entry_point = entry_point + """Name of the entry point, usually `octoprint.plugin`.""" + + self.module_name = module_name + """Module registered to the entry point.""" + + self.package_name = package_name + """Python package containing the entry point.""" + + self.package_version = package_version + """Version of the python package containing the entry point.""" -class FolderOrigin(_FolderOrigin): +class FolderOrigin: """ Origin of a (single file) plugin loaded from a plugin folder. - - .. attribute:: type - - Always `folder`. - - .. attribute:: folder - - Folder path from which the plugin was loaded. """ + def __init__(self, type, folder): + self.type = type + """Always `folder`.""" -_ModuleOrigin = namedtuple("ModuleOrigin", "type, module_name, folder") + self.folder = folder + """Folder path from which the plugin was loaded.""" -class ModuleOrigin(_ModuleOrigin): +class ModuleOrigin: """ Origin of a (single file) plugin loaded from a plugin folder. - - .. attribute:: type - - Always `module`. - - .. attribute:: module_name - - Name of the module from which the plugin was loaded. - - .. attribute:: folder - - Folder path from which the plugin was loaded. """ + def __init__(self, type, module_name, folder): + self.type = type + """Always `module`.""" + + self.module_name = module_name + """Name of the module from which the plugin was loaded.""" + + self.folder = folder + """Folder path from which the plugin was loaded.""" + class PluginInfo: """ - The :class:`PluginInfo` class wraps all available information about a registered plugin. + The `PluginInfo` class wraps all available information about a registered plugin. - This includes its meta data (like name, description, version, etc) as well as the actual plugin extensions like - implementations, hooks and helpers. + This includes its metadata (like name, description, version, etc) as well as the actual plugin extensions like + implementation, hooks and helpers. It works on Python module objects and extracts the relevant data from those via accessing the - :ref:`control properties `. + control properties. Arguments: key (str): Identifier of the plugin location (str): Installation folder of the plugin - instance (module): Plugin module instance - this may be ``None`` if the plugin has been blacklisted! + instance (module): Plugin module instance - this may be `None` if the plugin has been blacklisted! name (str): Human readable name of the plugin version (str): Version of the plugin description (str): Description of the plugin @@ -341,8 +341,8 @@ class PluginInfo: self.origin = None """ - The origin from which this plugin was loaded, either a :class:`EntryPointOrigin`, :class:`FolderOrigin` - or :class:`ModuleOrigin` instance. Set during loading, initially ``None``. + The origin from which this plugin was loaded, either a [octoprint.plugin.core.EntryPointOrigin][], [octoprint.plugin.core.FolderOrigin][] + or [octoprint.plugin.core.ModuleOrigin] instance. Set during loading, initially `None`. """ self.enabled = True @@ -389,9 +389,18 @@ class PluginInfo: """ Validates the plugin for various validation phases. - ``phase`` can be one of ``before_import``, ``before_load``, ``after_load``. + `phase` can be one of `before_import`, `before_load`, `after_load`. - Used by :class:`PluginManager`, should not be used elsewhere. + Used by [octoprint.plugin.core.PluginManager][], should not be used elsewhere. + + Arguments: + phase (str): Phase to validate for, one of `before_import`, `before_load`, `after_load` + additional_validators (list): List of additional validator functions to call, each of which should accept + two arguments, `phase` and `plugin_info`, and return a boolean indicating whether the plugin should + be considered valid for the given phase. + + Returns: + (bool): Whether the plugin is valid for the given phase. """ result = True @@ -433,32 +442,32 @@ class PluginInfo: enabled_strs=("* ", " ", "X ", "C "), ): """ - Long string representation of the plugin's information. Will return a string of the format ````. + Long string representation of the plugin's information. Will return a string of the format ``. - ``enabled``, ``bundled`` and ``location`` will only be displayed if the corresponding flags are set to ``True``. - The will be filled from ``enabled_str``, ``bundled_str`` and ``location_str`` as follows: + `enabled`, `bundled` and `location` will only be displayed if the corresponding flags are set to `True`. + They will be filled from `enabled_str`, `bundled_str` and `location_str` as follows: - ``enabled_str`` - a 4-tuple, the first entry being the string to insert when the plugin is enabled, the second + `enabled_str` + : a 4-tuple, the first entry being the string to insert when the plugin is enabled, the second entry the string to insert when it is not, the third entry the string when it is blacklisted - and the fourth when it is incompatible. - ``bundled_str`` - a 2-tuple, the first entry being the string to insert when the plugin is bundled, the second - entry the string to insert when it is not. - ``location_str`` - a format string (to be parsed with ``str.format``), the ``{location}`` placeholder will be - replaced with the plugin's installation folder on disk. + and the fourth when it is incompatible. Example: `("* ", " ", "X ", "C ")` + `bundled_str` + : a 2-tuple, the first entry being the string to insert when the plugin is bundled, the second + entry the string to insert when it is not. Example: `(" [B]", "")` + `location_str` + : a format string (to be parsed with `str.format`), the `{location}` placeholder will be + replaced with the plugin's installation folder on disk. Example: `" - {location}"` Arguments: - show_enabled (boolean): whether to show the ``enabled`` part + show_enabled (boolean): whether to show the `enabled` part enabled_strs (tuple): the 2-tuple containing the two possible strings to use for displaying the enabled state - show_bundled (boolean): whether to show the ``bundled`` part + show_bundled (boolean): whether to show the `bundled` part bundled_strs(tuple): the 2-tuple containing the two possible strings to use for displaying the bundled state - show_location (boolean): whether to show the ``location`` part + show_location (boolean): whether to show the `location` part location_str (str): the format string to use for displaying the plugin's installation location Returns: - str: The long string representation of the plugin as described above + (str): The long string representation of the plugin as described above """ if show_enabled: if self.incompatible: @@ -492,7 +501,7 @@ class PluginInfo: hook (str): Hook to return. Returns: - callable or None: Handler for the requested ``hook`` or None if no handler is registered. + (callable | None): Handler for the requested `hook`, or `None` if no handler is registered. """ if hook not in self.hooks: @@ -501,11 +510,13 @@ class PluginInfo: def get_implementation(self, *types): """ + Returns the plugin's implementation if it matches all of the requested `types`, `None` otherwise. + Arguments: - types (list): List of :class:`Plugin` sub classes the implementation needs to implement. + types (list): List of [octoprint.plugin.core.Plugin][] sub classes the implementation needs to implement. Returns: - object: The plugin's implementation if it matches all of the requested ``types``, None otherwise. + (object | None): The plugin's implementation if it matches all of the requested `types`, `None` otherwise. """ if self.implementation and all( @@ -518,11 +529,13 @@ class PluginInfo: @property def name(self): """ - Human readable name of the plugin. Will be taken from name attribute of the plugin module if available, - otherwise from the ``name`` supplied during construction with a fallback to ``key``. + Human readable name of the plugin. + + Will be taken from the name attribute of the plugin module if available, otherwise from the + `name` supplied during construction with a fallback to `key`. Returns: - str: Name of the plugin, fallback is the plugin's identifier. + (str): Name of the plugin, fallback is the plugin's identifier. """ return self._get_instance_attribute( ControlProperties.attr_name, @@ -533,12 +546,13 @@ class PluginInfo: @property def description(self): """ - Description of the plugin. Will be taken from the description attribute of the plugin module as defined in - :attr:`attr_description` if available, otherwise from the ``description`` supplied during construction. - May be None. + Description of the plugin. + + Will be taken from the description attribute of the plugin module if available, otherwise from the + `description` supplied during construction. May be `None`. Returns: - str or None: Description of the plugin. + (str | None): Description of the plugin. """ return self._get_instance_attribute( ControlProperties.attr_description, @@ -549,12 +563,15 @@ class PluginInfo: @property def disabling_discouraged(self): """ - Reason why disabling of this plugin is discouraged. Only evaluated for bundled plugins! Will be taken from - the disabling_discouraged attribute of the plugin module as defined in :attr:`attr_disabling_discouraged` if - available. False if unset or plugin not bundled. + Reason why disabling this plugin is discouraged. + + Only evaluated for bundled plugins! + + Will be taken from the `disabling_discouraged` attribute of the plugin module if + available. `False` if unset or plugin not bundled. Returns: - str or None: Reason why disabling this plugin is discouraged (only for bundled plugins) + (str | bool): Reason why disabling this plugin is discouraged (only for bundled plugins) """ return ( self._get_instance_attribute( @@ -567,11 +584,13 @@ class PluginInfo: @property def version(self): """ - Version of the plugin. Will be taken from the version attribute of the plugin module as defined in - :attr:`attr_version` if available, otherwise from the ``version`` supplied during construction. May be None. + Version of the plugin. + + Will be taken from the version attribute of the plugin module if available, otherwise from the + `version` supplied during construction. May be `None`. Returns: - str or None: Version of the plugin. + (str | None): Version of the plugin. """ return ( self._version @@ -586,11 +605,13 @@ class PluginInfo: @property def author(self): """ - Author of the plugin. Will be taken from the author attribute of the plugin module as defined in - :attr:`attr_author` if available, otherwise from the ``author`` supplied during construction. May be None. + Author of the plugin. + + Will be taken from the author attribute of the plugin module if available, otherwise from the + `author` supplied during construction. May be `None`. Returns: - str or None: Author of the plugin. + (str | None): Author of the plugin. """ return self._get_instance_attribute( ControlProperties.attr_author, default=self._author, incl_metadata=True @@ -599,11 +620,13 @@ class PluginInfo: @property def url(self): """ - Website URL for the plugin. Will be taken from the url attribute of the plugin module as defined in - :attr:`attr_url` if available, otherwise from the ``url`` supplied during construction. May be None. + Website URL for the plugin. + + Will be taken from the url attribute of the plugin module if available, otherwise from the + `url` supplied during construction. May be `None`. Returns: - str or None: Website URL for the plugin. + (str | None): Website URL for the plugin. """ return self._get_instance_attribute( ControlProperties.attr_url, default=self._url, incl_metadata=True @@ -612,11 +635,13 @@ class PluginInfo: @property def license(self): """ - License of the plugin. Will be taken from the license attribute of the plugin module as defined in - :attr:`attr_license` if available, otherwise from the ``license`` supplied during construction. May be None. + License of the plugin. + + Will be taken from the license attribute of the plugin module if available, otherwise from the + `license` supplied during construction. May be `None`. Returns: - str or None: License of the plugin. + (str | None): License of the plugin. """ return self._get_instance_attribute( ControlProperties.attr_license, default=self._license, incl_metadata=True @@ -625,11 +650,12 @@ class PluginInfo: @property def privacypolicy(self): """ - Privacy Policy URL of the plugin. Will be taken from the privacy policy attribute of the plugin module - as defined in :attr:`attr_privacypolicy` if available. May be None. + Privacy Policy URL of the plugin. + + Will be taken from the privacy policy attribute of the plugin module if available. May be `None`. Returns: - str or None: Privacy Policy URL of the plugin. + (str | None): Privacy Policy URL of the plugin. """ return self._get_instance_attribute( ControlProperties.attr_privacypolicy, default=None, incl_metadata=True @@ -638,11 +664,10 @@ class PluginInfo: @property def pythoncompat(self): """ - Python compatibility string of the plugin module as defined in :attr:`attr_pythoncompat` if available, otherwise - defaults to ``>=2.7,<3``. + Python compatibility string of the plugin module if available, otherwise defaults to ``>=2.7,<3``. Returns: - str: Python compatibility string of the plugin + (str): Python compatibility string of the plugin """ return self._get_instance_attribute( ControlProperties.attr_pythoncompat, default=">=2.7,<3", incl_metadata=True @@ -653,8 +678,10 @@ class PluginInfo: """ Hidden flag. + Will be taken from the hidden attribute of the plugin module if available, otherwise defaults to `False`. + Returns: - bool: Whether the plugin should be flagged as hidden or not + (bool): Whether the plugin should be flagged as hidden or not """ return self._get_instance_attribute( ControlProperties.attr_hidden, default=False, incl_metadata=True @@ -663,22 +690,24 @@ class PluginInfo: @property def hooks(self): """ - Hooks provided by the plugin. Will be taken from the hooks attribute of the plugin module as defined in - :attr:`attr_hooks` if available, otherwise an empty dictionary is returned. + Hooks provided by the plugin. + + Will be taken from the hooks attribute of the plugin module if available, otherwise an empty dictionary is returned. Returns: - dict: Hooks provided by the plugin. + (dict): Hooks provided by the plugin, mapping from hook name to handler [callable][]. """ return self._get_instance_attribute(ControlProperties.attr_hooks, default={}) @property def implementation(self): """ - Implementation provided by the plugin. Will be taken from the implementation attribute of the plugin module - as defined in :attr:`attr_implementation` if available, otherwise None is returned. + Implementation provided by the plugin. + + Will be taken from the implementation attribute of the plugin module if available, otherwise `None` is returned. Returns: - object: Implementation provided by the plugin. + (object | None): Implementation provided by the plugin. """ return self._get_instance_attribute( ControlProperties.attr_implementation, default=None @@ -687,22 +716,23 @@ class PluginInfo: @property def helpers(self): """ - Helpers provided by the plugin. Will be taken from the helpers attribute of the plugin module as defined in - :attr:`attr_helpers` if available, otherwise an empty list is returned. + Helpers provided by the plugin. + + Will be taken from the helpers attribute of the plugin module if available, otherwise an empty dictionary is returned. Returns: - dict: Helpers provided by the plugin. + (dict): Helpers provided by the plugin, mapping from helper name to helper [callable][]. """ return self._get_instance_attribute(ControlProperties.attr_helpers, default={}) @property def check(self): """ - Method for pre-load check of plugin. Will be taken from the check attribute of the plugin module as defined in - :attr:`attr_check` if available, otherwise a lambda always returning True is returned. + Method for pre-load check of plugin. Will be taken from the check attribute of the plugin module if available, + otherwise a lambda always returning True is returned. Returns: - callable: Check method for the plugin module which should return True if the plugin can be loaded, False + (callable): Check method for the plugin module which should return True if the plugin can be loaded, False otherwise. """ return self._get_instance_attribute( @@ -712,11 +742,11 @@ class PluginInfo: @property def load(self): """ - Method for loading the plugin module. Will be taken from the load attribute of the plugin module as defined - in :attr:`attr_load` if available, otherwise a no-operation lambda will be returned. + Method for loading the plugin module. Will be taken from the load attribute of the plugin module if available, + otherwise a no-operation lambda will be returned. Returns: - callable: Load method for the plugin module. + (callable): Load method for the plugin module. """ return self._get_instance_attribute( ControlProperties.attr_load, default=lambda: True @@ -725,11 +755,11 @@ class PluginInfo: @property def unload(self): """ - Method for unloading the plugin module. Will be taken from the unload attribute of the plugin module as defined - in :attr:`attr_unload` if available, otherwise a no-operation lambda will be returned. + Method for unloading the plugin module. Will be taken from the unload attribute of the plugin module if available, + otherwise a no-operation lambda will be returned. Returns: - callable: Unload method for the plugin module. + (callable): Unload method for the plugin module. """ return self._get_instance_attribute( ControlProperties.attr_unload, default=lambda: True @@ -738,11 +768,11 @@ class PluginInfo: @property def enable(self): """ - Method for enabling the plugin module. Will be taken from the enable attribute of the plugin module as defined - in :attr:`attr_enable` if available, otherwise a no-operation lambda will be returned. + Method for enabling the plugin module. Will be taken from the enable attribute of the plugin module if available, + otherwise a no-operation lambda will be returned. Returns: - callable: Enable method for the plugin module. + (callable): Enable method for the plugin module. """ return self._get_instance_attribute( ControlProperties.attr_enable, default=lambda: True @@ -751,11 +781,11 @@ class PluginInfo: @property def disable(self): """ - Method for disabling the plugin module. Will be taken from the disable attribute of the plugin module as defined - in :attr:`attr_disable` if available, otherwise a no-operation lambda will be returned. + Method for disabling the plugin module. Will be taken from the disable attribute of the plugin module if available, + otherwise a no-operation lambda will be returned. Returns: - callable: Disable method for the plugin module. + (callable): Disable method for the plugin module. """ return self._get_instance_attribute( ControlProperties.attr_disable, default=lambda: True @@ -786,6 +816,7 @@ class PluginInfo: @property def control_properties(self): + """The control properties recognized in the plugin's AST.""" return ControlProperties.all() @property @@ -806,7 +837,7 @@ class PluginInfo: class PluginManager: """ - The :class:`PluginManager` is the central component for finding, loading and accessing plugins provided to the + The `PluginManager` is the central component for finding, loading and accessing plugins provided to the system. It is able to discover plugins both through possible file system locations as well as customizable entry points. @@ -943,6 +974,17 @@ class PluginManager: } def find_plugins(self, existing=None, ignore_uninstalled=True, incl_all_found=False): + """ + Run the plugin discovery process and return the added plugins. + + Arguments: + existing (dict): Existing plugins to check against + ignore_uninstalled (bool): Ignore plugins marked as uninstalled + incl_all_found (bool): Return all found plugins, not just the added ones + + Returns: + (dict | tuple): Dictionary of added plugins or tuple of added (`dict`) and all found (`list`) plugins + """ added, found = self._find_plugins( existing=existing, ignore_uninstalled=ignore_uninstalled ) @@ -1351,10 +1393,12 @@ class PluginManager: """ Reloads plugins, detecting newly added ones in the process. - Args: - startup (boolean): whether this is called during startup of the platform - initialize_implementations (boolean): whether plugin implementations should be initialized - force_reload (list): list of plugin identifiers which should be force reloaded + Logs the currently detected plugins and their status. + + Arguments: + startup (boolean): whether this is called during startup of the platform + initialize_implementations (boolean): whether plugin implementations should be initialized + force_reload (list): list of plugin identifiers which should be force reloaded """ self.logger.info( "Loading plugins from {folders} and installed plugin packages...".format( @@ -1465,11 +1509,11 @@ class PluginManager: def mark_plugin(self, name, **flags): """ - Mark plugin ``name`` with an arbitrary number of flags. + Mark plugin `name` with an arbitrary number of flags. - Args: - name (str): plugin identifier - **flags (dict): dictionary of flag names and values + Arguments: + name (str): plugin identifier + flags (dict): dictionary of flag names and values """ if name not in self.plugins: self.logger.debug(f"Trying to mark an unknown plugin {name}") @@ -1487,12 +1531,12 @@ class PluginManager: """ Checks whether a plugin has been marked with a certain flag. - Args: - name (str): the plugin's identifier - flag (str): the flag to check + Arguments: + name (str): the plugin's identifier + flag (str): the flag to check Returns: - (boolean): True if the plugin has been flagged, False otherwise + (bool): `True` if the plugin has been flagged, `False` otherwise """ if name not in self.plugins: return False @@ -1502,6 +1546,18 @@ class PluginManager: def load_plugin( self, name, plugin=None, startup=False, initialize_implementation=True ): + """ + Loads plugin `name`, triggering all lifecycle events as needed. + + Arguments: + name (str): plugin identifier + plugin (octoprint.plugin.core.Plugin): plugin instance + startup (bool): whether this is called during startup of the platform + initialize_implementation (bool): whether plugin implementations should be initialized + + Raises: + (octoprint.plugin.core.PluginLifecycleException): if any of the lifecycle events fail + """ if name not in self.plugins: self.logger.warning(f"Trying to load an unknown plugin {name}") return @@ -1527,6 +1583,16 @@ class PluginManager: self.logger.exception("There was an error loading plugin %s" % name) def unload_plugin(self, name): + """ + Unloads plugin `name`, triggering all lifecycle events as needed. + + Arguments: + name (str): plugin identifier + + Raises: + (octoprint.plugin.core.PluginLifecycleException): if any of the lifecycle events fail, in which case + the plugin will be ensured to be marked as disabled + """ if name not in self.plugins: self.logger.warning(f"Trying to unload unknown plugin {name}") return @@ -1563,7 +1629,24 @@ class PluginManager: def enable_plugin( self, name, plugin=None, initialize_implementation=True, startup=False ): - """Enables a plugin""" + """ + Enables a plugin. + + Arguments: + name (str): plugin identifier + plugin (octoprint.plugin.core.Plugin): plugin instance + initialize_implementation (bool): whether plugin implementations should be initialized + startup (bool): whether this is called during startup of the platform + + Returns: + (bool): `True` if the plugin was enabled, `False` otherwise + + Raises: + (octoprint.plugin.core.PluginNeedsRestart): if the plugin needs a server restart to get enabled + (octoprint.plugin.core.PluginCantEnable): if the plugin cannot be enabled due to obsolete hooks + (octoprint.plugin.core.PluginLifecycleException): if anything fails during validation or activation + of the plugin + """ if name not in self.disabled_plugins: self.logger.warning( f"Tried to enable plugin {name}, however it is not disabled" @@ -1613,7 +1696,17 @@ class PluginManager: return True def disable_plugin(self, name, plugin=None): - """Disables a plugin""" + """ + Disables a plugin. + + Arguments: + name (str): plugin identifier + plugin (octoprint.plugin.core.Plugin): plugin instance + + Raises: + (octoprint.plugin.core.PluginNeedsRestart): if the plugin needs a server restart to get disabled + (octoprint.plugin.core.PluginLifecycleException): if anything fails during deactivation + """ if name not in self.enabled_plugins: self.logger.warning( f"Tried to disable plugin {name}, however it is not enabled" @@ -1740,7 +1833,15 @@ class PluginManager: pass def is_restart_needing_plugin(self, plugin): - """Checks whether the plugin needs a restart on changes""" + """ + Checks whether the plugin needs a restart on changes. + + Arguments: + plugin (octoprint.plugin.core.Plugin): plugin instance + + Returns: + (bool): `True` if the plugin needs a server restart on changes, `False` otherwise + """ return ( plugin.needs_restart or self.has_restart_needing_implementation(plugin) @@ -1748,39 +1849,79 @@ class PluginManager: ) def has_restart_needing_implementation(self, plugin): - """Checks whether the plugin's implementation needs a restart on changes""" + """ + Checks whether the plugin's implementation needs a restart on changes. + + Arguments: + plugin (octoprint.plugin.core.Plugin): plugin instance + + Returns: + (bool): `True` if the plugin's implementation needs a server restart on changes, `False` otherwise + """ return self.has_any_of_mixins(plugin, RestartNeedingPlugin) def has_restart_needing_hooks(self, plugin): - """Checks whether the plugin has any hooks that need a restart on changes""" + """ + Checks whether the plugin has any hooks that need a restart on changes. + + Arguments: + plugin (octoprint.plugin.core.Plugin): plugin instance + + Returns: + (bool): `True` if the plugin has any hooks that need a server restart on changes, `False` otherwise + """ return self.has_any_of_hooks(plugin, self.plugin_restart_needing_hooks) def has_obsolete_hooks(self, plugin): - """Checks whether the plugin uses any obsolete hooks""" + """ + Checks whether the plugin uses any of the defined obsolete hooks. + + Arguments: + plugin (octoprint.plugin.core.Plugin): plugin instance + + Returns: + (bool): `True` if the plugin uses any of the defined obsolete hooks, `False` otherwise + """ return self.has_any_of_hooks(plugin, self.plugin_obsolete_hooks) def is_restart_needing_hook(self, hook): - """Checks whether a hook needs a restart on changes""" + """ + Checks whether a hook needs a restart on changes. + + Arguments: + hook (str): hook to check + + Returns: + (bool): `True` if the hook needs a server restart on changes, `False` otherwise + """ return self.hook_matches_hooks(hook, self.plugin_restart_needing_hooks) def is_obsolete_hook(self, hook): - """Checks whether a hook is obsolete""" + """ + Checks whether a hook is defined obsolete. + + Arguments: + hook (str): hook to check + + Returns: + (bool): `True` if the hook is defined obsolete, `False` otherwise + """ return self.hook_matches_hooks(hook, self.plugin_obsolete_hooks) @staticmethod def has_any_of_hooks(plugin, *hooks): """ - Tests if the ``plugin`` contains any of the provided ``hooks``. + Tests if the plugin contains any of the provided hooks. - Uses :func:`octoprint.plugin.core.PluginManager.hook_matches_hooks`. + Uses [octoprint.plugin.core.PluginManager.hook_matches_hooks][]. - Args: - plugin: plugin to test hooks for - *hooks: hooks to test against + Arguments: + plugin (octoprint.plugin.core.Plugin): plugin to test hooks for + hooks (str): hooks to test against Returns: - (bool): True if any of the plugin's hooks match the provided hooks, - False otherwise. + (bool): `True` if any of the plugin's hooks match the provided hooks, + `False` otherwise. """ if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): @@ -1804,21 +1945,19 @@ class PluginManager: @staticmethod def hook_matches_hooks(hook, *hooks): """ - Tests if ``hook`` matches any of the provided ``hooks`` to test for. + Tests if `hook` matches any of the provided `hooks` to test for. - ``hook`` is expected to be an exact hook name. + `hook` is expected to be an exact hook name. - ``hooks`` is expected to be a list containing one or more hook names or - patterns. That can be either an exact hook name or an - :func:`fnmatch.fnmatch` pattern. + `hooks` is expected to be a list containing one or more hook names or + patterns. That can be either an exact hook name or an [fnmatch.fnmatch] pattern. - Args: - hook: the hook to test - hooks: the hook name patterns to test against + Arguments: + hook (str): the hook to test + hooks (str): the hook name patterns to test against Returns: - (bool): True if the ``hook`` matches any of the ``hooks``, False otherwise. - + (bool): `True` if the `hook` matches any of the `hooks`, `False` otherwise. """ if hooks and len(hooks) == 1 and isinstance(hooks[0], (list, tuple)): @@ -1834,6 +1973,18 @@ class PluginManager: @staticmethod def mixins_matching_bases(klass, *bases): + """ + Returns a set of all mixins of the given `klass` that match any of the + provided `bases`. + + Arguments: + klass (type): the class to check for mixins + bases (type): the base classes to check against + + Returns: + (set): a set of all mixins of the given `klass` that match any of the + provided `bases`. + """ result = set() for c in inspect.getmro(klass): if c == klass or c in bases: @@ -1846,16 +1997,16 @@ class PluginManager: @staticmethod def has_any_of_mixins(plugin, *mixins): """ - Tests if the ``plugin`` has an implementation implementing any - of the provided ``mixins``. + Tests if the `plugin` has an implementation implementing any + of the provided `mixins`. - Args: - plugin: plugin for which to check the implementation - *mixins: mixins to test against + Arguments: + plugin (octoprint.plugin.core.Plugin): plugin for which to check the implementation + mixins (type): mixins to test against Returns: - (bool): True if the plugin's implementation implements any of the - provided mixins, False otherwise. + (bool): `True` if the plugin's implementation implements any of the + provided mixins, `False` otherwise. """ if mixins and len(mixins) == 1 and isinstance(mixins[0], (list, tuple)): @@ -1876,6 +2027,21 @@ class PluginManager: additional_pre_inits=None, additional_post_inits=None, ): + """ + Initializes all plugin implementations. + + Arguments: + additional_injects (dict): additional injects to inject into the implementation, a + dict mapping inject names to inject objects + additional_inject_factories (list): additional inject factories to use to generate + injections into implementations, each included [callable][] will be called with + the plugin's identifier and implementation as arguments and is expected to return + a dict of injections mapping inject names to inject objects + additional_pre_inits (list): additional pre-initialization hooks to call, will be + called with the plugin's identifier and implementation as arguments + additional_post_inits (list): additional post-initialization hooks to call, will be + called with the plugin's identifier and implementation as arguments + """ for name, plugin in self.enabled_plugins.items(): self.initialize_implementation_of_plugin( name, @@ -1901,6 +2067,26 @@ class PluginManager: additional_pre_inits=None, additional_post_inits=None, ): + """ + Initializes the implementation of the given plugin. + + Arguments: + name (str): name of the plugin + plugin (octoprint.plugin.core.Plugin): plugin to initialize the implementation for + additional_injects (dict): additional injects to inject into the implementation, a + dict mapping inject names to inject objects + additional_inject_factories (list): additional inject factories to use to generate + injections into the implementation, each included [callable][] will be called with the plugin's identifier + and the implementation as parameters and is expected to return a dict of injections + mapping inject names to inject objects + additional_pre_inits (list): additional pre-initialization hooks to call, each included [callable][] will be + called with the plugin's identifier and implementation as arguments + additional_post_inits (list): additional post-initialization hooks to call, each included [callable][] will be + called with the plugin's identifier and implementation as arguments + + Returns: + (bool): `True` if the plugin's implementation was initialized, `False` otherwise. + """ if plugin.implementation is None: return @@ -1924,6 +2110,24 @@ class PluginManager: additional_pre_inits=None, additional_post_inits=None, ): + """ + Initializes the given implementation. + + Arguments: + name (str): name of the plugin + plugin (octoprint.plugin.core.Plugin): plugin to initialize the implementation for + implementation (tuple): implementation to initialize + additional_injects (dict): additional injects to inject into the implementation, a dict + mapping inject names to inject objects + additional_inject_factories (list): additional inject factories to use to generate + injections into the implementation, each included [callable][] will be called with the plugin's identifier + and the implementation as parameters and is expected to return a dict of injections + mapping inject names to inject objects + additional_pre_inits (list): additional pre-initialization hooks to call, each included [callable][] will be called with + the plugin's identifier and the implementation as parameters + additional_post_inits (list): additional post-initialization hooks to call, each included [callable][] will be called with + the plugin's identifier and the implementation as parameters + """ if additional_injects is None: additional_injects = {} if additional_inject_factories is None: @@ -2014,6 +2218,20 @@ class PluginManager: enabled_str=(" ", "!", "#", "*"), only_to_handler=None, ): + """ + Logs all plugins to the logger. + + Arguments: + show_bundled (bool): whether to show if plugins are bundled + bundled_str (tuple): strings to use for bundled plugins, first string is used if the plugin is bundled, + second string if it is not + show_location (bool): whether to show the location of the plugin + location_str (str): string to use for the location of the plugin, will be formatted with the location + show_enabled (bool): whether to show if plugins are enabled + enabled_str (tuple): strings to use for enabled plugins, first string is used if the plugin is enabled, + second string if it is not + only_to_handler (logging.handler.Handler): if given, only log to the given handler, otherwise log to the logger + """ all_plugins = list(self.enabled_plugins.values()) + list( self.disabled_plugins.values() ) @@ -2056,16 +2274,16 @@ class PluginManager: def get_plugin(self, identifier, require_enabled=True): """ - Retrieves the module of the plugin identified by ``identifier``. If the plugin is not registered or disabled and - ``required_enabled`` is True (the default) None will be returned. + Retrieves the module of the plugin identified by `identifier`. If the plugin is not registered or disabled and + `required_enabled` is `True` (the default) `None` will be returned. Arguments: identifier (str): The identifier of the plugin to retrieve. - require_enabled (boolean): Whether to only return the plugin if is enabled (True, default) or also if it's + require_enabled (bool): Whether to only return the plugin if is enabled (`True`, default) or also if it's disabled. Returns: - module: The requested plugin module or None + (module): The requested plugin module or None """ plugin_info = self.get_plugin_info(identifier, require_enabled=require_enabled) @@ -2075,16 +2293,17 @@ class PluginManager: def get_plugin_info(self, identifier, require_enabled=True): """ - Retrieves the :class:`PluginInfo` instance identified by ``identifier``. If the plugin is not registered or - disabled and ``required_enabled`` is True (the default) None will be returned. + Retrieves the [octoprint.plugin.core.PluginInfo] instance identified by `identifier`. + + If the plugin is not registered or disabled and `required_enabled` is `True` (the default) `None` will be returned. Arguments: identifier (str): The identifier of the plugin to retrieve. - require_enabled (boolean): Whether to only return the plugin if is enabled (True, default) or also if it's - disabled. + require_enabled (bool): Whether to only return the plugin if is enabled (`True`, default) or also if it's + `disabled`. Returns: - ~.PluginInfo: The requested :class:`PluginInfo` or None + (octoprint.plugin.core.PluginInfo): The requested `PluginInfo` or `None` """ if identifier in self.enabled_plugins: @@ -2102,7 +2321,7 @@ class PluginManager: hook (str): The hook for which to retrieve the handlers. Returns: - dict: A dict containing all registered handlers mapped by their plugin's identifier. + (dict): A dict containing all registered handlers mapped by their plugin's identifier. """ if hook not in self.plugin_hooks: @@ -2119,13 +2338,13 @@ class PluginManager: def get_implementations(self, *types, **kwargs): """ - Get all mixin implementations that implement *all* of the provided ``types``. + Get all mixin implementations that implement *all* of the provided `types`. Arguments: - types (one or more type): The types a mixin implementation needs to implement in order to be returned. + types (type): The types a mixin implementation needs to implement in order to be returned. Returns: - list: A list of all found implementations + (list): A list of all found implementations """ sorting_context = kwargs.get("sorting_context", None) @@ -2184,14 +2403,15 @@ class PluginManager: def get_filtered_implementations(self, f, *types, **kwargs): """ - Get all mixin implementations that implement *all* of the provided ``types`` and match the provided filter `f`. + Get all mixin implementations that implement *all* of the provided `types` and match the provided filter `f`. Arguments: - f (callable): A filter function returning True for implementations to return and False for those to exclude. - types (one or more type): The types a mixin implementation needs to implement in order to be returned. + f (callable): A filter function returning `True` for implementations to return and `False` for those to exclude. Gets + passed each implementation as its only argument. + types (type): The types a mixin implementation needs to implement in order to be returned. Returns: - list: A list of all found and matching implementations. + (list): A list of all found and matching implementations. """ assert callable(f) @@ -2202,17 +2422,17 @@ class PluginManager: def get_helpers(self, name, *helpers): """ - Retrieves the named ``helpers`` for the plugin with identifier ``name``. + Retrieves the named `helpers` for the plugin with identifier `name`. If the plugin is not available, returns None. Otherwise returns a :class:`dict` with the requested plugin helper names mapped to the method - if a helper could not be resolved, it will be missing from the dict. Arguments: - name (str): Identifier of the plugin for which to look up the ``helpers``. - helpers (one or more str): Identifiers of the helpers of plugin ``name`` to return. + name (str): Identifier of the plugin for which to look up the `helpers`. + helpers (str): Identifiers of the helpers of plugin `name` to return. Returns: - dict: A dictionary of all resolved helpers, mapped by their identifiers, or None if the plugin was not + (dict): A dictionary of all resolved helper [callables][callable], mapped by their identifiers, or `None` if the plugin was not registered with the system. """ @@ -2228,9 +2448,13 @@ class PluginManager: def register_message_receiver(self, client): """ - Registers a ``client`` for receiving plugin messages. The ``client`` needs to be a callable accepting two - input arguments, ``plugin`` (the sending plugin's identifier) and ``data`` (the message itself), and one - optional keyword argument, ``permissions`` (an optional list of permissions to test against). + Registers a `client` for receiving plugin messages. + + The `client` needs to be a [callable][] accepting two input arguments, `plugin` (the sending plugin's identifier) + and `data` (the message itself), and one optional keyword argument, `permissions` (an optional list of permissions to test against). + + Arguments: + client (callable): The client to register for receiving plugin messages. """ if client is None: @@ -2239,7 +2463,10 @@ class PluginManager: def unregister_message_receiver(self, client): """ - Unregisters a ``client`` for receiving plugin messages. + Unregisters a `client` for receiving plugin messages. + + Arguments: + client (callable): The client to unregister for receiving plugin messages. """ try: @@ -2250,12 +2477,12 @@ class PluginManager: def send_plugin_message(self, plugin, data, permissions=None): """ - Sends ``data`` in the name of ``plugin`` to all currently registered message receivers by invoking them + Sends `data` in the name of `plugin` to all currently registered message receivers by invoking them with the three arguments. Arguments: plugin (str): The sending plugin's identifier. - data (object): The message. + data (dict): The message. permissions (list): A list of permissions to test against in the client. """ @@ -2302,6 +2529,9 @@ def is_sub_path_of(path, parent): """ Tests if `path` is a sub path (or identical) to `path`. + Examples: + + ``` >>> is_sub_path_of("/a/b/c", "/a/b") True >>> is_sub_path_of("/a/b/c", "/a/b2") @@ -2312,12 +2542,29 @@ def is_sub_path_of(path, parent): True >>> is_sub_path_of("/a/b", "/a/b") True + ``` + + Arguments: + path (str): The path to test. + parent (str): The parent path to test against. """ rel_path = os.path.relpath(os.path.realpath(path), os.path.realpath(parent)) return not (rel_path == os.pardir or rel_path.startswith(os.pardir + os.sep)) def is_editable_install(install_dir, package, module, location): + """ + Tests if a package is installed in editable mode. + + Checks if a file `/.egg-link` exists and if it contains a line that points to + `/`. + + Arguments: + install_dir (str): The directory in which the package is installed. + package (str): The name of the package. + module (str): The name of the module. + location (str): The location of the module. + """ package_link = os.path.join(install_dir, f"{package}.egg-link") if os.path.isfile(package_link): expected_target = os.path.normcase(os.path.realpath(location)) @@ -2337,6 +2584,13 @@ def is_editable_install(install_dir, package, module, location): class EntryPointMetadata(pkginfo.Distribution): + """ + A wrapper around `pkginfo.Distribution` that extracts metadata from an `EntryPoint` object. + + Arguments: + entry_point (pkg_resources.EntryPoint): The entry point to extract metadata from. + """ + def __init__(self, entry_point): self.entry_point = entry_point self.extractMetadata() diff --git a/src/octoprint/schema/__init__.py b/src/octoprint/schema/__init__.py index e6938842c..a382d5161 100644 --- a/src/octoprint/schema/__init__.py +++ b/src/octoprint/schema/__init__.py @@ -3,6 +3,13 @@ __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms from pydantic import BaseModel as PydanticBaseModel +try: + # Python 3.8+ + from typing import Literal # noqa: F401 +except ImportError: + # Python 3.7 + from typing_extensions import Literal # noqa: F401 + class BaseModel(PydanticBaseModel): class Config: diff --git a/src/octoprint/schema/config/appearance.py b/src/octoprint/schema/config/appearance.py index f72cd25ca..9d0b3cc8f 100644 --- a/src/octoprint/schema/config/appearance.py +++ b/src/octoprint/schema/config/appearance.py @@ -1,23 +1,12 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" -from enum import Enum from typing import List -from octoprint.schema import BaseModel +from octoprint.schema import BaseModel, Literal from octoprint.vendor.with_attrs_docs import with_attrs_docs -class ColorEnum(str, Enum): - red = "red" - orange = "orange" - yellow = "yellow" - green = "green" - blue = "blue" - violet = "violet" - default = "default" - - @with_attrs_docs class ComponentOrderConfig(BaseModel): navbar: List[str] = [ @@ -140,7 +129,9 @@ class AppearanceConfig(BaseModel): name: str = "" """Use this to give your OctoPrint instance a name. It will be displayed in the title bar (as " [OctoPrint]") and in the navigation bar (as "OctoPrint: <>")""" - color: ColorEnum = ColorEnum.default + color: Literal[ + "red", "orange", "green", "blue", "yellow", "violet", "default" + ] = "default" """Use this to color the navigation bar.""" colorTransparent: bool = False diff --git a/src/octoprint/schema/config/controls.py b/src/octoprint/schema/config/controls.py index d89c82fa5..d04841145 100644 --- a/src/octoprint/schema/config/controls.py +++ b/src/octoprint/schema/config/controls.py @@ -1,18 +1,12 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" -from enum import Enum from typing import List, Optional, Union -from octoprint.schema import BaseModel +from octoprint.schema import BaseModel, Literal from octoprint.vendor.with_attrs_docs import with_attrs_docs -class LayoutEnum(str, Enum): - horizontal = "horizontal" - vertical = "vertical" - - class ControlSliderInputConfig(BaseModel): min: int = 0 """Minimum value of the slider.""" @@ -46,7 +40,7 @@ class ContainerConfig(BaseModel): name: Optional[str] = None """A name to display above the container, basically a section header.""" - layout: LayoutEnum = LayoutEnum.vertical + layout: Literal["horizontal", "vertical"] = "vertical" """The layout to use for laying out the contained children, either from top to bottom (`vertical`) or from left to right (`horizontal`).""" diff --git a/src/octoprint/schema/config/devel.py b/src/octoprint/schema/config/devel.py index 569328963..d6cc3b2ee 100644 --- a/src/octoprint/schema/config/devel.py +++ b/src/octoprint/schema/config/devel.py @@ -1,17 +1,10 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" -from enum import Enum - -from octoprint.schema import BaseModel +from octoprint.schema import BaseModel, Literal from octoprint.vendor.with_attrs_docs import with_attrs_docs -class StylesheetEnum(str, Enum): - css = "css" - less = "less" - - @with_attrs_docs class DevelWebassetsConfig(BaseModel): bundle: bool = True @@ -37,7 +30,7 @@ class DevelCacheConfig(BaseModel): @with_attrs_docs class DevelConfig(BaseModel): - stylesheet: StylesheetEnum = StylesheetEnum.css + stylesheet: Literal["css", "less"] = "css" """Settings for stylesheet preference. OctoPrint will prefer to use the stylesheet type specified here. Usually (on a production install) that will be the compiled css (default). Developers may specify less here too.""" cache: DevelCacheConfig = DevelCacheConfig() diff --git a/src/octoprint/schema/config/events.py b/src/octoprint/schema/config/events.py index 249476e9e..21389725f 100644 --- a/src/octoprint/schema/config/events.py +++ b/src/octoprint/schema/config/events.py @@ -1,18 +1,12 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" -from enum import Enum from typing import List, Optional -from octoprint.schema import BaseModel +from octoprint.schema import BaseModel, Literal from octoprint.vendor.with_attrs_docs import with_attrs_docs -class SubscriptionTypeEnum(str, Enum): - system = "system" - gcode = "gcode" - - @with_attrs_docs class EventSubscription(BaseModel): event: str @@ -24,7 +18,7 @@ class EventSubscription(BaseModel): command: str """The command to execute when the event is triggered, either a GCODE or a system command.""" - type: SubscriptionTypeEnum + type: Literal["system", "gcode"] """The type of the command.""" enabled: bool = True diff --git a/src/octoprint/schema/config/gcode_analysis.py b/src/octoprint/schema/config/gcode_analysis.py index 1a442f1a0..40cfaa380 100644 --- a/src/octoprint/schema/config/gcode_analysis.py +++ b/src/octoprint/schema/config/gcode_analysis.py @@ -1,18 +1,10 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" -from enum import Enum - -from octoprint.schema import BaseModel +from octoprint.schema import BaseModel, Literal from octoprint.vendor.with_attrs_docs import with_attrs_docs -class RunAtEnum(str, Enum): - never = "never" - idle = "idle" - always = "always" - - @with_attrs_docs class GcodeAnalysisConfig(BaseModel): maxExtruders: int = 10 @@ -27,7 +19,7 @@ class GcodeAnalysisConfig(BaseModel): throttle_lines: int = 100 """GCODE line batch size.""" - runAt: RunAtEnum = RunAtEnum.idle + runAt: Literal["never", "idle", "always"] = "idle" """Whether to run the analysis only when idle (not printing), regardless of printing state or never.""" bedZ: float = 0.0 diff --git a/src/octoprint/schema/config/serial.py b/src/octoprint/schema/config/serial.py index fea5b3bf9..99b986286 100644 --- a/src/octoprint/schema/config/serial.py +++ b/src/octoprint/schema/config/serial.py @@ -1,25 +1,12 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" -from enum import Enum from typing import List, Optional -from octoprint.schema import BaseModel +from octoprint.schema import BaseModel, Literal from octoprint.vendor.with_attrs_docs import with_attrs_docs -class AlwaysDetectNeverEnum(str, Enum): - always = "always" - detect = "detect" - never = "never" - - -class InfoWarnNeverEnum(str, Enum): - info = "info" - warn = "warn" - never = "never" - - @with_attrs_docs class SerialTimeoutConfig(BaseModel): detectionFirst: float = 10.0 @@ -172,7 +159,7 @@ class SerialConfig(BaseModel): logResends: bool = True """Whether to log resends to octoprint.log or not. Invaluable debug tool without performance impact, leave on if possible please.""" - supportResendsWithoutOk: AlwaysDetectNeverEnum = "detect" + supportResendsWithoutOk: Literal["always", "detect", "never"] = "detect" """Whether to support resends without follow-up ok or not.""" logPositionOnPause: bool = True @@ -230,13 +217,13 @@ class SerialConfig(BaseModel): blockWhileDwelling: bool = False """Whether to block all sending to the printer while a G4 (dwell) command is active (true, repetier) or not (false).""" - useParityWorkaround: AlwaysDetectNeverEnum = "detect" + useParityWorkaround: Literal["always", "detect", "never"] = "detect" maxConsecutiveResends: int = 10 sendM112OnError: bool = True disableSdPrintingDetection: bool = False ackMax: int = 1 sanityCheckTools: bool = True - notifySuppressedCommands: InfoWarnNeverEnum = "warn" + notifySuppressedCommands: Literal["info", "warn", "never"] = "warn" capabilities: SerialCapabilities = SerialCapabilities() resendRatioThreshold: int = 10 diff --git a/src/octoprint/schema/config/server.py b/src/octoprint/schema/config/server.py index ddc71b272..17da707a6 100644 --- a/src/octoprint/schema/config/server.py +++ b/src/octoprint/schema/config/server.py @@ -1,10 +1,9 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" -from enum import Enum from typing import Dict, List, Optional -from octoprint.schema import BaseModel +from octoprint.schema import BaseModel, Literal from octoprint.vendor.with_attrs_docs import with_attrs_docs CONST_15MIN = 15 * 60 @@ -133,18 +132,12 @@ class IpCheckConfig(BaseModel): """Additional non-local subnets to consider trusted, in CIDR notation, e.g. `192.168.1.0/24`.""" -class SameSiteEnum(str, Enum): - strict = "Strict" - lax = "Lax" - none = "None" - - @with_attrs_docs class CookiesConfig(BaseModel): secure: bool = False """Whether to set the `Secure` flag to true on cookies. Only set to true if you are running OctoPrint behind a reverse proxy taking care of SSL termination.""" - samesite: Optional[SameSiteEnum] = SameSiteEnum.lax + samesite: Optional[Literal["Strict", "Lax", "None"]] = "Lax" """`SameSite` setting to use on the cookies. Possible values are `None`, `Lax` and `Strict`. Defaults to `Lax`. Be advised that if forced unset, this has security implications as many browsers now default to `Lax` unless you configure cookies to be set with `Secure` flag set, explicitly set `SameSite` setting here and also serve OctoPrint over https. The `Lax` setting is known to cause with embedding OctoPrint in frames. See also ["Feature: Cookies default to SameSite=Lax"](https://www.chromestatus.com/feature/5088147346030592), ["Feature: Reject insecure SameSite=None cookies"](https://www.chromestatus.com/feature/5633521622188032) and [issue #3482](https://github.com/OctoPrint/OctoPrint/issues/3482).""" diff --git a/src/octoprint/schema/config/webcam.py b/src/octoprint/schema/config/webcam.py index 8f6bd7567..cd988485d 100644 --- a/src/octoprint/schema/config/webcam.py +++ b/src/octoprint/schema/config/webcam.py @@ -1,19 +1,12 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" -from enum import Enum from typing import Optional -from octoprint.schema import BaseModel +from octoprint.schema import BaseModel, Literal from octoprint.vendor.with_attrs_docs import with_attrs_docs -class TimelapseTypeEnum(str, Enum): - off = "off" - zchange = "zchange" - timed = "timed" - - @with_attrs_docs class TimelapseOptions(BaseModel): interval: Optional[int] = None @@ -28,7 +21,7 @@ class TimelapseOptions(BaseModel): @with_attrs_docs class TimelapseConfig(BaseModel): - type: TimelapseTypeEnum = TimelapseTypeEnum.off + type: Literal["off", "zchange", "timed"] = "off" """The timelapse type.""" fps: int = 25 diff --git a/src/octoprint/schema/webcam/__init__.py b/src/octoprint/schema/webcam/__init__.py index 18a223dc0..3f0c55131 100644 --- a/src/octoprint/schema/webcam/__init__.py +++ b/src/octoprint/schema/webcam/__init__.py @@ -1,24 +1,18 @@ __license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html" __copyright__ = "Copyright (C) 2022 The OctoPrint Project - Released under terms of the AGPLv3 License" -from enum import Enum from typing import List, Optional -from octoprint.schema import BaseModel +from octoprint.schema import BaseModel, Literal from octoprint.vendor.with_attrs_docs import with_attrs_docs -class RatioEnum(str, Enum): - sixteen_nine = "16:9" - four_three = "4:3" - - @with_attrs_docs class WebcamCompatibility(BaseModel): streamTimeout: int = 5 """The timeout of the stream in seconds""" - streamRatio: RatioEnum = RatioEnum.sixteen_nine + streamRatio: Literal["16:9", "4:3"] = "16:9" """The stream's native aspect ratio""" streamWebrtcIceServers: List[str] = ["stun:stun.l.google.com:19302"] diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py index 129b5498b..acb02d9cf 100644 --- a/src/octoprint/util/__init__.py +++ b/src/octoprint/util/__init__.py @@ -1,6 +1,8 @@ """ This module bundles commonly used utility methods or helper classes that are used in multiple places within OctoPrint's source code. + +[[ version_changed 1.8.0 ]] """