diff --git a/HASH b/HASH index 3e12e771..5aa14f71 100644 --- a/HASH +++ b/HASH @@ -1,4 +1,4 @@ -suse-tumbleweed/x86_64: 0f11ee4501fcdbb1e99e1b03c1ec2eaa +suse-tumbleweed/x86_64: 61628efd05405aa6e6498468b3df7538 suse-tumbleweed/i586: 86ea923ca3861900dd03d4b1da44f8b6 debian-10/amd64: 47167eb2d7fe2d845a1b12e0702a6e9b suse-42.3/x86_64: bd0e29fda82e38c89d2ed6f11797ce3a @@ -7,4 +7,4 @@ debian-8/amd64: b16e55fee0967a75aa67a4d859f0455d ubuntu-18.04/amd64: 190b5c45953399fd93354db0621d6f5f debian-10/armhf: 5d92c234d483deaf44c80cad168a8d5d debian-2025.4/amd64: 977965179baa6fd24d0975a05d583eb6 -kali-rolling/amd64: 9520b93fa4bdb6af3e75a78dd605b5a8 +kali-rolling/amd64: 61628efd05405aa6e6498468b3df7538 diff --git a/RELEASES b/RELEASES new file mode 100644 index 00000000..f4bd16c3 --- /dev/null +++ b/RELEASES @@ -0,0 +1,10 @@ +suse-tumbleweed/x86_64: 1.0.0-289 +suse-tumbleweed/i586: 1.0.0-44 +debian-10/amd64: 1.0.0-47 +suse-42.3/x86_64: 1.0.0-48 +centos-7/x86_64: 1.0.0-84 +debian-8/amd64: 1.0.0-84 +ubuntu-18.04/amd64: 1.0.0-99 +debian-10/armhf: 1.0.0-102 +debian-2025.4/amd64: 1.0.0-172 +kali-rolling/amd64: 1.0.0-289 diff --git a/VERSION b/VERSION index 8d4098dd..19b5421b 100644 --- a/VERSION +++ b/VERSION @@ -1 +1 @@ -1.0.0-294-dev +1.0.0-289-dev diff --git a/make/project.conf b/make/project.conf index 4827ad7e..9641d6d5 100644 --- a/make/project.conf +++ b/make/project.conf @@ -37,7 +37,6 @@ build = realpath [pkg.requires.suse] run = python3 release = rpmbuild, python3-base -lint = python3-ruff, python3-pyright [pkg.requires.debian] run = python3 diff --git a/make/projects-dir.mk b/make/projects-dir.mk index 0724beaa..d47d92a1 100644 --- a/make/projects-dir.mk +++ b/make/projects-dir.mk @@ -353,7 +353,7 @@ git-get-mini: $(SSH_WRAPPER_SH) PGIT_SH_PROJECTS="$(patsubst %/.git,%,$(wildcard $(addsuffix /.git,$(shell make -s build-order))))" $(PGIT_SH_GET_DEFAULT) git-pull-all: $(SSH_WRAPPER_SH) - $(PGIT_SH) pull $(PGIT_SH_OPTS_NETWORK) --all --tags + $(PGIT_SH) pull $(PGIT_SH_OPTS_NETWORK) --all git-get-maintainer: $(SSH_WRAPPER_SH) PGIT_SH_PROJECTS="$(PROJECTS_WITH_PROJECT_CONF)" $(PGIT_SH) exec make $@ diff --git a/make/rules.mk b/make/rules.mk index 3dbc26ba..1a1eea40 100644 --- a/make/rules.mk +++ b/make/rules.mk @@ -119,7 +119,7 @@ love: @echo "Not war?" cvsupdate update: - if [ -d "CVS" ]; then cvs update -dP || exit 1; else git pull --tags && git submodule update --init --recursive || exit 1; fi + if [ -d "CVS" ]; then cvs update -dP || exit 1; else git pull && git submodule update --init --recursive || exit 1; fi cvsdiff diff: if [ -d "CVS" ]; then cvs diff -u || exit 1; else git --no-pager diff --relative --no-prefix . || exit 1; fi diff --git a/make/topdir.mk b/make/topdir.mk index 56b612f7..3d51c7fa 100644 --- a/make/topdir.mk +++ b/make/topdir.mk @@ -280,7 +280,7 @@ git-get-maintainer: git-get-pub: set -e; if git remote | grep -q "^pub$$"; then \ - git fetch --prune --tags --recurse-submodules=on-demand pub master ;\ + git fetch --prune --recurse-submodules=on-demand pub master ;\ git submodule foreach --recursive 'git fetch --tags -f pub' ;\ git rebase --autostash pub/master ;\ git merge --ff-only pub/master ;\ @@ -303,7 +303,7 @@ pkg-install-release-deps: $(PKG_MANAGER) install $(shell $(proj_query_cmd) required-os-pkg --quote "build,run,release" $(PROJECT)) pkg-install-testbuild-deps: - $(PKG_MANAGER) install $(shell $(proj_query_cmd) pkg-requires --quote --hide-self --syntax names-only --delimiter " " "lint,build,run,devel,release" $(PROJECT)) + $(PKG_MANAGER) install $(shell $(proj_query_cmd) pkg-requires --quote --hide-self --syntax names-only --delimiter " " "build,run,devel,release" $(PROJECT)) recache-vars: rm -f $(TOPDIR)/make clean-cache cache diff --git a/scripts/pgit.sh b/scripts/pgit.sh index d9e68be5..70f0ee7b 100644 --- a/scripts/pgit.sh +++ b/scripts/pgit.sh @@ -263,7 +263,7 @@ cmd_get() run_git -C $project_dir remote add $remote_name $pull_url [ "$from_user" = "$remote_user" ] || run_git -C $project_dir remote set-url --push $remote_name no_push } - run_git -C $project_dir fetch --prune --tags --recurse-submodules=on-demand $remote_name $from_ref + run_git -C $project_dir fetch --prune --recurse-submodules=on-demand $remote_name $from_ref run_git -C $project_dir submodule foreach --recursive 'git fetch --tags -f origin' if [ "$to_ref" ]; then run_git -C $project_dir rebase --autostash $remote_name/$from_ref $to_ref diff --git a/scripts/pkg.sh b/scripts/pkg.sh index e83bb573..e3a2cffd 100644 --- a/scripts/pkg.sh +++ b/scripts/pkg.sh @@ -85,13 +85,6 @@ write_map() cmd_version -p `platform` $1 write $2 } -release_tags() -{ - # a release of a version on a platform is tagged - # v@ - git tag -l "v*@`platform`" -} - find_path() { local p @@ -130,7 +123,7 @@ check_scm() { if [ -d .git ]; then log + checking git - git pull --no-edit --tags || fatal "git pull failed, giving up" + git pull --no-edit || fatal "git pull failed, giving up" git submodule update --init --recursive || fatal "git submodule update failed, giving up" git status --porcelain | grep -v '^??' | grep -q . && { git status @@ -184,6 +177,12 @@ increase_build_no() check_next_version() { local v=`read_map $TOPDIR/VERSION | sed 's/-dev//'` + local n=`read_map -n $TOPDIR/RELEASES | sed 's/-dev//'` + if [ "$n" != "$v" ]; then + echo "+ $PKG_PROJECT version is already at $v, no need to increase for release" >&2 + echo $v + return + fi local h=`calculate_hash` [ -n "$h" ] || fatal "failed to calculate source hash" if [ ! -f $TOPDIR/HASH ]; then @@ -191,19 +190,12 @@ check_next_version() echo $v return fi - if ! grep -q $h $TOPDIR/HASH; then + if ! read_map $TOPDIR/HASH | grep -q $h; then echo "+ $PKG_PROJECT has no matching HASH value, needs release" >&2 increase_build_no $v return fi echo "+ $PKG_PROJECT has unchanged source" >&2 - if ! release_tags | grep -qF "v$v@"; then - # the release commit allocated $v and recorded the source hash; a missing tag means - # this platform has not released it yet, so release $v as is - echo "+ $PKG_PROJECT has no release tag for $v on `platform`, needs release" >&2 - echo $v - return - fi if [ "$reinstall_check_failed" = 1 ]; then echo "version $v is uninstallable, needs release" >&2 increase_build_no $v @@ -282,8 +274,8 @@ check_release_is_current() done shift - if ! release_tags | grep -qF "v$next@"; then - echo "next version $next is not released on `platform`, needs release" >&2 + if ! read_map -n $TOPDIR/RELEASES | grep -Fq $next; then + echo "next version $next is not in RELEASES, needs release" >&2 return 1 fi @@ -301,7 +293,7 @@ check_release_is_current() check_update_version() { - local comment="Release" + local comment="Start version" set -- `getopt 'c:' "$@"` while [ "$1" != -- ] ; do case "$1" in @@ -319,19 +311,8 @@ check_update_version() local next=`check_next_version` [ "$next" ] || fatal "Failed to get next version." if [ "$next" != "$v" ]; then - local h=`calculate_hash` - [ -n "$h" ] || fatal "failed to calculate source hash" - local files="VERSION $TOPDIR/HASH" - # the release tags replace the RELEASES file; the - # release commit drops it from the tree - if [ "$SCM" = git ] && [ -f $TOPDIR/RELEASES ] && \ - git rm -qf $TOPDIR/RELEASES 2>/dev/null; then - files="$files $TOPDIR/RELEASES" - fi echo "$next-dev" > VERSION - write_map $TOPDIR/HASH $h - $SCM add $TOPDIR/HASH || true - scm_commit -m "$comment $next" $files + scm_commit -m "$comment: $next" VERSION return 0 fi return 1 @@ -392,7 +373,6 @@ cmd_version() case $cmd in read) - [ -f "$file" ] || return 0 local p=`echo $platform | sed 's%/%\\\/%g'` local v=`sed "/$p:/ !d; s/$p: *//" $file` [ "$v" ] && { @@ -629,6 +609,8 @@ upload_pkg() set -e local p local v=`read_map $TOPDIR/VERSION | sed 's/-dev//'` + local h=`calculate_hash` + [ -n "$h" ] || fatal "failed to calculate source hash" case $PKG_FORMAT in rpm) server=pkg.janware.com @@ -675,12 +657,17 @@ upload_pkg() ;; esac + write_map $TOPDIR/RELEASES $v + $SCM add $TOPDIR/RELEASES || true + write_map $TOPDIR/HASH $h + $SCM add $TOPDIR/HASH || true echo "+ scheduling rebuild" $SSH -l root $server /opt/packager-server/bin/packager-server schedule-rebuild - local tag="v$v@`platform`" - git tag -m "Release $v@`platform`" "$tag" || fatal "Failed to tag the release as $tag" - # Don't use extra options, they might contain -l - JW_PKG_SSH_EXTRA_OPTS="" git push origin HEAD "$tag" || fatal "Failed to push the release commit and tag $tag" + scm_commit -m "Release $v@`platform`" $TOPDIR/RELEASES $TOPDIR/HASH + if [ "$SCM" = git ]; then + # Don't use extra options, they might contain -l + JW_PKG_SSH_EXTRA_OPTS="" git push || fatal "Failed to push changes to RELEASES and HASH" + fi } install_exe_wrapper() @@ -1310,7 +1297,7 @@ build) cmd_build "$@" ;; release-reinstall) - check_update_version + check_update_version -c "Start version" cmd_build "$@" cmd_upload ;; diff --git a/scripts/purge-stale-projects.sh b/scripts/purge-stale-projects.sh index 3e41caa0..ee71581a 100644 --- a/scripts/purge-stale-projects.sh +++ b/scripts/purge-stale-projects.sh @@ -116,7 +116,6 @@ for vcs in $vcss; do for p in $local_git_proj; do [ -L $p ] && continue [ -d $p ] || continue - git -C $p remote | grep -q . || { log "leaving \"$p\" alone, it has no remote"; continue; } echo $remote_git_proj | grep -q "\(^\| \)$p\($\| \)" && continue check_scm $p echo done checking scm diff --git a/src/python/jw/pkg/cmds/pkg/CmdLs.py b/src/python/jw/pkg/cmds/pkg/CmdLs.py index c162eda8..b3a74d6f 100644 --- a/src/python/jw/pkg/cmds/pkg/CmdLs.py +++ b/src/python/jw/pkg/cmds/pkg/CmdLs.py @@ -21,4 +21,4 @@ class CmdLs(NamedPkgsCmd): # export @override async def _run(self, args: Namespace) -> None: for name in args.names: - print('\n'.join(await self.distro.pkg_paths(name))) + print('\n'.join(await self.distro.pkg_files(name))) diff --git a/src/python/jw/pkg/cmds/projects/BaseCmdPkgRelations.py b/src/python/jw/pkg/cmds/projects/BaseCmdPkgRelations.py index 1d01b69a..98c42c27 100644 --- a/src/python/jw/pkg/cmds/projects/BaseCmdPkgRelations.py +++ b/src/python/jw/pkg/cmds/projects/BaseCmdPkgRelations.py @@ -71,7 +71,7 @@ class BaseCmdPkgRelations(Cmd): ) parser.add_argument( 'flavours', - help = 'Dependency flavours (lint, run, build, devel, release), ' + help = 'Dependency flavours (run, build, devel, release), ' 'separated by comma or whitespace' ) parser.add_argument('modules', nargs = '*', help = 'Modules') diff --git a/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py b/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py index 6a5ac7cd..8f5b8cf4 100644 --- a/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py +++ b/src/python/jw/pkg/cmds/secrets/lib/DistroContext.py @@ -33,12 +33,11 @@ class DistroContext(FilesContext): self.__distro = distro async def match_files(self, pkg_names: Collection[str], pattern: str) -> list[str]: - # -- One query for the whole name list: the distro backends - # accept a list and issue a single file-listing command ret: list[str] = [] - for path in await self.__distro.pkg_paths(list(pkg_names)): - if re.match(pattern, path): - ret.append(path) + for pkg_name in pkg_names: + for path in await self.__distro.pkg_files(pkg_name): + if re.match(pattern, path): + ret.append(path) return ret async def list_template_files(self, pkg_names: Collection[str]) -> list[str]: @@ -90,25 +89,20 @@ class DistroContext(FilesContext): ret: list[str] = [] failed: list[str] = [] missing = 0 - # -- Keep the exec context and the store open across the whole - # compile, so the run() calls in the per-target operations - # bump the reference counter instead of opening and closing - # the connection for every remote command. - async with self.ctx, self.store: - targets = await self.list_compilation_targets(pkg_names) - for target in targets: - try: - ok = await self.compile_template_file(target, default_attrs) - except Exception as e: - if not keep_going: - raise - log(ERR, f'{target}: {e}') - failed.append(target) - continue - if ok: - ret.append(target) - else: - missing += 1 + targets = await self.list_compilation_targets(pkg_names) + for target in targets: + try: + ok = await self.compile_template_file(target, default_attrs) + except Exception as e: + if not keep_going: + raise + log(ERR, f'{target}: {e}') + failed.append(target) + continue + if ok: + ret.append(target) + else: + missing += 1 if missing > 0: from ....lib.util import pretty_cmd diff --git a/src/python/jw/pkg/lib/Distro.py b/src/python/jw/pkg/lib/Distro.py index 2352be5a..b1f911c5 100644 --- a/src/python/jw/pkg/lib/Distro.py +++ b/src/python/jw/pkg/lib/Distro.py @@ -10,8 +10,6 @@ from typing import TYPE_CHECKING, Any from .base import InputMode from .log import ERR, INFO, WARNING, log -from .PathFilter import Verdict -from .pf.Pkg import PackageFilter if TYPE_CHECKING: from collections.abc import Collection @@ -22,6 +20,7 @@ if TYPE_CHECKING: from .FlaggedFile import FlaggedFile from .Package import Package from .PathFilter import PathFilter + from .pf.Pkg import PackageFilter class Distro(abc.ABC): @@ -505,13 +504,13 @@ class Distro(abc.ABC): return return await self._delete(names) - # -- pkg_paths + # -- pkg_files @abc.abstractmethod - async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: pass - async def pkg_paths(self, names: str | list[str] | None = None) -> Iterable[str]: + async def pkg_files(self, names: str | list[str] | None = None) -> Iterable[str]: # -- The file paths of the packages selected by the # argument: None, the default selection, filtered to the # app's packages when a filter is set, all installed @@ -520,49 +519,9 @@ class Distro(abc.ABC): # compatibility with the single-package call if isinstance(names, str): names = [names] - elif names is None and self.default_path_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_paths(names) - - # -- paths - - async def _paths( - self, - filter: PathFilter | None = None, - pkg_names: Collection[str] = [], - ) -> Iterable[str]: - if filter and pkg_names and not isinstance(filter, PackageFilter): - raise Exception( - f'Tried to select files from {self} with non-package-filter {filter} ' - f'and package list {", ".join(pkg_names)}' - ) - if not filter: - filter = self.__default_path_filter - # -- pkg_names follows the select() convention: an empty - # list selects every package, which is listed in one - # whole-system query instead of by name - if isinstance(filter, PackageFilter): - pkg_names = [p.name for p in await self._select(pkg_names, filter)] - ret: list[str] = [ - path for path in await self.pkg_paths(names = list(pkg_names)) - ] - elif pkg_names: - pkg_names = [p.name for p in await self._select_by_name(pkg_names)] - ret = [path for path in await self.pkg_paths(names = list(pkg_names))] - else: - # -- _pkg_paths() directly: pkg_paths() would re-resolve - # the default filter, which _paths() already did - ret = [path for path in await self._pkg_paths(None)] - if filter and not isinstance(filter, PackageFilter): - ret = [path for path in ret if await filter.run(path) == Verdict.ALLOW] - return ret - - async def paths( - self, - filter: PathFilter | None = None, - pkg_names: Collection[str] = [], - ) -> Iterable[str]: - return await self._paths(filter, pkg_names) + return await self._pkg_files(names) # -- verify diff --git a/src/python/jw/pkg/lib/FileContext.py b/src/python/jw/pkg/lib/FileContext.py index e5ced518..2caa26f9 100644 --- a/src/python/jw/pkg/lib/FileContext.py +++ b/src/python/jw/pkg/lib/FileContext.py @@ -124,31 +124,29 @@ class FileContext(abc.ABC): def chroot(self) -> bool: return self.__chroot - def _create_path_filter( - self, candidate: str | PathFilter | Literal[False] | None - ) -> 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) - @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 = self._create_path_filter(candidate) + 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._set_path_filter(value) - - def _set_path_filter(self, value: str | PathFilter | None | Literal[False]) -> None: self.__path_filter = None self.__default_path_filter = value diff --git a/src/python/jw/pkg/lib/PathFilter.py b/src/python/jw/pkg/lib/PathFilter.py index 6f0b43c4..dd1148aa 100644 --- a/src/python/jw/pkg/lib/PathFilter.py +++ b/src/python/jw/pkg/lib/PathFilter.py @@ -54,9 +54,7 @@ class PathFilter(abc.ABC): f'Unsupported filter spec "{spec}": expected a "name:spec" ' 'form, where the name picks the filter class' ) - from .util import kebab_to_pascal - - class_name = kebab_to_pascal(name) + class_name = name.capitalize() module_name = 'jw.pkg.lib.pf.' + class_name filter_classes: LoadTypes[PathFilter] = LoadTypes( [module_name], diff --git a/src/python/jw/pkg/lib/distros/arch/Distro.py b/src/python/jw/pkg/lib/distros/arch/Distro.py index 362c5708..cc31b9c4 100644 --- a/src/python/jw/pkg/lib/distros/arch/Distro.py +++ b/src/python/jw/pkg/lib/distros/arch/Distro.py @@ -67,7 +67,7 @@ class Distro(Base): ) @override - async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: raise NotImplementedError( 'distro pkg ls yet implemented for Arch-like distributions' ) diff --git a/src/python/jw/pkg/lib/distros/debian/Distro.py b/src/python/jw/pkg/lib/distros/debian/Distro.py index a9d73fa9..b6f472d0 100644 --- a/src/python/jw/pkg/lib/distros/debian/Distro.py +++ b/src/python/jw/pkg/lib/distros/debian/Distro.py @@ -156,7 +156,7 @@ class Distro(Base): await self.dpkg(['-P', *names], sudo = True) @override - async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: return await list_files(names, ec = self.ctx) @override diff --git a/src/python/jw/pkg/lib/distros/redhat/Distro.py b/src/python/jw/pkg/lib/distros/redhat/Distro.py index c8f6b77a..b365c3ad 100644 --- a/src/python/jw/pkg/lib/distros/redhat/Distro.py +++ b/src/python/jw/pkg/lib/distros/redhat/Distro.py @@ -88,7 +88,7 @@ class Distro(Base): await self.rpm(['-e', *names], sudo = True) @override - async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: return await list_files(names, ec = self.ctx) @override diff --git a/src/python/jw/pkg/lib/distros/suse/Distro.py b/src/python/jw/pkg/lib/distros/suse/Distro.py index aae12133..b143d839 100644 --- a/src/python/jw/pkg/lib/distros/suse/Distro.py +++ b/src/python/jw/pkg/lib/distros/suse/Distro.py @@ -107,7 +107,7 @@ class Distro(Base): await self.rpm(['-e', *names], sudo = True) @override - async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: return await list_files(names, ec = self.ctx) @override 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 afce76e5..afcca673 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/KvFile.py +++ b/src/python/jw/pkg/lib/ec/secret_store/KvFile.py @@ -18,7 +18,6 @@ from ...file_types import FT_COMPOUND, FT_DIR from ...FileContext import FileContext from ...kv import parse_kv, serialize_kv from ...PathFilter import PathFilter -from ...pf.PkgSecrets import PkgSecrets from ...Result import Result from .Base import Base from .layout import BLOB_SUFFIX, FT_SECRET, FT_SECRET_FILE, FT_SECRET_KEY, SECRET_SUFFIX @@ -33,9 +32,27 @@ class KvFile(Base): default_path_filter: str | PathFilter | None | Literal[False] = None, **kwargs: Any, ) -> None: - super().__init__( - uri, *args, default_path_filter = default_path_filter, **kwargs - ) + + 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( @@ -44,31 +61,12 @@ class KvFile(Base): f'{scheme}://{self.uri.authority}', chroot = False, **kwargs ), ) + self.__backend_path_filter = __create_backend_path_filter() self.___distro: Distro | None = None - self.___target_paths: list[str] | None = None + self.___config_paths: list[str] | None = None self.__root = self.uri.path.lstrip('/') self.__ctx = FcCache(self.__inner) - @override - def _create_path_filter( - self, candidate: str | PathFilter | Literal[False] | None - ) -> PathFilter | Literal[False]: - # -- The address space is scoped by a pkg-secrets filter - # backed by the inner connection, which alone knows the - # distribution; this context is a virtual layer over it - if candidate is None or candidate is False: - return False - if isinstance(candidate, PathFilter): - ret = candidate - else: - ret = PathFilter.create(spec = candidate, file_context = self.__inner) - if not isinstance(ret, PkgSecrets): - raise Exception( - f'A kvfile address space is scoped by a pkg-secrets ' - f'filter, not by {ret!r}' - ) - return ret - @override async def _open(self) -> None: await self.__inner.open() @@ -96,49 +94,49 @@ class KvFile(Base): async def __distro(self) -> Distro: if self.___distro is None: from ...Distro import Distro - self.___distro = await Distro.instantiate(ec = self.__inner) + self.___distro = await Distro.instantiate( + ec = self.__inner, default_path_filter = self.__backend_path_filter + ) return self.___distro - async def __target_paths(self) -> list[str]: - if self.___target_paths is None: - pf = self.path_filter - if isinstance(pf, PkgSecrets): - ret = await pf.target_paths() - else: - ret = await PkgSecrets.distro_target_paths( - await self.__distro(), filter = pf - ) - self.___target_paths = ret + async def __config_paths(self) -> list[str]: + if self.___config_paths is None: + ret: set[str] = set() + for f in await (await self.__distro()).pkg_files(): + if not f.endswith('.jw-tmpl'): + continue + ret.add(f.lstrip('/')[:-len('.jw-tmpl')]) + self.___config_paths = sorted(ret) warm = ['/'] - warm += [f'/{p}{SECRET_SUFFIX}' for p in self.___target_paths] - warm += [f'/{p}{BLOB_SUFFIX}' for p in self.___target_paths] + warm += [f'/{p}{SECRET_SUFFIX}' for p in self.___config_paths] + warm += [f'/{p}{BLOB_SUFFIX}' for p in self.___config_paths] dirs: set[str] = set() - for p in self.___target_paths: + for p in self.___config_paths: parts = p.split('/') for i in range(1, len(parts)): dirs.add('/'.join(parts[:i])) for d in sorted(dirs): warm += [f'/{d}', f'/{d}{SECRET_SUFFIX}', f'/{d}{BLOB_SUFFIX}'] await self.__ctx.warm(warm) - assert self.___target_paths is not None - return self.___target_paths + assert self.___config_paths is not None + return self.___config_paths - async def __compound_kv(self, target_path: str) -> dict[str, str]: - path = f'/{target_path.lstrip("/")}{SECRET_SUFFIX}' + async def __compound_kv(self, config_path: str) -> dict[str, str]: + path = f'/{config_path.lstrip("/")}{SECRET_SUFFIX}' if not await self.__ctx.file_exists(path): - raise FileNotFoundError(target_path) + raise FileNotFoundError(config_path) ret = await self.__ctx.get(path) return parse_kv(ret.stdout) - async def __is_compound(self, target_path: str) -> bool: - if not target_path: + async def __is_compound(self, config_path: str) -> bool: + if not config_path: return False - return await self.__ctx.file_exists(f'/{target_path}{SECRET_SUFFIX}') + return await self.__ctx.file_exists(f'/{config_path}{SECRET_SUFFIX}') @override async def _stat(self, path: str, follow_symlinks: bool) -> StatResult: path = self.__host_path(path) - target_path, is_blob = self.__strip_suffix(path) + config_path, is_blob = self.__strip_suffix(path) async def __stat_of(host_path: str, ftype: FileType) -> StatResult: st = await self.__ctx.stat(host_path, follow_symlinks) @@ -151,16 +149,16 @@ class KvFile(Base): size = st.size, ) - if not target_path: + if not config_path: return await __stat_of('/', FT_DIR) if is_blob: - secret_path = f'/{target_path}{BLOB_SUFFIX}' + secret_path = f'/{config_path}{BLOB_SUFFIX}' if not await self.__ctx.file_exists(secret_path): raise FileNotFoundError(errno.ENOENT, f'stat: {path}') return await __stat_of(secret_path, FT_SECRET_FILE) - if await self.__is_compound(target_path): - return await __stat_of(f'/{target_path}{SECRET_SUFFIX}', FT_SECRET) - parent, sep, key = target_path.rpartition('/') + if await self.__is_compound(config_path): + return await __stat_of(f'/{config_path}{SECRET_SUFFIX}', FT_SECRET) + parent, sep, key = config_path.rpartition('/') if sep and key: parent, _ = self.__strip_suffix(parent) if await self.__is_compound(parent) and \ @@ -173,41 +171,41 @@ class KvFile(Base): FT_SECRET_KEY, mode = st.mode, ) - secret_path = f'/{target_path}{BLOB_SUFFIX}' + secret_path = f'/{config_path}{BLOB_SUFFIX}' if await self.__ctx.file_exists(secret_path): return await __stat_of(secret_path, FT_SECRET_FILE) - if await self.__ctx.is_dir(f'/{target_path}'): - return await __stat_of(f'/{target_path}', FT_DIR) + if await self.__ctx.is_dir(f'/{config_path}'): + return await __stat_of(f'/{config_path}', FT_DIR) raise FileNotFoundError(errno.ENOENT, f'stat: {path}') @override async def _is_dir(self, path: str, follow_symlinks: bool) -> bool: path = self.__host_path(path) - target_path, is_blob = self.__strip_suffix(path) - if not target_path: + config_path, is_blob = self.__strip_suffix(path) + if not config_path: return True - parent, sep, _ = target_path.rpartition('/') + parent, sep, _ = config_path.rpartition('/') if sep: parent, _ = self.__strip_suffix(parent) if await self.__is_compound(parent): return False - if await self.__is_compound(target_path): + if await self.__is_compound(config_path): return True if is_blob: return False - return await self.__ctx.is_dir(f'/{target_path}') + return await self.__ctx.is_dir(f'/{config_path}') @override async def _readdir(self, path: str) -> Iterable[str]: path = self.__host_path(path) - target_path, is_blob = self.__strip_suffix(path) - if target_path and await self.__is_compound(target_path): - return (await self.__compound_kv(target_path)).keys() - if is_blob and await self.__ctx.file_exists(f'/{target_path}{BLOB_SUFFIX}'): + config_path, is_blob = self.__strip_suffix(path) + if config_path and await self.__is_compound(config_path): + return (await self.__compound_kv(config_path)).keys() + if is_blob and await self.__ctx.file_exists(f'/{config_path}{BLOB_SUFFIX}'): raise NotADirectoryError(path) children: set[str] = set() - prefix = f'{target_path}/' if target_path else '' - for cfg in await self.__target_paths(): + prefix = f'{config_path}/' if config_path else '' + for cfg in await self.__config_paths(): if not cfg.startswith(prefix): continue rest = cfg[len(prefix):] @@ -221,8 +219,8 @@ class KvFile(Base): children.add(f'{label}{SECRET_SUFFIX}') if await self.__ctx.file_exists(f'/{cfg}{BLOB_SUFFIX}'): children.add(f'{label}{BLOB_SUFFIX}') - if target_path and not children: - if not await self.__ctx.is_dir(f'/{target_path}'): + if config_path and not children: + if not await self.__ctx.is_dir(f'/{config_path}'): raise FileNotFoundError(path) return children @@ -231,23 +229,23 @@ class KvFile(Base): self, path: str, wd: str | None, throw: bool, verbose: bool | None, title: str ) -> Result: path = self.__host_path(path) - target_path, is_blob = self.__strip_suffix(path) + config_path, is_blob = self.__strip_suffix(path) if is_blob: - secret_path = f'/{target_path}{BLOB_SUFFIX}' + secret_path = f'/{config_path}{BLOB_SUFFIX}' if not await self.__ctx.file_exists(secret_path): raise FileNotFoundError(path) return await self.__ctx.get(secret_path) - secret_path = f'/{target_path}{SECRET_SUFFIX}' + secret_path = f'/{config_path}{SECRET_SUFFIX}' if await self.__ctx.file_exists(secret_path): return await self.__ctx.get(secret_path) - secret_path = f'/{target_path}{BLOB_SUFFIX}' + secret_path = f'/{config_path}{BLOB_SUFFIX}' if await self.__ctx.file_exists(secret_path): return await self.__ctx.get(secret_path) - if await self.__ctx.is_dir(f'/{target_path}'): + if await self.__ctx.is_dir(f'/{config_path}'): raise IsADirectoryError(errno.EISDIR, f'get: {path}') - if '/' not in target_path: + if '/' not in config_path: raise FileNotFoundError(path) - compound, key = target_path.rsplit('/', 1) + compound, key = config_path.rsplit('/', 1) compound, _ = self.__strip_suffix(compound) kv = await self.__compound_kv(compound) try: @@ -258,8 +256,8 @@ class KvFile(Base): @override async def _mkdir(self, path: str, mode: int, ftype: FileType) -> None: path = self.__host_path(path) - target_path, _ = self.__strip_suffix(path) - host_path = f'/{target_path}' + config_path, _ = self.__strip_suffix(path) + host_path = f'/{config_path}' if ftype.is_subtype(FT_COMPOUND): if await self.__ctx.file_exists(host_path + SECRET_SUFFIX): return @@ -297,7 +295,7 @@ class KvFile(Base): ftype: FileType, ) -> Result: path = self.__host_path(path) - target_path, is_blob = self.__strip_suffix(path) + config_path, is_blob = self.__strip_suffix(path) if ftype.is_subtype(FT_SECRET): if is_blob: raise ValueError( @@ -305,7 +303,7 @@ class KvFile(Base): ) m = 0o400 if mode is None else int(mode, 8) return await self.__ctx.put( - f'/{target_path}{SECRET_SUFFIX}', + f'/{config_path}{SECRET_SUFFIX}', content, owner = owner, group = group, @@ -315,14 +313,14 @@ class KvFile(Base): if ftype.is_subtype(FT_SECRET_FILE): m = 0o400 if mode is None else int(mode, 8) return await self.__ctx.put( - f'/{target_path}{BLOB_SUFFIX}', + f'/{config_path}{BLOB_SUFFIX}', content, owner = owner, group = group, mode = m, atomic = True, ) - compound, sep, key = target_path.rpartition('/') + compound, sep, key = config_path.rpartition('/') if not sep or not compound or not key or '/' in key: raise ValueError(f'put: "{path}" is not a compound/key path') compound, _ = self.__strip_suffix(compound) diff --git a/src/python/jw/pkg/lib/ec/secret_store/layout.py b/src/python/jw/pkg/lib/ec/secret_store/layout.py index ba8b54cd..67956350 100644 --- a/src/python/jw/pkg/lib/ec/secret_store/layout.py +++ b/src/python/jw/pkg/lib/ec/secret_store/layout.py @@ -12,9 +12,6 @@ from ...file_types import FT_COMPOUND, FT_REG, file_types # # Host-specific entries take precedence over default ones. -# Suffix of the template file accompanying a compiled target -TMPL_SUFFIX = '.jw-tmpl' - # Suffix of the key-value secret file accompanying a compiled target SECRET_SUFFIX = '.jw-secret' @@ -23,11 +20,11 @@ BLOB_SUFFIX = '.jw-secret-file' DEFAULT_PREFIX = 'default' -def target_name(name: str) -> str | None: - # -- The target path of a store or template file name: the - # name with its content suffix removed, or None if the - # name carries no suffix - for suffix in (TMPL_SUFFIX, SECRET_SUFFIX, BLOB_SUFFIX): +def content_name(name: str) -> str | None: + # -- The config path of an on-host secret file name: the name + # with its content suffix removed, or None if the name + # carries neither suffix + for suffix in (SECRET_SUFFIX, BLOB_SUFFIX): if name.endswith(suffix): return name.removesuffix(suffix) return None diff --git a/src/python/jw/pkg/lib/ec/ssh/AsyncSSH.py b/src/python/jw/pkg/lib/ec/ssh/AsyncSSH.py index 1cf75aef..cd7d53d6 100644 --- a/src/python/jw/pkg/lib/ec/ssh/AsyncSSH.py +++ b/src/python/jw/pkg/lib/ec/ssh/AsyncSSH.py @@ -439,23 +439,7 @@ class AsyncSSH(Base): await proc.stdin.drain() proc.stdin.write_eof() - finished = asyncio.create_task(proc.wait(check = False)) - try: - completed = await asyncio.shield(finished) - except asyncio.CancelledError: - # A Ctrl-C cancels this task while the connection is - # still open. Forward the interrupt to the remote process - # and wait for it to exit so we do not leave it (and its - # children) running. - if not finished.done(): - try: - proc.send_signal('INT') - except Exception as e: - log(DEBUG, f'Failed to send INT to remote process ({e})') - completed = await asyncio.shield(finished) - await asyncio.gather(*tasks) - raise - + completed = await proc.wait(check = False) await asyncio.gather(*tasks) stdout = b''.join(stdout_parts) if stdout_parts else None diff --git a/src/python/jw/pkg/lib/pf/Pkg.py b/src/python/jw/pkg/lib/pf/Pkg.py index a11e9a0c..b45dff44 100644 --- a/src/python/jw/pkg/lib/pf/Pkg.py +++ b/src/python/jw/pkg/lib/pf/Pkg.py @@ -65,33 +65,25 @@ class PackageFilter(FileContextFilter): # export async def _access(self, path: str, mode: int = os.F_OK) -> bool: if self.__space is None: distro = await self.distro() - self.__space = set( - self.__add_parent_paths(await distro.paths(filter = self)) - ) + 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) - self.__criterion, self.__rx = self._parse_spec(spec) - - def _parse_spec(self, spec: str) -> tuple[str | None, re.Pattern[str] | None]: - # -- Poor man's parsing for now: "pkg:criterion=~regex", - # where the criterion picks the package attribute to - # match + # -- 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}"') - return m.group(1), re.compile(m.group(2)) + self.__criterion = m.group(1) + self.__rx = re.compile(m.group(2)) @override def _match_pkg(self, package: Package) -> bool: - # -- A None criterion or regex matches every package - if self.__criterion not in (None, 'url'): + if self.__criterion != 'url': return False - if self.__rx is None: - return True url = package.url if url is None: return False diff --git a/src/python/jw/pkg/lib/pf/PkgSecrets.py b/src/python/jw/pkg/lib/pf/PkgSecrets.py deleted file mode 100644 index 15703dc3..00000000 --- a/src/python/jw/pkg/lib/pf/PkgSecrets.py +++ /dev/null @@ -1,91 +0,0 @@ -from __future__ import annotations - -import os -import re - -from pathlib import Path -from typing import TYPE_CHECKING, Any, override - -from ..ec.secret_store.layout import TMPL_SUFFIX, target_name -from .Pkg import Pkg - -if TYPE_CHECKING: - from ..Distro import Distro - from ..FileContext import FileContext - from ..PathFilter import PathFilter - -class PkgSecrets(Pkg): # export - - def __init__(self, *, spec: str, file_context: FileContext, **kwargs: Any) -> None: - super().__init__(spec = spec, file_context = file_context, **kwargs) - self.___targets: list[str] | None = None - self.___targets_set: set[str] | None = None - self.___targets_and_parents: set[str] | None = None - - @override - def _parse_spec(self, spec: str) -> tuple[str | None, re.Pattern[str] | None]: - # -- "pkg-secrets:criterion=~regex", following Pkg; a bare - # spec (no criterion) matches every installed package - m = re.match(r'^\s*pkg-secrets\s*:\s*(?:(\S+?)\s*=~\s*(.+?))?\s*$', spec) - if m is None: - raise Exception(f'Unsupported filter string "{spec}"') - criterion = m.group(1) - if criterion is not None and criterion != 'url': - raise Exception(f'Unsupported criterion "{criterion}" in "{spec}"') - rx = re.compile(m.group(2)) if m.group(2) is not None else None - return criterion, rx - - async def __targets(self) -> list[str]: - if self.___targets is None: - self.___targets = await self.distro_target_paths( - await self.distro(), filter = self - ) - return self.___targets - - async def __targets_set(self) -> set[str]: - if self.___targets_set is None: - self.___targets_set = set(await self.__targets()) - return self.___targets_set - - async def __targets_and_parents(self) -> set[str]: - if self.___targets_and_parents is None: - ret: set[str] = set() - cfgs = await self.__targets() - for p in cfgs: - item = Path(p) - for i in (item, *item.parents): - ret.add(str(i)) - self.___targets_and_parents = ret - return self.___targets_and_parents - - @override - async def _access(self, path: str, mode: int = os.F_OK) -> bool: - p = path.lstrip('/') - targets = target_name(p) - if targets is not None: - return targets in await self.__targets_and_parents() - if '/' in p: - parent = p.rpartition('/')[0] - ptargets = target_name(parent) - if ptargets is not None and ptargets in \ - await self.__targets_and_parents(): - return True - if parent in await self.__targets_set(): - return True - # -- A directory, a plain file, the root - return (p or '.') in await self.__targets_and_parents() - - @classmethod - async def distro_target_paths( - cls, - distro: Distro, - filter: PathFilter | None, - ) -> list[str]: - return sorted( - path.lstrip('/')[:-len(TMPL_SUFFIX)] - for path in await distro.paths(filter = filter) - if path.endswith(TMPL_SUFFIX) - ) - - async def target_paths(self) -> list[str]: - return await self.__targets() diff --git a/src/python/jw/pkg/lib/util.py b/src/python/jw/pkg/lib/util.py index f8eb78bd..ab06270c 100644 --- a/src/python/jw/pkg/lib/util.py +++ b/src/python/jw/pkg/lib/util.py @@ -2,7 +2,6 @@ from __future__ import annotations import json import os -import re import sys from enum import Enum, auto @@ -39,15 +38,6 @@ def pretty_cmd(cmd: list[str] | None = None, wd: str | None = None) -> str: ret += f' in {wd}' return ret -def kebab_to_pascal(value: str) -> str: - return ''.join(part.capitalize() for part in value.split('-')) - -def pascal_to_kebab(value: str) -> str: - # Handles normal CamelCase / PascalCase, including many acronym cases - s1 = re.sub(r'(.)([A-Z][a-z]+)', r'\1-\2', value) - s2 = re.sub(r'([a-z0-9])([A-Z])', r'\1-\2', s1) - return s2.lower() - # See ExecContext.run() for what this function does async def run_cmd( *args: Any, diff --git a/test/integration/jw_pkg/help/test-expected.txt b/test/integration/jw_pkg/help/test-expected.txt index ed24656b..0c711ccf 100644 --- a/test/integration/jw_pkg/help/test-expected.txt +++ b/test/integration/jw_pkg/help/test-expected.txt @@ -557,8 +557,8 @@ usage: jw-pkg.py projects pkg-conflicts [-h] [-S [SUBSECTIONS]] Print packages conflicting with a given package positional arguments: - flavours Dependency flavours (lint, run, build, devel, - release), separated by comma or whitespace + flavours Dependency flavours (run, build, devel, release), + separated by comma or whitespace modules Modules (default: None) options: @@ -608,8 +608,8 @@ usage: jw-pkg.py projects pkg-provides [-h] [-S [SUBSECTIONS]] Print packages and capabilities provided by a given package positional arguments: - flavours Dependency flavours (lint, run, build, devel, - release), separated by comma or whitespace + flavours Dependency flavours (run, build, devel, release), + separated by comma or whitespace modules Modules (default: None) options: @@ -660,8 +660,8 @@ usage: jw-pkg.py projects pkg-recommends [-h] [-S [SUBSECTIONS]] Print recommended packages positional arguments: - flavours Dependency flavours (lint, run, build, devel, - release), separated by comma or whitespace + flavours Dependency flavours (run, build, devel, release), + separated by comma or whitespace modules Modules (default: None) options: @@ -711,8 +711,8 @@ usage: jw-pkg.py projects pkg-requires [-h] [-S [SUBSECTIONS]] Print packages required for a given package positional arguments: - flavours Dependency flavours (lint, run, build, devel, - release), separated by comma or whitespace + flavours Dependency flavours (run, build, devel, release), + separated by comma or whitespace modules Modules (default: None) options: diff --git a/test/integration/jw_pkg/secrets/test.py b/test/integration/jw_pkg/secrets/test.py index b61ed17d..3daed322 100644 --- a/test/integration/jw_pkg/secrets/test.py +++ b/test/integration/jw_pkg/secrets/test.py @@ -72,7 +72,7 @@ class FakeDistro(SuseDistro): return [Package(name) for name in names if name in self.__files] @override - async def _pkg_paths(self, names: list[str] | None) -> list[str]: + async def _pkg_files(self, names: list[str] | None) -> list[str]: if names is None: names = list(self.__files) ret: list[str] = [] diff --git a/test/unit/python/jw/pkg/cmds/secrets/lib/FilesContext/test.py b/test/unit/python/jw/pkg/cmds/secrets/lib/FilesContext/test.py index 4e8920ef..11937687 100644 --- a/test/unit/python/jw/pkg/cmds/secrets/lib/FilesContext/test.py +++ b/test/unit/python/jw/pkg/cmds/secrets/lib/FilesContext/test.py @@ -4,15 +4,19 @@ import asyncio import grp import os import pwd +import sys import tempfile -from typing import override +from typing import TYPE_CHECKING, override from jw.pkg.cmds.secrets.lib.base import Attrs from jw.pkg.cmds.secrets.lib.FilesContext import FilesContext from jw.pkg.lib.ec.Local import Local from jw.pkg.lib.PathFilter import Verdict +if TYPE_CHECKING: + import os + # -- A context whose package space holds only the template, as on a # real host: the output file and the temp are not package files. # If the compile's own file operations honor the filter, the diff --git a/test/unit/python/jw/pkg/lib/Distro/test.py b/test/unit/python/jw/pkg/lib/Distro/test.py index 0ec1ef89..6af6c125 100644 --- a/test/unit/python/jw/pkg/lib/Distro/test.py +++ b/test/unit/python/jw/pkg/lib/Distro/test.py @@ -1,7 +1,6 @@ from __future__ import annotations import asyncio -import os from typing import TYPE_CHECKING, Iterable, cast, override @@ -9,7 +8,6 @@ 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.PathFilter import Handle, PathFilter from jw.pkg.lib.pf.Pkg import Pkg from jw.pkg.lib.Result import Result @@ -65,7 +63,7 @@ class DummyDistro(Distro): pass @override - async def _pkg_paths(self, names: list[str] | None) -> Iterable[str]: + async def _pkg_files(self, names: list[str] | None) -> Iterable[str]: return [] @override @@ -99,7 +97,7 @@ vd.verified = None assert asyncio.run(vd.verify()) == [] assert vd.verified is None -# -- pkg_paths -- +# -- pkg_files -- # -- Without a filter, the selection is passed through as the # whole system; the paths come back unfiltered @@ -115,7 +113,7 @@ class TmplDistro(DummyDistro): return [Package(n) for n in self.files] @override - async def _pkg_paths(self, names: list[str] | None) -> list[str]: + async def _pkg_files(self, names: list[str] | None) -> list[str]: if names is None: names = list(self.files) ret: list[str] = [] @@ -128,12 +126,12 @@ t.files = { 'a': ['/usr/share/a/a.conf.jw-tmpl', '/usr/bin/a'], 'b': ['/etc/b/b.conf.jw-tmpl'], } -assert sorted(asyncio.run(t.pkg_paths())) == [ +assert sorted(asyncio.run(t.pkg_files())) == [ '/etc/b/b.conf.jw-tmpl', '/usr/bin/a', '/usr/share/a/a.conf.jw-tmpl' ] # -- A single package name as a str is accepted for compatibility -assert sorted(asyncio.run(t.pkg_paths('a'))) == [ +assert sorted(asyncio.run(t.pkg_files('a'))) == [ '/usr/bin/a', '/usr/share/a/a.conf.jw-tmpl', ] @@ -254,9 +252,7 @@ class CannedRpmLocal(Local): ) -> Result: self.cmds.append(cmd) if '-qal' in cmd: - out = ('/usr/bin/x\n' - '/etc/a/a.conf.jw-tmpl\n' - '/etc/b/b.conf.jw-tmpl\n') + out = '/usr/bin/x\n/etc/a/a.conf.jw-tmpl\n' elif '-ql' in cmd: out = '/etc/a/a.conf.jw-tmpl\n/etc/b/b.conf.jw-tmpl\n' else: @@ -265,10 +261,9 @@ class CannedRpmLocal(Local): cl = CannedRpmLocal() sd = SuseDistro(cl, id = 'suse', os_release_str = OS_RELEASE_SUSE) -assert asyncio.run(sd.pkg_paths()) == [ +assert asyncio.run(sd.pkg_files()) == [ '/usr/bin/x', '/etc/a/a.conf.jw-tmpl', - '/etc/b/b.conf.jw-tmpl', ] assert cl.cmds[-1] == ['/usr/bin/rpm', '-qal'] @@ -278,7 +273,7 @@ sdf = SuseDistro( os_release_str = OS_RELEASE_SUSE, default_path_filter = Pkg(spec = 'pkg:url=~jw.dev', file_context = cl) ) -assert asyncio.run(sdf.pkg_paths()) == \ +assert asyncio.run(sdf.pkg_files()) == \ ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl'] assert cl.cmds[-1] == ['/usr/bin/rpm', '-ql', 'a', 'b'] @@ -288,48 +283,9 @@ sde = SuseDistro( os_release_str = OS_RELEASE_SUSE, default_path_filter = Pkg(spec = 'pkg:url=~zzz-nomatch', file_context = cl) ) -assert asyncio.run(sde.pkg_paths()) == [] +assert asyncio.run(sde.pkg_files()) == [] assert '--queryformat' in cl.cmds[-1] -# -- paths() -- - -# -- No filter and a bare path filter take the one-shot -# whole-system query, the second then checking the files one by -# one; a package filter selects the backing packages and lists -# their files by name; a path filter with package names is -# refused -class _AllowList(PathFilter): - - def __init__(self, allowed: set[str]) -> None: - super().__init__(spec = 'test:allow', handle = Handle(0)) - self.allowed = allowed - - @override - async def _access(self, path: str, mode: int = os.F_OK) -> bool: - return path in self.allowed - -allow = _AllowList({'/etc/b/b.conf.jw-tmpl'}) - -assert sorted(asyncio.run(sd.paths())) == \ - ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl', '/usr/bin/x'] -assert cl.cmds[-1] == ['/usr/bin/rpm', '-qal'] - -assert sorted( - asyncio.run(sd.paths(filter = Pkg(spec = 'pkg:url=~jw.dev', file_context = cl))) -) == ['/etc/a/a.conf.jw-tmpl', '/etc/b/b.conf.jw-tmpl'] -assert cl.cmds[-1] == ['/usr/bin/rpm', '-ql', 'a', 'b'] - -assert asyncio.run(sd.paths(filter = allow)) == ['/etc/b/b.conf.jw-tmpl'] -assert cl.cmds[-1] == ['/usr/bin/rpm', '-qal'] - -try: - asyncio.run(sd.paths(filter = allow, pkg_names = ['a'])) - assert False, 'Should have raised' -except AssertionError: - raise -except Exception: - pass - # -- _install_local_files -- # -- With dependency resolution, the files go to the package manager; 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 9da182fe..7cbaebbc 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 @@ -15,7 +15,6 @@ from jw.pkg.lib.ec.secret_store.layout import FT_SECRET, FT_SECRET_FILE, FT_SECR from jw.pkg.lib.file_types import FT_DIR from jw.pkg.lib.FileContext import FileContext from jw.pkg.lib.Package import Package -from jw.pkg.lib.pf.PkgSecrets import PkgSecrets async def run_tests() -> None: with tempfile.TemporaryDirectory() as tmp: @@ -213,7 +212,7 @@ async def run_tests() -> None: self.queries = 0 @override - async def _pkg_paths(self, names: list[str] | None) -> list[str]: + async def _pkg_files(self, names: list[str] | None) -> list[str]: self.queries += 1 return self.files @@ -347,120 +346,48 @@ async def run_tests() -> None: assert not os.path.exists(os.path.join(tree, 'etc', 'sub', 'conf.jw-secret')) await sstore.close() - patcher.stop() + # -- The autodetected distro applies the app's documented + # filter fallback: JW_DEFAULT_PATH_FILTER reaches + # Distro.instantiate() as the default path filter + astore = KvFile('kvfile://', default_path_filter = 'pkg:url=~jw.dev') + assert set(await astore.readdir('')) == {'tmp'} + flt = captured['kwargs'].get('default_path_filter') + assert flt is not None + assert flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) + assert not flt.match_pkg(Package('other', url = 'https://elsewhere/other.rpm')) - # -- The address space is scoped by a pkg-secrets filter, - # explicit or from the store URI's query: it scopes the - # operations and the enumeration alike, and a foreign - # filter kind is refused - class FilteredFake(SuseDistro): + # -- The backend filter also comes from the store URI's + # query's path-filter parameter; the constructor + # parameter wins + async def __flt_matches(flt: Any) -> None: + assert flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) + assert not flt.match_pkg( + Package('other', url = 'https://elsewhere/other.rpm') + ) - def __init__(self, pkgs: list[tuple[str, str, list[str]]]) -> None: - super().__init__(Local(), id = 'suse') - self.pkgs = pkgs - - # -- The package enumeration seam: Distro.paths() goes - # through _select(), which bottoms out here - @override - async def _select_by_name(self, names: Any) -> list[Package]: - ret = [Package(name = n, url = u) for n, u, _ in self.pkgs] - if names: - ret = [p for p in ret if p.name in names] - return ret - - @override - async def _pkg_paths(self, names: list[str] | None) -> list[str]: - ret: list[str] = [] - for n, _, files in self.pkgs: - if names is None or n in names: - ret.extend(files) - return ret - - ffake = FilteredFake( - [ - ( - 'fixture', - 'https://jw.dev/fixture.rpm', - [ - f'{tree}/etc/foo.conf.jw-tmpl', - f'{tree}/etc/cert.pem.jw-tmpl', - f'{tree}/etc/ghost.conf.jw-tmpl', - ], - ), - ( - 'other', - 'https://elsewhere.org/other.rpm', - [f'{tree}/etc/zzz.conf.jw-tmpl'], - ), - ] - ) - captured2: dict[str, Any] = {} - - async def __instantiate2(*args: Any, **kwargs: Any) -> FilteredFake: - captured2['kwargs'] = kwargs - return ffake - - patcher2 = mock.patch.object( - Distro, 'instantiate', new = classmethod(__instantiate2) - ) - patcher2.start() - with open(os.path.join(tree, 'etc', 'zzz.conf.jw-secret'), 'w') as f: - f.write('z=1\n') - - # -- Raw: no filter, every installed template is a config - # path, and the distro derivation carries no filter - rstore = KvFile('kvfile://') - assert rstore.path_filter is None - assert set(await rstore.readdir(f'{base}/etc')) == { - 'cert.pem.jw-secret-file', 'foo.conf.jw-secret', 'zzz.conf.jw-secret' - } - # -- The distro derivation carries no filter of its own - assert captured2['kwargs'].get('default_path_filter') is None - - # -- Scoped: only the matching packages back the address - # space; an unbacked entry is invisible and unwritable - fstore = KvFile('kvfile://', default_path_filter = 'pkg-secrets:url=~jw.dev') - assert isinstance(fstore.path_filter, PkgSecrets) - assert set(await fstore.readdir(f'{base}/etc')) == \ - {'cert.pem.jw-secret-file', 'foo.conf.jw-secret'} - try: - await fstore.get(f'{base}/etc/zzz.conf') - raise AssertionError('expected FileNotFoundError') - except FileNotFoundError: - pass - await fstore.put(f'{base}/etc/zzz.conf', b'z=2\n', ftype = FT_SECRET) - with open(os.path.join(tree, 'etc', 'zzz.conf.jw-secret')) as f: - assert f.read() == 'z=1\n' - # -- A backed address writes through - await fstore.put(f'{base}/etc/foo.conf/k9', b'v9', ftype = FT_SECRET_KEY) - assert (await fstore.get(f'{base}/etc/foo.conf/k9')).stdout == b'v9' - - # -- The query's path-filter parameter - qstore = KvFile('kvfile://?path-filter=pkg-secrets%3Aurl%3D~elsewhere') - assert isinstance(qstore.path_filter, PkgSecrets) - assert set(await qstore.readdir(f'{base}/etc')) == {'zzz.conf.jw-secret'} - - # -- An unrelated query parameter is not a filter spec + # No query, no parameter: no filter + s = KvFile('kvfile://') + await s.readdir('') + assert captured['kwargs'].get('default_path_filter') is None + # The query's path-filter parameter + s = KvFile('kvfile://?path-filter=pkg%3Aurl%3D~jw.dev') + await s.readdir('') + await __flt_matches(captured['kwargs'].get('default_path_filter')) + # An unrelated query parameter is not a filter spec s = KvFile('kvfile://?foo=bar') - assert s.path_filter is None - - # -- The query wins over the constructor parameter - wstore = KvFile( - 'kvfile://?path-filter=pkg-secrets%3Aurl%3D~jw.dev', - default_path_filter = 'pkg-secrets:url=~elsewhere', + await s.readdir('') + assert captured['kwargs'].get('default_path_filter') is None + # The constructor parameter wins over the query + s = KvFile( + 'kvfile://?path-filter=pkg%3Aurl%3D~jw.dev', + default_path_filter = 'pkg:url=~zzz-nomatch', ) - assert set(await wstore.readdir(f'{base}/etc') - ) == {'cert.pem.jw-secret-file', 'foo.conf.jw-secret'} + await s.readdir('') + flt = captured['kwargs'].get('default_path_filter') + assert flt is not None + assert not flt.match_pkg(Package('fixture', url = 'https://jw.dev/fixture.rpm')) - # -- A foreign filter kind is refused at resolution - xstore = KvFile('kvfile://', default_path_filter = 'pkg:url=~jw.dev') - try: - xstore.path_filter - raise AssertionError('expected Exception') - except Exception as e: - assert 'pkg-secrets' in str(e) - - patcher2.stop() + patcher.stop() # -- The lifecycle propagates to the host context: an # open() pin on the store keeps the host's transport diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py index a8f4c8fd..a6d163cd 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/Sops/test.py @@ -336,7 +336,7 @@ async def run_tests() -> None: self.files = files @override - async def _pkg_paths(self, names: list[str] | None) -> list[str]: + async def _pkg_files(self, names: list[str] | None) -> list[str]: return self.files fake = FakeDistro( diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py index b89de064..b202b15a 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/TarGpg/test.py @@ -321,7 +321,7 @@ async def run_tests() -> None: self.files = files @override - async def _pkg_paths(self, names: list[str] | None) -> list[str]: + async def _pkg_files(self, names: list[str] | None) -> list[str]: return self.files fake = FakeDistro( diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py index 1ae661a6..ff3892b6 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/Vault/test.py @@ -351,7 +351,7 @@ async def run_tests() -> None: self.files = files @override - async def _pkg_paths(self, names: list[str] | None) -> list[str]: + async def _pkg_files(self, names: list[str] | None) -> list[str]: return self.files fake = FakeDistro( diff --git a/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py b/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py index 477b3208..17b8d90e 100644 --- a/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py +++ b/test/unit/python/jw/pkg/lib/ec/secret_store/layout/test.py @@ -5,8 +5,8 @@ from jw.pkg.lib.ec.secret_store.layout import ( FT_SECRET_FILE, FT_SECRET_KEY, SECRET_SUFFIX, + content_name, host_prefix, - target_name, ) from jw.pkg.lib.file_types import FT_COMPOUND, FT_DIR, FT_REG @@ -15,11 +15,11 @@ assert DEFAULT_PREFIX == 'default' assert SECRET_SUFFIX == '.jw-secret' assert BLOB_SUFFIX == '.jw-secret-file' -# target_name strips the content suffix, and names without a +# content_name strips the content suffix, and names without a # content suffix are not store content -assert target_name('etc/a.jw-secret') == 'etc/a' -assert target_name('etc/c.pem.jw-secret-file') == 'etc/c.pem' -assert target_name('etc/README.md') is None +assert content_name('etc/a.jw-secret') == 'etc/a' +assert content_name('etc/c.pem.jw-secret-file') == 'etc/c.pem' +assert content_name('etc/README.md') is None # An FQDN maps to its reversed, dot-split host root assert host_prefix('host.example.com') == 'com/example/host' diff --git a/test/unit/python/jw/pkg/lib/pf/Pkg/test.py b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py index 16656998..ad10bde0 100644 --- a/test/unit/python/jw/pkg/lib/pf/Pkg/test.py +++ b/test/unit/python/jw/pkg/lib/pf/Pkg/test.py @@ -6,7 +6,6 @@ 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.PathFilter import PathFilter from jw.pkg.lib.pf.Pkg import Pkg if TYPE_CHECKING: @@ -66,13 +65,6 @@ for definition in ('', f = Pkg(file_context = fc, spec = 'pkg:url=~example\\.com') assert repr(f) == 'filter:pkg:url=~example\\.com' -# -- PathFilter.create() resolves the name kebab-to-pascal -- - -f3 = PathFilter.create(spec = 'pkg:url=~example\\.com', file_context = fc) -assert isinstance(f3, Pkg) -assert f3.match_pkg(pkg) -assert not f3.match_pkg(pkg_other) - class _FakeDistro: def __init__(self, pkgs: list[tuple[str, str | None, list[str]]]) -> None: @@ -85,23 +77,13 @@ class _FakeDistro: filter: Any = None) -> list[Package]: return [p for p, _ in self.__pkgs if filter is None or filter.match_pkg(p)] - async def pkg_paths(self, names: list[str] | None = None) -> list[str]: + 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 - async def paths(self, filter: Any = None, pkg_names: Any = []) -> list[str]: - ret: list[str] = [] - for p, files in self.__pkgs: - if filter is not None and not filter.match_pkg(p): - continue - if pkg_names and p.name not in pkg_names: - continue - ret.extend(files) - return ret - fake = _FakeDistro( [ ( diff --git a/test/unit/python/jw/pkg/lib/pf/PkgSecrets/Makefile b/test/unit/python/jw/pkg/lib/pf/PkgSecrets/Makefile deleted file mode 100644 index 49c7c21f..00000000 --- a/test/unit/python/jw/pkg/lib/pf/PkgSecrets/Makefile +++ /dev/null @@ -1,7 +0,0 @@ -TOPDIR = ../../../../../../../../ - -include $(TOPDIR)/make/proj.mk -include $(JWBDIR)/make/py-run.mk - -all: -test: run diff --git a/test/unit/python/jw/pkg/lib/pf/PkgSecrets/test.py b/test/unit/python/jw/pkg/lib/pf/PkgSecrets/test.py deleted file mode 100644 index 35d706f7..00000000 --- a/test/unit/python/jw/pkg/lib/pf/PkgSecrets/test.py +++ /dev/null @@ -1,138 +0,0 @@ -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.PathFilter import PathFilter, Verdict -from jw.pkg.lib.pf.PkgSecrets import PkgSecrets - -if TYPE_CHECKING: - from jw.pkg.lib.Result import Result - -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() - -# -- Unsupported specs raise at construction -- - -for bad in ['pkg-secrets', 'pkg-secrets:uri', 'pkg-secrets:name=~x']: - try: - PkgSecrets(spec = bad, file_context = _StubFC()) - assert False, f'Should have raised for "{bad}"' - except Exception: - pass - -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_paths(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 - - async def paths(self, filter: Any = None, pkg_names: Any = []) -> list[str]: - ret: list[str] = [] - for p, files in self.__pkgs: - if filter is not None and not filter.match_pkg(p): - continue - if pkg_names and p.name not in pkg_names: - continue - ret.extend(files) - return ret - -fake = _FakeDistro( - [ - ( - 'fixture', - 'https://example.com/fixture.rpm', - ['/etc/foo.conf.jw-tmpl', '/etc/fixture.conf', '/opt/jw-x/app.ini.jw-tmpl'], - ), - ('other', 'https://elsewhere.org/other.rpm', ['/etc/bar.conf.jw-tmpl']), - ] -) - -async def __run_tests() -> None: - from unittest import mock - - from jw.pkg.lib.Distro import Distro - from jw.pkg.lib.ec.Local import Local - - async def __instantiate(*args: Any, **kwargs: Any) -> _FakeDistro: - return fake - - with mock.patch.object(Distro, 'instantiate', new = classmethod(__instantiate)): - # -- Unscoped: every installed package backs - f = PkgSecrets(spec = 'pkg-secrets:', file_context = Local('local')) - # A compound, a key below it, and a blob are all addressable - assert await f.run('etc/foo.conf.jw-secret') == Verdict.ALLOW - assert await f.run('etc/foo.conf.jw-secret/key') == Verdict.ALLOW - # -- A key below the compound, its name unsuffixed - assert await f.run('etc/foo.conf/key') == Verdict.ALLOW - assert await f.run('opt/jw-x/app.ini/key') == Verdict.ALLOW - assert await f.run('etc/plain/key') == Verdict.IGNORE - assert await f.run('etc/foo.conf.jw-secret-file') == Verdict.ALLOW - # A deep target path - assert await f.run('opt/jw-x/app.ini.jw-secret') == Verdict.ALLOW - # The other package backs too, unscoped - assert await f.run('etc/bar.conf.jw-secret-file') == Verdict.ALLOW - # A plain file is not a target path - assert await f.run('etc/fixture.conf') == Verdict.IGNORE - # No template for this target path: the orphan case - assert await f.run('etc/fixture.conf.jw-secret') == Verdict.IGNORE - assert await f.run('nope.jw-secret') == Verdict.IGNORE - # Directories leading to target paths, and the root - assert await f.run('etc') == Verdict.ALLOW - assert await f.run('opt/jw-x') == Verdict.ALLOW - assert await f.run('') == Verdict.ALLOW - - # -- The backing set, as the filter computes it - assert await f.target_paths() == [ - 'etc/bar.conf', 'etc/foo.conf', 'opt/jw-x/app.ini' - ] - - # -- Scoped: only the matching packages back - f2 = PkgSecrets( - spec = 'pkg-secrets:url=~example\\.com', file_context = Local('local') - ) - assert await f2.run('etc/foo.conf.jw-secret') == Verdict.ALLOW - assert await f2.run('etc/bar.conf.jw-secret') == Verdict.IGNORE - assert await f2.target_paths() == ['etc/foo.conf', 'opt/jw-x/app.ini'] - - # -- PathFilter.create() resolves the kebab name - f3 = PathFilter.create( - spec = 'pkg-secrets:url=~example\\.com', file_context = Local('local') - ) - assert isinstance(f3, PkgSecrets) - - # -- A context that cannot be probed rejects - f4 = PkgSecrets(spec = 'pkg-secrets:', file_context = _StubFC()) - try: - await f4.run('etc/foo.conf.jw-secret') - 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 lib.pf.PkgSecrets tests passed') diff --git a/test/unit/python/jw/pkg/lib/util/test.py b/test/unit/python/jw/pkg/lib/util/test.py index aaf65cbc..8771a905 100644 --- a/test/unit/python/jw/pkg/lib/util/test.py +++ b/test/unit/python/jw/pkg/lib/util/test.py @@ -4,19 +4,12 @@ import stat import tempfile from jw.pkg.lib.ec.Local import Local -from jw.pkg.lib.util import copy, kebab_to_pascal, pascal_to_kebab +from jw.pkg.lib.util import copy def uri(path: str) -> str: return 'local://localhost' + path async def run_tests() -> None: - # -- kebab <-> pascal: the name conversion behind the dynamic - # loading of filters and, later, file contexts - assert kebab_to_pascal('pkg') == 'Pkg' - assert kebab_to_pascal('pkg-secrets') == 'PkgSecrets' - assert pascal_to_kebab('Pkg') == 'pkg' - assert pascal_to_kebab('PkgSecrets') == 'pkg-secrets' - with tempfile.TemporaryDirectory() as tmp: # -- Source tree #