Debian Codegraph @

ansible_collections/community/crypto/plugins/plugin_utils/_gnupg.py

raw
1 # Copyright (c) 2023, Felix Fontein <[email protected]>
2 # GNU General Public License v3.0+ (see LICENSES/GPL-3.0-or-later.txt or https://www.gnu.org/licenses/gpl-3.0.txt)
3 # SPDX-License-Identifier: GPL-3.0-or-later
4
5 # Note that this plugin util is **PRIVATE** to the collection. It can have breaking changes at any time.
6 # Do not use this from other collections or standalone plugins/modules!
7
8 from __future__ import annotations
9
10 import typing as t
11 from subprocess import PIPE, Popen
12
13 from ansible.module_utils.common.process import get_bin_path
14 from ansible.module_utils.common.text.converters import to_text
15
16 from ansible_collections.community.crypto.plugins.module_utils._gnupg.cli import (
17 GPGError,
18 GPGRunner,
19 )
20
21
22 class PluginGPGRunner(GPGRunner):
23 def __init__(
24 self, *, executable: str | None = None, cwd: str | None = None
25 ) -> None:
26 if executable is None:
27 try:
28 executable = get_bin_path("gpg")
29 except ValueError as exc:
30 raise GPGError(
31 "Cannot find the `gpg` executable on the controller"
32 ) from exc
33 self.executable = executable
34 self.cwd = cwd
35
36 def run_command(
37 self, command: list[str], *, check_rc: bool = True, data: bytes | None = None
38 ) -> tuple[int, str, str]:
39 """
40 Run ``[gpg] + command`` and return ``(rc, stdout, stderr)``.
41
42 If ``data`` is not ``None``, it will be provided as stdin.
43 The code assumes it is a bytes string.
44
45 Returned stdout and stderr are native Python strings.
46 Pass ``check_rc=False`` to allow return codes != 0.
47
48 Raises a ``GPGError`` in case of errors.
49 """
50 command = [self.executable] + command
51 with Popen(
52 command, shell=False, cwd=self.cwd, stdin=PIPE, stdout=PIPE, stderr=PIPE
53 ) as p:
54 stdout, stderr = p.communicate(input=data)
55 stdout_n = to_text(stdout, errors="surrogate_or_replace")
56 stderr_n = to_text(stderr, errors="surrogate_or_replace")
57 if check_rc and p.returncode != 0:
58 raise GPGError(
59 f'Running {" ".join(command)} yielded return code {p.returncode} with stdout: "{stdout_n}" and stderr: "{stderr_n}")'
60 )
61 return t.cast(int, p.returncode), stdout_n, stderr_n
62
63
64 __all__ = ("PluginGPGRunner",)