Skip to content

Instantly share code, notes, and snippets.

@renegarcia
Last active October 8, 2023 17:44
Show Gist options
  • Save renegarcia/82e94eeda09893d4dc7c7096c5c64bd0 to your computer and use it in GitHub Desktop.
Save renegarcia/82e94eeda09893d4dc7c7096c5c64bd0 to your computer and use it in GitHub Desktop.
Python script to create a new post in jekyll.
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)
@renegarcia
Copy link
Author

Call from the top-level directory of your jekyll site. (Where your _posts folder is).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment