From 26a257808431b2ff2efda8fa2040754a4933b349 Mon Sep 17 00:00:00 2001 From: Luca Beltrame Date: Sun, 24 May 2015 23:45:22 +0200 Subject: [PATCH] Use temporary files for editing --- jekyll_new_post.py | 33 ++++++++++++++++++++++----------- 1 file changed, 22 insertions(+), 11 deletions(-) diff --git a/jekyll_new_post.py b/jekyll_new_post.py index a9b7a6a..b2851a9 100644 --- a/jekyll_new_post.py +++ b/jekyll_new_post.py @@ -5,7 +5,9 @@ import datetime from hashlib import sha1 from pathlib import Path import subprocess +import shutil from textwrap import fill +import tempfile from git import Repo import pytz @@ -70,19 +72,25 @@ def create_new_post(title: str, categories: list=None, tags: list=None, final_path = Path("_posts") / filename - with final_path.open("w") as handle: - handle.write("---\n") - yaml.safe_dump(metadata, handle, default_flow_style=False) - handle.write("---\n") + with tempfile.NamedTemporaryFile() as temp: - pre_edit_hash = hash_file(final_path) - subprocess.check_call("/usr/bin/kate {}".format(Path("_posts") / filename), - shell=True) - post_edit_hash = hash_file(final_path) + temp_path = Path(temp.name) - if pre_edit_hash == post_edit_hash: - print("No post content. Aborting.") - return + temp.write("---\n") + yaml.safe_dump(metadata, temp, default_flow_style=False) + temp.write("---\n") + temp.flush() + + pre_edit_hash = hash_file(temp_path) + subprocess.check_call("/usr/bin/kate {}".format(temp.name), + shell=True) + post_edit_hash = hash_file(final_path) + + if pre_edit_hash == post_edit_hash: + print("No post content. Aborting.") + return + + shutil.copy(temp.name, str(final_path)) return (final_path) @@ -102,6 +110,9 @@ def main(): options = parser.parse_args() + if not is_jekyll_root(Path("./")): + raise FileNotFoundError("Jekyll root not found.") + path = create_new_post(options.title, options.categories, options.tags, comments=options.disable_comments)