Debian Codegraph @

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

raw
1 """Support code for working with GitHub Actions."""
2
3 from __future__ import annotations
4
5 import os
6 import typing as t
7
8 from ..config import (
9 CommonConfig,
10 TestConfig,
11 )
12
13 from ..util import (
14 ApplicationError,
15 MissingEnvironmentVariable,
16 )
17
18 from . import (
19 AuthContext,
20 CIProvider,
21 GeneratingAuthHelper,
22 )
23
24 CODE = 'gha'
25 JOB_ID_ENV_VAR = 'ANSIBLE_TEST_GHA_JOB_ID'
26 ARTIFACT_ID_ENV_VAR = 'ANSIBLE_TEST_GHA_SSH_KEY_ARTIFACT_ID'
27
28
29 class GitHubActions(CIProvider):
30 """CI provider implementation for GitHub Actions."""
31
32 def __init__(self) -> None:
33 self.auth = GitHubActionsAuthHelper()
34
35 @staticmethod
36 def is_supported() -> bool:
37 """Return True if this provider is supported in the current running environment."""
38 return JOB_ID_ENV_VAR in os.environ and ARTIFACT_ID_ENV_VAR in os.environ
39
40 @property
41 def code(self) -> str:
42 """Return a unique code representing this provider."""
43 return CODE
44
45 @property
46 def name(self) -> str:
47 """Return descriptive name for this provider."""
48 return 'GitHub Actions'
49
50 def generate_resource_prefix(self) -> str:
51 """Return a resource prefix specific to this CI provider."""
52 keys = [
53 'GITHUB_REPOSITORY',
54 JOB_ID_ENV_VAR,
55 ]
56
57 try:
58 segments = [os.environ[key] for key in keys]
59 except KeyError as ex:
60 raise MissingEnvironmentVariable(name=ex.args[0]) from None
61
62 prefix = '-'.join(['gha'] + segments)
63
64 return prefix
65
66 def get_base_commit(self, args: CommonConfig) -> str:
67 """Return the base commit or an empty string."""
68 return ''
69
70 def detect_changes(self, args: TestConfig) -> t.Optional[list[str]]:
71 """Initialize change detection."""
72 return None
73
74 def supports_core_ci_auth(self) -> bool:
75 """Return True if Ansible Core CI is supported."""
76 return True
77
78 def prepare_core_ci_request(self, config: dict[str, object], context: AuthContext) -> dict[str, object]:
79 try:
80 owner, name = os.environ['GITHUB_REPOSITORY'].split('/', 1)
81
82 request: dict[str, object] = dict(
83 type="gha:ssh",
84 config=config,
85 repository_owner=owner,
86 repository_name=name,
87 job_id=int(os.environ[JOB_ID_ENV_VAR]),
88 artifact_id=int(os.environ[ARTIFACT_ID_ENV_VAR]),
89 )
90 except KeyError as ex:
91 raise MissingEnvironmentVariable(name=ex.args[0]) from None
92
93 self.auth.sign_request(request, context)
94
95 return request
96
97 def get_git_details(self, args: CommonConfig) -> t.Optional[dict[str, t.Any]]:
98 """Return details about git in the current environment."""
99 return None
100
101
102 class GitHubActionsAuthHelper(GeneratingAuthHelper):
103 """Authentication helper for GitHub Actions."""
104
105 def generate_key_pair(self) -> None:
106 raise ApplicationError(f'Missing SSH private key: {self.private_key_file}')