From 99911d025a2e2af5eb62294135f5ce7235ec29e0 Mon Sep 17 00:00:00 2001 From: Dendy Faist Date: Sat, 24 Feb 2024 11:18:53 +0100 Subject: [PATCH] impl: Read and write members in DocumentTree --- src/__init__.py | 13 +++++-------- src/files.py | 26 +++++++++++++++++++++++--- 2 files changed, 28 insertions(+), 11 deletions(-) diff --git a/src/__init__.py b/src/__init__.py index 51f948e..96ffe28 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -33,7 +33,6 @@ app.jinja_env.globals.update( @app.route('/', methods=['POST', 'GET']) def index(path): data_path = config.get('data_path') - internal_path = os.path.join(data_path, path + '.md') document_tree = files.DocumentTree(data_path) document_tree.root.print_tree() @@ -58,18 +57,16 @@ def index(path): 200, ) - raw_markdown = request.form.get('text', None) - if raw_markdown is not None: - with open(internal_path, 'w') as file: - file.write(str(raw_markdown)) + sent_markdown = request.form.get('text', None) + if sent_markdown is not None: + document_tree.document_write(path, sent_markdown) # Get the document contents ################################ is_edit = 'edit' in request.args and path != '' - if os.path.exists(internal_path): - with open(internal_path) as file: - raw_markdown = file.read() + if True: + raw_markdown = document_tree.document_read(path) elif is_edit: raw_markdown = f'# {path}\n\nChangeme' else: diff --git a/src/files.py b/src/files.py index 1388897..b2b2c2b 100644 --- a/src/files.py +++ b/src/files.py @@ -68,9 +68,29 @@ class DocumentNode(): class DocumentTree(): - def __init__(self, path: str): - self.path = path - self.root = DocumentNode.get_tree(path, '') + def __init__(self, base: str): + self.base = base + self.root = DocumentNode.get_tree(base, '') def get_node(self, path: str) -> DocumentNode | None: return self.root.get_child(path) + + # ----- Document Operations ----- + + # Split and remerge for Windows + def document_read(self, path: str) -> str | None: + internal_path = os.path.join(self.base, *path.split('/')) + '.md' + if os.path.exists(internal_path): + return open(internal_path).read() + + # File doesn't exist + return None + + def document_write(self, path: str, text: str) -> None: + internal_path = os.path.join(self.base, *path.split('/')) + '.md' + + # TODO: Check if the directory exists before writing + with open(internal_path) as file: + file.write(text) + + # -------------------------------