gaisen/src/files.py

50 lines
1.5 KiB
Python

import os
import posixpath
from typing import Self
class DocumentTree():
def __init__(self, name: str, children: list[Self]):
self.name = name
self.children = children
def print_tree(self, level=0) -> None:
print('-' * level + self.name)
for child in self.children:
child.print_tree(level + 1)
@staticmethod
def get_tree(base: str, path: str = '') -> "DocumentTree":
print(base, path)
children = list()
# Split and remerge for Windows
internal_path = os.path.join(base, *path.split('/'))
if not os.path.exists(internal_path):
raise Exception("Tried to open a folder that doesn't exist")
_, dirs, files = next(os.walk(internal_path))
for dir in dirs:
subpath = posixpath.join(path, dir)
children.append(DocumentTree.get_tree(base, subpath))
# Second pass, add the files. If it's a .md file, strip the extension,
# checking for conflicts with folders
#
# TODO: Maybe this isn't the best way to define what the text of a
# folder should be.
#
# TODO: What if there's a file obscuring a folder?
# Check if the superposing is a .md file, warn the user otherwise
for file in files:
if file.endswith('.md'):
file = file[:-3]
if file not in children:
children.append(DocumentTree(file, []))
return DocumentTree(path.split('/')[-1], children)