Compare commits

..

2 Commits

Author SHA1 Message Date
Serendipity d5f3f5750c docs: 添加应用截图到 README
CI / 前端检查 (格式 + 类型 + Lint + 测试 + 覆盖率) (push) Has been cancelled
CI / Rust 检查 (格式 + Check + Clippy + Test) (push) Has been cancelled
2026-06-19 19:19:58 +08:00
Serendipity 8c0e80d862 chore: 开源项目基础设施全面完善
新增配置文件:
- .editorconfig — 跨编辑器代码风格统一
- .gitattributes — 行尾符 CRLF 规范化
- .prettierrc + .prettierignore — 前端代码格式化
- .markdownlint.json — Markdown 格式规范
- commitlint.config.js — Conventional Commits 强制校验

新增 GitHub 社区文件:
- .github/dependabot.yml — 依赖自动更新 (npm + Cargo + Actions)
- .github/CODEOWNERS — 自动 PR 审查分配
- .github/FUNDING.yml — 开源赞助入口

新增文档:
- ROADMAP.md — v5.1/v5.2/v6.0 路线图
- SUPPORT.md — 帮助与支持指南
- docs/screenshots/ — 截图目录就位

新增 Git Hooks:
- .husky/pre-commit — lint-staged 自动格式化+修复
- .husky/commit-msg — commitlint 校验提交消息

CI 强化 (.github/workflows/ci.yml):
- 新增 Prettier 格式检查步骤
- 新增 cargo fmt --check 步骤
- 新增 Vitest 覆盖率生成 + Codecov 上报

修复:
- index.html 标题 v4.0 → v5.0
- PathEditDialog set-state-in-effect 改用 useRef prevOpen 守卫
- use-app-actions.test.tsx 缺失 @vitest-environment jsdom
- 所有 TS/TSX 文件 Prettier 格式化统一

配置更新:
- vitest.config.ts — v8 覆盖率 + 阈值门禁 (60%/70%)
- package.json — format/format:check/test:coverage/prepare 脚本 + lint-staged
- .gitignore — 新增 coverage/sync-conflict/playwright-report
- README.md — 新增 coverage + platform 徽章 + 截图区域
2026-06-19 19:12:11 +08:00
57 changed files with 730 additions and 1472 deletions
+5
View File
@@ -0,0 +1,5 @@
# CodeGraph data files — local to each machine, not for committing.
# Ignore everything in .codegraph/ except this file itself, so transient
# files (the database, daemon.pid, sockets, logs) never show up in git.
*
!.gitignore
+6
View File
@@ -0,0 +1,6 @@
node_modules/
dist/
target/
test-results/
e2e/
*.config.*
+2 -4
View File
@@ -31,7 +31,7 @@ jobs:
run: npx tsc -b --noEmit
- name: ESLint
run: npx eslint src/ tests/ e2e/
run: npx eslint src/ tests/
- name: Vitest 测试 + 覆盖率
run: npx vitest run --coverage
@@ -50,9 +50,7 @@ jobs:
steps:
- uses: actions/checkout@v4
- uses: Swatinem/rust-cache@v2
- name: Cargo Format Check
- name: Cargo Format
run: cargo fmt --check
- name: Cargo Check
+1 -1
View File
@@ -26,6 +26,7 @@ playwright-report/
# Editor directories and files
.vscode/*
.codegraph/*
!.vscode/extensions.json
.idea
.DS_Store
@@ -37,7 +38,6 @@ playwright-report/
# AI assistant
.claude/
.codegraph/
CLAUDE.md
# Platform
+2 -4
View File
@@ -65,13 +65,11 @@ PathEditor/
│ │ ├── toolbar/ # ToolBar、ActionButtons、UndoRedoButtons
│ │ ├── dialogs/ # PathEdit、Help、Import、Analyze、Profile
│ │ └── ui/ # Modal、buttons
│ ├── hooks/ # useAppActions、useKeyboard、usePathValidation
│ ├── hooks/ # useAppActions、useKeyboard
│ ├── i18n/ # zh-CN / en
│ └── config/ # default.json
├── docs/ # REMaining-ISSUES 等审查文档
├── tests/unit/ # Vitest 前端单元测试
├── e2e/ # Playwright E2E 测试
├── rust-toolchain.toml # 固定工具链版本
└── Cargo.toml # Workspace 根 + [workspace.package]
```
@@ -146,7 +144,7 @@ patheditor profile {list|save|load|apply|delete|rename}
## 关键约束
- **TypeScript**`strict: true`,零编译错误
- **Rust 工具链**`stable-x86_64-pc-windows-gnu``rust-toolchain.toml` 强制
- **Rust 工具链**`stable-x86_64-pc-windows-gnu`项目已设 override
- **MinGW 兼容**`.cargo/config.toml` 添加 `-lmcfgthread`GCC 15.2.0 运行时)
- **运行权限**:需要管理员权限才能编辑系统 PATH,非管理员自动进入只读模式
- **构建产物**NSIS 安装包,约 8MB
Generated
+3 -4
View File
@@ -2379,20 +2379,19 @@ dependencies = [
[[package]]
name = "path-editor-core"
version = "5.1.0"
version = "5.0.0"
dependencies = [
"chrono",
"dirs 5.0.1",
"log",
"serde",
"serde_json",
"windows-sys 0.61.2",
"winreg 0.52.0",
]
[[package]]
name = "patheditor"
version = "5.1.0"
version = "5.0.0"
dependencies = [
"log",
"path-editor-core",
@@ -2405,7 +2404,7 @@ dependencies = [
[[package]]
name = "patheditor-cli"
version = "5.1.0"
version = "5.0.0"
dependencies = [
"clap",
"path-editor-core",
+1 -1
View File
@@ -7,7 +7,7 @@ members = [
]
[workspace.package]
version = "5.1.0"
version = "5.0.0"
edition = "2021"
license = "MIT"
authors = ["刘航宇"]
+6 -7
View File
@@ -4,14 +4,14 @@
</p>
<p align="center">
<img src="https://img.shields.io/badge/version-5.1.0-blue" alt="version">
<img src="https://img.shields.io/badge/version-5.0.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-157%20passed-brightgreen" alt="tests">
<a href="https://codecov.io/gh/LHY0125/PathEditor"><img src="https://codecov.io/gh/LHY0125/PathEditor/branch/v5.1/graph/badge.svg" alt="coverage"></a>
<img src="https://img.shields.io/badge/tests-72%20passed-brightgreen" alt="tests">
<a href="https://codecov.io/gh/LHY0125/PathEditor"><img src="https://codecov.io/gh/LHY0125/PathEditor/branch/v5.0/graph/badge.svg" alt="coverage"></a>
<img src="https://img.shields.io/badge/platform-Windows%2010%2B-0078D6" alt="platform">
<img src="https://github.com/LHY0125/PathEditor/actions/workflows/ci.yml/badge.svg" alt="CI">
</p>
@@ -281,8 +281,8 @@ npx tauri build
| 国际化 | i18next |
| 桌面框架 | Tauri 2.x |
| 核心库 | Rust workspace (core + gui + cli) |
| 前端测试 | Vitest (100 个测试) |
| Rust 测试 | cargo test (57 个测试) |
| 前端测试 | Vitest (72 个测试) |
| Rust 测试 | cargo test (10 个测试) |
| 构建 | Vite + Cargo |
| 打包 | NSIS |
@@ -304,11 +304,10 @@ src/ # React 前端
├── core/ # 纯逻辑 — 零框架依赖
├── store/ # Zustand 状态管理
├── components/ # UI 组件
├── hooks/ # useAppActions、useKeyboard、usePathValidation
├── hooks/ # useAppActions、useKeyboard
├── i18n/ # zh-CN / en
└── config/ # default.json
tests/unit/ # 前端单元测试
docs/ # 审查文档
```
## 快捷键
+100 -282
View File
@@ -13,109 +13,79 @@ 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),
@@ -124,10 +94,7 @@ enum Command {
#[derive(Subcommand)]
enum ProfileCmd {
/// 列出所有配置
List {
#[arg(long)]
json: bool,
},
List { #[arg(long)] json: bool },
/// 保存当前 PATH 为配置
Save { name: String },
/// 加载配置(预览)
@@ -138,10 +105,8 @@ enum ProfileCmd {
Delete { name: String },
/// 重命名配置
Rename {
#[arg(long)]
old: String,
#[arg(long)]
new: String,
#[arg(long)] old: String,
#[arg(long)] new: String,
},
}
@@ -151,14 +116,8 @@ 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>;
@@ -172,11 +131,7 @@ 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));
}
@@ -191,29 +146,6 @@ 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) {
@@ -231,15 +163,11 @@ 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); }
}
}
}
@@ -250,43 +178,49 @@ 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) {
load_operate_save(system, index, |mut list, idx| {
let removed = list.remove(idx);
(list, format!("已删除: {removed}"))
});
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();
}
fn cmd_edit(index: usize, new_path: String, system: bool) {
load_operate_save(system, index, |mut list, idx| {
let old = std::mem::replace(&mut list[idx], new_path.clone());
(list, format!("已编辑: {old}{new_path}"))
});
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();
}
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);
@@ -298,31 +232,19 @@ 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 {
@@ -331,31 +253,18 @@ 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); }
}
}
}
@@ -367,18 +276,11 @@ 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);
@@ -392,26 +294,23 @@ 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_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();
let (sys, usr) = core::fs::import_paths(&file, &content).unwrap_or_else(|e| exit_err(&e));
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_paths);
verify_and_save("system", &orig, sys);
println!("已导入到系统 PATH");
}
"user" => {
let orig = core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e));
verify_and_save("user", &orig, usr_paths);
verify_and_save("user", &orig, usr);
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_paths);
verify_and_save("user", &orig_usr, usr_paths);
verify_and_save("system", &orig_sys, sys);
verify_and_save("user", &orig_usr, usr);
println!("已导入到系统 + 用户 PATH");
}
}
@@ -423,12 +322,6 @@ 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 {
@@ -443,12 +336,8 @@ 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());
@@ -459,15 +348,7 @@ 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!();
}
@@ -476,26 +357,16 @@ 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); }
}
}
}
@@ -516,29 +387,15 @@ 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}");
}
@@ -546,29 +403,15 @@ 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));
@@ -595,37 +438,12 @@ 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(),
-1
View File
@@ -13,4 +13,3 @@ log = "0.4"
winreg = "0.52"
dirs = "5"
chrono = "0.4"
windows-sys = { version = "0.61.2", features = ["Win32_System_Environment", "Win32_UI_WindowsAndMessaging", "Win32_Foundation"] }
+16 -13
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,22 +19,24 @@ 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() => {
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
}
Some(ref dir) if !dir.is_empty() => std::path::PathBuf::from(dir),
_ => 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);
@@ -54,7 +56,8 @@ 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);
+10 -15
View File
@@ -1,9 +1,7 @@
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("."))
@@ -11,11 +9,6 @@ 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)]
@@ -30,13 +23,15 @@ 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))?;
atomic_write(&path, &json).map_err(|e| format!("无法写入 disabled.json: {}", e))?;
fs::write(&path, &json)
.map_err(|e| format!("无法写入 disabled.json: {}", e))?;
log::info!("已保存禁用状态到: {}", path.display());
Ok(())
@@ -50,15 +45,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))
}
+43 -306
View File
@@ -1,50 +1,13 @@
// 注意: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<ProfilePathEntry>, Vec<ProfilePathEntry>), String> {
/// 导入路径文件(JSON / CSV / TXT),返回 (系统路径, 用户路径)
pub fn import_paths(path: &str, content: &str) -> Result<(Vec<String>, Vec<String>), String> {
let ext = std::path::Path::new(path)
.extension()
.map(|e| e.to_ascii_lowercase())
@@ -59,85 +22,26 @@ pub fn import_paths(
}
}
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
}
fn import_json(content: &str) -> Result<(Vec<String>, Vec<String>), String> {
#[derive(serde::Deserialize)]
struct ImportData {
#[serde(default)]
system: Vec<ImportItem>,
system: Vec<String>,
#[serde(default)]
user: Vec<ImportItem>,
user: Vec<String>,
}
let data: ImportData =
serde_json::from_str(content).map_err(|e| format!("JSON 解析失败: {}", e))?;
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)),
))
Ok((data.system, data.user))
}
/// 解析 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> {
fn import_csv(content: &str) -> Result<(Vec<String>, Vec<String>), 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 {
@@ -145,88 +49,64 @@ fn import_csv(
if let Some(stripped) = trimmed.strip_prefix('\u{FEFF}') {
trimmed = stripped;
}
// 跳过 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;
}
// 跳过 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; }
}
}
let fields = parse_csv_line(trimmed);
let fields: Vec<&str> = trimmed.split(',').collect();
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(entry),
"user" | "usr" => usr.push(entry),
_ => {
log::warn!("import_csv: 无法识别的类型字段,已跳过: {trimmed}");
}
"system" | "sys" => sys.push(fields[1].trim().to_string()),
"user" | "usr" => usr.push(fields[1].trim().to_string()),
_ => { 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<ProfilePathEntry>, Vec<ProfilePathEntry>), String> {
let entries: Vec<ProfilePathEntry> = content
fn import_txt(content: &str) -> Result<(Vec<String>, Vec<String>), String> {
let paths: Vec<String> = content
.lines()
.map(|l| l.trim().to_string())
.filter(|l| !l.is_empty() && !l.starts_with('#'))
.map(|path| ProfilePathEntry {
path,
enabled: true,
})
.collect();
let entries = sanitize_entries(entries);
if entries.is_empty() {
if paths.is_empty() {
return Err("TXT 文件中未找到路径".into());
}
// TXT 格式全部导入为用户路径
Ok((vec![], entries))
Ok((vec![], paths))
}
/// 导出 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": to_entries(sys),
"user": to_entries(usr),
"system": sys,
"user": usr,
});
Ok(serde_json::to_string_pretty(&data).expect("JSON 序列化 Value 不应失败"))
Ok(serde_json::to_string_pretty(&data).unwrap_or_default())
}
"csv" => {
let mut out = String::from("type,path,enabled\n");
let mut out = String::from("type,path\n");
for p in sys {
out.push_str(&format!("system,{},true\n", p));
out.push_str(&format!("system,{}\n", p));
}
for p in usr {
out.push_str(&format!("user,{},true\n", p));
out.push_str(&format!("user,{}\n", p));
}
Ok(out)
}
@@ -254,30 +134,12 @@ 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": [{"path": "C:\\sys1"}, {"path": "C:\\sys2"}], "user": [{"path": "D:\\usr1"}]}"#;
let json = r#"{"system": ["C:\\sys1", "C:\\sys2"], "user": ["D:\\usr1"]}"#;
let (sys, usr) = import_json(json).unwrap();
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");
assert_eq!(sys, vec!["C:\\sys1", "C:\\sys2"]);
assert_eq!(usr, vec!["D:\\usr1"]);
}
#[test]
@@ -286,15 +148,6 @@ 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();
@@ -304,20 +157,16 @@ 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.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);
let (sys, _usr) = import_csv(csv).unwrap();
assert_eq!(sys, vec!["C:\\sys1"]);
assert_eq!(_usr, vec!["D:\\usr1"]);
}
#[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[0].path, "C:\\sys1");
assert_eq!(sys, vec!["C:\\sys1"]);
}
#[test]
@@ -329,27 +178,8 @@ 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[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);
assert_eq!(sys, vec!["D:\\a"]);
assert_eq!(usr, vec!["D:\\b"]);
}
#[test]
@@ -358,18 +188,16 @@ 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]["path"], "C:\\a");
assert_eq!(parsed["system"][0]["enabled"], true);
assert_eq!(parsed["system"][0], "C:\\a");
}
#[test]
fn export_csv_includes_enabled_column() {
fn export_csv_roundtrip() {
let sys = vec!["C:\\a".into()];
let usr = vec!["D:\\b".into()];
let exported = export_paths(&sys, &usr, "csv").unwrap();
assert!(exported.starts_with("type,path,enabled"));
assert!(exported.contains("system,C:\\a,true"));
assert!(exported.contains("user,D:\\b,true"));
assert!(exported.contains("system,C:\\a"));
assert!(exported.contains("user,D:\\b"));
}
#[test]
@@ -388,104 +216,13 @@ mod tests {
#[test]
fn import_paths_detects_format() {
let (sys, _) = import_paths("test.csv", "type,path\nsystem,C:\\x\n").unwrap();
assert_eq!(sys[0].path, "C:\\x");
assert_eq!(sys, vec!["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.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);
assert_eq!(usr, vec!["C:\\x", "D:\\y"]);
}
}
+12 -61
View File
@@ -1,9 +1,7 @@
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("."))
@@ -11,21 +9,8 @@ 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.len() > 255 {
return Err("配置名称过长(最大 255 字符)".into());
}
if name.contains('\0') || name.chars().any(|c| c.is_control()) {
return Err("配置名称包含非法字符".into());
}
if name.is_empty() { return Err("配置名称不能为空".into()); }
if name.contains('/') || name.contains('\\') || name.contains("..") {
return Err("配置名称包含非法字符".into());
}
@@ -130,7 +115,7 @@ pub fn save_profile(
let json =
serde_json::to_string_pretty(&data).map_err(|e| format!("JSON 序列化失败: {}", e))?;
atomic_write(&path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
fs::write(&path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
log::info!("已保存配置: {}", path.display());
Ok(())
@@ -143,8 +128,10 @@ 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))
}
/// 删除配置文件
@@ -161,25 +148,20 @@ 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))?;
atomic_write(&new_path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
fs::write(&new_path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
if old_path != new_path {
fs::remove_file(&old_path).map_err(|e| format!("无法删除旧配置文件: {}", e))?;
@@ -194,10 +176,7 @@ mod tests {
use super::*;
fn test_entry(path: &str) -> ProfilePathEntry {
ProfilePathEntry {
path: path.into(),
enabled: true,
}
ProfilePathEntry { path: path.into(), enabled: true }
}
#[test]
@@ -217,40 +196,12 @@ 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();
+21 -59
View File
@@ -1,16 +1,11 @@
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)
@@ -23,13 +18,17 @@ pub(crate) fn load_paths(
Ok(split_path(&value))
}
fn save_paths(
root: winreg::HKEY,
sub_path: &str,
label: &str,
paths: &[String],
) -> Result<(), String> {
let value = validate_and_join_paths(paths, label)?;
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
));
}
let key = RegKey::predef(root);
let env_key = key
@@ -44,6 +43,7 @@ fn save_paths(
Ok(())
}
/// 从 HKLM 注册表读取系统 PATH
///
/// # Returns
@@ -53,6 +53,7 @@ pub fn load_system_paths() -> Result<Vec<String>, String> {
load_paths(HKEY_LOCAL_MACHINE, SYS_REG_PATH, "系统")
}
/// 从 HKCU 注册表读取用户 PATH
///
/// # Returns
@@ -62,6 +63,7 @@ pub fn load_user_paths() -> Result<Vec<String>, String> {
load_paths(HKEY_CURRENT_USER, USER_REG_PATH, "用户")
}
/// 保存系统 PATH 到注册表,含 32767 字符上限检查
///
/// # Returns
@@ -71,6 +73,7 @@ pub fn save_system_paths(paths: Vec<String>) -> Result<(), String> {
save_paths(HKEY_LOCAL_MACHINE, SYS_REG_PATH, "系统", &paths)
}
/// 保存用户 PATH 到注册表
///
/// # Returns
@@ -98,25 +101,6 @@ 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>) {
@@ -164,7 +148,10 @@ 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]
@@ -180,29 +167,4 @@ 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 限制"));
}
}
+23 -65
View File
@@ -50,18 +50,13 @@ 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().map_err(|e| format!("扫描线程失败: {:?}", e)))
.collect::<Result<Vec<_>, _>>()
})
.map_err(|e| format!("线程扫描失败: {}", e))?;
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()
});
// 合并: exe_name (小写) → [(priority, dir)]
let mut map: HashMap<String, Vec<(usize, String)>> = HashMap::new();
@@ -97,46 +92,31 @@ 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().map_err(|e| format!("扫描线程失败: {:?}", e)))
.collect::<Result<Vec<_>, _>>()
})
.map_err(|e| format!("线程扫描失败: {}", e))?;
}).collect();
handles.into_iter().map(|h| h.join().unwrap()).collect()
});
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 });
}
}
}
@@ -149,39 +129,20 @@ mod tests {
use super::*;
use std::fs;
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 {
fn make_temp_dir_with_exes(prefix: &str, exe_names: &[&str]) -> std::path::PathBuf {
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();
}
TempDirGuard(dir)
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());
}
@@ -190,10 +151,7 @@ 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);
+38 -12
View File
@@ -1,7 +1,3 @@
use windows_sys::Win32::System::Environment::ExpandEnvironmentStringsW;
use windows_sys::Win32::UI::WindowsAndMessaging::{
SendMessageTimeoutW, HWND_BROADCAST, SMTO_ABORTIFHUNG, WM_SETTINGCHANGE,
};
use winreg::enums::*;
use winreg::RegKey;
@@ -30,19 +26,22 @@ pub fn validate_path(path: &str) -> bool {
}
/// 展开路径中的环境变量(如 %JAVA_HOME%\bin → C:\Program Files\Java\jdk-17\bin
/// 包含 % 的路径(环境变量路径)无法展开,返回原始路径
pub fn expand_env_vars(path: &str) -> String {
if !path.contains('%') {
return path.to_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 +50,10 @@ pub fn expand_env_vars(path: &str) -> String {
// SAFETY: buffer 容量为 requiredAPI 返回的精确大小),wide_path 以 null 结尾,
// 且两个指针指向不同的内存区域,不存在重叠
let mut buffer = vec![0_u16; required as usize];
let result =
unsafe { ExpandEnvironmentStringsW(wide_path.as_ptr(), buffer.as_mut_ptr(), required) };
let mut buffer: Vec<u16> = vec![0; required as usize];
let result = unsafe {
ExpandEnvironmentStringsW(wide_path.as_ptr(), buffer.as_mut_ptr(), required)
};
if result == 0 || result > required {
log::warn!("expand_env_vars: 展开失败或缓冲区不足, 返回原始路径: {path}");
@@ -78,6 +78,10 @@ fn decode_utf16_preserving(v: &[u16]) -> String {
/// 广播环境变量更改通知(WM_SETTINGCHANGE
/// 广播 `WM_SETTINGCHANGE` 通知系统环境变量已变更
pub fn broadcast_env_change() {
const HWND_BROADCAST: isize = 0xFFFF;
const WM_SETTINGCHANGE: u32 = 0x001A;
const SMTO_ABORTIFHUNG: u32 = 0x0002;
// SAFETY: env_str 是以 null 结尾的 UTF-16 字符串,所有指针和常量均遵循 Win32 API 约定
let env_str: Vec<u16> = "Environment\0".encode_utf16().collect();
@@ -85,7 +89,7 @@ pub fn broadcast_env_change() {
// lpdwResult 为 null 表示不需要返回值,其他参数均为常量
let result = unsafe {
SendMessageTimeoutW(
HWND_BROADCAST as _,
HWND_BROADCAST,
WM_SETTINGCHANGE,
0,
env_str.as_ptr() as isize,
@@ -102,6 +106,28 @@ pub fn broadcast_env_change() {
}
}
// ── 外部 FFI 声明 ──
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;
/// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-sendmessagetimeoutw
fn SendMessageTimeoutW(
hWnd: isize,
Msg: u32,
wParam: usize,
lParam: isize,
fuFlags: u32,
uTimeout: u32,
lpdwResult: *mut usize,
) -> isize;
}
#[cfg(test)]
mod tests {
use super::*;
+2 -1
View File
@@ -32,4 +32,5 @@
- ~~profiles.rs 同款问题~~ → 同上
---
*更新于: 2026-05-30 | 审查批次: v5.1 代码审查*
_更新于: 2026-05-30 | 审查批次: v5.1 代码审查_
+10
View File
@@ -4,6 +4,7 @@
PathEditor v5.0 是一个功能完善的 Windows 系统环境变量 (PATH) 编辑器,支持 GUI 与 CLI 双模式。
技术栈选型现代化且合理:
- **后端 / 核心逻辑**Rust (Cargo Workspace)
- **GUI 框架**Tauri 2.x
- **前端**React 19 + TypeScript + Zustand
@@ -13,7 +14,9 @@ PathEditor v5.0 是一个功能完善的 Windows 系统环境变量 (PATH) 编
## 2. 架构设计审查
### 2.1 Cargo Workspace 三层架构
项目采用了经典的 Cargo Workspace 模式,分为三层:
- `core`: 纯 Rust 库 crate,包含所有的核心业务逻辑(注册表读写、备份、配置文件管理、路径验证与清理等)。该层**完全不依赖** Tauri 或 CLI 库,极大地提高了代码的复用性和可测试性。
- `gui`: Tauri 桌面应用。仅作为薄包装层(Thin Wrapper),通过 `#[tauri::command]``core` 的功能暴露为 IPC 接口供前端调用。
- `cli`: 命令行工具层。依赖 `core``clap` 库,直接提供命令行交互能力。
@@ -21,13 +24,16 @@ PathEditor v5.0 是一个功能完善的 Windows 系统环境变量 (PATH) 编
**审查结论**:架构设计非常优秀。核心逻辑解耦彻底,无论是 GUI 还是 CLI 都能复用同一套安全、经过测试的核心代码。
### 2.2 IPC 通信与状态同步
前端与 Rust 后端通过 Tauri IPC 进行通信。
- 所有的错误处理均通过 `Result<T, String>` 返回,前端通过 `Promise` 捕获并处理,用户体验良好。
- 针对非事务性的双写操作(如同时保存系统和用户 PATH),前端 `app-store.ts` 中使用了 `Promise.allSettled`。当发生部分成功(Partial Success)时,能正确捕获并重新加载注册表状态,避免了前端内存状态与后端注册表状态的漂移(State Drift)。
## 3. 后端代码审查 (Rust)
### 3.1 核心逻辑 (`core`)
- **安全性与健壮性**
-`registry.rs` 中,严格检查了路径字符串的 Null 字节,以及 32767 个字符的 Windows 注册表长度上限,防止缓冲区溢出或写入失败。
- 使用了安全的 `winreg` 库进行注册表操作。
@@ -36,6 +42,7 @@ PathEditor v5.0 是一个功能完善的 Windows 系统环境变量 (PATH) 编
- 能够妥善处理 UTF-16 编码和解码,保留非法码点避免丢失路径信息,细节处理非常到位。
### 3.2 命令行工具 (`cli`)
- **原子性与并发安全**
- 在 CLI 的 `verify_and_save` 逻辑中,写入前会重新读取注册表并与原始状态对比。如果不一致,则拒绝写入并报错退出。这有效地防止了并发情况下的配置覆盖问题。
- **用户体验**
@@ -44,11 +51,13 @@ PathEditor v5.0 是一个功能完善的 Windows 系统环境变量 (PATH) 编
## 4. 前端代码审查 (React + TypeScript)
### 4.1 状态管理 (`app-store.ts`)
- 使用 `Zustand` 进行全局状态管理,状态树设计合理,避免了 React Context 可能带来的不必要重渲染。
- 实现了完善的 `UndoRedoManager`,将每一步操作抽象为 `OperationType`,支持撤销/重做功能,这对于编辑器类应用来说是核心体验的加分项。
- `isSaving` 状态守卫有效防止了用户双击保存按钮引发的并发竞争。
### 4.2 UI 与逻辑分离
- 业务逻辑抽象到 `src/core` 目录下(如 `path-manager.ts`, `validation.ts`),UI 组件仅负责渲染和事件绑定。
- `useAppActions.ts` 钩子巧妙地将组件层与 Store 状态操作解耦,使得组件代码极其整洁。
@@ -66,4 +75,5 @@ PathEditor v5.0 是一个功能完善的 Windows 系统环境变量 (PATH) 编
如果 PATH 环境变量条目非常多(虽然实际场景中一般在 100 条以内),React 渲染完整列表可能会有微小延迟。当前规模下无影响,但若未来考虑显示大量工具链路径扫描结果,可引入虚拟列表(Virtual List)。
## 总结
PathEditor v5.0 的代码库是一个优秀的 Rust + Tauri + React 实践范例。它具有清晰的三层架构、严格的类型和边界检查、以及良好的错误处理机制,整体架构稳健且易于长期维护。
+1 -5
View File
@@ -1,11 +1,7 @@
export type IpcOverrides = Partial<Record<string, unknown>>;
export function createIpcMock(overrides: IpcOverrides = {}) {
export function createIpcMock() {
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'];
+37 -8
View File
@@ -1,14 +1,43 @@
import { test, expect } from '@playwright/test';
import { createIpcMock } from '../mocks/ipc';
test.beforeEach(async ({ page }) => {
await page.addInitScript(
createIpcMock({
load_system_paths: ['C:\\Windows', 'invalid_path', 'C:\\Temp'],
load_user_paths: [],
validate_path: false,
}),
);
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.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', 'target', 'test-results', 'e2e', '*.config.*'] },
{ ignores: ['dist', 'gui'] },
{
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()
}
+2 -12
View File
@@ -1,22 +1,12 @@
{
"$schema": "../gen/schemas/desktop-schema.json",
"identifier": "default",
"description": "PathEditor main window capabilities",
"description": "enables the default permissions",
"windows": [
"main"
],
"permissions": [
"core: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"
"dialog:default"
]
}
+2 -6
View File
@@ -1,10 +1,6 @@
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() }
+2 -6
View File
@@ -1,10 +1,6 @@
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() }
+1 -3
View File
@@ -1,6 +1,4 @@
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) }
+5 -19
View File
@@ -1,26 +1,12 @@
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) }
+4 -24
View File
@@ -1,30 +1,10 @@
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>, original: Option<Vec<String>>) -> Result<(), String> {
if let Some(orig) = original {
let current = registry::load_system_paths()?;
if current != orig {
return Err("注册表已被其他进程修改,请重新加载后重试".to_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>, original: Option<Vec<String>>) -> Result<(), String> {
if let Some(orig) = original {
let current = registry::load_user_paths()?;
if current != orig {
return Err("注册表已被其他进程修改,请重新加载后重试".to_string());
}
}
registry::save_user_paths(paths)
}
pub fn save_user_paths(paths: Vec<String>) -> Result<(), String> { registry::save_user_paths(paths) }
+2 -6
View File
@@ -1,10 +1,6 @@
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) }
+4 -12
View File
@@ -1,18 +1,10 @@
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| {
let level = if cfg!(debug_assertions) {
log::LevelFilter::Info
} else {
log::LevelFilter::Warn
};
app.handle()
.plugin(tauri_plugin_log::Builder::default().level(level).build())?;
if cfg!(debug_assertions) {
app.handle().plugin(
tauri_plugin_log::Builder::default()
.level(log::LevelFilter::Info)
.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.1.0",
"version": "5.0.0",
"identifier": "com.liuhangyu.patheditor",
"build": {
"frontendDist": "../dist",
@@ -12,7 +12,7 @@
"app": {
"windows": [
{
"title": "PathEditor v5.1",
"title": "PathEditor v5.0",
"width": 900,
"height": 700,
"minWidth": 800,
+1 -1
View File
@@ -3,7 +3,7 @@
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>PathEditor v5.1</title>
<title>PathEditor v5.0</title>
</head>
<body>
<div id="root"></div>
+38 -66
View File
@@ -1,15 +1,14 @@
{
"name": "patheditor",
"version": "5.1.0",
"version": "5.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "patheditor",
"version": "5.1.0",
"version": "5.0.0",
"dependencies": {
"@tailwindcss/vite": "^4.3.0",
"@tanstack/react-virtual": "^3.13.26",
"@tauri-apps/api": "^2.11.0",
"@tauri-apps/plugin-dialog": "^2.7.1",
"i18next": "^26.2.0",
@@ -24,7 +23,7 @@
"@commitlint/cli": "^21.0.2",
"@commitlint/config-conventional": "^21.0.2",
"@eslint/js": "^10.0.1",
"@playwright/test": "^1.61.0",
"@playwright/test": "^1.60.0",
"@tauri-apps/cli": "^2.11.2",
"@testing-library/jest-dom": "^6.9.1",
"@testing-library/react": "^16.3.2",
@@ -32,7 +31,7 @@
"@types/react": "^19.2.14",
"@types/react-dom": "^19.2.3",
"@vitejs/plugin-react": "^6.0.1",
"@vitest/coverage-v8": "^4.1.7",
"@vitest/coverage-v8": "^4.1.9",
"eslint": "^10.3.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
@@ -44,7 +43,7 @@
"typescript": "~6.0.2",
"typescript-eslint": "^8.59.2",
"vite": "^8.0.12",
"vitest": "^4.1.9"
"vitest": "^4.1.7"
}
},
"node_modules/@adobe/css-tools": {
@@ -1160,13 +1159,13 @@
}
},
"node_modules/@playwright/test": {
"version": "1.61.0",
"resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.61.0.tgz",
"integrity": "sha512-cKA5B6lpFEMyMGjxF54QihfYpB4FkEGH+qZhtArDEG+wezQAJY8Pq6C7T1SjWz+FFzt3TbyoXBQYk/0292TdJA==",
"version": "1.60.0",
"resolved": "https://registry.npmmirror.com/@playwright/test/-/test-1.60.0.tgz",
"integrity": "sha512-O71yZIbAh/PxDMNGns37GHBIfrVkEVyn+AXyIa5dOTfb4/xNvRWV+Vv/NMbNCtODB/pO7vLlF2OTmMVLhmr7Ag==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright": "1.61.0"
"playwright": "1.60.0"
},
"bin": {
"playwright": "cli.js"
@@ -1454,7 +1453,7 @@
},
"node_modules/@standard-schema/spec": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
"resolved": "https://registry.npmmirror.com/@standard-schema/spec/-/spec-1.1.0.tgz",
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"dev": true,
"license": "MIT"
@@ -1716,33 +1715,6 @@
"vite": "^5.2.0 || ^6 || ^7 || ^8"
}
},
"node_modules/@tanstack/react-virtual": {
"version": "3.13.26",
"resolved": "https://registry.npmmirror.com/@tanstack/react-virtual/-/react-virtual-3.13.26.tgz",
"integrity": "sha512-DosdgjOxCLahkn0o+ilmZYwEjo1glfMGuRT/j3PQ18yr5XqA8N/BCaL9IJ3B5TRl+nnzyK2IOFgAILwzN3a9xQ==",
"license": "MIT",
"dependencies": {
"@tanstack/virtual-core": "3.16.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
},
"peerDependencies": {
"react": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0",
"react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0 || ^19.0.0"
}
},
"node_modules/@tanstack/virtual-core": {
"version": "3.16.0",
"resolved": "https://registry.npmmirror.com/@tanstack/virtual-core/-/virtual-core-3.16.0.tgz",
"integrity": "sha512-Er2N7q3WOiH6y2JLxsxNX+u2/sLqSsL0bxFgDjuiPiA7vKhZRm+IzcS17vRee3GNXr64UsesA5CAp9yTiIYw9A==",
"license": "MIT",
"funding": {
"type": "github",
"url": "https://github.com/sponsors/tannerlinsley"
}
},
"node_modules/@tauri-apps/api": {
"version": "2.11.0",
"resolved": "https://registry.npmmirror.com/@tauri-apps/api/-/api-2.11.0.tgz",
@@ -2075,7 +2047,7 @@
},
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
"resolved": "https://registry.npmmirror.com/@types/chai/-/chai-5.2.3.tgz",
"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
"dev": true,
"license": "MIT",
@@ -2086,7 +2058,7 @@
},
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
"resolved": "https://registry.npmmirror.com/@types/deep-eql/-/deep-eql-4.0.2.tgz",
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
"dev": true,
"license": "MIT"
@@ -2413,7 +2385,7 @@
},
"node_modules/@vitest/coverage-v8": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@vitest/coverage-v8/-/coverage-v8-4.1.9.tgz",
"resolved": "https://registry.npmmirror.com/@vitest/coverage-v8/-/coverage-v8-4.1.9.tgz",
"integrity": "sha512-G9/lgqibheLVBDRuya45EbsEXTYcWoSG+TLg7i2axuzx0Eq62eXn+aWXyaVdV5vKvFSWd6ywcX8hA7la9Pvu8g==",
"dev": true,
"license": "MIT",
@@ -2444,7 +2416,7 @@
},
"node_modules/@vitest/expect": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.9.tgz",
"resolved": "https://registry.npmmirror.com/@vitest/expect/-/expect-4.1.9.tgz",
"integrity": "sha512-vl/rYsUKcBr3SnQn166+XR5ZQcgMx3DQhFWdfli/cWpLnLUmbxZvyrJZotLFUryib+LtArYMSTJ5RbQ57ZqrlA==",
"dev": true,
"license": "MIT",
@@ -2462,7 +2434,7 @@
},
"node_modules/@vitest/mocker": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.9.tgz",
"resolved": "https://registry.npmmirror.com/@vitest/mocker/-/mocker-4.1.9.tgz",
"integrity": "sha512-EVkXzBjrPGM+cK8/ANWgBrkUCfJfb38/EfTSO8h7pWvKkyPkpWxvR7BkD2MyItMF62C97zAEoqdpUixwR/e+Rw==",
"dev": true,
"license": "MIT",
@@ -2489,7 +2461,7 @@
},
"node_modules/@vitest/pretty-format": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.9.tgz",
"resolved": "https://registry.npmmirror.com/@vitest/pretty-format/-/pretty-format-4.1.9.tgz",
"integrity": "sha512-s0iufns3iIFitdgm+YR7g1whCAaGtXz459VS9/PqyKDEEFgYIhsHOQmXgIgDuYCt7DeQmiZT0Qe2OA2p4ZPu5A==",
"dev": true,
"license": "MIT",
@@ -2502,7 +2474,7 @@
},
"node_modules/@vitest/runner": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.9.tgz",
"resolved": "https://registry.npmmirror.com/@vitest/runner/-/runner-4.1.9.tgz",
"integrity": "sha512-KXLMDtc7oe70+3mJfGrPUWPesswH+3sTxAMAMl8DG7I8IUQT4XW718dY5ID3vPUcmlu27CcKfY4P3h3I29SLJg==",
"dev": true,
"license": "MIT",
@@ -2516,7 +2488,7 @@
},
"node_modules/@vitest/snapshot": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.9.tgz",
"resolved": "https://registry.npmmirror.com/@vitest/snapshot/-/snapshot-4.1.9.tgz",
"integrity": "sha512-Jc7RKGNBo8Z28WYIm0Niej4xdSPByRf6mU58VpHQkd6Zh05rlnA+twjbK5HyeIGHxrzsc3mJgS43uM0CZKzaIA==",
"dev": true,
"license": "MIT",
@@ -2532,7 +2504,7 @@
},
"node_modules/@vitest/spy": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.9.tgz",
"resolved": "https://registry.npmmirror.com/@vitest/spy/-/spy-4.1.9.tgz",
"integrity": "sha512-fHpsS6mIi+PiEW+vcRVOMkX1oSaPKne3VOclSFICPcGOmfKgXPU5iAah+wcNcj2xPrCCmfq99IDGf+EojhhvhA==",
"dev": true,
"license": "MIT",
@@ -2542,7 +2514,7 @@
},
"node_modules/@vitest/utils": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.9.tgz",
"resolved": "https://registry.npmmirror.com/@vitest/utils/-/utils-4.1.9.tgz",
"integrity": "sha512-A51o8ymO5PpqlWNnBP9ZHPXDIpuMtTLlGSjN7la4US+LJzoUMyhwjA5QXlm39JexgwHKW4Xjs8Z2d3dLCXOeuA==",
"dev": true,
"license": "MIT",
@@ -2662,7 +2634,7 @@
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
"resolved": "https://registry.npmmirror.com/assertion-error/-/assertion-error-2.0.1.tgz",
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
"dev": true,
"license": "MIT",
@@ -2671,9 +2643,9 @@
}
},
"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==",
"version": "1.0.4",
"resolved": "https://registry.npmmirror.com/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.4.tgz",
"integrity": "sha512-0bC0/4bTSrnwdhU3IsZDwEdojvuPrSg59OYZfKsLRtJZ0u8VBx9DebfqqG8bRdCC0I7vjgxmPi41P0lpkhJHtA==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -2802,7 +2774,7 @@
},
"node_modules/chai": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
"resolved": "https://registry.npmmirror.com/chai/-/chai-6.2.2.tgz",
"integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
"dev": true,
"license": "MIT",
@@ -4568,9 +4540,9 @@
}
},
"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==",
"version": "7.8.4",
"resolved": "https://registry.npmmirror.com/semver/-/semver-7.8.4.tgz",
"integrity": "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==",
"dev": true,
"license": "ISC",
"bin": {
@@ -4825,7 +4797,7 @@
},
"node_modules/pathe": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
"resolved": "https://registry.npmmirror.com/pathe/-/pathe-2.0.3.tgz",
"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
"dev": true,
"license": "MIT"
@@ -4849,13 +4821,13 @@
}
},
"node_modules/playwright": {
"version": "1.61.0",
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.61.0.tgz",
"integrity": "sha512-Z+7BeeqQPRRzklHsVFP4KTGIyMxKUmfeRA4WisM6G3/XW6nwGeX6fX9qYaDa+CiUqpOkb2f6X3nar05R3kSuJQ==",
"version": "1.60.0",
"resolved": "https://registry.npmmirror.com/playwright/-/playwright-1.60.0.tgz",
"integrity": "sha512-hheHdokM8cdqCb0lcE3s+zT4t4W+vvjpGxsZlDnikarzx8tSzMebh3UiFtgqwFwnTnjYQcsyMF8ei2mCO/tpeA==",
"dev": true,
"license": "Apache-2.0",
"dependencies": {
"playwright-core": "1.61.0"
"playwright-core": "1.60.0"
},
"bin": {
"playwright": "cli.js"
@@ -4868,9 +4840,9 @@
}
},
"node_modules/playwright-core": {
"version": "1.61.0",
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.61.0.tgz",
"integrity": "sha512-caX7TrY3Ml6egyDX0WUcTHDxodl/b51y5wJOdCEA36QviK/s2g081hvmGs8eaE3DWb6NYZQ6BjO/QkNRPenoPA==",
"version": "1.60.0",
"resolved": "https://registry.npmmirror.com/playwright-core/-/playwright-core-1.60.0.tgz",
"integrity": "sha512-9bW6zvX/m0lEbgTKJ6YppOKx8H3VOPBMOCFh2irXFOT4BbHgrx5hPjwJYLT40Lu+4qtD36qKc/Hn56StUW57IA==",
"dev": true,
"license": "Apache-2.0",
"bin": {
@@ -4882,7 +4854,7 @@
},
"node_modules/playwright/node_modules/fsevents": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
"resolved": "https://registry.npmmirror.com/fsevents/-/fsevents-2.3.2.tgz",
"integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
"dev": true,
"hasInstallScript": true,
@@ -5661,7 +5633,7 @@
},
"node_modules/vitest": {
"version": "4.1.9",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.9.tgz",
"resolved": "https://registry.npmmirror.com/vitest/-/vitest-4.1.9.tgz",
"integrity": "sha512-nE3/LEyc0z87uHYLZebqCUOaJr2hdtuPp7BQ4BosVFnfltxgAvMG08NyrSGlPpOUWvR27c5flSmYFTNr78L9GQ==",
"dev": true,
"license": "MIT",
+66 -69
View File
@@ -1,69 +1,66 @@
{
"name": "patheditor",
"private": true,
"version": "5.1.0",
"type": "module",
"lint-staged": {
"*.{ts,tsx}": [
"prettier --write",
"eslint --fix"
],
"*.{json,md,css,html}": [
"prettier --write"
]
},
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"lint:fix": "eslint . --fix",
"format": "prettier --write \"src/**/*.{ts,tsx}\" \"tests/**/*.{ts,tsx}\" \"e2e/**/*.ts\"",
"format:check": "prettier --check \"src/**/*.{ts,tsx}\" \"tests/**/*.{ts,tsx}\" \"e2e/**/*.ts\"",
"format:rust": "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",
"prepare": "husky"
},
"dependencies": {
"@tailwindcss/vite": "^4.3.0",
"@tanstack/react-virtual": "^3.13.26",
"@tauri-apps/api": "^2.11.0",
"@tauri-apps/plugin-dialog": "^2.7.1",
"i18next": "^26.2.0",
"i18next-browser-languagedetector": "^8.2.1",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"react-i18next": "^17.0.8",
"tailwindcss": "^4.3.0",
"zustand": "^5.0.13"
},
"devDependencies": {
"@commitlint/cli": "^21.0.2",
"@commitlint/config-conventional": "^21.0.2",
"@eslint/js": "^10.0.1",
"@playwright/test": "^1.61.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",
"globals": "^17.6.0",
"husky": "^9.1.7",
"jsdom": "^29.1.1",
"lint-staged": "^16.4.0",
"prettier": "^3.8.4",
"typescript": "~6.0.2",
"typescript-eslint": "^8.59.2",
"vite": "^8.0.12",
"vitest": "^4.1.9"
}
}
{
"name": "patheditor",
"private": true,
"version": "5.0.0",
"type": "module",
"lint-staged": {
"*.{ts,tsx}": [
"prettier --write",
"eslint --fix"
],
"*.{json,md,css,html}": [
"prettier --write"
]
},
"scripts": {
"dev": "vite",
"build": "tsc -b && vite build",
"lint": "eslint .",
"format": "prettier --write \"src/**/*.{ts,tsx}\" \"tests/**/*.{ts,tsx}\" \"e2e/**/*.ts\"",
"format:check": "prettier --check \"src/**/*.{ts,tsx}\" \"tests/**/*.{ts,tsx}\" \"e2e/**/*.ts\"",
"preview": "vite preview",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage",
"test:e2e": "playwright test --config e2e/playwright.config.ts",
"prepare": "husky"
},
"dependencies": {
"@tailwindcss/vite": "^4.3.0",
"@tauri-apps/api": "^2.11.0",
"@tauri-apps/plugin-dialog": "^2.7.1",
"i18next": "^26.2.0",
"i18next-browser-languagedetector": "^8.2.1",
"react": "^19.2.6",
"react-dom": "^19.2.6",
"react-i18next": "^17.0.8",
"tailwindcss": "^4.3.0",
"zustand": "^5.0.13"
},
"devDependencies": {
"@commitlint/cli": "^21.0.2",
"@commitlint/config-conventional": "^21.0.2",
"@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.9",
"eslint": "^10.3.0",
"eslint-plugin-react-hooks": "^7.1.1",
"eslint-plugin-react-refresh": "^0.5.2",
"globals": "^17.6.0",
"husky": "^9.1.7",
"jsdom": "^29.1.1",
"lint-staged": "^16.4.0",
"prettier": "^3.8.4",
"typescript": "~6.0.2",
"typescript-eslint": "^8.59.2",
"vite": "^8.0.12",
"vitest": "^4.1.7"
}
}
+3 -7
View File
@@ -37,12 +37,8 @@ export function AnalyzeDialog({ open, onClose }: Props) {
const prevOpen = useRef(false);
useEffect(() => {
if (!open) {
prevOpen.current = false;
return;
}
if (prevOpen.current) return;
prevOpen.current = true;
if (!open || prevOpen.current) return;
prevOpen.current = open;
setLoading(true);
const paths = getEnabledPaths();
Promise.all([
@@ -194,7 +190,7 @@ function ToolsTab({
opacity: g.exists ? 1 : 0.6,
}}
>
{g.dir} {!g.exists && t('analyze.notExists')}
{g.dir} {!g.exists && '(不存在)'}
</div>
<div className="flex flex-wrap gap-1 mt-1 ml-2">
{g.exes.map((exe) => (
+2 -2
View File
@@ -22,9 +22,9 @@ export function ImportDialog({
<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 && t('dialog.importSystemCount', { count: systemCount })}
{systemCount > 0 && `系统变量: ${systemCount}`}
{systemCount > 0 && userCount > 0 && ' | '}
{userCount > 0 && t('dialog.importUserCount', { count: userCount })}
{userCount > 0 && `用户变量: ${userCount}`}
</p>
<div className="flex flex-col gap-2">
{systemCount > 0 && (
+7 -22
View File
@@ -73,22 +73,8 @@ export function ProfileDialog({ open, onClose }: Props) {
system: selectedData.sys.filter((e) => !e.enabled).map((e) => e.path),
user: selectedData.user.filter((e) => !e.enabled).map((e) => e.path),
});
const result = await useAppStore.getState().savePaths();
if (result.kind === 'success') {
onClose();
} else if (result.kind === 'warning') {
const { ask } = await import('@tauri-apps/plugin-dialog');
const confirmed = await ask(t('status.saveWarningLongPaths'), {
title: t('dialog.backupTitle'),
kind: 'warning',
});
if (confirmed) {
const forceResult = await useAppStore.getState().savePaths(true);
if (forceResult.kind === 'success') {
onClose();
}
}
}
await useAppStore.getState().savePaths();
onClose();
};
const handleDelete = async (name: string) => {
@@ -180,7 +166,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') : t('profile.selectProfile')}
{profiles.length === 0 ? t('profile.noProfiles') : '选择一个配置文件'}
</div>
) : (
<div>
@@ -236,7 +222,7 @@ export function ProfileDialog({ open, onClose }: Props) {
style={{ backgroundColor: '#3b82f6' }}
onClick={handleRename}
>
{t('button.save')}
</button>
</div>
)}
@@ -259,7 +245,6 @@ 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 }}>
@@ -267,13 +252,13 @@ function PathSection({ title, paths }: { title: string; paths: PathEntry[] }) {
</div>
{paths.length === 0 ? (
<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) => (
{paths.map((e, i) => (
<div
key={e.path}
key={i}
className="text-xs font-mono px-2 py-0.5 rounded flex items-center gap-1.5"
style={{
backgroundColor: 'var(--app-list-bg)',
+38 -55
View File
@@ -1,8 +1,7 @@
import { useMemo, useRef } from 'react';
import { useMemo } from 'react';
import { useAppStore } from '@/store/app-store';
import { useTranslation } from 'react-i18next';
import type { PathEntry } from '@/core/path-entry';
import { useVirtualizer } from '@tanstack/react-virtual';
export function MergePreview() {
const sysPaths = useAppStore((s) => s.sysPaths);
@@ -34,62 +33,46 @@ export function MergePreview() {
return merged.filter((r) => r.path.toLowerCase().includes(q));
}, [sysPaths, userPaths, searchQuery, t]);
const parentRef = useRef<HTMLDivElement>(null);
const rowVirtualizer = useVirtualizer({
count: allPaths.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 28, // 预估行高 28px
initialRect: { width: 800, height: 600 },
});
return (
<div ref={parentRef} className="flex-1 overflow-auto relative">
<div
className="sticky top-0 z-10 flex text-left text-xs uppercase"
style={{ backgroundColor: 'var(--app-list-alt)', color: 'var(--app-fg)' }}
>
<div className="w-10 px-2 py-1">#</div>
<div className="px-2 py-1 flex-1">{t('dialog.pathLabel')}</div>
<div className="w-16 px-2 py-1">{t('merge.source')}</div>
</div>
<div
style={{
height: `${rowVirtualizer.getTotalSize()}px`,
width: '100%',
position: 'relative',
}}
>
{rowVirtualizer.getVirtualItems().map((virtualRow) => {
const rowIdx = virtualRow.index;
const { path, enabled, source, displayIndex } = allPaths[rowIdx];
const textColor = enabled ? 'var(--app-fg)' : '#6b7280';
const textDecoration = enabled ? 'none' : 'line-through';
const opacity = enabled ? 1 : 0.6;
<div className="flex-1 overflow-auto">
<table className="w-full border-collapse">
<thead>
<tr
className="sticky top-0 z-10 text-left text-xs uppercase"
style={{ backgroundColor: 'var(--app-list-alt)', color: 'var(--app-fg)' }}
>
<th className="w-10 px-2 py-1">#</th>
<th className="px-2 py-1">{t('dialog.pathLabel')}</th>
<th className="w-16 px-2 py-1">{t('merge.source')}</th>
</tr>
</thead>
<tbody>
{allPaths.map(({ path, enabled, source, displayIndex }, rowIdx) => {
const textColor = enabled ? 'var(--app-fg)' : '#6b7280';
const textDecoration = enabled ? 'none' : 'line-through';
const opacity = enabled ? 1 : 0.6;
return (
<div
key={`${source}-${displayIndex}`}
className="flex items-center absolute top-0 left-0 w-full"
style={{
height: `${virtualRow.size}px`,
transform: `translateY(${virtualRow.start}px)`,
backgroundColor: rowIdx % 2 === 0 ? 'var(--app-list-bg)' : 'var(--app-list-alt)',
color: 'var(--app-fg)',
}}
>
<div className="w-10 px-2 py-0.5 text-xs opacity-50">{rowIdx + 1}</div>
<div
className="px-2 py-0.5 text-sm flex-1 truncate"
style={{ color: textColor, textDecoration, opacity }}
return (
<tr
key={`${source}-${displayIndex}`}
style={{
backgroundColor: rowIdx % 2 === 0 ? 'var(--app-list-bg)' : 'var(--app-list-alt)',
color: 'var(--app-fg)',
}}
>
{path}
</div>
<div className="w-16 px-2 py-0.5 text-xs opacity-60">{source}</div>
</div>
);
})}
</div>
<td className="px-2 py-0.5 text-xs opacity-50">{rowIdx + 1}</td>
<td
className="px-2 py-0.5 text-sm"
style={{ color: textColor, textDecoration, opacity }}
>
{path}
</td>
<td className="px-2 py-0.5 text-xs opacity-60">{source}</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
+151 -95
View File
@@ -1,10 +1,7 @@
import { useMemo, useCallback, useRef } from 'react';
import { useTranslation } from 'react-i18next';
import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
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';
import { useVirtualizer } from '@tanstack/react-virtual';
interface PathTableProps {
tabId: 'system' | 'user';
@@ -16,8 +13,10 @@ 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);
@@ -28,9 +27,15 @@ export function PathTable({ tabId }: PathTableProps) {
const paths = tabId === 'system' ? sysPaths : userPaths;
const isActive = activeTab === tabId;
const { validationCache, expandedCache } = usePathValidation(paths);
// 本次会话中已验证过的路径缓存(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 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();
@@ -43,15 +48,81 @@ 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);
const state: ValidationState = validationCache.get(path) ?? 'valid';
return { state, isDuplicate, isEnvVar: path.includes('%') };
return {
state: validationCache.get(path) ?? DEFAULT_VALIDATION_STATE,
isDuplicate,
isEnvVar: path.includes('%'),
};
});
}, [filtered, validationCache]);
@@ -82,94 +153,79 @@ export function PathTable({ tabId }: PathTableProps) {
[isActive, paths],
);
const parentRef = useRef<HTMLDivElement>(null);
const rowVirtualizer = useVirtualizer({
count: filtered.length,
getScrollElement: () => parentRef.current,
estimateSize: () => 28, // 预估行高 28px
initialRect: { width: 800, height: 600 },
});
return (
<div ref={parentRef} className="flex-1 overflow-auto relative">
<div
className="sticky top-0 z-10 flex text-left text-xs uppercase"
style={{ backgroundColor: 'var(--app-list-alt)', color: 'var(--app-fg)' }}
>
<div className="w-8 px-2 py-1">#</div>
<div className="w-6 px-1 py-1"></div>
<div className="px-2 py-1 flex-1">{t('table.path')}</div>
</div>
<div
style={{
height: `${rowVirtualizer.getTotalSize()}px`,
width: '100%',
position: 'relative',
}}
>
{rowVirtualizer.getVirtualItems().map((virtualRow) => {
const rowIdx = virtualRow.index;
const { path, index, enabled } = filtered[rowIdx];
const v = validations[rowIdx];
const isSelected = selectedIndices.includes(index);
let textColor = 'var(--app-fg)';
if (v.state === 'invalid') textColor = '#dc3545';
else if (v.isDuplicate) textColor = '#fd7e14';
else if (v.state === 'unknown') textColor = 'var(--app-fg)';
<div className="flex-1 overflow-auto">
<table className="w-full border-collapse">
<thead>
<tr
className="sticky top-0 z-10 text-left text-xs uppercase"
style={{ backgroundColor: 'var(--app-list-alt)', color: 'var(--app-fg)' }}
>
<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>
</tr>
</thead>
<tbody>
{filtered.map(({ path, index, enabled }, rowIdx) => {
const v = validations[rowIdx];
const isSelected = selectedIndices.includes(index);
let textColor = 'var(--app-fg)';
if (v.state === 'invalid') textColor = '#dc3545';
else if (v.isDuplicate) textColor = '#fd7e14';
else if (v.state === 'unknown') textColor = 'var(--app-fg)';
let textDecoration = 'none';
let opacity = 1;
if (!enabled) {
textColor = '#6b7280';
textDecoration = 'line-through';
opacity = 0.6;
}
let textDecoration = 'none';
let opacity = 1;
if (!enabled) {
textColor = '#6b7280';
textDecoration = 'line-through';
opacity = 0.6;
}
return (
<div
key={virtualRow.key}
onClick={(e) => handleClick(index, e)}
onDoubleClick={() => handleDoubleClick(index)}
className="cursor-pointer select-none flex items-center absolute top-0 left-0 w-full"
style={{
height: `${virtualRow.size}px`,
transform: `translateY(${virtualRow.start}px)`,
backgroundColor: isSelected
? 'var(--app-select-row)'
: rowIdx % 2 === 0
? 'var(--app-list-bg)'
: 'var(--app-list-alt)',
}}
>
<div
className="w-8 px-2 py-0.5 text-xs opacity-50"
style={{ color: 'var(--app-fg)' }}
return (
<tr
key={index}
onClick={(e) => handleClick(index, e)}
onDoubleClick={() => handleDoubleClick(index)}
className="cursor-pointer select-none"
style={{
backgroundColor: isSelected
? 'var(--app-select-row)'
: rowIdx % 2 === 0
? 'var(--app-list-bg)'
: 'var(--app-list-alt)',
}}
>
{index + 1}
</div>
<div className="w-6 px-1 py-0.5 flex items-center">
<input
type="checkbox"
checked={enabled}
onChange={() => {
const target = tabId === 'system' ? TargetType.SYSTEM : TargetType.USER;
useAppStore.getState().togglePath(index, target);
}}
className="cursor-pointer"
/>
</div>
<div
className="px-2 py-0.5 text-sm truncate flex-1"
style={{ color: textColor, textDecoration, opacity }}
title={expandedCache.get(path) || undefined}
>
{path}
</div>
</div>
);
})}
</div>
<td
className="w-8 px-2 py-0.5 text-xs opacity-50"
style={{ color: 'var(--app-fg)' }}
>
{index + 1}
</td>
<td className="w-6 px-1 py-0.5">
<input
type="checkbox"
checked={enabled}
onChange={() => {
const target = tabId === 'system' ? TargetType.SYSTEM : TargetType.USER;
useAppStore.getState().togglePath(index, target);
}}
className="cursor-pointer"
/>
</td>
<td
className="px-2 py-0.5 text-sm truncate max-w-2xl"
style={{ color: textColor, textDecoration, opacity }}
title={expandedCache.get(path) || undefined}
>
{path}
</td>
</tr>
);
})}
</tbody>
</table>
</div>
);
}
@@ -6,9 +6,6 @@ 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);
+2 -13
View File
@@ -124,19 +124,8 @@ export function useAppActions(activeTab: TabId, dialogs: DialogState) {
URL.revokeObjectURL(url);
}, []);
const handleSave = useCallback(async () => {
const result = await useAppStore.getState().savePaths();
if (result.kind === 'warning') {
// 长度超限,需要用户确认
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);
}
}
const handleSave = useCallback(() => {
useAppStore.getState().savePaths();
}, []);
// ── 键盘 ──
+5
View File
@@ -56,6 +56,11 @@ 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();
+4 -13
View File
@@ -8,9 +8,6 @@
"user": "User Variables",
"merged": "Merge Preview"
},
"table": {
"path": "Path"
},
"button": {
"new": "New",
"edit": "Edit",
@@ -54,8 +51,7 @@
"readonly_label": "Read-only",
"light": "Light",
"dark": "Dark",
"adminWarning": "Running without administrator privileges, some features are disabled",
"saveWarningLongPaths": "PATH length exceeds recommended value. Continue saving?"
"adminWarning": "Running without administrator privileges, some features are disabled"
},
"dialog": {
"newPath": "New Path",
@@ -74,9 +70,7 @@
"backupMessage": "Back up registry before saving?",
"confirm": "Confirm",
"cancel": "Cancel",
"search": "Search paths...",
"importSystemCount": "System: {{count}} entries",
"importUserCount": "User: {{count}} entries"
"search": "Search paths..."
},
"analyze": {
"title": "PATH Analysis",
@@ -88,8 +82,7 @@
"priority": "Prioritized",
"shadowed": "Shadowed",
"searchPlaceholder": "Search executable name...",
"conflictCount": "{{count}} file conflict(s) found",
"notExists": "(not found)"
"conflictCount": "{{count}} file conflict(s) found"
},
"profile": {
"title": "PATH Profiles",
@@ -102,9 +95,7 @@
"rename": "Rename",
"noProfiles": "No saved profiles",
"applyConfirm": "This will overwrite current PATH with profile \"{{name}}\" and write to registry. Confirm?",
"deleted": "Profile \"{{name}}\" deleted",
"selectProfile": "Select a profile",
"empty": "(empty)"
"deleted": "Profile \"{{name}}\" deleted"
},
"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"
+4 -13
View File
@@ -8,9 +8,6 @@
"user": "用户变量",
"merged": "合并预览"
},
"table": {
"path": "路径"
},
"button": {
"new": "新建",
"edit": "编辑",
@@ -54,8 +51,7 @@
"modified": "已修改",
"readonly_label": "只读",
"light": "浅色",
"dark": "深色",
"saveWarningLongPaths": "PATH 长度超过建议值,是否继续保存?"
"dark": "深色"
},
"dialog": {
"newPath": "新建路径",
@@ -74,9 +70,7 @@
"backupMessage": "保存前需要备份注册表吗?",
"confirm": "确认",
"cancel": "取消",
"search": "搜索路径...",
"importSystemCount": "系统变量: {{count}} 条",
"importUserCount": "用户变量: {{count}} 条"
"search": "搜索路径..."
},
"analyze": {
"title": "PATH 分析",
@@ -88,8 +82,7 @@
"priority": "优先执行",
"shadowed": "被遮蔽",
"searchPlaceholder": "搜索可执行文件名...",
"conflictCount": "发现 {{count}} 个文件冲突",
"notExists": "(不存在)"
"conflictCount": "发现 {{count}} 个文件冲突"
},
"profile": {
"title": "PATH 配置文件",
@@ -102,9 +95,7 @@
"rename": "重命名",
"noProfiles": "暂无配置文件",
"applyConfirm": "将用配置 \"{{name}}\" 覆盖当前 PATH 并写入注册表,确定吗?",
"deleted": "已删除配置 \"{{name}}\"",
"selectProfile": "选择一个配置文件",
"empty": "(空)"
"deleted": "已删除配置 \"{{name}}\""
},
"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"
+18 -42
View File
@@ -8,13 +8,6 @@ import appConfig from '@/config/default.json';
export type TabId = 'system' | 'user' | 'merged';
export type SaveResult =
| { kind: 'success' }
| { kind: 'warning'; reason: 'lengthExceeded' }
| { kind: 'failure'; message: string }
| { kind: 'partial'; message: string }
| { kind: 'blocked' };
interface AppState {
sysPaths: PathEntry[];
userPaths: PathEntry[];
@@ -52,7 +45,7 @@ interface AppState {
redo: () => void;
loadPaths: () => Promise<void>;
savePaths: (force?: boolean) => Promise<SaveResult>;
savePaths: () => Promise<void>;
initialize: () => Promise<void>;
}
@@ -296,9 +289,7 @@ export const useAppStore = create<AppState>((set, get) => {
const { sysPaths: sys, userPaths: usr } = 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((e) =>
console.warn('保存禁用状态失败:', e),
);
invoke('save_disabled_state', { system: sysDisabled, user: usrDisabled }).catch(() => {});
},
undo: () => {
@@ -316,7 +307,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((e) => console.warn('保存禁用状态失败:', e));
}).catch(() => {});
}
},
@@ -335,7 +326,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((e) => console.warn('保存禁用状态失败:', e));
}).catch(() => {});
}
},
@@ -382,9 +373,9 @@ export const useAppStore = create<AppState>((set, get) => {
}
},
savePaths: async (force?: boolean) => {
savePaths: async () => {
const state = get();
if (state.isSaving) return { kind: 'blocked' };
if (state.isSaving) return;
set({ isSaving: true, statusMessage: i18n.t('status.saving') });
// 只保存 enabled 的路径到注册表
@@ -393,16 +384,16 @@ export const useAppStore = create<AppState>((set, get) => {
const sysJoined = sysPaths.join(';');
const userJoined = userPaths.join(';');
// 长度检查:非强制模式下返回警告,由 UI 层确认
const { maxSystemLength, maxUserLength, maxCombinedLength } = appConfig.path;
if (
!force &&
(sysJoined.length > maxSystemLength ||
userJoined.length > maxUserLength ||
(sysJoined + userJoined).length > maxCombinedLength)
sysJoined.length > maxSystemLength ||
userJoined.length > maxUserLength ||
(sysJoined + userJoined).length > maxCombinedLength
) {
set({ isSaving: false, statusMessage: i18n.t('status.saveWarningLongPaths') });
return { kind: 'warning', reason: 'lengthExceeded' };
if (!window.confirm('PATH 长度超过建议值,是否继续保存?')) {
set({ isSaving: false });
return;
}
}
// 备份当前注册表(保存前备份旧值,失败仅警告不中断)
@@ -411,12 +402,9 @@ export const useAppStore = create<AppState>((set, get) => {
backupFailed = true;
});
const origSys = state._savedSys.filter((e) => e.enabled).map((e) => e.path);
const origUser = state._savedUser.filter((e) => e.enabled).map((e) => e.path);
const [sysResult, userResult] = await Promise.allSettled([
invoke('save_system_paths', { paths: sysPaths, original: origSys }),
invoke('save_user_paths', { paths: userPaths, original: origUser }),
invoke('save_system_paths', { paths: sysPaths }),
invoke('save_user_paths', { paths: userPaths }),
]);
const sysOk = sysResult.status === 'fulfilled';
@@ -435,28 +423,16 @@ export const useAppStore = create<AppState>((set, get) => {
_savedSys: savedSys,
_savedUser: savedUser,
});
return { kind: 'success' };
} 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 保存失败: ${usrErr}`
? '用户 PATH 保存失败'
: userOk
? `系统 PATH 保存失败: ${sysErr}`
? '系统 PATH 保存失败'
: `保存失败: ${parts.join('; ')}`;
if (sysOk || userOk) {
// partial success
set({ isSaving: false });
await get().loadPaths(); // reload to avoid state drift
set({ statusMessage: msg }); // restore the error message overwritten by loadPaths
return { kind: 'partial', message: msg };
} else {
set({ isSaving: false, statusMessage: msg });
return { kind: 'failure', message: msg };
}
set({ isSaving: false, statusMessage: msg });
}
},
+1
View File
@@ -1,3 +1,4 @@
// @vitest-environment jsdom
import { describe, it, expect, vi } from 'vitest';
import { render } from '@testing-library/react';
import { AnalyzeDialog } from '../../src/components/dialogs/AnalyzeDialog';
+6 -13
View File
@@ -242,26 +242,19 @@ describe('savePaths', () => {
it('保存成功', async () => {
mockedInvoke.mockResolvedValue(undefined);
const result = await useAppStore.getState().savePaths();
expect(result).toEqual({ kind: 'success' });
await useAppStore.getState().savePaths();
const s = useAppStore.getState();
expect(s.isSaving).toBe(false);
expect(s.isModified).toBe(false);
expect(s.statusMessage).toBe('保存成功');
});
it('部分失败时报告具体 hive 并回读', async () => {
it('部分失败时报告具体 hive', async () => {
mockedInvoke
.mockResolvedValueOnce(undefined) // backup_registry
.mockResolvedValueOnce(undefined) // save_system_paths
.mockRejectedValueOnce('权限不足') // save_user_paths
// 以下为 partial 触发的 loadPaths 调用
.mockResolvedValueOnce(['A']) // load_system_paths
.mockResolvedValueOnce(['B']) // load_user_paths
.mockResolvedValueOnce([[], []]); // load_disabled_state
const result = await useAppStore.getState().savePaths();
expect(result.kind).toBe('partial');
.mockRejectedValueOnce('权限不足'); // save_user_paths
await useAppStore.getState().savePaths();
const s = useAppStore.getState();
expect(s.isSaving).toBe(false);
expect(s.statusMessage).toContain('用户 PATH 保存失败');
@@ -280,8 +273,8 @@ describe('savePaths', () => {
// 第二次调用应被 isSaving 守卫拦截(此时 isSaving=true
const r2 = useAppStore.getState().savePaths();
// 第二次调用同步返回 blocked(被守卫拦截)
await expect(r2).resolves.toEqual({ kind: 'blocked' });
// 第二次调用同步返回 undefined(被守卫拦截)
await expect(r2).resolves.toBeUndefined();
// 放行第一次调用的所有 invoke
resolveAll!(undefined);
+1 -1
View File
@@ -24,7 +24,7 @@ describe('exportToJson', () => {
it('导出结构化 JSON', () => {
const json = exportToJson(sampleData);
const parsed = JSON.parse(json);
expect(parsed.version).toBe('5.1.0');
expect(parsed.version).toBe('5.0.0');
expect(parsed.timestamp).toBeDefined();
expect(parsed.system.map((e: { path: string }) => e.path)).toEqual(
sampleData.system.map((e) => e.path),
+1 -15
View File
@@ -1,3 +1,4 @@
// @vitest-environment jsdom
import { describe, it, expect, vi } from 'vitest';
import { render } from '@testing-library/react';
import { MergePreview } from '../../src/components/path-list/MergePreview';
@@ -16,21 +17,6 @@ vi.mock('@/store/app-store', () => ({
}),
}));
vi.mock('@tanstack/react-virtual', () => ({
useVirtualizer: (options: Record<string, number>) => ({
getVirtualItems: () => {
// return an array of objects to mock virtual items
return Array.from({ length: options.count }).map((_, index) => ({
index,
start: index * 28,
size: 28,
key: `mock-key-${index}`,
}));
},
getTotalSize: () => options.count * 28,
}),
}));
vi.mock('@/i18n', () => ({
default: { t: vi.fn((key: string) => key) },
}));
+1 -39
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { pathClean, analyzePaths } from '../../src/core/path-manager';
import { pathClean } from '../../src/core/path-manager';
import type { PathEntry } from '../../src/core/path-entry';
function pe(s: string, enabled: boolean = true): PathEntry {
@@ -9,31 +9,6 @@ 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(
@@ -53,25 +28,12 @@ describe('pathClean', () => {
expect(removed.length).toBe(1);
});
it('保留第一个出现的 enabled 状态', () => {
const [kept, removed] = pathClean([pe('C:\\Valid', false), pe('C:\\Valid', true)], alwaysValid);
expect(kept.length).toBe(1);
expect(kept[0].enabled).toBe(false); // 第一个状态
expect(removed.length).toBe(1);
});
it('全部有效无变化', () => {
const [kept, removed] = pathClean([pe('C:\\a'), pe('D:\\b')], alwaysValid);
expect(kept.map((e) => e.path)).toEqual(['C:\\a', 'D:\\b']);
expect(removed.length).toBe(0);
});
it('空数组处理', () => {
const [kept, removed] = pathClean([], alwaysValid);
expect(kept.length).toBe(0);
expect(removed.length).toBe(0);
});
it('全部无效全部移除', () => {
const [kept, removed] = pathClean([pe('C:\\Invalid1'), pe('C:\\Invalid2')], validateFn);
expect(kept.length).toBe(0);
-48
View File
@@ -146,26 +146,6 @@ describe('UndoRedoManager', () => {
expect(mgr.canRedo()).toBe(false);
});
it('空历史栈的撤销与重做', () => {
expect(mgr.undo(sys, user)).toBeNull();
expect(mgr.redo(sys, user)).toBeNull();
});
it('超出栈底/栈顶的安全处理', () => {
mgr.push(makeRecord(OperationType.ADD, TargetType.SYSTEM, 2, 1, [], [pe('C:\\NewPath')]));
sys.push(pe('C:\\NewPath'));
// undo一次
mgr.undo(sys, user);
// 再次undo,此时应到达底部返回null
expect(mgr.undo(sys, user)).toBeNull();
// redo一次
mgr.redo(sys, user);
// 再次redo,应到达顶部返回null
expect(mgr.redo(sys, user)).toBeNull();
});
it('超出最大历史容量时移除最旧记录', () => {
const small = new UndoRedoManager(3);
for (let i = 0; i < 5; i++) {
@@ -226,32 +206,4 @@ 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);
});
});
+1
View File
@@ -1,3 +1,4 @@
/** @vitest-environment jsdom */
import { describe, it, expect, vi, beforeEach } from 'vitest';
// ── Mock 外部依赖 ──
+1 -2
View File
@@ -2,7 +2,6 @@
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" },
{ "path": "./tsconfig.test.json" }
{ "path": "./tsconfig.node.json" }
]
}
+6 -4
View File
@@ -8,15 +8,17 @@ export default defineConfig({
},
},
test: {
environment: 'jsdom',
exclude: ['e2e/**', 'node_modules/**', 'gui/**'],
coverage: {
provider: 'v8',
reporter: ['text', 'lcov', 'cobertura'],
include: ['src/core/**', 'src/store/**', 'src/hooks/**'],
exclude: ['src/main.tsx', 'src/vite-env.d.ts'],
include: ['src/**/*.{ts,tsx}'],
exclude: ['src/main.tsx', 'src/vite-env.d.ts', '**/*.test.{ts,tsx}', '**/*.spec.{ts,tsx}'],
thresholds: {
lines: 80,
branches: 60,
functions: 60,
lines: 70,
statements: 70,
},
},
},