Debian Codegraph @

test/lib/ansible_test/_internal/ci/local.py

raw
1 """Support code for working without a supported CI provider."""
2
3 from __future__ import annotations
4
5 import abc
6 import inspect
7 import platform
8 import random
9 import re
10 import pathlib
11 import typing as t
12
13 from ..config import (
14 CommonConfig,
15 TestConfig,
16 )
17
18 from ..io import (
19 read_text_file,
20 )
21
22 from ..git import (
23 Git,
24 )
25
26 from ..util import (
27 ApplicationError,
28 display,
29 get_subclasses,
30 is_binary_file,
31 SubprocessError,
32 )
33
34 from . import (
35 AuthContext,
36 AuthHelper,
37 CIProvider,
38 )
39
40 CODE = '' # not really a CI provider, so use an empty string for the code
41
42
43 class Local(CIProvider):
44 """CI provider implementation when not using CI."""
45
46 priority = 1000
47
48 @staticmethod
49 def is_supported() -> bool:
50 """Return True if this provider is supported in the current running environment."""
51 return True
52
53 @property
54 def code(self) -> str:
55 """Return a unique code representing this provider."""
56 return CODE
57
58 @property
59 def name(self) -> str:
60 """Return descriptive name for this provider."""
61 return 'Local'
62
63 def generate_resource_prefix(self) -> str:
64 """Return a resource prefix specific to this CI provider."""
65 prefix = 'ansible-test-%d-%s' % (
66 random.randint(10000000, 99999999),
67 platform.node().split('.')[0],
68 )
69
70 return prefix
71
72 def get_base_commit(self, args: CommonConfig) -> str:
73 """Return the base commit or an empty string."""
74 return ''
75
76 def detect_changes(self, args: TestConfig) -> t.Optional[list[str]]:
77 """Initialize change detection."""
78 result = LocalChanges(args)
79
80 display.info('Detected branch %s forked from %s at commit %s' % (
81 result.current_branch, result.fork_branch, result.fork_point))
82
83 if result.untracked and not args.untracked:
84 display.warning('Ignored %s untracked file(s). Use --untracked to include them.' %
85 len(result.untracked))
86
87 if result.committed and not args.committed:
88 display.warning('Ignored %s committed change(s). Omit --ignore-committed to include them.' %
89 len(result.committed))
90
91 if result.staged and not args.staged:
92 display.warning('Ignored %s staged change(s). Omit --ignore-staged to include them.' %
93 len(result.staged))
94
95 if result.unstaged and not args.unstaged:
96 display.warning('Ignored %s unstaged change(s). Omit --ignore-unstaged to include them.' %
97 len(result.unstaged))
98
99 names = set()
100
101 if args.tracked:
102 names |= set(result.tracked)
103 if args.untracked:
104 names |= set(result.untracked)
105 if args.committed:
106 names |= set(result.committed)
107 if args.staged:
108 names |= set(result.staged)
109 if args.unstaged:
110 names |= set(result.unstaged)
111
112 if not args.metadata.changes:
113 args.metadata.populate_changes(result.diff)
114
115 for path in result.untracked:
116 if is_binary_file(path):
117 args.metadata.changes[path] = ((0, 0),)
118 continue
119
120 line_count = len(read_text_file(path).splitlines())
121
122 args.metadata.changes[path] = ((1, line_count),)
123
124 return sorted(names)
125
126 def supports_core_ci_auth(self) -> bool:
127 """Return True if Ansible Core CI is supported."""
128 return Authenticator.available()
129
130 def prepare_core_ci_request(self, config: dict[str, object], context: AuthContext) -> dict[str, object]:
131 if not (authenticator := Authenticator.load()):
132 raise ApplicationError('Ansible Core CI authentication has not been configured.')
133
134 display.info(f'Using {authenticator} for Ansible Core CI.', verbosity=1)
135
136 return authenticator.prepare_auth_request(config, context)
137
138 def get_git_details(self, args: CommonConfig) -> t.Optional[dict[str, t.Any]]:
139 """Return details about git in the current environment."""
140 return None # not yet implemented for local
141
142
143 class InvalidBranch(ApplicationError):
144 """Exception for invalid branch specification."""
145
146 def __init__(self, branch: str, reason: str) -> None:
147 message = 'Invalid branch: %s\n%s' % (branch, reason)
148
149 super().__init__(message)
150
151 self.branch = branch
152
153
154 class LocalChanges:
155 """Change information for local work."""
156
157 def __init__(self, args: TestConfig) -> None:
158 self.args = args
159 self.git = Git()
160
161 self.current_branch = self.git.get_branch()
162
163 if self.is_official_branch(self.current_branch):
164 raise InvalidBranch(branch=self.current_branch,
165 reason='Current branch is not a feature branch.')
166
167 self.fork_branch = None
168 self.fork_point = None
169
170 self.local_branches = sorted(self.git.get_branches())
171 self.official_branches = sorted([b for b in self.local_branches if self.is_official_branch(b)])
172
173 for self.fork_branch in self.official_branches:
174 try:
175 self.fork_point = self.git.get_branch_fork_point(self.fork_branch)
176 break
177 except SubprocessError:
178 pass
179
180 if self.fork_point is None:
181 raise ApplicationError('Unable to auto-detect fork branch and fork point.')
182
183 # tracked files (including unchanged)
184 self.tracked = sorted(self.git.get_file_names(['--cached']))
185 # untracked files (except ignored)
186 self.untracked = sorted(self.git.get_file_names(['--others', '--exclude-standard']))
187 # tracked changes (including deletions) committed since the branch was forked
188 self.committed = sorted(self.git.get_diff_names([self.fork_point, 'HEAD']))
189 # tracked changes (including deletions) which are staged
190 self.staged = sorted(self.git.get_diff_names(['--cached']))
191 # tracked changes (including deletions) which are not staged
192 self.unstaged = sorted(self.git.get_diff_names([]))
193 # diff of all tracked files from fork point to working copy
194 self.diff = self.git.get_diff([self.fork_point])
195
196 def is_official_branch(self, name: str) -> bool:
197 """Return True if the given branch name an official branch for development or releases."""
198 if self.args.base_branch:
199 return name == self.args.base_branch
200
201 if name == 'devel':
202 return True
203
204 if re.match(r'^stable-[0-9]+\.[0-9]+$', name):
205 return True
206
207 return False
208
209
210 class Authenticator(metaclass=abc.ABCMeta):
211 """Base class for authenticators."""
212
213 @staticmethod
214 def list() -> list[type[Authenticator]]:
215 """List all authenticators in priority order."""
216 return sorted((sc for sc in get_subclasses(Authenticator) if not inspect.isabstract(sc)), key=lambda obj: obj.priority())
217
218 @staticmethod
219 def load() -> Authenticator | None:
220 """Load an authenticator instance, returning None if not configured."""
221 for implementation in Authenticator.list():
222 if implementation.config_file().exists():
223 return implementation()
224
225 return None
226
227 @staticmethod
228 def available() -> bool:
229 """Return True if an authenticator is available, otherwise False."""
230 return bool(Authenticator.load())
231
232 @classmethod
233 @abc.abstractmethod
234 def priority(cls) -> int:
235 """Priority used to determine which authenticator is tried first, from lowest to highest."""
236
237 @classmethod
238 @abc.abstractmethod
239 def config_file(cls) -> pathlib.Path:
240 """Path to the config file for this authenticator."""
241
242 @abc.abstractmethod
243 def prepare_auth_request(self, config: dict[str, object], context: AuthContext) -> dict[str, object]:
244 """Prepare an authenticated Ansible Core CI request using the given config and context."""
245
246 def __str__(self) -> str:
247 return self.__class__.__name__
248
249
250 class PasswordAuthenticator(Authenticator):
251 """Authenticate using a password."""
252
253 @classmethod
254 def priority(cls) -> int:
255 return 200
256
257 @classmethod
258 def config_file(cls) -> pathlib.Path:
259 return pathlib.Path('~/.ansible-core-ci.key').expanduser()
260
261 def prepare_auth_request(self, config: dict[str, object], context: AuthContext) -> dict[str, object]:
262 parts = self.config_file().read_text().strip().split(maxsplit=1)
263 username, password = parts
264
265 request: dict[str, object] = dict(
266 type="remote:password",
267 config=config,
268 username=username,
269 password=password,
270 )
271
272 return request
273
274
275 class SshAuthenticator(Authenticator):
276 """Authenticate using an SSH key."""
277
278 @classmethod
279 def priority(cls) -> int:
280 return 100
281
282 @classmethod
283 def config_file(cls) -> pathlib.Path:
284 return pathlib.Path('~/.ansible-core-ci.auth').expanduser()
285
286 def prepare_auth_request(self, config: dict[str, object], context: AuthContext) -> dict[str, object]:
287 parts = self.config_file().read_text().strip().split(maxsplit=1)
288 username, key_file = parts
289
290 request: dict[str, object] = dict(
291 type="remote:ssh",
292 config=config,
293 username=username,
294 )
295
296 auth_helper = AuthHelper(pathlib.Path(key_file).expanduser())
297 auth_helper.sign_request(request, context)
298
299 return request