import os import subprocess import sys DELIMITER = " " HOME = os.environ[list(filter(lambda k: k.lower() == "userprofile", os.environ.keys()))[0]] os.environ["HOME"] = HOME os.chdir(HOME) class State: running = True def cwd_name(): cwd = os.getcwd() if cwd == os.environ["HOME"]: return "~" return os.path.basename(cwd) def cmd_exit(): State.running = False print("Goodbye") def cmd_pwd(): print(os.path.abspath(os.getcwd())) def cmd_ls(): cwd = os.path.abspath(os.getcwd()) print(f"Listing the contents of {cwd}\n") listing = os.listdir(cwd) if len(listing) > 0: for file in listing: path = os.path.join(cwd, file) stat = os.stat(path) type_str = "?" if os.path.isfile(path): type_str = "f" elif os.path.isdir(path): type_str = "d" print(f"{type_str} {file if len(file) < 60 else file[:57] + '...'} ({stat.st_size / 1024 / 1024} MiB)") else: print("Directory is empty!", file=sys.stderr) def cmd_cd(target): cwd = os.path.abspath(os.getcwd()) target_path = os.path.join(cwd, target) target_path = os.path.abspath(target_path) if os.path.exists(target_path): os.chdir(target_path) return possible_targets = list(filter(lambda path: path.startswith(target), os.listdir(cwd))) if len(possible_targets) > 1: print(f"Multiple possible targets to cd into:{str(possible_targets)}", file=sys.stderr) return if len(possible_targets) == 1: cmd_cd(possible_targets[0]) return print(f"Could not cd to {target}, it does not exist!", file=sys.stderr) def cmd_cat(*files): output = [] for file in files: path = os.path.join(os.path.abspath(os.getcwd()), file) with open(path, "rb") as fp: output.append(fp.read().decode("UTF-8")) print("".join(output)) BUILTIN_COMMANDS = { "exit": cmd_exit, "pwd": cmd_pwd, "ls": cmd_ls, "dir": cmd_ls, "cd": cmd_cd, "cat": cmd_cat } while State.running: prompt = f"{cwd_name()} -> " command = input(prompt).split(DELIMITER) command, arguments = command[0], command[1:] if not command: continue else: try: if command in BUILTIN_COMMANDS: BUILTIN_COMMANDS[command](*arguments) else: subprocess.check_call([command, *arguments]) except Exception as e: print(e, file=sys.stderr)