lib.PathFilter: Generalize the package filter into path filters #170
26 changed files with 846 additions and 161 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_path_filter = self.exec_context.path_filter,
|
||||
)
|
||||
|
||||
@override
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@ from __future__ import annotations
|
|||
|
||||
from typing import TYPE_CHECKING, override
|
||||
|
||||
from ...lib.PackageFilter import PackageFilterString
|
||||
from ...lib.PathFilter import PathFilter
|
||||
from .Cmd import Cmd, Parent
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
|
@ -20,6 +20,15 @@ class CmdSelect(Cmd): # export
|
|||
|
||||
@override
|
||||
async def _run(self, args: Namespace) -> None:
|
||||
filter = PackageFilterString(args.filter) if args.filter else None
|
||||
filter = PathFilter.create(
|
||||
spec = args.filter, file_context = self.app.exec_context
|
||||
) if args.filter else None
|
||||
if filter is not None:
|
||||
from ...lib.pf.Pkg import PackageFilter
|
||||
if not isinstance(filter, PackageFilter):
|
||||
raise Exception(
|
||||
'Use a package filter for selecting packages, this '
|
||||
f'is not a package filter: "{args.filter}"'
|
||||
)
|
||||
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.exec_context.path_filter,
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,8 +1,13 @@
|
|||
from typing import Any, Self
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any, Self
|
||||
|
||||
from .FileContext import FileContext
|
||||
from .Uri import Uri
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .PathFilter import PathFilter
|
||||
|
||||
class CopyContext:
|
||||
|
||||
def __init__(
|
||||
|
|
@ -10,6 +15,7 @@ class CopyContext:
|
|||
src: Uri | str | FileContext,
|
||||
dst: Uri | str | FileContext,
|
||||
chroot: bool = False,
|
||||
default_path_filter: str | PathFilter | None = None,
|
||||
) -> None:
|
||||
|
||||
def __uri(ctx: FileContext | Uri | str) -> Uri | str:
|
||||
|
|
@ -29,17 +35,28 @@ class CopyContext:
|
|||
self.__src, self.__src_uri = __info(src)
|
||||
self.__dst, self.__dst_uri = __info(dst)
|
||||
self.__chroot = chroot
|
||||
self.__default_path_filter = default_path_filter
|
||||
|
||||
async def __aenter__(self) -> Self:
|
||||
if self.__src is None:
|
||||
if self.__src_uri is None:
|
||||
raise Exception('Tried to create source context without URI')
|
||||
self.__src = FileContext.create(self.__src_uri, chroot = self.__chroot)
|
||||
self.__src = FileContext.create(
|
||||
self.__src_uri,
|
||||
chroot = self.__chroot,
|
||||
default_path_filter = self.__default_path_filter,
|
||||
)
|
||||
await self.__src.open()
|
||||
if self.__dst is None:
|
||||
if self.__dst_uri is None:
|
||||
raise Exception('Tried to create destination context without URI')
|
||||
self.__dst = FileContext.create(self.__dst_uri, chroot = self.__chroot)
|
||||
# -- The destination is the target of the copy, not part
|
||||
# of the source's address space: the filter bounds the
|
||||
# source only
|
||||
self.__dst = FileContext.create(
|
||||
self.__dst_uri,
|
||||
chroot = self.__chroot,
|
||||
)
|
||||
await self.__dst.open()
|
||||
return self
|
||||
|
||||
|
|
|
|||
|
|
@ -19,7 +19,8 @@ if TYPE_CHECKING:
|
|||
from .ExecContext import ExecContext
|
||||
from .FlaggedFile import FlaggedFile
|
||||
from .Package import Package
|
||||
from .PackageFilter import PackageFilter
|
||||
from .PathFilter import PathFilter
|
||||
from .pf.Pkg import PackageFilter
|
||||
|
||||
class Distro(abc.ABC):
|
||||
|
||||
|
|
@ -28,7 +29,7 @@ class Distro(abc.ABC):
|
|||
ec: ExecContext,
|
||||
id: str | None = None,
|
||||
os_release_str: str | None = None,
|
||||
default_pkg_filter: PackageFilter | None = None,
|
||||
default_path_filter: PathFilter | None = None,
|
||||
) -> None:
|
||||
if id is None:
|
||||
raise ValueError('Tried to instantiate Distro without id')
|
||||
|
|
@ -39,7 +40,7 @@ class Distro(abc.ABC):
|
|||
self.__exec_context = ec
|
||||
self.__id: str | None = None
|
||||
self.__os_release_str: str | None = os_release_str
|
||||
self.__default_pkg_filter = default_pkg_filter
|
||||
self.__default_path_filter = default_path_filter
|
||||
|
||||
# Names that can be used by code outside this class to retrieve
|
||||
# distribution properties by
|
||||
|
|
@ -61,7 +62,7 @@ class Distro(abc.ABC):
|
|||
async def read_os_release_str(cls, ec: ExecContext) -> str:
|
||||
release_file = '/etc/os-release'
|
||||
try:
|
||||
result = await ec.get(release_file, throw = True)
|
||||
result = await ec.get(release_file, throw = True, filtered = False)
|
||||
return result.stdout_str
|
||||
except Exception as e:
|
||||
log(
|
||||
|
|
@ -329,8 +330,8 @@ class Distro(abc.ABC):
|
|||
return self.__exec_context
|
||||
|
||||
@property
|
||||
def default_pkg_filter(self) -> PackageFilter | None:
|
||||
return self.__default_pkg_filter
|
||||
def default_path_filter(self) -> PathFilter | None:
|
||||
return self.__default_path_filter
|
||||
|
||||
async def run(self, *args: Any, **kwargs: Any) -> Result:
|
||||
return await self.__exec_context.run(*args, **kwargs)
|
||||
|
|
@ -381,7 +382,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,
|
||||
|
|
@ -389,7 +390,17 @@ class Distro(abc.ABC):
|
|||
filter: PackageFilter | None = None
|
||||
) -> Iterable[Package]:
|
||||
if not filter:
|
||||
filter = self.__default_pkg_filter
|
||||
from .pf.Pkg import PackageFilter
|
||||
|
||||
default = self.__default_path_filter
|
||||
if default is not None and not isinstance(default, PackageFilter):
|
||||
log(
|
||||
WARNING,
|
||||
f'The default path filter is not a package filter, '
|
||||
f'selecting all packages: "{default}"',
|
||||
)
|
||||
return await self._select_by_name(names)
|
||||
filter = default
|
||||
if not filter:
|
||||
return await self._select_by_name(names)
|
||||
return await self._select(names, filter)
|
||||
|
|
@ -508,7 +519,7 @@ class Distro(abc.ABC):
|
|||
# compatibility with the single-package call
|
||||
if isinstance(names, str):
|
||||
names = [names]
|
||||
if names is None and self.default_pkg_filter is not None:
|
||||
if names is None and self.default_path_filter is not None:
|
||||
names = [p.name for p in await self.select()]
|
||||
return await self._pkg_files(names)
|
||||
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ from __future__ import annotations
|
|||
import os
|
||||
import sys
|
||||
|
||||
from typing import TYPE_CHECKING, Any, Literal, override
|
||||
from typing import TYPE_CHECKING, Any, override
|
||||
|
||||
from .App import App as Base
|
||||
|
||||
|
|
@ -12,7 +12,6 @@ if TYPE_CHECKING:
|
|||
from argparse import ArgumentParser
|
||||
|
||||
from .ExecContext import ExecContext
|
||||
from .PackageFilter import PackageFilter
|
||||
|
||||
class ExecApp(Base): # export
|
||||
|
||||
|
|
@ -21,7 +20,6 @@ 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
|
||||
|
||||
@override
|
||||
async def __aexit__(self, exc_type: Any, exc: Any, tb: Any) -> None:
|
||||
|
|
@ -51,8 +49,9 @@ class ExecApp(Base): # export
|
|||
'--target', default = 'local', help = 'Run commands on this host'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--pkg-filter',
|
||||
help = 'Default filter for all distribution package-related operations',
|
||||
'--path-filter',
|
||||
help = 'Default path filter for the exec context, '
|
||||
'as a name:spec loader string',
|
||||
)
|
||||
|
||||
@property
|
||||
|
|
@ -81,30 +80,18 @@ class ExecApp(Base): # export
|
|||
assert self.__opt_verbose is not None
|
||||
return self.__opt_verbose
|
||||
|
||||
@property
|
||||
def pkg_filter(self) -> PackageFilter | None:
|
||||
if self.__pkg_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
|
||||
else:
|
||||
from .PackageFilter import PackageFilterString
|
||||
|
||||
self.__pkg_filter = PackageFilterString(spec)
|
||||
if not self.__pkg_filter:
|
||||
return None
|
||||
return self.__pkg_filter
|
||||
|
||||
@property
|
||||
def exec_context(self) -> ExecContext:
|
||||
if self.__exec_context is None:
|
||||
from .ExecContext import ExecContext
|
||||
|
||||
spec = self.args.path_filter
|
||||
if spec is None:
|
||||
spec = os.getenv('JW_DEFAULT_PATH_FILTER')
|
||||
self.__exec_context = ExecContext.create(
|
||||
self.args.target,
|
||||
interactive = self.interactive,
|
||||
verbose_default = self.verbose,
|
||||
default_path_filter = spec,
|
||||
)
|
||||
return self.__exec_context
|
||||
|
|
|
|||
|
|
@ -1,18 +1,21 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import os
|
||||
|
||||
from enum import Enum, auto
|
||||
from functools import cached_property
|
||||
from typing import TYPE_CHECKING, Any, Iterable, override
|
||||
from typing import TYPE_CHECKING, Any, Iterable, Literal, override
|
||||
|
||||
from .base import Result
|
||||
from .file_types import FT_DIR, FT_REG
|
||||
from .log import DEBUG, ERR, log
|
||||
from .log import DEBUG, ERR, get_caller_pos, log
|
||||
from .PathFilter import PathFilter, Verdict
|
||||
from .ProcFilter import ProcPipeline
|
||||
from .Uri import Uri
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .base import Result, StatResult
|
||||
from .base import StatResult
|
||||
from .file_types import FileType
|
||||
from .ProcFilter import ProcFilter
|
||||
|
||||
|
|
@ -30,6 +33,7 @@ class FileContext(abc.ABC):
|
|||
chroot: bool = False,
|
||||
in_pipe: ProcPipeline | None = None,
|
||||
out_pipe: ProcPipeline | None = None,
|
||||
default_path_filter: str | PathFilter | None | Literal[False] = None,
|
||||
):
|
||||
self.__uri = Uri.pimp(uri)
|
||||
self.__chroot = chroot
|
||||
|
|
@ -39,6 +43,10 @@ class FileContext(abc.ABC):
|
|||
self.__in_pipe = in_pipe
|
||||
self.__out_pipe = out_pipe
|
||||
self.__open_count = 0
|
||||
self.__default_path_filter: str | PathFilter | Literal[
|
||||
False] | None = default_path_filter
|
||||
self.__path_filter: PathFilter | Literal[
|
||||
False] | None = False if default_path_filter is False else None
|
||||
if verbose_default not in [True, False]:
|
||||
raise ValueError(
|
||||
'Tried to instantiate FileContext with verbose_default '
|
||||
|
|
@ -116,6 +124,49 @@ class FileContext(abc.ABC):
|
|||
def chroot(self) -> bool:
|
||||
return self.__chroot
|
||||
|
||||
@property
|
||||
def path_filter(self) -> PathFilter | None:
|
||||
|
||||
def __create_path_filter(
|
||||
candidate: str | None | PathFilter | Literal[False]
|
||||
) -> PathFilter | Literal[False]:
|
||||
if candidate is None or candidate is False:
|
||||
return False
|
||||
if isinstance(candidate, PathFilter):
|
||||
return candidate
|
||||
return PathFilter.create(spec = candidate, file_context = self)
|
||||
|
||||
if self.__path_filter is None:
|
||||
query = self.__uri.query_dict if self.__uri.query_dict else {}
|
||||
candidate: str | PathFilter | Literal[False] | None = \
|
||||
query.get('path-filter')
|
||||
if candidate is None:
|
||||
candidate = self.__default_path_filter
|
||||
self.__path_filter = __create_path_filter(candidate)
|
||||
return self.__path_filter or None
|
||||
|
||||
@path_filter.setter
|
||||
def path_filter(self, value: str | PathFilter | None | Literal[False]) -> None:
|
||||
self.__path_filter = None
|
||||
self.__default_path_filter = value
|
||||
|
||||
async def check_filtered(
|
||||
self,
|
||||
path: str,
|
||||
mode: int = os.F_OK,
|
||||
action: str = '',
|
||||
caller: tuple[str, str, int] | None = None,
|
||||
) -> Verdict:
|
||||
path_filter = self.path_filter
|
||||
if path_filter is None:
|
||||
return Verdict.ALLOW
|
||||
return await path_filter.run(
|
||||
path,
|
||||
mode = mode,
|
||||
msg = f'[{self.log_name}] {action}("{path}") is filtered',
|
||||
caller = caller or get_caller_pos(),
|
||||
)
|
||||
|
||||
@property
|
||||
def username(self) -> str | None:
|
||||
return self.__uri.username
|
||||
|
|
@ -145,7 +196,11 @@ class FileContext(abc.ABC):
|
|||
throw: bool = True,
|
||||
verbose: bool | None = None,
|
||||
title: str | None = None,
|
||||
filtered: bool = True,
|
||||
) -> Result:
|
||||
if filtered and await self.check_filtered(path, mode = os.R_OK,
|
||||
action = 'get') == Verdict.IGNORE:
|
||||
raise FileNotFoundError(path)
|
||||
ret = await self._get(
|
||||
self._chroot(path),
|
||||
wd = wd,
|
||||
|
|
@ -184,7 +239,11 @@ class FileContext(abc.ABC):
|
|||
mode: int | None = None,
|
||||
atomic: bool = False,
|
||||
ftype: FileType = FT_REG,
|
||||
filtered: bool = True,
|
||||
) -> Result:
|
||||
if filtered and await self.check_filtered(path, mode = os.W_OK,
|
||||
action = 'put') == Verdict.IGNORE:
|
||||
return Result()
|
||||
mode_str = None if mode is None else oct(mode).replace('0o', '0')
|
||||
if self.__out_pipe is not None:
|
||||
content = (await self.__out_pipe.run(content)).stdout
|
||||
|
|
@ -207,7 +266,10 @@ class FileContext(abc.ABC):
|
|||
f'{self.log_name}: unlink("{path}") is not implemented'
|
||||
)
|
||||
|
||||
async def unlink(self, path: str) -> None:
|
||||
async def unlink(self, path: str, filtered: bool = True) -> None:
|
||||
if filtered and await self.check_filtered(
|
||||
path, mode = os.W_OK, action = 'unlink') == Verdict.IGNORE:
|
||||
return
|
||||
return await self._unlink(self._chroot(path))
|
||||
|
||||
async def _erase(self, path: str) -> None:
|
||||
|
|
@ -215,7 +277,10 @@ class FileContext(abc.ABC):
|
|||
f'{self.log_name}: erase("{path}") is not implemented'
|
||||
)
|
||||
|
||||
async def erase(self, path: str) -> None:
|
||||
async def erase(self, path: str, filtered: bool = True) -> None:
|
||||
if filtered and await self.check_filtered(
|
||||
path, mode = os.W_OK, action = 'erase') == Verdict.IGNORE:
|
||||
return
|
||||
return await self._erase(self._chroot(path))
|
||||
|
||||
async def _rename(self, src: str, dst: str) -> None:
|
||||
|
|
@ -223,15 +288,28 @@ class FileContext(abc.ABC):
|
|||
f'{self.log_name}: rename("{src}" -> "{dst}") is not implemented'
|
||||
)
|
||||
|
||||
async def rename(self, src: str, dst: str) -> None:
|
||||
return await self._rename(src, dst)
|
||||
async def rename(self, src: str, dst: str, filtered: bool = True) -> None:
|
||||
if filtered and await self.check_filtered(
|
||||
src, mode = os.R_OK, action = 'rename') == Verdict.IGNORE:
|
||||
return
|
||||
if filtered and await self.check_filtered(
|
||||
dst, mode = os.W_OK, action = 'rename') == Verdict.IGNORE:
|
||||
return
|
||||
return await self._rename(self._chroot(src), self._chroot(dst))
|
||||
|
||||
async def _mkdir(self, path: str, mode: int, ftype: FileType) -> None:
|
||||
raise NotImplementedError(f'{self.log_name}: mkdir({path}) is not implemented')
|
||||
|
||||
async def mkdir(
|
||||
self, path: str, mode: int = 0o777, ftype: FileType = FT_DIR
|
||||
self,
|
||||
path: str,
|
||||
mode: int = 0o777,
|
||||
ftype: FileType = FT_DIR,
|
||||
filtered: bool = True,
|
||||
) -> None:
|
||||
if filtered and await self.check_filtered(
|
||||
path, mode = os.W_OK, action = 'mkdir') == Verdict.IGNORE:
|
||||
return
|
||||
return await self._mkdir(self._chroot(path), mode, ftype)
|
||||
|
||||
async def _mktemp(self, tmpl: str, directory: bool) -> str:
|
||||
|
|
@ -269,9 +347,17 @@ class FileContext(abc.ABC):
|
|||
f'{self.log_name}: lstat("{path}") is not implemented'
|
||||
)
|
||||
|
||||
async def stat(self, path: str, follow_symlinks: bool = True) -> StatResult:
|
||||
async def stat(
|
||||
self,
|
||||
path: str,
|
||||
follow_symlinks: bool = True,
|
||||
filtered: bool = True
|
||||
) -> StatResult:
|
||||
if not isinstance(path, str):
|
||||
raise TypeError(f'path must be str, got {type(path).__name__}')
|
||||
if filtered and await self.check_filtered(path, mode = os.F_OK,
|
||||
action = 'stat') == Verdict.IGNORE:
|
||||
raise FileNotFoundError(path)
|
||||
return await self._stat(self._chroot(path), follow_symlinks)
|
||||
|
||||
async def _file_exists(self, path: str) -> bool:
|
||||
|
|
@ -341,8 +427,16 @@ class FileContext(abc.ABC):
|
|||
f'{self.log_name}: readdir("{path}") is not implemented'
|
||||
)
|
||||
|
||||
async def readdir(self, path: str) -> Iterable[str]:
|
||||
return await self._readdir(self._chroot(path))
|
||||
async def readdir(self, path: str, filtered: bool = True) -> Iterable[str]:
|
||||
base = path.rstrip('/')
|
||||
ret: list[str] = []
|
||||
for entry in await self._readdir(self._chroot(path)):
|
||||
full = f'{base}/{entry}' if base else entry
|
||||
if filtered and await self.check_filtered(
|
||||
full, mode = os.R_OK, action = 'readdir') == Verdict.IGNORE:
|
||||
continue
|
||||
ret.append(entry)
|
||||
return ret
|
||||
|
||||
@classmethod
|
||||
def create(cls, uri: str | Uri, *args: Any, **kwargs: Any) -> 'FileContext':
|
||||
|
|
|
|||
|
|
@ -1,34 +0,0 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import re
|
||||
|
||||
from typing import TYPE_CHECKING, override
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .Package import Package
|
||||
|
||||
class PackageFilter(abc.ABC):
|
||||
|
||||
@abc.abstractmethod
|
||||
def _match(self, package: Package) -> bool:
|
||||
raise NotImplementedError()
|
||||
|
||||
def match(self, package: Package) -> bool:
|
||||
return self._match(package)
|
||||
|
||||
class PackageFilterString(PackageFilter):
|
||||
|
||||
def __init__(self, definition: str) -> None:
|
||||
# -- 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
|
||||
|
||||
@override
|
||||
def _match(self, package: Package) -> bool:
|
||||
url = package.url
|
||||
if url is None:
|
||||
return False
|
||||
return re.search(self.__definition, url) is not None
|
||||
95
src/python/jw/pkg/lib/PathFilter.py
Normal file
95
src/python/jw/pkg/lib/PathFilter.py
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import os
|
||||
|
||||
from enum import Enum, Flag, auto
|
||||
from typing import TYPE_CHECKING, override
|
||||
|
||||
from .log import WARNING, get_caller_pos, log
|
||||
from .Types import LoadTypes
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import Any
|
||||
|
||||
class DenyAction(Enum):
|
||||
LOG = auto()
|
||||
ABORT = auto()
|
||||
|
||||
class Handle(Flag):
|
||||
LOG = auto()
|
||||
ABORT = auto()
|
||||
|
||||
class Verdict(Enum):
|
||||
ALLOW = auto()
|
||||
IGNORE = auto()
|
||||
ABORT = auto()
|
||||
|
||||
class PathFilter(abc.ABC):
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
spec: str,
|
||||
deny_action: DenyAction = DenyAction.LOG,
|
||||
handle: Handle = Handle.LOG | Handle.ABORT,
|
||||
) -> None:
|
||||
self.__spec = spec
|
||||
self.__deny_action = deny_action
|
||||
self.__handle = handle
|
||||
|
||||
@override
|
||||
def __repr__(self) -> str:
|
||||
return f'filter:{self.__spec}'
|
||||
|
||||
@property
|
||||
def deny_action(self) -> DenyAction:
|
||||
return self.__deny_action
|
||||
|
||||
@classmethod
|
||||
def create(cls, *, spec: str, **kwargs: Any) -> PathFilter:
|
||||
name, sep, _ = spec.partition(':')
|
||||
if not sep:
|
||||
raise Exception(
|
||||
f'Unsupported filter spec "{spec}": expected a "name:spec" '
|
||||
'form, where the name picks the filter class'
|
||||
)
|
||||
class_name = name.capitalize()
|
||||
module_name = 'jw.pkg.lib.pf.' + class_name
|
||||
filter_classes: LoadTypes[PathFilter] = LoadTypes(
|
||||
[module_name],
|
||||
type_name_filter = class_name,
|
||||
type_filter = [PathFilter],
|
||||
)
|
||||
try:
|
||||
filter_class = next(iter(filter_classes))
|
||||
except (StopIteration, ModuleNotFoundError) as e:
|
||||
raise Exception(
|
||||
f'No PathFilter class "{class_name}" in module {module_name}'
|
||||
) from e
|
||||
return filter_class(spec = spec, **kwargs)
|
||||
|
||||
@abc.abstractmethod
|
||||
async def _access(self, path: str, mode: int = os.F_OK) -> bool:
|
||||
raise NotImplementedError()
|
||||
|
||||
async def run(
|
||||
self,
|
||||
path: str,
|
||||
mode: int = os.F_OK,
|
||||
msg: str | None = None,
|
||||
caller: tuple[str, str, int] | None = None,
|
||||
) -> Verdict:
|
||||
if await self._access(path, mode):
|
||||
return Verdict.ALLOW
|
||||
ret = Verdict.ABORT if self.__deny_action == DenyAction.ABORT \
|
||||
else Verdict.IGNORE
|
||||
if not (self.__handle & (Handle.LOG | Handle.ABORT)):
|
||||
return ret
|
||||
if msg is None:
|
||||
msg = f'"{path}" is filtered'
|
||||
if self.__handle & Handle.ABORT and ret == Verdict.ABORT:
|
||||
raise PermissionError(msg + ', aborting')
|
||||
if self.__handle & Handle.LOG and ret == Verdict.IGNORE:
|
||||
log(WARNING, msg + ', ignoring', caller = caller or get_caller_pos())
|
||||
return ret
|
||||
|
|
@ -141,6 +141,7 @@ class Base(FileContext):
|
|||
mode: int | None = None,
|
||||
atomic: bool = False,
|
||||
ftype: FileType = FT_REG,
|
||||
filtered: bool = True,
|
||||
) -> Result:
|
||||
# -- A put that changes nothing is a no-op: the pre-read is
|
||||
# fallback-aware, so a value already represented, below
|
||||
|
|
@ -171,6 +172,7 @@ class Base(FileContext):
|
|||
mode,
|
||||
atomic,
|
||||
ftype,
|
||||
filtered,
|
||||
)
|
||||
|
||||
def _put_is_noop(self, existing: bytes, content: bytes, ftype: FileType) -> bool:
|
||||
|
|
|
|||
|
|
@ -3,19 +3,21 @@ from __future__ import annotations
|
|||
import errno
|
||||
import os
|
||||
|
||||
from typing import TYPE_CHECKING, Any, Iterable, cast, override
|
||||
from typing import TYPE_CHECKING, cast, override
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ...Distro import Distro
|
||||
from typing import Any, Iterable, Literal
|
||||
from ...ExecContext import ExecContext
|
||||
from ...Uri import Uri
|
||||
from ...base import StatResult
|
||||
from ...file_types import FileType
|
||||
from ...Distro import Distro
|
||||
|
||||
from ...FcCache import FcCache
|
||||
from ...file_types import FT_COMPOUND, FT_DIR
|
||||
from ...FileContext import FileContext
|
||||
from ...kv import parse_kv, serialize_kv
|
||||
from ...PathFilter import PathFilter
|
||||
from ...Result import Result
|
||||
from .Base import Base
|
||||
from .layout import BLOB_SUFFIX, FT_SECRET, FT_SECRET_FILE, FT_SECRET_KEY, SECRET_SUFFIX
|
||||
|
|
@ -23,8 +25,34 @@ from .layout import BLOB_SUFFIX, FT_SECRET, FT_SECRET_FILE, FT_SECRET_KEY, SECRE
|
|||
class KvFile(Base):
|
||||
"""The on-host store of a host's package secrets. """
|
||||
|
||||
def __init__(self, uri: str | Uri, *args: Any, **kwargs: Any) -> None:
|
||||
super().__init__(uri, *args, **kwargs)
|
||||
def __init__(
|
||||
self,
|
||||
uri: str | Uri,
|
||||
*args: Any,
|
||||
default_path_filter: str | PathFilter | None | Literal[False] = None,
|
||||
**kwargs: Any,
|
||||
) -> None:
|
||||
|
||||
def __create_backend_path_filter() -> PathFilter | None:
|
||||
|
||||
def __spec() -> str | None:
|
||||
if isinstance(default_path_filter, str):
|
||||
return default_path_filter
|
||||
d = self.uri.query_dict
|
||||
if d is None:
|
||||
return None
|
||||
return d.get('path-filter')
|
||||
|
||||
if default_path_filter is False:
|
||||
return None
|
||||
if isinstance(default_path_filter, PathFilter):
|
||||
return default_path_filter
|
||||
spec: str | None = __spec()
|
||||
if spec is None:
|
||||
return None
|
||||
return PathFilter.create(spec = spec, file_context = self.__inner)
|
||||
|
||||
super().__init__(uri, *args, default_path_filter = False, **kwargs)
|
||||
kwargs.pop('chroot', None)
|
||||
scheme = 'ssh' if self.uri.hostname else 'local'
|
||||
self.__inner: ExecContext = cast(
|
||||
|
|
@ -33,7 +61,8 @@ class KvFile(Base):
|
|||
f'{scheme}://{self.uri.authority}', chroot = False, **kwargs
|
||||
),
|
||||
)
|
||||
self.__distro: Distro | None = None
|
||||
self.__backend_path_filter = __create_backend_path_filter()
|
||||
self.___distro: Distro | None = None
|
||||
self.___config_paths: list[str] | None = None
|
||||
self.__root = self.uri.path.lstrip('/')
|
||||
self.__ctx = FcCache(self.__inner)
|
||||
|
|
@ -62,21 +91,18 @@ class KvFile(Base):
|
|||
return path[:-len(BLOB_SUFFIX)], True
|
||||
return path, False
|
||||
|
||||
async def __distro(self) -> Distro:
|
||||
if self.___distro is None:
|
||||
from ...Distro import Distro
|
||||
self.___distro = await Distro.instantiate(
|
||||
ec = self.__inner, default_path_filter = self.__backend_path_filter
|
||||
)
|
||||
return self.___distro
|
||||
|
||||
async def __config_paths(self) -> list[str]:
|
||||
if self.___config_paths is None:
|
||||
if self.__distro is None:
|
||||
from ...Distro import Distro
|
||||
from ...PackageFilter import PackageFilterString
|
||||
|
||||
pkg_filter_str = os.environ.get('JW_DEFAULT_PKG_FILTER')
|
||||
self.__distro = await Distro.instantiate(
|
||||
ec = self.__inner,
|
||||
default_pkg_filter = (
|
||||
PackageFilterString(pkg_filter_str) if pkg_filter_str else None
|
||||
),
|
||||
)
|
||||
ret: set[str] = set()
|
||||
for f in await self.__distro.pkg_files():
|
||||
for f in await (await self.__distro()).pkg_files():
|
||||
if not f.endswith('.jw-tmpl'):
|
||||
continue
|
||||
ret.add(f.lstrip('/')[:-len('.jw-tmpl')])
|
||||
|
|
|
|||
4
src/python/jw/pkg/lib/pf/Makefile
Normal file
4
src/python/jw/pkg/lib/pf/Makefile
Normal file
|
|
@ -0,0 +1,4 @@
|
|||
TOPDIR = ../../../../../..
|
||||
|
||||
include $(TOPDIR)/make/proj.mk
|
||||
include $(JWBDIR)/make/py-mod.mk
|
||||
90
src/python/jw/pkg/lib/pf/Pkg.py
Normal file
90
src/python/jw/pkg/lib/pf/Pkg.py
Normal file
|
|
@ -0,0 +1,90 @@
|
|||
from __future__ import annotations
|
||||
|
||||
import abc
|
||||
import os
|
||||
import re
|
||||
|
||||
from pathlib import Path
|
||||
from typing import TYPE_CHECKING, override
|
||||
|
||||
from ..PathFilter import PathFilter
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import Any, Iterable
|
||||
|
||||
from ..Distro import Distro
|
||||
from ..FileContext import FileContext
|
||||
from ..Package import Package
|
||||
|
||||
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): # export
|
||||
|
||||
def __add_parent_paths(self, paths: Iterable[str]) -> Iterable[str]:
|
||||
seen: dict[str, None] = {}
|
||||
for value in paths:
|
||||
path = Path(value)
|
||||
for item in (path, *path.parents):
|
||||
seen.setdefault(str(item), None)
|
||||
return list(seen)
|
||||
|
||||
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_pkg(self, package: Package) -> bool:
|
||||
raise NotImplementedError()
|
||||
|
||||
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(self.__add_parent_paths(await distro.pkg_files(names)))
|
||||
return path in self.__space
|
||||
|
||||
class Pkg(PackageFilter): # export
|
||||
|
||||
def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None:
|
||||
super().__init__(spec = spec, file_context = file_context, **kwargs)
|
||||
# -- Poor man's parsing for now
|
||||
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_pkg(self, package: Package) -> bool:
|
||||
if self.__criterion != 'url':
|
||||
return False
|
||||
url = package.url
|
||||
if url is None:
|
||||
return False
|
||||
return self.__rx.search(url) is not None
|
||||
|
|
@ -16,6 +16,7 @@ if TYPE_CHECKING:
|
|||
from argparse import Namespace
|
||||
|
||||
from .ExecContext import ExecContext
|
||||
from .PathFilter import PathFilter
|
||||
from .ProcFilter import ProcFilter, ProcPipeline
|
||||
|
||||
T = TypeVar('T')
|
||||
|
|
@ -177,6 +178,7 @@ async def copy(
|
|||
throw: bool = True,
|
||||
recursive: bool = False,
|
||||
parents: bool = False,
|
||||
default_path_filter: str | PathFilter | None = None,
|
||||
) -> Exception | str | list[str]:
|
||||
|
||||
async def __copy_tree(src_path: str, dst_path: str) -> list[str]:
|
||||
|
|
@ -211,7 +213,17 @@ async def copy(
|
|||
if not isinstance(src, (str, FileContext)):
|
||||
ret = []
|
||||
for uri in src: # TODO: Group identical netlocs into one CopyContext
|
||||
rr = await copy(uri, dst, owner, group, mode, throw, recursive, parents)
|
||||
rr = await copy(
|
||||
uri,
|
||||
dst,
|
||||
owner,
|
||||
group,
|
||||
mode,
|
||||
throw,
|
||||
recursive,
|
||||
parents,
|
||||
default_path_filter,
|
||||
)
|
||||
if isinstance(rr, Exception):
|
||||
return rr
|
||||
if isinstance(rr, list):
|
||||
|
|
@ -226,7 +238,8 @@ async def copy(
|
|||
|
||||
from .CopyContext import CopyContext
|
||||
|
||||
async with CopyContext(src, dst) as ctx:
|
||||
async with CopyContext(src, dst,
|
||||
default_path_filter = default_path_filter) as ctx:
|
||||
|
||||
src_uri = src.uri if isinstance(src, FileContext) else Uri(src)
|
||||
ret = '' if ctx.dst.chroot else ctx.dst.root
|
||||
|
|
|
|||
|
|
@ -3,7 +3,7 @@ usage: jw-pkg.py [--log-flags LOG_FLAGS] [--log-level LOG_LEVEL]
|
|||
[--log-file LOG_FILE] [--backtrace]
|
||||
[--write-profile WRITE_PROFILE]
|
||||
[--interactive {true,false,auto}] [--verbose]
|
||||
[--target TARGET] [--pkg-filter PKG_FILTER] [-t TOPDIR]
|
||||
[--target TARGET] [--path-filter PATH_FILTER] [-t TOPDIR]
|
||||
[--topdir-format TOPDIR_FORMAT] [-p PREFIX]
|
||||
[--distro-id DISTRO_ID] [-h]
|
||||
...
|
||||
|
|
@ -25,9 +25,9 @@ options:
|
|||
--verbose Be verbose on stderr about what's being done on the
|
||||
distro level (default: False)
|
||||
--target TARGET Run commands on this host (default: local)
|
||||
--pkg-filter PKG_FILTER
|
||||
Default filter for all distribution package-related
|
||||
operations (default: None)
|
||||
--path-filter PATH_FILTER
|
||||
Default path filter for the exec context, as a
|
||||
name:spec loader string (default: None)
|
||||
-t, --topdir TOPDIR Project Path (default: None)
|
||||
--topdir-format TOPDIR_FORMAT
|
||||
Output references to topdir as one of "make:<var-
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ from jw.pkg.lib.Distro import Distro
|
|||
from jw.pkg.lib.distros.suse.Distro import Distro as SuseDistro
|
||||
from jw.pkg.lib.ec.Local import Local
|
||||
from jw.pkg.lib.Package import Package
|
||||
from jw.pkg.lib.PackageFilter import PackageFilterString
|
||||
from jw.pkg.lib.pf.Pkg import Pkg
|
||||
from jw.pkg.lib.Result import Result
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
|
@ -271,7 +271,7 @@ sdf = SuseDistro(
|
|||
cl,
|
||||
id = 'suse',
|
||||
os_release_str = OS_RELEASE_SUSE,
|
||||
default_pkg_filter = PackageFilterString('url=~jw.dev')
|
||||
default_path_filter = Pkg(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 +281,7 @@ sde = SuseDistro(
|
|||
cl,
|
||||
id = 'suse',
|
||||
os_release_str = OS_RELEASE_SUSE,
|
||||
default_pkg_filter = PackageFilterString('url=~zzz-nomatch')
|
||||
default_path_filter = Pkg(spec = 'pkg:url=~zzz-nomatch', file_context = cl)
|
||||
)
|
||||
assert asyncio.run(sde.pkg_files()) == []
|
||||
assert '--queryformat' in cl.cmds[-1]
|
||||
|
|
|
|||
|
|
@ -4,4 +4,5 @@ include $(TOPDIR)/make/proj.mk
|
|||
include $(JWBDIR)/make/py-run.mk
|
||||
|
||||
all:
|
||||
|
||||
test: run
|
||||
131
test/unit/python/jw/pkg/lib/FileContext/test.py
Normal file
131
test/unit/python/jw/pkg/lib/FileContext/test.py
Normal file
|
|
@ -0,0 +1,131 @@
|
|||
import asyncio
|
||||
import os
|
||||
import tempfile
|
||||
|
||||
from typing import Any, override
|
||||
|
||||
from jw.pkg.lib.Distro import Distro
|
||||
from jw.pkg.lib.ec.Local import Local
|
||||
from jw.pkg.lib.PathFilter import DenyAction, PathFilter
|
||||
|
||||
class BlockedFilter(PathFilter):
|
||||
|
||||
def __init__(self, *, spec: str, blocked: str, **kwargs: Any) -> None:
|
||||
super().__init__(spec = spec, **kwargs)
|
||||
self.__blocked = blocked
|
||||
|
||||
@override
|
||||
async def _access(self, path: str, mode: int = os.F_OK) -> bool:
|
||||
return not (path == self.__blocked or path.startswith(self.__blocked + '/'))
|
||||
|
||||
class AllIgnoreFilter(PathFilter):
|
||||
|
||||
def __init__(self, *, spec: str, **kwargs: Any) -> None:
|
||||
super().__init__(spec = spec, **kwargs)
|
||||
|
||||
@override
|
||||
async def _access(self, path: str, mode: int = os.F_OK) -> bool:
|
||||
return False
|
||||
|
||||
class AbortingFilter(PathFilter):
|
||||
|
||||
def __init__(self, *, spec: str, abort: str, **kwargs: Any) -> None:
|
||||
super().__init__(spec = spec, deny_action = DenyAction.ABORT, **kwargs)
|
||||
self.__abort = abort
|
||||
|
||||
@override
|
||||
async def _access(self, path: str, mode: int = os.F_OK) -> bool:
|
||||
return not (path == self.__abort or path.startswith(self.__abort + '/'))
|
||||
|
||||
async def run_tests() -> None:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
for name in ('a/x', 'b/y'):
|
||||
p = os.path.join(tmp, name)
|
||||
os.makedirs(os.path.dirname(p), exist_ok = True)
|
||||
with open(p, 'w') as f:
|
||||
f.write('v\n')
|
||||
|
||||
fc = Local(
|
||||
f'local://{tmp}',
|
||||
chroot = True,
|
||||
default_path_filter = BlockedFilter(spec = 'test:b', blocked = 'b')
|
||||
)
|
||||
assert isinstance(fc.path_filter, BlockedFilter)
|
||||
|
||||
# -- An unfiltered address passes through
|
||||
assert (await fc.get('a/x')).stdout == b'v\n'
|
||||
|
||||
# -- A filtered address is not visible to reads
|
||||
try:
|
||||
await fc.get('b/y')
|
||||
raise AssertionError('filtered get() should not pass')
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
try:
|
||||
await fc.stat('b/y')
|
||||
raise AssertionError('filtered stat() should not pass')
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
|
||||
# -- A filtered write is a no-op, an unfiltered one lands
|
||||
await fc.put('b/z', b'v\n')
|
||||
assert not os.path.exists(os.path.join(tmp, 'b', 'z'))
|
||||
await fc.put('a/z', b'v\n')
|
||||
assert os.path.exists(os.path.join(tmp, 'a', 'z'))
|
||||
|
||||
# -- A filtered unlink leaves the file in place
|
||||
await fc.unlink('b/y')
|
||||
assert os.path.exists(os.path.join(tmp, 'b', 'y'))
|
||||
await fc.unlink('a/z')
|
||||
assert not os.path.exists(os.path.join(tmp, 'a', 'z'))
|
||||
|
||||
# -- A filtered rename is a no-op, in either direction
|
||||
await fc.rename('b/y', 'a/moved')
|
||||
assert os.path.exists(os.path.join(tmp, 'b', 'y'))
|
||||
assert not os.path.exists(os.path.join(tmp, 'a', 'moved'))
|
||||
await fc.rename('a/x', 'a/moved')
|
||||
assert os.path.exists(os.path.join(tmp, 'a', 'moved'))
|
||||
|
||||
# -- A filtered mkdir and erase are no-ops
|
||||
await fc.mkdir('b/d')
|
||||
assert not os.path.exists(os.path.join(tmp, 'b', 'd'))
|
||||
await fc.erase('b/y')
|
||||
assert os.path.exists(os.path.join(tmp, 'b', 'y'))
|
||||
|
||||
# -- readdir() drops the filtered entries
|
||||
assert set(await fc.readdir('')) == {'a'}
|
||||
assert set(await fc.readdir('a')) == {'moved'}
|
||||
|
||||
# -- filtered=False bypasses the filter
|
||||
assert (await fc.get('b/y', filtered = False)).stdout == b'v\n'
|
||||
assert (await fc.stat('b/y', filtered = False)) is not None
|
||||
await fc.put('b/w', b'v\n', filtered = False)
|
||||
assert os.path.exists(os.path.join(tmp, 'b', 'w'))
|
||||
|
||||
# -- An aborting verdict denies the operation outright
|
||||
ac = Local(
|
||||
f'local://{tmp}',
|
||||
chroot = True,
|
||||
default_path_filter = AbortingFilter(spec = 'test:b', abort = 'b')
|
||||
)
|
||||
try:
|
||||
await ac.get('b/y')
|
||||
raise AssertionError('aborted get() should not pass')
|
||||
except PermissionError:
|
||||
pass
|
||||
|
||||
# -- Without a filter, everything is visible
|
||||
plain = Local(f'local://{tmp}', chroot = True)
|
||||
assert set(await plain.readdir('')) == {'a', 'b'}
|
||||
|
||||
# -- The distribution probe reads /etc/os-release even on a
|
||||
# context whose filter ignores every path
|
||||
if os.path.exists('/etc/os-release'):
|
||||
ec = Local(
|
||||
'local', default_path_filter = AllIgnoreFilter(spec = 'test:all')
|
||||
)
|
||||
with open('/etc/os-release') as f:
|
||||
expected = f.read()
|
||||
assert await Distro.read_os_release_str(ec) == expected
|
||||
|
||||
asyncio.run(run_tests())
|
||||
|
|
@ -1,34 +0,0 @@
|
|||
from jw.pkg.lib.Package import Package
|
||||
from jw.pkg.lib.PackageFilter import PackageFilterString
|
||||
|
||||
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)
|
||||
# A package without a url never matches
|
||||
assert not f.match(pkg_nourl)
|
||||
|
||||
# Whitespace around the operator is tolerated
|
||||
f = PackageFilterString(' url =~ example')
|
||||
assert f.match(pkg)
|
||||
|
||||
# An unanchored regex matches anywhere in the url
|
||||
f = PackageFilterString('url=~jw-core$')
|
||||
assert f.match(pkg)
|
||||
assert not f.match(pkg_other)
|
||||
|
||||
# -- Unsupported definitions raise --
|
||||
|
||||
for definition in ('', 'url=example.com', 'name=jw-core', 'url ~ example'):
|
||||
try:
|
||||
PackageFilterString(definition)
|
||||
assert False, f'Should have raised for "{definition}"'
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
print('All PackageFilter tests passed')
|
||||
8
test/unit/python/jw/pkg/lib/PathFilter/Makefile
Normal file
8
test/unit/python/jw/pkg/lib/PathFilter/Makefile
Normal file
|
|
@ -0,0 +1,8 @@
|
|||
TOPDIR = ../../../../../../..
|
||||
|
||||
include $(TOPDIR)/make/proj.mk
|
||||
include $(JWBDIR)/make/py-run.mk
|
||||
|
||||
all:
|
||||
|
||||
test: run
|
||||
Some files were not shown because too many files have changed in this diff Show more
Loading…
Reference in a new issue