microsoft/TypeAgent
Publicmirrored fromhttps://github.com/microsoft/TypeAgentAvailable
ts/examples/chat/watchdata.py
76lines · modecode
| 1 | # Copyright (c) Microsoft Corporation. |
| 2 | # Licensed under the MIT License. |
| 3 | |
| 4 | """Display the tree structure of a given directory tree.""" |
| 5 | |
| 6 | import binascii |
| 7 | import os |
| 8 | import sys |
| 9 | import time |
| 10 | |
| 11 | rootdir = "\\data\\code" |
| 12 | |
| 13 | |
| 14 | def main(): |
| 15 | global rootdir |
| 16 | # TODO: argparse |
| 17 | if sys.argv[1:]: |
| 18 | assert not sys.argv[2:], "Too many arguments." # TODO |
| 19 | rootdir = sys.argv[1] |
| 20 | rootdir = os.path.normpath(rootdir) |
| 21 | while True: |
| 22 | if os.name == "nt": |
| 23 | # Get screen width on Windows |
| 24 | import ctypes |
| 25 | handle = ctypes.windll.kernel32.GetStdHandle(-11) |
| 26 | info = ctypes.create_string_buffer(22) |
| 27 | ctypes.windll.kernel32.GetConsoleScreenBufferInfo(handle, info) |
| 28 | rows = int.from_bytes(info[0x10:0x12], "little") |
| 29 | columns = int.from_bytes(info[0x12:0x14], "little") |
| 30 | else: |
| 31 | # Get screen width on Unix |
| 32 | rows, columns = map(int, os.popen("stty size", "r").read().split()) |
| 33 | print_tree(rootdir, rows, columns) |
| 34 | time.sleep(1) |
| 35 | |
| 36 | |
| 37 | CLEAR_SCREEN = "\x1b[H\x1b[2J\x1b[3J" |
| 38 | |
| 39 | def print_tree(rootdir, screenheight, screenwidth): |
| 40 | output = [CLEAR_SCREEN] |
| 41 | # output.append(f"{screenheight, screenwidth}\n") # Debug |
| 42 | output.append(f"Rootdir: {rootdir}\n") |
| 43 | for dirpath, dirnames, filenames in os.walk(rootdir): |
| 44 | dirnames.sort() |
| 45 | filenames.sort() |
| 46 | if dirpath.startswith(rootdir): |
| 47 | dirpath = dirpath[len(rootdir):] |
| 48 | if dirpath.startswith(os.sep): |
| 49 | dirpath = dirpath[1:] |
| 50 | if not dirpath: |
| 51 | continue |
| 52 | parts = dirpath.split(os.sep) |
| 53 | assert parts |
| 54 | output.append(f"{' '*(len(parts)-1)}{parts[-1]}{os.sep}\n") |
| 55 | for filename in filenames: |
| 56 | fullpath = os.path.join(rootdir, dirpath, filename) |
| 57 | try: |
| 58 | with open(fullpath, "rb") as f: |
| 59 | contents = f.read() |
| 60 | except OSError as err: |
| 61 | output.append(f"{' '*len(parts)}{filename}: {err!r}\n") |
| 62 | continue |
| 63 | length = len(contents) |
| 64 | try: |
| 65 | contents = contents.decode("utf-8") |
| 66 | contents = ascii(contents) |
| 67 | except UnicodeDecodeError: |
| 68 | contents = binascii.hexlify(contents, " ").decode("ascii") |
| 69 | head = f"{' '*len(parts)}{filename}, {length} bytes: " |
| 70 | tail = f"{contents:.{screenwidth - len(head)}s}\n" |
| 71 | output.append(head + tail) |
| 72 | print("".join(output)) |
| 73 | |
| 74 | |
| 75 | if __name__ == "__main__": |
| 76 | main() |
| 77 | |