Compare commits

..

9 Commits

Author SHA1 Message Date
Serendipity 78439a6ac6 chore: update Cargo.lock for v5.1.0 build
CI / 前端检查 (TypeScript + Lint + Test) (push) Has been cancelled
CI / Rust 检查 (Check + Clippy + Test) (push) Has been cancelled
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-30 17:35:07 +08:00
Serendipity e0e3c802dd chore: bump version to 5.1.0
Cargo.toml / package.json / tauri.conf.json / README badge

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-30 17:33:41 +08:00
Serendipity 21da3b2930 fix: v5.1 代码审查修复 — ESLint/CSV/测试隔离/CLI 去重
- ESLint: 迁移到 flat config ignores,删除已废弃的 .eslintignore
- CSV: Rust/TS 格式对齐,统一 type,path,enabled 3 列
- JSON: 导入导出统一为 {path, enabled} 对象格式
- scanner: 移除未使用的 max_threads 死代码 + TempDirGuard 测试清理
- profiles: rename_profile 添加目标存在检查
- CLI: 抽取 load_operate_save helper,简化 cmd_remove/cmd_edit
- PathTable: 抽取 usePathValidation hook,消除 set-state-in-effect
- 测试隔离: disabled/profiles 通过 #[cfg(test)] 重定向到 temp dir
- toolchain: 新增 rust-toolchain.toml 固定 stable-x86_64-pc-windows-gnu
- docs: 更新 CLAUDE.md/README.md 测试计数 + 架构树

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-30 17:31:04 +08:00
Serendipity bce2dc8641 fix: E2E mock 统一 + CSV 引号字段解析
E2E:
- createIpcMock 支持 overrides 参数,保持 default: throw 行为
- search-clean.spec.ts 删除 30 行内联 mock,改用 createIpcMock(overrides)

Rust:
- 新增 parse_csv_line: 支持引号包裹字段 + 双引号转义 (RFC 4180 子集)
- import_csv 改用 parse_csv_line 替代 split(',')
- 与 TS 端 parseCsvLine 逻辑对称

测试: Rust 48 → 52 (+4), Frontend 100

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 23:51:28 +08:00
Serendipity 461ef231e4 test: useAppActions 15 个测试用例 — 覆盖全部导出函数
handleNew / handleEdit / handleDelete / handleMoveUp / handleMoveDown
/ handleClean / handleImportSelect / handleNewConfirm / handleEditConfirm
/ handleSave (正常 + 超长确认)

前端测试: 85 → 100

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 23:38:38 +08:00
Serendipity e5b348bb9b fix: e2e 类型声明 + ESLint 覆盖 e2e + backup 路径校验 + DX 脚本
- e2e/global.d.ts: Window.__TAURI_INTERNALS__ 类型声明
- e2e search-clean: 未使用参数 _args 前缀
- tsconfig.test.json: include e2e/
- CI: ESLint 扫描范围扩展到 e2e/
- backup_registry: 拒绝写入系统目录 (C:\Windows\, C:\Program Files\)
- package.json: 新增 lint:fix / format 脚本

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 23:23:51 +08:00
Serendipity cbf99f12fd v5.1: 全面代码审查修复 — 安全加固 + 功能修复 + 测试补全 + 工程化
安全修复 (CRITICAL):
- 启用 CSP (default-src 'self')
- read_text_file 限制文件扩展名白名单 (.json/.csv/.txt)
- capabilities 显式声明窗口权限
- profile 名校验增强 (null 字节/控制字符/长度限制)

功能修复 (HIGH):
- AnalyzeDialog 重新打开时正确刷新数据
- UndoRedoButtons 订阅路径长度变化确保响应性
- 禁用状态持久化错误处理 (.catch → console.warn)
- 硬编码中文全部迁移到 i18n (6 处)
- PATH 长度检查改用 UTF-16 字符计数
- PATH 写入前 null 字节校验
- CLI export 拒绝写入系统目录
- savePaths 职责分离: window.confirm → Tauri ask() 对话框

代码质量 (MEDIUM):
- 导入路径统一过滤 (sanitize_paths: null 字节/分号/空白)
- 原子写入 (atomic_write: disabled.json + profiles)
- 验证缓存自动清理 (PathTable useEffect)
- Scanner 线程错误处理改进 (.unwrap → .map_err)
- Ctrl+F 去重 (移除 use-keyboard 重复处理)
- Profile 路径列表 key 修复 (index → path)
- 生产构建启用日志插件 (Warn 级别)
- export_paths JSON 序列化改 expect

测试:
- Rust: 35 → 48 测试 (+13)
- Frontend: 80 → 85 测试 (+5)
- Vitest 全局 jsdom + 覆盖率阈值 (80%)
- 安装 @vitest/coverage-v8 + test:coverage 脚本
- 移除未使用的 @testing-library/jest-dom

工程化:
- CI 添加 Cargo 缓存 (Swatinem/rust-cache@v2)
- CI 添加 cargo fmt --check
- tsconfig.test.json 覆盖测试文件类型检查
- cargo fmt 全量格式化

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 23:17:27 +08:00
Serendipity 5c73321ce6 fix: 修复 ESLint set-state-in-effect 错误 — useEffect 加 prevOpen 守卫
CI / Rust 检查 (Check + Clippy + Test) (push) Has been cancelled
CI / 前端检查 (TypeScript + Lint + Test) (push) Has been cancelled
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 17:02:55 +08:00
Serendipity 44cd6c6595 fix: CI 修复 tsc 项目引用 + ESLint 限制扫描范围 + 新增 .eslintignore
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 16:53:52 +08:00
54 changed files with 1656 additions and 516 deletions
+7 -2
View File
@@ -25,10 +25,10 @@ jobs:
- run: npm ci
- name: TypeScript 类型检查
run: npx tsc --noEmit
run: npx tsc -b --noEmit
- name: ESLint
run: npm run lint
run: npx eslint src/ tests/ e2e/
- name: Vitest 测试
run: npm test
@@ -39,6 +39,8 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: Swatinem/rust-cache@v2
- name: Cargo Check
run: cargo check
@@ -47,3 +49,6 @@ jobs:
- name: Cargo Test
run: cargo test
- name: Cargo Format Check
run: cargo fmt --check
+1
View File
@@ -23,6 +23,7 @@ dist-ssr
*.sln
*.sw?
.claude/
.codegraph/
CLAUDE.md
e2e/debug-screenshot.png
test-results/
+4 -2
View File
@@ -65,11 +65,13 @@ PathEditor/
│ │ ├── toolbar/ # ToolBar、ActionButtons、UndoRedoButtons
│ │ ├── dialogs/ # PathEdit、Help、Import、Analyze、Profile
│ │ └── ui/ # Modal、buttons
│ ├── hooks/ # useAppActions、useKeyboard
│ ├── hooks/ # useAppActions、useKeyboard、usePathValidation
│ ├── i18n/ # zh-CN / en
│ └── config/ # default.json
├── docs/ # REMaining-ISSUES 等审查文档
├── tests/unit/ # Vitest 前端单元测试
├── e2e/ # Playwright E2E 测试
├── rust-toolchain.toml # 固定工具链版本
└── Cargo.toml # Workspace 根 + [workspace.package]
```
@@ -144,7 +146,7 @@ patheditor profile {list|save|load|apply|delete|rename}
## 关键约束
- **TypeScript**`strict: true`,零编译错误
- **Rust 工具链**`stable-x86_64-pc-windows-gnu`项目已设 override
- **Rust 工具链**`stable-x86_64-pc-windows-gnu``rust-toolchain.toml` 强制
- **MinGW 兼容**`.cargo/config.toml` 添加 `-lmcfgthread`GCC 15.2.0 运行时)
- **运行权限**:需要管理员权限才能编辑系统 PATH,非管理员自动进入只读模式
- **构建产物**NSIS 安装包,约 8MB
Generated
+3 -3
View File
@@ -2379,7 +2379,7 @@ dependencies = [
[[package]]
name = "path-editor-core"
version = "5.0.0"
version = "5.1.0"
dependencies = [
"chrono",
"dirs 5.0.1",
@@ -2391,7 +2391,7 @@ dependencies = [
[[package]]
name = "patheditor"
version = "5.0.0"
version = "5.1.0"
dependencies = [
"log",
"path-editor-core",
@@ -2404,7 +2404,7 @@ dependencies = [
[[package]]
name = "patheditor-cli"
version = "5.0.0"
version = "5.1.0"
dependencies = [
"clap",
"path-editor-core",
+1 -1
View File
@@ -7,7 +7,7 @@ members = [
]
[workspace.package]
version = "5.0.0"
version = "5.1.0"
edition = "2021"
license = "MIT"
authors = ["刘航宇"]
+12 -5
View File
@@ -4,13 +4,13 @@
</p>
<p align="center">
<img src="https://img.shields.io/badge/version-5.0.0-blue" alt="version">
<img src="https://img.shields.io/badge/version-5.1.0-blue" alt="version">
<img src="https://img.shields.io/badge/tauri-2.x-ffa03a" alt="tauri">
<img src="https://img.shields.io/badge/react-19-61dafb" alt="react">
<img src="https://img.shields.io/badge/rust-1.95-000000" alt="rust">
<img src="https://img.shields.io/badge/typescript-strict-blue" alt="typescript">
<img src="https://img.shields.io/badge/license-MIT-green" alt="license">
<img src="https://img.shields.io/badge/tests-72%20passed-brightgreen" alt="tests">
<img src="https://img.shields.io/badge/tests-157%20passed-brightgreen" alt="tests">
<img src="https://github.com/LHY0125/PathEditor/actions/workflows/ci.yml/badge.svg" alt="CI">
</p>
@@ -172,6 +172,7 @@ patheditor profile apply "Python开发"
## 功能
### 路径管理
- 查看和编辑 **系统 PATH**HKLM)和 **用户 PATH**HKCU
- 新建、编辑、删除、上移、下移路径条目
- 多选批量删除
@@ -180,26 +181,31 @@ patheditor profile apply "Python开发"
- 文件夹拖拽添加
### 路径验证
- **红色**标记:路径在文件系统中不存在
- **橙色**标记:路径在列表中重复出现
- 环境变量路径(含 `%VAR%`)悬浮展开预览
### 撤销/重做
- 支持 9 种操作类型,最多 50 步历史
- 新增、删除、编辑、移动、清理、清空、导入均可撤销
### 导入/导出
- **JSON**:结构化导出,含版本和时间戳
- **CSV**UTF-8 BOM 编码,兼容 Excel
- **TXT**:纯文本,每行一个路径
### 安全
- 保存前自动备份注册表到 `%APPDATA%/PathEditor/backups/`
- PATH 长度检查(Windows 单变量上限 32767 字符)
- 非管理员自动进入**只读模式**
- 保存中途失败精确提示哪个注册表 hive 出错
### 界面
- 深色模式 / 浅色模式
- 中文 / English 界面切换
- 全局键盘快捷键
@@ -253,8 +259,8 @@ npx tauri build
| 国际化 | i18next |
| 桌面框架 | Tauri 2.x |
| 核心库 | Rust workspace (core + gui + cli) |
| 前端测试 | Vitest (72 个测试) |
| Rust 测试 | cargo test (10 个测试) |
| 前端测试 | Vitest (100 个测试) |
| Rust 测试 | cargo test (57 个测试) |
| 构建 | Vite + Cargo |
| 打包 | NSIS |
@@ -276,10 +282,11 @@ src/ # React 前端
├── core/ # 纯逻辑 — 零框架依赖
├── store/ # Zustand 状态管理
├── components/ # UI 组件
├── hooks/ # useAppActions、useKeyboard
├── hooks/ # useAppActions、useKeyboard、usePathValidation
├── i18n/ # zh-CN / en
└── config/ # default.json
tests/unit/ # 前端单元测试
docs/ # 审查文档
```
## 快捷键
+282 -100
View File
@@ -13,79 +13,109 @@ struct Cli {
enum Command {
/// 列出 PATH 路径
List {
#[arg(short, long)] system: bool,
#[arg(short, long)] user: bool,
#[arg(long)] json: bool,
#[arg(short, long)]
system: bool,
#[arg(short, long)]
user: bool,
#[arg(long)]
json: bool,
},
/// 添加一条路径
Add {
path: String,
#[arg(short, long)] system: bool,
#[arg(short, long)] user: bool,
#[arg(short, long)]
system: bool,
#[arg(short, long)]
user: bool,
},
/// 删除指定位置的路径
Remove {
index: usize,
#[arg(short, long)] system: bool,
#[arg(short, long)]
system: bool,
},
/// 编辑指定位置的路径
Edit {
index: usize,
new_path: String,
#[arg(short, long)] system: bool,
#[arg(short, long)]
system: bool,
},
/// 上移路径(--steps 指定移动格数,默认 1)
MoveUp {
index: usize,
#[arg(long, default_value = "1")] steps: usize,
#[arg(short, long)] system: bool,
#[arg(long, default_value = "1")]
steps: usize,
#[arg(short, long)]
system: bool,
},
/// 下移路径(--steps 指定移动格数,默认 1)
MoveDown {
index: usize,
#[arg(long, default_value = "1")] steps: usize,
#[arg(short, long)] system: bool,
#[arg(long, default_value = "1")]
steps: usize,
#[arg(short, long)]
system: bool,
},
/// 清理无效和重复路径
Clean {
#[arg(short, long)] system: bool,
#[arg(short, long)] user: bool,
#[arg(long)] dry_run: bool,
#[arg(long)] json: bool,
#[arg(short, long)]
system: bool,
#[arg(short, long)]
user: bool,
#[arg(long)]
dry_run: bool,
#[arg(long)]
json: bool,
},
/// 启用指定位置的路径
Enable {
index: usize,
#[arg(short, long)] system: bool,
#[arg(short, long)] user: bool,
#[arg(short, long)]
system: bool,
#[arg(short, long)]
user: bool,
},
/// 禁用指定位置的路径
Disable {
index: usize,
#[arg(short, long)] system: bool,
#[arg(short, long)] user: bool,
#[arg(short, long)]
system: bool,
#[arg(short, long)]
user: bool,
},
/// 从文件导入 PATHJSON/CSV/TXT
Import {
file: String,
#[arg(long, default_value = "both")] target: String,
#[arg(long, default_value = "both")]
target: String,
},
/// 导出 PATH 为文件
Export {
#[arg(long, default_value = "json")] format: String,
#[arg(short, long)] output: Option<String>,
#[arg(long, default_value = "json")]
format: String,
#[arg(short, long)]
output: Option<String>,
},
/// 创建注册表备份
Backup,
/// 检测可执行文件冲突
Conflicts { #[arg(long)] json: bool },
Conflicts {
#[arg(long)]
json: bool,
},
/// 列出 PATH 目录中的可执行文件
Scan {
#[arg(long)] query: Option<String>,
#[arg(long)] json: bool,
#[arg(long)]
query: Option<String>,
#[arg(long)]
json: bool,
},
/// 检查管理员权限
CheckAdmin { #[arg(long)] json: bool },
CheckAdmin {
#[arg(long)]
json: bool,
},
/// 管理配置文件
#[command(subcommand)]
Profile(ProfileCmd),
@@ -94,7 +124,10 @@ enum Command {
#[derive(Subcommand)]
enum ProfileCmd {
/// 列出所有配置
List { #[arg(long)] json: bool },
List {
#[arg(long)]
json: bool,
},
/// 保存当前 PATH 为配置
Save { name: String },
/// 加载配置(预览)
@@ -105,8 +138,10 @@ enum ProfileCmd {
Delete { name: String },
/// 重命名配置
Rename {
#[arg(long)] old: String,
#[arg(long)] new: String,
#[arg(long)]
old: String,
#[arg(long)]
new: String,
},
}
@@ -116,8 +151,14 @@ fn exit_err(msg: &str) -> ! {
}
fn ensure_single_target(system: bool, user: bool) -> &'static str {
if system && user { exit_err("不能同时指定 --system 和 --user"); }
if system { "system" } else { "user" }
if system && user {
exit_err("不能同时指定 --system 和 --user");
}
if system {
"system"
} else {
"user"
}
}
type SaveFn = fn(Vec<String>) -> Result<(), String>;
@@ -131,7 +172,11 @@ fn verify_and_save(target: &str, original: &[String], new_list: Vec<String>) {
if reload != original {
exit_err("注册表已被其他进程修改,请重新执行操作");
}
let save: SaveFn = if target == "system" { core::registry::save_system_paths } else { core::registry::save_user_paths };
let save: SaveFn = if target == "system" {
core::registry::save_system_paths
} else {
core::registry::save_user_paths
};
save(new_list).unwrap_or_else(|e| exit_err(&e));
}
@@ -146,6 +191,29 @@ fn load_and_save(system: bool, f: impl FnOnce(Vec<String>) -> Vec<String>) {
verify_and_save(target, &list, new_list);
}
/// 加载、检查索引、操作、验证、保存的通用模式
/// `operate` 接收路径列表(包含原始列表)和要操作的索引,返回新列表和打印消息
fn load_operate_save(
system: bool,
index: usize,
operate: impl FnOnce(Vec<String>, usize) -> (Vec<String>, String),
) {
let target = ensure_single_target(system, false);
let list = if target == "system" {
core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e))
} else {
core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e))
};
if index >= list.len() {
exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len()));
}
let original = list.clone();
let (new_list, msg) = operate(list, index);
verify_and_save(target, &original, new_list);
println!("{msg}");
core::system::broadcast_env_change();
}
// ── 命令实现 ──
fn cmd_list(system: bool, user: bool, json_out: bool) {
@@ -163,11 +231,15 @@ fn cmd_list(system: bool, user: bool, json_out: bool) {
} else {
if !sys.is_empty() {
println!("═══ 系统 PATH ({}) ═══", sys.len());
for (i, p) in sys.iter().enumerate() { println!(" [{}] {}", i, p); }
for (i, p) in sys.iter().enumerate() {
println!(" [{}] {}", i, p);
}
}
if !usr.is_empty() {
println!("═══ 用户 PATH ({}) ═══", usr.len());
for (i, p) in usr.iter().enumerate() { println!(" [{}] {}", i, p); }
for (i, p) in usr.iter().enumerate() {
println!(" [{}] {}", i, p);
}
}
}
}
@@ -178,49 +250,43 @@ fn cmd_add(path: String, system: bool, user: bool) {
list.push(path.clone());
list
});
let label = if target == "system" { "系统" } else { "用户" };
let label = if target == "system" {
"系统"
} else {
"用户"
};
println!("已添加到{} PATH: {path}", label);
core::system::broadcast_env_change();
}
fn cmd_remove(index: usize, system: bool) {
let target = ensure_single_target(system, false);
let mut list = if target == "system" {
core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e))
} else {
core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e))
};
let original = list.clone();
if index >= list.len() { exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len())); }
let removed = list.remove(index);
verify_and_save(target, &original, list);
println!("已删除: {removed}");
core::system::broadcast_env_change();
load_operate_save(system, index, |mut list, idx| {
let removed = list.remove(idx);
(list, format!("已删除: {removed}"))
});
}
fn cmd_edit(index: usize, new_path: String, system: bool) {
let target = ensure_single_target(system, false);
let mut list = if target == "system" {
core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e))
} else {
core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e))
};
if index >= list.len() { exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len())); }
let original = list.clone();
let old = std::mem::replace(&mut list[index], new_path.clone());
verify_and_save(target, &original, list);
println!("已编辑: {old}{new_path}");
core::system::broadcast_env_change();
load_operate_save(system, index, |mut list, idx| {
let old = std::mem::replace(&mut list[idx], new_path.clone());
(list, format!("已编辑: {old}{new_path}"))
});
}
fn cmd_move(index: usize, steps: usize, system: bool, up: bool) {
load_and_save(system, |mut list| {
if index >= list.len() { exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len())); }
if index >= list.len() {
exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len()));
}
let end = if up {
index.saturating_sub(steps)
} else {
let max = list.len() - 1;
if index + steps > max { max } else { index + steps }
if index + steps > max {
max
} else {
index + steps
}
};
let removed = list.remove(index);
list.insert(end, removed);
@@ -232,19 +298,31 @@ fn cmd_move(index: usize, steps: usize, system: bool, up: bool) {
}
fn cmd_clean(system: bool, user: bool, dry_run: bool, json_out: bool) {
if system && user { exit_err("不能同时指定 --system 和 --user"); }
if system && user {
exit_err("不能同时指定 --system 和 --user");
}
let clean_sys = system || !user;
let clean_usr = user || !system;
if clean_sys { clean_one("system", dry_run, json_out); }
if clean_usr { clean_one("user", dry_run, json_out); }
if clean_sys {
clean_one("system", dry_run, json_out);
}
if clean_usr {
clean_one("user", dry_run, json_out);
}
if !dry_run && !json_out { core::system::broadcast_env_change(); }
if !dry_run && !json_out {
core::system::broadcast_env_change();
}
}
fn clean_one(target: &str, dry_run: bool, json_out: bool) {
let label = if target == "system" { "系统" } else { "用户" };
let label = if target == "system" {
"系统"
} else {
"用户"
};
let list = if target == "system" {
core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e))
} else {
@@ -253,18 +331,31 @@ fn clean_one(target: &str, dry_run: bool, json_out: bool) {
let (kept, removed) = core::registry::clean_paths(list.clone());
if json_out {
println!("{}", json!({ "target": target, "kept": kept, "removed": removed, "kept_count": kept.len(), "removed_count": removed.len() }));
println!(
"{}",
json!({ "target": target, "kept": kept, "removed": removed, "kept_count": kept.len(), "removed_count": removed.len() })
);
} else if dry_run {
println!("═══ {label} PATH — 将被移除({} 条)═══", removed.len());
for r in &removed { println!("{}", r); }
for r in &removed {
println!("{}", r);
}
println!("═══ {label} PATH — 将保留({} 条)═══", kept.len());
for k in &kept { println!("{}", k); }
for k in &kept {
println!("{}", k);
}
} else {
let kept_count = kept.len();
verify_and_save(target, &list, kept);
println!("{label} PATH 清理完成:移除 {} 条,保留 {}", removed.len(), kept_count);
println!(
"{label} PATH 清理完成:移除 {} 条,保留 {}",
removed.len(),
kept_count
);
if !removed.is_empty() {
for r in &removed { println!(" 已移除: {}", r); }
for r in &removed {
println!(" 已移除: {}", r);
}
}
}
}
@@ -276,11 +367,18 @@ fn cmd_toggle(index: usize, system: bool, user: bool, enable: bool) {
} else {
core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e))
};
if index >= list.len() { exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len())); }
if index >= list.len() {
exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len()));
}
let path = &list[index];
let (mut sys_dis, mut usr_dis) = core::disabled::load_disabled_state().unwrap_or_else(|_| (vec![], vec![]));
let target_list: &mut Vec<String> = if target == "system" { &mut sys_dis } else { &mut usr_dis };
let (mut sys_dis, mut usr_dis) =
core::disabled::load_disabled_state().unwrap_or_else(|_| (vec![], vec![]));
let target_list: &mut Vec<String> = if target == "system" {
&mut sys_dis
} else {
&mut usr_dis
};
if enable {
target_list.retain(|p| p != path);
@@ -294,23 +392,26 @@ fn cmd_toggle(index: usize, system: bool, user: bool, enable: bool) {
fn cmd_import(file: String, target: String) {
let content = core::fs::read_text_file(&file).unwrap_or_else(|e| exit_err(&e));
let (sys, usr) = core::fs::import_paths(&file, &content).unwrap_or_else(|e| exit_err(&e));
let (sys_entries, usr_entries) =
core::fs::import_paths(&file, &content).unwrap_or_else(|e| exit_err(&e));
let sys_paths: Vec<String> = sys_entries.into_iter().map(|e| e.path).collect();
let usr_paths: Vec<String> = usr_entries.into_iter().map(|e| e.path).collect();
match target.as_str() {
"system" => {
let orig = core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e));
verify_and_save("system", &orig, sys);
verify_and_save("system", &orig, sys_paths);
println!("已导入到系统 PATH");
}
"user" => {
let orig = core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e));
verify_and_save("user", &orig, usr);
verify_and_save("user", &orig, usr_paths);
println!("已导入到用户 PATH");
}
_ => {
let orig_sys = core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e));
let orig_usr = core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e));
verify_and_save("system", &orig_sys, sys);
verify_and_save("user", &orig_usr, usr);
verify_and_save("system", &orig_sys, sys_paths);
verify_and_save("user", &orig_usr, usr_paths);
println!("已导入到系统 + 用户 PATH");
}
}
@@ -322,6 +423,12 @@ fn cmd_export(format: String, output: Option<String>) {
let usr = core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e));
let content = core::fs::export_paths(&sys, &usr, &format).unwrap_or_else(|e| exit_err(&e));
if let Some(path) = output {
// 拒绝写入系统关键目录
let normalized = path.replace('/', "\\").to_lowercase();
if normalized.starts_with("c:\\windows\\") || normalized.starts_with("c:\\program files\\")
{
exit_err(&format!("不允许导出到系统目录: {path}"));
}
std::fs::write(&path, &content).unwrap_or_else(|e| exit_err(&format!("无法写入文件: {e}")));
println!("已导出到: {path}");
} else {
@@ -336,8 +443,12 @@ fn cmd_backup() {
fn cmd_conflicts(json_out: bool) {
let mut paths: Vec<String> = vec![];
if let Ok(sys) = core::registry::load_system_paths() { paths.extend(sys); }
if let Ok(usr) = core::registry::load_user_paths() { paths.extend(usr); }
if let Ok(sys) = core::registry::load_system_paths() {
paths.extend(sys);
}
if let Ok(usr) = core::registry::load_user_paths() {
paths.extend(usr);
}
let conflicts = core::scanner::scan_conflicts(paths).unwrap_or_else(|e| exit_err(&e));
if json_out {
println!("{}", serde_json::to_string_pretty(&conflicts).unwrap());
@@ -348,7 +459,15 @@ fn cmd_conflicts(json_out: bool) {
for c in &conflicts {
println!(" {}", c.name);
for loc in &c.locations {
println!(" {} {}", if loc.priority == 0 { "✓ 优先" } else { "✗ 遮蔽" }, loc.dir);
println!(
" {} {}",
if loc.priority == 0 {
"✓ 优先"
} else {
"✗ 遮蔽"
},
loc.dir
);
}
println!();
}
@@ -357,16 +476,26 @@ fn cmd_conflicts(json_out: bool) {
fn cmd_scan(query: Option<String>, json_out: bool) {
let mut paths: Vec<String> = vec![];
if let Ok(sys) = core::registry::load_system_paths() { paths.extend(sys); }
if let Ok(usr) = core::registry::load_user_paths() { paths.extend(usr); }
let groups = core::scanner::scan_tools(paths, query.unwrap_or_default()).unwrap_or_else(|e| exit_err(&e));
if let Ok(sys) = core::registry::load_system_paths() {
paths.extend(sys);
}
if let Ok(usr) = core::registry::load_user_paths() {
paths.extend(usr);
}
let groups = core::scanner::scan_tools(paths, query.unwrap_or_default())
.unwrap_or_else(|e| exit_err(&e));
if json_out {
println!("{}", serde_json::to_string_pretty(&groups).unwrap());
} else {
for g in &groups {
if !g.exists { println!(" {} (不存在)", g.dir); continue; }
if !g.exists {
println!(" {} (不存在)", g.dir);
continue;
}
println!("═══ {} ═══", g.dir);
for exe in &g.exes { println!(" {}", exe); }
for exe in &g.exes {
println!(" {}", exe);
}
}
}
}
@@ -387,15 +516,29 @@ fn profile_list(json_out: bool) {
} else if list.is_empty() {
println!("暂无配置文件。");
} else {
for p in &list { println!(" {} ({})", p.name, p.modified); }
for p in &list {
println!(" {} ({})", p.name, p.modified);
}
}
}
fn profile_save(name: String) {
let sys = core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e));
let usr = core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e));
let sys_entries = sys.into_iter().map(|p| core::ProfilePathEntry { path: p, enabled: true }).collect();
let usr_entries = usr.into_iter().map(|p| core::ProfilePathEntry { path: p, enabled: true }).collect();
let sys_entries = sys
.into_iter()
.map(|p| core::ProfilePathEntry {
path: p,
enabled: true,
})
.collect();
let usr_entries = usr
.into_iter()
.map(|p| core::ProfilePathEntry {
path: p,
enabled: true,
})
.collect();
core::profiles::save_profile(&name, sys_entries, usr_entries).unwrap_or_else(|e| exit_err(&e));
println!("已保存配置: {name}");
}
@@ -403,15 +546,29 @@ fn profile_save(name: String) {
fn profile_load(name: String) {
let data = core::profiles::load_profile(&name).unwrap_or_else(|e| exit_err(&e));
println!("═══ 系统 PATH ({} 条) ═══", data.sys.len());
for e in &data.sys { println!(" [{}] {}", if e.enabled { "" } else { "" }, e.path); }
for e in &data.sys {
println!(" [{}] {}", if e.enabled { "" } else { "" }, e.path);
}
println!("═══ 用户 PATH ({} 条) ═══", data.user.len());
for e in &data.user { println!(" [{}] {}", if e.enabled { "" } else { "" }, e.path); }
for e in &data.user {
println!(" [{}] {}", if e.enabled { "" } else { "" }, e.path);
}
}
fn profile_apply(name: String) {
let data = core::profiles::load_profile(&name).unwrap_or_else(|e| exit_err(&e));
let new_sys: Vec<String> = data.sys.into_iter().filter(|e| e.enabled).map(|e| e.path).collect();
let new_usr: Vec<String> = data.user.into_iter().filter(|e| e.enabled).map(|e| e.path).collect();
let new_sys: Vec<String> = data
.sys
.into_iter()
.filter(|e| e.enabled)
.map(|e| e.path)
.collect();
let new_usr: Vec<String> = data
.user
.into_iter()
.filter(|e| e.enabled)
.map(|e| e.path)
.collect();
let orig_sys = core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e));
let orig_usr = core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e));
@@ -438,12 +595,37 @@ fn main() {
Command::List { system, user, json } => cmd_list(system, user, json),
Command::Add { path, system, user } => cmd_add(path, system, user),
Command::Remove { index, system } => cmd_remove(index, system),
Command::Edit { index, new_path, system } => cmd_edit(index, new_path, system),
Command::MoveUp { index, steps, system } => cmd_move(index, steps, system, true),
Command::MoveDown { index, steps, system } => cmd_move(index, steps, system, false),
Command::Clean { system, user, dry_run, json } => cmd_clean(system, user, dry_run, json),
Command::Enable { index, system, user } => cmd_toggle(index, system, user, true),
Command::Disable { index, system, user } => cmd_toggle(index, system, user, false),
Command::Edit {
index,
new_path,
system,
} => cmd_edit(index, new_path, system),
Command::MoveUp {
index,
steps,
system,
} => cmd_move(index, steps, system, true),
Command::MoveDown {
index,
steps,
system,
} => cmd_move(index, steps, system, false),
Command::Clean {
system,
user,
dry_run,
json,
} => cmd_clean(system, user, dry_run, json),
Command::Enable {
index,
system,
user,
} => cmd_toggle(index, system, user, true),
Command::Disable {
index,
system,
user,
} => cmd_toggle(index, system, user, false),
Command::Import { file, target } => cmd_import(file, target),
Command::Export { format, output } => cmd_export(format, output),
Command::Backup => cmd_backup(),
+13 -16
View File
@@ -1,7 +1,7 @@
use crate::registry::{self, SYS_REG_PATH, USER_REG_PATH};
use chrono::Local;
use std::path::PathBuf;
use winreg::enums::*;
use crate::registry::{self, SYS_REG_PATH, USER_REG_PATH};
fn backup_base_dir() -> PathBuf {
dirs::home_dir()
@@ -19,24 +19,22 @@ pub fn get_appdata_dir() -> String {
/// 在保存前调用,备份的是注册表中的当前值(保存前的状态)
pub fn backup_registry(custom_dir: Option<String>) -> Result<String, String> {
let backup_dir = match custom_dir {
Some(ref dir) if !dir.is_empty() => std::path::PathBuf::from(dir),
Some(ref dir) if !dir.is_empty() => {
let p = std::path::PathBuf::from(dir);
let normalized = dir.replace('/', "\\").to_lowercase();
if normalized.starts_with("c:\\windows\\") || normalized.starts_with("c:\\program files\\") {
return Err("不允许备份到系统目录".into());
}
p
}
_ => backup_base_dir(),
};
std::fs::create_dir_all(&backup_dir)
.map_err(|e| format!("无法创建备份目录: {}", e))?;
std::fs::create_dir_all(&backup_dir).map_err(|e| format!("无法创建备份目录: {}", e))?;
// 读取当前注册表中的值(保存前的旧值)
let sys_paths = registry::load_paths(
HKEY_LOCAL_MACHINE,
SYS_REG_PATH,
"系统",
)?;
let user_paths = registry::load_paths(
HKEY_CURRENT_USER,
USER_REG_PATH,
"用户",
)?;
let sys_paths = registry::load_paths(HKEY_LOCAL_MACHINE, SYS_REG_PATH, "系统")?;
let user_paths = registry::load_paths(HKEY_CURRENT_USER, USER_REG_PATH, "用户")?;
let timestamp = Local::now().format("%Y%m%d_%H%M%S_%3f");
let filename = format!("path_backup_{}.txt", timestamp);
@@ -56,8 +54,7 @@ pub fn backup_registry(custom_dir: Option<String>) -> Result<String, String> {
content.push_str(&format!("{}\n", path));
}
std::fs::write(&filepath, &content)
.map_err(|e| format!("无法写入备份文件: {}", e))?;
std::fs::write(&filepath, &content).map_err(|e| format!("无法写入备份文件: {}", e))?;
let result = filepath.to_string_lossy().to_string();
log::info!("备份已保存到: {}", result);
+15 -10
View File
@@ -1,7 +1,9 @@
use crate::fs::atomic_write;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
#[cfg(not(test))]
fn disabled_file_path() -> PathBuf {
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
@@ -9,6 +11,11 @@ fn disabled_file_path() -> PathBuf {
.join("disabled.json")
}
#[cfg(test)]
fn disabled_file_path() -> PathBuf {
std::env::temp_dir().join("patheditor_test_disabled.json")
}
#[derive(Serialize, Deserialize, Default)]
struct DisabledState {
#[serde(default)]
@@ -23,15 +30,13 @@ pub fn save_disabled_state(system: Vec<String>, user: Vec<String>) -> Result<(),
let path = disabled_file_path();
if let Some(parent) = path.parent() {
fs::create_dir_all(parent)
.map_err(|e| format!("无法创建配置目录: {}", e))?;
fs::create_dir_all(parent).map_err(|e| format!("无法创建配置目录: {}", e))?;
}
let json = serde_json::to_string_pretty(&state)
.map_err(|e| format!("JSON 序列化失败: {}", e))?;
let json =
serde_json::to_string_pretty(&state).map_err(|e| format!("JSON 序列化失败: {}", e))?;
fs::write(&path, &json)
.map_err(|e| format!("无法写入 disabled.json: {}", e))?;
atomic_write(&path, &json).map_err(|e| format!("无法写入 disabled.json: {}", e))?;
log::info!("已保存禁用状态到: {}", path.display());
Ok(())
@@ -45,15 +50,15 @@ pub fn load_disabled_state() -> Result<(Vec<String>, Vec<String>), String> {
return Ok((vec![], vec![]));
}
let content = fs::read_to_string(&path)
.map_err(|e| format!("无法读取 disabled.json: {}", e))?;
let content =
fs::read_to_string(&path).map_err(|e| format!("无法读取 disabled.json: {}", e))?;
if content.trim().is_empty() {
return Ok((vec![], vec![]));
}
let state: DisabledState = serde_json::from_str(&content)
.map_err(|e| format!("JSON 解析失败: {}", e))?;
let state: DisabledState =
serde_json::from_str(&content).map_err(|e| format!("JSON 解析失败: {}", e))?;
Ok((state.system, state.user))
}
+306 -43
View File
@@ -1,13 +1,50 @@
// 注意:TS 端 src/core/import-export.ts 有对应的导入导出实现,
// 前端使用 TS 版(需 ImportDialog 交互),CLI 使用 Rust 版,修改时需同步两端。
use crate::profiles::ProfilePathEntry;
/// 过滤导入条目:去除空白、排除 null 字节和分号(PATH 分隔符冲突)
fn sanitize_entries(entries: Vec<ProfilePathEntry>) -> Vec<ProfilePathEntry> {
entries
.into_iter()
.map(|e| ProfilePathEntry {
path: e.path.trim().to_string(),
enabled: e.enabled,
})
.filter(|e| !e.path.is_empty() && !e.path.contains('\0') && !e.path.contains(';'))
.collect()
}
/// 原子写入:先写临时文件,再 rename 覆盖
pub fn atomic_write(path: &std::path::Path, content: &str) -> std::io::Result<()> {
let tmp = path.with_extension("tmp");
std::fs::write(&tmp, content)?;
std::fs::rename(&tmp, path)?;
Ok(())
}
/// 读取文本文件内容(供前端原生对话框选择文件后使用)
/// 仅允许 .json / .csv / .txt 扩展名,防止任意文件读取
pub fn read_text_file(path: &str) -> Result<String, String> {
let ext = std::path::Path::new(path)
.extension()
.and_then(|e| e.to_str())
.map(|e| e.to_ascii_lowercase())
.unwrap_or_default();
if !matches!(ext.as_str(), "json" | "csv" | "txt") {
return Err(format!(
"不支持的文件类型: .{}(仅允许 .json/.csv/.txt",
ext
));
}
std::fs::read_to_string(path).map_err(|e| format!("无法读取文件: {}", e))
}
/// 导入路径文件(JSON / CSV / TXT),返回 (系统路径, 用户路径)
pub fn import_paths(path: &str, content: &str) -> Result<(Vec<String>, Vec<String>), String> {
/// 导入路径文件(JSON / CSV / TXT),返回 (系统条目, 用户条目)
pub fn import_paths(
path: &str,
content: &str,
) -> Result<(Vec<ProfilePathEntry>, Vec<ProfilePathEntry>), String> {
let ext = std::path::Path::new(path)
.extension()
.map(|e| e.to_ascii_lowercase())
@@ -22,26 +59,85 @@ pub fn import_paths(path: &str, content: &str) -> Result<(Vec<String>, Vec<Strin
}
}
fn import_json(content: &str) -> Result<(Vec<String>, Vec<String>), String> {
fn import_json(content: &str) -> Result<(Vec<ProfilePathEntry>, Vec<ProfilePathEntry>), String> {
#[derive(serde::Deserialize)]
struct ImportItem {
path: String,
#[serde(default = "default_true")]
enabled: bool,
}
fn default_true() -> bool {
true
}
#[derive(serde::Deserialize)]
struct ImportData {
#[serde(default)]
system: Vec<String>,
system: Vec<ImportItem>,
#[serde(default)]
user: Vec<String>,
user: Vec<ImportItem>,
}
let data: ImportData =
serde_json::from_str(content).map_err(|e| format!("JSON 解析失败: {}", e))?;
Ok((data.system, data.user))
let into_entries = |items: Vec<ImportItem>| -> Vec<ProfilePathEntry> {
items
.into_iter()
.map(|i| ProfilePathEntry {
path: i.path,
enabled: i.enabled,
})
.collect()
};
Ok((
sanitize_entries(into_entries(data.system)),
sanitize_entries(into_entries(data.user)),
))
}
fn import_csv(content: &str) -> Result<(Vec<String>, Vec<String>), String> {
/// 解析 CSV 行,支持引号包裹的字段(RFC 4180 子集)
/// 与 TS 端 src/core/import-export.ts parseCsvLine 逻辑一致
fn parse_csv_line(line: &str) -> Vec<String> {
let mut fields = Vec::new();
let mut current = String::new();
let mut in_quotes = false;
let mut chars = line.chars().peekable();
while let Some(ch) = chars.next() {
if in_quotes {
if ch == '"' {
if chars.peek() == Some(&'"') {
current.push('"');
chars.next(); // 跳过转义引号
} else {
in_quotes = false;
}
} else {
current.push(ch);
}
} else if ch == '"' {
in_quotes = true;
} else if ch == ',' {
fields.push(current);
current = String::new();
} else {
current.push(ch);
}
}
fields.push(current);
fields
}
fn import_csv(
content: &str,
) -> Result<(Vec<ProfilePathEntry>, Vec<ProfilePathEntry>), String> {
let mut sys = Vec::new();
let mut usr = Vec::new();
let mut first = true;
for line in content.lines() {
let mut trimmed = line.trim();
if trimmed.is_empty() { continue; }
if trimmed.is_empty() {
continue;
}
// 处理 UTF-8 BOM(仅首行)
if first {
@@ -49,64 +145,88 @@ fn import_csv(content: &str) -> Result<(Vec<String>, Vec<String>), String> {
if let Some(stripped) = trimmed.strip_prefix('\u{FEFF}') {
trimmed = stripped;
}
// 跳过 header 行 "type,path"
let fields: Vec<&str> = trimmed.split(',').collect();
if fields.len() >= 2 {
let c0 = fields[0].trim().to_lowercase();
let c1 = fields[1].trim().to_lowercase();
if c0 == "type" && c1 == "path" { continue; }
// 跳过 header 行,兼容 type,path 和 type,path,enabled 两种格式
let header_fields = parse_csv_line(trimmed);
if header_fields.len() >= 2 {
let c0 = header_fields[0].trim().to_lowercase();
let c1 = header_fields[1].trim().to_lowercase();
if c0 == "type" && c1 == "path" {
continue;
}
}
}
let fields: Vec<&str> = trimmed.split(',').collect();
let fields = parse_csv_line(trimmed);
if fields.len() >= 2 {
let path = fields[1].trim().to_string();
let enabled = if fields.len() >= 3 {
fields[2].trim().to_lowercase() != "false"
} else {
true
};
let entry = ProfilePathEntry { path, enabled };
match fields[0].trim().to_lowercase().as_str() {
"system" | "sys" => sys.push(fields[1].trim().to_string()),
"user" | "usr" => usr.push(fields[1].trim().to_string()),
_ => { log::warn!("import_csv: 无法识别的类型字段,已跳过: {trimmed}"); }
"system" | "sys" => sys.push(entry),
"user" | "usr" => usr.push(entry),
_ => {
log::warn!("import_csv: 无法识别的类型字段,已跳过: {trimmed}");
}
}
} else {
log::warn!("import_csv: 格式不正确(缺逗号),已跳过: {trimmed}");
}
}
let sys = sanitize_entries(sys);
let usr = sanitize_entries(usr);
if sys.is_empty() && usr.is_empty() {
return Err("CSV 文件中未找到有效路径".into());
}
Ok((sys, usr))
}
fn import_txt(content: &str) -> Result<(Vec<String>, Vec<String>), String> {
let paths: Vec<String> = content
fn import_txt(content: &str) -> Result<(Vec<ProfilePathEntry>, Vec<ProfilePathEntry>), String> {
let entries: Vec<ProfilePathEntry> = content
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(|path| ProfilePathEntry {
path,
enabled: true,
})
.collect();
if paths.is_empty() {
let entries = sanitize_entries(entries);
if entries.is_empty() {
return Err("TXT 文件中未找到路径".into());
}
// TXT 格式全部导入为用户路径
Ok((vec![], paths))
Ok((vec![], entries))
}
/// 导出 PATH 为指定格式字符串
pub fn export_paths(sys: &[String], usr: &[String], format: &str) -> Result<String, String> {
match format {
"json" => {
let to_entries = |paths: &[String]| -> Vec<serde_json::Value> {
paths
.iter()
.map(|p| serde_json::json!({"path": p, "enabled": true}))
.collect()
};
let data = serde_json::json!({
"version": env!("CARGO_PKG_VERSION"),
"timestamp": chrono::Local::now().format("%Y-%m-%dT%H:%M:%S").to_string(),
"system": sys,
"user": usr,
"system": to_entries(sys),
"user": to_entries(usr),
});
Ok(serde_json::to_string_pretty(&data).unwrap_or_default())
Ok(serde_json::to_string_pretty(&data).expect("JSON 序列化 Value 不应失败"))
}
"csv" => {
let mut out = String::from("type,path\n");
let mut out = String::from("type,path,enabled\n");
for p in sys {
out.push_str(&format!("system,{}\n", p));
out.push_str(&format!("system,{},true\n", p));
}
for p in usr {
out.push_str(&format!("user,{}\n", p));
out.push_str(&format!("user,{},true\n", p));
}
Ok(out)
}
@@ -134,12 +254,30 @@ pub fn export_paths(sys: &[String], usr: &[String], format: &str) -> Result<Stri
mod tests {
use super::*;
fn entry(path: &str) -> ProfilePathEntry {
ProfilePathEntry {
path: path.into(),
enabled: true,
}
}
fn entry_disabled(path: &str) -> ProfilePathEntry {
ProfilePathEntry {
path: path.into(),
enabled: false,
}
}
#[test]
fn import_json_valid() {
let json = r#"{"system": ["C:\\sys1", "C:\\sys2"], "user": ["D:\\usr1"]}"#;
let json = r#"{"system": [{"path": "C:\\sys1"}, {"path": "C:\\sys2"}], "user": [{"path": "D:\\usr1"}]}"#;
let (sys, usr) = import_json(json).unwrap();
assert_eq!(sys, vec!["C:\\sys1", "C:\\sys2"]);
assert_eq!(usr, vec!["D:\\usr1"]);
assert_eq!(sys.len(), 2);
assert_eq!(sys[0].path, "C:\\sys1");
assert!(sys[0].enabled);
assert_eq!(sys[1].path, "C:\\sys2");
assert_eq!(usr.len(), 1);
assert_eq!(usr[0].path, "D:\\usr1");
}
#[test]
@@ -148,6 +286,15 @@ mod tests {
assert!(sys.is_empty() && usr.is_empty());
}
#[test]
fn import_json_disabled_entry() {
let json = r#"{"system": [{"path": "C:\\on", "enabled": true}, {"path": "C:\\off", "enabled": false}]}"#;
let (sys, _) = import_json(json).unwrap();
assert_eq!(sys.len(), 2);
assert!(sys[0].enabled);
assert!(!sys[1].enabled);
}
#[test]
fn import_json_missing_fields() {
let (sys, usr) = import_json(r#"{}"#).unwrap();
@@ -157,16 +304,20 @@ mod tests {
#[test]
fn import_csv_valid() {
let csv = "type,path\nsystem,C:\\sys1\nuser,D:\\usr1\n";
let (sys, _usr) = import_csv(csv).unwrap();
assert_eq!(sys, vec!["C:\\sys1"]);
assert_eq!(_usr, vec!["D:\\usr1"]);
let (sys, usr) = import_csv(csv).unwrap();
assert_eq!(sys.len(), 1);
assert_eq!(sys[0].path, "C:\\sys1");
assert!(sys[0].enabled);
assert_eq!(usr.len(), 1);
assert_eq!(usr[0].path, "D:\\usr1");
assert!(usr[0].enabled);
}
#[test]
fn import_csv_with_bom() {
let csv = "\u{FEFF}type,path\nsystem,C:\\sys1\n";
let (sys, _) = import_csv(csv).unwrap();
assert_eq!(sys, vec!["C:\\sys1"]);
assert_eq!(sys[0].path, "C:\\sys1");
}
#[test]
@@ -178,8 +329,27 @@ mod tests {
fn import_csv_alternate_type_names() {
let csv = "type,path\nsys,D:\\a\nusr,D:\\b\n";
let (sys, usr) = import_csv(csv).unwrap();
assert_eq!(sys, vec!["D:\\a"]);
assert_eq!(usr, vec!["D:\\b"]);
assert_eq!(sys[0].path, "D:\\a");
assert_eq!(usr[0].path, "D:\\b");
}
#[test]
fn import_csv_reads_enabled_column() {
let csv = "type,path,enabled\nsystem,C:\\ok,true\nsystem,C:\\disabled,false\n";
let (sys, _) = import_csv(csv).unwrap();
assert_eq!(sys.len(), 2);
assert_eq!(sys[0].path, "C:\\ok");
assert!(sys[0].enabled);
assert_eq!(sys[1].path, "C:\\disabled");
assert!(!sys[1].enabled);
}
#[test]
fn import_csv_enabled_defaults_true() {
// 2 列格式(无 enabled 列)默认为 true
let csv = "type,path\nsystem,C:\\x\n";
let (sys, _) = import_csv(csv).unwrap();
assert!(sys[0].enabled);
}
#[test]
@@ -188,16 +358,18 @@ mod tests {
let usr: Vec<String> = vec![];
let exported = export_paths(&sys, &usr, "json").unwrap();
let parsed: serde_json::Value = serde_json::from_str(&exported).unwrap();
assert_eq!(parsed["system"][0], "C:\\a");
assert_eq!(parsed["system"][0]["path"], "C:\\a");
assert_eq!(parsed["system"][0]["enabled"], true);
}
#[test]
fn export_csv_roundtrip() {
fn export_csv_includes_enabled_column() {
let sys = vec!["C:\\a".into()];
let usr = vec!["D:\\b".into()];
let exported = export_paths(&sys, &usr, "csv").unwrap();
assert!(exported.contains("system,C:\\a"));
assert!(exported.contains("user,D:\\b"));
assert!(exported.starts_with("type,path,enabled"));
assert!(exported.contains("system,C:\\a,true"));
assert!(exported.contains("user,D:\\b,true"));
}
#[test]
@@ -216,13 +388,104 @@ mod tests {
#[test]
fn import_paths_detects_format() {
let (sys, _) = import_paths("test.csv", "type,path\nsystem,C:\\x\n").unwrap();
assert_eq!(sys, vec!["C:\\x"]);
assert_eq!(sys[0].path, "C:\\x");
}
#[test]
fn import_paths_txt_to_user() {
let (sys, usr) = import_paths("test.txt", "C:\\x\nD:\\y\n").unwrap();
assert!(sys.is_empty());
assert_eq!(usr, vec!["C:\\x", "D:\\y"]);
assert_eq!(usr.len(), 2);
assert_eq!(usr[0].path, "C:\\x");
assert_eq!(usr[1].path, "D:\\y");
}
#[test]
fn read_text_file_rejects_non_whitelisted_ext() {
let result = read_text_file("C:\\Windows\\System32\\evil.dll");
assert!(result.is_err());
assert!(result.unwrap_err().contains("不支持的文件类型"));
}
#[test]
fn read_text_file_rejects_no_ext() {
let result = read_text_file("/etc/passwd");
assert!(result.is_err());
}
#[test]
fn sanitize_entries_filters_null_byte_paths() {
let entries = vec![entry("C:\\safe"), entry("C:\\bad\0path")];
let result = sanitize_entries(entries);
assert_eq!(result.len(), 1);
assert_eq!(result[0].path, "C:\\safe");
}
#[test]
fn import_csv_filters_semicolon_paths() {
let csv = "type,path\nsystem,C:\\good\nsystem,C:\\bad;path\n";
let (sys, _) = import_csv(csv).unwrap();
assert_eq!(sys.len(), 1);
assert_eq!(sys[0].path, "C:\\good");
}
#[test]
fn import_txt_trims_and_filters() {
let txt = " C:\\trimmed \n\nC:\\bad\0path\n# comment\n";
let (_, usr) = import_txt(txt).unwrap();
assert_eq!(usr.len(), 1);
assert_eq!(usr[0].path, "C:\\trimmed");
}
#[test]
fn sanitize_entries_removes_empty_after_trim() {
let result = sanitize_entries(vec![entry(" "), entry("C:\\ok")]);
assert_eq!(result.len(), 1);
assert_eq!(result[0].path, "C:\\ok");
}
#[test]
fn sanitize_entries_preserves_enabled_flag() {
let result = sanitize_entries(vec![entry_disabled("C:\\keep")]);
assert_eq!(result.len(), 1);
assert_eq!(result[0].path, "C:\\keep");
assert!(!result[0].enabled);
}
#[test]
fn parse_csv_line_basic() {
assert_eq!(parse_csv_line("a,b,c"), vec!["a", "b", "c"]);
}
#[test]
fn parse_csv_line_quoted_comma() {
assert_eq!(
parse_csv_line(r#"system,"C:\Program Files, Inc\bin""#),
vec!["system", r#"C:\Program Files, Inc\bin"#]
);
}
#[test]
fn parse_csv_line_escaped_quotes() {
assert_eq!(
parse_csv_line(r#"system,"He said ""hello""""#),
vec!["system", r#"He said "hello""#]
);
}
#[test]
fn import_csv_quoted_comma_path() {
let csv = "type,path\nsystem,\"C:\\Program Files, Inc\\bin\"\n";
let (sys, _) = import_csv(csv).unwrap();
assert_eq!(sys[0].path, "C:\\Program Files, Inc\\bin");
}
#[test]
fn csv_roundtrip_preserves_enabled() {
let csv = "type,path,enabled\nsystem,C:\\on,true\nsystem,C:\\off,false\n";
let (sys, _) = import_csv(csv).unwrap();
assert_eq!(sys.len(), 2);
assert!(sys[0].enabled);
assert!(!sys[1].enabled);
}
}
+61 -12
View File
@@ -1,7 +1,9 @@
use crate::fs::atomic_write;
use serde::{Deserialize, Serialize};
use std::fs;
use std::path::PathBuf;
#[cfg(not(test))]
fn profiles_dir() -> PathBuf {
dirs::home_dir()
.unwrap_or_else(|| PathBuf::from("."))
@@ -9,8 +11,21 @@ fn profiles_dir() -> PathBuf {
.join("profiles")
}
#[cfg(test)]
fn profiles_dir() -> PathBuf {
std::env::temp_dir().join("patheditor_test_profiles")
}
fn validate_profile_name(name: &str) -> Result<(), String> {
if name.is_empty() { return Err("配置名称不能为空".into()); }
if name.is_empty() {
return Err("配置名称不能为空".into());
}
if name.len() > 255 {
return Err("配置名称过长(最大 255 字符)".into());
}
if name.contains('\0') || name.chars().any(|c| c.is_control()) {
return Err("配置名称包含非法字符".into());
}
if name.contains('/') || name.contains('\\') || name.contains("..") {
return Err("配置名称包含非法字符".into());
}
@@ -115,7 +130,7 @@ pub fn save_profile(
let json =
serde_json::to_string_pretty(&data).map_err(|e| format!("JSON 序列化失败: {}", e))?;
fs::write(&path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
atomic_write(&path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
log::info!("已保存配置: {}", path.display());
Ok(())
@@ -128,10 +143,8 @@ pub fn load_profile(name: &str) -> Result<ProfileData, String> {
if !path.exists() {
return Err(format!("配置文件不存在: {}", name));
}
let content = fs::read_to_string(&path)
.map_err(|e| format!("无法读取配置文件: {}", e))?;
serde_json::from_str(&content)
.map_err(|e| format!("JSON 解析失败: {}", e))
let content = fs::read_to_string(&path).map_err(|e| format!("无法读取配置文件: {}", e))?;
serde_json::from_str(&content).map_err(|e| format!("JSON 解析失败: {}", e))
}
/// 删除配置文件
@@ -148,20 +161,25 @@ pub fn rename_profile(old_name: &str, new_name: &str) -> Result<(), String> {
validate_profile_name(old_name)?;
validate_profile_name(new_name)?;
let old_path = profile_path(old_name);
let new_path = profile_path(new_name);
if !old_path.exists() {
return Err(format!("配置文件不存在: {}", old_name));
}
if old_path != new_path && new_path.exists() {
return Err(format!("目标配置名已存在: {}", new_name));
}
let mut data: ProfileData =
serde_json::from_str(&fs::read_to_string(&old_path).map_err(|e| format!("无法读取配置文件: {}", e))?).map_err(|e| format!("JSON 解析失败: {}", e))?;
let mut data: ProfileData = serde_json::from_str(
&fs::read_to_string(&old_path).map_err(|e| format!("无法读取配置文件: {}", e))?,
)
.map_err(|e| format!("JSON 解析失败: {}", e))?;
data.name = new_name.to_string();
data.modified = chrono::Local::now().format("%Y-%m-%dT%H:%M:%S").to_string();
let new_path = profile_path(new_name);
let json =
serde_json::to_string_pretty(&data).map_err(|e| format!("JSON 序列化失败: {}", e))?;
fs::write(&new_path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
atomic_write(&new_path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
if old_path != new_path {
fs::remove_file(&old_path).map_err(|e| format!("无法删除旧配置文件: {}", e))?;
@@ -176,7 +194,10 @@ mod tests {
use super::*;
fn test_entry(path: &str) -> ProfilePathEntry {
ProfilePathEntry { path: path.into(), enabled: true }
ProfilePathEntry {
path: path.into(),
enabled: true,
}
}
#[test]
@@ -196,12 +217,40 @@ mod tests {
assert!(validate_profile_name("foo<bar").is_err());
}
#[test]
fn validate_name_rejects_null_bytes() {
assert!(validate_profile_name("foo\0bar").is_err());
}
#[test]
fn validate_name_rejects_control_chars() {
assert!(validate_profile_name("foo\tbar").is_err());
assert!(validate_profile_name("foo\nbar").is_err());
}
#[test]
fn validate_name_rejects_too_long() {
let long_name = "a".repeat(256);
assert!(validate_profile_name(&long_name).is_err());
}
#[test]
fn validate_name_accepts_255_chars() {
let name = "a".repeat(255);
assert!(validate_profile_name(&name).is_ok());
}
#[test]
fn profile_crud() {
// save -> load -> delete
let name = "__test_profile_crud";
let _ = delete_profile(name);
save_profile(name, vec![test_entry("C:\\sys")], vec![test_entry("D:\\usr")]).unwrap();
save_profile(
name,
vec![test_entry("C:\\sys")],
vec![test_entry("D:\\usr")],
)
.unwrap();
let loaded = load_profile(name).unwrap();
assert_eq!(loaded.sys[0].path, "C:\\sys");
delete_profile(name).unwrap();
+59 -21
View File
@@ -1,11 +1,16 @@
use winreg::enums::*;
use winreg::RegKey;
pub(crate) const SYS_REG_PATH: &str = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
pub(crate) const SYS_REG_PATH: &str =
"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
pub(crate) const USER_REG_PATH: &str = "Environment";
const PATH_VALUE: &str = "Path";
pub(crate) fn load_paths(root: winreg::HKEY, sub_path: &str, label: &str) -> Result<Vec<String>, String> {
pub(crate) fn load_paths(
root: winreg::HKEY,
sub_path: &str,
label: &str,
) -> Result<Vec<String>, String> {
let key = RegKey::predef(root);
let env_key = key
.open_subkey_with_flags(sub_path, KEY_READ)
@@ -18,17 +23,13 @@ pub(crate) fn load_paths(root: winreg::HKEY, sub_path: &str, label: &str) -> Res
Ok(split_path(&value))
}
fn save_paths(root: winreg::HKEY, sub_path: &str, label: &str, paths: &[String]) -> Result<(), String> {
let value = join_path(paths);
// Windows 注册表 REG_EXPAND_SZ 上限 32767 字符
const MAX_PATH_LEN: usize = 32767;
if value.len() > MAX_PATH_LEN {
return Err(format!(
"{} PATH 总长度 {} 超出 Windows 限制 {} 字符,请移除部分路径后再保存",
label, value.len(), MAX_PATH_LEN
));
}
fn save_paths(
root: winreg::HKEY,
sub_path: &str,
label: &str,
paths: &[String],
) -> Result<(), String> {
let value = validate_and_join_paths(paths, label)?;
let key = RegKey::predef(root);
let env_key = key
@@ -43,7 +44,6 @@ fn save_paths(root: winreg::HKEY, sub_path: &str, label: &str, paths: &[String])
Ok(())
}
/// 从 HKLM 注册表读取系统 PATH
///
/// # Returns
@@ -53,7 +53,6 @@ pub fn load_system_paths() -> Result<Vec<String>, String> {
load_paths(HKEY_LOCAL_MACHINE, SYS_REG_PATH, "系统")
}
/// 从 HKCU 注册表读取用户 PATH
///
/// # Returns
@@ -63,7 +62,6 @@ pub fn load_user_paths() -> Result<Vec<String>, String> {
load_paths(HKEY_CURRENT_USER, USER_REG_PATH, "用户")
}
/// 保存系统 PATH 到注册表,含 32767 字符上限检查
///
/// # Returns
@@ -73,7 +71,6 @@ pub fn save_system_paths(paths: Vec<String>) -> Result<(), String> {
save_paths(HKEY_LOCAL_MACHINE, SYS_REG_PATH, "系统", &paths)
}
/// 保存用户 PATH 到注册表
///
/// # Returns
@@ -101,6 +98,25 @@ fn join_path(paths: &[String]) -> String {
.join(";")
}
/// 验证路径列表并拼接为分号分隔字符串
/// - 检查 null 字节
/// - 检查 UTF-16 总长度不超过 32767
fn validate_and_join_paths(paths: &[String], label: &str) -> Result<String, String> {
if let Some(bad) = paths.iter().find(|p| p.contains('\0')) {
return Err(format!("{} PATH 包含非法字符(null 字节): {}", label, bad));
}
let value = join_path(paths);
const MAX_PATH_LEN: usize = 32767;
let utf16_len = value.encode_utf16().count();
if utf16_len > MAX_PATH_LEN {
return Err(format!(
"{} PATH 总长度 {} 超出 Windows 限制 {} 字符,请移除部分路径后再保存",
label, utf16_len, MAX_PATH_LEN
));
}
Ok(value)
}
/// 清理路径列表:移除不存在的目录 + 重复路径(保留首次出现)
/// 返回 (保留的路径, 被移除的路径)
pub fn clean_paths(paths: Vec<String>) -> (Vec<String>, Vec<String>) {
@@ -148,10 +164,7 @@ mod tests {
#[test]
fn split_trims_and_filters_empty() {
assert_eq!(
split_path(" C:\\ ; ; D:\\ "),
vec!["C:\\", "D:\\"]
);
assert_eq!(split_path(" C:\\ ; ; D:\\ "), vec!["C:\\", "D:\\"]);
}
#[test]
@@ -167,4 +180,29 @@ mod tests {
let paths = vec![" C:\\Windows ".to_string(), " D:\\ ".to_string()];
assert_eq!(join_path(&paths), "C:\\Windows;D:\\");
}
#[test]
fn validate_rejects_null_bytes() {
let paths = vec!["C:\\safe".into(), "C:\0invalid".into()];
let result = validate_and_join_paths(&paths, "测试");
assert!(result.is_err());
assert!(result.unwrap_err().contains("null 字节"));
}
#[test]
fn validate_accepts_cjk_paths() {
let paths = vec!["C:\\用户\\工具".into()];
let result = validate_and_join_paths(&paths, "测试");
assert!(result.is_ok());
}
#[test]
fn validate_rejects_oversized_paths() {
// 构造总长超过 32767 UTF-16 字符的路径
let long_path = "C:\\".to_string() + &"a".repeat(32767);
let paths = vec![long_path];
let result = validate_and_join_paths(&paths, "测试");
assert!(result.is_err());
assert!(result.unwrap_err().contains("超出 Windows 限制"));
}
}
+65 -23
View File
@@ -50,13 +50,18 @@ fn list_exes(dir: &str) -> Vec<String> {
/// 并行遍历每个 PATH 目录,查找 .exe/.bat/.cmd/.com/.ps1 文件,
/// 标记出现在多个目录中的同名文件(后面的目录会被前面的「遮蔽」)
pub fn scan_conflicts(paths: Vec<String>) -> Result<Vec<ConflictEntry>, String> {
// 并行扫描各目录
let results: Vec<(usize, String, Vec<String>)> = std::thread::scope(|s| {
let handles: Vec<_> = paths.iter().enumerate().map(|(priority, dir)| {
s.spawn(move || (priority, dir.clone(), list_exes(dir)))
}).collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
let handles: Vec<_> = paths
.iter()
.enumerate()
.map(|(priority, dir)| s.spawn(move || (priority, dir.clone(), list_exes(dir))))
.collect();
handles
.into_iter()
.map(|h| h.join().map_err(|e| format!("扫描线程失败: {:?}", e)))
.collect::<Result<Vec<_>, _>>()
})
.map_err(|e| format!("线程扫描失败: {}", e))?;
// 合并: exe_name (小写) → [(priority, dir)]
let mut map: HashMap<String, Vec<(usize, String)>> = HashMap::new();
@@ -92,31 +97,46 @@ pub fn scan_tools(paths: Vec<String>, query: String) -> Result<Vec<ToolGroup>, S
// 并行扫描各目录
let dir_results: Vec<(String, Option<Vec<String>>)> = std::thread::scope(|s| {
let handles: Vec<_> = paths.iter().map(|dir| {
s.spawn(move || {
let p = Path::new(dir);
if !p.is_dir() {
return (dir.clone(), None);
}
let exes = list_exes(dir);
(dir.clone(), Some(exes))
let handles: Vec<_> = paths
.iter()
.map(|dir| {
s.spawn(move || {
let p = Path::new(dir);
if !p.is_dir() {
return (dir.clone(), None);
}
let exes = list_exes(dir);
(dir.clone(), Some(exes))
})
})
}).collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
.collect();
handles
.into_iter()
.map(|h| h.join().map_err(|e| format!("扫描线程失败: {:?}", e)))
.collect::<Result<Vec<_>, _>>()
})
.map_err(|e| format!("线程扫描失败: {}", e))?;
let mut groups: Vec<ToolGroup> = Vec::new();
for (dir, opt_exes) in dir_results {
match opt_exes {
None => {
groups.push(ToolGroup { dir, exists: false, exes: vec![] });
groups.push(ToolGroup {
dir,
exists: false,
exes: vec![],
});
}
Some(mut exes) => {
if !query_lower.is_empty() {
exes.retain(|name| name.to_lowercase().contains(&query_lower));
}
exes.sort();
groups.push(ToolGroup { dir, exists: true, exes });
groups.push(ToolGroup {
dir,
exists: true,
exes,
});
}
}
}
@@ -129,20 +149,39 @@ mod tests {
use super::*;
use std::fs;
fn make_temp_dir_with_exes(prefix: &str, exe_names: &[&str]) -> std::path::PathBuf {
struct TempDirGuard(std::path::PathBuf);
impl Drop for TempDirGuard {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
impl std::ops::Deref for TempDirGuard {
type Target = std::path::PathBuf;
fn deref(&self) -> &Self::Target {
&self.0
}
}
fn make_temp_dir_with_exes(prefix: &str, exe_names: &[&str]) -> TempDirGuard {
let dir = std::env::temp_dir().join(format!("patheditor_test_{}", prefix));
let _ = fs::remove_dir_all(&dir); // 清理残留
fs::create_dir_all(&dir).unwrap();
for name in exe_names {
fs::write(dir.join(name), b"fake").unwrap();
}
dir
TempDirGuard(dir)
}
#[test]
fn scan_conflicts_no_duplicates() {
let d1 = make_temp_dir_with_exes("c_a", &["a.exe"]);
let d2 = make_temp_dir_with_exes("c_b", &["b.exe"]);
let paths = vec![d1.to_string_lossy().to_string(), d2.to_string_lossy().to_string()];
let paths = vec![
d1.to_string_lossy().to_string(),
d2.to_string_lossy().to_string(),
];
let conflicts = scan_conflicts(paths).unwrap();
assert!(conflicts.is_empty());
}
@@ -151,7 +190,10 @@ mod tests {
fn scan_conflicts_detects_duplicate() {
let d1 = make_temp_dir_with_exes("c_dup1", &["shared.exe"]);
let d2 = make_temp_dir_with_exes("c_dup2", &["shared.exe"]);
let paths = vec![d1.to_string_lossy().to_string(), d2.to_string_lossy().to_string()];
let paths = vec![
d1.to_string_lossy().to_string(),
d2.to_string_lossy().to_string(),
];
let conflicts = scan_conflicts(paths).unwrap();
assert_eq!(conflicts.len(), 1);
assert_eq!(conflicts[0].locations.len(), 2);
+6 -15
View File
@@ -32,16 +32,12 @@ pub fn expand_env_vars(path: &str) -> String {
}
// 转为 UTF-16 宽字符串(以 null 结尾)
let wide_path: Vec<u16> = path
.encode_utf16()
.chain(std::iter::once(0))
.collect();
let wide_path: Vec<u16> = path.encode_utf16().chain(std::iter::once(0)).collect();
// SAFETY: wide_path 是以 null 结尾的 UTF-16 字符串,lpDst 为 null 且 nSize 为 0
// 根据 MSDN 文档此时 API 只查询所需缓冲区大小而不写入数据
let required = unsafe {
ExpandEnvironmentStringsW(wide_path.as_ptr(), std::ptr::null_mut(), 0)
};
let required =
unsafe { ExpandEnvironmentStringsW(wide_path.as_ptr(), std::ptr::null_mut(), 0) };
if required == 0 {
log::warn!("expand_env_vars: API 查询缓冲区失败, 返回原始路径: {path}");
@@ -51,9 +47,8 @@ pub fn expand_env_vars(path: &str) -> String {
// SAFETY: buffer 容量为 requiredAPI 返回的精确大小),wide_path 以 null 结尾,
// 且两个指针指向不同的内存区域,不存在重叠
let mut buffer: Vec<u16> = vec![0; required as usize];
let result = unsafe {
ExpandEnvironmentStringsW(wide_path.as_ptr(), buffer.as_mut_ptr(), required)
};
let result =
unsafe { ExpandEnvironmentStringsW(wide_path.as_ptr(), buffer.as_mut_ptr(), required) };
if result == 0 || result > required {
log::warn!("expand_env_vars: 展开失败或缓冲区不足, 返回原始路径: {path}");
@@ -110,11 +105,7 @@ pub fn broadcast_env_change() {
extern "system" {
/// https://learn.microsoft.com/en-us/windows/win32/api/processenv/nf-processenv-expandenvironmentstringsw
fn ExpandEnvironmentStringsW(
lpSrc: *const u16,
lpDst: *mut u16,
nSize: u32,
) -> u32;
fn ExpandEnvironmentStringsW(lpSrc: *const u16, lpDst: *mut u16, nSize: u32) -> u32;
/// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessagetimeoutw
fn SendMessageTimeoutW(
+35
View File
@@ -0,0 +1,35 @@
# 未修复问题清单
> 从 v5.1 全面代码审查中筛选,暂不修复,留待后续评估。
---
## 1. CLI main.rs 单体文件 (639 行)
**严重级别**: LOW
**文件**: `cli/src/main.rs`
**问题**: 所有 18 条 CLI 命令集中在一个文件中。
**建议**: 当前规模尚可维护,等到命令数超过 25 条或文件超过 1000 行时再拆分为 `commands/` 子模块。
---
## 2. GUI 命令层零测试
**严重级别**: LOW
**文件**: `gui/src/commands/*.rs` (8 个文件)
**问题**: GUI 命令层是纯薄包装,无独立测试。
**建议**: 不值得投入 — 命令正确性由编译器类型系统保证,运行期由 57 个 core 测试 + E2E 覆盖。
---
## 已修复(本批次)
- ~~disabled.rs 测试写入真实文件~~ → `#[cfg(test)]` 条件编译重定向到 `std::env::temp_dir()`
- ~~profiles.rs 同款问题~~ → 同上
---
*更新于: 2026-05-30 | 审查批次: v5.1 代码审查*
+5
View File
@@ -0,0 +1,5 @@
interface Window {
__TAURI_INTERNALS__?: {
invoke: (cmd: string, args?: Record<string, unknown>) => Promise<unknown>;
};
}
+5 -1
View File
@@ -1,7 +1,11 @@
export function createIpcMock() {
export type IpcOverrides = Partial<Record<string, unknown>>;
export function createIpcMock(overrides: IpcOverrides = {}) {
return `
window.__TAURI_INTERNALS__ = {
invoke: async (cmd, args) => {
const overrides = ${JSON.stringify(overrides)};
if (cmd in overrides) return overrides[cmd];
switch (cmd) {
case 'check_admin': return true;
case 'load_system_paths': return ['C:\\\\Windows', 'C:\\\\Program Files'];
+6 -23
View File
@@ -1,29 +1,12 @@
import { test, expect } from '@playwright/test';
import { createIpcMock } from '../mocks/ipc';
test.beforeEach(async ({ page }) => {
await page.addInitScript(() => {
window.__TAURI_INTERNALS__ = {
// eslint-disable-next-line @typescript-eslint/no-unused-vars
invoke: async (cmd, args) => {
switch (cmd) {
case 'check_admin': return true;
case 'load_system_paths': return ['C:\\\\Windows', 'invalid_path', 'C:\\\\Temp'];
case 'load_user_paths': return [];
case 'load_disabled_state': return { system: [], user: [] };
case 'save_system_paths': return undefined;
case 'save_user_paths': return undefined;
case 'save_disabled_state': return undefined;
case 'backup_registry': return '';
case 'broadcast_env_change': return undefined;
case 'validate_path': return false;
case 'expand_env_vars': return '';
case 'read_text_file': return '';
case 'get_appdata_dir': return '';
default: return undefined;
}
}
};
});
await page.addInitScript(createIpcMock({
load_system_paths: ['C:\\Windows', 'invalid_path', 'C:\\Temp'],
load_user_paths: [],
validate_path: false,
}));
await page.goto('/');
});
+1 -1
View File
@@ -5,7 +5,7 @@ import reactRefresh from 'eslint-plugin-react-refresh';
import globals from 'globals';
export default tseslint.config(
{ ignores: ['dist', 'gui'] },
{ ignores: ['dist', 'gui', 'target', 'test-results', 'e2e', '*.config.*'] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ['**/*.{ts,tsx}'],
+1 -1
View File
@@ -1,3 +1,3 @@
fn main() {
tauri_build::build()
tauri_build::build()
}
+12 -2
View File
@@ -1,12 +1,22 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "enables the default permissions",
"description": "PathEditor main window capabilities",
"windows": [
"main"
],
"permissions": [
"core:default",
"dialog:default"
"core:window:allow-set-title",
"core:window:allow-close",
"core:window:allow-minimize",
"core:window:allow-start-dragging",
"core:window:allow-is-minimized",
"core:window:allow-set-focus",
"core:event:default",
"dialog:default",
"dialog:allow-open",
"dialog:allow-save",
"log:default"
]
}
+6 -2
View File
@@ -1,6 +1,10 @@
use path_editor_core::backup;
#[tauri::command]
pub fn backup_registry(custom_dir: Option<String>) -> Result<String, String> { backup::backup_registry(custom_dir) }
pub fn backup_registry(custom_dir: Option<String>) -> Result<String, String> {
backup::backup_registry(custom_dir)
}
#[tauri::command]
pub fn get_appdata_dir() -> String { backup::get_appdata_dir() }
pub fn get_appdata_dir() -> String {
backup::get_appdata_dir()
}
+6 -2
View File
@@ -1,6 +1,10 @@
use path_editor_core::disabled;
#[tauri::command]
pub fn save_disabled_state(system: Vec<String>, user: Vec<String>) -> Result<(), String> { disabled::save_disabled_state(system, user) }
pub fn save_disabled_state(system: Vec<String>, user: Vec<String>) -> Result<(), String> {
disabled::save_disabled_state(system, user)
}
#[tauri::command]
pub fn load_disabled_state() -> Result<(Vec<String>, Vec<String>), String> { disabled::load_disabled_state() }
pub fn load_disabled_state() -> Result<(Vec<String>, Vec<String>), String> {
disabled::load_disabled_state()
}
+3 -1
View File
@@ -1,4 +1,6 @@
use path_editor_core::fs;
#[tauri::command]
pub fn read_text_file(path: &str) -> Result<String, String> { fs::read_text_file(path) }
pub fn read_text_file(path: &str) -> Result<String, String> {
fs::read_text_file(path)
}
+19 -5
View File
@@ -1,12 +1,26 @@
use path_editor_core::profiles;
#[tauri::command]
pub fn list_profiles() -> Result<Vec<profiles::ProfileMeta>, String> { profiles::list_profiles() }
pub fn list_profiles() -> Result<Vec<profiles::ProfileMeta>, String> {
profiles::list_profiles()
}
#[tauri::command]
pub fn save_profile(name: String, sys: Vec<profiles::ProfilePathEntry>, user: Vec<profiles::ProfilePathEntry>) -> Result<(), String> { profiles::save_profile(&name, sys, user) }
pub fn save_profile(
name: String,
sys: Vec<profiles::ProfilePathEntry>,
user: Vec<profiles::ProfilePathEntry>,
) -> Result<(), String> {
profiles::save_profile(&name, sys, user)
}
#[tauri::command]
pub fn load_profile(name: String) -> Result<profiles::ProfileData, String> { profiles::load_profile(&name) }
pub fn load_profile(name: String) -> Result<profiles::ProfileData, String> {
profiles::load_profile(&name)
}
#[tauri::command]
pub fn delete_profile(name: String) -> Result<(), String> { profiles::delete_profile(&name) }
pub fn delete_profile(name: String) -> Result<(), String> {
profiles::delete_profile(&name)
}
#[tauri::command]
pub fn rename_profile(old_name: String, new_name: String) -> Result<(), String> { profiles::rename_profile(&old_name, &new_name) }
pub fn rename_profile(old_name: String, new_name: String) -> Result<(), String> {
profiles::rename_profile(&old_name, &new_name)
}
+12 -4
View File
@@ -1,10 +1,18 @@
use path_editor_core::registry;
#[tauri::command]
pub fn load_system_paths() -> Result<Vec<String>, String> { registry::load_system_paths() }
pub fn load_system_paths() -> Result<Vec<String>, String> {
registry::load_system_paths()
}
#[tauri::command]
pub fn load_user_paths() -> Result<Vec<String>, String> { registry::load_user_paths() }
pub fn load_user_paths() -> Result<Vec<String>, String> {
registry::load_user_paths()
}
#[tauri::command]
pub fn save_system_paths(paths: Vec<String>) -> Result<(), String> { registry::save_system_paths(paths) }
pub fn save_system_paths(paths: Vec<String>) -> Result<(), String> {
registry::save_system_paths(paths)
}
#[tauri::command]
pub fn save_user_paths(paths: Vec<String>) -> Result<(), String> { registry::save_user_paths(paths) }
pub fn save_user_paths(paths: Vec<String>) -> Result<(), String> {
registry::save_user_paths(paths)
}
+6 -2
View File
@@ -1,6 +1,10 @@
use path_editor_core::scanner;
#[tauri::command]
pub fn scan_conflicts(paths: Vec<String>) -> Result<Vec<scanner::ConflictEntry>, String> { scanner::scan_conflicts(paths) }
pub fn scan_conflicts(paths: Vec<String>) -> Result<Vec<scanner::ConflictEntry>, String> {
scanner::scan_conflicts(paths)
}
#[tauri::command]
pub fn scan_tools(paths: Vec<String>, query: String) -> Result<Vec<scanner::ToolGroup>, String> { scanner::scan_tools(paths, query) }
pub fn scan_tools(paths: Vec<String>, query: String) -> Result<Vec<scanner::ToolGroup>, String> {
scanner::scan_tools(paths, query)
}
+12 -4
View File
@@ -1,10 +1,18 @@
use path_editor_core::system;
#[tauri::command]
pub fn check_admin() -> bool { system::check_admin() }
pub fn check_admin() -> bool {
system::check_admin()
}
#[tauri::command]
pub fn validate_path(path: &str) -> bool { system::validate_path(path) }
pub fn validate_path(path: &str) -> bool {
system::validate_path(path)
}
#[tauri::command]
pub fn expand_env_vars(path: &str) -> String { system::expand_env_vars(path) }
pub fn expand_env_vars(path: &str) -> String {
system::expand_env_vars(path)
}
#[tauri::command]
pub fn broadcast_env_change() { system::broadcast_env_change() }
pub fn broadcast_env_change() {
system::broadcast_env_change()
}
+7 -7
View File
@@ -5,13 +5,13 @@ pub fn run() {
tauri::Builder::default()
.plugin(tauri_plugin_dialog::init())
.setup(|app| {
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.build(),
)?;
}
let level = if cfg!(debug_assertions) {
log::LevelFilter::Info
} else {
log::LevelFilter::Warn
};
app.handle()
.plugin(tauri_plugin_log::Builder::default().level(level).build())?;
Ok(())
})
.invoke_handler(tauri::generate_handler![
+1 -1
View File
@@ -2,5 +2,5 @@
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
fn main() {
app_lib::run();
app_lib::run();
}
+2 -2
View File
@@ -1,7 +1,7 @@
{
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
"productName": "PathEditor",
"version": "5.0.0",
"version": "5.1.0",
"identifier": "com.liuhangyu.patheditor",
"build": {
"frontendDist": "../dist",
@@ -12,7 +12,7 @@
"app": {
"windows": [
{
"title": "PathEditor v5.0",
"title": "PathEditor v5.1",
"width": 900,
"height": 700,
"minWidth": 800,
+165 -81
View File
@@ -23,12 +23,12 @@
"@eslint/js": "^10.0.1",
"@playwright/test": "^1.60.0",
"@tauri-apps/cli": "^2.11.2",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@types/node": "^24.12.3",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"@vitest/coverage-v8": "^4.1.7",
"eslint": "^10.3.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
@@ -40,13 +40,6 @@
"vitest": "^4.1.7"
}
},
"node_modules/@adobe/css-tools": {
"version": "4.5.0",
"resolved": "https://registry.npmmirror.com/@adobe/css-tools/-/css-tools-4.5.0.tgz",
"integrity": "sha512-6OzddxPio9UiWTCemp4N8cYLV2ZN1ncRnV1cVGtve7dhPOtRkleRyx32GQCYSwDYgaHU3USMm84tNsvKzRCa1Q==",
"dev": true,
"license": "MIT"
},
"node_modules/@asamuzakjp/css-color": {
"version": "5.1.11",
"resolved": "https://registry.npmmirror.com/@asamuzakjp/css-color/-/css-color-5.1.11.tgz",
@@ -347,6 +340,16 @@
"node": ">=6.9.0"
}
},
"node_modules/@bcoe/v8-coverage": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/@bcoe/v8-coverage/-/v8-coverage-1.0.2.tgz",
"integrity": "sha512-6zABk/ECA/QYSCQ1NGiVwwbQerUCZ+TQbp64Q3AgmfNvurHH0j8TtXa1qbShXA6qqkpAj4V5W8pP6mLe1mcMqA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/@bramus/specificity": {
"version": "2.4.2",
"resolved": "https://registry.npmmirror.com/@bramus/specificity/-/specificity-2.4.2.tgz",
@@ -1600,33 +1603,6 @@
"node": ">=18"
}
},
"node_modules/@testing-library/jest-dom": {
"version": "6.9.1",
"resolved": "https://registry.npmmirror.com/@testing-library/jest-dom/-/jest-dom-6.9.1.tgz",
"integrity": "sha512-zIcONa+hVtVSSep9UT3jZ5rizo2BsxgyDYU7WFD5eICBE7no3881HGeb/QkGfsJs6JTkY1aQhT7rIPC7e+0nnA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@adobe/css-tools": "^4.4.0",
"aria-query": "^5.0.0",
"css.escape": "^1.5.1",
"dom-accessibility-api": "^0.6.3",
"picocolors": "^1.1.1",
"redent": "^3.0.0"
},
"engines": {
"node": ">=14",
"npm": ">=6",
"yarn": ">=1"
}
},
"node_modules/@testing-library/jest-dom/node_modules/dom-accessibility-api": {
"version": "0.6.3",
"resolved": "https://registry.npmmirror.com/dom-accessibility-api/-/dom-accessibility-api-0.6.3.tgz",
"integrity": "sha512-7ZgogeTnjuHbo+ct10G9Ffp0mif17idi0IyWNVA/wcwcm7NPOD/WEHVP3n7n3MhXqxoIYm8d6MuZohYWIZ4T3w==",
"dev": true,
"license": "MIT"
},
"node_modules/@testing-library/react": {
"version": "16.3.2",
"resolved": "https://registry.npmmirror.com/@testing-library/react/-/react-16.3.2.tgz",
@@ -2011,6 +1987,37 @@
}
}
},
"node_modules/@vitest/coverage-v8": {
"version": "4.1.7",
"resolved": "https://registry.npmmirror.com/@vitest/coverage-v8/-/coverage-v8-4.1.7.tgz",
"integrity": "sha512-qsYPeXc5Q9dFLd1i8Ap+Bx8sQgcp+rFVQo4R0dDsWNBzl26ldVF1qOO+RL24K7FDrR6pA+50XedRLSoSG24bVQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@bcoe/v8-coverage": "^1.0.2",
"@vitest/utils": "4.1.7",
"ast-v8-to-istanbul": "^1.0.0",
"istanbul-lib-coverage": "^3.2.2",
"istanbul-lib-report": "^3.0.1",
"istanbul-reports": "^3.2.0",
"magicast": "^0.5.2",
"obug": "^2.1.1",
"std-env": "^4.0.0-rc.1",
"tinyrainbow": "^3.1.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@vitest/browser": "4.1.7",
"vitest": "4.1.7"
},
"peerDependenciesMeta": {
"@vitest/browser": {
"optional": true
}
}
},
"node_modules/@vitest/expect": {
"version": "4.1.7",
"resolved": "https://registry.npmmirror.com/@vitest/expect/-/expect-4.1.7.tgz",
@@ -2195,6 +2202,7 @@
"integrity": "sha512-b0P0sZPKtyu8HkeRAfCq0IfURZK+SuwMjY1UXGBU27wpAiTwQAIlq56IbIO+ytk/JjS1fMR14ee5WBBfKi5J6A==",
"dev": true,
"license": "Apache-2.0",
"peer": true,
"dependencies": {
"dequal": "^2.0.3"
}
@@ -2209,6 +2217,25 @@
"node": ">=12"
}
},
"node_modules/ast-v8-to-istanbul": {
"version": "1.0.2",
"resolved": "https://registry.npmmirror.com/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.2.tgz",
"integrity": "sha512-dKmJxJsGItLmc5CYZKuEjuG6GnBs6PG4gohMhyFOWKaNQoYCuRZJDECaBlHmcG0lv2wc2E0uU8lESmBEumC3DQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@jridgewell/trace-mapping": "^0.3.31",
"estree-walker": "^3.0.3",
"js-tokens": "^10.0.0"
}
},
"node_modules/ast-v8-to-istanbul/node_modules/js-tokens": {
"version": "10.0.0",
"resolved": "https://registry.npmmirror.com/js-tokens/-/js-tokens-10.0.0.tgz",
"integrity": "sha512-lM/UBzQmfJRo9ABXbPWemivdCW8V2G8FHaHdypQaIy523snUjog0W71ayWXTjiR+ixeMyVHN2XcpnTd/liPg/Q==",
"dev": true,
"license": "MIT"
},
"node_modules/balanced-match": {
"version": "4.0.4",
"resolved": "https://registry.npmmirror.com/balanced-match/-/balanced-match-4.0.4.tgz",
@@ -2356,13 +2383,6 @@
"node": "^10 || ^12.20.0 || ^14.13.0 || >=15.0.0"
}
},
"node_modules/css.escape": {
"version": "1.5.1",
"resolved": "https://registry.npmmirror.com/css.escape/-/css.escape-1.5.1.tgz",
"integrity": "sha512-YUifsXXuknHlUsmlgyY0PKzgPOr7/FjCePfHNt0jxm83wHZi44VDMQ7/fGNkjY3/jV1MC+1CmZbaHzugyeRtpg==",
"dev": true,
"license": "MIT"
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmmirror.com/csstype/-/csstype-3.2.3.tgz",
@@ -2422,6 +2442,7 @@
"integrity": "sha512-0je+qPKHEMohvfRTCEo3CrPG6cAzAYgmzKyxRiYSSDkS6eGJdyVJm7WaYA5ECaAD9wLB2T4EEeymA5aFVcYXCA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=6"
}
@@ -2853,6 +2874,16 @@
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"license": "ISC"
},
"node_modules/has-flag": {
"version": "4.0.0",
"resolved": "https://registry.npmmirror.com/has-flag/-/has-flag-4.0.0.tgz",
"integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/hermes-estree": {
"version": "0.25.1",
"resolved": "https://registry.npmmirror.com/hermes-estree/-/hermes-estree-0.25.1.tgz",
@@ -2883,6 +2914,13 @@
"node": "^20.19.0 || ^22.12.0 || >=24.0.0"
}
},
"node_modules/html-escaper": {
"version": "2.0.2",
"resolved": "https://registry.npmmirror.com/html-escaper/-/html-escaper-2.0.2.tgz",
"integrity": "sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg==",
"dev": true,
"license": "MIT"
},
"node_modules/html-parse-stringify": {
"version": "3.0.1",
"resolved": "https://registry.npmmirror.com/html-parse-stringify/-/html-parse-stringify-3.0.1.tgz",
@@ -2949,16 +2987,6 @@
"node": ">=0.8.19"
}
},
"node_modules/indent-string": {
"version": "4.0.0",
"resolved": "https://registry.npmmirror.com/indent-string/-/indent-string-4.0.0.tgz",
"integrity": "sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=8"
}
},
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmmirror.com/is-extglob/-/is-extglob-2.1.1.tgz",
@@ -2996,6 +3024,45 @@
"dev": true,
"license": "ISC"
},
"node_modules/istanbul-lib-coverage": {
"version": "3.2.2",
"resolved": "https://registry.npmmirror.com/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz",
"integrity": "sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg==",
"dev": true,
"license": "BSD-3-Clause",
"engines": {
"node": ">=8"
}
},
"node_modules/istanbul-lib-report": {
"version": "3.0.1",
"resolved": "https://registry.npmmirror.com/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz",
"integrity": "sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"istanbul-lib-coverage": "^3.0.0",
"make-dir": "^4.0.0",
"supports-color": "^7.1.0"
},
"engines": {
"node": ">=10"
}
},
"node_modules/istanbul-reports": {
"version": "3.2.0",
"resolved": "https://registry.npmmirror.com/istanbul-reports/-/istanbul-reports-3.2.0.tgz",
"integrity": "sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA==",
"dev": true,
"license": "BSD-3-Clause",
"dependencies": {
"html-escaper": "^2.0.0",
"istanbul-lib-report": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/jiti": {
"version": "2.7.0",
"resolved": "https://registry.npmmirror.com/jiti/-/jiti-2.7.0.tgz",
@@ -3429,6 +3496,47 @@
"@jridgewell/sourcemap-codec": "^1.5.5"
}
},
"node_modules/magicast": {
"version": "0.5.3",
"resolved": "https://registry.npmmirror.com/magicast/-/magicast-0.5.3.tgz",
"integrity": "sha512-pVKE4UdSQ7DvHzivsCIFx2BJn1mHG6KsyrFcaxFx6tONdneEuThrDx0Cj3AMg58KyN4pzYT+LHOotxDQDjNvkw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@babel/parser": "^7.29.3",
"@babel/types": "^7.29.0",
"source-map-js": "^1.2.1"
}
},
"node_modules/make-dir": {
"version": "4.0.0",
"resolved": "https://registry.npmmirror.com/make-dir/-/make-dir-4.0.0.tgz",
"integrity": "sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw==",
"dev": true,
"license": "MIT",
"dependencies": {
"semver": "^7.5.3"
},
"engines": {
"node": ">=10"
},
"funding": {
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/make-dir/node_modules/semver": {
"version": "7.8.1",
"resolved": "https://registry.npmmirror.com/semver/-/semver-7.8.1.tgz",
"integrity": "sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg==",
"dev": true,
"license": "ISC",
"bin": {
"semver": "bin/semver.js"
},
"engines": {
"node": ">=10"
}
},
"node_modules/mdn-data": {
"version": "2.27.1",
"resolved": "https://registry.npmmirror.com/mdn-data/-/mdn-data-2.27.1.tgz",
@@ -3436,16 +3544,6 @@
"dev": true,
"license": "CC0-1.0"
},
"node_modules/min-indent": {
"version": "1.0.1",
"resolved": "https://registry.npmmirror.com/min-indent/-/min-indent-1.0.1.tgz",
"integrity": "sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=4"
}
},
"node_modules/minimatch": {
"version": "10.2.5",
"resolved": "https://registry.npmmirror.com/minimatch/-/minimatch-10.2.5.tgz",
@@ -3790,20 +3888,6 @@
"license": "MIT",
"peer": true
},
"node_modules/redent": {
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/redent/-/redent-3.0.0.tgz",
"integrity": "sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg==",
"dev": true,
"license": "MIT",
"dependencies": {
"indent-string": "^4.0.0",
"strip-indent": "^3.0.0"
},
"engines": {
"node": ">=8"
}
},
"node_modules/require-from-string": {
"version": "2.0.2",
"resolved": "https://registry.npmmirror.com/require-from-string/-/require-from-string-2.0.2.tgz",
@@ -3929,14 +4013,14 @@
"dev": true,
"license": "MIT"
},
"node_modules/strip-indent": {
"version": "3.0.0",
"resolved": "https://registry.npmmirror.com/strip-indent/-/strip-indent-3.0.0.tgz",
"integrity": "sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ==",
"node_modules/supports-color": {
"version": "7.2.0",
"resolved": "https://registry.npmmirror.com/supports-color/-/supports-color-7.2.0.tgz",
"integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==",
"dev": true,
"license": "MIT",
"dependencies": {
"min-indent": "^1.0.0"
"has-flag": "^4.0.0"
},
"engines": {
"node": ">=8"
+5 -2
View File
@@ -1,15 +1,18 @@
{
"name": "patheditor",
"private": true,
"version": "5.0.0",
"version": "5.1.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "cargo fmt",
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"test:e2e": "playwright test --config e2e/playwright.config.ts"
},
"dependencies": {
@@ -28,12 +31,12 @@
"@eslint/js": "^10.0.1",
"@playwright/test": "^1.60.0",
"@tauri-apps/cli": "^2.11.2",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
"@types/node": "^24.12.3",
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"@vitest/coverage-v8": "^4.1.7",
"eslint": "^10.3.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
+2
View File
@@ -0,0 +1,2 @@
[toolchain]
channel = "stable-x86_64-pc-windows-gnu"
+6 -3
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useMemo } from 'react';
import { useState, useEffect, useMemo, useRef } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { useTranslation } from 'react-i18next';
import { Modal } from '@/components/ui/Modal';
@@ -35,8 +35,11 @@ export function AnalyzeDialog({ open, onClose }: Props) {
const [toolGroups, setToolGroups] = useState<ToolGroup[]>([]);
const [searchQuery, setSearchQuery] = useState('');
const prevOpen = useRef(false);
useEffect(() => {
if (!open) return;
if (!open) { prevOpen.current = false; return; }
if (prevOpen.current) return;
prevOpen.current = true;
setLoading(true);
const paths = getEnabledPaths();
Promise.all([
@@ -182,7 +185,7 @@ function ToolsTab({
opacity: g.exists ? 1 : 0.6,
}}
>
{g.dir} {!g.exists && '(不存在)'}
{g.dir} {!g.exists && t('analyze.notExists')}
</div>
<div className="flex flex-wrap gap-1 mt-1 ml-2">
{g.exes.map((exe) => (
+2 -2
View File
@@ -16,9 +16,9 @@ export function ImportDialog({ open, systemCount, userCount, onSelect, onCancel
<Modal open={open} onClose={onCancel}>
<h2 className="text-lg font-semibold mb-4">{t('dialog.importTarget')}</h2>
<p className="text-sm mb-4 opacity-70">
{systemCount > 0 && `系统变量: ${systemCount}`}
{systemCount > 0 && t('dialog.importSystemCount', { count: systemCount })}
{systemCount > 0 && userCount > 0 && ' | '}
{userCount > 0 && `用户变量: ${userCount}`}
{userCount > 0 && t('dialog.importUserCount', { count: userCount })}
</p>
<div className="flex flex-col gap-2">
{systemCount > 0 && <button className="px-4 py-2 text-sm rounded border text-left" style={{ borderColor: 'var(--app-border)' }} onClick={() => onSelect('system')}>{t('dialog.importSystem')}</button>}
+10 -7
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useCallback } from 'react';
import { useState, useEffect, useCallback, useRef } from 'react';
import { invoke } from '@tauri-apps/api/core';
import { useTranslation } from 'react-i18next';
import { Modal } from '@/components/ui/Modal';
@@ -39,8 +39,10 @@ export function ProfileDialog({ open, onClose }: Props) {
setProfiles(list);
}, []);
const prevOpen = useRef(false);
useEffect(() => {
if (open) refreshProfiles();
if (open && !prevOpen.current) refreshProfiles();
prevOpen.current = open;
}, [open, refreshProfiles]);
const handleSave = async () => {
@@ -149,7 +151,7 @@ export function ProfileDialog({ open, onClose }: Props) {
<div className="flex-1 p-3 overflow-auto">
{!selectedData ? (
<div className="text-center py-10 text-sm" style={{ opacity: 0.4 }}>
{profiles.length === 0 ? t('profile.noProfiles') : '选择一个配置文件'}
{profiles.length === 0 ? t('profile.noProfiles') : t('profile.selectProfile')}
</div>
) : (
<div>
@@ -192,7 +194,7 @@ export function ProfileDialog({ open, onClose }: Props) {
style={{ backgroundColor: 'var(--app-list-bg)', color: 'var(--app-fg)', borderColor: 'var(--app-border)' }}
/>
<button className="px-2 py-1 text-xs rounded text-white" style={{ backgroundColor: '#3b82f6' }} onClick={handleRename}>
{t('button.save')}
</button>
</div>
)}
@@ -209,16 +211,17 @@ export function ProfileDialog({ open, onClose }: Props) {
}
function PathSection({ title, paths }: { title: string; paths: PathEntry[] }) {
const { t } = useTranslation();
return (
<div className="mb-2">
<div className="text-xs font-medium mb-1" style={{ opacity: 0.7 }}>{title}</div>
{paths.length === 0 ? (
<div className="text-xs" style={{ opacity: 0.4 }}></div>
<div className="text-xs" style={{ opacity: 0.4 }}>{t('profile.empty')}</div>
) : (
<div className="space-y-0.5 max-h-48 overflow-auto">
{paths.map((e, i) => (
{paths.map((e) => (
<div
key={i}
key={e.path}
className="text-xs font-mono px-2 py-0.5 rounded flex items-center gap-1.5"
style={{
backgroundColor: 'var(--app-list-bg)',
+11 -81
View File
@@ -1,7 +1,9 @@
import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import { useMemo, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useAppStore } from '@/store/app-store';
import { invoke } from '@tauri-apps/api/core';
import { TargetType } from '@/core/undo-redo';
import { usePathValidation } from '@/hooks/use-path-validation';
import type { ValidationState } from '@/hooks/use-path-validation';
interface PathTableProps {
tabId: 'system' | 'user';
@@ -13,10 +15,8 @@ interface PathRow {
enabled: boolean;
}
type ValidationState = 'valid' | 'invalid' | 'unknown';
const DEFAULT_VALIDATION_STATE: ValidationState = 'valid';
export function PathTable({ tabId }: PathTableProps) {
const { t } = useTranslation();
const sysPaths = useAppStore((s) => s.sysPaths);
const userPaths = useAppStore((s) => s.userPaths);
const searchQuery = useAppStore((s) => s.searchQuery);
@@ -27,15 +27,9 @@ export function PathTable({ tabId }: PathTableProps) {
const paths = tabId === 'system' ? sysPaths : userPaths;
const isActive = activeTab === tabId;
// 本次会话中已验证过的路径缓存(key=path, value=ValidationState
const [validationCache, setValidationCache] = useState<Map<string, ValidationState>>(new Map());
// 环境变量展开结果缓存(key=path, value=expanded
const [expandedCache, setExpandedCache] = useState<Map<string, string>>(new Map());
const { validationCache, expandedCache } = usePathValidation(paths);
const validatedRef = useRef<Set<string>>(new Set());
const expandedRef = useRef<Set<string>>(new Set());
// 过滤搜索
// 搜索过滤
const filtered = useMemo<PathRow[]>(() => {
if (!searchQuery) return paths.map((p, i) => ({ path: p.path, index: i, enabled: p.enabled }));
const q = searchQuery.toLowerCase();
@@ -47,79 +41,15 @@ export function PathTable({ tabId }: PathTableProps) {
return result;
}, [paths, searchQuery]);
// 异步验证未缓存的路径
useEffect(() => {
let cancelled = false;
const toValidate = paths.filter((p) => !validatedRef.current.has(p.path));
if (toValidate.length === 0) return;
const batch = toValidate.slice(0, 20);
Promise.all(
batch.map(async (p): Promise<[string, ValidationState]> => {
try {
if (p.path.includes('%')) return [p.path, 'valid'];
const valid: boolean = await invoke('validate_path', { path: p.path });
return [p.path, valid ? 'valid' : 'invalid'];
} catch {
return [p.path, 'unknown'];
}
}),
).then((results) => {
if (cancelled) return;
for (const [p] of results) validatedRef.current.add(p);
setValidationCache((prev) => {
const next = new Map(prev);
for (const [p, v] of results) next.set(p, v);
return next;
});
});
return () => { cancelled = true; };
}, [paths]);
// 异步展开环境变量(用于 tooltip)
useEffect(() => {
let cancelled = false;
const toExpand = paths.filter(
(p) => p.path.includes('%') && !expandedRef.current.has(p.path),
);
if (toExpand.length === 0) return;
const batch = toExpand.slice(0, 20);
Promise.all(
batch.map(async (p): Promise<[string, string]> => {
try {
const expanded: string = await invoke('expand_env_vars', { path: p.path });
return [p.path, expanded !== p.path ? expanded : ''];
} catch {
return [p.path, ''];
}
}),
).then((results) => {
if (cancelled) return;
for (const [p] of results) expandedRef.current.add(p);
setExpandedCache((prev) => {
const next = new Map(prev);
for (const [p, v] of results) next.set(p, v);
return next;
});
});
return () => { cancelled = true; };
}, [paths]);
// 所有路径默认有效(异步验证结果回来后再精确染色)
// 计算验证状态(含去重检测)
const validations = useMemo(() => {
const seen = new Set<string>();
return filtered.map(({ path }) => {
const lower = path.toLowerCase();
const isDuplicate = seen.has(lower);
seen.add(lower);
return {
state: validationCache.get(path) ?? DEFAULT_VALIDATION_STATE,
isDuplicate,
isEnvVar: path.includes('%'),
};
const state: ValidationState = validationCache.get(path) ?? 'valid';
return { state, isDuplicate, isEnvVar: path.includes('%') };
});
}, [filtered, validationCache]);
@@ -160,7 +90,7 @@ export function PathTable({ tabId }: PathTableProps) {
>
<th className="w-8 px-2 py-1">#</th>
<th className="w-6 px-1 py-1"></th>
<th className="px-2 py-1"></th>
<th className="px-2 py-1">{t('table.path')}</th>
</tr>
</thead>
<tbody>
@@ -6,6 +6,9 @@ export function UndoRedoButtons() {
const { t } = useTranslation();
const isAdmin = useAppStore((s) => s.isAdmin);
const undoRedo = useAppStore((s) => s.undoRedo);
// 订阅路径数组长度变化,确保 undoRedo 内部状态变化时触发重渲染
useAppStore((s) => s.sysPaths.length);
useAppStore((s) => s.userPaths.length);
const undo = useAppStore((s) => s.undo);
const redo = useAppStore((s) => s.redo);
+10 -2
View File
@@ -117,8 +117,16 @@ export function useAppActions(activeTab: TabId, dialogs: DialogState) {
URL.revokeObjectURL(url);
}, []);
const handleSave = useCallback(() => {
useAppStore.getState().savePaths();
const handleSave = useCallback(async () => {
const saved = await useAppStore.getState().savePaths();
if (!saved && !useAppStore.getState().isSaving) {
// 长度超限,需要用户确认
const { ask } = await import('@tauri-apps/plugin-dialog');
const confirmed = await ask(i18n.t('status.saveWarningLongPaths'), { title: i18n.t('dialog.backupTitle'), kind: 'warning' });
if (confirmed) {
await useAppStore.getState().savePaths(true);
}
}
}, []);
// ── 键盘 ──
-5
View File
@@ -56,11 +56,6 @@ export function useKeyboard(actions: KeyboardActions) {
if (!isAdmin) return;
e.preventDefault();
a.onDelete();
} else if (ctrl && e.key === 'f') {
e.preventDefault();
const searchInput = document.querySelector<HTMLInputElement>('input[placeholder]');
searchInput?.focus();
searchInput?.select();
} else if (e.key === 'F1') {
e.preventDefault();
a.onHelp();
+125
View File
@@ -0,0 +1,125 @@
import { useState, useEffect, useRef, useMemo } from 'react';
import { invoke } from '@tauri-apps/api/core';
import type { PathEntry } from '@/core/path-entry';
export type ValidationState = 'valid' | 'invalid' | 'unknown';
/**
* 异步验证路径目录是否真实存在 + 展开环境变量
* 缓存结果避免重复 IPC 调用。
* setState 仅在异步 .then() 回调中调用(符合 React 规则),
* 不存在路径的缓存清理通过 useMemo 派生。
*/
export function usePathValidation(paths: readonly PathEntry[]) {
const validatedRef = useRef<Set<string>>(new Set());
const expandedRef = useRef<Set<string>>(new Set());
const [validationCache, setValidationCache] = useState<Map<string, ValidationState>>(new Map());
const [expandedCache, setExpandedCache] = useState<Map<string, string>>(new Map());
// 仅保留当前 paths 中存在的条目(派生 state,不在 effect 中同步 setState
const currentKeys = useMemo(() => new Set(paths.map((p) => p.path)), [paths]);
const cleanedValidationCache = useMemo(() => {
const next = new Map(validationCache);
let changed = false;
for (const key of next.keys()) {
if (!currentKeys.has(key)) {
next.delete(key);
changed = true;
}
}
return changed ? next : validationCache;
}, [validationCache, currentKeys]);
const cleanedExpandedCache = useMemo(() => {
const next = new Map(expandedCache);
let changed = false;
for (const key of next.keys()) {
if (!currentKeys.has(key)) {
next.delete(key);
changed = true;
}
}
return changed ? next : expandedCache;
}, [expandedCache, currentKeys]);
// 同步清理 refref 不能在 render 期间修改,放在 effect 中不 setState 是安全的)
useEffect(() => {
for (const key of validatedRef.current) {
if (!currentKeys.has(key)) validatedRef.current.delete(key);
}
for (const key of expandedRef.current) {
if (!currentKeys.has(key)) expandedRef.current.delete(key);
}
}, [currentKeys]);
// 异步验证路径(setState 在 .then() 回调中,符合 React 规则)
useEffect(() => {
let cancelled = false;
const toValidate = paths.filter((p) => !validatedRef.current.has(p.path));
if (toValidate.length === 0) return;
const batch = toValidate.slice(0, 20);
Promise.all(
batch.map(
async (p): Promise<[string, ValidationState]> => {
try {
if (p.path.includes('%')) return [p.path, 'valid'];
const valid: boolean = await invoke('validate_path', { path: p.path });
return [p.path, valid ? 'valid' : 'invalid'];
} catch {
return [p.path, 'unknown'];
}
},
),
).then((results) => {
if (cancelled) return;
for (const [p] of results) validatedRef.current.add(p);
setValidationCache((prev) => {
const next = new Map(prev);
for (const [p, v] of results) next.set(p, v);
return next;
});
});
return () => {
cancelled = true;
};
}, [paths]);
// 异步展开环境变量(setState 在 .then() 回调中)
useEffect(() => {
let cancelled = false;
const toExpand = paths.filter(
(p) => p.path.includes('%') && !expandedRef.current.has(p.path),
);
if (toExpand.length === 0) return;
const batch = toExpand.slice(0, 20);
Promise.all(
batch.map(
async (p): Promise<[string, string]> => {
try {
const expanded: string = await invoke('expand_env_vars', { path: p.path });
return [p.path, expanded !== p.path ? expanded : ''];
} catch {
return [p.path, ''];
}
},
),
).then((results) => {
if (cancelled) return;
for (const [p] of results) expandedRef.current.add(p);
setExpandedCache((prev) => {
const next = new Map(prev);
for (const [p, v] of results) next.set(p, v);
return next;
});
});
return () => {
cancelled = true;
};
}, [paths]);
return { validationCache: cleanedValidationCache, expandedCache: cleanedExpandedCache };
}
+13 -4
View File
@@ -8,6 +8,9 @@
"user": "User Variables",
"merged": "Merge Preview"
},
"table": {
"path": "Path"
},
"button": {
"new": "New",
"edit": "Edit",
@@ -51,7 +54,8 @@
"readonly_label": "Read-only",
"light": "Light",
"dark": "Dark",
"adminWarning": "Running without administrator privileges, some features are disabled"
"adminWarning": "Running without administrator privileges, some features are disabled",
"saveWarningLongPaths": "PATH length exceeds recommended value. Continue saving?"
},
"dialog": {
"newPath": "New Path",
@@ -70,7 +74,9 @@
"backupMessage": "Back up registry before saving?",
"confirm": "Confirm",
"cancel": "Cancel",
"search": "Search paths..."
"search": "Search paths...",
"importSystemCount": "System: {{count}} entries",
"importUserCount": "User: {{count}} entries"
},
"analyze": {
"title": "PATH Analysis",
@@ -82,7 +88,8 @@
"priority": "Prioritized",
"shadowed": "Shadowed",
"searchPlaceholder": "Search executable name...",
"conflictCount": "{{count}} file conflict(s) found"
"conflictCount": "{{count}} file conflict(s) found",
"notExists": "(not found)"
},
"profile": {
"title": "PATH Profiles",
@@ -95,7 +102,9 @@
"rename": "Rename",
"noProfiles": "No saved profiles",
"applyConfirm": "This will overwrite current PATH with profile \"{{name}}\" and write to registry. Confirm?",
"deleted": "Profile \"{{name}}\" deleted"
"deleted": "Profile \"{{name}}\" deleted",
"selectProfile": "Select a profile",
"empty": "(empty)"
},
"help": {
"content": "PathEditor v5.0 — Windows System Environment Variable (PATH) Editor\n\nFeatures:\n• Create/Edit/Delete path entries\n• Move Up/Down to adjust priority\n• One-click cleanup of invalid & duplicate paths\n• Import/Export JSON, CSV, TXT formats\n• Full Undo/Redo support\n\nShortcuts:\n• Ctrl+N New\n• Ctrl+S Save\n• Ctrl+Z Undo\n• Ctrl+Y Redo\n• Ctrl+F Search\n• Delete Delete selected\n• F1 Help\n\nAuthor: 刘航宇\nGitHub: https://github.com/LHY0125/PathEditor"
+13 -4
View File
@@ -8,6 +8,9 @@
"user": "用户变量",
"merged": "合并预览"
},
"table": {
"path": "路径"
},
"button": {
"new": "新建",
"edit": "编辑",
@@ -51,7 +54,8 @@
"modified": "已修改",
"readonly_label": "只读",
"light": "浅色",
"dark": "深色"
"dark": "深色",
"saveWarningLongPaths": "PATH 长度超过建议值,是否继续保存?"
},
"dialog": {
"newPath": "新建路径",
@@ -70,7 +74,9 @@
"backupMessage": "保存前需要备份注册表吗?",
"confirm": "确认",
"cancel": "取消",
"search": "搜索路径..."
"search": "搜索路径...",
"importSystemCount": "系统变量: {{count}} 条",
"importUserCount": "用户变量: {{count}} 条"
},
"analyze": {
"title": "PATH 分析",
@@ -82,7 +88,8 @@
"priority": "优先执行",
"shadowed": "被遮蔽",
"searchPlaceholder": "搜索可执行文件名...",
"conflictCount": "发现 {{count}} 个文件冲突"
"conflictCount": "发现 {{count}} 个文件冲突",
"notExists": "(不存在)"
},
"profile": {
"title": "PATH 配置文件",
@@ -95,7 +102,9 @@
"rename": "重命名",
"noProfiles": "暂无配置文件",
"applyConfirm": "将用配置 \"{{name}}\" 覆盖当前 PATH 并写入注册表,确定吗?",
"deleted": "已删除配置 \"{{name}}\""
"deleted": "已删除配置 \"{{name}}\"",
"selectProfile": "选择一个配置文件",
"empty": "(空)"
},
"help": {
"content": "PathEditor v5.0 — Windows 系统环境变量 (PATH) 编辑器\n\n功能:\n• 新建/编辑/删除路径条目\n• 上移/下移调整优先级\n• 一键清理无效和重复路径\n• 导入/导出 JSON、CSV、TXT 格式\n• 完整撤销/重做支持\n\n快捷键:\n• Ctrl+N 新建\n• Ctrl+S 保存\n• Ctrl+Z 撤销\n• Ctrl+Y 重做\n• Ctrl+F 搜索\n• Delete 删除选中\n• F1 帮助\n\n作者: 刘航宇\nGitHub: https://github.com/LHY0125/PathEditor"
+12 -8
View File
@@ -45,7 +45,7 @@ interface AppState {
redo: () => void;
loadPaths: () => Promise<void>;
savePaths: () => Promise<void>;
savePaths: (force?: boolean) => Promise<boolean>;
initialize: () => Promise<void>;
}
@@ -248,7 +248,7 @@ export const useAppStore = create<AppState>((set, get) => {
const sysDisabled = sys.filter(e => !e.enabled).map(e => e.path);
const usrDisabled = usr.filter(e => !e.enabled).map(e => e.path);
invoke('save_disabled_state', { system: sysDisabled, user: usrDisabled })
.catch(() => {});
.catch((e) => console.warn('保存禁用状态失败:', e));
},
undo: () => {
@@ -264,7 +264,7 @@ export const useAppStore = create<AppState>((set, get) => {
invoke('save_disabled_state', {
system: result[0].filter(e => !e.enabled).map(e => e.path),
user: result[1].filter(e => !e.enabled).map(e => e.path),
}).catch(() => {});
}).catch((e) => console.warn('保存禁用状态失败:', e));
}
},
@@ -281,7 +281,7 @@ export const useAppStore = create<AppState>((set, get) => {
invoke('save_disabled_state', {
system: result[0].filter(e => !e.enabled).map(e => e.path),
user: result[1].filter(e => !e.enabled).map(e => e.path),
}).catch(() => {});
}).catch((e) => console.warn('保存禁用状态失败:', e));
}
},
@@ -322,9 +322,9 @@ export const useAppStore = create<AppState>((set, get) => {
}
},
savePaths: async () => {
savePaths: async (force?: boolean) => {
const state = get();
if (state.isSaving) return;
if (state.isSaving) return false;
set({ isSaving: true, statusMessage: i18n.t('status.saving') });
// 只保存 enabled 的路径到注册表
@@ -333,9 +333,11 @@ export const useAppStore = create<AppState>((set, get) => {
const sysJoined = sysPaths.join(';');
const userJoined = userPaths.join(';');
// 长度检查:非强制模式下返回警告,由 UI 层确认
const { maxSystemLength, maxUserLength, maxCombinedLength } = appConfig.path;
if (sysJoined.length > maxSystemLength || userJoined.length > maxUserLength || (sysJoined + userJoined).length > maxCombinedLength) {
if (!window.confirm('PATH 长度超过建议值,是否继续保存?')) { set({ isSaving: false }); return; }
if (!force && (sysJoined.length > maxSystemLength || userJoined.length > maxUserLength || (sysJoined + userJoined).length > maxCombinedLength)) {
set({ isSaving: false, statusMessage: i18n.t('status.saveWarningLongPaths') });
return false;
}
// 备份当前注册表(保存前备份旧值,失败仅警告不中断)
@@ -357,12 +359,14 @@ export const useAppStore = create<AppState>((set, get) => {
set({ isModified: false, isSaving: false,
statusMessage: backupFailed ? i18n.t('status.saved_without_backup') : i18n.t('status.saved'),
_savedSys: savedSys, _savedUser: savedUser });
return true;
} else {
const sysErr = (!sysOk && sysResult.status === 'rejected') ? String(sysResult.reason) : '';
const usrErr = (!userOk && userResult.status === 'rejected') ? String(userResult.reason) : '';
const parts = [sysErr, usrErr].filter(Boolean);
const msg = sysOk ? '用户 PATH 保存失败' : userOk ? '系统 PATH 保存失败' : `保存失败: ${parts.join('; ')}`;
set({ isSaving: false, statusMessage: msg });
return false;
}
},
-1
View File
@@ -1,4 +1,3 @@
// @vitest-environment jsdom
import { describe, it, expect, vi } from 'vitest';
import { render } from '@testing-library/react';
import { AnalyzeDialog } from '../../src/components/dialogs/AnalyzeDialog';
+2 -2
View File
@@ -268,8 +268,8 @@ describe('savePaths', () => {
// 第二次调用应被 isSaving 守卫拦截(此时 isSaving=true
const r2 = useAppStore.getState().savePaths();
// 第二次调用同步返回 undefined(被守卫拦截)
await expect(r2).resolves.toBeUndefined();
// 第二次调用同步返回 false(被守卫拦截)
await expect(r2).resolves.toBe(false);
// 放行第一次调用的所有 invoke
resolveAll!(undefined);
-1
View File
@@ -1,4 +1,3 @@
// @vitest-environment jsdom
import { describe, it, expect, vi } from 'vitest';
import { render } from '@testing-library/react';
import { MergePreview } from '../../src/components/path-list/MergePreview';
+26 -1
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { pathClean } from '../../src/core/path-manager';
import { pathClean, analyzePaths } from '../../src/core/path-manager';
import type { PathEntry } from '../../src/core/path-entry';
function pe(s: string, enabled: boolean = true): PathEntry {
@@ -9,6 +9,31 @@ function pe(s: string, enabled: boolean = true): PathEntry {
const alwaysValid = () => true;
const validateFn = (path: string) => !path.includes('Invalid');
describe('analyzePaths', () => {
it('检测大小写重复', () => {
const result = analyzePaths([pe('C:\\Windows'), pe('c:\\windows')], alwaysValid);
expect(result[0].isDuplicate).toBe(false);
expect(result[1].isDuplicate).toBe(true);
});
it('识别环境变量路径', () => {
const result = analyzePaths([pe('C:\\Normal'), pe('%JAVA_HOME%\\bin')], alwaysValid);
expect(result[0].isEnvVar).toBe(false);
expect(result[1].isEnvVar).toBe(true);
});
it('标记无效路径', () => {
const result = analyzePaths([pe('C:\\Valid'), pe('C:\\Invalid')], validateFn);
expect(result[0].isValid).toBe(true);
expect(result[1].isValid).toBe(false);
});
it('空数组返回空', () => {
const result = analyzePaths([], alwaysValid);
expect(result).toEqual([]);
});
});
describe('pathClean', () => {
it('移除无效路径', () => {
const [kept, removed] = pathClean([pe('C:\\Valid'), pe('C:\\Invalid'), pe('D:\\Valid')], validateFn);
+25
View File
@@ -174,4 +174,29 @@ describe('UndoRedoManager', () => {
const r = mgr.redo(...u)!;
expect(r[0][0].enabled).toBe(false);
});
it('IMPORT_BOTH 撤销/重做(同时修改系统和用户路径)', () => {
const oldSys = [...sys];
const oldUser = [...user];
const newSys = [pe('C:\\ImportedSys')];
const newUser = [pe('C:\\ImportedUser')];
mgr.push({
type: OperationType.IMPORT_BOTH,
target: TargetType.SYSTEM,
index: 0, count: 0,
oldPaths: oldSys, newPaths: newSys,
oldPathsOther: oldUser, newPathsOther: newUser,
});
sys = newSys;
user = newUser;
const u = mgr.undo(sys, user)!;
expect(u[0]).toEqual(oldSys);
expect(u[1]).toEqual(oldUser);
const r = mgr.redo(...u)!;
expect(r[0]).toEqual(newSys);
expect(r[1]).toEqual(newUser);
});
});
+233
View File
@@ -0,0 +1,233 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
// ── Mock 外部依赖 ──
vi.mock('@tauri-apps/api/core', () => ({
invoke: vi.fn().mockResolvedValue(undefined),
}));
const mockOpen = vi.fn().mockResolvedValue(null);
const mockAsk = vi.fn().mockResolvedValue(true);
vi.mock('@tauri-apps/plugin-dialog', () => ({
open: (...args: unknown[]) => mockOpen(...args),
ask: (...args: unknown[]) => mockAsk(...args),
}));
vi.mock('@/i18n', () => ({
default: { t: vi.fn((key: string, opts?: Record<string, unknown>) => {
if (key === 'status.deleted') return `已删除 ${opts?.count}`;
if (key === 'status.saveWarningLongPaths') return 'PATH 长度超限';
return key;
}) },
}));
vi.mock('@/hooks/use-keyboard', () => ({
useKeyboard: vi.fn(),
}));
import { renderHook, act } from '@testing-library/react';
import { useAppStore } from '@/store/app-store';
import { UndoRedoManager, TargetType } from '@/core/undo-redo';
import { invoke } from '@tauri-apps/api/core';
import type { PathEntry } from '@/core/path-entry';
const mockedInvoke = vi.mocked(invoke);
function pe(s: string, enabled = true): PathEntry {
return { path: s, enabled };
}
function resetStore(sys: PathEntry[] = [], user: PathEntry[] = []) {
useAppStore.setState({
sysPaths: sys,
userPaths: user,
undoRedo: new UndoRedoManager(50),
_savedSys: sys,
_savedUser: user,
selectedIndices: [],
isModified: false,
isLoading: false,
isSaving: false,
isAdmin: true,
statusMessage: '',
});
}
// useAppActions 需要 DialogState,创建一个 mock
function mockDialogs() {
return {
editDialog: { open: false, index: -1, value: '', target: TargetType.SYSTEM },
newDialog: false,
helpOpen: false,
importDialog: { open: false, system: [] as PathEntry[], user: [] as PathEntry[] },
setEditDialog: vi.fn(),
setNewDialog: vi.fn(),
setHelpOpen: vi.fn(),
setImportDialog: vi.fn(),
setAnalyzeOpen: vi.fn(),
setProfilesOpen: vi.fn(),
};
}
describe('useAppActions', () => {
let dialogs: ReturnType<typeof mockDialogs>;
beforeEach(() => {
vi.clearAllMocks();
resetStore([pe('C:\\Windows'), pe('C:\\Program Files')], [pe('D:\\User')]);
dialogs = mockDialogs();
});
// ── handleNew ──
it('handleNew 打开新建弹窗', async () => {
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleNew(); });
expect(dialogs.setNewDialog).toHaveBeenCalledWith(true);
});
// ── handleEdit ──
it('handleEdit 打开编辑弹窗(有选中项)', async () => {
useAppStore.setState({ selectedIndices: [0] });
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleEdit(); });
expect(dialogs.setEditDialog).toHaveBeenCalledWith({
open: true, index: 0, value: 'C:\\Windows', target: TargetType.SYSTEM,
});
});
it('handleEdit 无选中项不操作', async () => {
useAppStore.setState({ selectedIndices: [] });
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleEdit(); });
expect(dialogs.setEditDialog).not.toHaveBeenCalled();
});
// ── handleDelete ──
it('handleDelete 删除选中项', async () => {
useAppStore.setState({ selectedIndices: [0] });
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleDelete(); });
expect(useAppStore.getState().sysPaths.map(e => e.path)).toEqual(['C:\\Program Files']);
});
it('handleDelete 无选中项不操作', async () => {
useAppStore.setState({ selectedIndices: [] });
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleDelete(); });
expect(useAppStore.getState().sysPaths.length).toBe(2);
});
// ── handleMoveUp / handleMoveDown ──
it('handleMoveUp 上移选中项', async () => {
useAppStore.setState({ selectedIndices: [1] });
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleMoveUp(); });
expect(useAppStore.getState().sysPaths.map(e => e.path)).toEqual(['C:\\Program Files', 'C:\\Windows']);
});
it('handleMoveDown 下移选中项', async () => {
useAppStore.setState({ selectedIndices: [0] });
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleMoveDown(); });
expect(useAppStore.getState().sysPaths.map(e => e.path)).toEqual(['C:\\Program Files', 'C:\\Windows']);
});
// ── handleClean ──
it('handleClean 清理无效路径', async () => {
resetStore([pe('C:\\Windows'), pe('invalid_path!@#')]);
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleClean(); });
expect(useAppStore.getState().sysPaths.map(e => e.path)).toEqual(['C:\\Windows']);
expect(useAppStore.getState().statusMessage).toContain('已删除 1 条');
});
// ── handleNewConfirm ──
it('handleNewConfirm 添加新路径', async () => {
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleNewConfirm('C:\\New'); });
expect(useAppStore.getState().sysPaths.map(e => e.path)).toContain('C:\\New');
expect(dialogs.setNewDialog).toHaveBeenCalledWith(false);
});
it('handleNewConfirm 空白不添加', async () => {
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleNewConfirm(' '); });
expect(useAppStore.getState().sysPaths.length).toBe(2);
});
// ── handleEditConfirm ──
it('handleEditConfirm 修改路径', async () => {
dialogs.editDialog = { open: true, index: 0, value: 'C:\\Windows', target: TargetType.SYSTEM };
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleEditConfirm('C:\\Edited'); });
expect(useAppStore.getState().sysPaths[0].path).toBe('C:\\Edited');
});
// ── handleImportSelect ──
it('handleImportSelect both 模式替换双 hive', async () => {
const sysImport = [pe('C:\\ImportSys')];
const usrImport = [pe('D:\\ImportUsr')];
dialogs.importDialog = { open: true, system: sysImport, user: usrImport };
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleImportSelect('both'); });
expect(useAppStore.getState().sysPaths.map(e => e.path)).toEqual(['C:\\ImportSys']);
expect(useAppStore.getState().userPaths.map(e => e.path)).toEqual(['D:\\ImportUsr']);
expect(dialogs.setImportDialog).toHaveBeenCalledWith({ open: false, system: [], user: [] });
});
it('handleImportSelect system 模式只替换 system', async () => {
dialogs.importDialog = { open: true, system: [pe('C:\\ImportSys')], user: [pe('D:\\ImportUsr')] };
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
act(() => { result.current.handleImportSelect('system'); });
expect(useAppStore.getState().sysPaths.map(e => e.path)).toEqual(['C:\\ImportSys']);
expect(useAppStore.getState().userPaths.map(e => e.path)).toEqual(['D:\\User']); // 未变
});
// ── handleSave ──
it('handleSave 正常保存', async () => {
mockedInvoke.mockResolvedValue(undefined);
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
await act(async () => { await result.current.handleSave(); });
// invoke 被调用(backup + save_system + save_user + broadcast
expect(mockedInvoke).toHaveBeenCalled();
});
it('handleSave 超长确认后强制保存', async () => {
// 第一次 savePaths 返回 false(超长)
// 第二次(force=true)返回 true
let callCount = 0;
vi.spyOn(useAppStore.getState(), 'savePaths').mockImplementation(async (force?: boolean) => {
callCount++;
if (!force) return false; // 第一次:超长警告
return true; // 第二次:强制保存成功
});
const { useAppActions } = await import('@/hooks/use-app-actions');
const { result } = renderHook(() => useAppActions('system', dialogs));
await act(async () => { await result.current.handleSave(); });
expect(callCount).toBe(2);
expect(mockAsk).toHaveBeenCalled();
});
});
+2 -1
View File
@@ -2,6 +2,7 @@
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
{ "path": "./tsconfig.node.json" },
{ "path": "./tsconfig.test.json" }
]
}
+8
View File
@@ -0,0 +1,8 @@
{
"extends": "./tsconfig.app.json",
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.test.tsbuildinfo",
"types": ["vite/client", "vitest/globals"]
},
"include": ["src", "tests", "e2e"]
}
+9
View File
@@ -8,6 +8,15 @@ export default defineConfig({
},
},
test: {
environment: 'jsdom',
exclude: ['e2e/**', 'node_modules/**', 'gui/**'],
coverage: {
provider: 'v8',
reporter: ['text', 'lcov'],
include: ['src/core/**', 'src/store/**', 'src/hooks/**'],
thresholds: {
lines: 80,
},
},
},
});