Blorg-Backend/orgHandler.py

44 lines
1.5 KiB
Python

from orgparse import load
debug: bool = True
def debugPrint(msg: str) -> None:
if debug:
print("(ORG HANDLER) PRINT: " + msg)
def checkAndRetrieveMetadata(fileData, metadataName: str):
line = fileData.readline()
metadataFullName = "#+" + metadataName + ":"
if metadataFullName in line:
linetoarray = line.split()
return " ".join(linetoarray[1:])
else:
debugPrint("Could not find " + metadataFullName + " metadata field of document!")
return False
def orgToHTML(filePath: str):
try:
fileData = open(filePath, 'r')
orgRoot = load(filePath)
Title = checkAndRetrieveMetadata(fileData, "TITLE")
if not Title:
raise Exception("A valid #+TITLE: field is required as the first line of the org page.")
shortDescription = checkAndRetrieveMetadata(fileData, "DESCRIPTION")
if not shortDescription:
debugPrint("No valid description found, will generate a placeholder from the blog itself...")
firstText = orgRoot[1].body
shortDescription = (firstText[:60] + "...") if len(firstText) > 60 else firstText
for node in orgRoot[1:]:
if node.heading:
headingLevel = str(node.level)
print("<h" + headingLevel + ">" + node.heading + "</h" + headingLevel + ">")
if node.body:
print(node.body)
except Exception as error:
debugPrint("Error parsing org! " + repr(error))
orgToHTML("./test.org")