Added support for custom filenames, plus minor changes.

This commit is contained in:
= 2022-06-05 21:36:41 +05:30
parent 7e335eb01d
commit 40870fd759
1 changed files with 53 additions and 18 deletions

71
gempost
View File

@ -86,7 +86,6 @@ def menuFunction(menu = [], headerLine = "Use the arrow keys or j,k to make a se
endOfPage = len(imenu)
highlight = endOfPage - 1
#stdscr.addstr("Use the arrow keys or j,k to make a selection. Press 'c' to cancel.\n")
stdscr.addstr(headerLine)
for sno in range(len(imenu)):
@ -199,7 +198,7 @@ def rebuildReferences(filename = None, title = None, callingFrom = "default"):
po.writelines(headerText)
def newpost(title, existing_content = None):
def newpost(title, existing_content = None, filename = None):
modified = False
""" Write and submit a new post """
if (existing_content == None or existing_content == []):
@ -207,8 +206,12 @@ def newpost(title, existing_content = None):
else:
modified = True # modify the function if doing this for existing file
filename = sha1(str(f"{title}{random()}").encode("utf-8")).hexdigest() # generating a unique filename
if (filename == None):
filename = sha1(str(f"{title}{random()}").encode("utf-8")).hexdigest() # generating a unique filename
if (title[-1] == '\n'): # remove the \n at end of title if its there
title = title[:-1]
exec(f"touch {wdir + filename}.gmi") # creating empty file
che = input("\nAdd an ASCII Art header to your post? (define it in blogpostHeader.gmi): (y/[n]) ")
@ -216,7 +219,6 @@ def newpost(title, existing_content = None):
try:
with open(f"{wdir}blogpostHeader.gmi") as a: # checking if header for each post has been defined
postHeader = a.readlines()
#postHeader.append('\n')
with open(f"{wdir + filename}.gmi",'w') as f:
f.writelines(postHeader)
except FileNotFoundError:
@ -268,12 +270,17 @@ def manage(direct = ""):
allposts = i.readlines()
postsList = []
"""
for i in allposts: # creating a list containing titles corresponding to filenames
postsList.append([i[56:-1],i[11:51]])
"""
for i in allposts: # creating a list containing titles corresponding to filenames
postsList.append(i[11:].split(".gmi ", 1))
menuItems = []
for i in postsList: # formatting it into a string list for the ncurses menu function
menuItems.append(f"{i[0]} | {i[1]}")
menuItems.append(f"{i[0]} | {i[1][:-1]}")
which = menuFunction(menuItems)
@ -426,30 +433,58 @@ elif (arg == "qs"):
elif (arg == "post"):
checkInit()
title = ""
while True: # inputting post title from user
title = input("\nPOST TITLE: ")
if (title[-1] == '\n'): # removing the \n that creeps in because of input()
title = title[:-1]
if (len(title) == 0):
prRed("Post title cannot be empty.")
else:
break
fname = None
existing_files = listdir(f"{postDir}")
while True: # inputting custom filename from user, or not. if empty, simply set fname to None, which makes newpost() know to generate filename using the sha1 hash
fname = input("\nFILENAME: (without .gmi extension) (no spaces. leave empty to generate random) ")
if (fname[-1] == '\n'): # removing the \n that creeps in because of input()
fname = fname[:-1]
if ".gmi" in fname:
prYellow("The filename should not contain .gmi extension because it is automatically added.\n Correcting and continuing...")
fname = fname[:-4]
if ' ' in fname:
prRed("The filename cannot contain spaces.")
elif (fname == ''):
fname = None
break
elif f"{fname}.gmi" in existing_files:
prRed("A file with this name already exists.")
else:
break
if (len(argv) >= 3): # checking if more than 1 arg (except python) to see if source file has been supplied
filePath = argv[2] # storing that file's path in a var
print(f"Using file {filePath}") # tell the user that the program is using a source file
print(f"\nUsing file {filePath}") # tell the user that the program is using a source file
exiting_content = [] # stores content of the file
title = input("\nPOST TITLE: ")
try:
with open(filePath, 'r') as f: # populating file content and title variables
existing_content = f.readlines()
newpost(title, existing_content)
newpost(title, existing_content, fname)
except FileNotFoundError:
prRed("Invalid file path / file does not exist.")
else:
print("\nAfter entering a title, an editor will be launched for you to write your blog post.")
else: # the normal flow of new post
print("\nAn editor will be launched for you to write your blog post.")
print("The process will continue after you exit the editor (Ctrl+X).")
title = input("\nPOST TITLE: ")
if (len(title) == 0):
prRed("Post title cannot be empty.")
else:
newpost(title)
cont = input("Press enter to continue.")
newpost(title, None, fname)
elif (arg == "manage"):
checkInit()
@ -508,7 +543,7 @@ elif (arg == "purge"): # permanently delete trashed posts
elif (arg == "init"): # initialize public_gemini/ for use with gempost
if (len(listdir(f"{wdir}")) <= 1):
exec(f"touch {wdir}postIndex && mkdir {wdir}postdir/ {wdir}trash/ && chmod 745 {wdir}* && chmod 700 {wdir}trash/")
ch = input("Also create index.gmi ? (y/[n]) ")
ch = input("\nAlso create index.gmi ? (y/[n]) ")
if (ch == 'y' or ch == 'Y'):
index_init = [f"# {getlogin()}'s page\n", "\nThis is your homepage. You can customize it however you want by editing this file.\n", "\nJust remember keeping around the link below to point your visitors to your posts!\n", "\n=> ./posts.gmi Posts"]
exec(f"touch {wdir}index.gmi")