website/format_wiki.py

98 lines
3 KiB
Python
Executable file

#!/usr/sbin/env python3
import os
import datetime
import subprocess
import sys
import re
# if sys.platform == 'win32':
# sys.exit("Sorry, I can't work on this operating system :(")
wikiPath = "content/wiki/adm.wiki/"
# Find absolute path of wiki submodule
scriptPath = os.path.dirname(os.path.realpath(__file__))
absWikiPath = os.path.join(scriptPath, wikiPath)
def line_prepender(filename, line):
with open(filename, 'r+') as f:
content = f.read()
f.seek(0, 0)
f.write(line.rstrip('\r\n') + '\n' + content)
def get_header_from_file(file_path):
global absWikiPath
title = os.path.basename(file_path).removesuffix(".md")
# date =
cmd = ['sh', '-c']
if sys.platform == "win32":
cmd = ['cmd', '/C']
gitCmd = ['git --no-pager -C ' + absWikiPath + ' log --diff-filter=AM --follow --format=%aI -1 -- ' + title + '.md']
cmdOut = subprocess.run(args=cmd + gitCmd, capture_output = True, text = True)
try:
date = datetime.datetime.fromisoformat(cmdOut.stdout).isoformat(timespec="seconds")
except ValueError:
date = datetime.datetime.now(datetime.timezone.utc).isoformat(timespec="seconds")
if title == '_index':
title = 'Wiki'
header = '---\n' \
+ f'title: "{title}"\n' \
+ f'date: {date}\n' \
+ 'author: "ADMStaff"\n' \
+ 'draft: false\n' \
+ '---\n\n'
return header
# Need to remove _Sidebar.md file
sidebar = "_Sidebar.md"
try:
os.remove(os.path.join(absWikiPath, sidebar))
except FileNotFoundError:
print("File", sidebar, "non presente nel path. Forse già eliminato?")
home = "Home.md"
try:
os.rename(os.path.join(absWikiPath, "Home.md"), os.path.join(absWikiPath, "_index.md"))
except OSError as e:
print("File", home,"non presente nel path. Forse già rinominato?")
for file in os.listdir(absWikiPath):
if file.find('.md') == -1:
continue
absFilePath = os.path.join(absWikiPath, file)
# Check if the file already contains the header
with open(absFilePath) as f:
content = f.read()
all_lines = content.splitlines()
first_line = all_lines[0]
# Some files have the NOT INCLUDE directive to avoid leaking sensitive information
# on the public website
if re.match(r'<!--+\s*(NOT|not)\s+(INCLUDE|include)\s*--+>', first_line) or re.match(r'<!--+\s*(private|PRIVATE)\s*--+>', first_line):
print("File has the 'NOT INCLUDE' or 'PRIVATE' directive, removing:", file)
os.remove(absFilePath)
continue
elif first_line.find("---") != -1:
print("File already formatted, skipping:", file)
continue
for i, line in enumerate(all_lines):
if line.startswith("#"):
all_lines[i] = "#" + line
endpath = os.path.join(absWikiPath, file)
with open(endpath, 'w') as f:
f.write("\n".join(all_lines))
header = get_header_from_file(absFilePath)
line_prepender(endpath, header)
print('Added header to', file)