修改说明
This commit is contained in:
199
version.py
Normal file
199
version.py
Normal file
@@ -0,0 +1,199 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
TSP智能助手版本管理模块
|
||||
"""
|
||||
|
||||
import os
|
||||
import json
|
||||
import subprocess
|
||||
from datetime import datetime
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
class VersionManager:
|
||||
"""版本管理器"""
|
||||
|
||||
def __init__(self, version_file: str = "version.json"):
|
||||
self.version_file = version_file
|
||||
self.version_info = self._load_version()
|
||||
|
||||
def _load_version(self) -> Dict:
|
||||
"""加载版本信息"""
|
||||
if os.path.exists(self.version_file):
|
||||
try:
|
||||
with open(self.version_file, 'r', encoding='utf-8') as f:
|
||||
return json.load(f)
|
||||
except Exception as e:
|
||||
print(f"加载版本文件失败: {e}")
|
||||
|
||||
# 默认版本信息
|
||||
return {
|
||||
"version": "1.0.0",
|
||||
"build_number": 1,
|
||||
"release_date": datetime.now().isoformat(),
|
||||
"git_commit": self._get_git_commit(),
|
||||
"deployment_status": "development",
|
||||
"changelog": [],
|
||||
"dependencies": self._get_dependencies()
|
||||
}
|
||||
|
||||
def _get_git_commit(self) -> str:
|
||||
"""获取Git提交哈希"""
|
||||
try:
|
||||
result = subprocess.run(['git', 'rev-parse', 'HEAD'],
|
||||
capture_output=True, text=True)
|
||||
return result.stdout.strip()[:8] if result.returncode == 0 else "unknown"
|
||||
except:
|
||||
return "unknown"
|
||||
|
||||
def _get_dependencies(self) -> Dict:
|
||||
"""获取依赖包信息"""
|
||||
try:
|
||||
result = subprocess.run(['pip', 'freeze'],
|
||||
capture_output=True, text=True)
|
||||
if result.returncode == 0:
|
||||
deps = {}
|
||||
for line in result.stdout.strip().split('\n'):
|
||||
if '==' in line:
|
||||
name, version = line.split('==', 1)
|
||||
deps[name] = version
|
||||
return deps
|
||||
except:
|
||||
pass
|
||||
return {}
|
||||
|
||||
def get_version(self) -> str:
|
||||
"""获取当前版本号"""
|
||||
return self.version_info["version"]
|
||||
|
||||
def get_build_number(self) -> int:
|
||||
"""获取构建号"""
|
||||
return self.version_info["build_number"]
|
||||
|
||||
def increment_version(self, version_type: str = "patch") -> str:
|
||||
"""增加版本号"""
|
||||
current_version = self.version_info["version"]
|
||||
major, minor, patch = map(int, current_version.split('.'))
|
||||
|
||||
if version_type == "major":
|
||||
major += 1
|
||||
minor = 0
|
||||
patch = 0
|
||||
elif version_type == "minor":
|
||||
minor += 1
|
||||
patch = 0
|
||||
else: # patch
|
||||
patch += 1
|
||||
|
||||
new_version = f"{major}.{minor}.{patch}"
|
||||
self.version_info["version"] = new_version
|
||||
self.version_info["build_number"] += 1
|
||||
self.version_info["release_date"] = datetime.now().isoformat()
|
||||
self.version_info["git_commit"] = self._get_git_commit()
|
||||
self.version_info["dependencies"] = self._get_dependencies()
|
||||
|
||||
self._save_version()
|
||||
return new_version
|
||||
|
||||
def add_changelog_entry(self, entry: str, version: str = None):
|
||||
"""添加变更日志条目"""
|
||||
if version is None:
|
||||
version = self.get_version()
|
||||
|
||||
changelog_entry = {
|
||||
"version": version,
|
||||
"date": datetime.now().isoformat(),
|
||||
"description": entry
|
||||
}
|
||||
|
||||
self.version_info["changelog"].insert(0, changelog_entry)
|
||||
self._save_version()
|
||||
|
||||
def set_deployment_status(self, status: str):
|
||||
"""设置部署状态"""
|
||||
valid_statuses = ["development", "staging", "production", "maintenance"]
|
||||
if status in valid_statuses:
|
||||
self.version_info["deployment_status"] = status
|
||||
self._save_version()
|
||||
else:
|
||||
raise ValueError(f"无效的部署状态: {status}")
|
||||
|
||||
def _save_version(self):
|
||||
"""保存版本信息"""
|
||||
try:
|
||||
with open(self.version_file, 'w', encoding='utf-8') as f:
|
||||
json.dump(self.version_info, f, indent=2, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
print(f"保存版本文件失败: {e}")
|
||||
|
||||
def get_version_info(self) -> Dict:
|
||||
"""获取完整版本信息"""
|
||||
return self.version_info.copy()
|
||||
|
||||
def create_release_tag(self, tag_message: str = None):
|
||||
"""创建Git标签"""
|
||||
version = self.get_version()
|
||||
tag_name = f"v{version}"
|
||||
|
||||
if tag_message is None:
|
||||
tag_message = f"Release version {version}"
|
||||
|
||||
try:
|
||||
# 创建标签
|
||||
subprocess.run(['git', 'tag', '-a', tag_name, '-m', tag_message],
|
||||
check=True)
|
||||
print(f"已创建标签: {tag_name}")
|
||||
return tag_name
|
||||
except subprocess.CalledProcessError as e:
|
||||
print(f"创建标签失败: {e}")
|
||||
return None
|
||||
|
||||
def main():
|
||||
"""命令行接口"""
|
||||
import argparse
|
||||
|
||||
parser = argparse.ArgumentParser(description='TSP智能助手版本管理')
|
||||
parser.add_argument('action', choices=['version', 'increment', 'status', 'changelog', 'tag'],
|
||||
help='要执行的操作')
|
||||
parser.add_argument('--type', choices=['major', 'minor', 'patch'],
|
||||
default='patch', help='版本类型')
|
||||
parser.add_argument('--status', choices=['development', 'staging', 'production', 'maintenance'],
|
||||
help='部署状态')
|
||||
parser.add_argument('--message', help='变更日志消息或标签消息')
|
||||
|
||||
args = parser.parse_args()
|
||||
|
||||
vm = VersionManager()
|
||||
|
||||
if args.action == 'version':
|
||||
print(f"当前版本: {vm.get_version()}")
|
||||
print(f"构建号: {vm.get_build_number()}")
|
||||
print(f"部署状态: {vm.version_info['deployment_status']}")
|
||||
|
||||
elif args.action == 'increment':
|
||||
new_version = vm.increment_version(args.type)
|
||||
print(f"版本已更新为: {new_version}")
|
||||
|
||||
elif args.action == 'status':
|
||||
if args.status:
|
||||
vm.set_deployment_status(args.status)
|
||||
print(f"部署状态已设置为: {args.status}")
|
||||
else:
|
||||
print(f"当前部署状态: {vm.version_info['deployment_status']}")
|
||||
|
||||
elif args.action == 'changelog':
|
||||
if args.message:
|
||||
vm.add_changelog_entry(args.message)
|
||||
print(f"已添加变更日志: {args.message}")
|
||||
else:
|
||||
print("变更日志:")
|
||||
for entry in vm.version_info['changelog'][:5]:
|
||||
print(f" {entry['version']} - {entry['description']}")
|
||||
|
||||
elif args.action == 'tag':
|
||||
tag_name = vm.create_release_tag(args.message)
|
||||
if tag_name:
|
||||
print(f"标签创建成功: {tag_name}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user