feat: 完成后清理进度文件,并支持迁移数据目录
This commit is contained in:
@@ -0,0 +1,296 @@
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
const RETRY_WAITS_MS: [u64; 5] = [0, 100, 300, 800, 1500];
|
||||
|
||||
pub fn check_target(source: &Path, target: &Path) -> Result<(), String> {
|
||||
if !target.is_absolute() {
|
||||
return Err("数据目录必须是绝对路径".into());
|
||||
}
|
||||
if same_path(source, target) {
|
||||
return Err("已经是当前数据目录".into());
|
||||
}
|
||||
if !source.is_dir() {
|
||||
return Err("当前数据目录不存在".into());
|
||||
}
|
||||
if within(target, source) || within(source, target) {
|
||||
return Err("不能选在当前数据目录里面,也不能选它的上级".into());
|
||||
}
|
||||
if target.exists() && !target.is_dir() {
|
||||
return Err("请选择文件夹".into());
|
||||
}
|
||||
if target.exists() && !is_empty_dir(target)? {
|
||||
return Err("请选择一个空文件夹".into());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn relocate_children(source: &Path, target: &Path, pointer: &Path) -> Result<(), String> {
|
||||
check_target(source, target)?;
|
||||
fs::create_dir_all(target).map_err(|error| format!("无法创建数据目录:{error}"))?;
|
||||
if !is_empty_dir(target)? {
|
||||
return Err("请选择一个空文件夹".into());
|
||||
}
|
||||
let entries = list_entries(source, pointer)?;
|
||||
if same_volume(source, target) {
|
||||
match rename_all(&entries, target) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(MoveError::CrossDevice) => copy_then_remove(&entries, target),
|
||||
Err(MoveError::Message(message)) => Err(message),
|
||||
}
|
||||
} else {
|
||||
copy_then_remove(&entries, target)
|
||||
}
|
||||
}
|
||||
|
||||
fn list_entries(source: &Path, pointer: &Path) -> Result<Vec<PathBuf>, String> {
|
||||
let read = fs::read_dir(source).map_err(|error| format!("无法读取数据目录:{error}"))?;
|
||||
let mut entries = Vec::new();
|
||||
for item in read {
|
||||
let item = item.map_err(|error| format!("无法读取数据目录:{error}"))?;
|
||||
let path = item.path();
|
||||
if same_path(&path, pointer) || skip_name(&item.file_name()) {
|
||||
continue;
|
||||
}
|
||||
entries.push(path);
|
||||
}
|
||||
entries.sort();
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn skip_name(name: &std::ffi::OsStr) -> bool {
|
||||
name == "backend.lock" || name == "data-root.txt" || name == ".nqi-data-root"
|
||||
}
|
||||
|
||||
fn rename_all(entries: &[PathBuf], target: &Path) -> Result<(), MoveError> {
|
||||
let mut moved = Vec::new();
|
||||
for source in entries {
|
||||
let dest = target.join(name_of(source).map_err(MoveError::Message)?);
|
||||
if let Err(error) = rename_retry(source, &dest) {
|
||||
undo_renames(&moved);
|
||||
return Err(error);
|
||||
}
|
||||
moved.push((dest, source.clone()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn undo_renames(moved: &[(PathBuf, PathBuf)]) {
|
||||
for (dest, source) in moved.iter().rev() {
|
||||
let _ = rename_retry(dest, source);
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_then_remove(entries: &[PathBuf], target: &Path) -> Result<(), String> {
|
||||
let mut copied: Vec<PathBuf> = Vec::new();
|
||||
for source in entries {
|
||||
let dest = target.join(name_of(source)?);
|
||||
if let Err(error) = copy_path(source, &dest) {
|
||||
for path in copied.iter().rev() {
|
||||
let _ = remove_path(path);
|
||||
}
|
||||
return Err(error);
|
||||
}
|
||||
copied.push(dest);
|
||||
}
|
||||
for source in entries {
|
||||
if let Err(error) = remove_path(source) {
|
||||
restore_sources(entries, target);
|
||||
return Err(error);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn restore_sources(entries: &[PathBuf], target: &Path) {
|
||||
for source in entries {
|
||||
let Ok(name) = name_of(source) else {
|
||||
continue;
|
||||
};
|
||||
let dest = target.join(name);
|
||||
if source.exists() {
|
||||
let _ = remove_path(&dest);
|
||||
continue;
|
||||
}
|
||||
if dest.exists() {
|
||||
let _ = transfer_back(&dest, source);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn transfer_back(from: &Path, to: &Path) -> Result<(), String> {
|
||||
match rename_retry(from, to) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(MoveError::CrossDevice) => copy_path(from, to).and_then(|_| remove_path(from)),
|
||||
Err(MoveError::Message(message)) => Err(message),
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_path(from: &Path, to: &Path) -> Result<(), String> {
|
||||
let meta = fs::symlink_metadata(from).map_err(|error| format!("无法读取 {from}: {error}", from = from.display()))?;
|
||||
if meta.file_type().is_symlink() {
|
||||
return Err(format!("数据目录里有链接,无法迁移:{}", from.display()));
|
||||
}
|
||||
if meta.is_dir() {
|
||||
fs::create_dir_all(to).map_err(|error| format!("无法创建 {to}: {error}", to = to.display()))?;
|
||||
let read = fs::read_dir(from).map_err(|error| format!("无法读取 {from}: {error}", from = from.display()))?;
|
||||
for item in read {
|
||||
let item = item.map_err(|error| format!("无法读取 {from}: {error}", from = from.display()))?;
|
||||
copy_path(&item.path(), &to.join(item.file_name()))?;
|
||||
}
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(parent) = to.parent() {
|
||||
fs::create_dir_all(parent).map_err(|error| format!("无法创建 {parent}: {error}", parent = parent.display()))?;
|
||||
}
|
||||
let copied = fs::copy(from, to).map_err(|error| format!("无法复制 {from}: {error}", from = from.display()))?;
|
||||
if copied != meta.len() {
|
||||
let _ = fs::remove_file(to);
|
||||
return Err(format!("复制不完整:{}", from.display()));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn rename_retry(from: &Path, to: &Path) -> Result<(), MoveError> {
|
||||
let mut last = String::new();
|
||||
for wait_ms in RETRY_WAITS_MS {
|
||||
if wait_ms > 0 {
|
||||
thread::sleep(Duration::from_millis(wait_ms));
|
||||
}
|
||||
match fs::rename(from, to) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(error) if is_cross_device(&error) => return Err(MoveError::CrossDevice),
|
||||
Err(error) if denied(&error) => last = error.to_string(),
|
||||
Err(error) => return Err(MoveError::Message(format!("无法移动 {from}: {error}", from = from.display()))),
|
||||
}
|
||||
}
|
||||
Err(MoveError::Message(format!("文件被占用,无法移动 {from}:{last}", from = from.display())))
|
||||
}
|
||||
|
||||
fn remove_path(path: &Path) -> Result<(), String> {
|
||||
let mut last = String::new();
|
||||
for wait_ms in RETRY_WAITS_MS {
|
||||
if wait_ms > 0 {
|
||||
thread::sleep(Duration::from_millis(wait_ms));
|
||||
}
|
||||
let result = if path.is_dir() {
|
||||
fs::remove_dir_all(path)
|
||||
} else {
|
||||
fs::remove_file(path)
|
||||
};
|
||||
match result {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(()),
|
||||
Err(error) if denied(&error) => last = error.to_string(),
|
||||
Err(error) => return Err(format!("无法删除 {path}: {error}", path = path.display())),
|
||||
}
|
||||
}
|
||||
Err(format!("文件被占用,无法删除 {path}:{last}", path = path.display()))
|
||||
}
|
||||
|
||||
fn name_of(path: &Path) -> Result<&std::ffi::OsStr, String> {
|
||||
path.file_name()
|
||||
.ok_or_else(|| format!("无法识别 {}", path.display()))
|
||||
}
|
||||
|
||||
fn is_empty_dir(path: &Path) -> Result<bool, String> {
|
||||
let read = fs::read_dir(path).map_err(|error| format!("无法读取目标文件夹:{error}"))?;
|
||||
for item in read {
|
||||
let item = item.map_err(|error| format!("无法读取目标文件夹:{error}"))?;
|
||||
if skip_name(&item.file_name()) {
|
||||
continue;
|
||||
}
|
||||
return Ok(false);
|
||||
}
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
fn same_volume(left: &Path, right: &Path) -> bool {
|
||||
volume_key(left) == volume_key(right)
|
||||
}
|
||||
|
||||
fn volume_key(path: &Path) -> Option<String> {
|
||||
path.components()
|
||||
.next()
|
||||
.map(|part| part.as_os_str().to_string_lossy().to_lowercase())
|
||||
}
|
||||
|
||||
fn same_path(left: &Path, right: &Path) -> bool {
|
||||
norm(left) == norm(right)
|
||||
}
|
||||
|
||||
fn within(child: &Path, parent: &Path) -> bool {
|
||||
if same_path(child, parent) {
|
||||
return false;
|
||||
}
|
||||
let child_text = norm(child);
|
||||
let parent_text = norm(parent).trim_end_matches(['\\', '/']).to_string();
|
||||
child_text.starts_with(&format!("{parent_text}\\")) || child_text.starts_with(&format!("{parent_text}/"))
|
||||
}
|
||||
|
||||
fn norm(path: &Path) -> String {
|
||||
path.to_string_lossy().replace('/', "\\").trim_end_matches('\\').to_lowercase()
|
||||
}
|
||||
|
||||
fn denied(error: &io::Error) -> bool {
|
||||
matches!(error.raw_os_error(), Some(5 | 32 | 33)) || error.kind() == io::ErrorKind::PermissionDenied
|
||||
}
|
||||
|
||||
fn is_cross_device(error: &io::Error) -> bool {
|
||||
matches!(error.raw_os_error(), Some(17 | 18))
|
||||
}
|
||||
|
||||
enum MoveError {
|
||||
CrossDevice,
|
||||
Message(String),
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn scratch(name: &str) -> PathBuf {
|
||||
let path = std::env::temp_dir().join(format!("nqi-move-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&path);
|
||||
fs::create_dir_all(&path).unwrap();
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn moves_children_and_leaves_the_pointer() {
|
||||
let root = scratch("move");
|
||||
let source = root.join("data");
|
||||
let target = root.join("next");
|
||||
fs::create_dir_all(source.join("jobs").join("1")).unwrap();
|
||||
fs::write(source.join("jobs").join("1").join("job.json"), b"{}").unwrap();
|
||||
fs::write(source.join("settings.json"), b"{\"showTray\":true}").unwrap();
|
||||
let pointer = source.join("data-root.txt");
|
||||
fs::write(&pointer, b"old\n").unwrap();
|
||||
fs::create_dir_all(&target).unwrap();
|
||||
relocate_children(&source, &target, &pointer).unwrap();
|
||||
assert!(target.join("jobs").join("1").join("job.json").is_file());
|
||||
assert!(target.join("settings.json").is_file());
|
||||
assert!(!target.join("data-root.txt").exists());
|
||||
assert!(pointer.is_file());
|
||||
assert!(!source.join("jobs").exists());
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_a_folder_that_already_has_files() {
|
||||
let root = scratch("busy");
|
||||
let source = root.join("data");
|
||||
let target = root.join("next");
|
||||
fs::create_dir_all(&source).unwrap();
|
||||
fs::write(source.join("settings.json"), b"{}").unwrap();
|
||||
fs::create_dir_all(&target).unwrap();
|
||||
fs::write(target.join("keep.txt"), b"x").unwrap();
|
||||
let error = relocate_children(&source, &target, &root.join("pointer.txt")).unwrap_err();
|
||||
assert_eq!(error, "请选择一个空文件夹");
|
||||
assert!(source.join("settings.json").is_file());
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
use std::net::TcpListener;
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
|
||||
@@ -7,6 +7,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use tauri::{Emitter, Manager};
|
||||
|
||||
mod datadir;
|
||||
#[cfg(windows)]
|
||||
mod job;
|
||||
mod tray;
|
||||
@@ -74,6 +75,59 @@ fn backend_info() -> BackendInfo {
|
||||
snapshot(&mut state)
|
||||
}
|
||||
|
||||
fn wait_ready(port: u16) {
|
||||
for _ in 0..50 {
|
||||
if TcpStream::connect(("127.0.0.1", port)).is_ok() {
|
||||
return;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn migrate_data_dir(app: tauri::AppHandle, target: String) -> BackendInfo {
|
||||
let _guard = lock_launch();
|
||||
let chosen = PathBuf::from(target.trim());
|
||||
let source = resolve_data_dir(&app);
|
||||
if let Err(message) = datadir::check_target(&source, &chosen) {
|
||||
let mut state = lock_backend();
|
||||
let mut info = snapshot(&mut state);
|
||||
info.error = Some(message);
|
||||
return info;
|
||||
}
|
||||
let mut state = lock_backend();
|
||||
stop_child(&mut state);
|
||||
prepare(&app, &mut state);
|
||||
let port = state.port;
|
||||
drop(state);
|
||||
let moved = datadir::relocate_children(&source, &chosen, &pointer_path(&app));
|
||||
if let Err(message) = moved {
|
||||
let mut state = lock_backend();
|
||||
spawn_child(&app, &mut state);
|
||||
wait_ready(port);
|
||||
let mut info = snapshot(&mut state);
|
||||
if info.error.is_none() {
|
||||
info.error = Some(message);
|
||||
}
|
||||
return info;
|
||||
}
|
||||
if let Err(message) = write_pointer(&pointer_path(&app), &chosen) {
|
||||
let _ = datadir::relocate_children(&chosen, &source, &pointer_path(&app));
|
||||
let mut state = lock_backend();
|
||||
spawn_child(&app, &mut state);
|
||||
wait_ready(port);
|
||||
let mut info = snapshot(&mut state);
|
||||
if info.error.is_none() {
|
||||
info.error = Some(message);
|
||||
}
|
||||
return info;
|
||||
}
|
||||
let mut state = lock_backend();
|
||||
spawn_child(&app, &mut state);
|
||||
wait_ready(port);
|
||||
snapshot(&mut state)
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn restart_backend(app: tauri::AppHandle) -> BackendInfo {
|
||||
let _guard = lock_launch();
|
||||
@@ -188,6 +242,48 @@ fn bundled_backend(app: &tauri::AppHandle) -> Option<PathBuf> {
|
||||
None
|
||||
}
|
||||
|
||||
fn pointer_path(app: &tauri::AppHandle) -> PathBuf {
|
||||
if cfg!(debug_assertions) {
|
||||
if let Some(root) = repo_root() {
|
||||
return root.join(".nqi-data-root");
|
||||
}
|
||||
}
|
||||
installed_data_dir(app).join("data-root.txt")
|
||||
}
|
||||
|
||||
fn default_data_dir(app: &tauri::AppHandle) -> PathBuf {
|
||||
if cfg!(debug_assertions) {
|
||||
if let Some(root) = repo_root() {
|
||||
return root.join("data");
|
||||
}
|
||||
}
|
||||
installed_data_dir(app)
|
||||
}
|
||||
|
||||
fn read_pointer(path: &Path) -> Option<PathBuf> {
|
||||
let text = std::fs::read_to_string(path).ok()?;
|
||||
let chosen = PathBuf::from(text.trim());
|
||||
if chosen.is_absolute() && chosen.is_dir() {
|
||||
Some(chosen)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
fn write_pointer(path: &Path, target: &Path) -> Result<(), String> {
|
||||
if let Some(parent) = path.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|error| format!("无法记住数据目录:{error}"))?;
|
||||
}
|
||||
std::fs::write(path, format!("{}\n", target.display())).map_err(|error| format!("无法记住数据目录:{error}"))
|
||||
}
|
||||
|
||||
fn resolve_data_dir(app: &tauri::AppHandle) -> PathBuf {
|
||||
if let Some(path) = read_pointer(&pointer_path(app)) {
|
||||
return path;
|
||||
}
|
||||
default_data_dir(app)
|
||||
}
|
||||
|
||||
fn installed_data_dir(app: &tauri::AppHandle) -> PathBuf {
|
||||
let folder = app.config().identifier.clone();
|
||||
if let Ok(appdata) = std::env::var("APPDATA") {
|
||||
@@ -216,7 +312,7 @@ fn launch_plan(app: &tauri::AppHandle, port: u16) -> Option<Launch> {
|
||||
program,
|
||||
args: Vec::new(),
|
||||
cwd,
|
||||
data_dir: installed_data_dir(app),
|
||||
data_dir: resolve_data_dir(app),
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -242,7 +338,7 @@ fn launch_plan(app: &tauri::AppHandle, port: u16) -> Option<Launch> {
|
||||
"--no-access-log".into(),
|
||||
],
|
||||
cwd: repo.join("backend"),
|
||||
data_dir: repo.join("data"),
|
||||
data_dir: resolve_data_dir(app),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -441,6 +537,7 @@ pub fn run() {
|
||||
backend_port,
|
||||
backend_info,
|
||||
restart_backend,
|
||||
migrate_data_dir,
|
||||
set_close_guard,
|
||||
close_app,
|
||||
write_sample_csv,
|
||||
|
||||
Reference in New Issue
Block a user