From ec21ff68e3eb53cdbf7e52811466f1d1967b7eae Mon Sep 17 00:00:00 2001
From: xiaji
+ + 代码最后更新:{% git_last_commit_time %} +
diff --git a/core/templatetags/__init__.py b/core/templatetags/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/templatetags/git_info.py b/core/templatetags/git_info.py new file mode 100644 index 0000000..7efe002 --- /dev/null +++ b/core/templatetags/git_info.py @@ -0,0 +1,54 @@ +import subprocess +from django import template +from loguru import logger + +register = template.Library() + + +@register.simple_tag +def git_last_commit_time(): + """ + 获取 Git 最后提交时间 + 返回格式:YYYY-MM-DD HH:MM:SS + """ + try: + result = subprocess.run( + ['git', 'log', '-1', '--format="%cd"', '--date=format:"%Y-%m-%d %H:%M:%S"'], + capture_output=True, + text=True, + check=True, + cwd='.', # 在项目根目录执行 + shell=True # Windows 下需要 shell=True 来正确处理引号 + ) + commit_time = result.stdout.strip().strip('"') # 去除可能的引号 + logger.debug(f"获取Git最后提交时间: {commit_time}") + return commit_time + except subprocess.CalledProcessError as e: + logger.error(f"获取Git提交时间失败: {e}") + return "未知" + except FileNotFoundError: + logger.error("Git命令未找到") + return "未知" + except Exception as e: + logger.error(f"获取Git提交时间时发生错误: {e}") + return "未知" + + +@register.simple_tag +def git_last_commit_hash(): + """ + 获取 Git 最后提交的短哈希值 + """ + try: + result = subprocess.run( + ['git', 'log', '-1', '--format=%h'], + capture_output=True, + text=True, + check=True, + cwd='.' + ) + commit_hash = result.stdout.strip() + return commit_hash + except Exception as e: + logger.error(f"获取Git提交哈希失败: {e}") + return "unknown"