Files
Thing/src-tauri/src/diff/commands.rs
T

208 lines
8.6 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 对比模块的命令层。
//!
//! 三件事:读取一侧的文件、把一侧的内容写回、对比两棵目录树。文本级差异计算全在前端
//! (`@codemirror/merge`);目录级扫描在 [`super::scan`]。
//!
//! # 尺寸上限为什么要有两个
//!
//! - [`DIFF_LARGE_MB`]:**软**阈值。超过就置 `large`,前端据此关掉未变化段折叠等
//! 高开销特性 —— 文件照样完整读出来,只是更省。
//! - [`DIFF_HARD_LIMIT`]:**硬**上限。超过直接拒绝。对比窗口天生同时持有两侧内容
//! (不像编辑器只有一篇),单侧 16MB 已经是「两份都塞进 WebView + CM6 状态」的
//! 上限量级;再大不是「慢」而是「卡死」,早拒绝比让用户等一分钟再失败好。
use std::path::Path;
use std::time::{Duration, Instant};
use tauri::{AppHandle, Emitter, State};
use crate::editor::files;
use super::scan;
use super::types::{DiffFileDoc, DiffScanProgress, DiffSettings, DirDiffReport};
use super::DiffManager;
/// 「大文件」软阈值(MB)。与编辑器设置的默认值一致。
const DIFF_LARGE_MB: u32 = 5;
/// 硬上限(字节):单侧超过则拒绝读取。
const DIFF_HARD_LIMIT: u64 = 16 * 1024 * 1024;
/// 二进制探测的头部字节数。**与 `editor::grep` 的判据一致**(头部含 NUL 即二进制),
/// 否则会出现「搜索跳过了但对比工具显示了乱码」这种自相矛盾的行为。
const BINARY_SNIFF_BYTES: usize = 8 * 1024;
/// 打开文件并读出头部,同时判断是否二进制(头部含 NUL 字节)。
///
/// 返回**同一个已打开的句柄**(读位置停在头部之后)与那段头部:文本文件随后要靠这个
/// 句柄继续整读(见 `files::read_file_after_head`)—— 于是文件只被打开一次,也不会
/// 出现「嗅探时与整读时文件已被换掉」的窗口。二进制则到此为止,绝不整读。
fn open_with_head(path: &Path) -> Result<(std::fs::File, Vec<u8>, bool), String> {
use std::io::Read;
let mut file = std::fs::File::open(path).map_err(|e| format!("读取文件失败: {e}"))?;
let mut head = vec![0u8; BINARY_SNIFF_BYTES];
let read = file
.read(&mut head)
.map_err(|e| format!("读取文件失败: {e}"))?;
head.truncate(read);
let binary = head.contains(&0u8);
Ok((file, head, binary))
}
/// 写权限探测:以写模式打开但**不写入**(失败 → 只读)。
///
/// `editor::files` 里同名的函数是私有的(只服务编辑器自己的打开流程),这里重写一遍
/// 三行而不是把它提升为 `pub(crate)`:那个是模块内部细节,把它开放出去会让「谁在读
/// 权限探测」变得不清晰。
fn is_writable(path: &Path) -> bool {
std::fs::OpenOptions::new().write(true).open(path).is_ok()
}
/// 读取对比窗口某一侧的文件。
///
/// 复用 `editor::files::read_file`(编码探测 / 换行归一 / 只读探测),并顺带登记
/// 授权 —— 于是该文件随后可以被 [`diff_write_file`] 写回。
#[tauri::command]
#[specta::specta]
pub fn diff_read_file(path: String) -> Result<DiffFileDoc, String> {
let trimmed = path.trim();
if trimmed.is_empty() {
return Err("路径为空".to_string());
}
let p = Path::new(trimmed);
let meta = std::fs::metadata(p).map_err(|e| format!("读取文件信息失败: {e}"))?;
if meta.is_dir() {
return Err("这是一个目录 —— 请切到「文件夹」模式并把它设为某一侧".to_string());
}
if !meta.is_file() {
return Err("目标不是普通文件".to_string());
}
if meta.len() > DIFF_HARD_LIMIT {
return Err(format!(
"文件过大({} MB),超出对比窗口的 {} MB 上限",
meta.len() / (1024 * 1024),
DIFF_HARD_LIMIT / (1024 * 1024)
));
}
// 先读头部判断二进制(二进制到此为止、不整读),并把这段头部与**同一个句柄**
// 交给文本读取路径复用 —— 同一个文件全程只打开一次
let (file, head, binary) = open_with_head(p)?;
if binary {
return Ok(DiffFileDoc::binary_of(p, &meta, is_writable(p)));
}
let doc = files::read_file_after_head(file, p, &meta, &head, DIFF_LARGE_MB)?;
// 「打开过就能保存」:读取即登记授权(写回仍会再校验一次授权与写权限)
files::authorize(Path::new(&doc.path));
Ok(DiffFileDoc::from_file_doc(doc))
}
/// 把某一侧的内容写回磁盘。
///
/// `encoding` / `eol` 由前端回传**读取时探测到的值**,写回时原样还原 —— 一次「随手
/// 保存」不该把 GBK 文件变成 UTF-8、把 CRLF 变成 LF(那会在整个 diff 里掀起风暴)。
#[tauri::command]
#[specta::specta]
pub fn diff_write_file(
path: String,
content: String,
encoding: String,
eol: String,
) -> Result<DiffFileDoc, String> {
let doc = files::write_file(&path, &content, &encoding, &eol, DIFF_LARGE_MB)?;
Ok(DiffFileDoc::from_file_doc(doc))
}
/// 探测一个路径是文件还是目录(`"dir"` / `"file"` / `"missing"`)。
///
/// 用途:拖入或 `?path=` 传进来的路径前端拿不到文件系统元信息,而对比窗口需要据此
/// 决定「进文件模式还是目录模式」。**刻意不新增 Rust 侧的状态**:只读一次 `metadata`,
/// 不写盘、不需授权。
#[tauri::command]
#[specta::specta]
pub fn diff_path_kind(path: String) -> Result<String, String> {
let trimmed = path.trim();
if trimmed.is_empty() {
return Err("路径为空".to_string());
}
match std::fs::metadata(trimmed) {
Ok(meta) if meta.is_dir() => Ok("dir".to_string()),
Ok(meta) if meta.is_file() => Ok("file".to_string()),
Ok(_) => Ok("missing".to_string()),
Err(_) => Ok("missing".to_string()),
}
}
/// 对比两棵目录树(只读)。
///
/// `skip_dirs` 是**目录名**清单(大小写不敏感):默认清单由前端给出(它是界面约定,
/// 用户能否修改是 UI 的事),后端只负责按它执行 —— 同 `editor::grep` 把默认跳过清单
/// 留在前端的取舍。
///
/// 走 `spawn_blocking`:两遍目录遍历 + 最多 2000 次读盘都是同步阻塞 IO,放在 Tauri
/// 命令线程上会占住它(范式同 `editor_search_in_path`)。
///
/// `scan_id` 由前端生成并随进度事件原样回传:进度事件是全局的,多选项卡并发扫描时
/// 前端据此只认自己那一轮(见 `constants::events::DIFF_SCAN_PROGRESS`)。
#[tauri::command]
#[specta::specta]
pub async fn diff_compare_dirs(
app: AppHandle,
scan_id: u64,
left: String,
right: String,
skip_dirs: Vec<String>,
compare_content: bool,
) -> Result<DirDiffReport, String> {
tauri::async_runtime::spawn_blocking(move || {
// 进度按**时间**节流(≥120ms 才发一条):整棵树可能有上万个条目、上千次读盘,
// 逐条 emit 会把 IPC 打满;而按条目数节流在「条目少但每个都很大」时又会太稀。
// 最后一条进度由前端在命令返回时清掉,不依赖这里补齐。
let mut last_emit = Instant::now();
let mut progress = |phase: scan::ScanPhase, done: u64, total: u64| {
if last_emit.elapsed() < Duration::from_millis(120) {
return;
}
last_emit = Instant::now();
let phase = match phase {
scan::ScanPhase::Walk => "scan",
scan::ScanPhase::Compare => "compare",
};
let payload = DiffScanProgress {
scan_id,
phase: phase.to_string(),
done,
total,
};
let _ = app.emit(crate::constants::events::DIFF_SCAN_PROGRESS, payload);
};
scan::compare_dirs(&left, &right, &skip_dirs, compare_content, &mut progress)
})
.await
.map_err(|e| format!("目录对比任务失败: {e}"))?
}
/// 读取对比模块设置。
#[tauri::command]
#[specta::specta]
pub fn diff_get_settings(state: State<'_, DiffManager>) -> DiffSettings {
state.load_settings()
}
/// 保存对比模块设置。
///
/// 保存后**就地重注册**全局快捷键(`register_shortcut` 会先注销本模块的旧键,因此
/// 「清空快捷键」也能通过传空串生效)—— 同 `editor_save_settings`。
#[tauri::command]
#[specta::specta]
pub fn diff_save_settings(
app: AppHandle,
state: State<'_, DiffManager>,
settings: DiffSettings,
) -> Result<DiffSettings, String> {
let mut next = settings;
next.heal();
state.save_settings(&next)?;
state.init_on_launch(&app);
Ok(next)
}