home · contact · privacy
Fix minor ProcessStep POST handling bugs.
[plomtask] / run.py
diff --git a/run.py b/run.py
index ef6aeab6b7fd56a93ed3c9e76a7b5bbfe532b68c..c69dc6ab061c522c75ee2d1420df0fdc44a2f1e1 100755 (executable)
--- a/run.py
+++ b/run.py
@@ -2,31 +2,37 @@
 """Call this to start the application."""
 from sys import exit as sys_exit
 from os import environ
-from plomtask.misc import HandledException
+from plomtask.exceptions import HandledException, NotFoundException
 from plomtask.http import TaskHandler, TaskServer
-from plomtask.db import DatabaseFile
+from plomtask.db import DatabaseFile, UnmigratedDbException
 
-PATH_DB = environ.get('PATH_DB')
+PLOMTASK_DB_PATH = environ.get('PLOMTASK_DB_PATH')
 HTTP_PORT = 8082
-TEMPLATES_DIR = 'templates'
 DB_CREATION_ASK = 'Database file not found. Create? Y/n\n'
+DB_MIGRATE_ASK = 'Database file needs migration. Migrate? Y/n\n'
+
+
+def yes_or_fail(question: str, fail_msg: str) -> None:
+    """Ask question, raise HandledException(fail_msg) if reply not yes."""
+    reply = input(question)
+    if not reply.lower() in {'y', 'yes', 'yes.', 'yes!'}:
+        print('Not recognizing reply as "yes".')
+        raise HandledException(fail_msg)
 
 
 if __name__ == '__main__':
     try:
-        if not PATH_DB:
-            raise HandledException('PATH_DB not set.')
-        db_file = DatabaseFile(PATH_DB)
-        if not db_file.exists:
-            legal_yesses = {'y', 'yes', 'yes.', 'yes!'}
-            reply = input(DB_CREATION_ASK)
-            if reply.lower() in legal_yesses:
-                db_file.remake()
-            else:
-                print('Not recognizing reply as "yes".')
-                raise HandledException('Cannot run without database.')
-        server = TaskServer(TEMPLATES_DIR, db_file,
-                            ('localhost', HTTP_PORT), TaskHandler)
+        if not PLOMTASK_DB_PATH:
+            raise HandledException('PLOMTASK_DB_PATH not set.')
+        try:
+            db_file = DatabaseFile(PLOMTASK_DB_PATH)
+        except NotFoundException:
+            yes_or_fail(DB_CREATION_ASK, 'Cannot run without DB.')
+            db_file = DatabaseFile.create_at(PLOMTASK_DB_PATH)
+        except UnmigratedDbException:
+            yes_or_fail(DB_MIGRATE_ASK, 'Cannot run with unmigrated DB.')
+            db_file = DatabaseFile.migrate(PLOMTASK_DB_PATH)
+        server = TaskServer(db_file, ('localhost', HTTP_PORT), TaskHandler)
         print(f'running at port {HTTP_PORT}')
         try:
             server.serve_forever()