lib.PackageFilter: Derive from PathFilter
This commit moves package-based filtering from the package level to the path level, using the new path filter framework. Derive PackageFilter from a new FileContextFilter base, which binds a PathFilter to the FileContext it guards, and implements _access(). The filter's space is the file list of the packages it selects, taken from the backing distro's pkg_files(). An address is allowed only if it names one of those files. The backing distro is taken from the file context, if the context carries one, and is otherwise autodetected from the host the context executes on, so the filter also works on a bare exec context. A context that is not an exec context and carries no distro rejects path queries with an error. The filter string now follows the loader syntax, pkg:url=~ regex, and a bare url=~regex like the old url=~jw.dev form is rejected; update JW_DEFAULT_PKG_FILTER values accordingly. PackageFilter's match() is renamed match_pkg(), to make clear that it matches packages, and Distro._select() calls the new name. ExecApp.path_filter builds the filter through PathFilter.create() and binds it to the exec context. CmdSelect passes its argument to the new constructor, CmdCopy hands the app's filter to the copy, and the App distro picks it up as the default package filter. Extend the unit test to cover the space membership and the distro lookup. Signed-off-by: Jan Lindemann <jan@janware.com> Assisted-by: unsloth/Qwen3.8-27B-GGUF:Q4_K_M with pi.dev v1.5.0
This commit is contained in:
parent
d27bf01714
commit
f74dca5a45
10 changed files with 198 additions and 41 deletions
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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:
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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]
|
||||
|
|
|
|||
|
|
@ -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')
|
||||
|
|
|
|||
|
|
@ -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']
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue