diff --git a/sort_known_hosts.py b/sort_known_hosts.py index dd396ab..29bae13 100755 --- a/sort_known_hosts.py +++ b/sort_known_hosts.py @@ -2,8 +2,8 @@ from __future__ import annotations +import argparse import sys -import os from pathlib import Path from collections import namedtuple @@ -19,7 +19,7 @@ class Entry(namedtuple('Entry', ['host', 'algorithm', 'hash'])): return f'{self.algorithm}{self.separator}{self.hash}' -def run(args) -> None: +def run(args: argparse.Namespace) -> None: filename: Path = getattr(args, 'input', Path()) file_path = filename.resolve() if not file_path.is_file(): @@ -73,20 +73,20 @@ def run(args) -> None: ) ) if output is None: - sys.stdout.write(output_lines) + for line in output_lines: + print(line, end='') else: output_file = output.resolve() - if not output_file.parent.exists(): - os.makedirs(output_file.parent) if output_file.is_dir(): print('Can not write to directory.') + sys.exit(1) + if not output_file.parent.exists(): + output_file.parent.mkdir(parents=True) with output_file.open('w', encoding='utf-8') as wfp: wfp.writelines(output_lines) def main() -> None: - import argparse - parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) @@ -94,7 +94,7 @@ def main() -> None: '-i', '--input', type=Path, - default=f'{os.path.expanduser("~")}/.ssh/known_hosts', + default=f'{Path("~").expanduser()}/.ssh/known_hosts', help='file to read', ) parser.add_argument('-o', '--output', type=Path, help='file to write')