Skip to content

DeepSeek Harness Tauri 桌面版 | Only 8mb installer, zero environment setup, preset plugins, Windows / macOS / Linux.

fix(preinstall): 非 ASCII 路径的 shim 按代码页落盘,修复启动卡在 PREINSTALL_FAILED

hairyfc787bc0e0802
diff --git a/src-tauri/src/service/cli/shim/build.rs b/src-tauri/src/service/cli/shim/build.rs
index 1d910ed6..941c7677 100644
--- a/src-tauri/src/service/cli/shim/build.rs
+++ b/src-tauri/src/service/cli/shim/build.rs
@@ -4,7 +4,7 @@
use std::path::{Path, PathBuf};
-use super::escape_path_cmd;
+use super::portable_path_cmd;
use super::escape_path_ps1;
use super::escape_path_sh;
#[cfg(not(windows))]
@@ -92,11 +92,11 @@ exit /b 1
echo [dsh] Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first. 1>&2
exit /b 1
"#,
- node_bin = escape_path_cmd(&paths.node_bin),
- node_dir = escape_path_cmd(&paths.node_dir()),
- git_dir = escape_path_cmd(&paths.git_dir()),
- dsh_bin = escape_path_cmd(&paths.dsh_bin),
- dsh_home = escape_path_cmd(dsh_home),
+ node_bin = portable_path_cmd(&paths.node_bin),
+ node_dir = portable_path_cmd(&paths.node_dir()),
+ git_dir = portable_path_cmd(&paths.git_dir()),
+ dsh_bin = portable_path_cmd(&paths.dsh_bin),
+ dsh_home = portable_path_cmd(dsh_home),
user_dsh = CMD_USER_DSH_PRECEDENCE,
node_resolve = CMD_NODE_RESOLVE,
))
@@ -200,6 +200,10 @@ set "NODE_BIN={node_bin}"
set "NODE_DIR={node_dir}"
set "GIT_DIR={git_dir}"
set "PNPM_BIN={pnpm_bin}"
+rem Runtime override: this file is read through the console code page, so a baked
+rem path containing non-ASCII (e.g. user name) is corrupted on parse. The desktop
+rem app passes the real path in DSH_PNPM_BIN, which arrives as UTF-16 and is safe.
+if exist "%DSH_PNPM_BIN%" set "PNPM_BIN=%DSH_PNPM_BIN%"
rem Use bundled MinGit only when system Git lacks its HTTPS transport helper.
set "SYSTEM_GIT_WORKS="
for /f "delims=" %%g in ('git --exec-path 2^>nul') do if exist "%%g\git-remote-https.exe" set "SYSTEM_GIT_WORKS=1"
@@ -271,10 +275,10 @@ exit /b 1
echo [pnpm] Node.js runtime not found. Please run DeepSeek Harness Desktop to install it first. 1>&2
exit /b 1
"#,
- node_bin = escape_path_cmd(&paths.node_bin),
- node_dir = escape_path_cmd(&paths.node_dir()),
- git_dir = escape_path_cmd(&paths.git_dir()),
- pnpm_bin = escape_path_cmd(&paths.pnpm_bin),
+ node_bin = portable_path_cmd(&paths.node_bin),
+ node_dir = portable_path_cmd(&paths.node_dir()),
+ git_dir = portable_path_cmd(&paths.git_dir()),
+ pnpm_bin = portable_path_cmd(&paths.pnpm_bin),
node_resolve = CMD_NODE_RESOLVE,
))
}
@@ -292,6 +296,9 @@ $nodeBin = '{node_bin}'
$nodeDir = '{node_dir}'
$gitDir = '{git_dir}'
$pnpmBin = '{pnpm_bin}'
+# Runtime override: the baked literal may be non-ASCII; the desktop app passes the
+# real path in DSH_PNPM_BIN (see the cmd shim note).
+if ($env:DSH_PNPM_BIN -and (Test-Path -LiteralPath $env:DSH_PNPM_BIN -PathType Leaf)) {{ $pnpmBin = $env:DSH_PNPM_BIN }}
# Use bundled MinGit only when system Git lacks its HTTPS transport helper.
$systemGitWorks = $false
try {{
@@ -357,6 +364,8 @@ pub fn build_pnpm_sh_shim(paths: &ShimPaths) -> String {
NODE_BIN='{node_bin}'
NODE_DIR='{node_dir}'
PNPM_BIN='{pnpm_bin}'
+# Runtime override: the desktop app passes the real bundled pnpm path here.
+if [ -n "$DSH_PNPM_BIN" ] && [ -f "$DSH_PNPM_BIN" ]; then PNPM_BIN="$DSH_PNPM_BIN"; fi
USE_BUNDLED=
if [ "$DSH_PREFER_BUNDLED_PNPM" = "1" ] && [ -f "$PNPM_BIN" ]; then
diff --git a/src-tauri/src/service/cli/shim/mod.rs b/src-tauri/src/service/cli/shim/mod.rs
index f089a5aa..061ef8d3 100644
--- a/src-tauri/src/service/cli/shim/mod.rs
+++ b/src-tauri/src/service/cli/shim/mod.rs
@@ -41,6 +41,50 @@ pub fn escape_path_cmd(path: &Path) -> String {
path.to_string_lossy().replace('%', "%%")
}
+/// 把路径烘焙进 `.cmd` 前,尽量换成语义等价的纯 ASCII 写法。
+///
+/// cmd.exe 按控制台代码页解析批处理文件:路径含非 ASCII(中文用户名)时,英文
+/// 系统(CP437)根本无法用该代码页表示,`if exist "%PNPM_BIN%"` 必然落空、shim
+/// 以退出码 1 结束。依次尝试:用户目录下的 `%APPDATA%`/`%LOCALAPPDATA%`/
+/// `%USERPROFILE%` 令牌、Windows 8.3 短名;都拿不到纯 ASCII 时才保留原字面量,
+/// 由 write.rs 的按代码页编码兜底。
+pub fn portable_path_cmd(path: &Path) -> String {
+ let text = path.to_string_lossy();
+ if text.is_ascii() {
+ return escape_path_cmd(path);
+ }
+ for (var, token) in [
+ ("APPDATA", "%APPDATA%"),
+ ("LOCALAPPDATA", "%LOCALAPPDATA%"),
+ ("USERPROFILE", "%USERPROFILE%"),
+ ] {
+ let Some(root) = std::env::var_os(var) else {
+ continue;
+ };
+ if let Some(rendered) = under_root(path, Path::new(&root), token) {
+ return rendered;
+ }
+ }
+ // 令牌之外的路径(如 `D:\软件\nodejs`)用 8.3 短名换回 ASCII;卷上关掉
+ // 短名或路径不存在时拿回的仍是长名,此处按 is_ascii 拒绝。
+ #[cfg(windows)]
+ if let Some(short) = crate::utils::short_path(path) {
+ if short.to_string_lossy().is_ascii() {
+ return escape_path_cmd(&short);
+ }
+ }
+ escape_path_cmd(path)
+}
+
+/// `path` 在 `root` 之下时渲染成 `<token>\<其余部分>`,其余部分按批处理转义。
+fn under_root(path: &Path, root: &Path, token: &str) -> Option<String> {
+ let rest = path.strip_prefix(root).ok()?;
+ if rest.as_os_str().is_empty() {
+ return None;
+ }
+ Some(format!("{token}\\{}", escape_path_cmd(rest)))
+}
+
/// 单引号字符串中 `'` 需翻倍
#[inline]
pub fn escape_path_ps1(path: &Path) -> String {
@@ -158,4 +202,55 @@ mod tests {
);
assert_eq!(escape_path_sh(Path::new("/plain/.dsh")), "/plain/.dsh");
}
+
+ // ------------------------------------------------------------------
+ // 非 ASCII 路径的 ASCII 令牌改写(cmd.exe 按代码页读批处理)
+ // ------------------------------------------------------------------
+
+ /// 中文用户名下的 AppData 路径必须退化成 `%APPDATA%` 令牌:英文系统
+ /// (CP437)用代码页也编不出这些字符,只有纯 ASCII 才与代码页无关。
+ #[test]
+ #[cfg(windows)]
+ fn portable_path_cmd_renders_non_ascii_user_paths_as_tokens() {
+ let root = Path::new(r"C:\Users\小蔡\AppData\Roaming");
+ assert_eq!(
+ under_root(
+ Path::new(r"C:\Users\小蔡\AppData\Roaming\dsh-tauri\dependencies\pnpm\bin\pnpm.cjs"),
+ root,
+ "%APPDATA%",
+ )
+ .as_deref(),
+ Some(r"%APPDATA%\dsh-tauri\dependencies\pnpm\bin\pnpm.cjs")
+ );
+ assert_eq!(
+ under_root(Path::new(r"C:\Users\小蔡\.dsh"), Path::new(r"C:\Users\小蔡"), "%USERPROFILE%")
+ .as_deref(),
+ Some(r"%USERPROFILE%\.dsh")
+ );
+ // 令牌之外没有剩余内容、或路径不在根下时不改写。
+ assert_eq!(under_root(root, root, "%APPDATA%"), None);
+ assert_eq!(
+ under_root(Path::new(r"D:\tools\x"), root, "%APPDATA%"),
+ None
+ );
+ // 其余部分仍按批处理转义。
+ assert_eq!(
+ under_root(Path::new(r"C:\Users\小蔡\a%20b"), Path::new(r"C:\Users\小蔡"), "%USERPROFILE%")
+ .as_deref(),
+ Some(r"%USERPROFILE%\a%%20b")
+ );
+ }
+
+ /// 纯 ASCII 路径逐字节走原逻辑(不留令牌、不做无谓改写)。
+ #[test]
+ fn portable_path_cmd_keeps_ascii_paths_verbatim() {
+ assert_eq!(
+ portable_path_cmd(Path::new(r"C:\Users\test\AppData\Roaming\dsh-tauri\pnpm.cjs")),
+ r"C:\Users\test\AppData\Roaming\dsh-tauri\pnpm.cjs"
+ );
+ assert_eq!(
+ portable_path_cmd(Path::new(r"C:\tools\100%\pnpm.cjs")),
+ r"C:\tools\100%%\pnpm.cjs"
+ );
+ }
}
diff --git a/src-tauri/src/service/cli/shim/write.rs b/src-tauri/src/service/cli/shim/write.rs
index bd99149a..4fa3c530 100644
--- a/src-tauri/src/service/cli/shim/write.rs
+++ b/src-tauri/src/service/cli/shim/write.rs
@@ -1,4 +1,5 @@
-//! shim 落盘:生成标记识别、悬空符号链接处理、用户文件保留与写入编排。
+//! shim 落盘:生成标记识别、悬空符号链接处理、用户文件保留、按外部解析方的
+//! 代码页编码(cmd 用系统代码页、ps1 用带 BOM 的 UTF-8)与写入编排。
use crate::config;
use std::fs;
@@ -54,8 +55,8 @@ fn is_dangling_symlink(path: &Path) -> bool {
/// 后的第二行)写 #/rem DeepSeek Harness Desktop - ...;用户文件即使正文
/// 提到同样的短语(如 README 引用)也不应被误判为本应用 shim。
pub fn is_generated_shim(path: &Path) -> bool {
- match std::fs::read_to_string(path) {
- Ok(content) => content
+ match std::fs::read(path) {
+ Ok(bytes) => String::from_utf8_lossy(&bytes)
.lines()
.take(2)
.any(|line| line.contains(GENERATED_MARKER)),
@@ -63,6 +64,43 @@ pub fn is_generated_shim(path: &Path) -> bool {
}
}
+/// shim 落盘编码。
+///
+/// cmd.exe 按控制台代码页(中文 Windows 为 936)读取 `.cmd`,PowerShell 5.1 只认
+/// 带 BOM 的 UTF-8 `.ps1`。此前一律写 UTF-8:一旦烘焙进内容的绝对路径含非 ASCII
+/// (用户名 `小蔡`、含中文的安装目录),`if exist "%PNPM_BIN%"` 判定就落空,shim
+/// 走 `:no_pnpm` 以退出码 1 结束,`dsh plugin add` 随之失败并让 Harness 启动停在
+/// `INTERNAL_PLUGIN_INSTALL_FAILED: PREINSTALL_FAILED`(重试/安全模式都走同一条
+/// preinstall,因此永远无法恢复)。纯 ASCII 内容保持原字节,行为完全不变。
+fn encode_shim(target: &Path, content: &str) -> Vec<u8> {
+ #[cfg(not(windows))]
+ let _ = target;
+ if content.is_ascii() {
+ return content.as_bytes().to_vec();
+ }
+ #[cfg(windows)]
+ match target.extension().and_then(|ext| ext.to_str()) {
+ Some("cmd") | Some("bat") => {
+ if let Some(bytes) =
+ crate::utils::encode_multibyte(content, crate::utils::console_code_page())
+ {
+ return bytes;
+ }
+ log::warn!(
+ "Shim {target:?} contains characters the console code page cannot represent; \
+ falling back to utf-8, its baked paths will not resolve"
+ );
+ }
+ Some("ps1") => {
+ let mut bytes = vec![0xEF, 0xBB, 0xBF];
+ bytes.extend_from_slice(content.as_bytes());
+ return bytes;
+ }
+ _ => {}
+ }
+ content.as_bytes().to_vec()
+}
+
/// 写入单个 shim 文件,处理目标已存在时的三种情形:
///
/// 1. 悬空符号链接(用户/官方安装器残留、目标已失效)→ 移除链接后正常写入;
@@ -88,7 +126,7 @@ fn write_shim_file(target: &Path, content: &str) -> Result<(), String> {
);
return Ok(());
}
- fs::write(target, content)
+ fs::write(target, encode_shim(target, content))
.map_err(|e| format!("SHIM_WRITE_FAILED: write {} failed: {e}", target.display()))
}
@@ -379,4 +417,97 @@ mod tests {
);
let _ = std::fs::remove_dir_all(&dir);
}
+
+ /// 非 ASCII 路径(用户名 `小蔡`)必须按 cmd.exe 的解析代码页落盘,
+ /// 否则 `if exist "%PNPM_BIN%"` 判定落空、shim 以退出码 1 结束。
+ #[test]
+ #[cfg(windows)]
+ fn cmd_shim_with_non_ascii_path_uses_console_code_page() {
+ let dir = temp_dir("non-ascii-cmd");
+ let target = dir.join("pnpm.cmd");
+ let content = "@echo off\r\nrem DeepSeek Harness Desktop - pnpm command shim (generated)\r\nset \"PNPM_BIN=C:\\Users\\小蔡\\pnpm.cjs\"\r\n";
+ assert!(!content.is_ascii());
+
+ write_shim_file(&target, content).unwrap();
+
+ let bytes = std::fs::read(&target).unwrap();
+ let codepage = crate::utils::console_code_page();
+ match crate::utils::encode_multibyte(content, codepage) {
+ Some(encoded) => {
+ assert_ne!(
+ bytes,
+ content.as_bytes(),
+ "non-ascii cmd shim must not be written as raw utf-8"
+ );
+ assert_eq!(bytes, encoded);
+ assert_eq!(
+ crate::utils::decode_multibyte(&bytes, codepage).as_deref(),
+ Some(content),
+ "cmd shim must round-trip through the console code page"
+ );
+ }
+ // 英文系统(CP437)表示不了中文用户名:只能退回原字节,应用侧靠
+ // DSH_PNPM_BIN 与 portable_path_cmd 的 ASCII 令牌兜底。
+ None => assert_eq!(bytes, content.as_bytes()),
+ }
+ assert!(
+ !is_foreign_file(&target),
+ "code-page encoded shim must still be recognised as generated"
+ );
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// PowerShell 5.1 只认带 BOM 的 UTF-8;无 BOM 的非 ASCII `.ps1` 会按 ANSI 读成乱码。
+ #[test]
+ #[cfg(windows)]
+ fn ps1_shim_with_non_ascii_path_gets_utf8_bom() {
+ let dir = temp_dir("non-ascii-ps1");
+ let target = dir.join("pnpm.ps1");
+ let content =
+ "# DeepSeek Harness Desktop - pnpm command shim (generated)\r\n$pnpmBin = 'C:\\Users\\小蔡\\pnpm.cjs'\r\n";
+
+ write_shim_file(&target, content).unwrap();
+
+ let bytes = std::fs::read(&target).unwrap();
+ assert_eq!(&bytes[..3], &[0xEF, 0xBB, 0xBF], "ps1 shim needs a utf-8 bom");
+ assert_eq!(
+ std::fs::read_to_string(&target).unwrap().trim_start_matches('\u{feff}'),
+ content
+ );
+ assert!(!is_foreign_file(&target));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// ASCII 内容必须逐字节保持原样:历史落盘文件与既有断言都不受影响。
+ #[test]
+ fn ascii_shim_bytes_are_unchanged() {
+ let dir = temp_dir("ascii-bytes");
+ let target = dir.join("pnpm.cmd");
+ let content = "@echo off\r\nset \"PNPM_BIN=C:\\tools\\pnpm.cjs\"\r\n";
+
+ write_shim_file(&target, content).unwrap();
+
+ assert_eq!(std::fs::read(&target).unwrap(), content.as_bytes());
+ let _ = std::fs::remove_dir_all(&dir);
+ }
+
+ /// 代码页编码后仍是本应用生成的文件,下一次 `ensure_shims` 才能覆盖自愈。
+ #[test]
+ #[cfg(windows)]
+ fn code_page_encoded_shim_stays_overwritable() {
+ let dir = temp_dir("codepage-overwrite");
+ let target = dir.join("pnpm.cmd");
+ let header = "@echo off\r\nrem DeepSeek Harness Desktop - pnpm command shim (generated)\r\n";
+ write_shim_file(&target, &format!("{header}rem C:\\Users\\小蔡\r\n")).unwrap();
+ assert!(!is_foreign_file(&target));
+
+ write_shim_file(&target, &format!("{header}rem C:\\Users\\小蔡\\fixed\r\n")).unwrap();
+
+ let codepage = crate::utils::console_code_page();
+ let fixed = format!("{header}rem C:\\Users\\小蔡\\fixed\r\n");
+ let expected = crate::utils::encode_multibyte(&fixed, codepage)
+ .unwrap_or_else(|| fixed.as_bytes().to_vec());
+ assert_eq!(std::fs::read(&target).unwrap(), expected);
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
diff --git a/src-tauri/src/service/plugin/install/diagnose.rs b/src-tauri/src/service/plugin/install/diagnose.rs
index f9e75bc7..bb0eaf9c 100644
--- a/src-tauri/src/service/plugin/install/diagnose.rs
+++ b/src-tauri/src/service/plugin/install/diagnose.rs
@@ -12,6 +12,29 @@ pub(super) fn diagnostic_suffix(detail: &str) -> String {
}
}
+/// 命中即视为可展示错误行的标记。除 pnpm/Node 的常规错误外,还覆盖「命令或
+/// shim 不可用」一类失败:cmd.exe 的 `'pnpm' is not recognized…`、shim 的
+/// `[pnpm] pnpm not found…`、批处理跳转失败 `The system cannot find the batch
+/// label…`,以及中文 cmd 文案。这些行不含 `error`/`failed`,一旦被过滤掉,
+/// 用户只会看到 dsh 包装后的 `pnpm failed in profile directory`,真实原因
+/// (shim 不可用)永远不可见。
+const ERROR_MARKERS: [&str; 14] = [
+ "ERR_",
+ "error",
+ "Error",
+ "failed",
+ "✖",
+ "warning",
+ "not recognized",
+ "not found",
+ "No such file",
+ "cannot find",
+ "Cannot find",
+ "找不到",
+ "无法",
+ "不是内部或外部命令",
+];
+
/// 从 dsh/pnpm 失败输出中提取可展示的错误消息:优先 git 传输层提示;
/// 否则挑出命中错误标记的行(最多 8 行),没有则取输出尾部,ANSI 清洗后
/// 截断到 2000 字符。
@@ -26,14 +49,7 @@ pub(super) fn pick_error_message(output: &str, hint: Option<&str>) -> String {
let trimmed = trimmed.trim();
(!trimmed.is_empty()).then(|| trimmed.to_string())
})
- .filter(|line| {
- line.contains("ERR_")
- || line.contains("error")
- || line.contains("Error")
- || line.contains("failed")
- || line.contains("✖")
- || line.contains("warning")
- })
+ .filter(|line| ERROR_MARKERS.iter().any(|marker| line.contains(marker)))
.take(8)
.collect();
let base = if cleaned.is_empty() {
@@ -216,6 +232,35 @@ mod tests {
// ---- git 传输层错误识别(区别于 allowBuilds 门禁)----
+ /// shim 不可用时 cmd.exe / shim 自己的原话,不含 `error`/`failed`:
+ /// 若被过滤掉,用户只剩 dsh 的 `pnpm failed in profile directory`。
+ #[test]
+ fn pick_error_message_keeps_shim_unavailable_lines() {
+ let out = "dsh: pnpm failed in profile directory C:\\Users\\小蔡\\.dsh\\profiles\\safe\n\
+ [pnpm] pnpm not found. Please run DeepSeek Harness Desktop to install it first.\n";
+ let picked = pick_error_message(out, None);
+ assert!(
+ picked.contains("pnpm not found"),
+ "shim diagnostic must survive: {picked}"
+ );
+
+ let cmd = "'pnpm' is not recognized as an internal or external command,\noperable program or batch file.\n";
+ assert!(pick_error_message(cmd, None).contains("not recognized"));
+
+ let label = "The system cannot find the batch label specified - no_pnpm\n";
+ assert!(pick_error_message(label, None).contains("batch label"));
+ }
+
+ #[test]
+ fn pick_error_message_still_drops_noise() {
+ let out = "Progress: resolved 1, reused 0, downloaded 0\n\
+ ERR_PNPM_LINKING_FAILED: stale symlink\n\
+ Done in 2.8s\n";
+ let picked = pick_error_message(out, None);
+ assert!(picked.contains("ERR_PNPM_LINKING_FAILED"));
+ assert!(!picked.contains("Done in"), "progress noise must be dropped: {picked}");
+ }
+
#[test]
fn git_transport_hint_detects_host_key_failure() {
let out = "git ls-remote \"git+ssh://[email protected]/foo.git\" HEAD\nHost key verification failed.\nfatal: Could not read from remote repository.\n";
diff --git a/src-tauri/src/service/plugin/install/env.rs b/src-tauri/src/service/plugin/install/env.rs
index bec8d6dc..8603769f 100644
--- a/src-tauri/src/service/plugin/install/env.rs
+++ b/src-tauri/src/service/plugin/install/env.rs
@@ -67,6 +67,19 @@ pub(crate) fn build_plugin_envs(
}
}
+ // 捆绑 pnpm 的绝对路径也显式下传(shim 优先采用 `DSH_PNPM_BIN`):shim 内
+ // 烘焙的字面量要经 cmd.exe/PowerShell 的代码页解析,用户名含非 ASCII(如
+ // `C:\Users\小蔡\...`)时会被读成乱码,`if exist "%PNPM_BIN%"` 判定落空 →
+ // shim 走 `:no_pnpm` 以退出码 1 结束,安装只报 `PREINSTALL_FAILED`。
+ // 环境变量块是 UTF-16,不受代码页影响。
+ let bundled_pnpm = config::get_pnpm_binary_path(app_handle);
+ if bundled_pnpm.exists() {
+ envs.insert(
+ "DSH_PNPM_BIN".to_string(),
+ bundled_pnpm.to_string_lossy().into_owned(),
+ );
+ }
+
// 档案 node_modules 是用哪份 store 装的,是既有事实:pnpm 只在「自己解析出的 store」
// 与 `node_modules/.modules.yaml` 记录的一致时才继续,否则直接
// `ERR_PNPM_UNEXPECTED_STORE` 退出(该错误与插件本身无关,用户看到的是「插件安装失败」)。
diff --git a/src-tauri/src/utils/mod.rs b/src-tauri/src/utils/mod.rs
index ce424c30..229888d6 100644
--- a/src-tauri/src/utils/mod.rs
+++ b/src-tauri/src/utils/mod.rs
@@ -147,7 +147,7 @@ pub fn decode_process_line(bytes: &[u8]) -> String {
/// 按给定代码页把多字节串解成 UTF-16,再取 `String`;转换失败返回 `None`。
#[cfg(windows)]
-fn decode_multibyte(bytes: &[u8], codepage: u32) -> Option<String> {
+pub(crate) fn decode_multibyte(bytes: &[u8], codepage: u32) -> Option<String> {
use windows_sys::Win32::Globalization::MultiByteToWideChar;
if bytes.is_empty() {
@@ -174,11 +174,119 @@ fn decode_multibyte(bytes: &[u8], codepage: u32) -> Option<String> {
Some(String::from_utf16_lossy(&wide))
}
+/// 按给定代码页把文本编码成多字节串;出现该代码页无法表示的字符时返回 `None`。
+///
+/// 与 [`decode_process_line`] 对称:写入交给外部程序按系统代码页解析的文件
+/// (`.cmd`/`.bat`)时,UTF-8 字节会被读成乱码。带 `WC_NO_BEST_FIT_CHARS`:
+/// 否则 `∞` 这类字符会被「近似」成 `8`,编出一条指向别处的路径却报成功。
+#[cfg(windows)]
+pub(crate) fn encode_multibyte(text: &str, codepage: u32) -> Option<Vec<u8>> {
+ use windows_sys::Win32::Globalization::{WideCharToMultiByte, CP_UTF8, WC_NO_BEST_FIT_CHARS};
+
+ if text.is_empty() {
+ return Some(Vec::new());
+ }
+ // UTF-8 能表示 Rust `str` 的全部字符(无落单代理项),且该代码页不接受
+ // `lpUsedDefaultChar`;直接给出等价字节。
+ if codepage == CP_UTF8 {
+ return Some(text.as_bytes().to_vec());
+ }
+ let wide: Vec<u16> = text.encode_utf16().collect();
+ if wide.len() > i32::MAX as usize {
+ return None;
+ }
+ let len = wide.len() as i32;
+ let mut used_default = 0i32;
+ // SAFETY: 指针与长度同源于 `wide`;空缓冲 + 0 长度只探测所需字节数。
+ let needed = unsafe {
+ WideCharToMultiByte(
+ codepage,
+ WC_NO_BEST_FIT_CHARS,
+ wide.as_ptr(),
+ len,
+ std::ptr::null_mut(),
+ 0,
+ std::ptr::null(),
+ &mut used_default,
+ )
+ };
+ if needed <= 0 {
+ return None;
+ }
+ let mut bytes = vec![0u8; needed as usize];
+ used_default = 0;
+ // SAFETY: `bytes` 恰有 `needed` 个元素,等于上一次探测出的所需长度。
+ let written = unsafe {
+ WideCharToMultiByte(
+ codepage,
+ WC_NO_BEST_FIT_CHARS,
+ wide.as_ptr(),
+ len,
+ bytes.as_mut_ptr(),
+ needed,
+ std::ptr::null(),
+ &mut used_default,
+ )
+ };
+ if written <= 0 || used_default != 0 {
+ return None;
+ }
+ bytes.truncate(written as usize);
+ Some(bytes)
+}
+
+/// 路径的 Windows 8.3 短名(纯 ASCII),长名含非 ASCII 时用它烘焙进 `.cmd`。
+///
+/// 短名由卷上的 8dot3 机制维护:路径不存在、或该卷已关闭短名时返回 `None`
+/// (此时 API 原样返回长名,调用方据 `is_ascii` 判定不可用)。
+#[cfg(windows)]
+pub(crate) fn short_path(path: &Path) -> Option<PathBuf> {
+ use std::os::windows::ffi::{OsStrExt, OsStringExt};
+ use windows_sys::Win32::Storage::FileSystem::GetShortPathNameW;
+
+ let wide: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
+ // SAFETY: 空缓冲 + 0 长度只探测所需长度(含结尾 NUL);指针来自 `wide`。
+ let needed = unsafe { GetShortPathNameW(wide.as_ptr(), std::ptr::null_mut(), 0) };
+ if needed == 0 {
+ return None;
+ }
+ let mut buf = vec![0u16; needed as usize];
+ // SAFETY: `buf` 恰有 `needed` 个元素,等于上一次探测出的所需长度。
+ let written = unsafe { GetShortPathNameW(wide.as_ptr(), buf.as_mut_ptr(), needed) };
+ if written == 0 || written >= needed {
+ return None;
+ }
+ buf.truncate(written as usize);
+ Some(PathBuf::from(std::ffi::OsString::from_wide(&buf)))
+}
+
+/// 外部程序(cmd.exe)解析文本文件所用的代码页:优先 OEM,其次 ANSI。
+///
+/// 批处理文件由 cmd.exe 按控制台代码页读取(中文 Windows 为 936),因此把带
+/// 非 ASCII 路径的 `.cmd` 写成 UTF-8 必然乱码。取不到时回落 UTF-8 代码页,
+/// 调用方据此退回原字节写出。
+#[cfg(windows)]
+pub(crate) fn console_code_page() -> u32 {
+ use windows_sys::Win32::Globalization::{GetACP, GetOEMCP};
+
+ // SAFETY: 两个 API 都无参数、无副作用,仅返回系统代码页常量。
+ let oem = unsafe { GetOEMCP() };
+ if oem != 0 {
+ return oem;
+ }
+ // SAFETY: 同上。
+ let ansi = unsafe { GetACP() };
+ if ansi != 0 {
+ return ansi;
+ }
+ 65001
+}
+
#[cfg(test)]
mod tests {
use super::decode_process_line;
#[cfg(windows)]
- use super::decode_multibyte;
+ use super::{decode_multibyte, encode_multibyte, short_path};
#[test]
fn keeps_valid_utf8_untouched() {
@@ -204,4 +312,31 @@ mod tests {
Some("系统找不到指定的路径。")
);
}
+
+ #[cfg(windows)]
+ #[test]
+ fn encodes_back_to_the_same_codepage_bytes() {
+ let text = "系统找不到指定的路径。";
+ let gbk = encode_multibyte(text, 936).expect("gbk");
+ assert!(!gbk.is_ascii());
+ assert_eq!(decode_multibyte(&gbk, 936).as_deref(), Some(text));
+ // UTF-8 代码页不看 `lpUsedDefaultChar`,直接给出等价字节。
+ assert_eq!(encode_multibyte(text, 65001).as_deref(), Some(text.as_bytes()));
+ }
+
+ /// 该代码页表示不了的字符必须报 `None`,不能靠「近似字符」蒙混过关。
+ #[cfg(windows)]
+ #[test]
+ fn rejects_characters_outside_the_codepage() {
+ assert_eq!(encode_multibyte("小蔡", 437), None);
+ }
+
+ /// 短名只在路径存在且卷上保留 8dot3 时才有;拿不到时调用方按 `is_ascii` 拒绝。
+ #[cfg(windows)]
+ #[test]
+ fn short_path_resolves_existing_paths() {
+ let temp = std::env::temp_dir();
+ let short = short_path(&temp).expect("temp dir always resolves");
+ assert!(short.exists());
+ }
}