mjestecko/tools/article_utils.py

44 lines
1.3 KiB
Python
Raw Normal View History

2023-05-21 14:24:54 +00:00
import time, subprocess
2024-02-24 06:33:57 +00:00
from os import walk, path
import urllib.parse
2023-05-21 14:24:54 +00:00
def the_line_after_metadata(lines: []) -> int:
i = 0
2024-02-16 14:59:57 +00:00
while i < len(lines) and lines[i].strip():
2023-05-21 14:24:54 +00:00
i += 1
return i
def parse_metadata(filepath: str) -> {}:
result = {}
with open(filepath, "r") as f:
content = f.readlines()
i = the_line_after_metadata(content)
for line in content[:i]:
delim = line.find(":")
key, val = (line[:delim].strip(), line[delim+1:].strip())
if key == "Date":
result["Date"] = time.gmtime(int(val))
2023-05-21 14:24:54 +00:00
elif key == "Tags":
2024-02-16 13:29:50 +00:00
result["Tags"] = [v.strip() for v in val.split(",")]
2024-02-16 14:59:57 +00:00
elif val:
result[key] = val
result["Last Edit"] = time.gmtime(int(subprocess.getoutput(r"stat -c %Y " + filepath)))
2023-05-21 14:24:54 +00:00
return result
2024-02-24 06:33:57 +00:00
def parse_article_directory(directory: str) -> {}:
articles = {}
for root, dirs, _ in walk(directory):
for d in dirs:
metadata = parse_metadata(path.abspath(root + '/' + d + "/page.mmd"))
article = urllib.parse.quote(d)
articles[article] = {
"metadata": metadata
}
break
return articles
def sort_titles_by_date(articles: {}) -> []:
return sorted(articles.keys(), key=lambda a: articles[a]["metadata"].get("Date", time.gmtime(0)), reverse=True)