mirror of
https://github.com/LHY0125/PathEditor.git
synced 2026-06-30 02:25:55 +08:00
Compare commits
12 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 10495a092d | |||
| d649b03c3b | |||
| 9453006310 | |||
| 60de924b08 | |||
| a9b36a6f47 | |||
| 78439a6ac6 | |||
| e0e3c802dd | |||
| 21da3b2930 | |||
| bce2dc8641 | |||
| 461ef231e4 | |||
| e5b348bb9b | |||
| cbf99f12fd |
@@ -1,5 +0,0 @@
|
||||
# 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
|
||||
@@ -1,6 +0,0 @@
|
||||
node_modules/
|
||||
dist/
|
||||
target/
|
||||
test-results/
|
||||
e2e/
|
||||
*.config.*
|
||||
@@ -31,7 +31,7 @@ jobs:
|
||||
run: npx tsc -b --noEmit
|
||||
|
||||
- name: ESLint
|
||||
run: npx eslint src/ tests/
|
||||
run: npx eslint src/ tests/ e2e/
|
||||
|
||||
- name: Vitest 测试 + 覆盖率
|
||||
run: npx vitest run --coverage
|
||||
@@ -50,7 +50,9 @@ jobs:
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Cargo Format
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
|
||||
- name: Cargo Format Check
|
||||
run: cargo fmt --check
|
||||
|
||||
- name: Cargo Check
|
||||
|
||||
+1
-1
@@ -26,7 +26,6 @@ playwright-report/
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
.codegraph/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
@@ -38,6 +37,7 @@ playwright-report/
|
||||
|
||||
# AI assistant
|
||||
.claude/
|
||||
.codegraph/
|
||||
CLAUDE.md
|
||||
|
||||
# Platform
|
||||
|
||||
@@ -65,11 +65,13 @@ PathEditor/
|
||||
│ │ ├── toolbar/ # ToolBar、ActionButtons、UndoRedoButtons
|
||||
│ │ ├── dialogs/ # PathEdit、Help、Import、Analyze、Profile
|
||||
│ │ └── ui/ # Modal、buttons
|
||||
│ ├── hooks/ # useAppActions、useKeyboard
|
||||
│ ├── hooks/ # useAppActions、useKeyboard、usePathValidation
|
||||
│ ├── i18n/ # zh-CN / en
|
||||
│ └── config/ # default.json
|
||||
├── docs/ # REMaining-ISSUES 等审查文档
|
||||
├── tests/unit/ # Vitest 前端单元测试
|
||||
├── e2e/ # Playwright E2E 测试
|
||||
├── rust-toolchain.toml # 固定工具链版本
|
||||
└── Cargo.toml # Workspace 根 + [workspace.package]
|
||||
```
|
||||
|
||||
@@ -144,7 +146,7 @@ patheditor profile {list|save|load|apply|delete|rename}
|
||||
## 关键约束
|
||||
|
||||
- **TypeScript**:`strict: true`,零编译错误
|
||||
- **Rust 工具链**:`stable-x86_64-pc-windows-gnu`(项目已设 override)
|
||||
- **Rust 工具链**:`stable-x86_64-pc-windows-gnu`(`rust-toolchain.toml` 强制)
|
||||
- **MinGW 兼容**:`.cargo/config.toml` 添加 `-lmcfgthread`(GCC 15.2.0 运行时)
|
||||
- **运行权限**:需要管理员权限才能编辑系统 PATH,非管理员自动进入只读模式
|
||||
- **构建产物**:NSIS 安装包,约 8MB
|
||||
|
||||
Generated
+4
-3
@@ -2379,19 +2379,20 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "path-editor-core"
|
||||
version = "5.0.0"
|
||||
version = "5.1.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.0.0"
|
||||
version = "5.1.0"
|
||||
dependencies = [
|
||||
"log",
|
||||
"path-editor-core",
|
||||
@@ -2404,7 +2405,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "patheditor-cli"
|
||||
version = "5.0.0"
|
||||
version = "5.1.0"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"path-editor-core",
|
||||
|
||||
+1
-1
@@ -7,7 +7,7 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "5.0.0"
|
||||
version = "5.1.0"
|
||||
edition = "2021"
|
||||
license = "MIT"
|
||||
authors = ["刘航宇"]
|
||||
|
||||
@@ -4,14 +4,14 @@
|
||||
</p>
|
||||
|
||||
<p align="center">
|
||||
<img src="https://img.shields.io/badge/version-5.0.0-blue" alt="version">
|
||||
<img src="https://img.shields.io/badge/version-5.1.0-blue" alt="version">
|
||||
<img src="https://img.shields.io/badge/tauri-2.x-ffa03a" alt="tauri">
|
||||
<img src="https://img.shields.io/badge/react-19-61dafb" alt="react">
|
||||
<img src="https://img.shields.io/badge/rust-1.95-000000" alt="rust">
|
||||
<img src="https://img.shields.io/badge/typescript-strict-blue" alt="typescript">
|
||||
<img src="https://img.shields.io/badge/license-MIT-green" alt="license">
|
||||
<img src="https://img.shields.io/badge/tests-72%20passed-brightgreen" alt="tests">
|
||||
<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/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/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 (72 个测试) |
|
||||
| Rust 测试 | cargo test (10 个测试) |
|
||||
| 前端测试 | Vitest (100 个测试) |
|
||||
| Rust 测试 | cargo test (57 个测试) |
|
||||
| 构建 | Vite + Cargo |
|
||||
| 打包 | NSIS |
|
||||
|
||||
@@ -304,10 +304,11 @@ src/ # React 前端
|
||||
├── core/ # 纯逻辑 — 零框架依赖
|
||||
├── store/ # Zustand 状态管理
|
||||
├── components/ # UI 组件
|
||||
├── hooks/ # useAppActions、useKeyboard
|
||||
├── hooks/ # useAppActions、useKeyboard、usePathValidation
|
||||
├── i18n/ # zh-CN / en
|
||||
└── config/ # default.json
|
||||
tests/unit/ # 前端单元测试
|
||||
docs/ # 审查文档
|
||||
```
|
||||
|
||||
## 快捷键
|
||||
|
||||
+282
-100
@@ -13,79 +13,109 @@ struct Cli {
|
||||
enum Command {
|
||||
/// 列出 PATH 路径
|
||||
List {
|
||||
#[arg(short, long)] system: bool,
|
||||
#[arg(short, long)] user: bool,
|
||||
#[arg(long)] json: bool,
|
||||
#[arg(short, long)]
|
||||
system: bool,
|
||||
#[arg(short, long)]
|
||||
user: bool,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// 添加一条路径
|
||||
Add {
|
||||
path: String,
|
||||
#[arg(short, long)] system: bool,
|
||||
#[arg(short, long)] user: bool,
|
||||
#[arg(short, long)]
|
||||
system: bool,
|
||||
#[arg(short, long)]
|
||||
user: bool,
|
||||
},
|
||||
/// 删除指定位置的路径
|
||||
Remove {
|
||||
index: usize,
|
||||
#[arg(short, long)] system: bool,
|
||||
#[arg(short, long)]
|
||||
system: bool,
|
||||
},
|
||||
/// 编辑指定位置的路径
|
||||
Edit {
|
||||
index: usize,
|
||||
new_path: String,
|
||||
#[arg(short, long)] system: bool,
|
||||
#[arg(short, long)]
|
||||
system: bool,
|
||||
},
|
||||
/// 上移路径(--steps 指定移动格数,默认 1)
|
||||
MoveUp {
|
||||
index: usize,
|
||||
#[arg(long, default_value = "1")] steps: usize,
|
||||
#[arg(short, long)] system: bool,
|
||||
#[arg(long, default_value = "1")]
|
||||
steps: usize,
|
||||
#[arg(short, long)]
|
||||
system: bool,
|
||||
},
|
||||
/// 下移路径(--steps 指定移动格数,默认 1)
|
||||
MoveDown {
|
||||
index: usize,
|
||||
#[arg(long, default_value = "1")] steps: usize,
|
||||
#[arg(short, long)] system: bool,
|
||||
#[arg(long, default_value = "1")]
|
||||
steps: usize,
|
||||
#[arg(short, long)]
|
||||
system: bool,
|
||||
},
|
||||
/// 清理无效和重复路径
|
||||
Clean {
|
||||
#[arg(short, long)] system: bool,
|
||||
#[arg(short, long)] user: bool,
|
||||
#[arg(long)] dry_run: bool,
|
||||
#[arg(long)] json: bool,
|
||||
#[arg(short, long)]
|
||||
system: bool,
|
||||
#[arg(short, long)]
|
||||
user: bool,
|
||||
#[arg(long)]
|
||||
dry_run: bool,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// 启用指定位置的路径
|
||||
Enable {
|
||||
index: usize,
|
||||
#[arg(short, long)] system: bool,
|
||||
#[arg(short, long)] user: bool,
|
||||
#[arg(short, long)]
|
||||
system: bool,
|
||||
#[arg(short, long)]
|
||||
user: bool,
|
||||
},
|
||||
/// 禁用指定位置的路径
|
||||
Disable {
|
||||
index: usize,
|
||||
#[arg(short, long)] system: bool,
|
||||
#[arg(short, long)] user: bool,
|
||||
#[arg(short, long)]
|
||||
system: bool,
|
||||
#[arg(short, long)]
|
||||
user: bool,
|
||||
},
|
||||
/// 从文件导入 PATH(JSON/CSV/TXT)
|
||||
Import {
|
||||
file: String,
|
||||
#[arg(long, default_value = "both")] target: String,
|
||||
#[arg(long, default_value = "both")]
|
||||
target: String,
|
||||
},
|
||||
/// 导出 PATH 为文件
|
||||
Export {
|
||||
#[arg(long, default_value = "json")] format: String,
|
||||
#[arg(short, long)] output: Option<String>,
|
||||
#[arg(long, default_value = "json")]
|
||||
format: String,
|
||||
#[arg(short, long)]
|
||||
output: Option<String>,
|
||||
},
|
||||
/// 创建注册表备份
|
||||
Backup,
|
||||
/// 检测可执行文件冲突
|
||||
Conflicts { #[arg(long)] json: bool },
|
||||
Conflicts {
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// 列出 PATH 目录中的可执行文件
|
||||
Scan {
|
||||
#[arg(long)] query: Option<String>,
|
||||
#[arg(long)] json: bool,
|
||||
#[arg(long)]
|
||||
query: Option<String>,
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// 检查管理员权限
|
||||
CheckAdmin { #[arg(long)] json: bool },
|
||||
CheckAdmin {
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// 管理配置文件
|
||||
#[command(subcommand)]
|
||||
Profile(ProfileCmd),
|
||||
@@ -94,7 +124,10 @@ enum Command {
|
||||
#[derive(Subcommand)]
|
||||
enum ProfileCmd {
|
||||
/// 列出所有配置
|
||||
List { #[arg(long)] json: bool },
|
||||
List {
|
||||
#[arg(long)]
|
||||
json: bool,
|
||||
},
|
||||
/// 保存当前 PATH 为配置
|
||||
Save { name: String },
|
||||
/// 加载配置(预览)
|
||||
@@ -105,8 +138,10 @@ enum ProfileCmd {
|
||||
Delete { name: String },
|
||||
/// 重命名配置
|
||||
Rename {
|
||||
#[arg(long)] old: String,
|
||||
#[arg(long)] new: String,
|
||||
#[arg(long)]
|
||||
old: String,
|
||||
#[arg(long)]
|
||||
new: String,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -116,8 +151,14 @@ fn exit_err(msg: &str) -> ! {
|
||||
}
|
||||
|
||||
fn ensure_single_target(system: bool, user: bool) -> &'static str {
|
||||
if system && user { exit_err("不能同时指定 --system 和 --user"); }
|
||||
if system { "system" } else { "user" }
|
||||
if system && user {
|
||||
exit_err("不能同时指定 --system 和 --user");
|
||||
}
|
||||
if system {
|
||||
"system"
|
||||
} else {
|
||||
"user"
|
||||
}
|
||||
}
|
||||
|
||||
type SaveFn = fn(Vec<String>) -> Result<(), String>;
|
||||
@@ -131,7 +172,11 @@ fn verify_and_save(target: &str, original: &[String], new_list: Vec<String>) {
|
||||
if reload != original {
|
||||
exit_err("注册表已被其他进程修改,请重新执行操作");
|
||||
}
|
||||
let save: SaveFn = if target == "system" { core::registry::save_system_paths } else { core::registry::save_user_paths };
|
||||
let save: SaveFn = if target == "system" {
|
||||
core::registry::save_system_paths
|
||||
} else {
|
||||
core::registry::save_user_paths
|
||||
};
|
||||
save(new_list).unwrap_or_else(|e| exit_err(&e));
|
||||
}
|
||||
|
||||
@@ -146,6 +191,29 @@ fn load_and_save(system: bool, f: impl FnOnce(Vec<String>) -> Vec<String>) {
|
||||
verify_and_save(target, &list, new_list);
|
||||
}
|
||||
|
||||
/// 加载、检查索引、操作、验证、保存的通用模式
|
||||
/// `operate` 接收路径列表(包含原始列表)和要操作的索引,返回新列表和打印消息
|
||||
fn load_operate_save(
|
||||
system: bool,
|
||||
index: usize,
|
||||
operate: impl FnOnce(Vec<String>, usize) -> (Vec<String>, String),
|
||||
) {
|
||||
let target = ensure_single_target(system, false);
|
||||
let list = if target == "system" {
|
||||
core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e))
|
||||
} else {
|
||||
core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e))
|
||||
};
|
||||
if index >= list.len() {
|
||||
exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len()));
|
||||
}
|
||||
let original = list.clone();
|
||||
let (new_list, msg) = operate(list, index);
|
||||
verify_and_save(target, &original, new_list);
|
||||
println!("{msg}");
|
||||
core::system::broadcast_env_change();
|
||||
}
|
||||
|
||||
// ── 命令实现 ──
|
||||
|
||||
fn cmd_list(system: bool, user: bool, json_out: bool) {
|
||||
@@ -163,11 +231,15 @@ fn cmd_list(system: bool, user: bool, json_out: bool) {
|
||||
} else {
|
||||
if !sys.is_empty() {
|
||||
println!("═══ 系统 PATH ({}) ═══", sys.len());
|
||||
for (i, p) in sys.iter().enumerate() { println!(" [{}] {}", i, p); }
|
||||
for (i, p) in sys.iter().enumerate() {
|
||||
println!(" [{}] {}", i, p);
|
||||
}
|
||||
}
|
||||
if !usr.is_empty() {
|
||||
println!("═══ 用户 PATH ({}) ═══", usr.len());
|
||||
for (i, p) in usr.iter().enumerate() { println!(" [{}] {}", i, p); }
|
||||
for (i, p) in usr.iter().enumerate() {
|
||||
println!(" [{}] {}", i, p);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -178,49 +250,43 @@ fn cmd_add(path: String, system: bool, user: bool) {
|
||||
list.push(path.clone());
|
||||
list
|
||||
});
|
||||
let label = if target == "system" { "系统" } else { "用户" };
|
||||
let label = if target == "system" {
|
||||
"系统"
|
||||
} else {
|
||||
"用户"
|
||||
};
|
||||
println!("已添加到{} PATH: {path}", label);
|
||||
core::system::broadcast_env_change();
|
||||
}
|
||||
|
||||
fn cmd_remove(index: usize, system: bool) {
|
||||
let target = ensure_single_target(system, false);
|
||||
let mut list = if target == "system" {
|
||||
core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e))
|
||||
} else {
|
||||
core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e))
|
||||
};
|
||||
let original = list.clone();
|
||||
if index >= list.len() { exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len())); }
|
||||
let removed = list.remove(index);
|
||||
verify_and_save(target, &original, list);
|
||||
println!("已删除: {removed}");
|
||||
core::system::broadcast_env_change();
|
||||
load_operate_save(system, index, |mut list, idx| {
|
||||
let removed = list.remove(idx);
|
||||
(list, format!("已删除: {removed}"))
|
||||
});
|
||||
}
|
||||
|
||||
fn cmd_edit(index: usize, new_path: String, system: bool) {
|
||||
let target = ensure_single_target(system, false);
|
||||
let mut list = if target == "system" {
|
||||
core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e))
|
||||
} else {
|
||||
core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e))
|
||||
};
|
||||
if index >= list.len() { exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len())); }
|
||||
let original = list.clone();
|
||||
let old = std::mem::replace(&mut list[index], new_path.clone());
|
||||
verify_and_save(target, &original, list);
|
||||
println!("已编辑: {old} → {new_path}");
|
||||
core::system::broadcast_env_change();
|
||||
load_operate_save(system, index, |mut list, idx| {
|
||||
let old = std::mem::replace(&mut list[idx], new_path.clone());
|
||||
(list, format!("已编辑: {old} → {new_path}"))
|
||||
});
|
||||
}
|
||||
|
||||
fn cmd_move(index: usize, steps: usize, system: bool, up: bool) {
|
||||
load_and_save(system, |mut list| {
|
||||
if index >= list.len() { exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len())); }
|
||||
if index >= list.len() {
|
||||
exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len()));
|
||||
}
|
||||
let end = if up {
|
||||
index.saturating_sub(steps)
|
||||
} else {
|
||||
let max = list.len() - 1;
|
||||
if index + steps > max { max } else { index + steps }
|
||||
if index + steps > max {
|
||||
max
|
||||
} else {
|
||||
index + steps
|
||||
}
|
||||
};
|
||||
let removed = list.remove(index);
|
||||
list.insert(end, removed);
|
||||
@@ -232,19 +298,31 @@ fn cmd_move(index: usize, steps: usize, system: bool, up: bool) {
|
||||
}
|
||||
|
||||
fn cmd_clean(system: bool, user: bool, dry_run: bool, json_out: bool) {
|
||||
if system && user { exit_err("不能同时指定 --system 和 --user"); }
|
||||
if system && user {
|
||||
exit_err("不能同时指定 --system 和 --user");
|
||||
}
|
||||
|
||||
let clean_sys = system || !user;
|
||||
let clean_usr = user || !system;
|
||||
|
||||
if clean_sys { clean_one("system", dry_run, json_out); }
|
||||
if clean_usr { clean_one("user", dry_run, json_out); }
|
||||
if clean_sys {
|
||||
clean_one("system", dry_run, json_out);
|
||||
}
|
||||
if clean_usr {
|
||||
clean_one("user", dry_run, json_out);
|
||||
}
|
||||
|
||||
if !dry_run && !json_out { core::system::broadcast_env_change(); }
|
||||
if !dry_run && !json_out {
|
||||
core::system::broadcast_env_change();
|
||||
}
|
||||
}
|
||||
|
||||
fn clean_one(target: &str, dry_run: bool, json_out: bool) {
|
||||
let label = if target == "system" { "系统" } else { "用户" };
|
||||
let label = if target == "system" {
|
||||
"系统"
|
||||
} else {
|
||||
"用户"
|
||||
};
|
||||
let list = if target == "system" {
|
||||
core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e))
|
||||
} else {
|
||||
@@ -253,18 +331,31 @@ fn clean_one(target: &str, dry_run: bool, json_out: bool) {
|
||||
let (kept, removed) = core::registry::clean_paths(list.clone());
|
||||
|
||||
if json_out {
|
||||
println!("{}", json!({ "target": target, "kept": kept, "removed": removed, "kept_count": kept.len(), "removed_count": removed.len() }));
|
||||
println!(
|
||||
"{}",
|
||||
json!({ "target": target, "kept": kept, "removed": removed, "kept_count": kept.len(), "removed_count": removed.len() })
|
||||
);
|
||||
} else if dry_run {
|
||||
println!("═══ {label} PATH — 将被移除({} 条)═══", removed.len());
|
||||
for r in &removed { println!(" ✗ {}", r); }
|
||||
for r in &removed {
|
||||
println!(" ✗ {}", r);
|
||||
}
|
||||
println!("═══ {label} PATH — 将保留({} 条)═══", kept.len());
|
||||
for k in &kept { println!(" ✓ {}", k); }
|
||||
for k in &kept {
|
||||
println!(" ✓ {}", k);
|
||||
}
|
||||
} else {
|
||||
let kept_count = kept.len();
|
||||
verify_and_save(target, &list, kept);
|
||||
println!("{label} PATH 清理完成:移除 {} 条,保留 {} 条", removed.len(), kept_count);
|
||||
println!(
|
||||
"{label} PATH 清理完成:移除 {} 条,保留 {} 条",
|
||||
removed.len(),
|
||||
kept_count
|
||||
);
|
||||
if !removed.is_empty() {
|
||||
for r in &removed { println!(" 已移除: {}", r); }
|
||||
for r in &removed {
|
||||
println!(" 已移除: {}", r);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -276,11 +367,18 @@ fn cmd_toggle(index: usize, system: bool, user: bool, enable: bool) {
|
||||
} else {
|
||||
core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e))
|
||||
};
|
||||
if index >= list.len() { exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len())); }
|
||||
if index >= list.len() {
|
||||
exit_err(&format!("索引 {index} 超出范围 (共 {} 条)", list.len()));
|
||||
}
|
||||
let path = &list[index];
|
||||
|
||||
let (mut sys_dis, mut usr_dis) = core::disabled::load_disabled_state().unwrap_or_else(|_| (vec![], vec![]));
|
||||
let target_list: &mut Vec<String> = if target == "system" { &mut sys_dis } else { &mut usr_dis };
|
||||
let (mut sys_dis, mut usr_dis) =
|
||||
core::disabled::load_disabled_state().unwrap_or_else(|_| (vec![], vec![]));
|
||||
let target_list: &mut Vec<String> = if target == "system" {
|
||||
&mut sys_dis
|
||||
} else {
|
||||
&mut usr_dis
|
||||
};
|
||||
|
||||
if enable {
|
||||
target_list.retain(|p| p != path);
|
||||
@@ -294,23 +392,26 @@ fn cmd_toggle(index: usize, system: bool, user: bool, enable: bool) {
|
||||
|
||||
fn cmd_import(file: String, target: String) {
|
||||
let content = core::fs::read_text_file(&file).unwrap_or_else(|e| exit_err(&e));
|
||||
let (sys, usr) = core::fs::import_paths(&file, &content).unwrap_or_else(|e| exit_err(&e));
|
||||
let (sys_entries, usr_entries) =
|
||||
core::fs::import_paths(&file, &content).unwrap_or_else(|e| exit_err(&e));
|
||||
let sys_paths: Vec<String> = sys_entries.into_iter().map(|e| e.path).collect();
|
||||
let usr_paths: Vec<String> = usr_entries.into_iter().map(|e| e.path).collect();
|
||||
match target.as_str() {
|
||||
"system" => {
|
||||
let orig = core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e));
|
||||
verify_and_save("system", &orig, sys);
|
||||
verify_and_save("system", &orig, sys_paths);
|
||||
println!("已导入到系统 PATH");
|
||||
}
|
||||
"user" => {
|
||||
let orig = core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e));
|
||||
verify_and_save("user", &orig, usr);
|
||||
verify_and_save("user", &orig, usr_paths);
|
||||
println!("已导入到用户 PATH");
|
||||
}
|
||||
_ => {
|
||||
let orig_sys = core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e));
|
||||
let orig_usr = core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e));
|
||||
verify_and_save("system", &orig_sys, sys);
|
||||
verify_and_save("user", &orig_usr, usr);
|
||||
verify_and_save("system", &orig_sys, sys_paths);
|
||||
verify_and_save("user", &orig_usr, usr_paths);
|
||||
println!("已导入到系统 + 用户 PATH");
|
||||
}
|
||||
}
|
||||
@@ -322,6 +423,12 @@ fn cmd_export(format: String, output: Option<String>) {
|
||||
let usr = core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e));
|
||||
let content = core::fs::export_paths(&sys, &usr, &format).unwrap_or_else(|e| exit_err(&e));
|
||||
if let Some(path) = output {
|
||||
// 拒绝写入系统关键目录
|
||||
let normalized = path.replace('/', "\\").to_lowercase();
|
||||
if normalized.starts_with("c:\\windows\\") || normalized.starts_with("c:\\program files\\")
|
||||
{
|
||||
exit_err(&format!("不允许导出到系统目录: {path}"));
|
||||
}
|
||||
std::fs::write(&path, &content).unwrap_or_else(|e| exit_err(&format!("无法写入文件: {e}")));
|
||||
println!("已导出到: {path}");
|
||||
} else {
|
||||
@@ -336,8 +443,12 @@ fn cmd_backup() {
|
||||
|
||||
fn cmd_conflicts(json_out: bool) {
|
||||
let mut paths: Vec<String> = vec![];
|
||||
if let Ok(sys) = core::registry::load_system_paths() { paths.extend(sys); }
|
||||
if let Ok(usr) = core::registry::load_user_paths() { paths.extend(usr); }
|
||||
if let Ok(sys) = core::registry::load_system_paths() {
|
||||
paths.extend(sys);
|
||||
}
|
||||
if let Ok(usr) = core::registry::load_user_paths() {
|
||||
paths.extend(usr);
|
||||
}
|
||||
let conflicts = core::scanner::scan_conflicts(paths).unwrap_or_else(|e| exit_err(&e));
|
||||
if json_out {
|
||||
println!("{}", serde_json::to_string_pretty(&conflicts).unwrap());
|
||||
@@ -348,7 +459,15 @@ fn cmd_conflicts(json_out: bool) {
|
||||
for c in &conflicts {
|
||||
println!(" {}", c.name);
|
||||
for loc in &c.locations {
|
||||
println!(" {} {}", if loc.priority == 0 { "✓ 优先" } else { "✗ 遮蔽" }, loc.dir);
|
||||
println!(
|
||||
" {} {}",
|
||||
if loc.priority == 0 {
|
||||
"✓ 优先"
|
||||
} else {
|
||||
"✗ 遮蔽"
|
||||
},
|
||||
loc.dir
|
||||
);
|
||||
}
|
||||
println!();
|
||||
}
|
||||
@@ -357,16 +476,26 @@ fn cmd_conflicts(json_out: bool) {
|
||||
|
||||
fn cmd_scan(query: Option<String>, json_out: bool) {
|
||||
let mut paths: Vec<String> = vec![];
|
||||
if let Ok(sys) = core::registry::load_system_paths() { paths.extend(sys); }
|
||||
if let Ok(usr) = core::registry::load_user_paths() { paths.extend(usr); }
|
||||
let groups = core::scanner::scan_tools(paths, query.unwrap_or_default()).unwrap_or_else(|e| exit_err(&e));
|
||||
if let Ok(sys) = core::registry::load_system_paths() {
|
||||
paths.extend(sys);
|
||||
}
|
||||
if let Ok(usr) = core::registry::load_user_paths() {
|
||||
paths.extend(usr);
|
||||
}
|
||||
let groups = core::scanner::scan_tools(paths, query.unwrap_or_default())
|
||||
.unwrap_or_else(|e| exit_err(&e));
|
||||
if json_out {
|
||||
println!("{}", serde_json::to_string_pretty(&groups).unwrap());
|
||||
} else {
|
||||
for g in &groups {
|
||||
if !g.exists { println!(" {} (不存在)", g.dir); continue; }
|
||||
if !g.exists {
|
||||
println!(" {} (不存在)", g.dir);
|
||||
continue;
|
||||
}
|
||||
println!("═══ {} ═══", g.dir);
|
||||
for exe in &g.exes { println!(" {}", exe); }
|
||||
for exe in &g.exes {
|
||||
println!(" {}", exe);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -387,15 +516,29 @@ fn profile_list(json_out: bool) {
|
||||
} else if list.is_empty() {
|
||||
println!("暂无配置文件。");
|
||||
} else {
|
||||
for p in &list { println!(" {} ({})", p.name, p.modified); }
|
||||
for p in &list {
|
||||
println!(" {} ({})", p.name, p.modified);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn profile_save(name: String) {
|
||||
let sys = core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e));
|
||||
let usr = core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e));
|
||||
let sys_entries = sys.into_iter().map(|p| core::ProfilePathEntry { path: p, enabled: true }).collect();
|
||||
let usr_entries = usr.into_iter().map(|p| core::ProfilePathEntry { path: p, enabled: true }).collect();
|
||||
let sys_entries = sys
|
||||
.into_iter()
|
||||
.map(|p| core::ProfilePathEntry {
|
||||
path: p,
|
||||
enabled: true,
|
||||
})
|
||||
.collect();
|
||||
let usr_entries = usr
|
||||
.into_iter()
|
||||
.map(|p| core::ProfilePathEntry {
|
||||
path: p,
|
||||
enabled: true,
|
||||
})
|
||||
.collect();
|
||||
core::profiles::save_profile(&name, sys_entries, usr_entries).unwrap_or_else(|e| exit_err(&e));
|
||||
println!("已保存配置: {name}");
|
||||
}
|
||||
@@ -403,15 +546,29 @@ fn profile_save(name: String) {
|
||||
fn profile_load(name: String) {
|
||||
let data = core::profiles::load_profile(&name).unwrap_or_else(|e| exit_err(&e));
|
||||
println!("═══ 系统 PATH ({} 条) ═══", data.sys.len());
|
||||
for e in &data.sys { println!(" [{}] {}", if e.enabled { "✓" } else { "✗" }, e.path); }
|
||||
for e in &data.sys {
|
||||
println!(" [{}] {}", if e.enabled { "✓" } else { "✗" }, e.path);
|
||||
}
|
||||
println!("═══ 用户 PATH ({} 条) ═══", data.user.len());
|
||||
for e in &data.user { println!(" [{}] {}", if e.enabled { "✓" } else { "✗" }, e.path); }
|
||||
for e in &data.user {
|
||||
println!(" [{}] {}", if e.enabled { "✓" } else { "✗" }, e.path);
|
||||
}
|
||||
}
|
||||
|
||||
fn profile_apply(name: String) {
|
||||
let data = core::profiles::load_profile(&name).unwrap_or_else(|e| exit_err(&e));
|
||||
let new_sys: Vec<String> = data.sys.into_iter().filter(|e| e.enabled).map(|e| e.path).collect();
|
||||
let new_usr: Vec<String> = data.user.into_iter().filter(|e| e.enabled).map(|e| e.path).collect();
|
||||
let new_sys: Vec<String> = data
|
||||
.sys
|
||||
.into_iter()
|
||||
.filter(|e| e.enabled)
|
||||
.map(|e| e.path)
|
||||
.collect();
|
||||
let new_usr: Vec<String> = data
|
||||
.user
|
||||
.into_iter()
|
||||
.filter(|e| e.enabled)
|
||||
.map(|e| e.path)
|
||||
.collect();
|
||||
|
||||
let orig_sys = core::registry::load_system_paths().unwrap_or_else(|e| exit_err(&e));
|
||||
let orig_usr = core::registry::load_user_paths().unwrap_or_else(|e| exit_err(&e));
|
||||
@@ -438,12 +595,37 @@ fn main() {
|
||||
Command::List { system, user, json } => cmd_list(system, user, json),
|
||||
Command::Add { path, system, user } => cmd_add(path, system, user),
|
||||
Command::Remove { index, system } => cmd_remove(index, system),
|
||||
Command::Edit { index, new_path, system } => cmd_edit(index, new_path, system),
|
||||
Command::MoveUp { index, steps, system } => cmd_move(index, steps, system, true),
|
||||
Command::MoveDown { index, steps, system } => cmd_move(index, steps, system, false),
|
||||
Command::Clean { system, user, dry_run, json } => cmd_clean(system, user, dry_run, json),
|
||||
Command::Enable { index, system, user } => cmd_toggle(index, system, user, true),
|
||||
Command::Disable { index, system, user } => cmd_toggle(index, system, user, false),
|
||||
Command::Edit {
|
||||
index,
|
||||
new_path,
|
||||
system,
|
||||
} => cmd_edit(index, new_path, system),
|
||||
Command::MoveUp {
|
||||
index,
|
||||
steps,
|
||||
system,
|
||||
} => cmd_move(index, steps, system, true),
|
||||
Command::MoveDown {
|
||||
index,
|
||||
steps,
|
||||
system,
|
||||
} => cmd_move(index, steps, system, false),
|
||||
Command::Clean {
|
||||
system,
|
||||
user,
|
||||
dry_run,
|
||||
json,
|
||||
} => cmd_clean(system, user, dry_run, json),
|
||||
Command::Enable {
|
||||
index,
|
||||
system,
|
||||
user,
|
||||
} => cmd_toggle(index, system, user, true),
|
||||
Command::Disable {
|
||||
index,
|
||||
system,
|
||||
user,
|
||||
} => cmd_toggle(index, system, user, false),
|
||||
Command::Import { file, target } => cmd_import(file, target),
|
||||
Command::Export { format, output } => cmd_export(format, output),
|
||||
Command::Backup => cmd_backup(),
|
||||
|
||||
@@ -13,3 +13,4 @@ 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"] }
|
||||
|
||||
+13
-16
@@ -1,7 +1,7 @@
|
||||
use crate::registry::{self, SYS_REG_PATH, USER_REG_PATH};
|
||||
use chrono::Local;
|
||||
use std::path::PathBuf;
|
||||
use winreg::enums::*;
|
||||
use crate::registry::{self, SYS_REG_PATH, USER_REG_PATH};
|
||||
|
||||
fn backup_base_dir() -> PathBuf {
|
||||
dirs::home_dir()
|
||||
@@ -19,24 +19,22 @@ pub fn get_appdata_dir() -> String {
|
||||
/// 在保存前调用,备份的是注册表中的当前值(保存前的状态)
|
||||
pub fn backup_registry(custom_dir: Option<String>) -> Result<String, String> {
|
||||
let backup_dir = match custom_dir {
|
||||
Some(ref dir) if !dir.is_empty() => std::path::PathBuf::from(dir),
|
||||
Some(ref dir) if !dir.is_empty() => {
|
||||
let p = std::path::PathBuf::from(dir);
|
||||
let normalized = dir.replace('/', "\\").to_lowercase();
|
||||
if normalized.starts_with("c:\\windows\\") || normalized.starts_with("c:\\program files\\") {
|
||||
return Err("不允许备份到系统目录".into());
|
||||
}
|
||||
p
|
||||
}
|
||||
_ => backup_base_dir(),
|
||||
};
|
||||
|
||||
std::fs::create_dir_all(&backup_dir)
|
||||
.map_err(|e| format!("无法创建备份目录: {}", e))?;
|
||||
std::fs::create_dir_all(&backup_dir).map_err(|e| format!("无法创建备份目录: {}", e))?;
|
||||
|
||||
// 读取当前注册表中的值(保存前的旧值)
|
||||
let sys_paths = registry::load_paths(
|
||||
HKEY_LOCAL_MACHINE,
|
||||
SYS_REG_PATH,
|
||||
"系统",
|
||||
)?;
|
||||
let user_paths = registry::load_paths(
|
||||
HKEY_CURRENT_USER,
|
||||
USER_REG_PATH,
|
||||
"用户",
|
||||
)?;
|
||||
let sys_paths = registry::load_paths(HKEY_LOCAL_MACHINE, SYS_REG_PATH, "系统")?;
|
||||
let user_paths = registry::load_paths(HKEY_CURRENT_USER, USER_REG_PATH, "用户")?;
|
||||
|
||||
let timestamp = Local::now().format("%Y%m%d_%H%M%S_%3f");
|
||||
let filename = format!("path_backup_{}.txt", timestamp);
|
||||
@@ -56,8 +54,7 @@ pub fn backup_registry(custom_dir: Option<String>) -> Result<String, String> {
|
||||
content.push_str(&format!("{}\n", path));
|
||||
}
|
||||
|
||||
std::fs::write(&filepath, &content)
|
||||
.map_err(|e| format!("无法写入备份文件: {}", e))?;
|
||||
std::fs::write(&filepath, &content).map_err(|e| format!("无法写入备份文件: {}", e))?;
|
||||
|
||||
let result = filepath.to_string_lossy().to_string();
|
||||
log::info!("备份已保存到: {}", result);
|
||||
|
||||
+15
-10
@@ -1,7 +1,9 @@
|
||||
use crate::fs::atomic_write;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn disabled_file_path() -> PathBuf {
|
||||
dirs::home_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
@@ -9,6 +11,11 @@ fn disabled_file_path() -> PathBuf {
|
||||
.join("disabled.json")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn disabled_file_path() -> PathBuf {
|
||||
std::env::temp_dir().join("patheditor_test_disabled.json")
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize, Default)]
|
||||
struct DisabledState {
|
||||
#[serde(default)]
|
||||
@@ -23,15 +30,13 @@ pub fn save_disabled_state(system: Vec<String>, user: Vec<String>) -> Result<(),
|
||||
let path = disabled_file_path();
|
||||
|
||||
if let Some(parent) = path.parent() {
|
||||
fs::create_dir_all(parent)
|
||||
.map_err(|e| format!("无法创建配置目录: {}", e))?;
|
||||
fs::create_dir_all(parent).map_err(|e| format!("无法创建配置目录: {}", e))?;
|
||||
}
|
||||
|
||||
let json = serde_json::to_string_pretty(&state)
|
||||
.map_err(|e| format!("JSON 序列化失败: {}", e))?;
|
||||
let json =
|
||||
serde_json::to_string_pretty(&state).map_err(|e| format!("JSON 序列化失败: {}", e))?;
|
||||
|
||||
fs::write(&path, &json)
|
||||
.map_err(|e| format!("无法写入 disabled.json: {}", e))?;
|
||||
atomic_write(&path, &json).map_err(|e| format!("无法写入 disabled.json: {}", e))?;
|
||||
|
||||
log::info!("已保存禁用状态到: {}", path.display());
|
||||
Ok(())
|
||||
@@ -45,15 +50,15 @@ pub fn load_disabled_state() -> Result<(Vec<String>, Vec<String>), String> {
|
||||
return Ok((vec![], vec![]));
|
||||
}
|
||||
|
||||
let content = fs::read_to_string(&path)
|
||||
.map_err(|e| format!("无法读取 disabled.json: {}", e))?;
|
||||
let content =
|
||||
fs::read_to_string(&path).map_err(|e| format!("无法读取 disabled.json: {}", e))?;
|
||||
|
||||
if content.trim().is_empty() {
|
||||
return Ok((vec![], vec![]));
|
||||
}
|
||||
|
||||
let state: DisabledState = serde_json::from_str(&content)
|
||||
.map_err(|e| format!("JSON 解析失败: {}", e))?;
|
||||
let state: DisabledState =
|
||||
serde_json::from_str(&content).map_err(|e| format!("JSON 解析失败: {}", e))?;
|
||||
|
||||
Ok((state.system, state.user))
|
||||
}
|
||||
|
||||
+306
-43
@@ -1,13 +1,50 @@
|
||||
// 注意:TS 端 src/core/import-export.ts 有对应的导入导出实现,
|
||||
// 前端使用 TS 版(需 ImportDialog 交互),CLI 使用 Rust 版,修改时需同步两端。
|
||||
|
||||
use crate::profiles::ProfilePathEntry;
|
||||
|
||||
/// 过滤导入条目:去除空白、排除 null 字节和分号(PATH 分隔符冲突)
|
||||
fn sanitize_entries(entries: Vec<ProfilePathEntry>) -> Vec<ProfilePathEntry> {
|
||||
entries
|
||||
.into_iter()
|
||||
.map(|e| ProfilePathEntry {
|
||||
path: e.path.trim().to_string(),
|
||||
enabled: e.enabled,
|
||||
})
|
||||
.filter(|e| !e.path.is_empty() && !e.path.contains('\0') && !e.path.contains(';'))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// 原子写入:先写临时文件,再 rename 覆盖
|
||||
pub fn atomic_write(path: &std::path::Path, content: &str) -> std::io::Result<()> {
|
||||
let tmp = path.with_extension("tmp");
|
||||
std::fs::write(&tmp, content)?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 读取文本文件内容(供前端原生对话框选择文件后使用)
|
||||
/// 仅允许 .json / .csv / .txt 扩展名,防止任意文件读取
|
||||
pub fn read_text_file(path: &str) -> Result<String, String> {
|
||||
let ext = std::path::Path::new(path)
|
||||
.extension()
|
||||
.and_then(|e| e.to_str())
|
||||
.map(|e| e.to_ascii_lowercase())
|
||||
.unwrap_or_default();
|
||||
if !matches!(ext.as_str(), "json" | "csv" | "txt") {
|
||||
return Err(format!(
|
||||
"不支持的文件类型: .{}(仅允许 .json/.csv/.txt)",
|
||||
ext
|
||||
));
|
||||
}
|
||||
std::fs::read_to_string(path).map_err(|e| format!("无法读取文件: {}", e))
|
||||
}
|
||||
|
||||
/// 导入路径文件(JSON / CSV / TXT),返回 (系统路径, 用户路径)
|
||||
pub fn import_paths(path: &str, content: &str) -> Result<(Vec<String>, Vec<String>), String> {
|
||||
/// 导入路径文件(JSON / CSV / TXT),返回 (系统条目, 用户条目)
|
||||
pub fn import_paths(
|
||||
path: &str,
|
||||
content: &str,
|
||||
) -> Result<(Vec<ProfilePathEntry>, Vec<ProfilePathEntry>), String> {
|
||||
let ext = std::path::Path::new(path)
|
||||
.extension()
|
||||
.map(|e| e.to_ascii_lowercase())
|
||||
@@ -22,26 +59,85 @@ pub fn import_paths(path: &str, content: &str) -> Result<(Vec<String>, Vec<Strin
|
||||
}
|
||||
}
|
||||
|
||||
fn import_json(content: &str) -> Result<(Vec<String>, Vec<String>), String> {
|
||||
fn import_json(content: &str) -> Result<(Vec<ProfilePathEntry>, Vec<ProfilePathEntry>), String> {
|
||||
#[derive(serde::Deserialize)]
|
||||
struct ImportItem {
|
||||
path: String,
|
||||
#[serde(default = "default_true")]
|
||||
enabled: bool,
|
||||
}
|
||||
fn default_true() -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
#[derive(serde::Deserialize)]
|
||||
struct ImportData {
|
||||
#[serde(default)]
|
||||
system: Vec<String>,
|
||||
system: Vec<ImportItem>,
|
||||
#[serde(default)]
|
||||
user: Vec<String>,
|
||||
user: Vec<ImportItem>,
|
||||
}
|
||||
let data: ImportData =
|
||||
serde_json::from_str(content).map_err(|e| format!("JSON 解析失败: {}", e))?;
|
||||
Ok((data.system, data.user))
|
||||
let into_entries = |items: Vec<ImportItem>| -> Vec<ProfilePathEntry> {
|
||||
items
|
||||
.into_iter()
|
||||
.map(|i| ProfilePathEntry {
|
||||
path: i.path,
|
||||
enabled: i.enabled,
|
||||
})
|
||||
.collect()
|
||||
};
|
||||
Ok((
|
||||
sanitize_entries(into_entries(data.system)),
|
||||
sanitize_entries(into_entries(data.user)),
|
||||
))
|
||||
}
|
||||
|
||||
fn import_csv(content: &str) -> Result<(Vec<String>, Vec<String>), String> {
|
||||
/// 解析 CSV 行,支持引号包裹的字段(RFC 4180 子集)
|
||||
/// 与 TS 端 src/core/import-export.ts parseCsvLine 逻辑一致
|
||||
fn parse_csv_line(line: &str) -> Vec<String> {
|
||||
let mut fields = Vec::new();
|
||||
let mut current = String::new();
|
||||
let mut in_quotes = false;
|
||||
let mut chars = line.chars().peekable();
|
||||
|
||||
while let Some(ch) = chars.next() {
|
||||
if in_quotes {
|
||||
if ch == '"' {
|
||||
if chars.peek() == Some(&'"') {
|
||||
current.push('"');
|
||||
chars.next(); // 跳过转义引号
|
||||
} else {
|
||||
in_quotes = false;
|
||||
}
|
||||
} else {
|
||||
current.push(ch);
|
||||
}
|
||||
} else if ch == '"' {
|
||||
in_quotes = true;
|
||||
} else if ch == ',' {
|
||||
fields.push(current);
|
||||
current = String::new();
|
||||
} else {
|
||||
current.push(ch);
|
||||
}
|
||||
}
|
||||
fields.push(current);
|
||||
fields
|
||||
}
|
||||
|
||||
fn import_csv(
|
||||
content: &str,
|
||||
) -> Result<(Vec<ProfilePathEntry>, Vec<ProfilePathEntry>), String> {
|
||||
let mut sys = Vec::new();
|
||||
let mut usr = Vec::new();
|
||||
let mut first = true;
|
||||
for line in content.lines() {
|
||||
let mut trimmed = line.trim();
|
||||
if trimmed.is_empty() { continue; }
|
||||
if trimmed.is_empty() {
|
||||
continue;
|
||||
}
|
||||
|
||||
// 处理 UTF-8 BOM(仅首行)
|
||||
if first {
|
||||
@@ -49,64 +145,88 @@ fn import_csv(content: &str) -> Result<(Vec<String>, Vec<String>), String> {
|
||||
if let Some(stripped) = trimmed.strip_prefix('\u{FEFF}') {
|
||||
trimmed = stripped;
|
||||
}
|
||||
// 跳过 header 行 "type,path"
|
||||
let fields: Vec<&str> = trimmed.split(',').collect();
|
||||
if fields.len() >= 2 {
|
||||
let c0 = fields[0].trim().to_lowercase();
|
||||
let c1 = fields[1].trim().to_lowercase();
|
||||
if c0 == "type" && c1 == "path" { continue; }
|
||||
// 跳过 header 行,兼容 type,path 和 type,path,enabled 两种格式
|
||||
let header_fields = parse_csv_line(trimmed);
|
||||
if header_fields.len() >= 2 {
|
||||
let c0 = header_fields[0].trim().to_lowercase();
|
||||
let c1 = header_fields[1].trim().to_lowercase();
|
||||
if c0 == "type" && c1 == "path" {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let fields: Vec<&str> = trimmed.split(',').collect();
|
||||
let fields = parse_csv_line(trimmed);
|
||||
if fields.len() >= 2 {
|
||||
let path = fields[1].trim().to_string();
|
||||
let enabled = if fields.len() >= 3 {
|
||||
fields[2].trim().to_lowercase() != "false"
|
||||
} else {
|
||||
true
|
||||
};
|
||||
let entry = ProfilePathEntry { path, enabled };
|
||||
match fields[0].trim().to_lowercase().as_str() {
|
||||
"system" | "sys" => sys.push(fields[1].trim().to_string()),
|
||||
"user" | "usr" => usr.push(fields[1].trim().to_string()),
|
||||
_ => { log::warn!("import_csv: 无法识别的类型字段,已跳过: {trimmed}"); }
|
||||
"system" | "sys" => sys.push(entry),
|
||||
"user" | "usr" => usr.push(entry),
|
||||
_ => {
|
||||
log::warn!("import_csv: 无法识别的类型字段,已跳过: {trimmed}");
|
||||
}
|
||||
}
|
||||
} else {
|
||||
log::warn!("import_csv: 格式不正确(缺逗号),已跳过: {trimmed}");
|
||||
}
|
||||
}
|
||||
let sys = sanitize_entries(sys);
|
||||
let usr = sanitize_entries(usr);
|
||||
if sys.is_empty() && usr.is_empty() {
|
||||
return Err("CSV 文件中未找到有效路径".into());
|
||||
}
|
||||
Ok((sys, usr))
|
||||
}
|
||||
|
||||
fn import_txt(content: &str) -> Result<(Vec<String>, Vec<String>), String> {
|
||||
let paths: Vec<String> = content
|
||||
fn import_txt(content: &str) -> Result<(Vec<ProfilePathEntry>, Vec<ProfilePathEntry>), String> {
|
||||
let entries: Vec<ProfilePathEntry> = content
|
||||
.lines()
|
||||
.map(|l| l.trim().to_string())
|
||||
.filter(|l| !l.is_empty() && !l.starts_with('#'))
|
||||
.map(|path| ProfilePathEntry {
|
||||
path,
|
||||
enabled: true,
|
||||
})
|
||||
.collect();
|
||||
if paths.is_empty() {
|
||||
let entries = sanitize_entries(entries);
|
||||
if entries.is_empty() {
|
||||
return Err("TXT 文件中未找到路径".into());
|
||||
}
|
||||
// TXT 格式全部导入为用户路径
|
||||
Ok((vec![], paths))
|
||||
Ok((vec![], entries))
|
||||
}
|
||||
|
||||
/// 导出 PATH 为指定格式字符串
|
||||
pub fn export_paths(sys: &[String], usr: &[String], format: &str) -> Result<String, String> {
|
||||
match format {
|
||||
"json" => {
|
||||
let to_entries = |paths: &[String]| -> Vec<serde_json::Value> {
|
||||
paths
|
||||
.iter()
|
||||
.map(|p| serde_json::json!({"path": p, "enabled": true}))
|
||||
.collect()
|
||||
};
|
||||
let data = serde_json::json!({
|
||||
"version": env!("CARGO_PKG_VERSION"),
|
||||
"timestamp": chrono::Local::now().format("%Y-%m-%dT%H:%M:%S").to_string(),
|
||||
"system": sys,
|
||||
"user": usr,
|
||||
"system": to_entries(sys),
|
||||
"user": to_entries(usr),
|
||||
});
|
||||
Ok(serde_json::to_string_pretty(&data).unwrap_or_default())
|
||||
Ok(serde_json::to_string_pretty(&data).expect("JSON 序列化 Value 不应失败"))
|
||||
}
|
||||
"csv" => {
|
||||
let mut out = String::from("type,path\n");
|
||||
let mut out = String::from("type,path,enabled\n");
|
||||
for p in sys {
|
||||
out.push_str(&format!("system,{}\n", p));
|
||||
out.push_str(&format!("system,{},true\n", p));
|
||||
}
|
||||
for p in usr {
|
||||
out.push_str(&format!("user,{}\n", p));
|
||||
out.push_str(&format!("user,{},true\n", p));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
@@ -134,12 +254,30 @@ pub fn export_paths(sys: &[String], usr: &[String], format: &str) -> Result<Stri
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn entry(path: &str) -> ProfilePathEntry {
|
||||
ProfilePathEntry {
|
||||
path: path.into(),
|
||||
enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
fn entry_disabled(path: &str) -> ProfilePathEntry {
|
||||
ProfilePathEntry {
|
||||
path: path.into(),
|
||||
enabled: false,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_json_valid() {
|
||||
let json = r#"{"system": ["C:\\sys1", "C:\\sys2"], "user": ["D:\\usr1"]}"#;
|
||||
let json = r#"{"system": [{"path": "C:\\sys1"}, {"path": "C:\\sys2"}], "user": [{"path": "D:\\usr1"}]}"#;
|
||||
let (sys, usr) = import_json(json).unwrap();
|
||||
assert_eq!(sys, vec!["C:\\sys1", "C:\\sys2"]);
|
||||
assert_eq!(usr, vec!["D:\\usr1"]);
|
||||
assert_eq!(sys.len(), 2);
|
||||
assert_eq!(sys[0].path, "C:\\sys1");
|
||||
assert!(sys[0].enabled);
|
||||
assert_eq!(sys[1].path, "C:\\sys2");
|
||||
assert_eq!(usr.len(), 1);
|
||||
assert_eq!(usr[0].path, "D:\\usr1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -148,6 +286,15 @@ mod tests {
|
||||
assert!(sys.is_empty() && usr.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_json_disabled_entry() {
|
||||
let json = r#"{"system": [{"path": "C:\\on", "enabled": true}, {"path": "C:\\off", "enabled": false}]}"#;
|
||||
let (sys, _) = import_json(json).unwrap();
|
||||
assert_eq!(sys.len(), 2);
|
||||
assert!(sys[0].enabled);
|
||||
assert!(!sys[1].enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_json_missing_fields() {
|
||||
let (sys, usr) = import_json(r#"{}"#).unwrap();
|
||||
@@ -157,16 +304,20 @@ mod tests {
|
||||
#[test]
|
||||
fn import_csv_valid() {
|
||||
let csv = "type,path\nsystem,C:\\sys1\nuser,D:\\usr1\n";
|
||||
let (sys, _usr) = import_csv(csv).unwrap();
|
||||
assert_eq!(sys, vec!["C:\\sys1"]);
|
||||
assert_eq!(_usr, vec!["D:\\usr1"]);
|
||||
let (sys, usr) = import_csv(csv).unwrap();
|
||||
assert_eq!(sys.len(), 1);
|
||||
assert_eq!(sys[0].path, "C:\\sys1");
|
||||
assert!(sys[0].enabled);
|
||||
assert_eq!(usr.len(), 1);
|
||||
assert_eq!(usr[0].path, "D:\\usr1");
|
||||
assert!(usr[0].enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_csv_with_bom() {
|
||||
let csv = "\u{FEFF}type,path\nsystem,C:\\sys1\n";
|
||||
let (sys, _) = import_csv(csv).unwrap();
|
||||
assert_eq!(sys, vec!["C:\\sys1"]);
|
||||
assert_eq!(sys[0].path, "C:\\sys1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -178,8 +329,27 @@ mod tests {
|
||||
fn import_csv_alternate_type_names() {
|
||||
let csv = "type,path\nsys,D:\\a\nusr,D:\\b\n";
|
||||
let (sys, usr) = import_csv(csv).unwrap();
|
||||
assert_eq!(sys, vec!["D:\\a"]);
|
||||
assert_eq!(usr, vec!["D:\\b"]);
|
||||
assert_eq!(sys[0].path, "D:\\a");
|
||||
assert_eq!(usr[0].path, "D:\\b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_csv_reads_enabled_column() {
|
||||
let csv = "type,path,enabled\nsystem,C:\\ok,true\nsystem,C:\\disabled,false\n";
|
||||
let (sys, _) = import_csv(csv).unwrap();
|
||||
assert_eq!(sys.len(), 2);
|
||||
assert_eq!(sys[0].path, "C:\\ok");
|
||||
assert!(sys[0].enabled);
|
||||
assert_eq!(sys[1].path, "C:\\disabled");
|
||||
assert!(!sys[1].enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_csv_enabled_defaults_true() {
|
||||
// 2 列格式(无 enabled 列)默认为 true
|
||||
let csv = "type,path\nsystem,C:\\x\n";
|
||||
let (sys, _) = import_csv(csv).unwrap();
|
||||
assert!(sys[0].enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -188,16 +358,18 @@ mod tests {
|
||||
let usr: Vec<String> = vec![];
|
||||
let exported = export_paths(&sys, &usr, "json").unwrap();
|
||||
let parsed: serde_json::Value = serde_json::from_str(&exported).unwrap();
|
||||
assert_eq!(parsed["system"][0], "C:\\a");
|
||||
assert_eq!(parsed["system"][0]["path"], "C:\\a");
|
||||
assert_eq!(parsed["system"][0]["enabled"], true);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn export_csv_roundtrip() {
|
||||
fn export_csv_includes_enabled_column() {
|
||||
let sys = vec!["C:\\a".into()];
|
||||
let usr = vec!["D:\\b".into()];
|
||||
let exported = export_paths(&sys, &usr, "csv").unwrap();
|
||||
assert!(exported.contains("system,C:\\a"));
|
||||
assert!(exported.contains("user,D:\\b"));
|
||||
assert!(exported.starts_with("type,path,enabled"));
|
||||
assert!(exported.contains("system,C:\\a,true"));
|
||||
assert!(exported.contains("user,D:\\b,true"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -216,13 +388,104 @@ mod tests {
|
||||
#[test]
|
||||
fn import_paths_detects_format() {
|
||||
let (sys, _) = import_paths("test.csv", "type,path\nsystem,C:\\x\n").unwrap();
|
||||
assert_eq!(sys, vec!["C:\\x"]);
|
||||
assert_eq!(sys[0].path, "C:\\x");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_paths_txt_to_user() {
|
||||
let (sys, usr) = import_paths("test.txt", "C:\\x\nD:\\y\n").unwrap();
|
||||
assert!(sys.is_empty());
|
||||
assert_eq!(usr, vec!["C:\\x", "D:\\y"]);
|
||||
assert_eq!(usr.len(), 2);
|
||||
assert_eq!(usr[0].path, "C:\\x");
|
||||
assert_eq!(usr[1].path, "D:\\y");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_text_file_rejects_non_whitelisted_ext() {
|
||||
let result = read_text_file("C:\\Windows\\System32\\evil.dll");
|
||||
assert!(result.is_err());
|
||||
assert!(result.unwrap_err().contains("不支持的文件类型"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_text_file_rejects_no_ext() {
|
||||
let result = read_text_file("/etc/passwd");
|
||||
assert!(result.is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_entries_filters_null_byte_paths() {
|
||||
let entries = vec![entry("C:\\safe"), entry("C:\\bad\0path")];
|
||||
let result = sanitize_entries(entries);
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(result[0].path, "C:\\safe");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_csv_filters_semicolon_paths() {
|
||||
let csv = "type,path\nsystem,C:\\good\nsystem,C:\\bad;path\n";
|
||||
let (sys, _) = import_csv(csv).unwrap();
|
||||
assert_eq!(sys.len(), 1);
|
||||
assert_eq!(sys[0].path, "C:\\good");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_txt_trims_and_filters() {
|
||||
let txt = " C:\\trimmed \n\nC:\\bad\0path\n# comment\n";
|
||||
let (_, usr) = import_txt(txt).unwrap();
|
||||
assert_eq!(usr.len(), 1);
|
||||
assert_eq!(usr[0].path, "C:\\trimmed");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_entries_removes_empty_after_trim() {
|
||||
let result = sanitize_entries(vec![entry(" "), entry("C:\\ok")]);
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(result[0].path, "C:\\ok");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn sanitize_entries_preserves_enabled_flag() {
|
||||
let result = sanitize_entries(vec![entry_disabled("C:\\keep")]);
|
||||
assert_eq!(result.len(), 1);
|
||||
assert_eq!(result[0].path, "C:\\keep");
|
||||
assert!(!result[0].enabled);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_csv_line_basic() {
|
||||
assert_eq!(parse_csv_line("a,b,c"), vec!["a", "b", "c"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_csv_line_quoted_comma() {
|
||||
assert_eq!(
|
||||
parse_csv_line(r#"system,"C:\Program Files, Inc\bin""#),
|
||||
vec!["system", r#"C:\Program Files, Inc\bin"#]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_csv_line_escaped_quotes() {
|
||||
assert_eq!(
|
||||
parse_csv_line(r#"system,"He said ""hello""""#),
|
||||
vec!["system", r#"He said "hello""#]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn import_csv_quoted_comma_path() {
|
||||
let csv = "type,path\nsystem,\"C:\\Program Files, Inc\\bin\"\n";
|
||||
let (sys, _) = import_csv(csv).unwrap();
|
||||
assert_eq!(sys[0].path, "C:\\Program Files, Inc\\bin");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn csv_roundtrip_preserves_enabled() {
|
||||
let csv = "type,path,enabled\nsystem,C:\\on,true\nsystem,C:\\off,false\n";
|
||||
let (sys, _) = import_csv(csv).unwrap();
|
||||
assert_eq!(sys.len(), 2);
|
||||
assert!(sys[0].enabled);
|
||||
assert!(!sys[1].enabled);
|
||||
}
|
||||
}
|
||||
|
||||
+61
-12
@@ -1,7 +1,9 @@
|
||||
use crate::fs::atomic_write;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
#[cfg(not(test))]
|
||||
fn profiles_dir() -> PathBuf {
|
||||
dirs::home_dir()
|
||||
.unwrap_or_else(|| PathBuf::from("."))
|
||||
@@ -9,8 +11,21 @@ fn profiles_dir() -> PathBuf {
|
||||
.join("profiles")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
fn profiles_dir() -> PathBuf {
|
||||
std::env::temp_dir().join("patheditor_test_profiles")
|
||||
}
|
||||
|
||||
fn validate_profile_name(name: &str) -> Result<(), String> {
|
||||
if name.is_empty() { return Err("配置名称不能为空".into()); }
|
||||
if name.is_empty() {
|
||||
return Err("配置名称不能为空".into());
|
||||
}
|
||||
if name.len() > 255 {
|
||||
return Err("配置名称过长(最大 255 字符)".into());
|
||||
}
|
||||
if name.contains('\0') || name.chars().any(|c| c.is_control()) {
|
||||
return Err("配置名称包含非法字符".into());
|
||||
}
|
||||
if name.contains('/') || name.contains('\\') || name.contains("..") {
|
||||
return Err("配置名称包含非法字符".into());
|
||||
}
|
||||
@@ -115,7 +130,7 @@ pub fn save_profile(
|
||||
|
||||
let json =
|
||||
serde_json::to_string_pretty(&data).map_err(|e| format!("JSON 序列化失败: {}", e))?;
|
||||
fs::write(&path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
|
||||
atomic_write(&path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
|
||||
|
||||
log::info!("已保存配置: {}", path.display());
|
||||
Ok(())
|
||||
@@ -128,10 +143,8 @@ pub fn load_profile(name: &str) -> Result<ProfileData, String> {
|
||||
if !path.exists() {
|
||||
return Err(format!("配置文件不存在: {}", name));
|
||||
}
|
||||
let content = fs::read_to_string(&path)
|
||||
.map_err(|e| format!("无法读取配置文件: {}", e))?;
|
||||
serde_json::from_str(&content)
|
||||
.map_err(|e| format!("JSON 解析失败: {}", e))
|
||||
let content = fs::read_to_string(&path).map_err(|e| format!("无法读取配置文件: {}", e))?;
|
||||
serde_json::from_str(&content).map_err(|e| format!("JSON 解析失败: {}", e))
|
||||
}
|
||||
|
||||
/// 删除配置文件
|
||||
@@ -148,20 +161,25 @@ pub fn rename_profile(old_name: &str, new_name: &str) -> Result<(), String> {
|
||||
validate_profile_name(old_name)?;
|
||||
validate_profile_name(new_name)?;
|
||||
let old_path = profile_path(old_name);
|
||||
let new_path = profile_path(new_name);
|
||||
if !old_path.exists() {
|
||||
return Err(format!("配置文件不存在: {}", old_name));
|
||||
}
|
||||
if old_path != new_path && new_path.exists() {
|
||||
return Err(format!("目标配置名已存在: {}", new_name));
|
||||
}
|
||||
|
||||
let mut data: ProfileData =
|
||||
serde_json::from_str(&fs::read_to_string(&old_path).map_err(|e| format!("无法读取配置文件: {}", e))?).map_err(|e| format!("JSON 解析失败: {}", e))?;
|
||||
let mut data: ProfileData = serde_json::from_str(
|
||||
&fs::read_to_string(&old_path).map_err(|e| format!("无法读取配置文件: {}", e))?,
|
||||
)
|
||||
.map_err(|e| format!("JSON 解析失败: {}", e))?;
|
||||
|
||||
data.name = new_name.to_string();
|
||||
data.modified = chrono::Local::now().format("%Y-%m-%dT%H:%M:%S").to_string();
|
||||
|
||||
let new_path = profile_path(new_name);
|
||||
let json =
|
||||
serde_json::to_string_pretty(&data).map_err(|e| format!("JSON 序列化失败: {}", e))?;
|
||||
fs::write(&new_path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
|
||||
atomic_write(&new_path, &json).map_err(|e| format!("无法写入配置文件: {}", e))?;
|
||||
|
||||
if old_path != new_path {
|
||||
fs::remove_file(&old_path).map_err(|e| format!("无法删除旧配置文件: {}", e))?;
|
||||
@@ -176,7 +194,10 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn test_entry(path: &str) -> ProfilePathEntry {
|
||||
ProfilePathEntry { path: path.into(), enabled: true }
|
||||
ProfilePathEntry {
|
||||
path: path.into(),
|
||||
enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -196,12 +217,40 @@ mod tests {
|
||||
assert!(validate_profile_name("foo<bar").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_name_rejects_null_bytes() {
|
||||
assert!(validate_profile_name("foo\0bar").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_name_rejects_control_chars() {
|
||||
assert!(validate_profile_name("foo\tbar").is_err());
|
||||
assert!(validate_profile_name("foo\nbar").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_name_rejects_too_long() {
|
||||
let long_name = "a".repeat(256);
|
||||
assert!(validate_profile_name(&long_name).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_name_accepts_255_chars() {
|
||||
let name = "a".repeat(255);
|
||||
assert!(validate_profile_name(&name).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn profile_crud() {
|
||||
// save -> load -> delete
|
||||
let name = "__test_profile_crud";
|
||||
let _ = delete_profile(name);
|
||||
save_profile(name, vec![test_entry("C:\\sys")], vec![test_entry("D:\\usr")]).unwrap();
|
||||
save_profile(
|
||||
name,
|
||||
vec![test_entry("C:\\sys")],
|
||||
vec![test_entry("D:\\usr")],
|
||||
)
|
||||
.unwrap();
|
||||
let loaded = load_profile(name).unwrap();
|
||||
assert_eq!(loaded.sys[0].path, "C:\\sys");
|
||||
delete_profile(name).unwrap();
|
||||
|
||||
+59
-21
@@ -1,11 +1,16 @@
|
||||
use winreg::enums::*;
|
||||
use winreg::RegKey;
|
||||
|
||||
pub(crate) const SYS_REG_PATH: &str = "SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
|
||||
pub(crate) const SYS_REG_PATH: &str =
|
||||
"SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment";
|
||||
pub(crate) const USER_REG_PATH: &str = "Environment";
|
||||
const PATH_VALUE: &str = "Path";
|
||||
|
||||
pub(crate) fn load_paths(root: winreg::HKEY, sub_path: &str, label: &str) -> Result<Vec<String>, String> {
|
||||
pub(crate) fn load_paths(
|
||||
root: winreg::HKEY,
|
||||
sub_path: &str,
|
||||
label: &str,
|
||||
) -> Result<Vec<String>, String> {
|
||||
let key = RegKey::predef(root);
|
||||
let env_key = key
|
||||
.open_subkey_with_flags(sub_path, KEY_READ)
|
||||
@@ -18,17 +23,13 @@ pub(crate) fn load_paths(root: winreg::HKEY, sub_path: &str, label: &str) -> Res
|
||||
Ok(split_path(&value))
|
||||
}
|
||||
|
||||
fn save_paths(root: winreg::HKEY, sub_path: &str, label: &str, paths: &[String]) -> Result<(), String> {
|
||||
let value = join_path(paths);
|
||||
|
||||
// Windows 注册表 REG_EXPAND_SZ 上限 32767 字符
|
||||
const MAX_PATH_LEN: usize = 32767;
|
||||
if value.len() > MAX_PATH_LEN {
|
||||
return Err(format!(
|
||||
"{} PATH 总长度 {} 超出 Windows 限制 {} 字符,请移除部分路径后再保存",
|
||||
label, value.len(), MAX_PATH_LEN
|
||||
));
|
||||
}
|
||||
fn save_paths(
|
||||
root: winreg::HKEY,
|
||||
sub_path: &str,
|
||||
label: &str,
|
||||
paths: &[String],
|
||||
) -> Result<(), String> {
|
||||
let value = validate_and_join_paths(paths, label)?;
|
||||
|
||||
let key = RegKey::predef(root);
|
||||
let env_key = key
|
||||
@@ -43,7 +44,6 @@ fn save_paths(root: winreg::HKEY, sub_path: &str, label: &str, paths: &[String])
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
/// 从 HKLM 注册表读取系统 PATH
|
||||
///
|
||||
/// # Returns
|
||||
@@ -53,7 +53,6 @@ pub fn load_system_paths() -> Result<Vec<String>, String> {
|
||||
load_paths(HKEY_LOCAL_MACHINE, SYS_REG_PATH, "系统")
|
||||
}
|
||||
|
||||
|
||||
/// 从 HKCU 注册表读取用户 PATH
|
||||
///
|
||||
/// # Returns
|
||||
@@ -63,7 +62,6 @@ pub fn load_user_paths() -> Result<Vec<String>, String> {
|
||||
load_paths(HKEY_CURRENT_USER, USER_REG_PATH, "用户")
|
||||
}
|
||||
|
||||
|
||||
/// 保存系统 PATH 到注册表,含 32767 字符上限检查
|
||||
///
|
||||
/// # Returns
|
||||
@@ -73,7 +71,6 @@ pub fn save_system_paths(paths: Vec<String>) -> Result<(), String> {
|
||||
save_paths(HKEY_LOCAL_MACHINE, SYS_REG_PATH, "系统", &paths)
|
||||
}
|
||||
|
||||
|
||||
/// 保存用户 PATH 到注册表
|
||||
///
|
||||
/// # Returns
|
||||
@@ -101,6 +98,25 @@ fn join_path(paths: &[String]) -> String {
|
||||
.join(";")
|
||||
}
|
||||
|
||||
/// 验证路径列表并拼接为分号分隔字符串
|
||||
/// - 检查 null 字节
|
||||
/// - 检查 UTF-16 总长度不超过 32767
|
||||
fn validate_and_join_paths(paths: &[String], label: &str) -> Result<String, String> {
|
||||
if let Some(bad) = paths.iter().find(|p| p.contains('\0')) {
|
||||
return Err(format!("{} PATH 包含非法字符(null 字节): {}", label, bad));
|
||||
}
|
||||
let value = join_path(paths);
|
||||
const MAX_PATH_LEN: usize = 32767;
|
||||
let utf16_len = value.encode_utf16().count();
|
||||
if utf16_len > MAX_PATH_LEN {
|
||||
return Err(format!(
|
||||
"{} PATH 总长度 {} 超出 Windows 限制 {} 字符,请移除部分路径后再保存",
|
||||
label, utf16_len, MAX_PATH_LEN
|
||||
));
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
/// 清理路径列表:移除不存在的目录 + 重复路径(保留首次出现)
|
||||
/// 返回 (保留的路径, 被移除的路径)
|
||||
pub fn clean_paths(paths: Vec<String>) -> (Vec<String>, Vec<String>) {
|
||||
@@ -148,10 +164,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn split_trims_and_filters_empty() {
|
||||
assert_eq!(
|
||||
split_path(" C:\\ ; ; D:\\ "),
|
||||
vec!["C:\\", "D:\\"]
|
||||
);
|
||||
assert_eq!(split_path(" C:\\ ; ; D:\\ "), vec!["C:\\", "D:\\"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -167,4 +180,29 @@ mod tests {
|
||||
let paths = vec![" C:\\Windows ".to_string(), " D:\\ ".to_string()];
|
||||
assert_eq!(join_path(&paths), "C:\\Windows;D:\\");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_null_bytes() {
|
||||
let paths = vec!["C:\\safe".into(), "C:\0invalid".into()];
|
||||
let result = validate_and_join_paths(&paths, "测试");
|
||||
assert!(result.is_err());
|
||||
assert!(result.unwrap_err().contains("null 字节"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_accepts_cjk_paths() {
|
||||
let paths = vec!["C:\\用户\\工具".into()];
|
||||
let result = validate_and_join_paths(&paths, "测试");
|
||||
assert!(result.is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn validate_rejects_oversized_paths() {
|
||||
// 构造总长超过 32767 UTF-16 字符的路径
|
||||
let long_path = "C:\\".to_string() + &"a".repeat(32767);
|
||||
let paths = vec![long_path];
|
||||
let result = validate_and_join_paths(&paths, "测试");
|
||||
assert!(result.is_err());
|
||||
assert!(result.unwrap_err().contains("超出 Windows 限制"));
|
||||
}
|
||||
}
|
||||
|
||||
+58
-16
@@ -50,13 +50,18 @@ fn list_exes(dir: &str) -> Vec<String> {
|
||||
/// 并行遍历每个 PATH 目录,查找 .exe/.bat/.cmd/.com/.ps1 文件,
|
||||
/// 标记出现在多个目录中的同名文件(后面的目录会被前面的「遮蔽」)
|
||||
pub fn scan_conflicts(paths: Vec<String>) -> Result<Vec<ConflictEntry>, String> {
|
||||
// 并行扫描各目录
|
||||
let results: Vec<(usize, String, Vec<String>)> = std::thread::scope(|s| {
|
||||
let handles: Vec<_> = paths.iter().enumerate().map(|(priority, dir)| {
|
||||
s.spawn(move || (priority, dir.clone(), list_exes(dir)))
|
||||
}).collect();
|
||||
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
||||
});
|
||||
let handles: Vec<_> = paths
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(priority, dir)| s.spawn(move || (priority, dir.clone(), list_exes(dir))))
|
||||
.collect();
|
||||
handles
|
||||
.into_iter()
|
||||
.map(|h| h.join().map_err(|e| format!("扫描线程失败: {:?}", e)))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
})
|
||||
.map_err(|e| format!("线程扫描失败: {}", e))?;
|
||||
|
||||
// 合并: exe_name (小写) → [(priority, dir)]
|
||||
let mut map: HashMap<String, Vec<(usize, String)>> = HashMap::new();
|
||||
@@ -92,7 +97,9 @@ 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| {
|
||||
let handles: Vec<_> = paths
|
||||
.iter()
|
||||
.map(|dir| {
|
||||
s.spawn(move || {
|
||||
let p = Path::new(dir);
|
||||
if !p.is_dir() {
|
||||
@@ -101,22 +108,35 @@ pub fn scan_tools(paths: Vec<String>, query: String) -> Result<Vec<ToolGroup>, S
|
||||
let exes = list_exes(dir);
|
||||
(dir.clone(), Some(exes))
|
||||
})
|
||||
}).collect();
|
||||
handles.into_iter().map(|h| h.join().unwrap()).collect()
|
||||
});
|
||||
})
|
||||
.collect();
|
||||
handles
|
||||
.into_iter()
|
||||
.map(|h| h.join().map_err(|e| format!("扫描线程失败: {:?}", e)))
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
})
|
||||
.map_err(|e| format!("线程扫描失败: {}", e))?;
|
||||
|
||||
let mut groups: Vec<ToolGroup> = Vec::new();
|
||||
for (dir, opt_exes) in dir_results {
|
||||
match opt_exes {
|
||||
None => {
|
||||
groups.push(ToolGroup { dir, exists: false, exes: vec![] });
|
||||
groups.push(ToolGroup {
|
||||
dir,
|
||||
exists: false,
|
||||
exes: vec![],
|
||||
});
|
||||
}
|
||||
Some(mut exes) => {
|
||||
if !query_lower.is_empty() {
|
||||
exes.retain(|name| name.to_lowercase().contains(&query_lower));
|
||||
}
|
||||
exes.sort();
|
||||
groups.push(ToolGroup { dir, exists: true, exes });
|
||||
groups.push(ToolGroup {
|
||||
dir,
|
||||
exists: true,
|
||||
exes,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -129,20 +149,39 @@ mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
fn make_temp_dir_with_exes(prefix: &str, exe_names: &[&str]) -> std::path::PathBuf {
|
||||
struct TempDirGuard(std::path::PathBuf);
|
||||
|
||||
impl Drop for TempDirGuard {
|
||||
fn drop(&mut self) {
|
||||
let _ = std::fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
impl std::ops::Deref for TempDirGuard {
|
||||
type Target = std::path::PathBuf;
|
||||
fn deref(&self) -> &Self::Target {
|
||||
&self.0
|
||||
}
|
||||
}
|
||||
|
||||
fn make_temp_dir_with_exes(prefix: &str, exe_names: &[&str]) -> TempDirGuard {
|
||||
let dir = std::env::temp_dir().join(format!("patheditor_test_{}", prefix));
|
||||
let _ = fs::remove_dir_all(&dir); // 清理残留
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
for name in exe_names {
|
||||
fs::write(dir.join(name), b"fake").unwrap();
|
||||
}
|
||||
dir
|
||||
TempDirGuard(dir)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scan_conflicts_no_duplicates() {
|
||||
let d1 = make_temp_dir_with_exes("c_a", &["a.exe"]);
|
||||
let d2 = make_temp_dir_with_exes("c_b", &["b.exe"]);
|
||||
let paths = vec![d1.to_string_lossy().to_string(), d2.to_string_lossy().to_string()];
|
||||
let paths = vec![
|
||||
d1.to_string_lossy().to_string(),
|
||||
d2.to_string_lossy().to_string(),
|
||||
];
|
||||
let conflicts = scan_conflicts(paths).unwrap();
|
||||
assert!(conflicts.is_empty());
|
||||
}
|
||||
@@ -151,7 +190,10 @@ mod tests {
|
||||
fn scan_conflicts_detects_duplicate() {
|
||||
let d1 = make_temp_dir_with_exes("c_dup1", &["shared.exe"]);
|
||||
let d2 = make_temp_dir_with_exes("c_dup2", &["shared.exe"]);
|
||||
let paths = vec![d1.to_string_lossy().to_string(), d2.to_string_lossy().to_string()];
|
||||
let paths = vec![
|
||||
d1.to_string_lossy().to_string(),
|
||||
d2.to_string_lossy().to_string(),
|
||||
];
|
||||
let conflicts = scan_conflicts(paths).unwrap();
|
||||
assert_eq!(conflicts.len(), 1);
|
||||
assert_eq!(conflicts[0].locations.len(), 2);
|
||||
|
||||
+12
-38
@@ -1,3 +1,7 @@
|
||||
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;
|
||||
|
||||
@@ -26,22 +30,19 @@ 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}");
|
||||
@@ -50,10 +51,9 @@ pub fn expand_env_vars(path: &str) -> String {
|
||||
|
||||
// SAFETY: buffer 容量为 required(API 返回的精确大小),wide_path 以 null 结尾,
|
||||
// 且两个指针指向不同的内存区域,不存在重叠
|
||||
let mut buffer: Vec<u16> = vec![0; required as usize];
|
||||
let result = unsafe {
|
||||
ExpandEnvironmentStringsW(wide_path.as_ptr(), buffer.as_mut_ptr(), required)
|
||||
};
|
||||
let mut buffer = vec![0_u16; 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,10 +78,6 @@ 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();
|
||||
|
||||
@@ -89,7 +85,7 @@ pub fn broadcast_env_change() {
|
||||
// lpdwResult 为 null 表示不需要返回值,其他参数均为常量
|
||||
let result = unsafe {
|
||||
SendMessageTimeoutW(
|
||||
HWND_BROADCAST,
|
||||
HWND_BROADCAST as _,
|
||||
WM_SETTINGCHANGE,
|
||||
0,
|
||||
env_str.as_ptr() as isize,
|
||||
@@ -106,28 +102,6 @@ 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::*;
|
||||
|
||||
@@ -32,5 +32,4 @@
|
||||
- ~~profiles.rs 同款问题~~ → 同上
|
||||
|
||||
---
|
||||
|
||||
_更新于: 2026-05-30 | 审查批次: v5.1 代码审查_
|
||||
*更新于: 2026-05-30 | 审查批次: v5.1 代码审查*
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
|
||||
PathEditor v5.0 是一个功能完善的 Windows 系统环境变量 (PATH) 编辑器,支持 GUI 与 CLI 双模式。
|
||||
技术栈选型现代化且合理:
|
||||
|
||||
- **后端 / 核心逻辑**:Rust (Cargo Workspace)
|
||||
- **GUI 框架**:Tauri 2.x
|
||||
- **前端**:React 19 + TypeScript + Zustand
|
||||
@@ -14,9 +13,7 @@ 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` 库,直接提供命令行交互能力。
|
||||
@@ -24,16 +21,13 @@ 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` 库进行注册表操作。
|
||||
@@ -42,7 +36,6 @@ PathEditor v5.0 是一个功能完善的 Windows 系统环境变量 (PATH) 编
|
||||
- 能够妥善处理 UTF-16 编码和解码,保留非法码点避免丢失路径信息,细节处理非常到位。
|
||||
|
||||
### 3.2 命令行工具 (`cli`)
|
||||
|
||||
- **原子性与并发安全**:
|
||||
- 在 CLI 的 `verify_and_save` 逻辑中,写入前会重新读取注册表并与原始状态对比。如果不一致,则拒绝写入并报错退出。这有效地防止了并发情况下的配置覆盖问题。
|
||||
- **用户体验**:
|
||||
@@ -51,13 +44,11 @@ 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 状态操作解耦,使得组件代码极其整洁。
|
||||
|
||||
@@ -75,5 +66,4 @@ PathEditor v5.0 是一个功能完善的 Windows 系统环境变量 (PATH) 编
|
||||
如果 PATH 环境变量条目非常多(虽然实际场景中一般在 100 条以内),React 渲染完整列表可能会有微小延迟。当前规模下无影响,但若未来考虑显示大量工具链路径扫描结果,可引入虚拟列表(Virtual List)。
|
||||
|
||||
## 总结
|
||||
|
||||
PathEditor v5.0 的代码库是一个优秀的 Rust + Tauri + React 实践范例。它具有清晰的三层架构、严格的类型和边界检查、以及良好的错误处理机制,整体架构稳健且易于长期维护。
|
||||
|
||||
+5
-1
@@ -1,7 +1,11 @@
|
||||
export function createIpcMock() {
|
||||
export type IpcOverrides = Partial<Record<string, unknown>>;
|
||||
|
||||
export function createIpcMock(overrides: IpcOverrides = {}) {
|
||||
return `
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
invoke: async (cmd, args) => {
|
||||
const overrides = ${JSON.stringify(overrides)};
|
||||
if (cmd in overrides) return overrides[cmd];
|
||||
switch (cmd) {
|
||||
case 'check_admin': return true;
|
||||
case 'load_system_paths': return ['C:\\\\Windows', 'C:\\\\Program Files'];
|
||||
|
||||
@@ -1,43 +1,14 @@
|
||||
import { test, expect } from '@playwright/test';
|
||||
import { createIpcMock } from '../mocks/ipc';
|
||||
|
||||
test.beforeEach(async ({ page }) => {
|
||||
await page.addInitScript(() => {
|
||||
window.__TAURI_INTERNALS__ = {
|
||||
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
||||
invoke: async (cmd, args) => {
|
||||
switch (cmd) {
|
||||
case 'check_admin':
|
||||
return true;
|
||||
case 'load_system_paths':
|
||||
return ['C:\\\\Windows', 'invalid_path', 'C:\\\\Temp'];
|
||||
case 'load_user_paths':
|
||||
return [];
|
||||
case 'load_disabled_state':
|
||||
return { system: [], user: [] };
|
||||
case 'save_system_paths':
|
||||
return undefined;
|
||||
case 'save_user_paths':
|
||||
return undefined;
|
||||
case 'save_disabled_state':
|
||||
return undefined;
|
||||
case 'backup_registry':
|
||||
return '';
|
||||
case 'broadcast_env_change':
|
||||
return undefined;
|
||||
case 'validate_path':
|
||||
return false;
|
||||
case 'expand_env_vars':
|
||||
return '';
|
||||
case 'read_text_file':
|
||||
return '';
|
||||
case 'get_appdata_dir':
|
||||
return '';
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
},
|
||||
};
|
||||
});
|
||||
await page.addInitScript(
|
||||
createIpcMock({
|
||||
load_system_paths: ['C:\\Windows', 'invalid_path', 'C:\\Temp'],
|
||||
load_user_paths: [],
|
||||
validate_path: false,
|
||||
}),
|
||||
);
|
||||
await page.goto('/');
|
||||
});
|
||||
|
||||
|
||||
+1
-1
@@ -5,7 +5,7 @@ import reactRefresh from 'eslint-plugin-react-refresh';
|
||||
import globals from 'globals';
|
||||
|
||||
export default tseslint.config(
|
||||
{ ignores: ['dist', 'gui'] },
|
||||
{ ignores: ['dist', 'gui', 'target', 'test-results', 'e2e', '*.config.*'] },
|
||||
{
|
||||
extends: [js.configs.recommended, ...tseslint.configs.recommended],
|
||||
files: ['**/*.{ts,tsx}'],
|
||||
|
||||
@@ -1,12 +1,22 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "enables the default permissions",
|
||||
"description": "PathEditor main window capabilities",
|
||||
"windows": [
|
||||
"main"
|
||||
],
|
||||
"permissions": [
|
||||
"core:default",
|
||||
"dialog:default"
|
||||
"core:window:allow-set-title",
|
||||
"core:window:allow-close",
|
||||
"core:window:allow-minimize",
|
||||
"core:window:allow-start-dragging",
|
||||
"core:window:allow-is-minimized",
|
||||
"core:window:allow-set-focus",
|
||||
"core:event:default",
|
||||
"dialog:default",
|
||||
"dialog:allow-open",
|
||||
"dialog:allow-save",
|
||||
"log:default"
|
||||
]
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
use path_editor_core::backup;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn backup_registry(custom_dir: Option<String>) -> Result<String, String> { backup::backup_registry(custom_dir) }
|
||||
pub fn backup_registry(custom_dir: Option<String>) -> Result<String, String> {
|
||||
backup::backup_registry(custom_dir)
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn get_appdata_dir() -> String { backup::get_appdata_dir() }
|
||||
pub fn get_appdata_dir() -> String {
|
||||
backup::get_appdata_dir()
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
use path_editor_core::disabled;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn save_disabled_state(system: Vec<String>, user: Vec<String>) -> Result<(), String> { disabled::save_disabled_state(system, user) }
|
||||
pub fn save_disabled_state(system: Vec<String>, user: Vec<String>) -> Result<(), String> {
|
||||
disabled::save_disabled_state(system, user)
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn load_disabled_state() -> Result<(Vec<String>, Vec<String>), String> { disabled::load_disabled_state() }
|
||||
pub fn load_disabled_state() -> Result<(Vec<String>, Vec<String>), String> {
|
||||
disabled::load_disabled_state()
|
||||
}
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
use path_editor_core::fs;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn read_text_file(path: &str) -> Result<String, String> { fs::read_text_file(path) }
|
||||
pub fn read_text_file(path: &str) -> Result<String, String> {
|
||||
fs::read_text_file(path)
|
||||
}
|
||||
|
||||
@@ -1,12 +1,26 @@
|
||||
use path_editor_core::profiles;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn list_profiles() -> Result<Vec<profiles::ProfileMeta>, String> { profiles::list_profiles() }
|
||||
pub fn list_profiles() -> Result<Vec<profiles::ProfileMeta>, String> {
|
||||
profiles::list_profiles()
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn save_profile(name: String, sys: Vec<profiles::ProfilePathEntry>, user: Vec<profiles::ProfilePathEntry>) -> Result<(), String> { profiles::save_profile(&name, sys, user) }
|
||||
pub fn save_profile(
|
||||
name: String,
|
||||
sys: Vec<profiles::ProfilePathEntry>,
|
||||
user: Vec<profiles::ProfilePathEntry>,
|
||||
) -> Result<(), String> {
|
||||
profiles::save_profile(&name, sys, user)
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn load_profile(name: String) -> Result<profiles::ProfileData, String> { profiles::load_profile(&name) }
|
||||
pub fn load_profile(name: String) -> Result<profiles::ProfileData, String> {
|
||||
profiles::load_profile(&name)
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn delete_profile(name: String) -> Result<(), String> { profiles::delete_profile(&name) }
|
||||
pub fn delete_profile(name: String) -> Result<(), String> {
|
||||
profiles::delete_profile(&name)
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn rename_profile(old_name: String, new_name: String) -> Result<(), String> { profiles::rename_profile(&old_name, &new_name) }
|
||||
pub fn rename_profile(old_name: String, new_name: String) -> Result<(), String> {
|
||||
profiles::rename_profile(&old_name, &new_name)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,30 @@
|
||||
use path_editor_core::registry;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn load_system_paths() -> Result<Vec<String>, String> { registry::load_system_paths() }
|
||||
pub fn load_system_paths() -> Result<Vec<String>, String> {
|
||||
registry::load_system_paths()
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn load_user_paths() -> Result<Vec<String>, String> { registry::load_user_paths() }
|
||||
pub fn load_user_paths() -> Result<Vec<String>, String> {
|
||||
registry::load_user_paths()
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn save_system_paths(paths: Vec<String>) -> Result<(), String> { registry::save_system_paths(paths) }
|
||||
pub fn save_system_paths(paths: Vec<String>, 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)
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn save_user_paths(paths: Vec<String>) -> Result<(), String> { registry::save_user_paths(paths) }
|
||||
pub fn save_user_paths(paths: Vec<String>, 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)
|
||||
}
|
||||
|
||||
@@ -1,6 +1,10 @@
|
||||
use path_editor_core::scanner;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn scan_conflicts(paths: Vec<String>) -> Result<Vec<scanner::ConflictEntry>, String> { scanner::scan_conflicts(paths) }
|
||||
pub fn scan_conflicts(paths: Vec<String>) -> Result<Vec<scanner::ConflictEntry>, String> {
|
||||
scanner::scan_conflicts(paths)
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn scan_tools(paths: Vec<String>, query: String) -> Result<Vec<scanner::ToolGroup>, String> { scanner::scan_tools(paths, query) }
|
||||
pub fn scan_tools(paths: Vec<String>, query: String) -> Result<Vec<scanner::ToolGroup>, String> {
|
||||
scanner::scan_tools(paths, query)
|
||||
}
|
||||
|
||||
@@ -1,10 +1,18 @@
|
||||
use path_editor_core::system;
|
||||
|
||||
#[tauri::command]
|
||||
pub fn check_admin() -> bool { system::check_admin() }
|
||||
pub fn check_admin() -> bool {
|
||||
system::check_admin()
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn validate_path(path: &str) -> bool { system::validate_path(path) }
|
||||
pub fn validate_path(path: &str) -> bool {
|
||||
system::validate_path(path)
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn expand_env_vars(path: &str) -> String { system::expand_env_vars(path) }
|
||||
pub fn expand_env_vars(path: &str) -> String {
|
||||
system::expand_env_vars(path)
|
||||
}
|
||||
#[tauri::command]
|
||||
pub fn broadcast_env_change() { system::broadcast_env_change() }
|
||||
pub fn broadcast_env_change() {
|
||||
system::broadcast_env_change()
|
||||
}
|
||||
|
||||
+7
-7
@@ -5,13 +5,13 @@ pub fn run() {
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.setup(|app| {
|
||||
if cfg!(debug_assertions) {
|
||||
app.handle().plugin(
|
||||
tauri_plugin_log::Builder::default()
|
||||
.level(log::LevelFilter::Info)
|
||||
.build(),
|
||||
)?;
|
||||
}
|
||||
let level = if cfg!(debug_assertions) {
|
||||
log::LevelFilter::Info
|
||||
} else {
|
||||
log::LevelFilter::Warn
|
||||
};
|
||||
app.handle()
|
||||
.plugin(tauri_plugin_log::Builder::default().level(level).build())?;
|
||||
Ok(())
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../node_modules/@tauri-apps/cli/config.schema.json",
|
||||
"productName": "PathEditor",
|
||||
"version": "5.0.0",
|
||||
"version": "5.1.0",
|
||||
"identifier": "com.liuhangyu.patheditor",
|
||||
"build": {
|
||||
"frontendDist": "../dist",
|
||||
@@ -12,7 +12,7 @@
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "PathEditor v5.0",
|
||||
"title": "PathEditor v5.1",
|
||||
"width": 900,
|
||||
"height": 700,
|
||||
"minWidth": 800,
|
||||
|
||||
+1
-1
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>PathEditor v5.0</title>
|
||||
<title>PathEditor v5.1</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
|
||||
Generated
+100
-72
@@ -1,20 +1,21 @@
|
||||
{
|
||||
"name": "patheditor",
|
||||
"version": "5.0.0",
|
||||
"version": "5.1.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "patheditor",
|
||||
"version": "5.0.0",
|
||||
"version": "5.1.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",
|
||||
"i18next-browser-languagedetector": "^8.2.1",
|
||||
"react": "^19.2.6",
|
||||
"react-dom": "^19.2.6",
|
||||
"react": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-i18next": "^17.0.8",
|
||||
"tailwindcss": "^4.3.0",
|
||||
"zustand": "^5.0.13"
|
||||
@@ -28,10 +29,10 @@
|
||||
"@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": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"@vitest/coverage-v8": "^4.1.9",
|
||||
"@vitest/coverage-v8": "^4.1.7",
|
||||
"eslint": "^10.3.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
@@ -1715,6 +1716,33 @@
|
||||
"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",
|
||||
@@ -2095,9 +2123,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@types/react": {
|
||||
"version": "19.2.15",
|
||||
"resolved": "https://registry.npmmirror.com/@types/react/-/react-19.2.15.tgz",
|
||||
"integrity": "sha512-eRwcGNHve+E8qtEQSSRl6urh+rFop4v8gm6O8rGv25CodbvFdLjA1vVQ1KkiFE0w0UPOnb8tDiFKL5lp0rtY5Q==",
|
||||
"version": "19.2.17",
|
||||
"resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz",
|
||||
"integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==",
|
||||
"devOptional": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -2384,14 +2412,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/coverage-v8": {
|
||||
"version": "4.1.9",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/coverage-v8/-/coverage-v8-4.1.9.tgz",
|
||||
"integrity": "sha512-G9/lgqibheLVBDRuya45EbsEXTYcWoSG+TLg7i2axuzx0Eq62eXn+aWXyaVdV5vKvFSWd6ywcX8hA7la9Pvu8g==",
|
||||
"version": "4.1.7",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/coverage-v8/-/coverage-v8-4.1.7.tgz",
|
||||
"integrity": "sha512-qsYPeXc5Q9dFLd1i8Ap+Bx8sQgcp+rFVQo4R0dDsWNBzl26ldVF1qOO+RL24K7FDrR6pA+50XedRLSoSG24bVQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@bcoe/v8-coverage": "^1.0.2",
|
||||
"@vitest/utils": "4.1.9",
|
||||
"@vitest/utils": "4.1.7",
|
||||
"ast-v8-to-istanbul": "^1.0.0",
|
||||
"istanbul-lib-coverage": "^3.2.2",
|
||||
"istanbul-lib-report": "^3.0.1",
|
||||
@@ -2405,8 +2433,8 @@
|
||||
"url": "https://opencollective.com/vitest"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@vitest/browser": "4.1.9",
|
||||
"vitest": "4.1.9"
|
||||
"@vitest/browser": "4.1.7",
|
||||
"vitest": "4.1.7"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"@vitest/browser": {
|
||||
@@ -2415,16 +2443,16 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/expect": {
|
||||
"version": "4.1.9",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/expect/-/expect-4.1.9.tgz",
|
||||
"integrity": "sha512-vl/rYsUKcBr3SnQn166+XR5ZQcgMx3DQhFWdfli/cWpLnLUmbxZvyrJZotLFUryib+LtArYMSTJ5RbQ57ZqrlA==",
|
||||
"version": "4.1.7",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/expect/-/expect-4.1.7.tgz",
|
||||
"integrity": "sha512-1R+tw0ortHEbZDGMymm+pN7/AFQ/RkFFdtd7EN+VBpynKmLbP8A3rpEXdshBJ7+8hQ9zBJh/i1s0yKNtxAnU7w==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@standard-schema/spec": "^1.1.0",
|
||||
"@types/chai": "^5.2.2",
|
||||
"@vitest/spy": "4.1.9",
|
||||
"@vitest/utils": "4.1.9",
|
||||
"@vitest/spy": "4.1.7",
|
||||
"@vitest/utils": "4.1.7",
|
||||
"chai": "^6.2.2",
|
||||
"tinyrainbow": "^3.1.0"
|
||||
},
|
||||
@@ -2433,13 +2461,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/mocker": {
|
||||
"version": "4.1.9",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/mocker/-/mocker-4.1.9.tgz",
|
||||
"integrity": "sha512-EVkXzBjrPGM+cK8/ANWgBrkUCfJfb38/EfTSO8h7pWvKkyPkpWxvR7BkD2MyItMF62C97zAEoqdpUixwR/e+Rw==",
|
||||
"version": "4.1.7",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/mocker/-/mocker-4.1.7.tgz",
|
||||
"integrity": "sha512-vY7nuamKgfvpA1Koa3oYIw/k7D6kZnpGyNMZW8loow2bsBYla1TFdqTaXncWdRn4pgwNs+90RhnXhJScDwQeJA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/spy": "4.1.9",
|
||||
"@vitest/spy": "4.1.7",
|
||||
"estree-walker": "^3.0.3",
|
||||
"magic-string": "^0.30.21"
|
||||
},
|
||||
@@ -2460,9 +2488,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/pretty-format": {
|
||||
"version": "4.1.9",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/pretty-format/-/pretty-format-4.1.9.tgz",
|
||||
"integrity": "sha512-s0iufns3iIFitdgm+YR7g1whCAaGtXz459VS9/PqyKDEEFgYIhsHOQmXgIgDuYCt7DeQmiZT0Qe2OA2p4ZPu5A==",
|
||||
"version": "4.1.7",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/pretty-format/-/pretty-format-4.1.7.tgz",
|
||||
"integrity": "sha512-umgCarTOYQWIaDMvGDRZij+6b9oVeLIyJzfN+AS88e0ZOU3QTgNNSTtjQOpcvWr3np1N0j4WgZj+sb3oYBDscw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -2473,13 +2501,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/runner": {
|
||||
"version": "4.1.9",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/runner/-/runner-4.1.9.tgz",
|
||||
"integrity": "sha512-KXLMDtc7oe70+3mJfGrPUWPesswH+3sTxAMAMl8DG7I8IUQT4XW718dY5ID3vPUcmlu27CcKfY4P3h3I29SLJg==",
|
||||
"version": "4.1.7",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/runner/-/runner-4.1.7.tgz",
|
||||
"integrity": "sha512-BapjmAQ2aI78WdMEfeUWivnfVzB+VPGwWRQcJE0OUq7qEeEcBsCSf+0T5iREBNE5nBb4wA5Ya0W6IA+sghdEFw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/utils": "4.1.9",
|
||||
"@vitest/utils": "4.1.7",
|
||||
"pathe": "^2.0.3"
|
||||
},
|
||||
"funding": {
|
||||
@@ -2487,14 +2515,14 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/snapshot": {
|
||||
"version": "4.1.9",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/snapshot/-/snapshot-4.1.9.tgz",
|
||||
"integrity": "sha512-Jc7RKGNBo8Z28WYIm0Niej4xdSPByRf6mU58VpHQkd6Zh05rlnA+twjbK5HyeIGHxrzsc3mJgS43uM0CZKzaIA==",
|
||||
"version": "4.1.7",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/snapshot/-/snapshot-4.1.7.tgz",
|
||||
"integrity": "sha512-ZacLzja+TmJeZ1h14xW2FB/WpeimUD3haBXQPyJqxvo8jQTmfeA8zv58mtjN2C7EHXZDYVcVYdYmAxjkWVvKCw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/pretty-format": "4.1.9",
|
||||
"@vitest/utils": "4.1.9",
|
||||
"@vitest/pretty-format": "4.1.7",
|
||||
"@vitest/utils": "4.1.7",
|
||||
"magic-string": "^0.30.21",
|
||||
"pathe": "^2.0.3"
|
||||
},
|
||||
@@ -2503,9 +2531,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/spy": {
|
||||
"version": "4.1.9",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/spy/-/spy-4.1.9.tgz",
|
||||
"integrity": "sha512-fHpsS6mIi+PiEW+vcRVOMkX1oSaPKne3VOclSFICPcGOmfKgXPU5iAah+wcNcj2xPrCCmfq99IDGf+EojhhvhA==",
|
||||
"version": "4.1.7",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/spy/-/spy-4.1.7.tgz",
|
||||
"integrity": "sha512-kbkI5LMWakyuTIvs6fUJ5qdIVb1XVKsYJAT4OJ938cHMROYMSfmoQdZy0aaAnjbbc8F61vkoTqz/Az+/HiIu5Q==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"funding": {
|
||||
@@ -2513,13 +2541,13 @@
|
||||
}
|
||||
},
|
||||
"node_modules/@vitest/utils": {
|
||||
"version": "4.1.9",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/utils/-/utils-4.1.9.tgz",
|
||||
"integrity": "sha512-A51o8ymO5PpqlWNnBP9ZHPXDIpuMtTLlGSjN7la4US+LJzoUMyhwjA5QXlm39JexgwHKW4Xjs8Z2d3dLCXOeuA==",
|
||||
"version": "4.1.7",
|
||||
"resolved": "https://registry.npmmirror.com/@vitest/utils/-/utils-4.1.7.tgz",
|
||||
"integrity": "sha512-T532WBu791cBxJlCl6SO+J14l81DQx6uQHm1bQbmCDY7nqlEIgkza/UFnSBNaUtSf41unldDFjdOBYEQC4b5Hw==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/pretty-format": "4.1.9",
|
||||
"@vitest/pretty-format": "4.1.7",
|
||||
"convert-source-map": "^2.0.0",
|
||||
"tinyrainbow": "^3.1.0"
|
||||
},
|
||||
@@ -2643,9 +2671,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/ast-v8-to-istanbul": {
|
||||
"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==",
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmmirror.com/ast-v8-to-istanbul/-/ast-v8-to-istanbul-1.0.2.tgz",
|
||||
"integrity": "sha512-dKmJxJsGItLmc5CYZKuEjuG6GnBs6PG4gohMhyFOWKaNQoYCuRZJDECaBlHmcG0lv2wc2E0uU8lESmBEumC3DQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
@@ -4540,9 +4568,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/make-dir/node_modules/semver": {
|
||||
"version": "7.8.4",
|
||||
"resolved": "https://registry.npmmirror.com/semver/-/semver-7.8.4.tgz",
|
||||
"integrity": "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==",
|
||||
"version": "7.8.1",
|
||||
"resolved": "https://registry.npmmirror.com/semver/-/semver-7.8.1.tgz",
|
||||
"integrity": "sha512-rkVq3IXh+4FDGch+KwzX3aV9W3kO54GyEgpvBzSyctDA6Xtd7RJQV1xmXbeQp5v7+VzLOfVqiutSE6GICgPFvg==",
|
||||
"dev": true,
|
||||
"license": "ISC",
|
||||
"bin": {
|
||||
@@ -4948,24 +4976,24 @@
|
||||
}
|
||||
},
|
||||
"node_modules/react": {
|
||||
"version": "19.2.6",
|
||||
"resolved": "https://registry.npmmirror.com/react/-/react-19.2.6.tgz",
|
||||
"integrity": "sha512-sfWGGfavi0xr8Pg0sVsyHMAOziVYKgPLNrS7ig+ivMNb3wbCBw3KxtflsGBAwD3gYQlE/AEZsTLgToRrSCjb0Q==",
|
||||
"version": "19.2.7",
|
||||
"resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz",
|
||||
"integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/react-dom": {
|
||||
"version": "19.2.6",
|
||||
"resolved": "https://registry.npmmirror.com/react-dom/-/react-dom-19.2.6.tgz",
|
||||
"integrity": "sha512-0prMI+hvBbPjsWnxDLxlCGyM8PN6UuWjEUCYmZhO67xIV9Xasa/r/vDnq+Xyq4Lo27g8QSbO5YzARu0D1Sps3g==",
|
||||
"version": "19.2.7",
|
||||
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz",
|
||||
"integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"scheduler": "^0.27.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"react": "^19.2.6"
|
||||
"react": "^19.2.7"
|
||||
}
|
||||
},
|
||||
"node_modules/react-i18next": {
|
||||
@@ -5632,19 +5660,19 @@
|
||||
}
|
||||
},
|
||||
"node_modules/vitest": {
|
||||
"version": "4.1.9",
|
||||
"resolved": "https://registry.npmmirror.com/vitest/-/vitest-4.1.9.tgz",
|
||||
"integrity": "sha512-nE3/LEyc0z87uHYLZebqCUOaJr2hdtuPp7BQ4BosVFnfltxgAvMG08NyrSGlPpOUWvR27c5flSmYFTNr78L9GQ==",
|
||||
"version": "4.1.7",
|
||||
"resolved": "https://registry.npmmirror.com/vitest/-/vitest-4.1.7.tgz",
|
||||
"integrity": "sha512-flYyaFd2CgoCoU+0UKt3pxksgC+S02iTDN0n3LtqaMeXsI9SBcdNujc2k0DeFLzUn/0k538yNjOSdwgCqcrwJA==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@vitest/expect": "4.1.9",
|
||||
"@vitest/mocker": "4.1.9",
|
||||
"@vitest/pretty-format": "4.1.9",
|
||||
"@vitest/runner": "4.1.9",
|
||||
"@vitest/snapshot": "4.1.9",
|
||||
"@vitest/spy": "4.1.9",
|
||||
"@vitest/utils": "4.1.9",
|
||||
"@vitest/expect": "4.1.7",
|
||||
"@vitest/mocker": "4.1.7",
|
||||
"@vitest/pretty-format": "4.1.7",
|
||||
"@vitest/runner": "4.1.7",
|
||||
"@vitest/snapshot": "4.1.7",
|
||||
"@vitest/spy": "4.1.7",
|
||||
"@vitest/utils": "4.1.7",
|
||||
"es-module-lexer": "^2.0.0",
|
||||
"expect-type": "^1.3.0",
|
||||
"magic-string": "^0.30.21",
|
||||
@@ -5672,12 +5700,12 @@
|
||||
"@edge-runtime/vm": "*",
|
||||
"@opentelemetry/api": "^1.9.0",
|
||||
"@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
|
||||
"@vitest/browser-playwright": "4.1.9",
|
||||
"@vitest/browser-preview": "4.1.9",
|
||||
"@vitest/browser-webdriverio": "4.1.9",
|
||||
"@vitest/coverage-istanbul": "4.1.9",
|
||||
"@vitest/coverage-v8": "4.1.9",
|
||||
"@vitest/ui": "4.1.9",
|
||||
"@vitest/browser-playwright": "4.1.7",
|
||||
"@vitest/browser-preview": "4.1.7",
|
||||
"@vitest/browser-webdriverio": "4.1.7",
|
||||
"@vitest/coverage-istanbul": "4.1.7",
|
||||
"@vitest/coverage-v8": "4.1.7",
|
||||
"@vitest/ui": "4.1.7",
|
||||
"happy-dom": "*",
|
||||
"jsdom": "*",
|
||||
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
|
||||
+8
-5
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "patheditor",
|
||||
"private": true,
|
||||
"version": "5.0.0",
|
||||
"version": "5.1.0",
|
||||
"type": "module",
|
||||
"lint-staged": {
|
||||
"*.{ts,tsx}": [
|
||||
@@ -16,8 +16,10 @@
|
||||
"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",
|
||||
@@ -27,12 +29,13 @@
|
||||
},
|
||||
"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": "^19.2.7",
|
||||
"react-dom": "^19.2.7",
|
||||
"react-i18next": "^17.0.8",
|
||||
"tailwindcss": "^4.3.0",
|
||||
"zustand": "^5.0.13"
|
||||
@@ -46,10 +49,10 @@
|
||||
"@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": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.1",
|
||||
"@vitest/coverage-v8": "^4.1.9",
|
||||
"@vitest/coverage-v8": "^4.1.7",
|
||||
"eslint": "^10.3.0",
|
||||
"eslint-plugin-react-hooks": "^7.1.1",
|
||||
"eslint-plugin-react-refresh": "^0.5.2",
|
||||
|
||||
@@ -37,8 +37,12 @@ export function AnalyzeDialog({ open, onClose }: Props) {
|
||||
|
||||
const prevOpen = useRef(false);
|
||||
useEffect(() => {
|
||||
if (!open || prevOpen.current) return;
|
||||
prevOpen.current = open;
|
||||
if (!open) {
|
||||
prevOpen.current = false;
|
||||
return;
|
||||
}
|
||||
if (prevOpen.current) return;
|
||||
prevOpen.current = true;
|
||||
setLoading(true);
|
||||
const paths = getEnabledPaths();
|
||||
Promise.all([
|
||||
@@ -190,7 +194,7 @@ function ToolsTab({
|
||||
opacity: g.exists ? 1 : 0.6,
|
||||
}}
|
||||
>
|
||||
{g.dir} {!g.exists && '(不存在)'}
|
||||
{g.dir} {!g.exists && t('analyze.notExists')}
|
||||
</div>
|
||||
<div className="flex flex-wrap gap-1 mt-1 ml-2">
|
||||
{g.exes.map((exe) => (
|
||||
|
||||
@@ -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 && `系统变量: ${systemCount} 条`}
|
||||
{systemCount > 0 && t('dialog.importSystemCount', { count: systemCount })}
|
||||
{systemCount > 0 && userCount > 0 && ' | '}
|
||||
{userCount > 0 && `用户变量: ${userCount} 条`}
|
||||
{userCount > 0 && t('dialog.importUserCount', { count: userCount })}
|
||||
</p>
|
||||
<div className="flex flex-col gap-2">
|
||||
{systemCount > 0 && (
|
||||
|
||||
@@ -73,8 +73,22 @@ 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),
|
||||
});
|
||||
await useAppStore.getState().savePaths();
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleDelete = async (name: string) => {
|
||||
@@ -166,7 +180,7 @@ export function ProfileDialog({ open, onClose }: Props) {
|
||||
<div className="flex-1 p-3 overflow-auto">
|
||||
{!selectedData ? (
|
||||
<div className="text-center py-10 text-sm" style={{ opacity: 0.4 }}>
|
||||
{profiles.length === 0 ? t('profile.noProfiles') : '选择一个配置文件'}
|
||||
{profiles.length === 0 ? t('profile.noProfiles') : t('profile.selectProfile')}
|
||||
</div>
|
||||
) : (
|
||||
<div>
|
||||
@@ -222,7 +236,7 @@ export function ProfileDialog({ open, onClose }: Props) {
|
||||
style={{ backgroundColor: '#3b82f6' }}
|
||||
onClick={handleRename}
|
||||
>
|
||||
确认
|
||||
{t('button.save')}
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
@@ -245,6 +259,7 @@ 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 }}>
|
||||
@@ -252,13 +267,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, i) => (
|
||||
{paths.map((e) => (
|
||||
<div
|
||||
key={i}
|
||||
key={e.path}
|
||||
className="text-xs font-mono px-2 py-0.5 rounded flex items-center gap-1.5"
|
||||
style={{
|
||||
backgroundColor: 'var(--app-list-bg)',
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useMemo } from 'react';
|
||||
import { useMemo, useRef } 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);
|
||||
@@ -33,46 +34,62 @@ 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 className="flex-1 overflow-auto">
|
||||
<table className="w-full border-collapse">
|
||||
<thead>
|
||||
<tr
|
||||
className="sticky top-0 z-10 text-left text-xs uppercase"
|
||||
<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)' }}
|
||||
>
|
||||
<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) => {
|
||||
<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;
|
||||
|
||||
return (
|
||||
<tr
|
||||
<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)',
|
||||
}}
|
||||
>
|
||||
<td className="px-2 py-0.5 text-xs opacity-50">{rowIdx + 1}</td>
|
||||
<td
|
||||
className="px-2 py-0.5 text-sm"
|
||||
<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 }}
|
||||
>
|
||||
{path}
|
||||
</td>
|
||||
<td className="px-2 py-0.5 text-xs opacity-60">{source}</td>
|
||||
</tr>
|
||||
</div>
|
||||
<div className="w-16 px-2 py-0.5 text-xs opacity-60">{source}</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
|
||||
import { useMemo, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useAppStore } from '@/store/app-store';
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { TargetType } from '@/core/undo-redo';
|
||||
import { usePathValidation } from '@/hooks/use-path-validation';
|
||||
import type { ValidationState } from '@/hooks/use-path-validation';
|
||||
import { useVirtualizer } from '@tanstack/react-virtual';
|
||||
|
||||
interface PathTableProps {
|
||||
tabId: 'system' | 'user';
|
||||
@@ -13,10 +16,8 @@ interface PathRow {
|
||||
enabled: boolean;
|
||||
}
|
||||
|
||||
type ValidationState = 'valid' | 'invalid' | 'unknown';
|
||||
const DEFAULT_VALIDATION_STATE: ValidationState = 'valid';
|
||||
|
||||
export function PathTable({ tabId }: PathTableProps) {
|
||||
const { t } = useTranslation();
|
||||
const sysPaths = useAppStore((s) => s.sysPaths);
|
||||
const userPaths = useAppStore((s) => s.userPaths);
|
||||
const searchQuery = useAppStore((s) => s.searchQuery);
|
||||
@@ -27,15 +28,9 @@ export function PathTable({ tabId }: PathTableProps) {
|
||||
const paths = tabId === 'system' ? sysPaths : userPaths;
|
||||
const isActive = activeTab === tabId;
|
||||
|
||||
// 本次会话中已验证过的路径缓存(key=path, value=ValidationState)
|
||||
const [validationCache, setValidationCache] = useState<Map<string, ValidationState>>(new Map());
|
||||
// 环境变量展开结果缓存(key=path, value=expanded)
|
||||
const [expandedCache, setExpandedCache] = useState<Map<string, string>>(new Map());
|
||||
const { validationCache, expandedCache } = usePathValidation(paths);
|
||||
|
||||
const validatedRef = useRef<Set<string>>(new Set());
|
||||
const expandedRef = useRef<Set<string>>(new Set());
|
||||
|
||||
// 过滤搜索
|
||||
// 搜索过滤
|
||||
const filtered = useMemo<PathRow[]>(() => {
|
||||
if (!searchQuery) return paths.map((p, i) => ({ path: p.path, index: i, enabled: p.enabled }));
|
||||
const q = searchQuery.toLowerCase();
|
||||
@@ -48,81 +43,15 @@ export function PathTable({ tabId }: PathTableProps) {
|
||||
return result;
|
||||
}, [paths, searchQuery]);
|
||||
|
||||
// 异步验证未缓存的路径
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const toValidate = paths.filter((p) => !validatedRef.current.has(p.path));
|
||||
if (toValidate.length === 0) return;
|
||||
|
||||
const batch = toValidate.slice(0, 20);
|
||||
Promise.all(
|
||||
batch.map(async (p): Promise<[string, ValidationState]> => {
|
||||
try {
|
||||
if (p.path.includes('%')) return [p.path, 'valid'];
|
||||
const valid: boolean = await invoke('validate_path', { path: p.path });
|
||||
return [p.path, valid ? 'valid' : 'invalid'];
|
||||
} catch {
|
||||
return [p.path, 'unknown'];
|
||||
}
|
||||
}),
|
||||
).then((results) => {
|
||||
if (cancelled) return;
|
||||
for (const [p] of results) validatedRef.current.add(p);
|
||||
setValidationCache((prev) => {
|
||||
const next = new Map(prev);
|
||||
for (const [p, v] of results) next.set(p, v);
|
||||
return next;
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [paths]);
|
||||
|
||||
// 异步展开环境变量(用于 tooltip)
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
const toExpand = paths.filter((p) => p.path.includes('%') && !expandedRef.current.has(p.path));
|
||||
if (toExpand.length === 0) return;
|
||||
|
||||
const batch = toExpand.slice(0, 20);
|
||||
Promise.all(
|
||||
batch.map(async (p): Promise<[string, string]> => {
|
||||
try {
|
||||
const expanded: string = await invoke('expand_env_vars', { path: p.path });
|
||||
return [p.path, expanded !== p.path ? expanded : ''];
|
||||
} catch {
|
||||
return [p.path, ''];
|
||||
}
|
||||
}),
|
||||
).then((results) => {
|
||||
if (cancelled) return;
|
||||
for (const [p] of results) expandedRef.current.add(p);
|
||||
setExpandedCache((prev) => {
|
||||
const next = new Map(prev);
|
||||
for (const [p, v] of results) next.set(p, v);
|
||||
return next;
|
||||
});
|
||||
});
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [paths]);
|
||||
|
||||
// 所有路径默认有效(异步验证结果回来后再精确染色)
|
||||
// 计算验证状态(含去重检测)
|
||||
const validations = useMemo(() => {
|
||||
const seen = new Set<string>();
|
||||
return filtered.map(({ path }) => {
|
||||
const lower = path.toLowerCase();
|
||||
const isDuplicate = seen.has(lower);
|
||||
seen.add(lower);
|
||||
return {
|
||||
state: validationCache.get(path) ?? DEFAULT_VALIDATION_STATE,
|
||||
isDuplicate,
|
||||
isEnvVar: path.includes('%'),
|
||||
};
|
||||
const state: ValidationState = validationCache.get(path) ?? 'valid';
|
||||
return { state, isDuplicate, isEnvVar: path.includes('%') };
|
||||
});
|
||||
}, [filtered, validationCache]);
|
||||
|
||||
@@ -153,21 +82,35 @@ 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 className="flex-1 overflow-auto">
|
||||
<table className="w-full border-collapse">
|
||||
<thead>
|
||||
<tr
|
||||
className="sticky top-0 z-10 text-left text-xs uppercase"
|
||||
<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)' }}
|
||||
>
|
||||
<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) => {
|
||||
<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)';
|
||||
@@ -184,12 +127,14 @@ export function PathTable({ tabId }: PathTableProps) {
|
||||
}
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={index}
|
||||
<div
|
||||
key={virtualRow.key}
|
||||
onClick={(e) => handleClick(index, e)}
|
||||
onDoubleClick={() => handleDoubleClick(index)}
|
||||
className="cursor-pointer select-none"
|
||||
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
|
||||
@@ -197,13 +142,13 @@ export function PathTable({ tabId }: PathTableProps) {
|
||||
: 'var(--app-list-alt)',
|
||||
}}
|
||||
>
|
||||
<td
|
||||
<div
|
||||
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">
|
||||
</div>
|
||||
<div className="w-6 px-1 py-0.5 flex items-center">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={enabled}
|
||||
@@ -213,19 +158,18 @@ export function PathTable({ tabId }: PathTableProps) {
|
||||
}}
|
||||
className="cursor-pointer"
|
||||
/>
|
||||
</td>
|
||||
<td
|
||||
className="px-2 py-0.5 text-sm truncate max-w-2xl"
|
||||
</div>
|
||||
<div
|
||||
className="px-2 py-0.5 text-sm truncate flex-1"
|
||||
style={{ color: textColor, textDecoration, opacity }}
|
||||
title={expandedCache.get(path) || undefined}
|
||||
>
|
||||
{path}
|
||||
</td>
|
||||
</tr>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -6,6 +6,9 @@ export function UndoRedoButtons() {
|
||||
const { t } = useTranslation();
|
||||
const isAdmin = useAppStore((s) => s.isAdmin);
|
||||
const undoRedo = useAppStore((s) => s.undoRedo);
|
||||
// 订阅路径数组长度变化,确保 undoRedo 内部状态变化时触发重渲染
|
||||
useAppStore((s) => s.sysPaths.length);
|
||||
useAppStore((s) => s.userPaths.length);
|
||||
const undo = useAppStore((s) => s.undo);
|
||||
const redo = useAppStore((s) => s.redo);
|
||||
|
||||
|
||||
@@ -124,8 +124,19 @@ export function useAppActions(activeTab: TabId, dialogs: DialogState) {
|
||||
URL.revokeObjectURL(url);
|
||||
}, []);
|
||||
|
||||
const handleSave = useCallback(() => {
|
||||
useAppStore.getState().savePaths();
|
||||
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);
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
// ── 键盘 ──
|
||||
|
||||
@@ -56,11 +56,6 @@ export function useKeyboard(actions: KeyboardActions) {
|
||||
if (!isAdmin) return;
|
||||
e.preventDefault();
|
||||
a.onDelete();
|
||||
} else if (ctrl && e.key === 'f') {
|
||||
e.preventDefault();
|
||||
const searchInput = document.querySelector<HTMLInputElement>('input[placeholder]');
|
||||
searchInput?.focus();
|
||||
searchInput?.select();
|
||||
} else if (e.key === 'F1') {
|
||||
e.preventDefault();
|
||||
a.onHelp();
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
"user": "User Variables",
|
||||
"merged": "Merge Preview"
|
||||
},
|
||||
"table": {
|
||||
"path": "Path"
|
||||
},
|
||||
"button": {
|
||||
"new": "New",
|
||||
"edit": "Edit",
|
||||
@@ -51,7 +54,8 @@
|
||||
"readonly_label": "Read-only",
|
||||
"light": "Light",
|
||||
"dark": "Dark",
|
||||
"adminWarning": "Running without administrator privileges, some features are disabled"
|
||||
"adminWarning": "Running without administrator privileges, some features are disabled",
|
||||
"saveWarningLongPaths": "PATH length exceeds recommended value. Continue saving?"
|
||||
},
|
||||
"dialog": {
|
||||
"newPath": "New Path",
|
||||
@@ -70,7 +74,9 @@
|
||||
"backupMessage": "Back up registry before saving?",
|
||||
"confirm": "Confirm",
|
||||
"cancel": "Cancel",
|
||||
"search": "Search paths..."
|
||||
"search": "Search paths...",
|
||||
"importSystemCount": "System: {{count}} entries",
|
||||
"importUserCount": "User: {{count}} entries"
|
||||
},
|
||||
"analyze": {
|
||||
"title": "PATH Analysis",
|
||||
@@ -82,7 +88,8 @@
|
||||
"priority": "Prioritized",
|
||||
"shadowed": "Shadowed",
|
||||
"searchPlaceholder": "Search executable name...",
|
||||
"conflictCount": "{{count}} file conflict(s) found"
|
||||
"conflictCount": "{{count}} file conflict(s) found",
|
||||
"notExists": "(not found)"
|
||||
},
|
||||
"profile": {
|
||||
"title": "PATH Profiles",
|
||||
@@ -95,7 +102,9 @@
|
||||
"rename": "Rename",
|
||||
"noProfiles": "No saved profiles",
|
||||
"applyConfirm": "This will overwrite current PATH with profile \"{{name}}\" and write to registry. Confirm?",
|
||||
"deleted": "Profile \"{{name}}\" deleted"
|
||||
"deleted": "Profile \"{{name}}\" deleted",
|
||||
"selectProfile": "Select a profile",
|
||||
"empty": "(empty)"
|
||||
},
|
||||
"help": {
|
||||
"content": "PathEditor v5.0 — Windows System Environment Variable (PATH) Editor\n\nFeatures:\n• Create/Edit/Delete path entries\n• Move Up/Down to adjust priority\n• One-click cleanup of invalid & duplicate paths\n• Import/Export JSON, CSV, TXT formats\n• Full Undo/Redo support\n\nShortcuts:\n• Ctrl+N New\n• Ctrl+S Save\n• Ctrl+Z Undo\n• Ctrl+Y Redo\n• Ctrl+F Search\n• Delete Delete selected\n• F1 Help\n\nAuthor: 刘航宇\nGitHub: https://github.com/LHY0125/PathEditor"
|
||||
|
||||
@@ -8,6 +8,9 @@
|
||||
"user": "用户变量",
|
||||
"merged": "合并预览"
|
||||
},
|
||||
"table": {
|
||||
"path": "路径"
|
||||
},
|
||||
"button": {
|
||||
"new": "新建",
|
||||
"edit": "编辑",
|
||||
@@ -51,7 +54,8 @@
|
||||
"modified": "已修改",
|
||||
"readonly_label": "只读",
|
||||
"light": "浅色",
|
||||
"dark": "深色"
|
||||
"dark": "深色",
|
||||
"saveWarningLongPaths": "PATH 长度超过建议值,是否继续保存?"
|
||||
},
|
||||
"dialog": {
|
||||
"newPath": "新建路径",
|
||||
@@ -70,7 +74,9 @@
|
||||
"backupMessage": "保存前需要备份注册表吗?",
|
||||
"confirm": "确认",
|
||||
"cancel": "取消",
|
||||
"search": "搜索路径..."
|
||||
"search": "搜索路径...",
|
||||
"importSystemCount": "系统变量: {{count}} 条",
|
||||
"importUserCount": "用户变量: {{count}} 条"
|
||||
},
|
||||
"analyze": {
|
||||
"title": "PATH 分析",
|
||||
@@ -82,7 +88,8 @@
|
||||
"priority": "优先执行",
|
||||
"shadowed": "被遮蔽",
|
||||
"searchPlaceholder": "搜索可执行文件名...",
|
||||
"conflictCount": "发现 {{count}} 个文件冲突"
|
||||
"conflictCount": "发现 {{count}} 个文件冲突",
|
||||
"notExists": "(不存在)"
|
||||
},
|
||||
"profile": {
|
||||
"title": "PATH 配置文件",
|
||||
@@ -95,7 +102,9 @@
|
||||
"rename": "重命名",
|
||||
"noProfiles": "暂无配置文件",
|
||||
"applyConfirm": "将用配置 \"{{name}}\" 覆盖当前 PATH 并写入注册表,确定吗?",
|
||||
"deleted": "已删除配置 \"{{name}}\""
|
||||
"deleted": "已删除配置 \"{{name}}\"",
|
||||
"selectProfile": "选择一个配置文件",
|
||||
"empty": "(空)"
|
||||
},
|
||||
"help": {
|
||||
"content": "PathEditor v5.0 — Windows 系统环境变量 (PATH) 编辑器\n\n功能:\n• 新建/编辑/删除路径条目\n• 上移/下移调整优先级\n• 一键清理无效和重复路径\n• 导入/导出 JSON、CSV、TXT 格式\n• 完整撤销/重做支持\n\n快捷键:\n• Ctrl+N 新建\n• Ctrl+S 保存\n• Ctrl+Z 撤销\n• Ctrl+Y 重做\n• Ctrl+F 搜索\n• Delete 删除选中\n• F1 帮助\n\n作者: 刘航宇\nGitHub: https://github.com/LHY0125/PathEditor"
|
||||
|
||||
+40
-16
@@ -8,6 +8,13 @@ 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[];
|
||||
@@ -45,7 +52,7 @@ interface AppState {
|
||||
redo: () => void;
|
||||
|
||||
loadPaths: () => Promise<void>;
|
||||
savePaths: () => Promise<void>;
|
||||
savePaths: (force?: boolean) => Promise<SaveResult>;
|
||||
initialize: () => Promise<void>;
|
||||
}
|
||||
|
||||
@@ -289,7 +296,9 @@ 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(() => {});
|
||||
invoke('save_disabled_state', { system: sysDisabled, user: usrDisabled }).catch((e) =>
|
||||
console.warn('保存禁用状态失败:', e),
|
||||
);
|
||||
},
|
||||
|
||||
undo: () => {
|
||||
@@ -307,7 +316,7 @@ export const useAppStore = create<AppState>((set, get) => {
|
||||
invoke('save_disabled_state', {
|
||||
system: result[0].filter((e) => !e.enabled).map((e) => e.path),
|
||||
user: result[1].filter((e) => !e.enabled).map((e) => e.path),
|
||||
}).catch(() => {});
|
||||
}).catch((e) => console.warn('保存禁用状态失败:', e));
|
||||
}
|
||||
},
|
||||
|
||||
@@ -326,7 +335,7 @@ export const useAppStore = create<AppState>((set, get) => {
|
||||
invoke('save_disabled_state', {
|
||||
system: result[0].filter((e) => !e.enabled).map((e) => e.path),
|
||||
user: result[1].filter((e) => !e.enabled).map((e) => e.path),
|
||||
}).catch(() => {});
|
||||
}).catch((e) => console.warn('保存禁用状态失败:', e));
|
||||
}
|
||||
},
|
||||
|
||||
@@ -373,9 +382,9 @@ export const useAppStore = create<AppState>((set, get) => {
|
||||
}
|
||||
},
|
||||
|
||||
savePaths: async () => {
|
||||
savePaths: async (force?: boolean) => {
|
||||
const state = get();
|
||||
if (state.isSaving) return;
|
||||
if (state.isSaving) return { kind: 'blocked' };
|
||||
set({ isSaving: true, statusMessage: i18n.t('status.saving') });
|
||||
|
||||
// 只保存 enabled 的路径到注册表
|
||||
@@ -384,16 +393,16 @@ export const useAppStore = create<AppState>((set, get) => {
|
||||
const sysJoined = sysPaths.join(';');
|
||||
const userJoined = userPaths.join(';');
|
||||
|
||||
// 长度检查:非强制模式下返回警告,由 UI 层确认
|
||||
const { maxSystemLength, maxUserLength, maxCombinedLength } = appConfig.path;
|
||||
if (
|
||||
sysJoined.length > maxSystemLength ||
|
||||
!force &&
|
||||
(sysJoined.length > maxSystemLength ||
|
||||
userJoined.length > maxUserLength ||
|
||||
(sysJoined + userJoined).length > maxCombinedLength
|
||||
(sysJoined + userJoined).length > maxCombinedLength)
|
||||
) {
|
||||
if (!window.confirm('PATH 长度超过建议值,是否继续保存?')) {
|
||||
set({ isSaving: false });
|
||||
return;
|
||||
}
|
||||
set({ isSaving: false, statusMessage: i18n.t('status.saveWarningLongPaths') });
|
||||
return { kind: 'warning', reason: 'lengthExceeded' };
|
||||
}
|
||||
|
||||
// 备份当前注册表(保存前备份旧值,失败仅警告不中断)
|
||||
@@ -402,9 +411,12 @@ 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 }),
|
||||
invoke('save_user_paths', { paths: userPaths }),
|
||||
invoke('save_system_paths', { paths: sysPaths, original: origSys }),
|
||||
invoke('save_user_paths', { paths: userPaths, original: origUser }),
|
||||
]);
|
||||
|
||||
const sysOk = sysResult.status === 'fulfilled';
|
||||
@@ -423,16 +435,28 @@ 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 保存失败'
|
||||
? `用户 PATH 保存失败: ${usrErr}`
|
||||
: userOk
|
||||
? '系统 PATH 保存失败'
|
||||
? `系统 PATH 保存失败: ${sysErr}`
|
||||
: `保存失败: ${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 };
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// @vitest-environment jsdom
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render } from '@testing-library/react';
|
||||
import { AnalyzeDialog } from '../../src/components/dialogs/AnalyzeDialog';
|
||||
|
||||
@@ -242,19 +242,26 @@ describe('savePaths', () => {
|
||||
|
||||
it('保存成功', async () => {
|
||||
mockedInvoke.mockResolvedValue(undefined);
|
||||
await useAppStore.getState().savePaths();
|
||||
const result = await useAppStore.getState().savePaths();
|
||||
expect(result).toEqual({ kind: 'success' });
|
||||
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
|
||||
await useAppStore.getState().savePaths();
|
||||
.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');
|
||||
const s = useAppStore.getState();
|
||||
expect(s.isSaving).toBe(false);
|
||||
expect(s.statusMessage).toContain('用户 PATH 保存失败');
|
||||
@@ -273,8 +280,8 @@ describe('savePaths', () => {
|
||||
// 第二次调用应被 isSaving 守卫拦截(此时 isSaving=true)
|
||||
const r2 = useAppStore.getState().savePaths();
|
||||
|
||||
// 第二次调用同步返回 undefined(被守卫拦截)
|
||||
await expect(r2).resolves.toBeUndefined();
|
||||
// 第二次调用同步返回 blocked(被守卫拦截)
|
||||
await expect(r2).resolves.toEqual({ kind: 'blocked' });
|
||||
|
||||
// 放行第一次调用的所有 invoke
|
||||
resolveAll!(undefined);
|
||||
|
||||
@@ -24,7 +24,7 @@ describe('exportToJson', () => {
|
||||
it('导出结构化 JSON', () => {
|
||||
const json = exportToJson(sampleData);
|
||||
const parsed = JSON.parse(json);
|
||||
expect(parsed.version).toBe('5.0.0');
|
||||
expect(parsed.version).toBe('5.1.0');
|
||||
expect(parsed.timestamp).toBeDefined();
|
||||
expect(parsed.system.map((e: { path: string }) => e.path)).toEqual(
|
||||
sampleData.system.map((e) => e.path),
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
// @vitest-environment jsdom
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render } from '@testing-library/react';
|
||||
import { MergePreview } from '../../src/components/path-list/MergePreview';
|
||||
@@ -17,6 +16,21 @@ 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,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { pathClean } from '../../src/core/path-manager';
|
||||
import { pathClean, analyzePaths } from '../../src/core/path-manager';
|
||||
import type { PathEntry } from '../../src/core/path-entry';
|
||||
|
||||
function pe(s: string, enabled: boolean = true): PathEntry {
|
||||
@@ -9,6 +9,31 @@ function pe(s: string, enabled: boolean = true): PathEntry {
|
||||
const alwaysValid = () => true;
|
||||
const validateFn = (path: string) => !path.includes('Invalid');
|
||||
|
||||
describe('analyzePaths', () => {
|
||||
it('检测大小写重复', () => {
|
||||
const result = analyzePaths([pe('C:\\Windows'), pe('c:\\windows')], alwaysValid);
|
||||
expect(result[0].isDuplicate).toBe(false);
|
||||
expect(result[1].isDuplicate).toBe(true);
|
||||
});
|
||||
|
||||
it('识别环境变量路径', () => {
|
||||
const result = analyzePaths([pe('C:\\Normal'), pe('%JAVA_HOME%\\bin')], alwaysValid);
|
||||
expect(result[0].isEnvVar).toBe(false);
|
||||
expect(result[1].isEnvVar).toBe(true);
|
||||
});
|
||||
|
||||
it('标记无效路径', () => {
|
||||
const result = analyzePaths([pe('C:\\Valid'), pe('C:\\Invalid')], validateFn);
|
||||
expect(result[0].isValid).toBe(true);
|
||||
expect(result[1].isValid).toBe(false);
|
||||
});
|
||||
|
||||
it('空数组返回空', () => {
|
||||
const result = analyzePaths([], alwaysValid);
|
||||
expect(result).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('pathClean', () => {
|
||||
it('移除无效路径', () => {
|
||||
const [kept, removed] = pathClean(
|
||||
@@ -28,12 +53,25 @@ 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);
|
||||
|
||||
@@ -146,6 +146,26 @@ 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++) {
|
||||
@@ -206,4 +226,32 @@ 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,4 +1,3 @@
|
||||
/** @vitest-environment jsdom */
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
|
||||
// ── Mock 外部依赖 ──
|
||||
|
||||
+2
-1
@@ -2,6 +2,7 @@
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
{ "path": "./tsconfig.node.json" },
|
||||
{ "path": "./tsconfig.test.json" }
|
||||
]
|
||||
}
|
||||
|
||||
+4
-6
@@ -8,17 +8,15 @@ export default defineConfig({
|
||||
},
|
||||
},
|
||||
test: {
|
||||
environment: 'jsdom',
|
||||
exclude: ['e2e/**', 'node_modules/**', 'gui/**'],
|
||||
coverage: {
|
||||
provider: 'v8',
|
||||
reporter: ['text', 'lcov', 'cobertura'],
|
||||
include: ['src/**/*.{ts,tsx}'],
|
||||
exclude: ['src/main.tsx', 'src/vite-env.d.ts', '**/*.test.{ts,tsx}', '**/*.spec.{ts,tsx}'],
|
||||
include: ['src/core/**', 'src/store/**', 'src/hooks/**'],
|
||||
exclude: ['src/main.tsx', 'src/vite-env.d.ts'],
|
||||
thresholds: {
|
||||
branches: 60,
|
||||
functions: 60,
|
||||
lines: 70,
|
||||
statements: 70,
|
||||
lines: 80,
|
||||
},
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user