diff --git a/dev-services.py b/dev-services.py index 870b68e..aed1840 100644 --- a/dev-services.py +++ b/dev-services.py @@ -67,6 +67,14 @@ DEFAULT_PORTS = { "spring-boot-gradle": 8080, } +# 前端/H5 服务固定端口映射(按项目目录名匹配) +FIXED_FRONTEND_PORTS = { + "web": 5178, + "web-admin": 5179, + "mini-program": 5180, + "life-script": 5181, +} + # ANSI 颜色 COLORS = { "INFO": "\033[37m", @@ -328,33 +336,69 @@ def _update_service_port(svc: Service, port: int): svc.health_url = re.sub(r":\d+", f":{port}", svc.health_url, count=1) updated = [] skip_next = False + has_port_arg = False for index, part in enumerate(svc.start_cmd): if skip_next: skip_next = False continue - if part == "--port" and index + 1 < len(svc.start_cmd): - updated.extend([part, str(port)]) - skip_next = True + if part == "--port": + has_port_arg = True + if index + 1 < len(svc.start_cmd): + updated.extend([part, str(port)]) + skip_next = True elif part.startswith("--port="): + has_port_arg = True updated.append(f"--port={port}") elif f"--server.port={old_port}" in part: updated.append(part.replace(f"--server.port={old_port}", f"--server.port={port}")) else: updated.append(part) + + # 前端框架如果没有 --port 参数,追加 --port + if not has_port_arg and svc.project_type in {"vite", "uniapp", "taro", "next"}: + updated.extend(["--port", str(port)]) + svc.start_cmd = updated def assign_unique_ports(services: list[Service]) -> list[Service]: - reserved = {svc.port for svc in services if _service_has_explicit_port(svc)} - used = set() + # 按目录名匹配固定前端端口 + dir_name_to_service = {} + for svc in services: + dir_name = svc.project_dir.name + if dir_name in FIXED_FRONTEND_PORTS: + dir_name_to_service[dir_name] = svc + + # 先为固定前端服务分配端口 + for dir_name, svc in dir_name_to_service.items(): + fixed_port = FIXED_FRONTEND_PORTS[dir_name] + if svc.port != fixed_port: + log(f"{svc.name} 使用固定前端端口 {fixed_port}", "INFO") + _update_service_port(svc, fixed_port) + + # 检查端口冲突 + used_ports = {} for svc in services: port = svc.port - if port in used or (port in reserved and not _service_has_explicit_port(svc)): - while port in used or port in reserved: + if port in used_ports: + other = used_ports[port] + log(f"端口冲突: {svc.name} ({port}) 与 {other.name} ({port}) 冲突", "ERROR") + sys.exit(1) + used_ports[port] = svc + + # 非固定前端服务按原有逻辑处理冲突 + for svc in services: + dir_name = svc.project_dir.name + if dir_name in FIXED_FRONTEND_PORTS: + continue + + port = svc.port + if port in used_ports and used_ports[port] is not svc: + while port in used_ports: port += 1 log(f"{svc.name} 端口 {svc.port} 与其他服务冲突,自动调整为 {port}", "WARN") _update_service_port(svc, port) - used.add(svc.port) + return services