Install project-compatible Node.js version
This commit is contained in:
@@ -6,6 +6,7 @@ AutoDeploy 是一个面向 Windows 的 Spring Boot / SSM + Vue 本地自动化
|
|||||||
|
|
||||||
- 自动识别 Maven/Gradle Spring Boot 后端、Maven/Gradle SSM WAR 后端、一个或多个 Vue/Vite 前端以及 `.sql` 文件。
|
- 自动识别 Maven/Gradle Spring Boot 后端、Maven/Gradle SSM WAR 后端、一个或多个 Vue/Vite 前端以及 `.sql` 文件。
|
||||||
- 从 Maven、Gradle 和 Spring Boot 配置中推断 Java 版本,推荐 JDK 8、11、17 或 21。
|
- 从 Maven、Gradle 和 Spring Boot 配置中推断 Java 版本,推荐 JDK 8、11、17 或 21。
|
||||||
|
- 从 `.nvmrc`、`.node-version`、`package.json` 的 `engines.node` 以及 Vite/Vue CLI 版本推断 Node.js 要求;从 Node.js 官方版本索引选择最新兼容版本,校验 SHA-256 后安装到当前用户目录。
|
||||||
- 检测 JDK、Maven、Tomcat、Gradle、Node.js、npm、Vue CLI、MySQL 和 Git。
|
- 检测 JDK、Maven、Tomcat、Gradle、Node.js、npm、Vue CLI、MySQL 和 Git。
|
||||||
- 支持手动指定工具路径,并可将工具目录写入当前用户的 `PATH`;JDK、Maven、Tomcat 和 Gradle 会同步设置对应的环境变量。
|
- 支持手动指定工具路径,并可将工具目录写入当前用户的 `PATH`;JDK、Maven、Tomcat 和 Gradle 会同步设置对应的环境变量。
|
||||||
- Maven 和 Tomcat 从 Apache 官方地址下载并校验后安装到当前用户目录;MySQL 从 Oracle 官方归档下载安装包并校验 SHA-256,固定安装 8.0.43,默认将 root 密码设置为 `123456` 并永久允许 6 位弱密码。MySQL 分两阶段安装并等待 Server 安装任务的真实结果;已有 MySQL Installer 时直接复用。首次安装会显示 Windows Installer 进度窗口,详细日志保存在 `%LOCALAPPDATA%\AutoDeploy\logs\mysql-install.log`。JDK、Node.js 等环境通过 `winget` 接受软件源和包协议后无人值守安装,执行安装前会要求用户确认。
|
- Maven 和 Tomcat 从 Apache 官方地址下载并校验后安装到当前用户目录;MySQL 从 Oracle 官方归档下载安装包并校验 SHA-256,固定安装 8.0.43,默认将 root 密码设置为 `123456` 并永久允许 6 位弱密码。MySQL 分两阶段安装并等待 Server 安装任务的真实结果;已有 MySQL Installer 时直接复用。首次安装会显示 Windows Installer 进度窗口,详细日志保存在 `%LOCALAPPDATA%\AutoDeploy\logs\mysql-install.log`。JDK、Node.js 等环境通过 `winget` 接受软件源和包协议后无人值守安装,执行安装前会要求用户确认。
|
||||||
|
|||||||
@@ -62,11 +62,6 @@ def check_environment(
|
|||||||
results: list[EnvironmentCheck] = []
|
results: list[EnvironmentCheck] = []
|
||||||
|
|
||||||
for name, command in selected_checks.items():
|
for name, command in selected_checks.items():
|
||||||
path_result = _try_command(name, command, "PATH", command_runner)
|
|
||||||
if path_result.installed:
|
|
||||||
results.append(path_result)
|
|
||||||
continue
|
|
||||||
|
|
||||||
manual_path = configured_paths.get(name)
|
manual_path = configured_paths.get(name)
|
||||||
if manual_path and manual_path.exists():
|
if manual_path and manual_path.exists():
|
||||||
manual_command = [str(manual_path), *command[1:]]
|
manual_command = [str(manual_path), *command[1:]]
|
||||||
@@ -75,6 +70,11 @@ def check_environment(
|
|||||||
results.append(manual_result)
|
results.append(manual_result)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
|
path_result = _try_command(name, command, "PATH", command_runner)
|
||||||
|
if path_result.installed:
|
||||||
|
results.append(path_result)
|
||||||
|
continue
|
||||||
|
|
||||||
discovered = discover_executable(name, roots)
|
discovered = discover_executable(name, roots)
|
||||||
if discovered:
|
if discovered:
|
||||||
discovered_command = [str(discovered), *command[1:]]
|
discovered_command = [str(discovered), *command[1:]]
|
||||||
|
|||||||
@@ -16,8 +16,10 @@ from .installer import (
|
|||||||
build_install_command,
|
build_install_command,
|
||||||
install_maven,
|
install_maven,
|
||||||
install_mysql,
|
install_mysql,
|
||||||
|
install_node,
|
||||||
install_tomcat,
|
install_tomcat,
|
||||||
recommend_jdk_version,
|
recommend_jdk_version,
|
||||||
|
recommend_node_version,
|
||||||
run_install_command,
|
run_install_command,
|
||||||
)
|
)
|
||||||
from .path_manager import apply_user_environment, build_environment_update
|
from .path_manager import apply_user_environment, build_environment_update
|
||||||
@@ -62,6 +64,9 @@ class DeployWorkbench(tk.Tk):
|
|||||||
self.output_dir = tk.StringVar()
|
self.output_dir = tk.StringVar()
|
||||||
self.jdk_version = tk.StringVar(value="8")
|
self.jdk_version = tk.StringVar(value="8")
|
||||||
self.jdk_reason = tk.StringVar(value="默认推荐 JDK 8,扫描项目后会自动调整。")
|
self.jdk_reason = tk.StringVar(value="默认推荐 JDK 8,扫描项目后会自动调整。")
|
||||||
|
self.node_requirement = tk.StringVar(value="lts")
|
||||||
|
self.node_reason = tk.StringVar(value="默认安装 Node.js 最新 LTS,扫描项目后会自动调整。")
|
||||||
|
self.node_recommendation = recommend_node_version(None)
|
||||||
|
|
||||||
self.tool_paths = load_tool_paths()
|
self.tool_paths = load_tool_paths()
|
||||||
self.tool_path_vars: dict[str, tk.StringVar] = {
|
self.tool_path_vars: dict[str, tk.StringVar] = {
|
||||||
@@ -263,6 +268,10 @@ class DeployWorkbench(tk.Tk):
|
|||||||
ttk.Button(row, text="\u5b89\u88c5", command=lambda tool=name: self.install_tool_async(tool)).pack(side=tk.LEFT)
|
ttk.Button(row, text="\u5b89\u88c5", command=lambda tool=name: self.install_tool_async(tool)).pack(side=tk.LEFT)
|
||||||
ttk.Button(row, text="\u9009\u62e9\u8def\u5f84", command=lambda tool=name: self.choose_tool_path(tool)).pack(side=tk.LEFT, padx=(8, 0))
|
ttk.Button(row, text="\u9009\u62e9\u8def\u5f84", command=lambda tool=name: self.choose_tool_path(tool)).pack(side=tk.LEFT, padx=(8, 0))
|
||||||
ttk.Button(row, text="\u52a0\u5165 PATH", command=lambda tool=name: self.add_tool_to_path(tool)).pack(side=tk.LEFT, padx=(8, 0))
|
ttk.Button(row, text="\u52a0\u5165 PATH", command=lambda tool=name: self.add_tool_to_path(tool)).pack(side=tk.LEFT, padx=(8, 0))
|
||||||
|
if name == "Node.js":
|
||||||
|
ttk.Label(row, textvariable=self.node_reason, style="Muted.TLabel").pack(
|
||||||
|
side=tk.LEFT, fill=tk.X, expand=True, padx=(10, 0)
|
||||||
|
)
|
||||||
|
|
||||||
ttk.Separator(panel).pack(fill=tk.X, pady=14)
|
ttk.Separator(panel).pack(fill=tk.X, pady=14)
|
||||||
ttk.Button(panel, text="\u68c0\u6d4b\u73af\u5883", command=self.check_environment_async).pack(side=tk.LEFT)
|
ttk.Button(panel, text="\u68c0\u6d4b\u73af\u5883", command=self.check_environment_async).pack(side=tk.LEFT)
|
||||||
@@ -333,6 +342,7 @@ class DeployWorkbench(tk.Tk):
|
|||||||
self.mysql_database.set(database_name)
|
self.mysql_database.set(database_name)
|
||||||
self._append_log(f"已根据 SQL 文件自动填写数据库名: {database_name}")
|
self._append_log(f"已根据 SQL 文件自动填写数据库名: {database_name}")
|
||||||
self._apply_jdk_recommendation()
|
self._apply_jdk_recommendation()
|
||||||
|
self._apply_node_recommendation()
|
||||||
self._render_scan_result()
|
self._render_scan_result()
|
||||||
self._append_log("项目扫描完成。")
|
self._append_log("项目扫描完成。")
|
||||||
|
|
||||||
@@ -342,6 +352,12 @@ class DeployWorkbench(tk.Tk):
|
|||||||
self.jdk_reason.set(recommendation.reason)
|
self.jdk_reason.set(recommendation.reason)
|
||||||
self._append_log(f"JDK 推荐: {recommendation.reason}")
|
self._append_log(f"JDK 推荐: {recommendation.reason}")
|
||||||
|
|
||||||
|
def _apply_node_recommendation(self) -> None:
|
||||||
|
self.node_recommendation = recommend_node_version(self.scan_result)
|
||||||
|
self.node_requirement.set(self.node_recommendation.display_requirement)
|
||||||
|
self.node_reason.set(f"要求 {self.node_recommendation.display_requirement}")
|
||||||
|
self._append_log(f"Node.js 推荐: {self.node_recommendation.reason}")
|
||||||
|
|
||||||
def check_environment_async(self) -> None:
|
def check_environment_async(self) -> None:
|
||||||
self.save_tool_path_settings(silent=True)
|
self.save_tool_path_settings(silent=True)
|
||||||
manual_paths = load_tool_paths()
|
manual_paths = load_tool_paths()
|
||||||
@@ -375,6 +391,9 @@ class DeployWorkbench(tk.Tk):
|
|||||||
if tool_name == "MySQL":
|
if tool_name == "MySQL":
|
||||||
self.install_mysql_async()
|
self.install_mysql_async()
|
||||||
return
|
return
|
||||||
|
if tool_name == "Node.js":
|
||||||
|
self.install_node_async()
|
||||||
|
return
|
||||||
try:
|
try:
|
||||||
command = build_install_command(tool_name)
|
command = build_install_command(tool_name)
|
||||||
except ValueError as exc:
|
except ValueError as exc:
|
||||||
@@ -393,6 +412,28 @@ class DeployWorkbench(tk.Tk):
|
|||||||
daemon=True,
|
daemon=True,
|
||||||
).start()
|
).start()
|
||||||
|
|
||||||
|
def install_node_async(self) -> None:
|
||||||
|
recommendation = recommend_node_version(self.scan_result)
|
||||||
|
if not messagebox.askyesno(
|
||||||
|
"确认安装 Node.js",
|
||||||
|
"程序将读取 Node.js 官方版本索引,自动选择满足项目要求的最新 Windows x64 版本。\n\n"
|
||||||
|
f"项目要求: {recommendation.display_requirement}\n"
|
||||||
|
f"判断依据: {recommendation.reason}\n\n"
|
||||||
|
"安装包会校验 SHA-256,安装完成后自动保存 node.exe 和 npm.cmd 路径。是否继续?",
|
||||||
|
):
|
||||||
|
return
|
||||||
|
self.node_recommendation = recommendation
|
||||||
|
self._append_log(f"开始按项目要求安装 Node.js: {recommendation.display_requirement}")
|
||||||
|
threading.Thread(target=self._install_node_worker, args=(recommendation.requirements,), daemon=True).start()
|
||||||
|
|
||||||
|
def _install_node_worker(self, requirements: tuple[str, ...]) -> None:
|
||||||
|
try:
|
||||||
|
node, npm, version = install_node(requirements, self._thread_log)
|
||||||
|
except Exception as exc:
|
||||||
|
self.ui_queue.put(("node_install_done", (None, None, None, str(exc))))
|
||||||
|
return
|
||||||
|
self.ui_queue.put(("node_install_done", (node, npm, version, "")))
|
||||||
|
|
||||||
def install_mysql_async(self) -> None:
|
def install_mysql_async(self) -> None:
|
||||||
if not messagebox.askyesno(
|
if not messagebox.askyesno(
|
||||||
"确认安装 MySQL",
|
"确认安装 MySQL",
|
||||||
@@ -578,6 +619,7 @@ class DeployWorkbench(tk.Tk):
|
|||||||
lines.append(f" {display_name}: {frontend.path}")
|
lines.append(f" {display_name}: {frontend.path}")
|
||||||
lines.append(f" 端口: {port},依据: {frontend.detail}")
|
lines.append(f" 端口: {port},依据: {frontend.detail}")
|
||||||
lines.append(f"JDK 推荐: JDK {self.jdk_version.get()} - {self.jdk_reason.get()}")
|
lines.append(f"JDK 推荐: JDK {self.jdk_version.get()} - {self.jdk_reason.get()}")
|
||||||
|
lines.append(f"Node.js 要求: {self.node_requirement.get()} - {self.node_recommendation.reason}")
|
||||||
lines.append("SQL:")
|
lines.append("SQL:")
|
||||||
lines.extend(f" - {path}" for path in scan.sql_files[:20])
|
lines.extend(f" - {path}" for path in scan.sql_files[:20])
|
||||||
if len(scan.sql_files) > 20:
|
if len(scan.sql_files) > 20:
|
||||||
@@ -663,6 +705,19 @@ class DeployWorkbench(tk.Tk):
|
|||||||
self._append_log(f"MySQL 路径已保存: {executable}")
|
self._append_log(f"MySQL 路径已保存: {executable}")
|
||||||
self.check_environment_async()
|
self.check_environment_async()
|
||||||
self.after(1800, lambda: self._prompt_add_tool_after_install("MySQL"))
|
self.after(1800, lambda: self._prompt_add_tool_after_install("MySQL"))
|
||||||
|
elif event == "node_install_done":
|
||||||
|
node, npm, version, error = payload # type: ignore[misc]
|
||||||
|
if error:
|
||||||
|
self._append_log(f"Node.js 安装失败: {error}")
|
||||||
|
messagebox.showerror("Node.js 安装失败", str(error))
|
||||||
|
continue
|
||||||
|
self.tool_path_vars["Node.js"].set(str(node))
|
||||||
|
self.tool_path_vars["npm"].set(str(npm))
|
||||||
|
self.save_tool_path_settings(silent=True)
|
||||||
|
self._append_log(f"Node.js {version} 路径已保存: {node}")
|
||||||
|
self._append_log(f"npm 路径已保存: {npm}")
|
||||||
|
self.check_environment_async()
|
||||||
|
self.after(1800, lambda: self._prompt_add_tool_after_install("Node.js"))
|
||||||
self.after(120, self._drain_queue)
|
self.after(120, self._drain_queue)
|
||||||
|
|
||||||
def _prompt_add_tool_after_install(self, tool_name: str) -> None:
|
def _prompt_add_tool_after_install(self, tool_name: str) -> None:
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import ctypes
|
import ctypes
|
||||||
|
import json
|
||||||
import re
|
import re
|
||||||
import hashlib
|
import hashlib
|
||||||
import os
|
import os
|
||||||
@@ -45,6 +46,7 @@ MYSQL_INSTALLER_URL = (
|
|||||||
f"{MYSQL_INSTALLER_ARCHIVE_NAME}"
|
f"{MYSQL_INSTALLER_ARCHIVE_NAME}"
|
||||||
)
|
)
|
||||||
MYSQL_INSTALLER_SHA256 = "F60502EB1EE10A9C1D0A26706A627D224DFAE466D82EF3EB9D76A8A718DB9D80"
|
MYSQL_INSTALLER_SHA256 = "F60502EB1EE10A9C1D0A26706A627D224DFAE466D82EF3EB9D76A8A718DB9D80"
|
||||||
|
NODE_DIST_BASE = "https://nodejs.org/dist"
|
||||||
|
|
||||||
ANSI_PATTERN = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
|
ANSI_PATTERN = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
|
||||||
PERCENT_PATTERN = re.compile(r"(\d{1,3})\s*%")
|
PERCENT_PATTERN = re.compile(r"(\d{1,3})\s*%")
|
||||||
@@ -57,6 +59,22 @@ class JdkRecommendation:
|
|||||||
reason: str
|
reason: str
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class NodeRecommendation:
|
||||||
|
requirements: tuple[str, ...]
|
||||||
|
reason: str
|
||||||
|
|
||||||
|
@property
|
||||||
|
def display_requirement(self) -> str:
|
||||||
|
return " 且 ".join(self.requirements)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class NodeRelease:
|
||||||
|
version: str
|
||||||
|
lts: str | bool
|
||||||
|
|
||||||
|
|
||||||
def recommend_jdk_version(scan: ScanResult | None) -> JdkRecommendation:
|
def recommend_jdk_version(scan: ScanResult | None) -> JdkRecommendation:
|
||||||
if not scan or not scan.backend:
|
if not scan or not scan.backend:
|
||||||
return JdkRecommendation("8", "\u672a\u626b\u63cf\u5230\u540e\u7aef\u7248\u672c\u4fe1\u606f\uff0c\u9ed8\u8ba4\u63a8\u8350 JDK 8\u3002")
|
return JdkRecommendation("8", "\u672a\u626b\u63cf\u5230\u540e\u7aef\u7248\u672c\u4fe1\u606f\uff0c\u9ed8\u8ba4\u63a8\u8350 JDK 8\u3002")
|
||||||
@@ -77,6 +95,25 @@ def recommend_jdk_version(scan: ScanResult | None) -> JdkRecommendation:
|
|||||||
return JdkRecommendation("8", "\u672a\u53d1\u73b0\u660e\u786e Java \u7248\u672c\uff0c\u9ed8\u8ba4\u63a8\u8350 JDK 8\u3002")
|
return JdkRecommendation("8", "\u672a\u53d1\u73b0\u660e\u786e Java \u7248\u672c\uff0c\u9ed8\u8ba4\u63a8\u8350 JDK 8\u3002")
|
||||||
|
|
||||||
|
|
||||||
|
def recommend_node_version(scan: ScanResult | None) -> NodeRecommendation:
|
||||||
|
if not scan or not scan.detected_frontends:
|
||||||
|
return NodeRecommendation(("lts",), "未扫描到前端版本信息,使用 Node.js 最新 LTS。")
|
||||||
|
|
||||||
|
requirements: list[str] = []
|
||||||
|
reasons: list[str] = []
|
||||||
|
for frontend in scan.detected_frontends:
|
||||||
|
requirement = frontend.metadata.get("node_requirement", "").strip()
|
||||||
|
source = frontend.metadata.get("node_requirement_source", "").strip()
|
||||||
|
if requirement and requirement not in requirements:
|
||||||
|
requirements.append(requirement)
|
||||||
|
if requirement:
|
||||||
|
name = frontend.metadata.get("display_name", frontend.path.name)
|
||||||
|
reasons.append(f"{name}: {source or '项目配置'} → {requirement}")
|
||||||
|
if not requirements:
|
||||||
|
return NodeRecommendation(("lts",), "项目未声明 Node.js 版本,使用最新 LTS。")
|
||||||
|
return NodeRecommendation(tuple(requirements), ";".join(reasons))
|
||||||
|
|
||||||
|
|
||||||
def build_install_command(tool_name: str, version: str | None = None) -> list[str]:
|
def build_install_command(tool_name: str, version: str | None = None) -> list[str]:
|
||||||
if tool_name == "JDK":
|
if tool_name == "JDK":
|
||||||
package_id = JDK_PACKAGES.get(version or "8")
|
package_id = JDK_PACKAGES.get(version or "8")
|
||||||
@@ -417,6 +454,174 @@ def default_maven_install_root() -> Path:
|
|||||||
return base / "AutoDeploy" / "tools"
|
return base / "AutoDeploy" / "tools"
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_node_release(index_data: bytes | str, requirements: tuple[str, ...]) -> NodeRelease:
|
||||||
|
try:
|
||||||
|
releases = json.loads(index_data)
|
||||||
|
except (json.JSONDecodeError, UnicodeDecodeError, TypeError) as exc:
|
||||||
|
raise RuntimeError("Node.js 官方版本索引格式无效。") from exc
|
||||||
|
if not isinstance(releases, list):
|
||||||
|
raise RuntimeError("Node.js 官方版本索引格式无效。")
|
||||||
|
|
||||||
|
candidates: list[NodeRelease] = []
|
||||||
|
for item in releases:
|
||||||
|
if not isinstance(item, dict) or not isinstance(item.get("version"), str):
|
||||||
|
continue
|
||||||
|
version = item["version"].lstrip("v")
|
||||||
|
if not re.fullmatch(r"\d+\.\d+\.\d+", version):
|
||||||
|
continue
|
||||||
|
files = item.get("files")
|
||||||
|
if isinstance(files, list) and "win-x64-zip" not in files:
|
||||||
|
continue
|
||||||
|
lts = item.get("lts", False)
|
||||||
|
if all(_node_version_matches(version, requirement, lts) for requirement in requirements):
|
||||||
|
candidates.append(NodeRelease(version, lts if isinstance(lts, str) else bool(lts)))
|
||||||
|
if not candidates:
|
||||||
|
joined = " 且 ".join(requirements)
|
||||||
|
raise RuntimeError(f"Node.js 官方版本中找不到满足项目要求的 Windows x64 版本: {joined}")
|
||||||
|
return max(candidates, key=lambda item: _version_tuple(item.version))
|
||||||
|
|
||||||
|
|
||||||
|
def install_node(
|
||||||
|
requirements: tuple[str, ...],
|
||||||
|
on_output: Callable[[str], None],
|
||||||
|
install_root: Path | None = None,
|
||||||
|
opener: Callable[..., BinaryIO] | None = None,
|
||||||
|
) -> tuple[Path, Path, str]:
|
||||||
|
root = Path(install_root) if install_root is not None else default_maven_install_root()
|
||||||
|
open_url = opener or urllib.request.urlopen
|
||||||
|
on_output(f"正在读取 Node.js 官方版本索引,项目要求: {' 且 '.join(requirements)}")
|
||||||
|
with open_url(f"{NODE_DIST_BASE}/index.json", timeout=30) as response:
|
||||||
|
release = resolve_node_release(response.read(), requirements)
|
||||||
|
|
||||||
|
version = release.version
|
||||||
|
directory_name = f"node-v{version}-win-x64"
|
||||||
|
archive_name = f"{directory_name}.zip"
|
||||||
|
product_home = root / directory_name
|
||||||
|
node_executable = product_home / "node.exe"
|
||||||
|
npm_executable = product_home / "npm.cmd"
|
||||||
|
if node_executable.exists() and npm_executable.exists():
|
||||||
|
on_output(f"Node.js {version} 已安装: {node_executable}")
|
||||||
|
return node_executable, npm_executable, version
|
||||||
|
|
||||||
|
archive_url = f"{NODE_DIST_BASE}/v{version}/{archive_name}"
|
||||||
|
checksum_url = f"{NODE_DIST_BASE}/v{version}/SHASUMS256.txt"
|
||||||
|
root.mkdir(parents=True, exist_ok=True)
|
||||||
|
with tempfile.TemporaryDirectory(prefix="autodeploy-node-") as temporary:
|
||||||
|
temp_dir = Path(temporary)
|
||||||
|
archive_path = temp_dir / archive_name
|
||||||
|
on_output(f"已自动选择 Node.js {version},正在从官方地址下载...")
|
||||||
|
_download_to_file(archive_url, archive_path, open_url, on_output)
|
||||||
|
expected_checksum = _download_node_checksum(checksum_url, archive_name, open_url)
|
||||||
|
actual_checksum = _sha256(archive_path)
|
||||||
|
if actual_checksum.lower() != expected_checksum.lower():
|
||||||
|
raise RuntimeError("Node.js 安装包 SHA-256 校验失败,已停止安装。")
|
||||||
|
on_output("Node.js 安装包校验通过,正在解压...")
|
||||||
|
extract_root = temp_dir / "extracted"
|
||||||
|
_safe_extract_zip(archive_path, extract_root)
|
||||||
|
extracted_home = extract_root / directory_name
|
||||||
|
if not (extracted_home / "node.exe").exists() or not (extracted_home / "npm.cmd").exists():
|
||||||
|
raise RuntimeError("Node.js 安装包结构异常,未找到 node.exe 或 npm.cmd。")
|
||||||
|
shutil.copytree(extracted_home, product_home, dirs_exist_ok=True)
|
||||||
|
|
||||||
|
on_output(f"Node.js {version} 安装完成: {node_executable}")
|
||||||
|
return node_executable, npm_executable, version
|
||||||
|
|
||||||
|
|
||||||
|
def _download_node_checksum(
|
||||||
|
url: str,
|
||||||
|
archive_name: str,
|
||||||
|
opener: Callable[..., BinaryIO],
|
||||||
|
) -> str:
|
||||||
|
with opener(url, timeout=30) as response:
|
||||||
|
text = response.read().decode("ascii", errors="strict")
|
||||||
|
for line in text.splitlines():
|
||||||
|
parts = line.split()
|
||||||
|
if len(parts) >= 2 and parts[-1].lstrip("*") == archive_name:
|
||||||
|
checksum = parts[0]
|
||||||
|
if re.fullmatch(r"[0-9a-fA-F]{64}", checksum):
|
||||||
|
return checksum
|
||||||
|
raise RuntimeError(f"Node.js 校验清单中未找到 {archive_name}。")
|
||||||
|
|
||||||
|
|
||||||
|
def _node_version_matches(version: str, requirement: str, lts: object) -> bool:
|
||||||
|
text = requirement.strip().lower()
|
||||||
|
if text in {"", "*", "node", "latest"}:
|
||||||
|
return True
|
||||||
|
if text.startswith("lts"):
|
||||||
|
requested_name = text.partition("/")[2]
|
||||||
|
if requested_name in {"", "*", "-*"}:
|
||||||
|
return bool(lts)
|
||||||
|
return isinstance(lts, str) and lts.lower() == requested_name
|
||||||
|
return any(_node_clause_matches(version, clause) for clause in text.split("||"))
|
||||||
|
|
||||||
|
|
||||||
|
def _node_clause_matches(version: str, clause: str) -> bool:
|
||||||
|
current = _version_tuple(version)
|
||||||
|
normalized = clause.replace(",", " ").replace("(", " ").replace(")", " ")
|
||||||
|
hyphen = re.fullmatch(r"\s*v?(\d+(?:\.\d+){0,2})\s+-\s+v?(\d+(?:\.\d+){0,2})\s*", normalized)
|
||||||
|
if hyphen:
|
||||||
|
return _compare_versions(current, ">=", _partial_version_tuple(hyphen.group(1))) and _compare_versions(
|
||||||
|
current, "<=", _partial_version_tuple(hyphen.group(2), upper=True)
|
||||||
|
)
|
||||||
|
tokens = re.findall(r"(?:>=|<=|>|<|=|\^|~)?\s*v?\d+(?:\.\d+){0,2}(?:\.(?:x|\*))?|(?:\d+\.)?(?:x|\*)", normalized)
|
||||||
|
if not tokens:
|
||||||
|
return False
|
||||||
|
return all(_node_token_matches(current, token.replace(" ", "")) for token in tokens)
|
||||||
|
|
||||||
|
|
||||||
|
def _node_token_matches(current: tuple[int, int, int], token: str) -> bool:
|
||||||
|
match = re.fullmatch(r"(>=|<=|>|<|=|\^|~)?v?(.+)", token)
|
||||||
|
if not match:
|
||||||
|
return False
|
||||||
|
operator = match.group(1) or ""
|
||||||
|
value = match.group(2)
|
||||||
|
if value in {"x", "*"}:
|
||||||
|
return True
|
||||||
|
parts = value.split(".")
|
||||||
|
numeric = [int(part) for part in parts if part not in {"x", "*"}]
|
||||||
|
if not numeric:
|
||||||
|
return True
|
||||||
|
target = tuple((numeric + [0, 0, 0])[:3])
|
||||||
|
if operator == "^":
|
||||||
|
upper = (target[0] + 1, 0, 0) if target[0] else (0, target[1] + 1, 0)
|
||||||
|
return current >= target and current < upper
|
||||||
|
if operator == "~":
|
||||||
|
upper = (target[0], target[1] + 1, 0) if len(numeric) > 1 else (target[0] + 1, 0, 0)
|
||||||
|
return current >= target and current < upper
|
||||||
|
if operator:
|
||||||
|
return _compare_versions(current, operator, target)
|
||||||
|
if len(numeric) == 1:
|
||||||
|
return current[0] == target[0]
|
||||||
|
if len(numeric) == 2:
|
||||||
|
return current[:2] == target[:2]
|
||||||
|
return current == target
|
||||||
|
|
||||||
|
|
||||||
|
def _version_tuple(value: str) -> tuple[int, int, int]:
|
||||||
|
parts = [int(part) for part in value.lstrip("v").split(".")[:3]]
|
||||||
|
return tuple((parts + [0, 0, 0])[:3])
|
||||||
|
|
||||||
|
|
||||||
|
def _partial_version_tuple(value: str, upper: bool = False) -> tuple[int, int, int]:
|
||||||
|
parts = [int(part) for part in value.split(".")]
|
||||||
|
padded = (parts + ([999999] * 3 if upper else [0] * 3))[:3]
|
||||||
|
return tuple(padded)
|
||||||
|
|
||||||
|
|
||||||
|
def _compare_versions(
|
||||||
|
current: tuple[int, int, int],
|
||||||
|
operator: str,
|
||||||
|
target: tuple[int, int, int],
|
||||||
|
) -> bool:
|
||||||
|
return {
|
||||||
|
">=": current >= target,
|
||||||
|
"<=": current <= target,
|
||||||
|
">": current > target,
|
||||||
|
"<": current < target,
|
||||||
|
"=": current == target,
|
||||||
|
}.get(operator, False)
|
||||||
|
|
||||||
|
|
||||||
def install_maven(
|
def install_maven(
|
||||||
on_output: Callable[[str], None],
|
on_output: Callable[[str], None],
|
||||||
install_root: Path | None = None,
|
install_root: Path | None = None,
|
||||||
@@ -562,7 +767,7 @@ def _safe_extract_zip(archive_path: Path, destination: Path) -> None:
|
|||||||
for member in archive.infolist():
|
for member in archive.infolist():
|
||||||
target = (destination / member.filename).resolve()
|
target = (destination / member.filename).resolve()
|
||||||
if target != destination_resolved and destination_resolved not in target.parents:
|
if target != destination_resolved and destination_resolved not in target.parents:
|
||||||
raise RuntimeError("Maven 安装包包含不安全的文件路径。")
|
raise RuntimeError("ZIP 安装包包含不安全的文件路径。")
|
||||||
archive.extractall(destination)
|
archive.extractall(destination)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -121,6 +121,7 @@ def _find_frontends(root: Path) -> list[ProjectComponent]:
|
|||||||
score += 1
|
score += 1
|
||||||
detail_parts.append("Vue/Vite config")
|
detail_parts.append("Vue/Vite config")
|
||||||
metadata = _classify_frontend(project_dir)
|
metadata = _classify_frontend(project_dir)
|
||||||
|
metadata.update(_extract_node_metadata(root, project_dir, package, deps))
|
||||||
for script_name in ("serve", "dev", "start"):
|
for script_name in ("serve", "dev", "start"):
|
||||||
if isinstance(scripts.get(script_name), str):
|
if isinstance(scripts.get(script_name), str):
|
||||||
metadata["start_script"] = script_name
|
metadata["start_script"] = script_name
|
||||||
@@ -160,6 +161,86 @@ def _classify_frontend(project_dir: Path) -> dict[str, str]:
|
|||||||
return {"role": "frontend", "display_name": project_dir.name}
|
return {"role": "frontend", "display_name": project_dir.name}
|
||||||
|
|
||||||
|
|
||||||
|
def _extract_node_metadata(
|
||||||
|
root: Path,
|
||||||
|
project_dir: Path,
|
||||||
|
package: dict,
|
||||||
|
dependencies: dict,
|
||||||
|
) -> dict[str, str]:
|
||||||
|
search_dirs = [project_dir]
|
||||||
|
if root != project_dir:
|
||||||
|
search_dirs.append(root)
|
||||||
|
for directory in search_dirs:
|
||||||
|
for filename in (".nvmrc", ".node-version"):
|
||||||
|
version_file = directory / filename
|
||||||
|
if version_file.is_file():
|
||||||
|
requirement = _read_version_file(version_file)
|
||||||
|
if requirement:
|
||||||
|
return {
|
||||||
|
"node_requirement": requirement,
|
||||||
|
"node_requirement_source": str(version_file),
|
||||||
|
}
|
||||||
|
|
||||||
|
engines = package.get("engines")
|
||||||
|
if isinstance(engines, dict) and isinstance(engines.get("node"), str):
|
||||||
|
requirement = engines["node"].strip()
|
||||||
|
if requirement:
|
||||||
|
return {
|
||||||
|
"node_requirement": requirement,
|
||||||
|
"node_requirement_source": "package.json engines.node",
|
||||||
|
}
|
||||||
|
|
||||||
|
vite_major = _dependency_major(dependencies.get("vite"))
|
||||||
|
if vite_major is not None:
|
||||||
|
if vite_major >= 7:
|
||||||
|
requirement = "^20.19.0 || >=22.12.0"
|
||||||
|
elif vite_major >= 5:
|
||||||
|
requirement = ">=18 <23"
|
||||||
|
elif vite_major >= 3:
|
||||||
|
requirement = ">=14.18 <21"
|
||||||
|
else:
|
||||||
|
requirement = ">=12 <18"
|
||||||
|
return {
|
||||||
|
"node_requirement": requirement,
|
||||||
|
"node_requirement_source": f"Vite {vite_major}.x 兼容性推断",
|
||||||
|
}
|
||||||
|
|
||||||
|
cli_major = _dependency_major(dependencies.get("@vue/cli-service"))
|
||||||
|
if cli_major is not None:
|
||||||
|
recommended_major = 16 if cli_major >= 5 else 14 if cli_major == 4 else 12
|
||||||
|
return {
|
||||||
|
"node_requirement": str(recommended_major),
|
||||||
|
"node_requirement_source": f"Vue CLI {cli_major}.x 兼容性推断",
|
||||||
|
}
|
||||||
|
|
||||||
|
vue_major = _dependency_major(dependencies.get("vue"))
|
||||||
|
if vue_major == 2:
|
||||||
|
return {
|
||||||
|
"node_requirement": "14",
|
||||||
|
"node_requirement_source": "Vue 2 兼容性推断",
|
||||||
|
}
|
||||||
|
if vue_major and vue_major >= 3:
|
||||||
|
return {
|
||||||
|
"node_requirement": "lts",
|
||||||
|
"node_requirement_source": "Vue 3 兼容性推断",
|
||||||
|
}
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _read_version_file(path: Path) -> str:
|
||||||
|
try:
|
||||||
|
return path.read_text(encoding="utf-8", errors="ignore").strip().splitlines()[0].strip()
|
||||||
|
except (OSError, IndexError):
|
||||||
|
return ""
|
||||||
|
|
||||||
|
|
||||||
|
def _dependency_major(value: object) -> int | None:
|
||||||
|
if not isinstance(value, str):
|
||||||
|
return None
|
||||||
|
match = re.search(r"\d+", value)
|
||||||
|
return int(match.group()) if match else None
|
||||||
|
|
||||||
|
|
||||||
def _extract_frontend_port(project_dir: Path) -> str | None:
|
def _extract_frontend_port(project_dir: Path) -> str | None:
|
||||||
for name in ("vue.config.js", "vite.config.js", "vite.config.ts"):
|
for name in ("vue.config.js", "vite.config.js", "vite.config.ts"):
|
||||||
config_file = project_dir / name
|
config_file = project_dir / name
|
||||||
|
|||||||
@@ -50,6 +50,25 @@ class EnvironmentTests(unittest.TestCase):
|
|||||||
self.assertEqual(results[0].source, "手动指定")
|
self.assertEqual(results[0].source, "手动指定")
|
||||||
self.assertEqual(results[0].command[0], str(mysql))
|
self.assertEqual(results[0].command[0], str(mysql))
|
||||||
|
|
||||||
|
def test_prefers_configured_node_version_over_another_path_version(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
node = Path(tmp) / "node.exe"
|
||||||
|
node.write_text("", encoding="utf-8")
|
||||||
|
|
||||||
|
def runner(command):
|
||||||
|
version = "v16.20.2" if command[0] == str(node) else "v22.0.0"
|
||||||
|
return subprocess.CompletedProcess(command, 0, version, "")
|
||||||
|
|
||||||
|
results = check_environment(
|
||||||
|
runner=runner,
|
||||||
|
checks={"Node.js": ["node", "--version"]},
|
||||||
|
manual_paths={"Node.js": node},
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(results[0].source, "手动指定")
|
||||||
|
self.assertEqual(results[0].command[0], str(node))
|
||||||
|
self.assertEqual(results[0].version, "v16.20.2")
|
||||||
|
|
||||||
def test_discovers_executable_from_known_search_paths(self):
|
def test_discovers_executable_from_known_search_paths(self):
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
mysql = Path(tmp) / "MySQL" / "MySQL Server 8.4" / "bin" / "mysql.exe"
|
mysql = Path(tmp) / "MySQL" / "MySQL Server 8.4" / "bin" / "mysql.exe"
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import hashlib
|
import hashlib
|
||||||
import io
|
import io
|
||||||
|
import json
|
||||||
import tempfile
|
import tempfile
|
||||||
import unittest
|
import unittest
|
||||||
import zipfile
|
import zipfile
|
||||||
@@ -16,6 +17,7 @@ from deploy_tool.installer import (
|
|||||||
MYSQL_ROOT_PASSWORD,
|
MYSQL_ROOT_PASSWORD,
|
||||||
MYSQL_INSTALLER_SHA256,
|
MYSQL_INSTALLER_SHA256,
|
||||||
MYSQL_INSTALLER_URL,
|
MYSQL_INSTALLER_URL,
|
||||||
|
NODE_DIST_BASE,
|
||||||
build_mysql_installer_command,
|
build_mysql_installer_command,
|
||||||
build_mysql_server_install_command,
|
build_mysql_server_install_command,
|
||||||
configure_mysql_weak_password_policy,
|
configure_mysql_weak_password_policy,
|
||||||
@@ -23,11 +25,14 @@ from deploy_tool.installer import (
|
|||||||
TOMCAT_VERSION,
|
TOMCAT_VERSION,
|
||||||
install_maven,
|
install_maven,
|
||||||
install_mysql,
|
install_mysql,
|
||||||
|
install_node,
|
||||||
install_tomcat,
|
install_tomcat,
|
||||||
build_install_command,
|
build_install_command,
|
||||||
explain_install_failure,
|
explain_install_failure,
|
||||||
format_install_output,
|
format_install_output,
|
||||||
recommend_jdk_version,
|
recommend_jdk_version,
|
||||||
|
recommend_node_version,
|
||||||
|
resolve_node_release,
|
||||||
)
|
)
|
||||||
from deploy_tool.scanner import scan_project
|
from deploy_tool.scanner import scan_project
|
||||||
|
|
||||||
@@ -113,6 +118,72 @@ class InstallerTests(unittest.TestCase):
|
|||||||
self.assertIn("--accept-package-agreements", command)
|
self.assertIn("--accept-package-agreements", command)
|
||||||
self.assertIn("--disable-interactivity", command)
|
self.assertIn("--disable-interactivity", command)
|
||||||
|
|
||||||
|
def test_recommends_node_from_project_engines(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
root = Path(tmp)
|
||||||
|
frontend = root / "web"
|
||||||
|
frontend.mkdir()
|
||||||
|
(frontend / "package.json").write_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"engines": {"node": ">=18 <21"},
|
||||||
|
"dependencies": {"vue": "^3.4.0"},
|
||||||
|
"scripts": {"build": "vite build"},
|
||||||
|
}
|
||||||
|
),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
recommendation = recommend_node_version(scan_project(root))
|
||||||
|
|
||||||
|
self.assertEqual(recommendation.requirements, (">=18 <21",))
|
||||||
|
self.assertIn("engines.node", recommendation.reason)
|
||||||
|
|
||||||
|
def test_resolves_latest_compatible_node_release(self):
|
||||||
|
index = json.dumps(
|
||||||
|
[
|
||||||
|
{"version": "v22.3.0", "lts": "Jod", "files": ["win-x64-zip"]},
|
||||||
|
{"version": "v20.12.2", "lts": "Iron", "files": ["win-x64-zip"]},
|
||||||
|
{"version": "v20.11.1", "lts": "Iron", "files": ["win-x64-zip"]},
|
||||||
|
{"version": "v18.20.0", "lts": "Hydrogen", "files": ["win-x64-zip"]},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
release = resolve_node_release(index, (">=18 <21",))
|
||||||
|
|
||||||
|
self.assertEqual(release.version, "20.12.2")
|
||||||
|
self.assertEqual(resolve_node_release(index, ("lts/iron",)).version, "20.12.2")
|
||||||
|
|
||||||
|
def test_installs_verified_node_archive_selected_from_official_index(self):
|
||||||
|
version = "20.12.2"
|
||||||
|
directory = f"node-v{version}-win-x64"
|
||||||
|
archive_name = f"{directory}.zip"
|
||||||
|
archive_buffer = io.BytesIO()
|
||||||
|
with zipfile.ZipFile(archive_buffer, "w") as archive:
|
||||||
|
archive.writestr(f"{directory}/node.exe", "node")
|
||||||
|
archive.writestr(f"{directory}/npm.cmd", "npm")
|
||||||
|
archive_bytes = archive_buffer.getvalue()
|
||||||
|
checksum = hashlib.sha256(archive_bytes).hexdigest()
|
||||||
|
index_bytes = json.dumps(
|
||||||
|
[{"version": f"v{version}", "lts": "Iron", "files": ["win-x64-zip"]}]
|
||||||
|
).encode("utf-8")
|
||||||
|
|
||||||
|
def opener(url, timeout):
|
||||||
|
if url == f"{NODE_DIST_BASE}/index.json":
|
||||||
|
return io.BytesIO(index_bytes)
|
||||||
|
if url.endswith("SHASUMS256.txt"):
|
||||||
|
return io.BytesIO(f"{checksum} {archive_name}\n".encode("ascii"))
|
||||||
|
return io.BytesIO(archive_bytes)
|
||||||
|
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
messages = []
|
||||||
|
node, npm, installed_version = install_node((">=18 <21",), messages.append, Path(tmp), opener)
|
||||||
|
|
||||||
|
self.assertEqual(installed_version, version)
|
||||||
|
self.assertTrue(node.exists())
|
||||||
|
self.assertTrue(npm.exists())
|
||||||
|
self.assertTrue(any("自动选择 Node.js 20.12.2" in message for message in messages))
|
||||||
|
|
||||||
def test_builds_unattended_mysql_msi_install_command(self):
|
def test_builds_unattended_mysql_msi_install_command(self):
|
||||||
command = build_mysql_installer_command(Path("mysql-installer.msi"), Path("mysql-install.log"))
|
command = build_mysql_installer_command(Path("mysql-installer.msi"), Path("mysql-install.log"))
|
||||||
|
|
||||||
|
|||||||
@@ -99,6 +99,49 @@ class ScannerTests(unittest.TestCase):
|
|||||||
self.assertEqual(result.frontend.path, frontend)
|
self.assertEqual(result.frontend.path, frontend)
|
||||||
self.assertEqual(result.sql_files, [sql_dir / "schema.sql"])
|
self.assertEqual(result.sql_files, [sql_dir / "schema.sql"])
|
||||||
|
|
||||||
|
def test_reads_node_version_from_nvmrc_before_package_engines(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
root = Path(tmp)
|
||||||
|
frontend = root / "web"
|
||||||
|
frontend.mkdir()
|
||||||
|
(frontend / ".nvmrc").write_text("v16.20.2\n", encoding="utf-8")
|
||||||
|
(frontend / "package.json").write_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"engines": {"node": ">=18"},
|
||||||
|
"dependencies": {"vue": "^2.7.0"},
|
||||||
|
"scripts": {"build": "vue-cli-service build"},
|
||||||
|
}
|
||||||
|
),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
result = scan_project(root)
|
||||||
|
|
||||||
|
self.assertEqual(result.frontend.metadata["node_requirement"], "v16.20.2")
|
||||||
|
self.assertIn(".nvmrc", result.frontend.metadata["node_requirement_source"])
|
||||||
|
|
||||||
|
def test_infers_node_version_from_vue_cli_when_project_has_no_explicit_version(self):
|
||||||
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
|
root = Path(tmp)
|
||||||
|
frontend = root / "web"
|
||||||
|
frontend.mkdir()
|
||||||
|
(frontend / "package.json").write_text(
|
||||||
|
json.dumps(
|
||||||
|
{
|
||||||
|
"dependencies": {"vue": "^2.6.0"},
|
||||||
|
"devDependencies": {"@vue/cli-service": "^4.5.19"},
|
||||||
|
"scripts": {"build": "vue-cli-service build"},
|
||||||
|
}
|
||||||
|
),
|
||||||
|
encoding="utf-8",
|
||||||
|
)
|
||||||
|
|
||||||
|
result = scan_project(root)
|
||||||
|
|
||||||
|
self.assertEqual(result.frontend.metadata["node_requirement"], "14")
|
||||||
|
self.assertIn("Vue CLI 4", result.frontend.metadata["node_requirement_source"])
|
||||||
|
|
||||||
def test_detects_maven_ssm_war_project_and_context_path(self):
|
def test_detects_maven_ssm_war_project_and_context_path(self):
|
||||||
with tempfile.TemporaryDirectory() as tmp:
|
with tempfile.TemporaryDirectory() as tmp:
|
||||||
root = Path(tmp)
|
root = Path(tmp)
|
||||||
|
|||||||
Reference in New Issue
Block a user