-
Notifications
You must be signed in to change notification settings - Fork 0
/
new_post.py
90 lines (69 loc) · 2.59 KB
/
new_post.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
"""
This script is meant to create a new post with the days date
and fill in the markdown front matter.
These posts are designed to work with Hugo
The front matter is generated by the command line argument for the
post title. The date is collected from the system date at time.
This also dictates the file name for a new post.
USAGE: python3 new_post.py --filename [post name] --category [category]
EXAMPLE: python3 new_post.py --filename example_post_title --category til
"""
import os
from datetime import date
from datetime import datetime
import click
@click.command()
@click.option("--filename", help="The name of the file.")
@click.option("--category", help="The category of the post.")
def main(filename, category):
create_post(filename, category)
def create_post(filename, category):
# Variables that create the front matter.
post_title = filename
path = "content/posts/"
if category == "til" or "TIL":
til_path = "content/posts/til/"
filename = f"{post_title}"
filename = f"{post_title}"
get_time = datetime.now()
formatted_time = get_time.strftime("%H:%M:%S")
extension = ".md"
front_matter = f"""---
layout: post
title: "{post_title}"
date: {date.today()} {formatted_time} -0700
categories: {category}
---
"""
if category == "til" or "TIL":
new_post_file = f"{til_path}{filename}{extension}"
else:
new_post_file = f"{path}{filename}{extension}"
# Calls the create_git_branch function and passes
# in the post_title.
try:
create_git_branch(post_title)
print(f"🚀 Successfully created {post_title + extension} and checked out a new git branch: {post_title}")
except:
print(f"❌ Failed created a new git branch named {post_title}")
# Creates the new post file and adds the Jekyll front matter.
try:
# Creates new post file using the new_post_file variable.
# Stores the file in the _posts/ directory.
os.system(f"touch {new_post_file}")
# Opens new_post_file with read/write access
# and writes the contents of the front_matter
# variable at the top of the file.
with open(f"{new_post_file}", "r+") as f:
f.write(f"{front_matter}")
# Prints to the console that a new file has been created.
print(f"👍 {filename} successfully created in {path}{filename}")
except:
print("😳 An error occured")
def create_git_branch(post_title):
try:
os.system(f"git checkout -b {post_title}")
except:
print(f"Failed to checkout branch: {post_title}")
if __name__ == "__main__":
main()