impl: Make get_tree() a static method & return DocumentTree

This commit is contained in:
Dendy 2024-02-24 09:37:56 +01:00
parent 1707fac972
commit 6e4ae37bea
3 changed files with 30 additions and 29 deletions

View File

@ -30,9 +30,8 @@ def index(path):
internal_path = os.path.join(data_path, path + '.md') internal_path = os.path.join(data_path, path + '.md')
path = '/' + path path = '/' + path
document_tree = files.get_tree(data_path) document_tree = files.DocumentTree.get_tree(data_path)
for entry in document_tree: document_tree.print_tree()
entry.print_tree()
# Checks ################################################### # Checks ###################################################

View File

@ -1,4 +1,5 @@
import os import os
import posixpath
from typing import Self from typing import Self
@ -13,35 +14,36 @@ class DocumentTree():
for child in self.children: for child in self.children:
child.print_tree(level + 1) child.print_tree(level + 1)
@staticmethod
def get_tree(base: str, path: str = '') -> "DocumentTree":
print(base, path)
children = list()
# TODO: Make this a static method or something, so we can make some sort of # Split and remerge for Windows
# interface that calls this predefined class internal_path = os.path.join(base, *path.split('/'))
def get_tree(path: str) -> list[DocumentTree]:
ret = list()
_, dirs, files = next(os.walk(path)) if not os.path.exists(internal_path):
raise Exception("Tried to open a folder that doesn't exist")
# First pass, get the whole folder structure _, dirs, files = next(os.walk(internal_path))
for dir in dirs:
dir_path = os.path.join(path, dir)
ret.append( for dir in dirs:
DocumentTree(dir, get_tree(dir_path)) 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, # Second pass, add the files. If it's a .md file, strip the extension,
# checking for conflicts with folders # checking for conflicts with folders
# #
# TODO: Maybe this isn't the best way to define what the text of a folder # TODO: Maybe this isn't the best way to define what the text of a
# should be. # folder should be.
# #
# TODO: What if there's a file obscuring a folder? # TODO: What if there's a file obscuring a folder?
# Check if the superposing is a .md file, warn the user otherwise # Check if the superposing is a .md file, warn the user otherwise
for file in files: for file in files:
if file.endswith('.md'): if file.endswith('.md'):
file = file[:-3] file = file[:-3]
if file not in ret: if file not in children:
ret.append(DocumentTree(file, [])) children.append(DocumentTree(file, []))
return ret return DocumentTree(path.split('/')[-1], children)

View File

@ -16,7 +16,7 @@
{% block body %} {% block body %}
<main> <main>
<nav> <nav>
{{ render_tree(item_list) }} {{ render_tree(item_list.children) }}
</nav> </nav>
<article> <article>