feat: dev-services.py restart 命令新增热加载保护

- 无必须重启的变更时禁止 restart
- 支持 --force 参数强制重启
- 避免无意义重启前端热加载服务
This commit is contained in:
2026-06-28 10:34:54 +08:00
parent 4dc3d4cfdc
commit 75de32828a
+60
View File
@@ -75,6 +75,17 @@ FIXED_FRONTEND_PORTS = {
"life-script": 5181,
}
# 必须重启才能生效的文件模式
RESTART_REQUIRED_PATTERNS = [
re.compile(r'vite\.config\.(ts|js|mjs|cjs)$'),
re.compile(r'tsconfig\.json$'),
re.compile(r'\.env(\.[^/]*)?$'),
re.compile(r'package\.json$'),
re.compile(r'application.*\.ya?ml$'),
re.compile(r'pom\.xml$'),
re.compile(r'build\.gradle(\.kts)?$'),
]
# ANSI 颜色
COLORS = {
"INFO": "\033[37m",
@@ -402,6 +413,37 @@ def assign_unique_ports(services: list[Service]) -> list[Service]:
return services
def _should_restart_for_changes(service_dir: Path) -> tuple[bool, list[str]]:
"""
检查指定服务目录下是否有必须重启才能生效的变更。
返回: (是否需要重启, 已修改文件列表)
"""
try:
result = subprocess.run(
["git", "diff", "--name-only", "--", str(service_dir)],
capture_output=True,
text=True,
cwd=SCRIPT_DIR,
check=True,
)
changed_files = [line.strip() for line in result.stdout.splitlines() if line.strip()]
except subprocess.CalledProcessError:
# 非 git 仓库或 git 命令失败,默认允许重启
return True, []
except FileNotFoundError:
return True, []
if not changed_files:
return False, []
for file_path in changed_files:
for pattern in RESTART_REQUIRED_PATTERNS:
if pattern.search(file_path):
return True, changed_files
return False, changed_files
def _extract_port_from_pom(pom_path: Path) -> Optional[int]:
"""从 pom.xml 提取 server.port"""
try:
@@ -1597,6 +1639,7 @@ def main():
parser.add_argument("--type", dest="svc_type", default=None, help="服务类型过滤: vite|python|spring-boot|node-backend")
parser.add_argument("--port", dest="port", type=int, default=None, help="端口号过滤")
parser.add_argument("--foreground", "-f", action="store_true", help="前台模式运行")
parser.add_argument("--force", action="store_true", help="强制重启,忽略热加载保护")
args = parser.parse_args()
@@ -1675,6 +1718,23 @@ def main():
return
if args.action == "restart":
if not args.force:
blocked = []
for svc in services:
should_restart, changed_files = _should_restart_for_changes(svc.project_dir)
if not should_restart:
blocked.append((svc.name, changed_files))
if blocked:
log("检测到以下服务无需重启(当前修改支持热加载):", "WARN")
for name, files in blocked:
if files:
log(f" - {name}: 修改文件 {', '.join(files)}", "WARN")
else:
log(f" - {name}: 未检测到代码变更", "WARN")
log("如需强制重启,请使用: python dev-services.py restart --force", "WARN")
sys.exit(0)
for svc in services:
restart_service(svc)
else: