make get_git_commit_number work under systemd

This commit is contained in:
Vladless
2025-06-14 06:30:09 +03:00
parent 902a051dc1
commit 40ccd8060a
+35 -13
View File
@@ -1,4 +1,5 @@
import traceback
import os
from aiogram import Bot, Dispatcher
from aiogram.client.default import DefaultBotProperties
@@ -21,23 +22,43 @@ dp = Dispatcher(bot=bot, storage=storage)
def get_git_commit_number() -> str:
repo_url = "https://github.com/Vladless/Solo_bot"
cwd = os.path.abspath(os.path.dirname(__file__))
if not os.path.isdir(os.path.join(cwd, ".git")):
cwd = "/root/Prod/Solo_bot"
env = os.environ.copy()
env["GIT_DIR"] = os.path.join(cwd, ".git")
env["GIT_WORK_TREE"] = cwd
try:
local_number = subprocess.check_output(
["git", "rev-list", "--count", "HEAD"]
["git", "rev-list", "--count", "HEAD"],
cwd=cwd,
env=env
).decode().strip()
local_hash = subprocess.check_output(
["git", "rev-parse", "HEAD"]
["git", "rev-parse", "HEAD"],
cwd=cwd,
env=env
).decode().strip()
try:
branch = subprocess.check_output(
["git", "rev-parse", "--abbrev-ref", "HEAD"]
["git", "rev-parse", "--abbrev-ref", "HEAD"],
cwd=cwd,
env=env
).decode().strip()
if branch == "HEAD":
describe = subprocess.check_output(["git", "describe", "--tags", "--exact-match"], stderr=subprocess.DEVNULL).decode().strip()
describe = subprocess.check_output(
["git", "describe", "--tags", "--exact-match"],
cwd=cwd,
env=env,
stderr=subprocess.DEVNULL
).decode().strip()
if describe.startswith("v") or "release" in describe.lower():
branch = "main"
else:
@@ -45,17 +66,21 @@ def get_git_commit_number() -> str:
except Exception:
branch = "dev"
except Exception:
return "\n(Требуется обновление через CLI)"
except Exception as e:
return f"\n(Требуется обновление через CLI: {e})"
try:
remote_commit = subprocess.check_output(
["git", "ls-remote", "origin", f"refs/heads/{branch}"]
["git", "ls-remote", "origin", f"refs/heads/{branch}"],
cwd=cwd,
env=env
).decode()
remote_hash = remote_commit.split()[0]
remote_number = subprocess.check_output(
["git", "rev-list", "--count", remote_hash]
["git", "rev-list", "--count", remote_hash],
cwd=cwd,
env=env
).decode().strip()
if local_hash == remote_hash:
@@ -68,10 +93,7 @@ def get_git_commit_number() -> str:
)
except Exception:
return (
f"\n(commit <a href=\"{repo_url}/commit/{local_hash}\">"
f"#{local_number}</a> / actual commit unknown)"
)
return ""
version = f"v4.4-b140642{get_git_commit_number()}"
@@ -181,4 +203,4 @@ async def errors_handler(event: ErrorEvent, bot: Bot) -> bool:
except Exception as exception:
logger.error(f"Неожиданная ошибка в error handler: {exception}")
return True
return True