mjestecko/tools/article_wrapper.py
2024-03-31 10:38:30 +05:00

67 lines
2.2 KiB
Python
Executable File

#!/usr/bin/python3
# todo: Show related git history of a file?
from sys import argv, exit
import time, urllib.parse, re
import os.path as path
from article_utils import the_line_after_metadata, parse_metadata
from page_builder import wrap_page
from date_descriptions import MONTHS
if len(argv) <= 1:
print("No file was supplied")
exit(-1)
if len(argv) <= 2:
print("No address was supplied")
exit(-1)
with open(argv[1], "r") as f:
content = f.readlines()
i = the_line_after_metadata(content)
metadata = parse_metadata(argv[1])
directory = path.split(path.dirname(path.abspath(argv[1])))[-1]
title = metadata["Title"]
article_head = "\n# " + title + "\n"
brief = metadata.get("Brief")
if not brief is None:
article_head += f"*{brief}*\n\n"
date = metadata.get("Date")
if not date is None:
article_head += f"-- Created: *{MONTHS[date.tm_mon]} {date.tm_mday}, {date.tm_year} UTC*\n\n"
last_edit = metadata.get("Last Edit")
if not last_edit is None:
if date is None or last_edit.tm_mon != date.tm_mon or \
last_edit.tm_mday != date.tm_mday or last_edit.tm_year != date.tm_year:
article_head += f"-- Edited: *{MONTHS[last_edit.tm_mon]} {last_edit.tm_mday}, {last_edit.tm_year} UTC*\n\n"
tags = metadata.get("Tags")
if tags:
tag_links = []
for tag in tags:
tag_links.append(f"[{tag}](/tags/{urllib.parse.quote(tag.lower())}.html)")
article_head += f"""-- Tags: *{", ".join(tag_links)}*\n\n"""
article_head += "---\n\n"
header = f"""HTML header: <meta property="og:title" content="{title} on mjestečko"></meta>
<meta property="og:type" content="article"></meta>
<meta property="og:url" content="{argv[2]}/articles/{urllib.parse.quote(directory)}.html"></meta>
<meta name="viewport" content="width=device-width, initial-scale=1">
"""
if not brief is None:
header += f"""<meta property="og:description" content="{brief}"></meta>\n"""
front_image = re.compile(r"!\[.*\]\((.+?)\)", re.DOTALL).search(''.join(content[i:]))
if not front_image is None:
header += f"""<meta property="og:image" content="{argv[2]}/{urllib.parse.quote(front_image.group(1))}"></meta>\n"""
print(header + ''.join(content[:i]) + wrap_page(article_head + ''.join(content[i:])))