dsh模块、快捷键调整
This commit is contained in:
1 parent
ff1d5cd517
commit
7e65825d3e
54 files changed
+7082
-109
No files matched your search
@@ -0,0 +1,399 @@
|
||||
//! Node 运行环境:探测系统 Node / 下载并解压便携 Node。
|
||||
//!
|
||||
//! dsh 要求 Node `^22.19.0 || >=24.0.0`。策略(用户已确认):
|
||||
//! 优先复用 PATH 上的系统 Node,版本不满足或缺失时才下载官方便携版到
|
||||
//! `{app_data}/dsh/node`(官方 zip 内含 npm/npx,因此托管 Node 自带 npm)。
|
||||
|
||||
use std::fs;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::atomic::Ordering;
|
||||
|
||||
use futures_util::StreamExt;
|
||||
use tauri::AppHandle;
|
||||
|
||||
use super::types::{NodeStatus, NODE_REQUIRED};
|
||||
use super::{satisfies_node_requirement, DshManager, NodeEnv};
|
||||
|
||||
/// 用户取消时返回的错误信息(前端静默处理,不弹错误 toast)。
|
||||
pub(crate) const NODE_CANCELLED: &str = "已取消";
|
||||
|
||||
impl DshManager {
|
||||
/// 系统 PATH 上的 node.exe
|
||||
pub fn system_node(&self) -> Option<PathBuf> {
|
||||
which_node()
|
||||
}
|
||||
|
||||
/// 托管便携 Node 的 node.exe
|
||||
pub fn managed_node(&self) -> Option<PathBuf> {
|
||||
let exe = self.node_dir().join(if cfg!(windows) { "node.exe" } else { "bin/node" });
|
||||
exe.exists().then_some(exe)
|
||||
}
|
||||
|
||||
/// 解析实际使用的 Node 环境(按 nodeSource 设置)。
|
||||
pub fn resolve_node_env(&self) -> Option<NodeEnv> {
|
||||
let settings = self.load_settings();
|
||||
let system = self.system_node();
|
||||
let managed = self.managed_node();
|
||||
|
||||
let system_ok = system
|
||||
.as_ref()
|
||||
.and_then(|p| node_version(p))
|
||||
.map(|v| satisfies_node_requirement(&v))
|
||||
.unwrap_or(false);
|
||||
|
||||
// 选定 (是否托管, 可执行文件)
|
||||
let chosen: Option<(bool, PathBuf)> = match settings.node_source.as_str() {
|
||||
"system" => system.map(|p| (false, p)),
|
||||
"managed" => managed.map(|p| (true, p)),
|
||||
// auto:系统满足即复用,否则回落托管;两者都没有时退回系统 Node 仅用于展示版本
|
||||
_ => {
|
||||
if system_ok {
|
||||
system.map(|p| (false, p))
|
||||
} else {
|
||||
managed
|
||||
.map(|p| (true, p))
|
||||
.or_else(|| system.map(|p| (false, p)))
|
||||
}
|
||||
}
|
||||
};
|
||||
let (is_managed, exe) = chosen?;
|
||||
|
||||
let version = node_version(&exe).unwrap_or_default();
|
||||
let npm = npm_cli_js(&exe);
|
||||
Some(NodeEnv {
|
||||
source: if is_managed { "managed" } else { "system" },
|
||||
node_exe: exe,
|
||||
npm,
|
||||
version,
|
||||
})
|
||||
}
|
||||
|
||||
/// 当前 Node 状态(供 UI 首屏展示)。
|
||||
pub fn node_status(&self) -> NodeStatus {
|
||||
match self.resolve_node_env() {
|
||||
Some(env) => {
|
||||
let satisfies = satisfies_node_requirement(&env.version);
|
||||
NodeStatus {
|
||||
source: if env.source == "managed" { "managed".into() } else { "system".into() },
|
||||
path: Some(env.node_exe.to_string_lossy().to_string()),
|
||||
version: Some(env.version),
|
||||
satisfies,
|
||||
required: NODE_REQUIRED.into(),
|
||||
}
|
||||
}
|
||||
None => NodeStatus {
|
||||
source: "none".into(),
|
||||
path: None,
|
||||
version: None,
|
||||
satisfies: false,
|
||||
required: NODE_REQUIRED.into(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
/// 下载并安装便携 Node(进度经 `dsh-install-progress` 推送)。
|
||||
///
|
||||
/// `version` 为空时自动解析满足要求的最新版本(优先 LTS)。
|
||||
pub async fn node_install(&self, app: &AppHandle, version: Option<String>) -> Result<NodeStatus, String> {
|
||||
if !cfg!(windows) {
|
||||
return Err("便携 Node 安装仅支持 Windows,请改用系统 Node(nodeSource = system)".into());
|
||||
}
|
||||
self.cancel.store(false, Ordering::SeqCst);
|
||||
let result = self.node_install_inner(app, version).await;
|
||||
self.cancel.store(false, Ordering::SeqCst);
|
||||
if let Err(ref e) = result {
|
||||
if e != NODE_CANCELLED {
|
||||
self.emit_progress(app, "error", 0, 0, None, e);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
async fn node_install_inner(&self, app: &AppHandle, version: Option<String>) -> Result<NodeStatus, String> {
|
||||
let base = self.node_mirror_base();
|
||||
let version = match version.filter(|v| !v.trim().is_empty()) {
|
||||
Some(v) => normalize_version(&v),
|
||||
None => {
|
||||
self.emit_progress(app, "download", 0, 0, None, "正在解析 Node 版本...");
|
||||
let requested = self.load_settings().managed_node_version;
|
||||
if requested.trim().is_empty() {
|
||||
self.resolve_latest_node_version(&base).await?
|
||||
} else {
|
||||
normalize_version(&requested)
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let arch = platform_arch();
|
||||
let url = format!("{base}/{version}/node-{version}-{arch}.zip");
|
||||
let zip_path = self.node_dir().join("node-download.zip");
|
||||
self.emit_progress(
|
||||
app,
|
||||
"download",
|
||||
1,
|
||||
0,
|
||||
None,
|
||||
&format!("正在下载 Node {version}..."),
|
||||
);
|
||||
self.download_to_file(app, &url, &zip_path, "正在下载 Node").await?;
|
||||
|
||||
if self.cancel.load(Ordering::SeqCst) {
|
||||
let _ = fs::remove_file(&zip_path);
|
||||
return Err(NODE_CANCELLED.into());
|
||||
}
|
||||
|
||||
// 解压:官方 zip 顶层是 node-vX-win-x64/,剥掉这一层直接落到 node/
|
||||
self.emit_progress(app, "extracting", 92, 0, None, "正在解压...");
|
||||
let dest = self.node_dir();
|
||||
if dest.exists() {
|
||||
fs::remove_dir_all(&dest).map_err(|e| format!("清理旧 Node 目录失败: {e}"))?;
|
||||
}
|
||||
fs::create_dir_all(&dest).map_err(|e| format!("创建 Node 目录失败: {e}"))?;
|
||||
if let Err(e) = extract_zip_strip_top(&zip_path, &dest) {
|
||||
let _ = fs::remove_file(&zip_path);
|
||||
return Err(format!("解压 Node 失败: {e}"));
|
||||
}
|
||||
let _ = fs::remove_file(&zip_path);
|
||||
|
||||
let exe = dest.join("node.exe");
|
||||
if !exe.exists() {
|
||||
return Err("解压后未找到 node.exe".into());
|
||||
}
|
||||
let actual = node_version(&exe).unwrap_or(version.clone());
|
||||
self.emit_progress(app, "done", 100, 0, None, &format!("Node {actual} 安装完成"));
|
||||
crate::logger::log_info("dsh", &format!("便携 Node 安装完成: {actual} ({})", exe.display()));
|
||||
Ok(self.node_status())
|
||||
}
|
||||
|
||||
/// 托管 Node 的镜像基址(`{base}/{version}/node-{version}-win-x64.zip`)。
|
||||
fn node_mirror_base(&self) -> String {
|
||||
let mirror = self.load_settings().node_mirror;
|
||||
let mirror = mirror.trim().trim_end_matches('/');
|
||||
if mirror.is_empty() {
|
||||
"https://nodejs.org/dist".to_string()
|
||||
} else {
|
||||
mirror.to_string()
|
||||
}
|
||||
}
|
||||
|
||||
/// 解析满足要求的最新 Node 版本(优先 LTS)。
|
||||
async fn resolve_latest_node_version(&self, base: &str) -> Result<String, String> {
|
||||
let url = format!("{base}/index.json");
|
||||
let resp = self
|
||||
.http_client(30)
|
||||
.get(&url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("获取 Node 版本列表失败: {e}"))?;
|
||||
if !resp.status().is_success() {
|
||||
return Err(format!("获取 Node 版本列表失败: HTTP {}", resp.status().as_u16()));
|
||||
}
|
||||
let list: Vec<serde_json::Value> = resp
|
||||
.json()
|
||||
.await
|
||||
.map_err(|e| format!("解析 Node 版本列表失败: {e}"))?;
|
||||
|
||||
let mut latest_lts: Option<(u32, u32, u32, String)> = None;
|
||||
let mut latest_any: Option<(u32, u32, u32, String)> = None;
|
||||
for item in list {
|
||||
let Some(version) = item.get("version").and_then(|v| v.as_str()) else {
|
||||
continue;
|
||||
};
|
||||
if !satisfies_node_requirement(version) {
|
||||
continue;
|
||||
}
|
||||
let Some(parsed) = super::parse_version(version) else {
|
||||
continue;
|
||||
};
|
||||
let is_lts = item.get("lts").map(|l| !l.is_null() && l != false).unwrap_or(false);
|
||||
if latest_any.as_ref().map(|(maj, min, pat, _)| (parsed.0, parsed.1, parsed.2) > (*maj, *min, *pat)).unwrap_or(true) {
|
||||
latest_any = Some((parsed.0, parsed.1, parsed.2, version.to_string()));
|
||||
}
|
||||
if is_lts
|
||||
&& latest_lts
|
||||
.as_ref()
|
||||
.map(|(maj, min, pat, _)| (parsed.0, parsed.1, parsed.2) > (*maj, *min, *pat))
|
||||
.unwrap_or(true)
|
||||
{
|
||||
latest_lts = Some((parsed.0, parsed.1, parsed.2, version.to_string()));
|
||||
}
|
||||
}
|
||||
latest_lts
|
||||
.or(latest_any)
|
||||
.map(|(_, _, _, v)| v)
|
||||
.ok_or_else(|| "未找到满足 dsh 要求的 Node 版本".to_string())
|
||||
}
|
||||
|
||||
/// 流式下载到文件(带取消 + 进度事件,percent 0-90)。
|
||||
pub(crate) async fn download_to_file(
|
||||
&self,
|
||||
app: &AppHandle,
|
||||
url: &str,
|
||||
dest: &Path,
|
||||
label: &str,
|
||||
) -> Result<(), String> {
|
||||
let resp = self
|
||||
.http_client(1800)
|
||||
.get(url)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("请求下载失败({url}): {e}"))?;
|
||||
let status = resp.status();
|
||||
if !status.is_success() {
|
||||
return Err(format!("下载返回 HTTP {}", status.as_u16()));
|
||||
}
|
||||
let total = resp.content_length();
|
||||
let mut file = fs::File::create(dest).map_err(|e| format!("创建文件失败: {e}"))?;
|
||||
let mut stream = resp.bytes_stream();
|
||||
let mut downloaded: u64 = 0;
|
||||
let mut last_percent: u8 = 0;
|
||||
while let Some(chunk) = stream.next().await {
|
||||
if self.cancel.load(Ordering::SeqCst) {
|
||||
drop(file);
|
||||
fs::remove_file(dest).ok();
|
||||
return Err(NODE_CANCELLED.into());
|
||||
}
|
||||
let chunk = chunk.map_err(|e| format!("下载中断: {e}"))?;
|
||||
file.write_all(&chunk).map_err(|e| format!("写入文件失败: {e}"))?;
|
||||
downloaded += chunk.len() as u64;
|
||||
let percent = total
|
||||
.filter(|t| *t > 0)
|
||||
.map(|t| ((downloaded as f64 / t as f64) * 90.0) as u8)
|
||||
.unwrap_or(0)
|
||||
.min(90);
|
||||
if percent >= last_percent + 1 {
|
||||
last_percent = percent;
|
||||
self.emit_progress(
|
||||
app,
|
||||
"download",
|
||||
percent,
|
||||
downloaded,
|
||||
total,
|
||||
&format!("{label} {:.1} MB", downloaded as f64 / 1048576.0),
|
||||
);
|
||||
}
|
||||
}
|
||||
file.flush().ok();
|
||||
self.emit_progress(app, "download", 90, downloaded, total, "下载完成");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 请求取消(下载 / 安装 / 解压均轮询此标志)。
|
||||
pub(crate) fn request_cancel(&self) {
|
||||
self.cancel.store(true, Ordering::SeqCst);
|
||||
let pid = self.install_pid.load(Ordering::SeqCst);
|
||||
if pid > 0 {
|
||||
taskkill_tree(pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 官方分发包的平台标识(Windows x64 / arm64)。
|
||||
fn platform_arch() -> &'static str {
|
||||
match std::env::consts::ARCH {
|
||||
"aarch64" => "win-arm64",
|
||||
_ => "win-x64",
|
||||
}
|
||||
}
|
||||
|
||||
/// PATH 上查找 node 可执行文件。
|
||||
fn which_node() -> Option<PathBuf> {
|
||||
let name = if cfg!(windows) { "node.exe" } else { "node" };
|
||||
let path_var = std::env::var_os("PATH")?;
|
||||
for dir in std::env::split_paths(&path_var) {
|
||||
let candidate = dir.join(name);
|
||||
if candidate.is_file() {
|
||||
return Some(candidate);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// 取 node 目录下的 npm 入口(`node_modules/npm/bin/npm-cli.js`)。
|
||||
///
|
||||
/// 直接 `node npm-cli.js` 而不是 `npm.cmd`:`.cmd` 在 Windows 上无法被
|
||||
/// CreateProcess 直接执行(需经 `cmd /C`,而 cmd 的引号规则易踩坑),
|
||||
/// 且批处理 shim 会多出一层进程影响取消时的进程树清理。
|
||||
fn npm_cli_js(node_exe: &Path) -> Option<PathBuf> {
|
||||
let dir = node_exe.parent()?;
|
||||
let candidates = [
|
||||
dir.join("node_modules").join("npm").join("bin").join("npm-cli.js"),
|
||||
dir.join("lib").join("node_modules").join("npm").join("bin").join("npm-cli.js"),
|
||||
];
|
||||
candidates.into_iter().find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// 执行 `node --version` 取版本号。
|
||||
fn node_version(node_exe: &Path) -> Option<String> {
|
||||
let mut cmd = std::process::Command::new(node_exe);
|
||||
cmd.arg("--version");
|
||||
cmd.stdout(std::process::Stdio::piped())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.stdin(std::process::Stdio::null());
|
||||
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||
let out = cmd.output().ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
let text = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
(!text.is_empty()).then_some(text)
|
||||
}
|
||||
|
||||
/// 规范化版本号:补上 `v` 前缀。
|
||||
fn normalize_version(raw: &str) -> String {
|
||||
let t = raw.trim();
|
||||
if t.starts_with('v') {
|
||||
t.to_string()
|
||||
} else {
|
||||
format!("v{t}")
|
||||
}
|
||||
}
|
||||
|
||||
/// 解压 zip 并剥掉顶层目录(Node 官方分发包顶层是 `node-vX-win-x64/`)。
|
||||
pub(crate) fn extract_zip_strip_top(zip_path: &Path, dest: &Path) -> Result<(), String> {
|
||||
let file = fs::File::open(zip_path).map_err(|e| format!("打开 zip 失败: {e}"))?;
|
||||
let mut archive = zip::ZipArchive::new(file).map_err(|e| format!("读取 zip 失败: {e}"))?;
|
||||
for i in 0..archive.len() {
|
||||
let mut entry = archive.by_index(i).map_err(|e| format!("读取条目失败: {e}"))?;
|
||||
let Some(name) = entry.enclosed_name() else {
|
||||
continue;
|
||||
};
|
||||
// 剥掉第一层目录;顶层目录条目本身(只有一个组件)跳过
|
||||
let mut comps = name.components();
|
||||
comps.next();
|
||||
let rel: PathBuf = comps.map(|c| c.as_os_str()).collect();
|
||||
if rel.as_os_str().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let outpath = dest.join(&rel);
|
||||
if entry.is_dir() {
|
||||
fs::create_dir_all(&outpath).map_err(|e| e.to_string())?;
|
||||
} else {
|
||||
if let Some(parent) = outpath.parent() {
|
||||
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let mut outfile = fs::File::create(&outpath).map_err(|e| e.to_string())?;
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
let n = entry.read(&mut buf).map_err(|e| e.to_string())?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
outfile.write_all(&buf[..n]).map_err(|e| e.to_string())?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 强杀进程树(安装子进程取消用)。
|
||||
pub(crate) fn taskkill_tree(pid: u64) {
|
||||
let mut cmd = std::process::Command::new("taskkill");
|
||||
cmd.args(["/F", "/T", "/PID", &pid.to_string()])
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null())
|
||||
.stdin(std::process::Stdio::null());
|
||||
crate::process_manager::setup_creation_flags(&mut cmd);
|
||||
let _ = cmd.status();
|
||||
}
|
||||
Reference in new issue
Block a user