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

@@ -26,35 +26,25 @@ struct WingetPackage {
}
pub fn ensure_winget_dependencies(handle: &AppHandle) -> Result<(), String> {
emit_log(handle, "Check Environment", "Performing fast environment check...", "info");
let log_id = "env-check";
emit_log(handle, log_id, "Environment Check", "Starting system configuration...", "info");
// 优化后的脚本:先尝试极速检测,存在则直接退出
let setup_script = r#"
$ErrorActionPreference = 'SilentlyContinue'
# 极速路径:如果模块已安装,直接输出 Success 并退出
Write-Output "Checking module status..."
if (Get-Module -ListAvailable Microsoft.WinGet.Client) {
Write-Output "ALREADY_READY"
exit 0
}
# 慢速路径:仅在模块缺失时执行完整初始化
Write-Output "CONFIGURING_ENV"
Write-Output "Step 1: Enabling TLS 1.2"
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
Import-Module PackageManagement -ErrorAction SilentlyContinue
if ($null -eq (Get-PackageProvider -Name NuGet -ErrorAction SilentlyContinue)) {
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Confirm:$false
}
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
Set-ExecutionPolicy -ExecutionPolicy RemoteSigned -Scope CurrentUser -Force
if (-not (Get-Module -ListAvailable Microsoft.WinGet.Client)) {
Install-Module -Name Microsoft.WinGet.Client -Force -AllowClobber -Scope CurrentUser -Confirm:$false
}
# 注意:此处不再执行 winget source update因为它太慢了移至后台或按需执行
Install-Module -Name Microsoft.WinGet.Client -Force -AllowClobber -Scope CurrentUser -Confirm:$false
"#;
let output = Command::new("powershell")
@@ -65,34 +55,35 @@ pub fn ensure_winget_dependencies(handle: &AppHandle) -> Result<(), String> {
match output {
Ok(out) => {
let stdout = String::from_utf8_lossy(&out.stdout).to_string();
emit_log(handle, log_id, "", &stdout, "info");
if stdout.contains("ALREADY_READY") {
emit_log(handle, "Environment Setup", "Fast check passed: System is ready.", "success");
emit_log(handle, log_id, "Result", "Ready (Fast check).", "success");
Ok(())
} else {
// 验证安装结果
let check = Command::new("powershell")
.args(["-NoProfile", "-Command", "Get-Module -ListAvailable Microsoft.WinGet.Client"])
.creation_flags(0x08000000)
.output();
if check.map(|o| !o.stdout.is_empty()).unwrap_or(false) {
emit_log(handle, "Environment Setup", "Full configuration successful.", "success");
emit_log(handle, log_id, "Result", "Module installed successfully.", "success");
Ok(())
} else {
let err = String::from_utf8_lossy(&out.stderr).to_string();
emit_log(handle, "Environment Setup Error", &format!("STDOUT: {}\nSTDERR: {}", stdout, err), "error");
emit_log(handle, log_id, "Result", "Module installation failed.", "error");
Err("Setup failed".to_string())
}
}
},
Err(e) => {
emit_log(handle, "Environment Setup Fatal", &e.to_string(), "error");
emit_log(handle, log_id, "Fatal Error", &e.to_string(), "error");
Err(e.to_string())
}
}
}
pub fn list_all_software(handle: &AppHandle) -> Vec<Software> {
let log_id = format!("list-all-{}", chrono::Local::now().timestamp_millis());
let script = r#"
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = 'SilentlyContinue'
@@ -112,18 +103,15 @@ pub fn list_all_software(handle: &AppHandle) -> Vec<Software> {
}
"#;
execute_powershell(handle, "Get All Software", script)
execute_powershell(handle, &log_id, "Fetch All Software", script)
}
pub fn list_updates(handle: &AppHandle) -> Vec<Software> {
let log_id = format!("list-updates-{}", chrono::Local::now().timestamp_millis());
let script = r#"
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = 'SilentlyContinue'
Import-Module Microsoft.WinGet.Client -ErrorAction SilentlyContinue
# 在检查更新前,尝试静默更新源(可选,为了准确性)
# winget source update --accept-source-agreements | Out-Null
$pkgs = Get-WinGetPackage -ErrorAction SilentlyContinue | Where-Object { $_.IsUpdateAvailable }
if ($pkgs) {
$pkgs | ForEach-Object {
@@ -139,11 +127,11 @@ pub fn list_updates(handle: &AppHandle) -> Vec<Software> {
}
"#;
execute_powershell(handle, "Get Updates", script)
execute_powershell(handle, &log_id, "Fetch Updates", script)
}
fn execute_powershell(handle: &AppHandle, cmd_name: &str, script: &str) -> Vec<Software> {
emit_log(handle, cmd_name, "Executing PowerShell script...", "info");
fn execute_powershell(handle: &AppHandle, log_id: &str, cmd_title: &str, script: &str) -> Vec<Software> {
emit_log(handle, log_id, cmd_title, "Executing PowerShell...", "info");
let output = Command::new("powershell")
.args(["-NoProfile", "-Command", script])
@@ -157,20 +145,20 @@ fn execute_powershell(handle: &AppHandle, cmd_name: &str, script: &str) -> Vec<S
let clean_json = stdout.trim_start_matches('\u{feff}').trim();
if !out.status.success() && !stderr.is_empty() {
emit_log(handle, &format!("{} stderr", cmd_name), &stderr, "error");
emit_log(handle, log_id, "", &format!("STDERR: {}", stderr), "error");
}
if clean_json.is_empty() || clean_json == "[]" {
emit_log(handle, cmd_name, "No data returned.", "info");
emit_log(handle, log_id, "Result", "No software found.", "info");
return vec![];
}
let result = parse_json_output(clean_json.to_string());
emit_log(handle, cmd_name, &format!("Success: found {} items", result.len()), "success");
emit_log(handle, log_id, "Result", &format!("Successfully parsed {} items.", result.len()), "success");
result
},
Err(e) => {
emit_log(handle, cmd_name, &format!("Execution error: {}", e), "error");
emit_log(handle, log_id, "Execution Error", &e.to_string(), "error");
vec![]
},
}