Last active
October 8, 2023 17:44
-
-
Save renegarcia/82e94eeda09893d4dc7c7096c5c64bd0 to your computer and use it in GitHub Desktop.
Python script to create a new post in jekyll.
This file contains 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
import argparse | |
from datetime import date | |
from pathlib import Path | |
FRONTMATTER_TEMPLATE = """--- | |
layout: page | |
title: {args.title} | |
comments: true | |
published: true | |
categories: | |
tags: | |
--- | |
""" | |
FILEEXISTSERROR_TEMPLATE = """Error | |
Missing --overwrite option: The file {path} exists.""" | |
def format_filename( | |
title, publication_date: str = None, markdown_extension: str = "md" | |
): | |
if publication_date is None: | |
publication_date = date.today().isoformat() | |
return f'{publication_date}-{title.replace(" ", "-").lower()}.{markdown_extension}' | |
def write_frontmatter(args): | |
filename = format_filename(args.title, args.date) | |
path = Path(f"./_posts/{filename}") | |
try: | |
path.touch(exist_ok=args.overwrite) | |
except FileExistsError: | |
print(FILEEXISTSERROR_TEMPLATE.format(path=path)) | |
exit(1) | |
path.write_text(FRONTMATTER_TEMPLATE.format(args=args)) | |
if __name__ == "__main__": | |
parser = argparse.ArgumentParser(description="Create a new post") | |
parser.add_argument("title", type=str, help="Provide a title") | |
parser.add_argument("--date", type=str, help="Provide a date in format yyyy-mm-dd") | |
parser.add_argument( | |
"--overwrite", action="store_true", help="Overwrite existing post" | |
) | |
args = parser.parse_args() | |
write_frontmatter(args) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Call from the top-level directory of your jekyll site. (Where your
_posts
folder is).