Add option to pass root directory

This commit is contained in:
Knoch 2019-12-17 21:49:14 +01:00
parent b3a1a09266
commit 5684fa85cf

34
main.py
View File

@ -2,7 +2,12 @@
import yaml
import pypandoc
import os
import re
import sys
root = ""
lang = "de"
# Compiles a presentation in the given language from the given directory and
# stores it in a corresponding slides.lang.html file inside the same directory.
@ -11,10 +16,10 @@ def compile(directory, language='en'):
root = directory
global lang
lang = language
wrapper = open(root + 'layouts/root.html', 'r').read()
wrapper = open(os.path.join(root, 'layouts/root.html'), 'r').read()
wrapper = wrapper.replace('@slides', compile_chapters())
wrapper = insert_metadata(wrapper, lang=lang)
with open(root + 'slides.' + lang + '.html', 'w+') as output:
with open(os.path.join(root, 'slides.' + lang + '.html'), 'w+') as output:
output.write(wrapper)
print('done')
@ -42,10 +47,11 @@ def compile_chapters():
# Compiles a presentation's chapter (given its name) by splitting it into
# slides, compiling those, and returning them as a string of <article>s.
def compile_chapter(chapter):
global root
if type(chapter) != str:
raise Exception('Chapters with attributes are not supported yet.\n' +
str(chapter))
chapter_file = open(root + 'slides/' + chapter + '.' + lang + '.md', 'r')
chapter_file = open(os.path.join(root, 'slides/' + chapter + '.' + lang + '.md'), 'r')
delimiter = '\n@slide'
chapter_input = ('\n' + chapter_file.read()).split(delimiter)
slides = [delimiter + slide for slide in chapter_input][1:]
@ -96,8 +102,9 @@ def get_slide_data(slide):
# Reads the layout file for a given layout name and returns its content as a
# string.
def get_slide_layout(layout_name):
global root
try:
return open(root + 'layouts/' + layout_name + '.html', 'r').read()
return open(os.path.join(root, 'layouts/' + layout_name + '.html'), 'r').read()
except FileNotFoundError:
raise Exception('Layout ' + layout_name + ' not found!')
@ -106,16 +113,25 @@ def get_slide_layout(layout_name):
def convert_slide_content(content):
return pypandoc.convert_text(content, 'html', format='md')
# Calls a YAML parser for the given relativ path inside the presentation root
# Calls a YAML parser for the given relative path inside the presentation root
# directory. Returns a dictionary with the YAML content.
def read_yaml(path):
with open(root + path, 'r') as stream:
global root
with open(os.path.join(root, path), 'r') as stream:
try:
return yaml.safe_load(stream)
except yaml.YAMLError as exc:
print(exc)
if __name__ == '__main__':
compile('../test/', language='de')
compile('../test/', language='en')
# Print information on how to use this program.
def print_usage():
print("Usage: python3 main.py <root-directory>")
if __name__ == '__main__':
if len(sys.argv) != 2:
print_usage()
else:
compile(sys.argv[1], language='de')
# TODO: Handle multiple languages
# compile(sys.argv[1], language='en')