Skip to content

Commit

Permalink
Clean up updater code (#152)
Browse files Browse the repository at this point in the history
* Clean up updater code

* Remove testing

* Run isort

* Run black
  • Loading branch information
Pbatch authored Jun 19, 2024
1 parent e235ba8 commit 3c9d83f
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 86 deletions.
82 changes: 0 additions & 82 deletions clashroyalebuildabot/state/updater.py

This file was deleted.

100 changes: 100 additions & 0 deletions clashroyalebuildabot/updater.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
import os
import shutil
import subprocess
import zipfile

from loguru import logger
import requests


class Updater:
GITHUB_REPO = "Pbatch/ClashRoyaleBuildABot"
DOWNLOAD_PATH = "update.zip"
EXTRACT_PATH = "."

@staticmethod
def _get_current_sha():
result = subprocess.run(
["git", "rev-parse", "HEAD"],
capture_output=True,
text=True,
check=True,
)
sha = result.stdout.strip()
return sha

def _get_latest_sha(self):
url = f"https://api.github.com/repos/{self.GITHUB_REPO}/commits/main"
response = requests.get(url, timeout=300)
response.raise_for_status()
sha = response.json()["sha"]
return sha

def _download_update(self, commit_sha):
url = f"https://github.com/{self.GITHUB_REPO}/archive/{commit_sha}.zip"
response = requests.get(url, timeout=300)
response.raise_for_status()
with open(self.DOWNLOAD_PATH, "wb") as file:
file.write(response.content)

def _extract_update(self):
with zipfile.ZipFile(self.DOWNLOAD_PATH, "r") as zip_ref:
zip_ref.extractall(self.EXTRACT_PATH)

def _replace_old_version(self, commit_sha):
new_folder_name = (
f"{self.GITHUB_REPO.rsplit('/', maxsplit=1)[-1]}-{commit_sha}"
)
new_folder_path = os.path.join(self.EXTRACT_PATH, new_folder_name)

if not os.path.exists(new_folder_path):
return

logger.info(
f"Replacing old version with new version: {new_folder_name}"
)
for item in os.listdir(self.EXTRACT_PATH):
item_path = os.path.join(self.EXTRACT_PATH, item)
if item in {new_folder_name, "bot.log", ".git"}:
continue

if os.path.isdir(item_path):
shutil.rmtree(item_path)
else:
os.remove(item_path)

for item in os.listdir(new_folder_path):
shutil.move(os.path.join(new_folder_path, item), self.EXTRACT_PATH)

shutil.rmtree(new_folder_path)

def check_for_update(self):
logger.info("Checking for updates...")

current_sha = self._get_current_sha()
logger.info(f"Current commit SHA: {current_sha}")

latest_sha = self._get_latest_sha()
logger.info(f"Latest commit SHA: {latest_sha}")

if current_sha == latest_sha:
logger.info("You are already using the latest version.")
return

user_input = input(
"A new update is available. Do you want to update? (Y/N): "
)
if user_input.lower() == "y":
logger.info("Downloading update...")
self._download_update(latest_sha)

logger.info(f"Extracting update from {self.DOWNLOAD_PATH}...")
self._extract_update()

logger.info("Replacing old version with new version...")
self._replace_old_version(latest_sha)
if os.path.exists(self.DOWNLOAD_PATH):
os.remove(self.DOWNLOAD_PATH)
logger.info("Update successful!")
else:
logger.info("Update cancelled.")
14 changes: 10 additions & 4 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,16 @@
import sys
import threading
import time

from loguru import logger

from clashroyalebuildabot.bot.example.custom_bot import CustomBot
from clashroyalebuildabot.namespaces.cards import Cards
from clashroyalebuildabot.state.updater import check_for_update
from loguru import logger
from clashroyalebuildabot.updater import Updater

start_time = datetime.now()


def update_terminal_title():
while True:
elapsed_time = datetime.now() - start_time
Expand All @@ -19,8 +22,10 @@ def update_terminal_title():
sys.stdout.flush()
time.sleep(1)


def main():
check_for_update()
updater = Updater()
updater.check_for_update()
cards = [
Cards.MINIONS,
Cards.ARCHERS,
Expand All @@ -34,8 +39,9 @@ def main():
bot = CustomBot(cards, debug=False)
bot.run()


if __name__ == "__main__":
logger.add("bot.log", rotation="500 MB") # Fügt die Logdatei hinzu
logger.add("bot.log", rotation="500 MB")
title_thread = threading.Thread(target=update_terminal_title, daemon=True)
title_thread.start()
main()

0 comments on commit 3c9d83f

Please sign in to comment.