jarvis-bot/run.py

111 lines
2.8 KiB
Python

#!/bin/python3
import jarvis
import git
from pathlib import Path
from multiprocessing import Value, Process, freeze_support
from importlib import reload as ireload
from time import sleep
def run():
ctx = None
while True:
ireload(jarvis)
ctx = jarvis.run(ctx)
def restart():
global jarvis_process
Path(get_pid_file()).unlink()
jarvis_process.terminate()
jarvis_process = Process(target=run, name="jarvis")
jarvis_process.start()
def update():
repo = git.Repo(".")
dirty = repo.is_dirty()
if dirty:
print(" Local system has uncommitted changes.")
current_hash = repo.head.object.hexsha
origin = repo.remotes.origin
origin.fetch()
if current_hash != origin.refs["main"].object.hexsha:
if dirty:
return 2
origin.pull()
return 0
return 1
def get_pid_file():
return f"jarvis.{get_pid()}.pid"
def get_pid():
global jarvis_process
return jarvis_process.pid
def cli():
pfile = Path(get_pid_file())
while not pfile.exists():
sleep(0.2)
print(
"""
All systems online.
Command List:
(R)eload
(U)pdate
(Q)uit
"""
)
while True:
cmd = input("> ")
if cmd.lower() in ["q", "quit", "e", "exit"]:
print(" Shutting down core systems...")
pfile.unlink()
break
if cmd.lower() in ["u", "update"]:
print(" Updating core systems...")
status = update()
if status == 0:
restart()
pfile = Path(get_pid_file())
while not pfile.exists():
sleep(0.2)
print(" Core systems successfully updated.")
elif status == 1:
print(" No core updates available.")
elif status == 2:
print(" Core system update available, but core is dirty.")
if cmd.lower() in ["r", "reload"]:
print(" Reloading core systems...")
restart()
pfile = Path(get_pid_file())
while not pfile.exists():
sleep(0.2)
print(" All systems reloaded.")
if __name__ == "__main__":
freeze_support()
pid_file = Value("i", 0)
jarvis_process = Process(target=run, name="jarvis")
print("J.A.R.V.I.S. initializing....")
print(" Updating core systems...")
status = update()
if status == 0:
print(" Core systems successfully updated")
elif status == 1:
print(" No core updates available.")
elif status == 2:
print(" Core updates available, but not applied.")
print(" Starting core systems...")
jarvis_process.start()
cli()
if jarvis_process.is_alive():
jarvis_process.terminate()
jarvis_process.join(30)
print("All systems shut down.")