|
| 1 | +import argparse |
| 2 | +import io |
| 3 | +import pprint |
| 4 | +import re |
| 5 | +import shutil |
| 6 | +import sys |
| 7 | +from typing import Optional |
| 8 | + |
| 9 | +from bencodex import load |
| 10 | + |
| 11 | +__all__ = 'main', |
| 12 | + |
| 13 | +parser = argparse.ArgumentParser( |
| 14 | + description='Debug-friendly Bencodex formatter', |
| 15 | +) |
| 16 | +parser.add_argument( |
| 17 | + 'file', |
| 18 | + metavar='FILE', |
| 19 | + nargs='?', |
| 20 | + help='the path of the Bencodex file to show. if omitted (default) it ' |
| 21 | + 'expects the Bencodex data from the standard input' |
| 22 | +) |
| 23 | +parser.add_argument( |
| 24 | + '-x', '--hex-input', |
| 25 | + action='store_true', |
| 26 | + default=False, |
| 27 | + help='expects the input data is not binary, but hexadecimal text' |
| 28 | +) |
| 29 | + |
| 30 | + |
| 31 | +def read_input(path: Optional[str], hex: bool): |
| 32 | + if path is None: |
| 33 | + # Pipes are not seekable |
| 34 | + if hex: |
| 35 | + data = hex_to_bin(sys.stdin.read()) |
| 36 | + else: |
| 37 | + data = sys.stdin.buffer.read() |
| 38 | + return io.BytesIO(data) |
| 39 | + elif hex: |
| 40 | + with open(path, 'r') as f: |
| 41 | + hex_data = f.read() |
| 42 | + data = hex_to_bin(hex_data) |
| 43 | + return io.BytesIO(data) |
| 44 | + return open(path, 'rb') |
| 45 | + |
| 46 | + |
| 47 | +def hex_to_bin(hex: str) -> bytes: |
| 48 | + return bytes.fromhex(re.sub(r'[\s.,:;_-]+', '', hex)) |
| 49 | + |
| 50 | + |
| 51 | +def main() -> None: |
| 52 | + args = parser.parse_args() |
| 53 | + term_size = shutil.get_terminal_size() |
| 54 | + with read_input(args.file, args.hex_input) as f: |
| 55 | + tree = load(f) |
| 56 | + try: |
| 57 | + pprint.pprint(tree, width=term_size.columns, compact=True) |
| 58 | + except KeyboardInterrupt: |
| 59 | + raise SystemExit(130) |
| 60 | + |
| 61 | + |
| 62 | +if __name__ == '__main__': |
| 63 | + main() |
0 commit comments