Commit ae1fcd3a authored by Dominik Woiwode's avatar Dominik Woiwode
Browse files

Some cleanup

parent fec9e17a
......@@ -7,6 +7,7 @@ from email import encoders
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from enum import Enum
from pathlib import Path
from typing import Optional, Dict, List
......@@ -25,15 +26,16 @@ LDAP_PASSWORD = None
LDAP_MAIL = None
LDAP_NAME = None
IGNORED_TOPS = ["Anwesende", "Ständiges", "Termine"
"Mitteilungen/Verschiedenes", "Schluss"]
IGNORED_TOPS = ["Anwesende", "Ständiges", "Termine", "Mitteilungen/Verschiedenes", "Schluss"]
GIT_REPO = None
GIT_REPO_NAME = None
GIT_REPO_PATH = None
GIT_NAME = None
GIT_EMAIL = None
GIT_HELPER = None
GRAV_PROTOCOL_PATH = "pages/fachrat/02.protokolle/"
git = None
@dataclass
......@@ -47,8 +49,7 @@ class Gremium:
GREMIUM_FR = Gremium("finf", "Fachrat Informatik", "pandoc.finf.tex")
GREMIUM_FSR = Gremium(
"fsr", "Fachschaftsrat Elektrotechnik und Informatik", "pandoc.fsr.tex")
GREMIUM_FSR = Gremium("fsr", "Fachschaftsrat Elektrotechnik und Informatik", "pandoc.fsr.tex")
@dataclass
......@@ -72,7 +73,6 @@ class MailParticipant:
# Helper Functions
def sendFRMail(text: str, subject: str, sender: MailParticipant, receivers: List[MailParticipant],
attachement: "BasePad" = None):
mail = MIMEMultipart()
......@@ -109,88 +109,94 @@ def sendFRMail(text: str, subject: str, sender: MailParticipant, receivers: List
# === Git Helper ===
class GitHelper:
def __init__(self, repository, repository_name):
def __init__(self, repository:str, repository_path:str):
self.repository = repository
self.repository_name = repository_name
self.repository_path = repository_path
def clone(self):
cmd = f'git clone {self.repository}'
cmd = f'git clone {self.repository} {self.repository_path}'
os.system(cmd)
def forcePull(self):
cmd = f'git -C {self.repository_name} fetch origin master'
cmd = f'git -C {self.repository_path} fetch origin master'
os.system(cmd)
cmd = f'git -C {self.repository_name} reset --hard origin/master'
cmd = f'git -C {self.repository_path} reset --hard origin/master'
os.system(cmd)
def update(self):
if os.path.exists(self.repository_name+"/.git"):
if os.path.exists(self.repository_path + "/.git"):
self.forcePull()
else:
self.clone()
def push(self):
cmd = f'git -C {self.repository_name} push origin master'
cmd = f'git -C {self.repository_path} push origin master'
os.system(cmd)
def add(self, file):
cmd = f'git -C {self.repository_name} add {file}'
def add(self, file: str):
cmd = f'git -C {self.repository_path} add {file}'
os.system(cmd)
def commit(self, msg):
cmd = f'git -C {self.repository_name} commit -m \"{msg}\"'
def commit(self, msg: str):
cmd = f'git -C {self.repository_path} commit -m \"{msg}\"'
os.system(cmd)
def config(self, email, name):
cmd = f'git -C {self.repository_name} config user.name {name}'
cmd = f'git -C {self.repository_path} config user.name {name}'
os.system(cmd)
cmd = f'git -C {self.repository_name} config user.email {email}'
cmd = f'git -C {self.repository_path} config user.email {email}'
os.system(cmd)
class Semester:
class SemesterPart(Enum):
Summer = "Sommersemester"
Winter = "Wintersemester"
def __init__(self, year: int, part: str, displayName: str = None):
self.year = year
self.part = part.upper()
self.displayName = displayName or self.DEFAULT_DISPLAY_NAME()
self.gravPath = self.DEFAULT_GRAV_PATH()
def short(self):
if self == SemesterPart.Summer:
return "SS"
return "WS"
def DEFAULT_DISPLAY_NAME(self):
return "Wintersemester "+str(self.year)+"/"+str(self.year+1) if self.part == "WS" else "Sommersemester "+str(self.year)
def DEFAULT_GRAV_PATH(self):
return os.path.join(GIT_REPO_NAME, "pages", "fachrat", "02.protokolle", str(self.year)[2:] + self.part, "protocol_semester.de.md")
@dataclass(unsafe_hash=True)
class Semester:
year: int
part: SemesterPart
def tup(self):
return (self.year, self.part)
def __post_init__(self):
self.displayName = f"{self.part.value} {self.year}"
self.gravPath = os.path.join(GIT_REPO_PATH, GRAV_PROTOCOL_PATH,
self._gravName(), "protocol_semester.de.md")
def _gravName(self):
return f"{self.year - 2000}{self.part.short()}"
@classmethod
def fromDate(cls, date: datetime.datetime) -> "Semester":
if 4 <= date.month < 10:
# Summer
return Semester(date.year, SemesterPart.Summer)
elif date.month >= 10:
# Winter
return Semester(date.year, SemesterPart.Winter)
else:
# Winter
return Semester(date.year - 1, SemesterPart.Winter)
def uploadToGrav(self):
if os.path.exists(self.gravPath):
return
os.makedirs(str(Path(self.gravPath).parent), exist_ok=True)
with open(self.gravPath, "w") as f:
f.write(f"---\ntitle: {self.displayName}\n---")
GIT_HELPER.add("pages/")
GIT_HELPER.commit(f"Added semester {self.part} {self.year}")
GIT_HELPER.push()
@staticmethod
def getSemesterTuple(date: datetime.datetime):
if date.month > 3 and date.month < 10:
# summer
return (date.year, "SS")
elif date.month >= 10:
# winter
return (date.year, "WS")
else:
# winter
return (date.year-1, "WS")
os.makedirs(str(Path(self.gravPath).parent), exist_ok=True)
with open(self.gravPath, "w") as d:
d.write(f"---\ntitle: {self.displayName}\n---")
# === Source Types ===
git.add(GRAV_PROTOCOL_PATH)
git.commit(f"Added {self.part.value} {self.year}")
git.push()
# === Source Types ===
class SourceTypes:
def __init__(self, url: str):
self.url: str = url
......@@ -261,8 +267,8 @@ class BasePad:
outPath = Path(outFilePath)
os.makedirs(outPath.parent, exist_ok=True)
metadataStr = " " + \
" ".join([f'-M {key}="{val}"' for key,
val in self.metadata.items()])
" ".join([f'-M {key}="{val}"' for key,
val in self.metadata.items()])
templateStr = ""
if template is None and hasattr(self, "gremium"):
templateStr = f' --template="{getattr(self, "gremium").fullTemplate()}" '
......@@ -275,6 +281,7 @@ class BasePad:
return ret
class ProtocolPad(BasePad):
def __init__(self, source: SourceTypes, *_, date: datetime.datetime = None,
isFachgruppenvollversammlung: bool = False, isApproved: bool = False, gremium: Gremium = None):
......@@ -289,10 +296,33 @@ class ProtocolPad(BasePad):
return super(ProtocolPad, self).__repr__()[:-1] + f", {self.date})"
def DEFAULT_DISPLAY_NAME(self):
return f"Protokoll {self.gremium.name} {self.date.strftime('%Y-%m-%d')}" + " - Fachgruppenvollversammlung"*self.isFachgruppenvollversammlung
return f"Protokoll {self.gremium.name} {self.date.strftime('%Y-%m-%d')}" + " - Fachgruppenvollversammlung" * self.isFachgruppenvollversammlung
def DEFAULT_GRAV_PATH(self):
return os.path.join(GIT_REPO_NAME, "pages", "fachrat", "02.protokolle", str(self.semester.year)[2:] + self.semester.part, self.date.strftime("%Y-%m-%d")+"-fgvv"*self.isFachgruppenvollversammlung, "default.de.md")
return os.path.join(GIT_REPO_PATH, GRAV_PROTOCOL_PATH,
self.semester._gravName(),
self.date.strftime("%Y-%m-%d") + "-fgvv" * self.isFachgruppenvollversammlung,
"default.de.md")
def parseTops(self):
# TODO: better top filter?
lines = self.source.retrieveContent().split("\n")
# with open(self.rawPath, "r", encoding="utf-8") as f:
# lines = f.read().split("\n")
tops = []
for l in lines:
# Change to regex?
# import re
# res = re.match("^## ([\w\d &!\"'§$%/\-+äöüß]+)\w*(\(\d\d:\d\d Uhr\))?", l)
# if res is not None:
# top = res.group(1)
if l.startswith("## "):
top = l.strip("#").rsplit("(")[0].strip()
if any(top in t or t in top for t in IGNORED_TOPS):
continue
tops.append(top)
return tops
def sendMailAsUnapproved(self) -> bool:
sender = MailParticipant(LDAP_MAIL, LDAP_NAME)
......@@ -336,62 +366,55 @@ class ProtocolPad(BasePad):
pass
def uploadToGrav(self):
# Init semester
# TODO: better file management
self.semester.uploadToGrav()
if not os.path.exists(self.DEFAULT_RAW_PATH()):
raise FileNotFoundError(f"{self.DEFAULT_RAW_PATH()} doesn't exist")
self.rawPath = self.DEFAULT_RAW_PATH()
lines_new = []
# TODO: move conversion to another moethod?
if not os.path.exists(self.rawPath):
raise FileNotFoundError(f"{self.rawPath} doesn't exist")
# TODO: move conversion to another method?
with open(self.rawPath, "r", encoding="utf-8") as f:
lines = f.read().split("\n")
tops = []
# TODO: better top filter?
for l in lines:
if l.startswith("## "):
l = l[3:]
if "(" in l:
l = l[:l.index("(")]
l = l.strip()
if any(l in t or t in l for t in IGNORED_TOPS):
continue
tops.append(l)
header = ""
tops_text = ", ".join(tops)
if self.isFachgruppenvollversammlung:
header = ("---\n"
f"title: Protokoll der Fachgruppenvollversammlung am {self.date.strftime('%d.%m.%Y')}\n"
f"date: {self.date.strftime('%d.%m.%Y')}\n"
f"tops: {tops_text}\n"
"---\n\n"
"[MINITOC]\n\n")
else:
header = ("---\n"
f"title: Protokoll des {self.gremium.fullName} am {self.date.strftime('%d.%m.%Y')}\n"
f"date: {self.date.strftime('%d.%m.%Y')}\n"
f"tops: {tops_text}\n"
"---\n\n"
"[MINITOC]\n\n")
lines_new.append(header)
ignore = False
for l in lines:
if l.startswith("######"):
continue
if l == "---":
ignore = True
continue
if l == "...":
ignore = False
continue
if ignore:
continue
lines_new.append(l)
# Tops
tops = self.parseTops()
tops_text = ", ".join(tops)
# Header
if self.isFachgruppenvollversammlung:
name = "der Fachgruppenvollversammlung"
else:
name = f"des {self.gremium.fullName}"
header = ("---\n"
f"title: Protokoll {name} am {self.date.strftime('%d.%m.%Y')}\n"
f"date: {self.date.strftime('%d.%m.%Y')}\n"
f"tops: {tops_text}\n"
"---\n\n"
"[MINITOC]\n\n")
# Lines
lines_new = [header]
ignore = False
for l in lines:
if l.startswith("######"): # tags 'fr'
continue
if l == "---":
ignore = True
continue
if l == "...":
ignore = False
continue
if ignore:
continue
lines_new.append(l)
# Upload
os.makedirs(str(Path(self.DEFAULT_GRAV_PATH()).parent), exist_ok=True)
with open(self.DEFAULT_GRAV_PATH(), "w", encoding="utf-8") as f:
f.write("\n".join(lines_new))
GIT_HELPER.add("pages/")
GIT_HELPER.commit(f"Added protocol {self.DEFAULT_DISPLAY_NAME()}")
GIT_HELPER.push()
git.add(GRAV_PROTOCOL_PATH)
git.commit(f"Added protocol {self.displayName}")
git.push()
class AttachementPad(BasePad):
......@@ -426,11 +449,11 @@ class PadCollection(BasePad):
continue
if currentFolder not in pads:
pads[currentFolder] = list()
if pad.date != None:
semTuple = Semester.getSemesterTuple(pad.date)
if semTuple not in semesters:
semesters[semTuple] = Semester(semTuple[0], semTuple[1])
pad.semester = semesters[semTuple]
if isinstance(pad, ProtocolPad) and pad.date is not None:
semester = Semester.fromDate(pad.date)
if semester not in semesters:
semesters[semester] = semester
pad.semester = semester
pad.folder = currentFolder
pads[currentFolder].append(pad)
......@@ -478,12 +501,12 @@ class PadCollection(BasePad):
def initGit():
global GIT_HELPER
if GIT_REPO == None or GIT_REPO_NAME == None or GIT_EMAIL == None or GIT_NAME == None:
global git
if any(o is None for o in [GIT_REPO, GIT_REPO_PATH, GIT_EMAIL, GIT_NAME]):
raise RuntimeError("Git is not configured correctly")
GIT_HELPER = GitHelper(GIT_REPO, GIT_REPO_NAME)
GIT_HELPER.config(GIT_EMAIL, GIT_NAME)
GIT_HELPER.update()
git = GitHelper(GIT_REPO, GIT_REPO_PATH)
git.config(GIT_EMAIL, GIT_NAME)
git.update()
if __name__ == '__main__':
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment