1#!/usr/bin/env python3
2#"""Transform errors to expected failures."""
3
4from collections.abc import Sequence
5import os
6import re
7import sys
8
9class TransformExpectedFailures:
10    """Automate transforming error log to expected failure."""
11    def transform(self, errors: str, expected_types: str | None = None) -> None:
12        """Transform erro log to expected failure format.
13
14        It split the error log into multiple lines each line contain one error
15        based on the expexted types and remove the Error part. then remove the
16        white space after ':' and strip the error line.
17        """
18        if expected_types == None:
19            expected_types = "extra_field|missing_method|extra_class|missing_annotation"
20
21        result_list = self._transform(self._extract_error_logs(errors, expected_types))
22        print(",\n".join(result_list))
23
24    def _extract_error_logs(self, errors: str, expected_types: str) -> list[str]:
25        return re.findall(
26                    f"\\b(?:{expected_types})\\b:.+?(?=Error)",
27                    errors,
28                )
29
30    def _transform(self, error_logs : list[str]) -> list[str]:
31        result = [self._transform_single_message(error_log) for error_log in error_logs]
32        result = sorted(set(result))
33        return result
34
35    def _transform_single_message(self, error_log: str) -> str:
36        error_log = error_log.strip()
37        index = error_log.find(":") + 1
38        return '"' + error_log[:index] + error_log[index + 1 :] + '"'
39
40
41if __name__ == "__main__":
42    if len(sys.argv) < 2 or sys.argv[1] == "":
43        print('The errors report is required')
44        sys.exit(1)
45    if len(sys.argv) > 3:
46        print('Invalid number of arguments, please specify the path to the file and optionally the expected failures types annotation separated by |')
47        sys.exit(1)
48    if len(sys.argv) == 2:
49        TransformExpectedFailures().transform(sys.argv[1])
50    else:
51        TransformExpectedFailures().transform(sys.argv[1], sys.argv[2])
52