Install project-compatible Node.js version
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import ctypes
|
||||
import json
|
||||
import re
|
||||
import hashlib
|
||||
import os
|
||||
@@ -45,6 +46,7 @@ MYSQL_INSTALLER_URL = (
|
||||
f"{MYSQL_INSTALLER_ARCHIVE_NAME}"
|
||||
)
|
||||
MYSQL_INSTALLER_SHA256 = "F60502EB1EE10A9C1D0A26706A627D224DFAE466D82EF3EB9D76A8A718DB9D80"
|
||||
NODE_DIST_BASE = "https://nodejs.org/dist"
|
||||
|
||||
ANSI_PATTERN = re.compile(r"\x1b\[[0-?]*[ -/]*[@-~]")
|
||||
PERCENT_PATTERN = re.compile(r"(\d{1,3})\s*%")
|
||||
@@ -57,6 +59,22 @@ class JdkRecommendation:
|
||||
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:
|
||||
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")
|
||||
@@ -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")
|
||||
|
||||
|
||||
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]:
|
||||
if tool_name == "JDK":
|
||||
package_id = JDK_PACKAGES.get(version or "8")
|
||||
@@ -417,6 +454,174 @@ def default_maven_install_root() -> Path:
|
||||
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(
|
||||
on_output: Callable[[str], 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():
|
||||
target = (destination / member.filename).resolve()
|
||||
if target != destination_resolved and destination_resolved not in target.parents:
|
||||
raise RuntimeError("Maven 安装包包含不安全的文件路径。")
|
||||
raise RuntimeError("ZIP 安装包包含不安全的文件路径。")
|
||||
archive.extractall(destination)
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user