From bb79d0b3f28395faf381d2d29f4e9efc7186b647 Mon Sep 17 00:00:00 2001 From: Alexander Druz Date: Wed, 7 Feb 2024 12:53:49 +0100 Subject: [PATCH] Add Python docstrings --- main.py | 54 +++++++++++++++++++++--------------------------------- 1 file changed, 21 insertions(+), 33 deletions(-) diff --git a/main.py b/main.py index c557ee7..719a218 100755 --- a/main.py +++ b/main.py @@ -1,4 +1,7 @@ #!/usr/bin/env python3 +""" +Parse strategy matrix in GitHub Action. +""" import json import os from typing import Any @@ -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( @@ -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()