add logger

This commit is contained in:
Julian Freeman
2026-03-14 20:55:46 -04:00
parent db20a31643
commit cdeb52c316
8 changed files with 348 additions and 54 deletions

View File

@@ -1,6 +1,8 @@
use serde::{Deserialize, Serialize};
use std::process::Command;
use std::os::windows::process::CommandExt;
use tauri::AppHandle;
use crate::emit_log;
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct Software {
@@ -23,30 +25,60 @@ struct WingetPackage {
pub available_versions: Option<Vec<String>>,
}
pub fn ensure_winget_dependencies() -> Result<(), String> {
// 确保执行权限和模块存在
pub fn ensure_winget_dependencies(handle: &AppHandle) -> Result<(), String> {
emit_log(handle, "Check Environment", "Checking Winget and Microsoft.WinGet.Client...", "info");
let setup_script = r#"
$ErrorActionPreference = 'SilentlyContinue'
$ErrorActionPreference = 'Stop'
Write-Output "Step 1: Enabling TLS 1.2"
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12
Write-Output "Step 2: Installing NuGet provider"
Install-PackageProvider -Name NuGet -MinimumVersion 2.8.5.201 -Force -Confirm:$false
Write-Output "Step 3: Trusting PSGallery"
Set-PSRepository -Name 'PSGallery' -InstallationPolicy Trusted
Write-Output "Step 4: Setting Execution Policy"
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
Write-Output "Step 5: Installing Microsoft.WinGet.Client module"
Install-Module -Name Microsoft.WinGet.Client -Force -AllowClobber -Scope CurrentUser -Confirm:$false
} else {
Write-Output "Step 5: Module already installed"
}
"#;
let _ = Command::new("powershell")
let output = Command::new("powershell")
.args(["-NoProfile", "-Command", setup_script])
.creation_flags(0x08000000)
.status();
.output();
Ok(())
match output {
Ok(out) => {
let msg = String::from_utf8_lossy(&out.stdout).to_string();
let err = String::from_utf8_lossy(&out.stderr).to_string();
if out.status.success() {
emit_log(handle, "Environment Setup", &format!("Success: {}", msg), "success");
Ok(())
} else {
emit_log(handle, "Environment Setup Error", &format!("OUT: {}\nERR: {}", msg, err), "error");
Err(format!("Setup failed: {}", err))
}
},
Err(e) => {
emit_log(handle, "Environment Setup Fatal", &e.to_string(), "error");
Err(e.to_string())
}
}
}
pub fn list_all_software() -> Vec<Software> {
// 使用更健壮的脚本获取 JSON
pub fn list_all_software(handle: &AppHandle) -> Vec<Software> {
let script = r#"
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = 'SilentlyContinue'
Import-Module Microsoft.WinGet.Client -ErrorAction SilentlyContinue
Import-Module Microsoft.WinGet.Client
$pkgs = Get-WinGetPackage
if ($pkgs) {
$pkgs | ForEach-Object {
@@ -62,14 +94,14 @@ pub fn list_all_software() -> Vec<Software> {
}
"#;
execute_powershell(script)
execute_powershell(handle, "Get All Software", script)
}
pub fn list_updates() -> Vec<Software> {
pub fn list_updates(handle: &AppHandle) -> Vec<Software> {
let script = r#"
$OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
$ErrorActionPreference = 'SilentlyContinue'
Import-Module Microsoft.WinGet.Client -ErrorAction SilentlyContinue
Import-Module Microsoft.WinGet.Client
$pkgs = Get-WinGetPackage | Where-Object { $_.IsUpdateAvailable }
if ($pkgs) {
$pkgs | ForEach-Object {
@@ -85,10 +117,12 @@ pub fn list_updates() -> Vec<Software> {
}
"#;
execute_powershell(script)
execute_powershell(handle, "Get Updates", script)
}
fn execute_powershell(script: &str) -> Vec<Software> {
fn execute_powershell(handle: &AppHandle, cmd_name: &str, script: &str) -> Vec<Software> {
emit_log(handle, cmd_name, "Executing PowerShell script...", "info");
let output = Command::new("powershell")
.args(["-NoProfile", "-Command", script])
.creation_flags(0x08000000)
@@ -97,29 +131,37 @@ fn execute_powershell(script: &str) -> Vec<Software> {
match output {
Ok(out) => {
let stdout = String::from_utf8_lossy(&out.stdout);
// 移除可能存在的 UTF-8 BOM
let stderr = String::from_utf8_lossy(&out.stderr);
let clean_json = stdout.trim_start_matches('\u{feff}').trim();
parse_json_output(clean_json.to_string())
if !out.status.success() || !stderr.is_empty() {
emit_log(handle, &format!("{} stderr", cmd_name), &stderr, "error");
}
if clean_json.is_empty() || clean_json == "[]" {
emit_log(handle, cmd_name, "No software found (Empty JSON)", "info");
return vec![];
}
let result = parse_json_output(clean_json.to_string());
emit_log(handle, cmd_name, &format!("Success: found {} items", result.len()), "success");
result
},
Err(e) => {
emit_log(handle, cmd_name, &format!("Execution error: {}", e), "error");
vec![]
},
Err(_) => vec![],
}
}
// 修正Rust 并没有 .length(),应使用 .len()
fn parse_json_output(json_str: String) -> Vec<Software> {
if json_str.is_empty() || json_str == "[]" {
return vec![];
}
// 尝试解析数组
if let Ok(packages) = serde_json::from_str::<Vec<WingetPackage>>(&json_str) {
return packages.into_iter().map(map_package).collect();
}
// 尝试解析单个对象
if let Ok(package) = serde_json::from_str::<WingetPackage>(&json_str) {
return vec![map_package(package)];
}
vec![]
}