fix logger bug

This commit is contained in:
Julian Freeman
2026-03-14 22:17:55 -04:00
parent 569b13d820
commit 9803ec67ca
6 changed files with 178 additions and 85 deletions

View File

@@ -1,12 +1,14 @@
pub mod winget;
use std::fs;
use std::process::Command;
use std::process::{Command, Stdio};
use std::os::windows::process::CommandExt;
use std::io::{BufRead, BufReader};
use tokio::sync::mpsc;
use tauri::{AppHandle, Manager, State, Emitter};
use serde::Serialize;
use winget::{Software, list_all_software, list_updates, ensure_winget_dependencies};
use regex::Regex;
struct AppState {
install_tx: mpsc::Sender<String>,
@@ -14,15 +16,17 @@ struct AppState {
#[derive(Clone, Serialize)]
pub struct LogPayload {
pub id: String,
pub timestamp: String,
pub command: String,
pub output: String,
pub status: String,
}
pub fn emit_log(handle: &AppHandle, command: &str, output: &str, status: &str) {
pub fn emit_log(handle: &AppHandle, id: &str, command: &str, output: &str, status: &str) {
let now = chrono::Local::now().format("%H:%M:%S").to_string();
let _ = handle.emit("log-event", LogPayload {
id: id.to_string(),
timestamp: now,
command: command.to_string(),
output: output.to_string(),
@@ -32,7 +36,6 @@ pub fn emit_log(handle: &AppHandle, command: &str, output: &str, status: &str) {
#[tauri::command]
async fn initialize_app(app: AppHandle) -> Result<bool, String> {
// 执行耗时的环境配置
tokio::task::spawn_blocking(move || {
ensure_winget_dependencies(&app).map(|_| true)
}).await.unwrap_or(Err("Initialization Task Panicked".to_string()))
@@ -112,49 +115,102 @@ pub fn run() {
let (tx, mut rx) = mpsc::channel::<String>(100);
app.manage(AppState { install_tx: tx });
// 移除了在 setup 中直接执行异步 init 的逻辑,改为由前端指令触发
let init_handle = handle.clone();
tauri::async_runtime::spawn(async move {
let _ = tokio::task::spawn_blocking(move || {
let _ = ensure_winget_dependencies(&init_handle);
}).await;
});
// 安装队列处理器
tauri::async_runtime::spawn(async move {
let perc_re = Regex::new(r"(\d+)\s*%").unwrap();
let size_re = Regex::new(r"([\d\.]+)\s*[a-zA-Z]+\s*/\s*([\d\.]+)\s*[a-zA-Z]+").unwrap();
while let Some(id) = rx.recv().await {
let log_id = format!("install-{}", id);
let _ = handle.emit("install-status", InstallProgress {
id: id.clone(),
status: "installing".to_string(),
progress: 0.5,
progress: 0.0,
});
emit_log(&handle, &format!("winget install --id {}", id), "Starting installation...", "info");
emit_log(&handle, &log_id, &format!("Winget Install: {}", id), "Starting...", "info");
let id_for_cmd = id.clone();
let h = handle.clone();
let status_result = tokio::task::spawn_blocking(move || {
let output = Command::new("winget")
.args([
"install", "--id", &id_for_cmd, "-e", "--silent",
"--accept-package-agreements", "--accept-source-agreements",
"--disable-interactivity"
])
.creation_flags(0x08000000)
.output();
let child = Command::new("winget")
.args([
"install", "--id", &id_for_cmd, "-e", "--silent",
"--accept-package-agreements", "--accept-source-agreements",
"--disable-interactivity"
])
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.creation_flags(0x08000000)
.spawn();
match output {
Ok(out) => {
let msg = String::from_utf8_lossy(&out.stdout).to_string();
let err = String::from_utf8_lossy(&out.stderr).to_string();
emit_log(&h, &format!("Install result for {}", id_for_cmd), &format!("OUT: {}\nERR: {}", msg, err), if out.status.success() { "success" } else { "error" });
if out.status.success() { "success" } else { "error" }
},
Err(e) => {
emit_log(&h, &format!("Install error for {}", id_for_cmd), &e.to_string(), "error");
"error"
},
let status_result = match child {
Ok(mut child_proc) => {
if let Some(stdout) = child_proc.stdout.take() {
let reader = BufReader::new(stdout);
for line_res in reader.split(b'\r') {
if let Ok(line_bytes) = line_res {
let line_str = String::from_utf8_lossy(&line_bytes).to_string();
let clean_line = line_str.trim();
if clean_line.is_empty() { continue; }
let mut is_progress = false;
if let Some(caps) = perc_re.captures(clean_line) {
if let Ok(p_val) = caps[1].parse::<f32>() {
let _ = h.emit("install-status", InstallProgress {
id: id_for_cmd.clone(),
status: "installing".to_string(),
progress: p_val / 100.0,
});
is_progress = true;
}
}
else if let Some(caps) = size_re.captures(clean_line) {
let current = caps[1].parse::<f32>().unwrap_or(0.0);
let total = caps[2].parse::<f32>().unwrap_or(1.0);
if total > 0.0 {
let _ = h.emit("install-status", InstallProgress {
id: id_for_cmd.clone(),
status: "installing".to_string(),
progress: (current / total).min(1.0),
});
is_progress = true;
}
}
if !is_progress {
// 追加内容到同一个日志卡片
emit_log(&h, &log_id, "", clean_line, "info");
}
}
}
}
let exit_status = child_proc.wait().map(|s| s.success()).unwrap_or(false);
if exit_status { "success" } else { "error" }
},
Err(e) => {
emit_log(&h, &log_id, "Fatal Error", &e.to_string(), "error");
"error"
}
}).await.unwrap_or("error");
};
let _ = handle.emit("install-status", InstallProgress {
id: id.clone(),
status: status_result.to_string(),
progress: 1.0,
});
emit_log(&handle, &log_id, "Result", &format!("Execution finished: {}", status_result), if status_result == "success" { "success" } else { "error" });
}
});