diff --git a/src/python/jw/pkg/App.py b/src/python/jw/pkg/App.py index 4e20fcda..fad60663 100644 --- a/src/python/jw/pkg/App.py +++ b/src/python/jw/pkg/App.py @@ -389,7 +389,7 @@ class App(Base): self.__distro = await Distro.instantiate( ec = self.exec_context, id = self.args.distro_id, - default_pkg_filter = self.pkg_filter, + default_pkg_filter = self.path_filter, ) @override diff --git a/src/python/jw/pkg/cmds/pkg/CmdSelect.py b/src/python/jw/pkg/cmds/pkg/CmdSelect.py index 0432f0cd..f8b05423 100644 --- a/src/python/jw/pkg/cmds/pkg/CmdSelect.py +++ b/src/python/jw/pkg/cmds/pkg/CmdSelect.py @@ -20,6 +20,8 @@ class CmdSelect(Cmd): # export @override async def _run(self, args: Namespace) -> None: - filter = PackageFilterString(args.filter) if args.filter else None + filter = PackageFilterString( + file_context = self.app.exec_context, spec = args.filter + ) if args.filter else None for p in await self.distro.select(filter = filter): print(p.name) diff --git a/src/python/jw/pkg/cmds/posix/CmdCopy.py b/src/python/jw/pkg/cmds/posix/CmdCopy.py index 96014c79..142a8f4d 100644 --- a/src/python/jw/pkg/cmds/posix/CmdCopy.py +++ b/src/python/jw/pkg/cmds/posix/CmdCopy.py @@ -67,4 +67,5 @@ class CmdCopy(Cmd): # export mode = int(args.mode, 0) if args.mode is not None else None, recursive = args.recursive, parents = args.parents, + default_path_filter = self.app.path_filter, ) diff --git a/src/python/jw/pkg/lib/Distro.py b/src/python/jw/pkg/lib/Distro.py index 705d136d..2be551fe 100644 --- a/src/python/jw/pkg/lib/Distro.py +++ b/src/python/jw/pkg/lib/Distro.py @@ -381,7 +381,7 @@ class Distro(abc.ABC): async def _select(self, names: Collection[str], filter: PackageFilter) -> Iterable[Package]: - return [p for p in await self._select_by_name(names) if filter.match(p)] + return [p for p in await self._select_by_name(names) if filter.match_pkg(p)] async def select( self, diff --git a/src/python/jw/pkg/lib/ExecApp.py b/src/python/jw/pkg/lib/ExecApp.py index 1c282893..a733c057 100644 --- a/src/python/jw/pkg/lib/ExecApp.py +++ b/src/python/jw/pkg/lib/ExecApp.py @@ -6,13 +6,13 @@ import sys from typing import TYPE_CHECKING, Any, Literal, override from .App import App as Base +from .PathFilter import PathFilter if TYPE_CHECKING: from argparse import ArgumentParser from .ExecContext import ExecContext - from .PackageFilter import PackageFilter class ExecApp(Base): # export @@ -21,7 +21,7 @@ class ExecApp(Base): # export self.__opt_interactive: bool | None = None self.__opt_verbose: bool | None = None self.__exec_context: ExecContext | None = None - self.__pkg_filter: PackageFilter | None | Literal[False] = None + self.__path_filter: PathFilter | None | Literal[False] = None @override async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None: @@ -82,20 +82,20 @@ class ExecApp(Base): # export return self.__opt_verbose @property - def pkg_filter(self) -> PackageFilter | None: - if self.__pkg_filter is None: + def path_filter(self) -> PathFilter | None: + if self.__path_filter is None: spec = self.args.pkg_filter if spec is None: spec = os.getenv('JW_DEFAULT_PKG_FILTER') if spec is None: - self.__pkg_filter = False + self.__path_filter = False else: - from .PackageFilter import PackageFilterString - - self.__pkg_filter = PackageFilterString(spec) - if not self.__pkg_filter: + self.__path_filter = PathFilter.create( + spec = spec, file_context = self.exec_context + ) + if not self.__path_filter: return None - return self.__pkg_filter + return self.__path_filter @property def exec_context(self) -> ExecContext: diff --git a/src/python/jw/pkg/lib/PackageFilter.py b/src/python/jw/pkg/lib/PackageFilter.py index c0b7eb51..610da9f1 100644 --- a/src/python/jw/pkg/lib/PackageFilter.py +++ b/src/python/jw/pkg/lib/PackageFilter.py @@ -1,34 +1,81 @@ from __future__ import annotations import abc +import os import re from typing import TYPE_CHECKING, override +from .PathFilter import PathFilter + if TYPE_CHECKING: + from typing import Any + + from .Distro import Distro + from .FileContext import FileContext from .Package import Package -class PackageFilter(abc.ABC): +class FileContextFilter(PathFilter): + + def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: + super().__init__(spec = spec, **kwargs) + self.__file_context = file_context + + @property + def file_context(self) -> FileContext: + return self.__file_context + +class PackageFilter(FileContextFilter): + + def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: + super().__init__(spec = spec, file_context = file_context, **kwargs) + self.__space: set[str] | None = None + self.___distro: Distro | None = None + + async def distro(self) -> Distro: + if self.___distro is None: + from .Distro import Distro + from .ExecContext import ExecContext + + if not isinstance(self.file_context, ExecContext): + raise Exception( + 'Package-based filters need to be backed by ' + f'distributions, but "{self}" isn\'t' + ) + self.___distro = await Distro.instantiate(ec = self.file_context) + return self.___distro @abc.abstractmethod - def _match(self, package: Package) -> bool: + def _match_pkg(self, package: Package) -> bool: raise NotImplementedError() - def match(self, package: Package) -> bool: - return self._match(package) + def match_pkg(self, package: Package) -> bool: + return self._match_pkg(package) + + @override + async def _access(self, path: str, mode: int = os.F_OK) -> bool: + if self.__space is None: + distro = await self.distro() + names = [p.name for p in await distro.select([], filter = self)] + self.__space = set(await distro.pkg_files(names)) + return path in self.__space class PackageFilterString(PackageFilter): - def __init__(self, definition: str) -> None: + def __init__(self, *, spec: str, file_context: FileContext) -> None: + super().__init__(spec = spec, file_context = file_context) # -- Poor man's parsing for now - url_rx_str = re.sub(r'^\s*url\s*=~\s*', '', definition) - if url_rx_str == definition: - raise Exception(f'Unsupported filter string "{definition}"') - self.__definition = url_rx_str + m = re.match(r'^\s*pkg\s*:\s*(\S+?)\s*=~\s*(.+?)\s*$', spec) + if m is None: + raise Exception(f'Unsupported filter string "{spec}"') + self.__criterion = m.group(1) + self.__rx = re.compile(m.group(2)) @override - def _match(self, package: Package) -> bool: + def _match_pkg(self, package: Package) -> bool: + if self.__criterion != 'url': + return False url = package.url if url is None: return False - return re.search(self.__definition, url) is not None + return self.__rx.search(url) is not None diff --git a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py index 498ecb92..1fbc06f9 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -72,7 +72,8 @@ class KvFile(Base): self.__distro = await Distro.instantiate( ec = self.__inner, default_pkg_filter = ( - PackageFilterString(pkg_filter_str) if pkg_filter_str else None + PackageFilterString(file_context = self, spec = pkg_filter_str) + if pkg_filter_str else None ), ) ret: set[str] = set() diff --git a/test/unit/python/jw/pkg/lib/Distro/test.py b/test/unit/python/jw/pkg/lib/Distro/test.py index 1725d5de..95d9ec50 100644 --- a/test/unit/python/jw/pkg/lib/Distro/test.py +++ b/test/unit/python/jw/pkg/lib/Distro/test.py @@ -271,7 +271,9 @@ sdf = SuseDistro( cl, id = 'suse', os_release_str = OS_RELEASE_SUSE, - default_pkg_filter = PackageFilterString('url=~jw.dev') + default_pkg_filter = PackageFilterString( + spec = 'pkg:url=~jw.dev', file_context = cl + ) ) assert asyncio.run(sdf.pkg_files()) == \ ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl'] @@ -281,7 +283,9 @@ sde = SuseDistro( cl, id = 'suse', os_release_str = OS_RELEASE_SUSE, - default_pkg_filter = PackageFilterString('url=~zzz-nomatch') + default_pkg_filter = PackageFilterString( + spec = 'pkg:url=~zzz-nomatch', file_context = cl + ) ) assert asyncio.run(sde.pkg_files()) == [] assert '--queryformat' in cl.cmds[-1] diff --git a/test/unit/python/jw/pkg/lib/PackageFilter/test.py b/test/unit/python/jw/pkg/lib/PackageFilter/test.py index f7c985bd..835243d0 100644 --- a/test/unit/python/jw/pkg/lib/PackageFilter/test.py +++ b/test/unit/python/jw/pkg/lib/PackageFilter/test.py @@ -1,34 +1,134 @@ +from __future__ import annotations + +import asyncio + +from typing import TYPE_CHECKING, Any, override + +from jw.pkg.lib.FileContext import FileContext from jw.pkg.lib.Package import Package from jw.pkg.lib.PackageFilter import PackageFilterString +if TYPE_CHECKING: + from jw.pkg.lib.Result import Result + +# -- A minimal file context; the match_pkg() role never touches its distro -- + +class _StubFC(FileContext): + + def __init__(self) -> None: + super().__init__(uri = 'file:///') + + @override + async def _get( + self, path: str, wd: str | None, throw: bool, verbose: bool | None, title: str + ) -> Result: + raise NotImplementedError() + +fc = _StubFC() + pkg = Package(name = 'jw-core', url = 'https://example.com/jw-core') pkg_other = Package(name = 'jw-base', url = 'https://other.org/jw-base') pkg_nourl = Package(name = 'no-url') # -- url=~ filters -- -f = PackageFilterString('url=~example\\.com') -assert f.match(pkg) -assert not f.match(pkg_other) +f = PackageFilterString(file_context = fc, spec = 'pkg:url=~example\\.com') +assert f.match_pkg(pkg) +assert not f.match_pkg(pkg_other) # A package without a url never matches -assert not f.match(pkg_nourl) +assert not f.match_pkg(pkg_nourl) # Whitespace around the operator is tolerated -f = PackageFilterString(' url =~ example') -assert f.match(pkg) +f = PackageFilterString(file_context = fc, spec = 'pkg: url =~ example') +assert f.match_pkg(pkg) # An unanchored regex matches anywhere in the url -f = PackageFilterString('url=~jw-core$') -assert f.match(pkg) -assert not f.match(pkg_other) +f = PackageFilterString(file_context = fc, spec = 'pkg:url=~jw-core$') +assert f.match_pkg(pkg) +assert not f.match_pkg(pkg_other) # -- Unsupported definitions raise -- -for definition in ('', 'url=example.com', 'name=jw-core', 'url ~ example'): +for definition in ('', + 'url=example.com', + 'name=jw-core', + 'url ~ example', + 'pkg:url=example.com'): try: - PackageFilterString(definition) + PackageFilterString(file_context = fc, spec = definition) assert False, f'Should have raised for "{definition}"' except Exception: pass +# -- __repr__ -- + +f = PackageFilterString(file_context = fc, spec = 'pkg:url=~example\\.com') +assert repr(f) == 'filter:pkg:url=~example\\.com' + +class _FakeDistro: + + def __init__(self, pkgs: list[tuple[str, str | None, list[str]]]) -> None: + self.__pkgs = [ + (Package(name = name, url = url), files) for name, url, files in pkgs + ] + + async def select(self, + names: list[str] | None = None, + filter: Any = None) -> list[Package]: + return [p for p, _ in self.__pkgs if filter is None or filter.match_pkg(p)] + + async def pkg_files(self, names: list[str] | None = None) -> list[str]: + ret: list[str] = [] + for p, files in self.__pkgs: + if names is None or p.name in names: + ret.extend(files) + return ret + +fake = _FakeDistro( + [ + ( + 'fixture', + 'https://example.com/fixture.rpm', + ['/etc/foo.conf.jw-tmpl', '/etc/fixture.conf'], + ), + ('other', 'https://elsewhere.org/other.rpm', ['/etc/bar.conf']), + ] +) + +# -- _access(): the space is the selected packages' file list, and +# the context's distro is probed on first use -- +async def __run_tests() -> None: + from unittest import mock + + from jw.pkg.lib.Distro import Distro + from jw.pkg.lib.ec.Local import Local + from jw.pkg.lib.PathFilter import Verdict + + f2 = PackageFilterString( + spec = 'pkg:url=~example\\.com', file_context = Local('local') + ) + + async def __instantiate(*args: Any, **kwargs: Any) -> _FakeDistro: + return fake + + with mock.patch.object(Distro, 'instantiate', new = classmethod(__instantiate)): + # The files of the selected package are in the space, + # template and plain alike + assert await f2.run('/etc/foo.conf.jw-tmpl') == Verdict.ALLOW + assert await f2.run('/etc/fixture.conf') == Verdict.ALLOW + # An address of a non-selected package is out of the space + assert await f2.run('/etc/bar.conf') == Verdict.IGNORE + # An address that is not a package file is out of the space + assert await f2.run('/etc/foo.conf') == Verdict.IGNORE + + # -- A context that cannot be probed rejects + f4 = PackageFilterString(spec = 'pkg:url=~example\\.com', file_context = _StubFC()) + try: + await f4.run('/etc/foo.conf') + assert False, 'An unbacked context should reject path queries' + except Exception as e: + assert 'backed by distributions' in str(e) + +asyncio.run(__run_tests()) + print('All PackageFilter tests passed') diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py index 594dd9cc..b9b11437 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/KvFile/test.py @@ -349,14 +349,16 @@ async def run_tests() -> None: # -- The autodetected distro applies the app's documented # filter fallback: JW_DEFAULT_PKG_FILTER reaches # Distro.instantiate() as the default package filter - os.environ['JW_DEFAULT_PKG_FILTER'] = 'url=~jw.dev' + os.environ['JW_DEFAULT_PKG_FILTER'] = 'pkg:url=~jw.dev' try: astore = KvFile('kvfile://') assert set(await astore.readdir('')) == {'tmp'} flt = captured['kwargs'].get('default_pkg_filter') assert flt is not None - assert flt.match(Package('fixture', url = 'https://jw.dev/fixture.rpm')) - assert not flt.match(Package('other', url = 'https://elsewhere/other.rpm')) + assert flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) + assert not flt.match_pkg( + Package('other', url = 'https://elsewhere/other.rpm') + ) finally: del os.environ['JW_DEFAULT_PKG_FILTER']