cook2tex/cooklangbook.py

107 lines
2.9 KiB
Python
Raw Normal View History

import sys, os, cook2tex
2022-05-16 00:01:54 +02:00
def create_book(argv):
"""
Takes: [ string ] argv
Returns: [ string ] tex
Takes multiple recipe paths as arguments and returns a complete latex document.
One element per line.
"""
tex = []
for path in argv:
tex.append("\n")
tex += cook2tex.parse_recipe_from_file(path)
return latex_boilerplate(tex)
def create_book_recursive(source_path, dest_path):
"""
Takes: string source_path
string dest_path
Returns:
Reads all .cook files found in source_path and it's subdirectories.
Creates a new directory at dest_dir if it doesn't exist already.
When a recipe path reads '/source_dir/.../last_dir/recipe.cook',
creates /dest_dir/last_dir/recipe.tex and writes texified recipe to it.
Creates /dest_dir/recipe-book.tex which includes all generated recipe files,
has one chapter per directory and a table of contents.
"""
try:
os.mkdir(dest_path)
except FileExistsError:
pass
chapters = {}
for root, dirs, files in os.walk(source_path):
cook_files = {}
for name in files:
split_name = os.path.splitext(name)
if split_name[-1] == ".cook":
cook_files[split_name[0]] = os.path.join(root, name)
if cook_files:
dir_name = os.path.basename(root)
dir_path = os.path.join(dest_path, dir_name)
chapters[dir_name] = []
try:
os.mkdir(dir_path)
except FileExistsError:
pass
for name in cook_files.keys():
recipe_path = os.path.join(dir_path, name + ".tex")
chapters[dir_name].append(recipe_path)
with open(recipe_path, "w") as file:
for line in cook2tex.parse_recipe_from_file(cook_files[name]):
file.write(line + "\n")
tex = []
for chap in chapters.keys():
tex.append("\\section{" + chap + "}")
for file_name in chapters[chap]:
tex.append("\\input{" +
os.path.relpath(file_name, dest_path) + "}")
tex.append("\n")
with open(os.path.join(dest_path, "recipe-book.tex"), "w") as file:
for line in latex_boilerplate(tex):
file.write(line + "\n")
def latex_boilerplate(body):
tex = []
2022-05-16 00:01:54 +02:00
tex.append("\\documentclass{article}")
tex.append("\\usepackage{cuisine}")
tex.append("\n")
tex.append("\\begin{document}")
tex.append("\n")
tex.append("\\tableofcontents")
tex.append("\n")
2022-05-16 00:01:54 +02:00
tex += body
2022-05-16 00:01:54 +02:00
tex.append("\n")
tex.append("\\end{document}")
return tex
2022-05-16 00:01:54 +02:00
if __name__ == "__main__":
if sys.argv[1] == "-r":
tex = create_book_recursive(sys.argv[2], sys.argv[3])
else:
for line in create_book(sys.argv[1:]):
print(line)