100 lines
3.0 KiB
Python
100 lines
3.0 KiB
Python
"""
|
|
Logic for managing documents.
|
|
"""
|
|
import os
|
|
|
|
from redstring.parser import load, DocumentTag, DocumentTab, Document, TabOptions, TagOptions
|
|
|
|
|
|
def generate_index_document(directory: str) -> Document:
|
|
"""
|
|
Generate a document describing a document collection.
|
|
"""
|
|
categories: dict = {}
|
|
|
|
for filename in os.listdir(directory):
|
|
with open(os.path.join(directory, filename)) as f:
|
|
document: Document = load(f)
|
|
|
|
# Check if this document specifies a tab, and create it if necessary.
|
|
if category_tag := document.get_tag('category'):
|
|
category = category_tag.value
|
|
else:
|
|
category = 'index'
|
|
if category not in categories:
|
|
categories[category] = {}
|
|
category_tab = categories[category]
|
|
|
|
# Check if this document specifies a topic, and create it if necessary.
|
|
if topic_tag := document.get_tag('topic'):
|
|
topic = topic_tag.value
|
|
else:
|
|
topic = 'uncategorized'
|
|
if '.' in topic:
|
|
topic, subtopic = topic.split('.', maxsplit=1)
|
|
else:
|
|
subtopic = None
|
|
if topic not in category_tab:
|
|
category_tab[topic] = []
|
|
topic_tag = category_tab[topic]
|
|
|
|
# Save the title and id.
|
|
doc_id = document.get_tag('id').value
|
|
if doc_title_tag := document.get_tag('title'):
|
|
doc_title = doc_title_tag.value
|
|
else:
|
|
doc_title = None
|
|
|
|
topic_tag.append((doc_id, doc_title))
|
|
|
|
# Build an index document
|
|
def document_link(info):
|
|
doc_id, doc_title = info
|
|
return (
|
|
f'<a href="/doc/{doc_id}">{doc_title} ({doc_id})</a>'
|
|
if doc_title else
|
|
f'<a href="/doc/{doc_id}">{doc_id}</a>'
|
|
)
|
|
|
|
built_tabs: list = []
|
|
for category in sorted(categories.keys()):
|
|
built_tags: list = []
|
|
|
|
for topic in sorted(categories[category].keys()):
|
|
docs = sorted(categories[category][topic], key=lambda x: x[0])
|
|
doc_links = map(document_link, docs)
|
|
value = '- ' + '<br>- '.join(doc_links)
|
|
built_tags.append(DocumentTag(topic, value))
|
|
|
|
built_tabs.append(DocumentTab(category, built_tags))
|
|
|
|
return Document(built_tabs)
|
|
|
|
|
|
def generate_default_document(doc_id) -> Document:
|
|
"""
|
|
Generate a blank document.
|
|
"""
|
|
return Document(tabs=[
|
|
DocumentTab(
|
|
name='tags',
|
|
tags=[
|
|
DocumentTag('id', doc_id),
|
|
DocumentTag('title', ''),
|
|
DocumentTag('author', ''),
|
|
DocumentTag('date', ''),
|
|
DocumentTag('source', ''),
|
|
DocumentTag('summary', ''),
|
|
DocumentTag('category', 'index', TagOptions(private=True)),
|
|
DocumentTag('topic', 'uncategorized', TagOptions(private=True)),
|
|
]
|
|
),
|
|
DocumentTab(
|
|
name='notes',
|
|
tags=[
|
|
DocumentTag('notes', ''),
|
|
],
|
|
options=TabOptions(private=True, hide_names=True)
|
|
)
|
|
])
|