-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathtool_version_manager.py
More file actions
259 lines (204 loc) · 8.36 KB
/
Copy pathtool_version_manager.py
File metadata and controls
259 lines (204 loc) · 8.36 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
工具版本管理模块
负责工具本身的版本号管理,包括自动修改version.py文件版本号
"""
import os
import sys
import re
from lib_logger import logger
from typing import Optional, Tuple
from datetime import datetime
class ToolVersionManager:
"""工具版本管理器"""
def __init__(self):
"""初始化工具版本管理器"""
# 版本文件路径
if hasattr(sys, 'frozen') and sys.frozen:
# 如果是打包后的exe,使用exe所在目录
base_path = os.path.dirname(sys.executable)
else:
# 如果是开发环境,使用脚本所在目录
base_path = os.path.dirname(__file__)
self.version_file_path = os.path.join(base_path, 'version.py')
# 版本号模式 - 支持数量不定的空格和注释
self.version_pattern = r'VERSION\s*=\s*["\']([^"\']+)["\'](?:\s*#.*)?'
self.version_format = 'VERSION = "{}"'
logger.info(f"工具版本管理器初始化,版本文件路径: {self.version_file_path}")
def get_current_version(self) -> str:
"""
获取当前工具版本号
Returns:
str: 当前版本号
"""
try:
if not os.path.exists(self.version_file_path):
logger.error(f"版本文件不存在: {self.version_file_path}")
return "1.0.0.0"
with open(self.version_file_path, 'r', encoding='utf-8') as f:
content = f.read()
match = re.search(self.version_pattern, content)
if match:
version = match.group(1)
logger.info(f"当前版本号: {version}")
return version
else:
logger.error("版本文件中未找到版本号")
return "1.0.0.0"
except Exception as e:
logger.error(f"读取版本号失败: {e}")
return "1.0.0.0"
def increment_version(self, increment_type: str = 'build') -> str:
"""
递增版本号
每位范围为 0-9,末位加一后超限则向高位进位。
例如: 1.0.0.9 -> 1.0.1.0,而不是 1.0.0.10
Args:
increment_type: 递增类型 ('major', 'minor', 'patch', 'build')
Returns:
str: 新的版本号
"""
current_version = self.get_current_version()
version_parts = self.parse_version(current_version)
if not version_parts:
logger.error(f"版本号格式错误: {current_version}")
return current_version
try:
major, minor, patch, build = version_parts
if increment_type == 'major':
major += 1
minor = 0
patch = 0
build = 0
elif increment_type == 'minor':
minor += 1
patch = 0
build = 0
elif increment_type == 'patch':
patch += 1
build = 0
elif increment_type == 'build':
build += 1
else:
logger.error(f"无效的递增类型: {increment_type}")
return current_version
# 每位 0-9,超限进位(与 increment_version_advanced 一致)
major, minor, patch, build = self._apply_digit_carry(major, minor, patch, build)
new_version = self.format_version(major, minor, patch, build)
logger.info(f"版本号递增: {current_version} -> {new_version}")
return new_version
except ValueError as e:
logger.error(f"版本号解析失败: {e}")
return current_version
def _apply_digit_carry(self, major: int, minor: int, revision: int, build: int) -> Tuple[int, int, int, int]:
"""
对版本号各位做 0-9 进位归一化
Args:
major, minor, revision, build: 版本号各部分
Returns:
tuple: 进位归一化后的版本号
"""
if build > 9:
build = 0
revision += 1
if revision > 9:
revision = 0
minor += 1
if minor > 9:
minor = 0
major += 1
if major > 9:
logger.warning("版本号已达上限,保持 9.9.9.9")
return 9, 9, 9, 9
return major, minor, revision, build
def update_version(self, new_version: str) -> bool:
"""
更新版本号到文件
Args:
new_version: 新的版本号
Returns:
bool: 是否更新成功
"""
try:
if not os.path.exists(self.version_file_path):
logger.error(f"版本文件不存在: {self.version_file_path}")
return False
with open(self.version_file_path, 'r', encoding='utf-8') as f:
content = f.read()
# 替换版本号
new_content = re.sub(self.version_pattern, self.version_format.format(new_version), content)
if new_content == content:
logger.error("版本号替换失败,可能格式不匹配")
return False
with open(self.version_file_path, 'w', encoding='utf-8') as f:
f.write(new_content)
logger.info(f"版本号更新成功: {new_version}")
return True
except Exception as e:
logger.error(f"更新版本号失败: {e}")
return False
def get_version_info(self) -> dict:
"""
获取版本信息
Returns:
dict: 版本信息字典
"""
version = self.get_current_version()
return {
'version': version,
'timestamp': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'file_path': self.version_file_path
}
def auto_increment_and_update(self, increment_type: str = 'build') -> Tuple[bool, str]:
"""
自动递增版本号并更新文件
Args:
increment_type: 递增类型,默认 'build'(末位加一并进位)
Returns:
Tuple[bool, str]: (是否成功, 新版本号)
"""
new_version = self.increment_version(increment_type)
success = self.update_version(new_version)
return success, new_version
def parse_version(self, version_str: str) -> Optional[Tuple[int, int, int, int]]:
"""
解析版本字符串
Args:
version_str: 版本字符串,格式如 "1.0.1.9"
Returns:
tuple: (major, minor, revision, build) 或 None
"""
pattern = r'(\d+)\.(\d+)\.(\d+)\.(\d+)'
match = re.match(pattern, version_str)
if match:
return tuple(int(x) for x in match.groups())
return None
def format_version(self, major: int, minor: int, revision: int, build: int) -> str:
"""
格式化版本号
Args:
major, minor, revision, build: 版本号各部分
Returns:
str: 格式化后的版本号
"""
return f"{major}.{minor}.{revision}.{build}"
def increment_version_advanced(self, major: int, minor: int, revision: int, build: int) -> Tuple[int, int, int, int]:
"""
高级版本号递增(支持进位)
每位限制在 0-9:1.0.0.9 -> 1.0.1.0
Args:
major, minor, revision, build: 当前版本号
Returns:
tuple: 递增后的版本号
"""
build += 1
return self._apply_digit_carry(major, minor, revision, build)
def increment_and_update_advanced(self) -> Tuple[bool, str]:
"""
高级版本号递增并更新文件(用于构建脚本)
等同于按 build 位递增并进位。
Returns:
Tuple[bool, str]: (是否成功, 新版本号)
"""
return self.auto_increment_and_update(increment_type='build')