Skip to content

Commit bf8dafe

Browse files
committed
Move GitHub related functions to a new module
The functions related to GitHub used in the `cli.version.mike.info` module are moved to a new module `github` to they can be reused. Signed-off-by: Leandro Lucarella <[email protected]>
1 parent 1012f0c commit bf8dafe

File tree

2 files changed

+241
-180
lines changed

2 files changed

+241
-180
lines changed

src/frequenz/repo/config/cli/version/mike/info.py

Lines changed: 4 additions & 180 deletions
Original file line numberDiff line numberDiff line change
@@ -21,45 +21,15 @@
2121
"""
2222

2323
import logging
24-
import os
25-
import subprocess
26-
import sys
27-
from typing import NoReturn
2824

2925
import github_action_utils as gha
3026

31-
from .... import version
27+
from .... import github
3228
from ....mkdocs import mike
3329

3430
_logger = logging.getLogger(__name__)
3531

3632

37-
class GitHubActionsFormatter(logging.Formatter):
38-
"""A formatter for GitHub Actions."""
39-
40-
level_mapping: dict[int, str] = {
41-
logging.CRITICAL: "error",
42-
logging.ERROR: "error",
43-
logging.WARNING: "warning",
44-
logging.INFO: "notice",
45-
logging.DEBUG: "debug",
46-
}
47-
"""The mapping from logging levels to GitHub Actions levels."""
48-
49-
def format(self, record: logging.LogRecord) -> str:
50-
"""Format the record using GitHub Actions commands.
51-
52-
Args:
53-
record: The record to format.
54-
55-
Returns:
56-
The formatted record.
57-
"""
58-
github_level = self.level_mapping.get(record.levelno, "notice")
59-
github_command = f"::{github_level}::{record.getMessage()}"
60-
return github_command
61-
62-
6333
def _output_gha_vars(mike_version: mike.MikeVersionInfo) -> None:
6434
"""Output mike version information as GitHub Action variables."""
6535
_logger.debug("Outputting mike version information as GitHub Action variables:")
@@ -72,160 +42,14 @@ def _output_gha_vars(mike_version: mike.MikeVersionInfo) -> None:
7242
gha.set_output("aliases", " ".join(mike_version.aliases))
7343

7444

75-
def abort( # pylint: disable=too-many-arguments
76-
message: str,
77-
title: str | None = None,
78-
file: str | None = None,
79-
col: int | None = None,
80-
end_column: int | None = None,
81-
line: int | None = None,
82-
end_line: int | None = None,
83-
use_subprocess: bool = False,
84-
error_code: int = 1,
85-
) -> NoReturn:
86-
"""Print an error message using GitHub Actions commands and exit.
87-
88-
Args:
89-
message: The message of the error.
90-
title: The title of the error.
91-
file: The file where the error occurred.
92-
col: The column where the error occurred.
93-
end_column: The end column where the error occurred.
94-
line: The line where the error occurred.
95-
end_line: The end line where the error occurred.
96-
use_subprocess: Whether to use subprocess to print the error.
97-
error_code: The error code to exit with.
98-
"""
99-
gha.error(
100-
message,
101-
title=title,
102-
file=file,
103-
col=col,
104-
end_column=end_column,
105-
line=line,
106-
end_line=end_line,
107-
use_subprocess=use_subprocess,
108-
)
109-
sys.exit(error_code)
110-
111-
112-
def require_env(name: str) -> str:
113-
"""Get the environment variable.
114-
115-
Exit with an error if the environment variable is not defined.
116-
117-
Args:
118-
name: The name of the environment variable.
119-
120-
Returns:
121-
The environment variable.
122-
"""
123-
value = os.environ.get(name)
124-
if value is None:
125-
abort(f"{name} is not defined", title="Environment variable not defined")
126-
return value
127-
128-
129-
def _get_tags(repository: str) -> list[str]:
130-
"""Get the tags of the repository.
131-
132-
Args:
133-
repository: The repository to get the tags of.
134-
135-
Returns:
136-
The tags of the repository.
137-
"""
138-
tags_str: list[str]
139-
if env_tags := os.environ.get("TAGS", None):
140-
tags_str = env_tags.split()
141-
else:
142-
tags_str = (
143-
subprocess.check_output(
144-
[
145-
"gh",
146-
"api",
147-
"-q",
148-
".[].name",
149-
"-H",
150-
"Accept: application/vnd.github+json",
151-
"-H",
152-
"X-GitHub-Api-Version: 2022-11-28",
153-
f"/repos/{repository}/tags",
154-
]
155-
)
156-
.decode("utf-8")
157-
.splitlines()
158-
)
159-
160-
_logger.debug("Got tags: %r", tags_str)
161-
return tags_str
162-
163-
164-
def _get_branches(repository: str) -> list[str]:
165-
"""Get the branches of the repository.
166-
167-
Args:
168-
repository: The repository to get the branches of.
169-
170-
Returns:
171-
The branches of the repository.
172-
"""
173-
branches_str: list[str]
174-
if env_branches := os.environ.get("BRANCHES", None):
175-
branches_str = env_branches.split()
176-
else:
177-
branches_str = (
178-
subprocess.check_output(
179-
[
180-
"gh",
181-
"api",
182-
"-q",
183-
".[].name",
184-
"-H",
185-
"Accept: application/vnd.github+json",
186-
"-H",
187-
"X-GitHub-Api-Version: 2022-11-28",
188-
f"/repos/{repository}/branches",
189-
]
190-
)
191-
.decode("utf-8")
192-
.splitlines()
193-
)
194-
_logger.debug("Got branches: %r", branches_str)
195-
return branches_str
196-
197-
198-
def _configure_logging(is_debug_run: bool) -> None:
199-
"""Configure logging for GitHub Actions.
200-
201-
Args:
202-
is_debug_run: Whether the run is a debug run.
203-
"""
204-
handler = logging.StreamHandler()
205-
handler.setFormatter(GitHubActionsFormatter())
206-
level = logging.DEBUG if is_debug_run else logging.INFO
207-
logging.basicConfig(level=level, handlers=[handler])
208-
209-
21045
def main() -> None:
21146
"""Output mike version variables for GitHub Actions."""
212-
is_debug_run = os.environ.get("RUNNER_DEBUG", None) == "1"
213-
_configure_logging(is_debug_run)
214-
215-
repository = require_env("GITHUB_REPO")
216-
repo_info = version.RepoVersionInfo(
217-
ref=require_env("GIT_REF"),
218-
sha=require_env("GIT_SHA"),
219-
tags=_get_tags(repository),
220-
branches=_get_branches(repository),
221-
)
222-
# Just for checking it is defined, github_action_utils deals with it automatically.
223-
require_env("GITHUB_OUTPUT")
47+
github.configure_logging()
22448

22549
try:
226-
mike_version = mike.build_mike_version(repo_info)
50+
mike_version = mike.build_mike_version(github.get_repo_version_info())
22751
except ValueError as error:
228-
abort(f"{error}.", title="Documentation was not published")
52+
github.abort(f"{error}.", title="Documentation was not published")
22953

23054
_output_gha_vars(mike_version)
23155

0 commit comments

Comments
 (0)