|
| 1 | +import argparse |
| 2 | +import os |
| 3 | +import stat |
| 4 | +import sys |
| 5 | + |
| 6 | + |
| 7 | +def parse_args(): |
| 8 | + parser = argparse.ArgumentParser( |
| 9 | + description="List directory contents", |
| 10 | + ) |
| 11 | + parser.add_argument( |
| 12 | + "paths", |
| 13 | + nargs="*", |
| 14 | + help="The file path to process (defaults to current directory)", |
| 15 | + ) |
| 16 | + parser.add_argument( |
| 17 | + "-a", |
| 18 | + action="store_true", |
| 19 | + dest="include_hidden", |
| 20 | + help="Include directory entries whose names begin with a dot ('.').", |
| 21 | + ) |
| 22 | + parser.add_argument( |
| 23 | + "-1", |
| 24 | + action="store_true", |
| 25 | + dest="one_per_line", |
| 26 | + help="Force output to be one entry per line.", |
| 27 | + ) |
| 28 | + return parser.parse_args() |
| 29 | + |
| 30 | + |
| 31 | +def filter_hidden(files): |
| 32 | + return [name for name in files if not name.startswith(".")] |
| 33 | + |
| 34 | + |
| 35 | +def get_visible_entries(files, include_hidden): |
| 36 | + return files if include_hidden else filter_hidden(files) |
| 37 | + |
| 38 | + |
| 39 | +def format_entries(files, one_per_line): |
| 40 | + if len(files) == 0: |
| 41 | + return |
| 42 | + print(("\n" if one_per_line else "\t").join(files)) |
| 43 | + |
| 44 | + |
| 45 | +def main(): |
| 46 | + args = parse_args() |
| 47 | + |
| 48 | + try: |
| 49 | + file_paths = args.paths if args.paths else ["."] |
| 50 | + include_hidden = bool(args.include_hidden) |
| 51 | + one_per_line = bool(args.one_per_line) |
| 52 | + |
| 53 | + result_files = [] |
| 54 | + result_dirs = {} |
| 55 | + |
| 56 | + for file_path in file_paths: |
| 57 | + st = os.stat(file_path) |
| 58 | + # Is a file? |
| 59 | + if stat.S_ISREG(st.st_mode): |
| 60 | + result_files.append(file_path) |
| 61 | + # Is a directory? |
| 62 | + if stat.S_ISDIR(st.st_mode): |
| 63 | + result_dirs[file_path] = os.listdir(file_path) |
| 64 | + |
| 65 | + result_files = get_visible_entries(result_files, include_hidden) |
| 66 | + |
| 67 | + if len(file_paths) == 1: |
| 68 | + entries = list(result_files) |
| 69 | + for contents in result_dirs.values(): |
| 70 | + filtered = get_visible_entries(contents, include_hidden) |
| 71 | + entries.extend(filtered) |
| 72 | + format_entries(entries, one_per_line) |
| 73 | + else: |
| 74 | + format_entries(result_files, one_per_line) |
| 75 | + |
| 76 | + for directory, contents in result_dirs.items(): |
| 77 | + print("\n" + directory + ":") |
| 78 | + filtered = get_visible_entries(contents, include_hidden) |
| 79 | + format_entries(filtered, one_per_line) |
| 80 | + except OSError as err: |
| 81 | + print(str(err), file=sys.stderr) |
| 82 | + |
| 83 | + return 0 |
| 84 | + |
| 85 | + |
| 86 | +main() |
0 commit comments