diff options
author | neodarz <neodarz@neodarz.net> | 2019-05-26 16:48:15 +0200 |
---|---|---|
committer | neodarz <neodarz@neodarz.net> | 2019-05-26 16:48:18 +0200 |
commit | 6d020825e5f2fa09bd5488954ecec2afe8c85aef (patch) | |
tree | ad1fd7d79b719f9e0e04e01e4241a4e7a86f3feb /cli | |
parent | 12e05d77288c39f262322eaee36faf3d0b31c781 (diff) | |
download | my_new_personal_website-6d020825e5f2fa09bd5488954ecec2afe8c85aef.tar.xz my_new_personal_website-6d020825e5f2fa09bd5488954ecec2afe8c85aef.zip |
Move touch to external file
Diffstat (limited to 'cli')
-rw-r--r-- | cli/cli.py | 66 |
1 files changed, 66 insertions, 0 deletions
@@ -5,6 +5,10 @@ import subprocess import sys +import re +import io +import fileinput + from config.config import * from utils import utils @@ -82,3 +86,65 @@ def new_post(title): def new_post_cli(args): """CLI wrapper around new_post.""" new_post(args.title) + + +def touch(filename): + """Update the timestamp of a post to the current time.""" + filename = os.path.basename(filename) + fullpath = os.path.join(POSTSDIR, filename) + if not os.path.exists(fullpath): + sys.stderr.write("%serror: post %s not found %s\n" % + (RED, fullpath, RESET)) + return 1 + filename_prefix_re = re.compile(r"^[0-9]{4}-[0-9]{2}-[0-9]{2}") + if not filename_prefix_re.match(filename): + sys.stderr.write(RED) + sys.stderr.write("error: post %s is not a valid post\n" % filename) + sys.stderr.write("error: the filename of a valid post begins with " + "a date in the form xxxx-xx-xx\n") + sys.stderr.write(RESET) + return 1 + + # update timestamp in the metadata section of the post + whatchanged = io.StringIO() + date = utils.current_datetime() + iso_date = date.isoformat() + display_date = "%s %d, %d" % (date.strftime("%B"), date.day, date.year) + filename_date = date.strftime("%Y-%m-%d") + with fileinput.input(files=(fullpath), inplace=True) as lines: + meta_fences = 0 + for line in lines: + if line.startswith("---"): + meta_fences += 1 + sys.stdout.write(line) + continue + if meta_fences >= 2: + # already went past the metadata section + sys.stdout.write(line) + continue + + if line.startswith("date: "): + updated_line = "date: %s\n" % iso_date + sys.stdout.write(updated_line) + whatchanged.write("-%s+%s\n" % (line, updated_line)) + continue + + if line.startswith("date_display: "): + updated_line = "date_display: %s\n" % display_date + sys.stdout.write(updated_line) + whatchanged.write("-%s+%s\n" % (line, updated_line)) + continue + + sys.stdout.write(line) + + sys.stderr.write("\n%schangeset:%s\n\n%s" % + (YELLOW, RESET, whatchanged.getvalue())) + whatchanged.close() + + # check if the file needs to be renamed + new_filename = filename_prefix_re.sub(filename_date, filename) + if new_filename != filename: + new_fullpath = os.path.join(POSTSDIR, new_filename) + os.rename(fullpath, new_fullpath) + sys.stderr.write("%srenamed to %s%s\n" % (YELLOW, new_filename, RESET)) + return 0 |