AnalogueLife

Analogue witterings…

Python v1.0

This now has the same functionality as my BASH script

It is approx 100 lines of code longer. It took a bit more effort in finding solutions, allied to my knowledge also.

There are a couple of lines that are essentially calls to BASH, that I could probably convert in some way to more pythonic versions. There is a lot of verbose coding to my very untrained eye. It works, but I think could be tighter. A rewrite in the future if my knowledge increases…

#!/usr/bin/env python
# TODO - work out how to link *Tags* to tags.html & to do a search on *Tag*

import os, re, subprocess, frontmatter
from datetime import datetime

draftsDir = 'drafts/'
postsDir = 'posts/'
tmplDir = 'tmpl/'

WEBSITE = "https://analoguelife.xyz/"
SITE = "AnalogueLife"
AUTHOR = f"{os.getlogin()}@analoguelife"
DEFAULTFOLDER = os.getcwd()
EDITOR = os.environ.get('EDITOR','lvim+ +startinsert')
INDEX = "index.html"

# Create New Post
def newPost():
title = input("Title of new Post? ")
TITLE = title
HEADER = SITE
SUBHEAD = "Analogue witterings..."
DATE = datetime.now().strftime("%Y-%m-%d %H:%M")
EXT = "md"
SLUG = re.sub(r'[^a-zA-Z0-9]', '-', title).lower()
if title[0] == "2":
TITLE = title[11:]
if not os.path.isfile(f"{DEFAULTFOLDER}/drafts/{SLUG}.{EXT}"):
with open(f"{DEFAULTFOLDER}/drafts/{SLUG}.{EXT}", "w") as file:
file.write(f"---\nwebsite: {WEBSITE}\nsite: {SITE}\nheader: {HEADER}\nsubhead: {SUBHEAD}\ntitle: {TITLE}\nauthor: {AUTHOR}\ndate: {DATE}\nslug: {SLUG}\ntags: [ , ]\n---\n\n")
os.system(f"{EDITOR} {DEFAULTFOLDER}/drafts/{SLUG}.{EXT}")
exit()

# Publish draft Post to posts/ directory before pushing via Git.
def publishPost():
print(' Choose which Post to \'Publish\', or 0 to exit')
print(' ----------------------------------------------')
filesDict = getFiles()
if not filesDict:
print('\t### No Files in Drafts to Publish ###\n')
else:
# code here to select file from list/dict
userOption = ''
userOption = int(input('\t >> Enter your choice: '))
print('\t','\t>> You chose this file to \'PUBLISH\':', filesDict[userOption])
filename = filesDict[userOption]
#get tags from frontmatter
getTags(filename)
# write markdown to main html files
fileout = postsDir+os.path.splitext(filename)[0] + ".html"
args1 = ['pandoc', draftsDir+filename, '-o', fileout, '--template=tmpl/main.html']
subprocess.check_call(args1)
# write tags to post.html
subprocess.call(['sed', '-i', '/<!--TAGS-->/r tmpl/tags.html', fileout])
# write markdown to main html files
entryout = os.path.splitext(filename)[0] + '-entry' + ".html"
args2 = ['pandoc', draftsDir+filename, '-o', entryout, '--template=tmpl/entry.html']
subprocess.check_call(args2)
subprocess.call(['sed', '-i', '/<!--ENTRY-->/r'+entryout, 'index.html'])
# Remove entry
os.remove(entryout)
# Delete draft
os.remove(draftsDir+filesDict[userOption])
print('\t>> Temporary \'Entry\' & Draft deleted\n')

# Delete draft Post
def deleteLocalDraft():
print(' Select Draft to \'Delete\', or 0 to exit')
print(' ----------------------------------------')
filesDict = getFiles()
if not filesDict:
print('\t### No Files in Drafts to Delete ###\n')
else:
userOption = ''
userOption = int(input('\t>> Enter your choice: '))
print('\t','----> You chose this file to \'DELETE\':', filesDict[userOption])
while True:
ans = ''
try:
print('Confirm by typing: yes, no or Q to exit')
ans = input('\t>> Enter confirmation: ')
except:
print('>> Answer either \'yes\', \'no\' or Q\n')
if ans == 'yes':
os.remove(draftsDir+filesDict[userOption])
print('>> File deleted\n')
exit()
elif ans == 'no':
print('>> Cancelled\n')
exit()
elif ans == 'Q':
print('>> You chose to exit!\n')
exit()
else:
print('>> Invalid option. Please enter \'yes\', \'no\' or \'Q\'.\n')

# Push to repository
def pushToRepo():
print(subprocess.run(["./gitpush","arguments"], shell=True))
print('\n -----------------------------')
print(' Successfully pushed to repo')
print(' -----------------------------\n')
exit()

# Read .md for Tags in frontmatter
def getTags(filename):
with open(draftsDir+filename) as f:
metadata, content = frontmatter.parse(f.read())
lst = metadata.items()
mydict = {t[0]: t[1] for t in lst}
tags = list(mydict)[-1]
with open(tmplDir+"tags.html", 'w') as f:
for value in mydict[tags]:
f.write('<li>'+value+'</li>' + '\n')

# Get files in Directory 'Drafts'.
def getFiles():
files= os.listdir(draftsDir)
filesDict = dict(enumerate(files, start=1))
print("\n".join(" \t {} -- {}".format(key, value) for key, value in filesDict.items()))
return filesDict

# Menu Choice Options
menuOptions = {
1:'Create New Post',
2:'Publish Post',
3:'Delete Draft',
4:'Push to Repository',
0:'Exit',
}

def printMenu():
for key in menuOptions.keys():
print('\t',key, '--', menuOptions[key] )

if __name__ == "__main__":
while(True):
print(' ----------------------')
print(' Analogelife Blog Menu ')
print(' ----------------------')
printMenu()
userOption = ''
try:
userOption = int(input('\t>> Enter your choice: '))
print()
except:
print('>> Wrong input. Please enter a number ...\n')
if userOption == 1:
newPost()
elif userOption == 2:
publishPost()
elif userOption == 3:
deleteLocalDraft()
elif userOption == 4:
pushToRepo()
elif userOption == 0:
print('>> You chose to exit!\n')
exit()
else:
print('>> Invalid option. Please enter a number between 1 and 4.\n')
  • python
  • bash
  • coding
  • dev
© matthew@analoguelife | 2024-01-12 15:38