Skip to content

Commit

Permalink
Add Python docstrings
Browse files Browse the repository at this point in the history
  • Loading branch information
druzsan committed Feb 7, 2024
1 parent 867c6e3 commit bb79d0b
Showing 1 changed file with 21 additions and 33 deletions.
54 changes: 21 additions & 33 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
#!/usr/bin/env python3
"""
Parse strategy matrix in GitHub Action.
"""
import json
import os
from typing import Any
Expand All @@ -7,47 +10,24 @@


def output(name: str, value: str) -> None:
"""
Write out an GitHub Action output.
"""
with open(os.environ["GITHUB_OUTPUT"], "a", encoding="UTF-8") as output_file:
output_file.write(f"{name}={value}\r\n")


def setenv(name: str, value: str) -> None:
"""
Write out an GitHub Action environment variable.
"""
with open(os.environ["GITHUB_ENV"], "a", encoding="UTF-8") as output_file:
output_file.write(f"{name}={value}\r\n")


def parse_base_matrix(input_matrix: str) -> dict:
matrix = yaml.load(input_matrix, Loader=yaml.loader.BaseLoader)
if matrix is None:
return {}
if not isinstance(matrix, dict):
raise TypeError(f"Matrix must be a dict, but {type(matrix)} received.")
for variable, values in matrix.items():
if not isinstance(variable, str):
raise TypeError(
f"Matrix variables must be strings, but variable of type "
f"{type(variable)} received."
)
for reserved_name in ("include", "exclude"):
if variable == reserved_name:
raise ValueError(f"Variable name '{reserved_name}' is reserved.")
if not isinstance(values, list):
raise TypeError(
f"Matrix values must be lists, but {type(values)} received "
f"for variable '{variable}'."
)
for value in values:
if not isinstance(value, str):
raise TypeError(
f"Each matrix value must be a string, but value of type "
f"{type(values)} received for variable '{variable}'."
)
return matrix


def assert_valid_extra(extra: Any) -> None:
"""
Validate strategy include/exclude.
Validate strategy matrix include/exclude.
"""
if not isinstance(extra, list):
raise TypeError(
Expand Down Expand Up @@ -117,19 +97,27 @@ def parse_matrix(input_matrix: str) -> dict:
"""
# Parse every YAML scalar as a string
matrix = yaml.load(input_matrix, Loader=yaml.loader.BaseLoader)
print(matrix)

assert_valid_matrix(matrix)

return matrix


if __name__ == "__main__":
def main() -> None:
"""
Parse strategy matrix from GitHub Action input ('matrix'), parse and
validate it, print it out and set it as output ('matrix') and as
environment variable ('MATRIX').
"""
matrix = parse_matrix(os.environ["INPUT_MATRIX"])

print(yaml.dump({"matrix": matrix}))
print(yaml.dump({"matrix": matrix}, sort_keys=False))

output_matrix = json.dumps(matrix)

output("matrix", output_matrix)
setenv("MATRIX", output_matrix)


if __name__ == "__main__":
main()

0 comments on commit bb79d0b

Please sign in to comment.