jw.pkg: Fix "make check" static code check fallout
The previous commits have put rules for linting and formatting via
ruff, yapf, mypy and pyright into place. They are checked with the
make check target, and this commit adds the fixes for the target to
succeed.
It does some refactoring where type checking dug up dirty bits, and
also adds lots of churn in the Python code. To a good deal, that's
owed to mere formatting changes. It would have been better to
seperate those from syntax and refactoring fixes into multiple
commits, so that the interesting changes don't drown in the
formatting nose. However, that would have been a lot of additional
work only to be thrown away by later commits, hence this commit has a
big diff in one piece. The size of the diff is regrettable but
hopefully a one-off: What it buys is automatic format checking for CI
and predictble formats for smaller diffs in the future.
Rules that "make check" enforces are, in the following order
- Syntax checkers:
- ruff check .
- mypy .
- pyright
- Format check:
- yapf --diff --recursive .
The refactoring includes:
- Turn the Result class into a more elaborate object, capable of
doing more heavy lifting around stderr and stdout decoding,
summarizing outcome, and matching error strings.
Aside from fixing broken type checks, this also removes lots of
boilerplate calling code which is currently used for handling
possible call outcome scenarios. Trying to access an inexistent,
decoded string should raise a meaningful exception by itself now,
which removes lots of code with case distinctions.
- Fix Cmd type hierarchy:
- Add the AbstractCmd class above Cmd. This is necessary because
the checker rightfully complains it can't instantiate a Cmd
instance where constructor arguments were needed. They never
were, but the type used at the instantiating code's location in
jw.pkg.App so claims.
- Lots of sub- and sub-subcommands are derived from the base
class of the invoking command. That provides some properties
shared across the ancestor hierarchy of a command, but is
semantically unsound. Fix that by introducing jw.pkg.BaseCmd
class as a place to provide basic helpers shared across all
commands used in a jw.pkg.App's context, and derive all command
classes from that afresh. The parent command is still reachable
via a common parent property.
Formatting changes are conforming to PEP-8, mostly, with minor
tweaks. All in all they include the following changes.
- Remove # -*- coding: utf-8 -*-
The line was needed by Python 2 which is not supported anylonger.
For Python 3, the default encoding is UTF-8, anyway.
- Allow to run "make py-format" without having it produce any
changes. It's basically "yapf --in-place --recursive ." with some
code style settings, see conf/topdir/pyproject.toml. The settings
may be debatable. I've had custom tweaks in place on that target,
too, but then again, IDEs would have more hassle to integrate
that.
- Introduce a 88 character line length limit
- One import per line, reshuffle them semantically, see
[tool.isort] in pyproject.toml.
- Hide imports needed for type-checking only behind
if TYPE_CHECKING
- Spaces around assignments accounts for much churn. Having having
no spaces in inline parameter list assignments and default
parameter values would arguably be more compact where it's
useful. On the other hand, I have not found a code formatter
which allows spaces around assignments in parameter lists broken
into one per line and that's often better than a wall of text.
- Add two spaces before # export, as this seems to be mandated by
PEP-8
- Use single quotes by default
Signed-off-by: Jan Lindemann <jan@janware.com>
This commit is contained in:
parent
8c5c98c95a
commit
6db73873e7
97 changed files with 3229 additions and 1893 deletions
|
|
@ -1,24 +1,22 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from argparse import ArgumentParser
|
||||
from functools import cached_property
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from ..Cmd import Cmd as Base
|
||||
from ...CmdBase import CmdBase
|
||||
from ..CmdSecrets import CmdSecrets as Parent
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import Iterable
|
||||
from ...lib.Distro import Distro
|
||||
from ...lib.ExecContext import ExecContext
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
from .lib.base import Attrs
|
||||
|
||||
from .lib.DistroContext import DistroContext
|
||||
|
||||
class Cmd(Base): # export
|
||||
class Cmd(CmdBase): # export
|
||||
|
||||
@cached_property
|
||||
def ctx(self) -> ExecContext:
|
||||
def ctx(self) -> DistroContext:
|
||||
return DistroContext(self.app.distro)
|
||||
|
||||
async def _match_files(self, packages: Iterable[str], pattern: str) -> list[str]:
|
||||
|
|
@ -27,21 +25,27 @@ class Cmd(Base): # export
|
|||
async def _list_template_files(self, packages: Iterable[str]) -> list[str]:
|
||||
return await self.ctx.list_template_files(packages)
|
||||
|
||||
async def _list_secret_paths(self, packages: Iterable[str], ignore_missing: bool=False) -> list[str]:
|
||||
async def _list_secret_paths(
|
||||
self, packages: Iterable[str], ignore_missing: bool = False
|
||||
) -> list[str]:
|
||||
return await self.ctx.list_secret_paths(packages, ignore_missing)
|
||||
|
||||
async def _list_compilation_targets(self, packages: Iterable[str], ignore_missing: bool=False) -> list[str]:
|
||||
async def _list_compilation_targets(
|
||||
self, packages: Iterable[str], ignore_missing: bool = False
|
||||
) -> list[str]:
|
||||
return await self.ctx.list_compilation_targets(packages, ignore_missing)
|
||||
|
||||
async def _remove_compilation_targets(self, packages: Iterable[str]) -> list[str]:
|
||||
return await self.ctx.remove_compilation_targets(packages)
|
||||
|
||||
async def _compile_template_files(self, packages: Iterable[str], default_attrs: Attrs) -> list[str]:
|
||||
async def _compile_template_files(
|
||||
self, packages: Iterable[str], default_attrs: Attrs
|
||||
) -> list[str]:
|
||||
return await self.ctx.compile_template_files(packages, default_attrs)
|
||||
|
||||
def __init__(self, parent: CmdSecrets, name: str, help: str) -> None:
|
||||
def __init__(self, parent: Parent, name: str, help: str) -> None:
|
||||
super().__init__(parent, name, help)
|
||||
|
||||
def add_arguments(self, parser: ArgumentParser) -> None:
|
||||
super().add_arguments(parser)
|
||||
parser.add_argument("packages", nargs='*', help="Package names")
|
||||
parser.add_argument('packages', nargs = '*', help = 'Package names')
|
||||
|
|
|
|||
|
|
@ -1,20 +1,21 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .Cmd import Cmd
|
||||
from .lib.base import Attrs
|
||||
|
||||
from .Cmd import Cmd
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
from argparse import Namespace, ArgumentParser
|
||||
from argparse import ArgumentParser, Namespace
|
||||
|
||||
class CmdCompileTemplates(Cmd): # export
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
|
||||
class CmdCompileTemplates(Cmd): # export
|
||||
|
||||
def __init__(self, parent: CmdSecrets) -> None:
|
||||
super().__init__(parent, 'compile-templates', help="Compile package template files")
|
||||
super().__init__(
|
||||
parent, 'compile-templates', help = 'Compile package template files'
|
||||
)
|
||||
|
||||
async def _run(self, args: Namespace) -> None:
|
||||
attrs = Attrs(args.mode, args.owner, args.group, None)
|
||||
|
|
@ -22,6 +23,12 @@ class CmdCompileTemplates(Cmd): # export
|
|||
|
||||
def add_arguments(self, parser: ArgumentParser) -> None:
|
||||
super().add_arguments(parser)
|
||||
parser.add_argument('--owner', '-o', default=None, help='Default output file owner')
|
||||
parser.add_argument('--group', '-g', default=None, help='Default output file group')
|
||||
parser.add_argument('--mode', '-m', default=None, help='Default output file mode')
|
||||
parser.add_argument(
|
||||
'--owner', '-o', default = None, help = 'Default output file owner'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--group', '-g', default = None, help = 'Default output file group'
|
||||
)
|
||||
parser.add_argument(
|
||||
'--mode', '-m', default = None, help = 'Default output file mode'
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,22 +1,33 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .Cmd import Cmd
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
from argparse import Namespace, ArgumentParser
|
||||
from argparse import ArgumentParser, Namespace
|
||||
|
||||
class CmdInstall(Cmd): # export
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
|
||||
class CmdInstall(Cmd): # export
|
||||
|
||||
def __init__(self, parent: CmdSecrets) -> None:
|
||||
super().__init__(parent, 'install', help='Install secrets from various sources as static secrets onto the target')
|
||||
super().__init__(
|
||||
parent,
|
||||
'install',
|
||||
help = (
|
||||
'Install secrets from various sources as static secrets onto the target'
|
||||
),
|
||||
)
|
||||
|
||||
def add_arguments(self, parser: ArgumentParser) -> None:
|
||||
parser.add_argument('src', help='URI of secret source')
|
||||
parser.add_argument('--only-missing', action='store_true', default=False, help='Install only secrets not already on the target')
|
||||
parser.add_argument('src', help = 'URI of secret source')
|
||||
parser.add_argument(
|
||||
'--only-missing',
|
||||
action = 'store_true',
|
||||
default = False,
|
||||
help = 'Install only secrets not already on the target',
|
||||
)
|
||||
super().add_arguments(parser)
|
||||
|
||||
async def _run(self, args: Namespace) -> None:
|
||||
|
|
|
|||
|
|
@ -1,22 +1,37 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .Cmd import Cmd
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
from argparse import Namespace, ArgumentParser
|
||||
from argparse import ArgumentParser, Namespace
|
||||
|
||||
class CmdListCompilationOutput(Cmd): # export
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
|
||||
class CmdListCompilationOutput(Cmd): # export
|
||||
|
||||
def __init__(self, parent: CmdSecrets) -> None:
|
||||
super().__init__(parent, 'list-compilation-output', help="List package compilation output files")
|
||||
super().__init__(
|
||||
parent,
|
||||
'list-compilation-output',
|
||||
help = 'List package compilation output files',
|
||||
)
|
||||
|
||||
def add_arguments(self, parser: ArgumentParser) -> None:
|
||||
super().add_arguments(parser)
|
||||
parser.add_argument("--all", action='store_true', default=False, help="Show all output targets, including non-existent files")
|
||||
parser.add_argument(
|
||||
'--all',
|
||||
action = 'store_true',
|
||||
default = False,
|
||||
help = 'Show all output targets, including non-existent files',
|
||||
)
|
||||
|
||||
async def _run(self, args: Namespace) -> None:
|
||||
print('\n'.join(await self._list_compilation_targets(args.packages, ignore_missing=(not args.all))))
|
||||
print(
|
||||
'\n'.join(
|
||||
await self._list_compilation_targets(
|
||||
args.packages, ignore_missing = (not args.all)
|
||||
)
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,22 +1,32 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .Cmd import Cmd
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
from argparse import Namespace, ArgumentParser
|
||||
from argparse import ArgumentParser, Namespace
|
||||
|
||||
class CmdListSecrets(Cmd): # export
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
|
||||
class CmdListSecrets(Cmd): # export
|
||||
|
||||
def __init__(self, parent: CmdSecrets) -> None:
|
||||
super().__init__(parent, 'list-secrets', help="List package secret files")
|
||||
super().__init__(parent, 'list-secrets', help = 'List package secret files')
|
||||
|
||||
def add_arguments(self, parser: ArgumentParser) -> None:
|
||||
super().add_arguments(parser)
|
||||
parser.add_argument("--all", action='store_true', default=False, help="Show all secret paths, including non-existent files")
|
||||
parser.add_argument(
|
||||
'--all',
|
||||
action = 'store_true',
|
||||
default = False,
|
||||
help = 'Show all secret paths, including non-existent files',
|
||||
)
|
||||
|
||||
async def _run(self, args: Namespace) -> None:
|
||||
print('\n'.join(await self._list_secret_paths(args.packages, ignore_missing=(not args.all))))
|
||||
print(
|
||||
'\n'.join(
|
||||
await
|
||||
self._list_secret_paths(args.packages, ignore_missing = (not args.all))
|
||||
)
|
||||
)
|
||||
|
|
|
|||
|
|
@ -1,18 +1,18 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .Cmd import Cmd
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
from argparse import Namespace, ArgumentParser
|
||||
from argparse import Namespace
|
||||
|
||||
class CmdListTemplates(Cmd): # export
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
|
||||
class CmdListTemplates(Cmd): # export
|
||||
|
||||
def __init__(self, parent: CmdSecrets) -> None:
|
||||
super().__init__(parent, 'list-templates', help="List package template files")
|
||||
super().__init__(parent, 'list-templates', help = 'List package template files')
|
||||
|
||||
async def _run(self, args: Namespace) -> None:
|
||||
print('\n'.join(await self._list_template_files(args.packages)))
|
||||
|
|
|
|||
|
|
@ -1,18 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from .Cmd import Cmd
|
||||
from .Cmd import Cmd, Parent
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ..CmdSecrets import CmdSecrets
|
||||
from argparse import Namespace, ArgumentParser
|
||||
from argparse import Namespace
|
||||
|
||||
class CmdRmCompilationOutput(Cmd): # export
|
||||
class CmdRmCompilationOutput(Cmd): # export
|
||||
|
||||
def __init__(self, parent: CmdSecrets) -> None:
|
||||
super().__init__(parent, 'rm-compilation-output', help="Remove package compilation output files")
|
||||
def __init__(self, parent: Parent) -> None:
|
||||
super().__init__(
|
||||
parent,
|
||||
'rm-compilation-output',
|
||||
help = 'Remove package compilation output files',
|
||||
)
|
||||
|
||||
async def _run(self, args: Namespace) -> None:
|
||||
await self._remove_compilation_targets(args.packages)
|
||||
|
|
|
|||
|
|
@ -1,24 +1,20 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import sys
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from ....lib.log import DEBUG, NOTICE, WARNING, log
|
||||
from ....lib.ProcFilterGpg import ProcFilterGpg
|
||||
from .base import Attrs
|
||||
from .FilesContext import FilesContext
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import Iterable
|
||||
from ....lib.FileContext import FileContext
|
||||
|
||||
from ....lib.log import *
|
||||
from ....lib.util import run_cmd
|
||||
from ....lib.TarIo import TarIo
|
||||
from ....lib.ProcFilterGpg import ProcFilterGpg
|
||||
|
||||
from .base import Attrs
|
||||
from .FilesContext import FilesContext
|
||||
from ....lib.Distro import Distro
|
||||
|
||||
class DistroContext(FilesContext):
|
||||
|
||||
|
|
@ -37,18 +33,22 @@ class DistroContext(FilesContext):
|
|||
async def list_template_files(self, pkg_names: Iterable[str]) -> list[str]:
|
||||
if not pkg_names:
|
||||
pkg_names = [p.name for p in await self.__distro.select()]
|
||||
return await self.match_files(pkg_names, pattern=r'.*\.jw-tmpl$')
|
||||
return await self.match_files(pkg_names, pattern = r'.*\.jw-tmpl$')
|
||||
|
||||
async def list_secret_paths(self, pkg_names: Iterable[str], ignore_missing: bool=False) -> list[str]:
|
||||
async def list_secret_paths(
|
||||
self, pkg_names: Iterable[str], ignore_missing: bool = False
|
||||
) -> list[str]:
|
||||
ret = []
|
||||
for tmpl in await self.list_template_files(pkg_names):
|
||||
path = str(Path(tmpl).with_suffix(".jw-secret"))
|
||||
path = str(Path(tmpl).with_suffix('.jw-secret'))
|
||||
if ignore_missing and not await self.ctx.file_exists(path):
|
||||
continue
|
||||
ret.append(path)
|
||||
return ret
|
||||
|
||||
async def list_compilation_targets(self, pkg_names: Iterable[str], ignore_missing: bool=False) -> list[str]:
|
||||
async def list_compilation_targets(
|
||||
self, pkg_names: Iterable[str], ignore_missing: bool = False
|
||||
) -> list[str]:
|
||||
ret = []
|
||||
for tmpl in await self.list_template_files(pkg_names):
|
||||
path = tmpl.removesuffix('.jw-tmpl')
|
||||
|
|
@ -58,72 +58,119 @@ class DistroContext(FilesContext):
|
|||
return ret
|
||||
|
||||
async def remove_compilation_targets(self, pkg_names: Iterable[str]) -> list[str]:
|
||||
ret: list[str] = []
|
||||
for path in await self.list_compilation_targets(pkg_names):
|
||||
try:
|
||||
self.ctx.stat(path)
|
||||
await self.ctx.stat(path)
|
||||
log(NOTICE, f'Removing {path}')
|
||||
await self.ctx.unlink(path)
|
||||
except FileNotFoundError as e:
|
||||
log(DEBUG, f'Compilation target {path} doesn\'t exist (ignored)')
|
||||
ret.append(path)
|
||||
except FileNotFoundError:
|
||||
log(DEBUG, f"Compilation target {path} doesn't exist (ignored)")
|
||||
continue
|
||||
return ret
|
||||
|
||||
async def compile_template_files(self, pkg_names: Iterable[str], default_attrs: Attrs) -> list[str]:
|
||||
async def compile_template_files(
|
||||
self, pkg_names: Iterable[str], default_attrs: Attrs
|
||||
) -> list[str]:
|
||||
ret: list[str] = []
|
||||
missing = 0
|
||||
for target in await self.list_compilation_targets(pkg_names):
|
||||
if not await self.compile_template_file(target, default_attrs):
|
||||
if await self.compile_template_file(target, default_attrs):
|
||||
ret.append(target)
|
||||
else:
|
||||
missing += 1
|
||||
if missing > 0:
|
||||
log(WARNING, f'{missing} missing secrets found. You might want to add them and run sudo {app.cmdline} again')
|
||||
from ....lib.util import pretty_cmd
|
||||
|
||||
async def install(self, src_uri: str, pkg_names: Iterable[str], only_missing: bool=False, verbose: bool=False) -> None:
|
||||
cmdline = pretty_cmd(sys.argv)
|
||||
log(
|
||||
WARNING,
|
||||
(
|
||||
f'{missing} missing secrets found. You might want to add them and '
|
||||
f'run sudo {cmdline} again'
|
||||
),
|
||||
)
|
||||
return ret
|
||||
|
||||
async def _read_secret_tar_blob(src_uri: str):
|
||||
async def install(
|
||||
self,
|
||||
src_uri: str,
|
||||
pkg_names: Iterable[str],
|
||||
only_missing: bool = False,
|
||||
verbose: bool = False,
|
||||
) -> None:
|
||||
|
||||
async def _read_secret_tar_blob(src_uri: str) -> bytes:
|
||||
ec = self.ctx
|
||||
from ....lib.ec.Local import Local
|
||||
from ....lib.util import get
|
||||
|
||||
if not isinstance(ec, Local):
|
||||
ec = Local() # Security: Use a local exec context for decrypting and filtering secrets
|
||||
return (await get(src_uri, content_filter=ProcFilterGpg(ec=ec))).stdout
|
||||
# Security: Use a local exec context for decrypting and
|
||||
# filtering secrets
|
||||
ec = Local()
|
||||
return (await get(src_uri, content_filter = ProcFilterGpg(ec = ec))).stdout
|
||||
|
||||
def _matches_host_prefix(path: str) -> bool:
|
||||
return re.match(r'^' + root_in_tar, path)
|
||||
return re.match(r'^' + host_root_in_tar, path) is not None
|
||||
|
||||
def _crop_host_prefix(path: str) -> bool:
|
||||
return re.sub(r'^' + root_in_tar, '', path)
|
||||
return re.sub(r'^' + host_root_in_tar, '', path) is not None
|
||||
|
||||
def _crop_default_prefix(path: str) -> bool:
|
||||
return re.sub(r'^' + default, '', path)
|
||||
return re.sub(default_rx, '', path) is not None
|
||||
|
||||
def _matches_default_prefix(path: str) -> bool:
|
||||
return re.match(r'^default', path)
|
||||
return re.match(r'^default', path) is not None
|
||||
|
||||
def _is_needed_secret(path: str) -> bool:
|
||||
return path in secret_paths
|
||||
|
||||
from .tar import filter as tar_filter, rewrite as tar_rewrite, extract as tar_extract, merge as tar_merge
|
||||
from .tar import extract as tar_extract
|
||||
from .tar import filter as tar_filter
|
||||
from .tar import merge as tar_merge
|
||||
from .tar import rewrite as tar_rewrite
|
||||
|
||||
if only_missing:
|
||||
raise NotImplementedError('--only-missing is not yet implemented')
|
||||
|
||||
secret_paths = await self.list_secret_paths(pkg_names)
|
||||
|
||||
host_root_in_tar = '/'.join(reversed(self.ctx.hostname.split('.')))
|
||||
hostname = self.ctx.uri.hostname
|
||||
if not hostname:
|
||||
raise Exception('Have no hostname to find secrets in tar file')
|
||||
host_root_in_tar = '/'.join(reversed(hostname.split('.')))
|
||||
host_rx = re.compile(r'^' + host_root_in_tar)
|
||||
default_rx = re.compile(r'^default')
|
||||
|
||||
filtered_paths: list[str] = []
|
||||
extracted_paths: list[str] = []
|
||||
|
||||
blob_all = await _read_secret_tar_blob(src_uri)
|
||||
blob_host_filtered = tar_filter(blob_all, lambda p: re.match(host_rx, p), filtered_paths)
|
||||
blob_host_transformed = tar_rewrite(blob_host_filtered, lambda p: re.sub(host_rx, '', p))
|
||||
blob_default_filtered = tar_filter(blob_all, lambda p: re.match(default_rx, p), filtered_paths)
|
||||
blob_default_transformed = tar_rewrite(blob_default_filtered, lambda p: re.sub(default_rx, '', p))
|
||||
blob_secret_material = tar_merge([blob_host_transformed, blob_default_transformed], overwrite=False)
|
||||
blob_needed = tar_filter(blob_secret_material, _is_needed_secret, extracted_paths)
|
||||
blob_all = await _read_secret_tar_blob(src_uri)
|
||||
if blob_all is None:
|
||||
raise Exception(f'Tar blob {src_uri} is empty')
|
||||
blob_host_filtered = tar_filter(
|
||||
blob_all, lambda p: re.match(host_rx, p) is not None, filtered_paths
|
||||
)
|
||||
blob_host_transformed = tar_rewrite(
|
||||
blob_host_filtered, lambda p: re.sub(host_rx, '', p)
|
||||
)
|
||||
blob_default_filtered = tar_filter(
|
||||
blob_all, lambda p: re.match(default_rx, p) is not None, filtered_paths
|
||||
)
|
||||
blob_default_transformed = tar_rewrite(
|
||||
blob_default_filtered, lambda p: re.sub(default_rx, '', p)
|
||||
)
|
||||
blob_secret_material = tar_merge(
|
||||
[blob_host_transformed, blob_default_transformed], overwrite = False
|
||||
)
|
||||
blob_needed = tar_filter(
|
||||
blob_secret_material, _is_needed_secret, extracted_paths
|
||||
)
|
||||
|
||||
await tar_extract(self.ctx, blob_needed, root='/', verbose=verbose)
|
||||
await tar_extract(self.ctx, blob_needed, root = '/', verbose = verbose)
|
||||
for path in secret_paths:
|
||||
if not path in extracted_paths:
|
||||
log(NOTICE, f'not extracted: {path}')
|
||||
else:
|
||||
log(NOTICE, f'extracted: {path}')
|
||||
if path not in extracted_paths:
|
||||
log(NOTICE, f'not extracted: {path}')
|
||||
else:
|
||||
log(NOTICE, f'extracted: {path}')
|
||||
|
|
|
|||
|
|
@ -1,21 +1,17 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re, stat, copy
|
||||
import copy
|
||||
import re
|
||||
import stat
|
||||
|
||||
from contextlib import suppress
|
||||
from pathlib import Path
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from typing import Iterable
|
||||
from ....lib.FileContext import FileContext
|
||||
|
||||
from ....lib.log import *
|
||||
from ....lib.util import run_cmd
|
||||
|
||||
from ....lib.log import DEBUG, NOTICE, WARNING, log
|
||||
from .base import Attrs
|
||||
|
||||
class FilesContext:
|
||||
|
|
@ -27,17 +23,17 @@ class FilesContext:
|
|||
def ctx(self) -> FileContext:
|
||||
return self.__ctx
|
||||
|
||||
async def _read_key_value_file(self, path: str, throw=False) -> dict[str, str]:
|
||||
async def _read_key_value_file(self, path: str, throw = False) -> dict[str, str]:
|
||||
ret: dict[str, str] = {}
|
||||
try:
|
||||
result = await self.ctx.get(path)
|
||||
for line in result.stdout.decode().splitlines():
|
||||
for line in result.stdout_str.splitlines():
|
||||
line = line.strip()
|
||||
if not line or line.startswith("#"):
|
||||
if not line or line.startswith('#'):
|
||||
continue
|
||||
if "=" not in line:
|
||||
if '=' not in line:
|
||||
continue
|
||||
key, val = line.split("=", 1)
|
||||
key, val = line.split('=', 1)
|
||||
key = key.strip()
|
||||
val = val.strip()
|
||||
if key:
|
||||
|
|
@ -46,39 +42,39 @@ class FilesContext:
|
|||
log(DEBUG, f'File not found {path}')
|
||||
return ret
|
||||
|
||||
def _parse_attributes(self, content: str) -> Attrs:
|
||||
def _parse_attributes(self, content: str) -> Attrs | None:
|
||||
|
||||
if not content:
|
||||
return None
|
||||
|
||||
first_line = content.splitlines()[0]
|
||||
if not re.match(r"^\s*#\s*conf\s*:", first_line):
|
||||
if not re.match(r'^\s*#\s*conf\s*:', first_line):
|
||||
return None
|
||||
|
||||
ret = Attrs()
|
||||
ret.conf = first_line
|
||||
|
||||
m = re.match(r"^\s*#\s*conf\s*:\s*(.*?)\s*$", first_line)
|
||||
m = re.match(r'^\s*#\s*conf\s*:\s*(.*?)\s*$', first_line)
|
||||
if not m:
|
||||
return ret
|
||||
|
||||
for part in re.split(r'[; ,]', m.group(1)):
|
||||
part = part.strip()
|
||||
if not part or "=" not in part:
|
||||
if not part or '=' not in part:
|
||||
continue
|
||||
|
||||
key, val = part.split("=", 1)
|
||||
key, val = part.split('=', 1)
|
||||
key = key.strip()
|
||||
val = val.strip()
|
||||
|
||||
if key == "owner":
|
||||
if key == 'owner':
|
||||
ret.owner = val or None
|
||||
elif key == "group":
|
||||
elif key == 'group':
|
||||
ret.group = val or None
|
||||
elif key == "mode":
|
||||
elif key == 'mode':
|
||||
if val:
|
||||
try:
|
||||
if re.fullmatch(r"0[0-7]+", val):
|
||||
if re.fullmatch(r'0[0-7]+', val):
|
||||
ret.mode = int(val, 8)
|
||||
else:
|
||||
ret.mode = int(val, 0)
|
||||
|
|
@ -87,20 +83,26 @@ class FilesContext:
|
|||
|
||||
return ret
|
||||
|
||||
async def _read_attributes(self, paths: Iterable[str]) -> Attrs|None:
|
||||
async def _read_attributes(self, paths: Iterable[str]) -> Attrs | None:
|
||||
ret = Attrs()
|
||||
for path in paths:
|
||||
try:
|
||||
result = await self.ctx.get(path)
|
||||
lines = result.stdout.decode().splitlines()
|
||||
lines = result.stdout_str.splitlines()
|
||||
if lines:
|
||||
ret.update(self._parse_attributes(lines[0]))
|
||||
except FileNotFoundError:
|
||||
log(DEBUG, f'Can\'t parse "{path}" for attributes, file doesn\'t exist (ignored)')
|
||||
log(
|
||||
DEBUG,
|
||||
(
|
||||
f'Can\'t parse "{path}" for attributes, '
|
||||
"file doesn't exist (ignored)"
|
||||
),
|
||||
)
|
||||
return ret
|
||||
|
||||
def _format_metadata(self, owner: str, group: str, mode: int) -> str:
|
||||
return f"{owner}:{group} {mode:o}"
|
||||
return f'{owner}:{group} {mode:o}'
|
||||
|
||||
async def _compile_one_template_file(
|
||||
self,
|
||||
|
|
@ -110,11 +112,12 @@ class FilesContext:
|
|||
replace: dict[str, str] = {},
|
||||
) -> None:
|
||||
|
||||
owner = "root"
|
||||
group = "root"
|
||||
owner = 'root'
|
||||
group = 'root'
|
||||
mode = 0o400
|
||||
|
||||
new_content = (await self.ctx.get(src)).stdout.decode()
|
||||
result = await self.ctx.get(src)
|
||||
new_content = result.stdout_str
|
||||
|
||||
attrs = self._parse_attributes(new_content)
|
||||
if attrs is None:
|
||||
|
|
@ -133,15 +136,21 @@ class FilesContext:
|
|||
for key, val in replace.items():
|
||||
new_content = new_content.replace(key, val)
|
||||
|
||||
tmp_path: str|None = None
|
||||
tmp_path: str | None = None
|
||||
|
||||
try:
|
||||
tmp_path = await self.ctx.mktemp(dst + '.jw-pkg.XXXXX')
|
||||
await self.ctx.put(tmp_path, new_content.encode('utf-8'), owner=owner, group=group, mode=mode)
|
||||
await self.ctx.put(
|
||||
tmp_path,
|
||||
new_content.encode('utf-8'),
|
||||
owner = owner,
|
||||
group = group,
|
||||
mode = mode,
|
||||
)
|
||||
|
||||
content_changed = True
|
||||
metadata_changed = True
|
||||
old_meta = "<missing>"
|
||||
old_meta = '<missing>'
|
||||
|
||||
try:
|
||||
st = await self.ctx.stat(dst)
|
||||
|
|
@ -150,23 +159,21 @@ class FilesContext:
|
|||
else:
|
||||
old_mode = stat.S_IMODE(st.mode)
|
||||
old_meta = self._format_metadata(st.owner, st.group, old_mode)
|
||||
old_content = (await self.ctx.get(dst)).stdout.decode()
|
||||
old_content = (await self.ctx.get(dst)).stdout_str
|
||||
|
||||
content_changed = old_content != new_content
|
||||
metadata_changed = (
|
||||
st.owner != owner
|
||||
or st.group != group
|
||||
or old_mode != mode
|
||||
st.owner != owner or st.group != group or old_mode != mode
|
||||
)
|
||||
|
||||
changes = []
|
||||
if content_changed:
|
||||
changes.append("@content")
|
||||
changes.append('@content')
|
||||
if metadata_changed:
|
||||
changes.append(f"@metadata ({old_meta} -> {new_meta})")
|
||||
changes.append(f'@metadata ({old_meta} -> {new_meta})')
|
||||
|
||||
details = ", ".join(changes) if changes else "no changes"
|
||||
log(NOTICE, f"Applying macros in {src} to {dst}: {details}")
|
||||
details = ', '.join(changes) if changes else 'no changes'
|
||||
log(NOTICE, f'Applying macros in {src} to {dst}: {details}')
|
||||
|
||||
if not changes:
|
||||
await self.ctx.unlink(tmp_path)
|
||||
|
|
@ -181,23 +188,28 @@ class FilesContext:
|
|||
with suppress(FileNotFoundError):
|
||||
await self.ctx.unlink(tmp_path)
|
||||
|
||||
async def compile_template_file(self, target_path: str, default_attrs: Attrs|None=None) -> bool:
|
||||
path_tmpl = target_path + '.jw-tmpl'
|
||||
async def compile_template_file(
|
||||
self, target_path: str, default_attrs: Attrs | None = None
|
||||
) -> bool:
|
||||
path_tmpl = target_path + '.jw-tmpl'
|
||||
path_secret_file = target_path + '.jw-secret-file'
|
||||
path_secret = target_path + '.jw-secret'
|
||||
path_secret = target_path + '.jw-secret'
|
||||
attrs = copy.deepcopy(default_attrs if default_attrs is not None else Attrs())
|
||||
attrs.update(await self._read_attributes([
|
||||
path_tmpl,
|
||||
path_secret_file,
|
||||
path_secret
|
||||
]))
|
||||
attrs.update(
|
||||
await self._read_attributes([path_tmpl, path_secret_file, path_secret])
|
||||
)
|
||||
replace = await self._read_key_value_file(path_secret)
|
||||
for src in [ path_secret_file, path_tmpl ]:
|
||||
for src in [path_secret_file, path_tmpl]:
|
||||
try:
|
||||
await self._compile_one_template_file(src=src, dst=target_path, default_attrs=attrs, replace=replace)
|
||||
await self._compile_one_template_file(
|
||||
src = src,
|
||||
dst = target_path,
|
||||
default_attrs = attrs,
|
||||
replace = replace
|
||||
)
|
||||
return True
|
||||
except FileNotFoundError as e:
|
||||
log(DEBUG, f'Compilation source {src} doesn\'t exist (ignored)')
|
||||
except FileNotFoundError:
|
||||
log(DEBUG, f"Compilation source {src} doesn't exist (ignored)")
|
||||
continue
|
||||
|
||||
log(WARNING, f'No secret found for target {target_path}, not compiling')
|
||||
|
|
|
|||
|
|
@ -1,18 +1,15 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
|
||||
@dataclass
|
||||
class Attrs:
|
||||
|
||||
mode: int | None = None
|
||||
owner: str | None = None
|
||||
group: str | None = None
|
||||
conf: str | None = None
|
||||
|
||||
def update(self, rhs: Args|None) -> Args:
|
||||
def update(self, rhs: Attrs | None) -> Attrs:
|
||||
if rhs is not None:
|
||||
if rhs.mode:
|
||||
self.mode = rhs.mode
|
||||
|
|
@ -32,4 +29,3 @@ class Attrs:
|
|||
if self.group is not None:
|
||||
return False
|
||||
return True
|
||||
|
||||
|
|
|
|||
|
|
@ -1,21 +1,27 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
import tarfile
|
||||
|
||||
from tarfile import TarFile
|
||||
from typing import TYPE_CHECKING, Callable
|
||||
|
||||
import tarfile, io
|
||||
from tarfile import TarFile
|
||||
|
||||
from ....lib.log import *
|
||||
from ....lib.log import DEBUG, log
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from ....lib.ExecContext import ExecContext
|
||||
from typing import Iterable
|
||||
|
||||
def filter(blob: bytes, path_filter: Callable[[str], bool]|None, matched: list[str]|None=None) -> bytes:
|
||||
from ....lib.ExecContext import ExecContext
|
||||
from ....lib.FileContext import FileContext
|
||||
|
||||
def filter(
|
||||
blob: bytes,
|
||||
path_filter: Callable[[str], bool] | None,
|
||||
matched: list[str] | None = None,
|
||||
) -> bytes:
|
||||
ret = io.BytesIO()
|
||||
with tarfile.open(fileobj=ret, mode='w') as tf_out:
|
||||
tf_in = TarFile(fileobj=io.BytesIO(blob))
|
||||
with tarfile.open(fileobj = ret, mode = 'w') as tf_out:
|
||||
tf_in = TarFile(fileobj = io.BytesIO(blob))
|
||||
for info in tf_in.getmembers():
|
||||
if path_filter is not None and not path_filter(info.name):
|
||||
continue
|
||||
|
|
@ -28,8 +34,8 @@ def filter(blob: bytes, path_filter: Callable[[str], bool]|None, matched: list[s
|
|||
|
||||
def rewrite(blob: bytes, rewrite_filter: Callable[[str], str]) -> bytes:
|
||||
ret = io.BytesIO()
|
||||
with tarfile.open(fileobj=ret, mode='w') as tf_out:
|
||||
tf_in = TarFile(fileobj=io.BytesIO(blob))
|
||||
with tarfile.open(fileobj = ret, mode = 'w') as tf_out:
|
||||
tf_in = TarFile(fileobj = io.BytesIO(blob))
|
||||
for info in tf_in.getmembers():
|
||||
new_name = rewrite_filter(info.name)
|
||||
log(DEBUG, f'Rewriting {info.name} -> {new_name}')
|
||||
|
|
@ -38,11 +44,11 @@ def rewrite(blob: bytes, rewrite_filter: Callable[[str], str]) -> bytes:
|
|||
tf_out.addfile(info, buf)
|
||||
return ret.getvalue()
|
||||
|
||||
def merge(blobs: Iterable[bytes], overwrite: bool=False) -> bytes:
|
||||
def merge(blobs: Iterable[bytes], overwrite: bool = False) -> bytes:
|
||||
ret = io.BytesIO()
|
||||
with tarfile.open(fileobj=ret, mode='w') as tf_out:
|
||||
with tarfile.open(fileobj = ret, mode = 'w') as tf_out:
|
||||
for blob in blobs:
|
||||
tf_in = TarFile(fileobj=io.BytesIO(blob))
|
||||
tf_in = TarFile(fileobj = io.BytesIO(blob))
|
||||
existing_names = tf_out.getnames()
|
||||
for info in tf_in.getmembers():
|
||||
if not overwrite and info.name in existing_names:
|
||||
|
|
@ -51,11 +57,21 @@ def merge(blobs: Iterable[bytes], overwrite: bool=False) -> bytes:
|
|||
tf_out.addfile(info, buf)
|
||||
return ret.getvalue()
|
||||
|
||||
async def extract(dst: ExecContext, blob: bytes, root: str|None=None, verbose: bool=False) -> None:
|
||||
async def extract(
|
||||
dst: FileContext,
|
||||
blob: bytes,
|
||||
root: str | None = None,
|
||||
verbose: bool = False
|
||||
) -> None:
|
||||
cmd = ['tar']
|
||||
if root is not None:
|
||||
cmd += ['-C', root]
|
||||
if verbose:
|
||||
cmd += '-v'
|
||||
cmd += ['-x', '-f', '-']
|
||||
await dst.run(cmd, verbose=verbose, cmd_input=blob)
|
||||
if not isinstance(dst, ExecContext):
|
||||
raise NotImplementedError(
|
||||
'Extracting tar files to a non-executable '
|
||||
f'context is not yet implemented: {dst}'
|
||||
)
|
||||
await dst.run(cmd, verbose = verbose, cmd_input = blob)
|
||||
|
|
|
|||
|
|
@ -1,17 +1,21 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from ....lib.FileContext import FileContext
|
||||
from ....lib.ec.Local import Local
|
||||
from ....lib.FileContext import FileContext
|
||||
from .FilesContext import FilesContext
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from .base import Attrs
|
||||
|
||||
async def compile_template_file(target_path: str, default_attrs: Attrs|None=None, ctx: FileContext|None=None) -> bool:
|
||||
async def compile_template_file(
|
||||
target_path: str,
|
||||
default_attrs: Attrs | None = None,
|
||||
ctx: FileContext | None = None
|
||||
) -> bool:
|
||||
if ctx is None:
|
||||
ctx = Local()
|
||||
await FilesContext(ctx).compile_template_file(target_path, default_attrs=default_attrs)
|
||||
return await FilesContext(ctx).compile_template_file(
|
||||
target_path, default_attrs = default_attrs
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in a new issue