| 
 | 1 | +import os.path  | 
 | 2 | +import sys  | 
 | 3 | +import argparse  | 
 | 4 | +import typing  | 
 | 5 | +import concurrent.futures  | 
 | 6 | + | 
 | 7 | + | 
 | 8 | +import md.language.yofication  | 
 | 9 | + | 
 | 10 | +__all__ = (  | 
 | 11 | +    'ApplicationEchoLines',  | 
 | 12 | +    'ApplicationReplaceLines',  | 
 | 13 | +    'create_cli_parser',  | 
 | 14 | +    'main',  | 
 | 15 | +)  | 
 | 16 | + | 
 | 17 | + | 
 | 18 | +class ApplicationEchoLines:  | 
 | 19 | +    def __init__(self, yoficate: md.language.yofication.YoficateInterface) -> None:  | 
 | 20 | +        self._yoficate = yoficate  | 
 | 21 | + | 
 | 22 | +    def run(self, input_stream: typing.IO[str]) -> None:  | 
 | 23 | +        try:  | 
 | 24 | +            for line in iter(input_stream):  | 
 | 25 | +                print(self._yoficate.text(text=line.rstrip('\n')))  | 
 | 26 | +        except (KeyboardInterrupt, EOFError):  | 
 | 27 | +            pass  | 
 | 28 | + | 
 | 29 | + | 
 | 30 | +class ApplicationReplaceLines:  | 
 | 31 | +    def __init__(self, yoficate: md.language.yofication.YoficateInterface) -> None:  | 
 | 32 | +        self._yoficate = yoficate  | 
 | 33 | + | 
 | 34 | +    def run(self, file_path_list: typing.List[str]) -> None:  | 
 | 35 | +        with concurrent.futures.ThreadPoolExecutor(max_workers=3) as executor:  | 
 | 36 | +            for file_path in file_path_list:  | 
 | 37 | +                executor.submit(self._replace_file, file_path=file_path)  | 
 | 38 | + | 
 | 39 | +    def _replace_file(self, file_path: str) -> None:  | 
 | 40 | +        directory, filename = os.path.split(file_path)  | 
 | 41 | + | 
 | 42 | +        with open(file_path) as source_stream, open(f'{directory}/.tmp.{filename}', 'w') as destination_stream:  | 
 | 43 | +            for line in source_stream:  | 
 | 44 | +                destination_stream.write(self._yoficate.text(text=line))  | 
 | 45 | + | 
 | 46 | +        os.rename(file_path, f'{directory}/{filename}.bak.before-yofication')  | 
 | 47 | +        os.rename(f'{directory}/.tmp.{filename}', file_path)  | 
 | 48 | +        os.remove(f'{directory}/{filename}.bak.before-yofication')  | 
 | 49 | + | 
 | 50 | + | 
 | 51 | +def create_cli_parser() -> argparse.ArgumentParser:  | 
 | 52 | +    parser = argparse.ArgumentParser(  | 
 | 53 | +        prog='md.language.yofication',  | 
 | 54 | +        description='Yofication program replaces cyrillic letter "е" with letter "ё" in word where it should be.',  | 
 | 55 | +    )  | 
 | 56 | +    parser.add_argument('file_path', nargs='*', help='file to yoficate')  | 
 | 57 | + | 
 | 58 | +    # dictionary_group = parser.add_mutually_exclusive_group()  | 
 | 59 | +    # dictionary_group.add_argument('--locale', action='store', choices=['ru_RU'], default='ru_RU')  | 
 | 60 | +    # dictionary_group.add_argument('--dictionary', action='store', default=None)  | 
 | 61 | + | 
 | 62 | +    replace_group = parser.add_mutually_exclusive_group()  | 
 | 63 | +    replace_group.add_argument(  | 
 | 64 | +        '--replace',  | 
 | 65 | +        action='store_true',  | 
 | 66 | +        default=False,  | 
 | 67 | +        help='Replaces files with yoficated content'  | 
 | 68 | +    )  | 
 | 69 | +    replace_group.add_argument(  | 
 | 70 | +        '--no-replace',  | 
 | 71 | +        action='store_true',  | 
 | 72 | +        default=True,  | 
 | 73 | +        help=(  | 
 | 74 | +            'DEFAULT: Prints yoficated file content instead of replace. '  | 
 | 75 | +            'Exits with error, if few `file_path` arguments passed.'  | 
 | 76 | +        )  | 
 | 77 | +    )  | 
 | 78 | +    return parser  | 
 | 79 | + | 
 | 80 | + | 
 | 81 | +def main(arguments: typing.Sequence[str]) -> int:  | 
 | 82 | +    # | FILES | REPLACE | RESULT            |  | 
 | 83 | +    # |-------|---------|-------------------|  | 
 | 84 | +    # | =0    | 0       | OK (STDIN/STDOUT) |  | 
 | 85 | +    # | =0    | 1       | ERROR             |  | 
 | 86 | +    # | =1    | 0       | OK (STDOUT)       |  | 
 | 87 | +    # | =1    | 1       | OK (REPLACE)      |  | 
 | 88 | +    # | >1    | 0       | ERROR             |  | 
 | 89 | +    # | >1    | 1       | OK (REPLACE)      |  | 
 | 90 | + | 
 | 91 | +    parser = create_cli_parser()  | 
 | 92 | +    parsed_arguments = parser.parse_args(arguments)  | 
 | 93 | +    locale: typing.Literal['ru_RU'] = 'ru_RU'  # todo add support in further versions  | 
 | 94 | + | 
 | 95 | +    file_path_count = len(parsed_arguments.file_path)  | 
 | 96 | + | 
 | 97 | +    # validate  | 
 | 98 | +    if parsed_arguments.replace:  | 
 | 99 | +        if file_path_count == 0:  | 
 | 100 | +            print('Error: no files specified to replace', file=sys.stderr)  | 
 | 101 | +            return 1  | 
 | 102 | +    else:  | 
 | 103 | +        if file_path_count > 1:  | 
 | 104 | +            print('Error: using `--no-replace` option with many files makes no sense', file=sys.stderr)  | 
 | 105 | +            return 1  | 
 | 106 | + | 
 | 107 | +    # act  | 
 | 108 | +    builtin_dictionary = md.language.yofication.get_builtin_dictionary(locale=locale)  | 
 | 109 | +    yoficate = md.language.yofication.DefaultYoficate(dictionary=builtin_dictionary)  | 
 | 110 | + | 
 | 111 | +    if not parsed_arguments.replace:  | 
 | 112 | +        # todo consider to separate to `--interactive/-i` and `-`$  | 
 | 113 | +        application = ApplicationEchoLines(yoficate=yoficate)  | 
 | 114 | +        if file_path_count == 0:  | 
 | 115 | +            application.run(input_stream=sys.stdin)  | 
 | 116 | +            return 0  | 
 | 117 | + | 
 | 118 | +        assert file_path_count == 1  | 
 | 119 | +        with open(parsed_arguments.file_path[0], 'r') as stream:  | 
 | 120 | +            application.run(input_stream=stream)  | 
 | 121 | +        return 0  | 
 | 122 | + | 
 | 123 | +    assert parsed_arguments.replace and file_path_count >= 1  | 
 | 124 | +    application = ApplicationReplaceLines(yoficate=yoficate)  | 
 | 125 | +    application.run(file_path_list=parsed_arguments.file_path)  | 
 | 126 | +    return 0  | 
 | 127 | + | 
 | 128 | + | 
 | 129 | +if __name__ == '__main__':  | 
 | 130 | +    exit_code = main(sys.argv[1:])  | 
 | 131 | +    exit(exit_code)  | 
0 commit comments