Skip to content

Commit

Permalink
ci: [pre-commit.ci] autoupdate (#330)
Browse files Browse the repository at this point in the history
<!--pre-commit.ci start-->
updates:
- [github.com/pre-commit/pre-commit-hooks: v4.4.0 →
v4.6.0](pre-commit/pre-commit-hooks@v4.4.0...v4.6.0)
- [github.com/psf/black: 23.7.0 →
24.8.0](psf/black@23.7.0...24.8.0)
- [github.com/astral-sh/ruff-pre-commit: v0.0.282 →
v0.6.3](astral-sh/ruff-pre-commit@v0.0.282...v0.6.3)
- [github.com/pre-commit/mirrors-mypy: v1.4.1 →
v1.11.2](pre-commit/mirrors-mypy@v1.4.1...v1.11.2)
<!--pre-commit.ci end-->

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Grzegorz Bokota <bokota+github@gmail.com>
Co-authored-by: Lorenzo Gaifas <brisvag@gmail.com>
  • Loading branch information
3 people authored Sep 11, 2024
1 parent e48ab10 commit fa6f67b
Show file tree
Hide file tree
Showing 25 changed files with 95 additions and 116 deletions.
8 changes: 4 additions & 4 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,24 @@ exclude: _docs/example_plugin/some_module.py

repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.4.0
rev: v4.6.0
hooks:
- id: check-docstring-first
- id: end-of-file-fixer
- id: trailing-whitespace

- repo: https://github.com/psf/black
rev: 23.7.0
rev: 24.8.0
hooks:
- id: black

- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.0.282
rev: v0.6.4
hooks:
- id: ruff

- repo: https://github.com/pre-commit/mirrors-mypy
rev: v1.4.1
rev: v1.11.2
hooks:
- id: mypy
additional_dependencies:
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ select = [

[tool.ruff.per-file-ignores]
"src/npe2/cli.py" = ["B008", "A00"]
"**/test_*.py" = ["RUF018"]

[tool.ruff.pyupgrade]
# Preserve types, even if a file imports `from __future__ import annotations`.
Expand Down
6 changes: 2 additions & 4 deletions src/npe2/_dynamic_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,14 +203,12 @@ def __init__(self, plugin: DynamicPlugin, contrib_type: Type[C]) -> None:
self._contrib_name = CONTRIB_NAMES[self.contrib_type]

@overload
def __call__(self, func: T, **kwargs) -> T:
...
def __call__(self, func: T, **kwargs) -> T: ...

@overload
def __call__(
self, func: Optional[Literal[None]] = None, **kwargs
) -> Callable[[T], T]:
...
) -> Callable[[T], T]: ...

def __call__(
self, func: Optional[T] = None, **kwargs
Expand Down
2 changes: 1 addition & 1 deletion src/npe2/_inspection/_fetch.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ def _manifest_from_npe2_dist(
module: str = match.groupdict()["module"]
attr: str = match.groupdict()["attr"]

mf_file = Path(dist.locate_file(Path(module.replace(".", os.sep)) / attr))
mf_file = Path(dist.locate_file(Path(module.replace(".", os.sep)) / attr)) # type: ignore[arg-type]
if not mf_file.exists():
raise ValueError( # pragma: no cover
f"manifest {mf_file.name!r} does not exist in distribution "
Expand Down
2 changes: 1 addition & 1 deletion src/npe2/_inspection/_from_npe1.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ def get_top_module_path(package_name, top_module: Optional[str] = None) -> Path:
)
top_module = top_mods[0]

path = Path(dist.locate_file(top_module))
path = Path(dist.locate_file(top_module)) # type: ignore[arg-type]
if not path.is_dir() and dist.files:
for f_path in dist.files:
if "__editable__" in f_path.name:
Expand Down
6 changes: 3 additions & 3 deletions src/npe2/_plugin_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -236,9 +236,9 @@ def __init__(
self._manifests: Dict[PluginName, PluginManifest] = {}
self.events = PluginManagerEvents(self)
self._npe1_adapters: List[NPE1Adapter] = []
self._command_menu_map: Dict[
str, Dict[str, Dict[str, List[MenuCommand]]]
] = defaultdict(dict)
self._command_menu_map: Dict[str, Dict[str, Dict[str, List[MenuCommand]]]] = (
defaultdict(dict)
)

# up to napari 0.4.15, discovery happened in the init here
# so if we're running on an older version of napari, we need to discover
Expand Down
1 change: 1 addition & 0 deletions src/npe2/_setuptools_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
[tool.npe2]
"""

from __future__ import annotations

import os
Expand Down
20 changes: 9 additions & 11 deletions src/npe2/io_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,7 @@ def _read(
plugin_name: Optional[str] = None,
return_reader: Literal[False] = False,
_pm=None,
) -> List[LayerData]:
...
) -> List[LayerData]: ...


@overload
Expand All @@ -138,8 +137,7 @@ def _read(
plugin_name: Optional[str] = None,
return_reader: Literal[True],
_pm=None,
) -> Tuple[List[LayerData], ReaderContribution]:
...
) -> Tuple[List[LayerData], ReaderContribution]: ...


def _read(
Expand Down Expand Up @@ -270,8 +268,7 @@ def _write(
plugin_name: Optional[str] = None,
return_writer: Literal[False] = False,
_pm: Optional[PluginManager] = None,
) -> List[str]:
...
) -> List[str]: ...


@overload
Expand All @@ -282,8 +279,7 @@ def _write(
plugin_name: Optional[str] = None,
return_writer: Literal[True],
_pm: Optional[PluginManager] = None,
) -> Tuple[List[str], WriterContribution]:
...
) -> Tuple[List[str], WriterContribution]: ...


def _write(
Expand All @@ -300,9 +296,11 @@ def _write(
_pm = PluginManager.instance()

_layer_tuples: List[FullLayerData] = [
cast("napari.layers.Layer", x).as_layer_data_tuple()
if hasattr(x, "as_layer_data_tuple")
else x
(
cast("napari.layers.Layer", x).as_layer_data_tuple()
if hasattr(x, "as_layer_data_tuple")
else x
)
for x in layer_data
]
layer_types = [x[2] for x in _layer_tuples]
Expand Down
2 changes: 1 addition & 1 deletion src/npe2/manifest/contributions/_configuration.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class ConfigurationProperty(Draft07JsonSchema):
"plain text, set this value to `plain`.",
)

enum: Optional[conlist(Any, min_items=1, unique_items=True)] = Field( # type: ignore # noqa: E501
enum: Optional[conlist(Any, min_items=1, unique_items=True)] = Field( # type: ignore
None,
description="A list of valid options for this field. If you provide this field,"
"the settings UI will render a dropdown menu.",
Expand Down
2 changes: 1 addition & 1 deletion src/npe2/manifest/contributions/_json_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,7 +110,7 @@ class Config:
unique_items: bool = Field(False)
max_properties: Optional[int] = Field(None, ge=0)
min_properties: Optional[int] = Field(0, ge=0)
enum: Optional[conlist(Any, min_items=1, unique_items=True)] = Field(None) # type: ignore # noqa
enum: Optional[conlist(Any, min_items=1, unique_items=True)] = Field(None) # type: ignore
type: Union[JsonType, JsonTypeArray] = Field(None) # type: ignore
format: Optional[str] = Field(None)

Expand Down
16 changes: 13 additions & 3 deletions src/npe2/manifest/contributions/_readers.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,13 @@
from functools import wraps
from typing import List, Optional
from typing import TYPE_CHECKING, List, Optional

from npe2._pydantic_compat import Extra, Field
from npe2.manifest.utils import Executable, v2_to_v1
from npe2.types import ReaderFunction

if TYPE_CHECKING:
from npe2._command_registry import CommandRegistry


class ReaderContribution(Executable[Optional[ReaderFunction]]):
"""Contribute a file reader.
Expand Down Expand Up @@ -36,19 +39,26 @@ def __hash__(self):
(self.command, tuple(self.filename_patterns), self.accepts_directories)
)

def exec(self, *, kwargs):
def exec(
self,
args: tuple = (),
kwargs: Optional[dict] = None,
_registry: Optional["CommandRegistry"] = None,
):
"""
We are trying to simplify internal npe2 logic to always deal with a
(list[str], bool) pair instead of Union[PathLike, Seq[Pathlike]]. We
thus wrap the Reader Contributions to still give them the old api. Later
on we could add a "if manifest.version == 2" or similar to not have this
backward-compatibility logic for new plugins.
"""
if kwargs is None: # pragma: no cover
kwargs = {}
kwargs = kwargs.copy()
stack = kwargs.pop("stack", None)
assert stack is not None
kwargs["path"] = v2_to_v1(kwargs["path"], stack)
callable_ = super().exec(kwargs=kwargs)
callable_ = super().exec(args=args, kwargs=kwargs, _registry=_registry)

if callable_ is None: # pragma: no cover
return None
Expand Down
3 changes: 1 addition & 2 deletions src/npe2/manifest/contributions/_sample_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ class _SampleDataContribution(GenericModel, ABC):
@abstractmethod
def open(
self, *args, _registry: Optional["CommandRegistry"] = None, **kwargs
) -> List[LayerData]:
...
) -> List[LayerData]: ...


class SampleDataGenerator(_SampleDataContribution, Executable[List[LayerData]]):
Expand Down
6 changes: 4 additions & 2 deletions src/npe2/manifest/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,8 @@ def _from_entrypoint(
entry_point: metadata.EntryPoint,
distribution: Optional[metadata.Distribution] = None,
) -> PluginManifest:
assert (match := entry_point.pattern.match(entry_point.value))
match = entry_point.pattern.match(entry_point.value)
assert match is not None
module = match.group("module")

spec = util.find_spec(module or "")
Expand All @@ -397,7 +398,8 @@ def _from_entrypoint(
f"entrypoint: {entry_point.value!r}"
)

assert (match := entry_point.pattern.match(entry_point.value))
match = entry_point.pattern.match(entry_point.value)
assert match is not None
fname = match.group("attr")

for loc in spec.submodule_search_locations or []:
Expand Down
12 changes: 4 additions & 8 deletions src/npe2/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,19 +30,15 @@

class ArrayLike(Protocol):
@property
def shape(self) -> Tuple[int, ...]:
...
def shape(self) -> Tuple[int, ...]: ...

@property
def ndim(self) -> int:
...
def ndim(self) -> int: ...

@property
def dtype(self) -> "np.dtype":
...
def dtype(self) -> "np.dtype": ...

def __array__(self) -> "np.ndarray":
... # pragma: no cover
def __array__(self) -> "np.ndarray": ... # pragma: no cover


LayerName = Literal[
Expand Down
14 changes: 6 additions & 8 deletions tests/fixtures/my-compiled-plugin/my_module/_a.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,13 +11,11 @@


@implements.on_activate
def activate(ctx):
...
def activate(ctx): ...


@implements.on_deactivate
def deactivate(ctx):
...
def deactivate(ctx): ...


@implements.reader(
Expand All @@ -26,8 +24,7 @@ def deactivate(ctx):
filename_patterns=["*.fzy", "*.fzzy"],
accepts_directories=True,
)
def get_reader(path: str):
...
def get_reader(path: str): ...


@implements.writer(
Expand All @@ -42,5 +39,6 @@ def get_reader(path: str):
filename_extensions=["*.pcd", "*.e57"],
layer_types=["points{1}", "surface+"],
)
def writer_function(path: str, layer_data: List[Tuple[Any, Dict, str]]) -> List[str]:
...
def writer_function(
path: str, layer_data: List[Tuple[Any, Dict, str]]
) -> List[str]: ...
9 changes: 3 additions & 6 deletions tests/fixtures/my-compiled-plugin/my_module/_b.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@


@implements.widget(id="some_widget", title="Create my widget", display_name="My Widget")
class SomeWidget:
...
class SomeWidget: ...


@implements.sample_data_generator(
Expand All @@ -18,8 +17,7 @@ class SomeWidget:
key="random_data",
display_name="Some Random Data (512 x 512)",
)
def random_data():
...
def random_data(): ...


@implements.widget(
Expand All @@ -28,5 +26,4 @@ def random_data():
display_name="A Widget From a Function",
autogenerate=True,
)
def make_widget_from_function(x: int, threshold: int):
...
def make_widget_from_function(x: int, threshold: int): ...
24 changes: 8 additions & 16 deletions tests/npe1-plugin/npe1_module/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,31 +5,25 @@
from napari_plugin_engine import napari_hook_implementation


class MyWidget:
...
class MyWidget: ...


def some_function(x: int):
...
def some_function(x: int): ...


def gen_data():
...
def gen_data(): ...


@napari_hook_implementation
def napari_get_reader(path):
...
def napari_get_reader(path): ...


@napari_hook_implementation
def napari_write_image(path, data, meta):
...
def napari_write_image(path, data, meta): ...


@napari_hook_implementation
def napari_write_labels(path, data, meta):
...
def napari_write_labels(path, data, meta): ...


@napari_hook_implementation
Expand Down Expand Up @@ -79,8 +73,7 @@ def napari_experimental_provide_theme():
@napari_hook_implementation
def napari_experimental_provide_dock_widget():
@magic_factory
def local_widget(y: str):
...
def local_widget(y: str): ...

return [
MyWidget,
Expand All @@ -91,7 +84,6 @@ def local_widget(y: str):

@napari_hook_implementation
def napari_experimental_provide_function():
def local_function(x: int):
...
def local_function(x: int): ...

return [some_function, local_function]
Loading

0 comments on commit fa6f67b

Please sign in to comment.