|
class Directory: |
|
def __init__(self, name): |
|
self.name = name |
|
self.directories = [] |
|
self.files = [] |
|
self.created = False |
|
|
|
|
|
def parse_dir(lines: list[str], dir_name: str, position: int = 0, indent: int = 0) -> (Directory, int): |
|
dir = Directory(dir_name) |
|
index = 0 |
|
while position + index < len(lines): |
|
line = lines[position + index] |
|
name = line.lstrip() |
|
current_indent = len(line) - len(name) |
|
|
|
if len(line) == 0: |
|
index += 1 |
|
continue |
|
|
|
if current_indent < indent: |
|
break |
|
|
|
if name[-1] == "/": |
|
next_position = position + index + 1 |
|
cur_dir, idx = parse_dir(lines, name, next_position, current_indent + 1) |
|
dir.directories.append(cur_dir) |
|
index += idx |
|
else: |
|
dir.files.append(name) |
|
|
|
index += 1 |
|
|
|
return dir, index |
|
|
|
|
|
def gen_dir(lines: list[str]) -> Directory: |
|
lines = [line.replace("\n", "").rstrip() for line in lines] |
|
|
|
root_dir, _ = parse_dir(lines, "root") |
|
|
|
return root_dir |
|
|
|
|
|
def make_line(cmd: str, path: str, fields: list[str], end: str = "") -> str: |
|
sep, lhs, rhs = "", "", "" |
|
if len(fields) > 1: |
|
sep, lhs, rhs = ",", "{", "}" |
|
|
|
names = sep.join(fields) |
|
|
|
return f"{cmd} {path}{lhs}{names}{rhs}{end}\n" |
|
|
|
|
|
def gen_sh(dir: Directory, path: str = "") -> str: |
|
mkdir = touch = txt = result = "" |
|
|
|
if len(dir.directories) == 1: |
|
directory = dir.directories[0] |
|
result = gen_sh(directory, f"{path}{directory.name}") |
|
else: |
|
dir_names = [] |
|
if len(dir.directories) > 1: |
|
for directory in dir.directories: |
|
directory.created = True |
|
dir_names.append(directory.name.replace("/", "")) |
|
result += gen_sh(directory, f"{path}{directory.name}") |
|
if not dir.created or len(dir_names) > 0: |
|
mkdir = make_line("mkdir -p", path, dir_names) |
|
|
|
if len(dir.files) > 0: |
|
files_name = [file for file in dir.files] |
|
touch = make_line("touch", path, files_name) |
|
|
|
txt += f"{mkdir}{touch}{result}" |
|
|
|
return txt |
|
|
|
|
|
def main(): |
|
with open("input.txt", "r") as f: |
|
lines = f.readlines() |
|
|
|
root_dir = gen_dir(lines) |
|
|
|
txt = gen_sh(root_dir) |
|
with open("output.sh", "w") as f: |
|
f.write(txt) |
|
|
|
print(txt) |
|
|
|
|
|
if __name__ == "__main__": |
|
main() |