Debian Codegraph @

ansible_collections/community/general/plugins/module_utils/_android_sdkmanager.py

raw
1 # Copyright (c) 2024, Stanislav Shamilov <[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 module 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 re
11 import typing as t
12
13 from ansible_collections.community.general.plugins.module_utils._cmd_runner import CmdRunner, cmd_runner_fmt
14
15 if t.TYPE_CHECKING:
16 from ansible.module_utils.basic import AnsibleModule
17
18
19 __state_map = {"present": "--install", "absent": "--uninstall"}
20
21 # sdkmanager --help 2>&1 | grep -A 2 -- --channel
22 __channel_map = {"stable": 0, "beta": 1, "dev": 2, "canary": 3}
23
24
25 def __map_channel(channel_name: str) -> int:
26 if channel_name not in __channel_map:
27 raise ValueError(f"Unknown channel name '{channel_name}'")
28 return __channel_map[channel_name]
29
30
31 def sdkmanager_runner(module: AnsibleModule, **kwargs) -> CmdRunner:
32 return CmdRunner(
33 module,
34 command="sdkmanager",
35 arg_formats=dict(
36 state=cmd_runner_fmt.as_map(__state_map),
37 name=cmd_runner_fmt.as_list(),
38 installed=cmd_runner_fmt.as_fixed("--list_installed"),
39 list=cmd_runner_fmt.as_fixed("--list"),
40 newer=cmd_runner_fmt.as_fixed("--newer"),
41 sdk_root=cmd_runner_fmt.as_opt_eq_val("--sdk_root"),
42 channel=cmd_runner_fmt.as_func(lambda x: [f"--channel={__map_channel(x)}"]),
43 ),
44 force_lang="C.UTF-8", # Without this, sdkmanager binary crashes
45 **kwargs,
46 )
47
48
49 class Package:
50 def __init__(self, name: str) -> None:
51 self.name = name
52
53 def __hash__(self) -> int:
54 return hash(self.name)
55
56 def __ne__(self, other: object) -> bool:
57 if not isinstance(other, Package):
58 return True
59 return self.name != other.name
60
61 def __eq__(self, other: object) -> bool:
62 if not isinstance(other, Package):
63 return False
64
65 return self.name == other.name
66
67
68 class SdkManagerException(Exception):
69 pass
70
71
72 class AndroidSdkManager:
73 _RE_INSTALLED_PACKAGES_HEADER = re.compile(r"^Installed packages:$")
74 _RE_UPDATABLE_PACKAGES_HEADER = re.compile(r"^Available Updates:$")
75
76 # Example: ' platform-tools | 27.0.0 | Android SDK Platform-Tools 27 | platform-tools '
77 _RE_INSTALLED_PACKAGE = re.compile(r"^\s*(?P<name>\S+)\s*\|\s*[0-9][^|]*\b\s*\|\s*.+\s*\|\s*(\S+)\s*$")
78
79 # Example: ' platform-tools | 27.0.0 | 35.0.2'
80 _RE_UPDATABLE_PACKAGE = re.compile(r"^\s*(?P<name>\S+)\s*\|\s*[0-9][^|]*\b\s*\|\s*[0-9].*\b\s*$")
81
82 _RE_UNKNOWN_PACKAGE = re.compile(r"^Warning: Failed to find package \'(?P<package>\S+)\'\s*$")
83 _RE_ACCEPT_LICENSE = re.compile(
84 r"^The following packages can not be installed since their licenses or those of "
85 r"the packages they depend on were not accepted"
86 )
87
88 def __init__(self, module: AnsibleModule) -> None:
89 self.runner = sdkmanager_runner(module)
90
91 def get_installed_packages(self) -> set[Package]:
92 with self.runner("installed sdk_root channel") as ctx:
93 rc, stdout, stderr = ctx.run()
94 return self._parse_packages(stdout, self._RE_INSTALLED_PACKAGES_HEADER, self._RE_INSTALLED_PACKAGE)
95
96 def get_updatable_packages(self) -> set[Package]:
97 with self.runner("list newer sdk_root channel") as ctx:
98 rc, stdout, stderr = ctx.run()
99 return self._parse_packages(stdout, self._RE_UPDATABLE_PACKAGES_HEADER, self._RE_UPDATABLE_PACKAGE)
100
101 def apply_packages_changes(self, packages: list[Package], accept_licenses: bool = False) -> tuple[int, str, str]:
102 """Install or delete packages, depending on the `module.vars.state` parameter"""
103 if len(packages) == 0:
104 return 0, "", ""
105
106 if accept_licenses:
107 license_prompt_answer = "y"
108 else:
109 license_prompt_answer = "N"
110 for package in packages:
111 with self.runner("state name sdk_root channel", data=license_prompt_answer) as ctx:
112 rc, stdout, stderr = ctx.run(name=package.name)
113
114 for line in stdout.splitlines():
115 if self._RE_ACCEPT_LICENSE.match(line):
116 raise SdkManagerException("Licenses for some packages were not accepted")
117
118 if rc != 0:
119 self._try_parse_stderr(stderr)
120 return rc, stdout, stderr
121 return 0, "", ""
122
123 def _try_parse_stderr(self, stderr: str) -> None:
124 data = stderr.splitlines()
125 for line in data:
126 unknown_package_regex = self._RE_UNKNOWN_PACKAGE.match(line)
127 if unknown_package_regex:
128 package = unknown_package_regex.group("package")
129 raise SdkManagerException(f"Unknown package {package}")
130
131 @staticmethod
132 def _parse_packages(stdout: str, header_regexp: re.Pattern, row_regexp: re.Pattern) -> set[Package]:
133 data = stdout.splitlines()
134
135 section_found: bool = False
136 packages = set()
137
138 for line in data:
139 if not section_found:
140 section_found = bool(header_regexp.match(line))
141 continue
142 else:
143 p = row_regexp.match(line)
144 if p:
145 packages.add(Package(p.group("name")))
146 return packages