Last active
July 26, 2020 11:41
-
-
Save pixelchai/4726bd3e3e9c7d7137f4a96833702cd3 to your computer and use it in GitHub Desktop.
Python script to manage a simple Journal system (with a template)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/env python3 | |
import os | |
import datetime | |
EDIT_CMD = "vim {{ path }}" | |
BASE_PATH = "posts" | |
def template(s, data): | |
""" | |
a very simple template evaluation method | |
""" | |
ret = "" | |
buf = "" | |
inside = False | |
i = 0 | |
while i < len(s): | |
lookahead = s[i:i+2] | |
if lookahead in ("{{", "}}"): | |
inside = not inside | |
if inside: | |
buf = "" | |
else: | |
ret += data.get(buf.strip(), "??") | |
i += len(lookahead) | |
continue | |
if inside: | |
buf += s[i] | |
else: | |
ret += s[i] | |
i += 1 | |
return ret | |
# https://stackoverflow.com/a/50992575/5013267 | |
def make_ordinal(n): | |
""" | |
Convert an integer into its ordinal representation:: | |
make_ordinal(0) => '0th' | |
make_ordinal(3) => '3rd' | |
make_ordinal(122) => '122nd' | |
make_ordinal(213) => '213th' | |
""" | |
n = int(n) | |
suffix = ['th', 'st', 'nd', 'rd', 'th'][min(n % 10, 4)] | |
if 11 <= (n % 100) <= 13: | |
suffix = 'th' | |
return str(n) + suffix | |
def get_long_date(date): | |
return date.strftime("%a ") + make_ordinal(date.day) + date.strftime(" of %B, %Y") | |
def write_page(date): | |
file_path = os.path.join(BASE_PATH, date.strftime("%Y-%m-%d.md")) | |
if not os.path.isfile(file_path): | |
with open(file_path, "w") as new_file: | |
with open("res/templ.md", "r") as templ_file: | |
new_file.write(template(templ_file.read(), { | |
"longdate": get_long_date(date), | |
"date": date.strftime("%x"), | |
})) | |
return file_path | |
def edit_page(date): | |
file_path = write_page(date) | |
os.system(template(EDIT_CMD, { | |
"path": file_path, | |
})) | |
if __name__ == "__main__": | |
os.makedirs(BASE_PATH, exist_ok=True) | |
edit_page(datetime.date.today()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment