From 6d020825e5f2fa09bd5488954ecec2afe8c85aef Mon Sep 17 00:00:00 2001 From: neodarz Date: Sun, 26 May 2019 16:48:15 +0200 Subject: Move touch to external file --- cli/cli.py | 66 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) (limited to 'cli') diff --git a/cli/cli.py b/cli/cli.py index 71491357..0de89048 100644 --- a/cli/cli.py +++ b/cli/cli.py @@ -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 -- cgit v1.2.1