47 lines
1.4 KiB
Python
47 lines
1.4 KiB
Python
from docxtpl import DocxTemplate
|
|
from pathlib import Path
|
|
import sys
|
|
import html
|
|
|
|
# Загрузка шаблона
|
|
doc = DocxTemplate("template/source-code-template.docx")
|
|
|
|
|
|
def get_sources(source_root):
|
|
filenames = [str(path.absolute())[len(source_root):] for path in Path(source_root).rglob('*.*')]
|
|
filenames.sort()
|
|
return filenames
|
|
|
|
|
|
def _get_file_context(source_root, filename):
|
|
with open(source_root + filename, 'r', encoding="utf8") as f:
|
|
content = f.read()
|
|
return {
|
|
'filename': filename.replace('\\', '/'), # для шиндовс, чтобы правильно генерить пути
|
|
'content': html.escape(content, quote=True)
|
|
}
|
|
|
|
|
|
def render_source_code(source_root, out_filename, doc_number="РОФ.ГУТВ.00000-12"):
|
|
# Данные для заполнения шаблона
|
|
context = {
|
|
'doc_number': doc_number,
|
|
'files': [
|
|
_get_file_context(source_root, src)
|
|
for src in get_sources(source_root)
|
|
]
|
|
}
|
|
|
|
# Заполнение шаблона данными
|
|
doc.render(context)
|
|
|
|
# Сохранение документа
|
|
doc.save(out_filename)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
if len(sys.argv) != 4:
|
|
print(f"Usage: {sys.argv[0]} /path/to/source/code /path/to/out.docx DOC.NUMBER")
|
|
else:
|
|
render_source_code(sys.argv[1], sys.argv[2], doc_number=sys.argv[3])
|