diff --git a/MacUtilGUI.Tests/BrewClientTests.fs b/MacUtilGUI.Tests/BrewClientTests.fs index 65ac03d..4573d41 100644 --- a/MacUtilGUI.Tests/BrewClientTests.fs +++ b/MacUtilGUI.Tests/BrewClientTests.fs @@ -6,7 +6,8 @@ open MacUtilGUI.Services module BrewClientTests = - type FakeBrew(casks: string list, formulas: string list) = + type FakeBrew(casks: string list, formulas: string list, ?outdated: string list) = + let outdated = defaultArg outdated [] let calls = ResizeArray() member _.Calls = List.ofSeq calls @@ -19,13 +20,24 @@ module BrewClientTests = | _ -> false) |> Seq.toList + member _.UpgradeCalls = + calls + |> Seq.filter (fun args -> + match args with + | "upgrade" :: _ -> true + | _ -> false) + |> Seq.toList + member _.Exec(args: string list) = calls.Add args match args with | [ "list"; "--cask" ] -> 0, String.concat "\n" casks, "" | [ "list"; "--formula" ] -> 0, String.concat "\n" formulas, "" + | [ "outdated" ] + | [ "outdated"; "--verbose" ] -> 0, String.concat "\n" outdated, "" | "install" :: _ -> 0, "", "" + | "upgrade" :: _ -> 0, "", "" | _ -> 1, "", "unexpected brew args" let private vscode = diff --git a/MacUtilGUI.Tests/MacUtilGUI.Tests.fsproj b/MacUtilGUI.Tests/MacUtilGUI.Tests.fsproj index a7128ac..58fb4b0 100644 --- a/MacUtilGUI.Tests/MacUtilGUI.Tests.fsproj +++ b/MacUtilGUI.Tests/MacUtilGUI.Tests.fsproj @@ -13,6 +13,7 @@ + diff --git a/MacUtilGUI.Tests/MaintenanceTests.fs b/MacUtilGUI.Tests/MaintenanceTests.fs index 757d2e2..47e3669 100644 --- a/MacUtilGUI.Tests/MaintenanceTests.fs +++ b/MacUtilGUI.Tests/MaintenanceTests.fs @@ -21,6 +21,8 @@ module MaintenanceTests = | [ "update" ] -> 0, "Already up-to-date.", "" | [ "cleanup" ] -> 0, "", "" | [ "--cache" ] -> 0, cachePath, "" + | [ "outdated" ] + | [ "outdated"; "--verbose" ] -> 0, "", "" | _ -> 1, "", "unexpected brew args" let private catalog () = diff --git a/MacUtilGUI.Tests/UpdateServiceTests.fs b/MacUtilGUI.Tests/UpdateServiceTests.fs new file mode 100644 index 0000000..b5f453e --- /dev/null +++ b/MacUtilGUI.Tests/UpdateServiceTests.fs @@ -0,0 +1,195 @@ +namespace MacUtilGUI.Tests + +open System +open System.Diagnostics +open System.IO +open Xunit +open MacUtilGUI.Services +open MacUtilGUI.ViewModels + +module UpdateServiceTests = + + let private tahoeList = + String.concat + "\n" + [ "Software Update Tool" + "" + "Finding available software" + "Software Update found the following new or updated software:" + "* Label: Safari26.6.1SequoiaAuto-26.6.1" + "\tTitle: Safari, Version: 26.6.1, Size: 225311KiB, Recommended: YES, " + "* Label: macOS Tahoe 26.6.2-25G83" + "\tTitle: macOS Tahoe 26.6.2, Version: 26.6.2, Size: 5885236KiB, Recommended: YES, Action: restart, " ] + + let private catalog () = + ConfigLoader.load (ConfigSchemaTests.findConfigDir ()) + + let private listApple () = 0, tahoeList, "" + + let private makeVm (brew: BrewClientTests.FakeBrew) = + let client = FakeDefaultsClient() + let killer = FakeProcessKiller() + + MainWindowViewModel( + catalog (), + client :> IDefaultsClient, + killer :> IProcessKiller, + brew.Exec, + MaintenanceEngine.unixClear, + listApple + ) + + let private repoRoot () = + let rec walk dir = + if String.IsNullOrEmpty dir then + None + elif File.Exists(Path.Combine(dir, "MacUtilGUI", "Views", "MainWindow.axaml")) then + Some dir + else + let parent = Directory.GetParent dir + + if isNull parent then None else walk parent.FullName + + match walk AppContext.BaseDirectory with + | Some dir -> dir + | None -> + match walk (Directory.GetCurrentDirectory()) with + | Some dir -> dir + | None -> failwith "repo root not found" + + let private textExts = + set + [ ".fs" + ".fsproj" + ".axaml" + ".md" + ".json" + ".sh" + ".yml" + ".yaml" + ".toml" + ".plist" + ".txt" + ".xml" ] + + let private skipDir name = + name = "bin" || name = "obj" || name = ".git" || name = "node_modules" + + let rec private textFiles dir = + seq { + for file in Directory.GetFiles dir do + let ext = Path.GetExtension(file).ToLowerInvariant() + + if textExts.Contains ext then + yield file + + for sub in Directory.GetDirectories dir do + let name = Path.GetFileName sub + + if not (skipDir name) then + yield! textFiles sub + } + + [] + let ParseMajorUpgrade () = + let rows = UpdateService.parseSoftwareUpdateList tahoeList + Assert.Equal(2, rows.Length) + + let safari = rows |> List.find (fun row -> row.Title = "Safari") + Assert.Equal(AppleUpdateKind.Recommended, safari.Kind) + Assert.Equal("Safari26.6.1SequoiaAuto-26.6.1", safari.Label) + Assert.Equal("26.6.1", safari.Version) + Assert.True(safari.Recommended) + + let tahoe = + rows + |> List.find (fun row -> row.Title.IndexOf("macOS Tahoe", StringComparison.OrdinalIgnoreCase) >= 0) + + Assert.Equal(AppleUpdateKind.Major, tahoe.Kind) + Assert.Contains("macOS Tahoe", tahoe.Label) + Assert.True(UpdateService.isMajorUpgrade tahoe.Label tahoe.Title) + + let sw = Stopwatch.StartNew() + + for _ in 1..100 do + UpdateService.parseSoftwareUpdateList tahoeList |> ignore + + sw.Stop() + Assert.True(sw.ElapsedMilliseconds < 200L, sprintf "100 parses took %d ms" sw.ElapsedMilliseconds) + + let brew = BrewClientTests.FakeBrew([], [], [ "wget (1.21.4) < 1.25.3" ]) + let vm = makeVm brew + Assert.Equal("MacUtil", vm.Title) + Assert.Equal(2, vm.AppleUpdates.Count) + Assert.Equal(1, vm.BrewOutdated.Count) + Assert.Contains("System Settings", vm.SystemSettingsHelp) + + let tahoeRow = + vm.AppleUpdates + |> Seq.find (fun row -> row.Content.IndexOf("macOS Tahoe", StringComparison.OrdinalIgnoreCase) >= 0) + + Assert.Equal("Major", tahoeRow.KindLabel) + Assert.True(tahoeRow.IsMajor) + Assert.False(tahoeRow.IsEnabled) + Assert.False(tahoeRow.IsChecked) + tahoeRow.IsChecked <- true + Assert.False(tahoeRow.IsChecked) + + let safariRow = vm.AppleUpdates |> Seq.find (fun row -> row.Content = "Safari") + Assert.Equal("Recommended", safariRow.KindLabel) + Assert.False(safariRow.IsMajor) + Assert.True(safariRow.IsEnabled) + Assert.False(safariRow.IsChecked) + + let wget = Seq.exactlyOne vm.BrewOutdated + Assert.Equal("wget", wget.Name) + Assert.False(wget.IsChecked) + Assert.NotEmpty(vm.SafeTweaks) + Assert.Equal(26, Seq.length vm.AllApps) + + [] + let NoSilentInstall () = + let needle = String.concat "" [ "softwareupdate"; " --"; "install" ] + let root = repoRoot () + + let hits = + textFiles root + |> Seq.choose (fun path -> + let text = File.ReadAllText path + + if text.IndexOf(needle, StringComparison.Ordinal) >= 0 then + Some(Path.GetRelativePath(root, path)) + else + None) + |> Seq.toList + + Assert.True(hits.IsEmpty, String.concat ", " hits) + + let brew = BrewClientTests.FakeBrew([], [], [ "wget (1.21.4) < 1.25.3" ]) + let vm = makeVm brew + Assert.Empty(brew.UpgradeCalls) + + vm.UpdateHomebrew() + Assert.Empty(brew.UpgradeCalls) + Assert.Equal("Nothing is selected.", vm.StatusText) + + let wget = Seq.exactlyOne vm.BrewOutdated + wget.IsChecked <- true + vm.UpdateHomebrew() + Assert.Equal([ [ "upgrade"; "wget" ] ], brew.UpgradeCalls) + Assert.Equal("Updated 1 Homebrew package(s).", vm.StatusText) + + let axaml = + File.ReadAllText(Path.Combine(root, "MacUtilGUI", "Views", "MainWindow.axaml")) + + Assert.Contains("Updates", axaml) + Assert.Contains("Homebrew", axaml) + Assert.Contains("Copy command", axaml) + Assert.DoesNotContain("Install all", axaml, StringComparison.OrdinalIgnoreCase) + Assert.DoesNotContain("Install All", axaml) + Assert.Contains("Tweaks", axaml) + Assert.Contains("Install", axaml) + Assert.Contains("Maintenance", axaml) + Assert.Contains("Standard", axaml) + Assert.Contains("Minimal", axaml) + Assert.Contains("#1C1C1E", axaml) diff --git a/MacUtilGUI/MacUtilGUI.fsproj b/MacUtilGUI/MacUtilGUI.fsproj index 94977b3..d4041e8 100644 --- a/MacUtilGUI/MacUtilGUI.fsproj +++ b/MacUtilGUI/MacUtilGUI.fsproj @@ -47,9 +47,11 @@ + + diff --git a/MacUtilGUI/Services/UpdateService.fs b/MacUtilGUI/Services/UpdateService.fs new file mode 100644 index 0000000..b5dc98e --- /dev/null +++ b/MacUtilGUI/Services/UpdateService.fs @@ -0,0 +1,179 @@ +namespace MacUtilGUI.Services + +open System +open System.Diagnostics + +type SoftwareUpdateList = unit -> int * string * string + +type AppleUpdateKind = + | Major + | Recommended + +type AppleUpdate = + { Label: string + Title: string + Version: string + Recommended: bool + Kind: AppleUpdateKind } + +type BrewOutdated = { Name: string; Detail: string } + +module UpdateService = + + let systemSettingsHelp = + "Install major macOS upgrades in System Settings, General, Software Update." + + let systemSettingsCommand = + "open x-apple.systempreferences:com.apple.Software-Update-Settings.extension" + + let isMajorUpgrade (label: string) (title: string) = + let blob = label + " " + title + blob.IndexOf("macOS Tahoe", StringComparison.OrdinalIgnoreCase) >= 0 + + let private kindOf label title = + if isMajorUpgrade label title then + AppleUpdateKind.Major + else + AppleUpdateKind.Recommended + + let private splitFields (line: string) = + line.Split([| ',' |], StringSplitOptions.RemoveEmptyEntries) + |> Array.map (fun part -> part.Trim()) + |> Array.choose (fun part -> + let idx = part.IndexOf(':') + + if idx <= 0 then + None + else + Some(part.Substring(0, idx).Trim(), part.Substring(idx + 1).Trim())) + + let private fieldValue (fields: (string * string) array) (name: string) = + fields + |> Array.tryPick (fun (key, value) -> + if key.Equals(name, StringComparison.OrdinalIgnoreCase) then + Some value + else + None) + |> Option.defaultValue "" + + let private parseTitleLine (raw: string) = + let trimmed = raw.Trim() + + if trimmed.StartsWith("Title:", StringComparison.OrdinalIgnoreCase) then + let fields = splitFields trimmed + let title = fieldValue fields "Title" + let version = fieldValue fields "Version" + let recommended = fieldValue fields "Recommended" + Some(title, version, recommended.Equals("YES", StringComparison.OrdinalIgnoreCase)) + else + None + + let parseSoftwareUpdateList (text: string) = + if isNull text then + [] + else + let lines = text.Split([| '\n'; '\r' |], StringSplitOptions.None) + + let acc = ResizeArray() + let mutable i = 0 + + while i < lines.Length do + let line = lines.[i].Trim() + let star = line.StartsWith("* ", StringComparison.Ordinal) + + let labelIdx = + if star then + line.IndexOf("Label:", StringComparison.OrdinalIgnoreCase) + else + -1 + + if labelIdx >= 0 then + let label = line.Substring(labelIdx + "Label:".Length).Trim() + let mutable title = label + let mutable version = "" + let mutable recommended = false + + if i + 1 < lines.Length then + match parseTitleLine lines.[i + 1] with + | Some(parsedTitle, parsedVersion, parsedRecommended) -> + if parsedTitle <> "" then + title <- parsedTitle + + version <- parsedVersion + recommended <- parsedRecommended + i <- i + 1 + | None -> () + + acc.Add( + { Label = label + Title = title + Version = version + Recommended = recommended + Kind = kindOf label title } + ) + + i <- i + 1 + + List.ofSeq acc + + let private skipBrewLine (line: string) = + String.IsNullOrWhiteSpace line + || line.StartsWith("==>", StringComparison.Ordinal) + || line.StartsWith("✔", StringComparison.Ordinal) + || line.StartsWith("✓", StringComparison.Ordinal) + || line.IndexOf("JSON API", StringComparison.OrdinalIgnoreCase) >= 0 + || line.StartsWith("Downloading", StringComparison.OrdinalIgnoreCase) + || line.StartsWith("No outdated", StringComparison.OrdinalIgnoreCase) + || line.StartsWith("Already up-to-date", StringComparison.OrdinalIgnoreCase) + + let parseBrewOutdated (text: string) = + if isNull text then + [] + else + text.Split([| '\n'; '\r' |], StringSplitOptions.RemoveEmptyEntries) + |> Array.choose (fun raw -> + let line = raw.Trim() + + if skipBrewLine line then + None + else + let name = + line.Split([| ' '; '\t' |], StringSplitOptions.RemoveEmptyEntries) + |> Array.tryHead + |> Option.defaultValue "" + + if name = "" then + None + else + Some { Name = name; Detail = line }) + |> Array.toList + + let upgradeBrew (exec: BrewExec) (names: string list) = + match names with + | [] -> Error "Nothing is selected." + | _ -> + match exec ("upgrade" :: names) with + | 0, _, _ -> Ok(sprintf "Updated %d Homebrew package(s)." names.Length) + | _, _, stderr -> + let msg = stderr.Trim() + Error(if msg = "" then "brew upgrade failed." else msg) + + let unixList () = + try + use proc = new Process() + proc.StartInfo.FileName <- "/usr/sbin/softwareupdate" + proc.StartInfo.UseShellExecute <- false + proc.StartInfo.RedirectStandardOutput <- true + proc.StartInfo.RedirectStandardError <- true + proc.StartInfo.CreateNoWindow <- true + proc.StartInfo.ArgumentList.Add("--list") + + if not (proc.Start()) then + 1, "", "softwareupdate did not start" + else + let stdout = proc.StandardOutput.ReadToEnd() + let stderr = proc.StandardError.ReadToEnd() + proc.WaitForExit() + proc.ExitCode, stdout, stderr + with ex -> + 1, "", ex.Message diff --git a/MacUtilGUI/ViewModels/MainWindowViewModel.fs b/MacUtilGUI/ViewModels/MainWindowViewModel.fs index 3336dae..e3f59e9 100644 --- a/MacUtilGUI/ViewModels/MainWindowViewModel.fs +++ b/MacUtilGUI/ViewModels/MainWindowViewModel.fs @@ -20,8 +20,14 @@ type RelayCommand(canExecute: obj -> bool, execute: obj -> unit) = new(execute: obj -> unit) = RelayCommand((fun _ -> true), execute) type MainWindowViewModel - (catalog: Catalog, client: IDefaultsClient, killer: IProcessKiller, brew: BrewExec, cacheClear: CacheClear) as this - = + ( + catalog: Catalog, + client: IDefaultsClient, + killer: IProcessKiller, + brew: BrewExec, + cacheClear: CacheClear, + listApple: SoftwareUpdateList + ) as this = inherit ViewModelBase() let mutable statusText: string = "" @@ -30,6 +36,8 @@ type MainWindowViewModel let cautionTweaks = ObservableCollection() let allApps = ResizeArray() let apps = ObservableCollection() + let appleUpdates = ObservableCollection() + let brewOutdated = ObservableCollection() let allRows () = Seq.append safeTweaks cautionTweaks @@ -144,6 +152,46 @@ type MainWindowViewModel | Ok msg -> setStatus msg | Error msg -> setStatus msg + let combinedOutput stdout stderr = stdout + "\n" + stderr + + let refreshUpdates report = + appleUpdates.Clear() + brewOutdated.Clear() + + let _, stdout, stderr = listApple () + + for update in UpdateService.parseSoftwareUpdateList (combinedOutput stdout stderr) do + appleUpdates.Add(AppleUpdateRowViewModel(update)) + + let _, brewOut, brewErr = brew [ "outdated"; "--verbose" ] + + for pkg in UpdateService.parseBrewOutdated (combinedOutput brewOut brewErr) do + brewOutdated.Add(BrewOutdatedRowViewModel(pkg)) + + if report then + setStatus ( + sprintf "Listed %d Apple update(s) and %d Homebrew package(s)." appleUpdates.Count brewOutdated.Count + ) + + let copySystemSettings () = + setStatus UpdateService.systemSettingsHelp + + let updateBrewSelected () = + let selected = + brewOutdated + |> Seq.filter (fun row -> row.IsChecked) + |> Seq.map (fun row -> row.Name) + |> Seq.toList + + if selected.IsEmpty then + setStatus "Nothing is selected." + else + match UpdateService.upgradeBrew brew selected with + | Ok msg -> + refreshUpdates false + setStatus msg + | Error msg -> setStatus msg + let applyCommand = RelayCommand(fun _ -> applySelected ()) let undoCommand = RelayCommand(fun _ -> undoSelected ()) let installCommand = RelayCommand(fun _ -> installSelected ()) @@ -152,6 +200,9 @@ type MainWindowViewModel let brewUpdateCommand = RelayCommand(fun _ -> runMaintenance BrewUpdate) let brewCleanupCommand = RelayCommand(fun _ -> runMaintenance BrewCleanup) let userCacheBrewCommand = RelayCommand(fun _ -> runMaintenance UserCacheBrew) + let refreshUpdatesCommand = RelayCommand(fun _ -> refreshUpdates true) + let copySystemSettingsCommand = RelayCommand(fun _ -> copySystemSettings ()) + let updateHomebrewCommand = RelayCommand(fun _ -> updateBrewSelected ()) let categoryRank category = match category with @@ -191,6 +242,10 @@ type MainWindowViewModel |> Seq.iter (fun app -> allApps.Add(AppRowViewModel(app, BrewClient.installed brew app))) applyFilter () + refreshUpdates false + + new(catalog, client, killer, brew, cacheClear) = + MainWindowViewModel(catalog, client, killer, brew, cacheClear, fun () -> 0, "", "") new(catalog, client, killer, brew) = MainWindowViewModel(catalog, client, killer, brew, MaintenanceEngine.unixClear) @@ -205,7 +260,8 @@ type MainWindowViewModel UnixDefaultsClient() :> IDefaultsClient, UnixProcessKiller() :> IProcessKiller, BrewClient.unixExec, - MaintenanceEngine.unixClear + MaintenanceEngine.unixClear, + UpdateService.unixList ) member _.SafeTweaks = safeTweaks @@ -270,4 +326,24 @@ type MainWindowViewModel member _.UserCacheBrewCommand = userCacheBrewCommand + member _.RefreshUpdatesCommand = refreshUpdatesCommand + + member _.CopySystemSettingsCommand = copySystemSettingsCommand + + member _.UpdateHomebrewCommand = updateHomebrewCommand + + member _.AppleUpdates = appleUpdates + + member _.BrewOutdated = brewOutdated + + member _.SystemSettingsHelp = UpdateService.systemSettingsHelp + + member _.SystemSettingsCommand = UpdateService.systemSettingsCommand + + member _.RefreshUpdates() = refreshUpdates true + + member _.CopySystemSettings() = copySystemSettings () + + member _.UpdateHomebrew() = updateBrewSelected () + member _.Title = "MacUtil" diff --git a/MacUtilGUI/ViewModels/UpdateRowViewModel.fs b/MacUtilGUI/ViewModels/UpdateRowViewModel.fs new file mode 100644 index 0000000..35e700a --- /dev/null +++ b/MacUtilGUI/ViewModels/UpdateRowViewModel.fs @@ -0,0 +1,63 @@ +namespace MacUtilGUI.ViewModels + +open MacUtilGUI.Services + +type AppleUpdateRowViewModel(update: AppleUpdate) = + inherit ViewModelBase() + + let isMajor = update.Kind = AppleUpdateKind.Major + let mutable isChecked = false + + member _.Label = update.Label + member _.Title = update.Title + member _.Version = update.Version + member _.Kind = update.Kind + member _.Content = update.Title + member _.IsMajor = isMajor + member _.IsEnabled = not isMajor + member _.Update = update + + member _.KindLabel = + match update.Kind with + | AppleUpdateKind.Major -> "Major" + | AppleUpdateKind.Recommended -> "Recommended" + + member _.Description = + match update.Kind with + | AppleUpdateKind.Major -> "Major. Install from System Settings." + | AppleUpdateKind.Recommended -> + if update.Version = "" then + update.Label + else + sprintf "%s. %s" update.Version update.Label + + member this.IsChecked + with get () = isChecked + and set v = + let next = if isMajor then false else v + + if isChecked <> next then + isChecked <- next + this.OnPropertyChanged("IsChecked") + +type BrewOutdatedRowViewModel(pkg: BrewOutdated) = + inherit ViewModelBase() + + let mutable isChecked = false + + member _.Name = pkg.Name + member _.Content = pkg.Name + member _.Package = pkg + + member _.Description = + if pkg.Detail = pkg.Name then + "Outdated Homebrew package." + else + pkg.Detail + + member this.IsChecked + with get () = isChecked + and set v = + if isChecked <> v then + isChecked <- v + this.OnPropertyChanged("IsChecked") diff --git a/MacUtilGUI/Views/MainWindow.axaml b/MacUtilGUI/Views/MainWindow.axaml index 78df233..f55ac7f 100644 --- a/MacUtilGUI/Views/MainWindow.axaml +++ b/MacUtilGUI/Views/MainWindow.axaml @@ -205,6 +205,90 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +