liab-deployments/liab_deployments/operations/git.py

139 lines
3.9 KiB
Python

from collections.abc import Sequence
from io import StringIO
from os import environ
from urllib.parse import urlparse
from pyinfra import host
from pyinfra.api import (
DeployError,
operation,
)
from pyinfra.api.operation import (
OperationMeta,
)
from pyinfra.operations import (
files,
git,
)
@operation()
def gitcredentialstore_file(
path: str,
creds: Sequence[tuple[str, str, str]],
user: str | None = None,
):
"""Wraps `files.put()` and formats git credential record lines
Any number of credentials can be given as a list of
url, user name, token/password 3-tuples. The credentials
are put at the given `path` with mode `600` and owned
by the given `user`.
"""
lines = []
for cred in creds:
url, cuser, ctoken = cred
url_p = urlparse(url)
lines.append(
f'{url_p.scheme}://{cuser}:{ctoken}@{url_p.netloc}'
)
yield from files.put._inner(
dest=path,
src=StringIO('\n'.join(lines)),
user=user,
mode='0600',
)
def _get_credential_from_env(
auth_spec: tuple[str, str] | None,
) -> tuple[str | None, str | None, str | None]:
if auth_spec is None:
return None, None, None
user_name, token_env_var = auth_spec
return token_env_var, user_name, environ.get(token_env_var)
@operation()
def gitcredential_from_env(
path: str,
url: str,
user: str,
env_var: str,
):
"""Retrieve a token/password from an env var to deposit as a gitcredential
The credential file is placed at `path`. The credential is constrained
to the given `url` and `user`. The actual secret is retrieved from
environment variable identified by `env_var`.
If this environment variable is not set, the operation will still
check of the target credential file exists with correct access mode.
"""
token = environ.get(env_var)
if not token:
info = host.get_fact(files.File, path)
if info is None:
msg = f'No git credential found at {path!r}, set {env_var!r} to deposit one.'
raise DeployError(msg)
if info['mode'] != 600:
msg = 'Unexpected permissions for credential store file' \
f' {dict((k, v) for k, v in info.items() if k in ("mode",))}' \
f' set {env_var!r} to fix.'
raise DeployError(msg)
return
yield from gitcredentialstore_file._inner(
path=path,
creds=[(url, user, token)],
)
def repo_w_credential(
src: str,
dest: str,
*,
cred_file: str | None,
name: str | None = None,
_sudo_user: str | None = None,
**kwargs,
) -> OperationMeta:
"""Just like `git.repo` from pyinfra, but with a credential store set
The helper configures a call to the standard `git.repo` operation,
and can be used as a drop-in replacement in many cases.
In addition to plain `git.repo`, Git config is used to instruct
Git to use a `store` credential helper pointing to the given
credential file. This is done via an environment setup initially,
and is then persistent in the repositories local config for
reuse by other operations.
"""
repo_op = git.repo(
src,
dest,
name=name,
_sudo_user=_sudo_user,
# configure the credential setup we will be setting
# for the repo later on also for this one time operation
_env=None if not cred_file else {
'GIT_CONFIG_COUNT': '1',
'GIT_CONFIG_KEY_0': 'credential.helper',
'GIT_CONFIG_VALUE_0': f'store --file={cred_file}' \
},
**kwargs
)
if not cred_file:
return repo_op
git.config(
name='Configure Git credential helper for remote access',
key='credential.helper',
value=f'store --file={cred_file}',
repo=dest,
_sudo_user=_sudo_user,
)
return repo_op