From a892256374277be3945c1cbab98fa18cfc698f33 Mon Sep 17 00:00:00 2001
From: Manuel Thalmann <m@nuth.ch>
Date: Wed, 26 Jul 2023 18:12:18 +0200
Subject: [PATCH] Refactor the logic for reordering the association config

---
 scripts/Windows/Scripts/AppAssociations.ps1 | 15 +++++++++------
 1 file changed, 9 insertions(+), 6 deletions(-)

diff --git a/scripts/Windows/Scripts/AppAssociations.ps1 b/scripts/Windows/Scripts/AppAssociations.ps1
index 75fefce5..563250c4 100644
--- a/scripts/Windows/Scripts/AppAssociations.ps1
+++ b/scripts/Windows/Scripts/AppAssociations.ps1
@@ -1,6 +1,7 @@
 $null = New-Module {
     class AppAssociations {
-        static $associationSelector = "/DefaultAssociations/Association";
+        static $defaultAssociationsSelector = "/DefaultAssociations";
+        static $associationSelector = "./Association";
 
         static [string] GetSelector([string] $identifier) {
             return "$([AppAssociations]::associationSelector)[@Identifier='$identifier']";
@@ -13,25 +14,27 @@ $null = New-Module {
         }
 
         static SetAssociation([string] $identifier, [string] $progId, [string] $applicationName) {
-            $associations = [AppAssociations]::GetAppAssociations();
+            $document = [AppAssociations]::GetAppAssociations();
+            $associations = $document.SelectSingleNode([AppAssociations]::defaultAssociationsSelector);
+
             [System.Xml.XmlNode] $association = $null;
             $candidates = $associations.SelectNodes([AppAssociations]::GetSelector($identifier));
 
             if ($candidates.Count -eq 1) {
                 $association = $candidates[0];
             } else {
-                $defaultAssociations = $associations.SelectSingleNode("/DefaultAssociations");
                 $association = ($associations.SelectNodes([AppAssociations]::associationSelector) | Select-Object -Last 1).CloneNode($true);
                 $association.Identifier = $identifier;
-                $association = $defaultAssociations.AppendChild($association);
+                $association = $associations.AppendChild($association);
             }
 
             $association.ProgId = $progId;
             $association.ApplicationName = $applicationName;
-            [AppAssociations]::SaveAssociations($associations);
+            [AppAssociations]::SaveAssociations($document);
         }
 
-        static SaveAssociations([xml] $associations) {
+        static SaveAssociations([xml] $document) {
+            $associations = $document.SelectSingleNode([AppAssociations]::defaultAssociationsSelector);
             $defaultAssociations = $associations.SelectNodes([AppAssociations]::associationSelector);
             $defaultAssociations | ForEach-Object { $associations.RemoveChild($_); } | Sort-Object -Property "Identifier" | ForEach-Object { $associations.AppendChild($_); };