From 09652efec5549556e84f0abc03262bce100ca0bf Mon Sep 17 00:00:00 2001
From: Jon Evans <jon@craftyjon.com>
Date: Sat, 2 Nov 2024 14:53:23 -0400
Subject: [PATCH] Clear unknown keys from environment variable maps on save

Also fix the previous code for clearing unknown keys to use
a JSON pointer so that it functions correctly when the JSON path
is more than one level deep.

Fixes https://gitlab.com/kicad/code/kicad/-/issues/18734
---
 common/settings/common_settings.cpp | 3 ++-
 common/settings/json_settings.cpp   | 8 +++++---
 include/settings/parameters.h       | 2 ++
 3 files changed, 9 insertions(+), 4 deletions(-)

diff --git a/common/settings/common_settings.cpp b/common/settings/common_settings.cpp
index 04b2d88611..2241bf1e5a 100644
--- a/common/settings/common_settings.cpp
+++ b/common/settings/common_settings.cpp
@@ -120,7 +120,7 @@ COMMON_SETTINGS::COMMON_SETTINGS() :
     m_params.emplace_back( new PARAM<int>( "auto_backup.min_interval",
             &m_Backup.min_interval, 300 ) );
 
-    m_params.emplace_back( new PARAM_LAMBDA<nlohmann::json>( "environment.vars",
+    auto envVarsParam = m_params.emplace_back( new PARAM_LAMBDA<nlohmann::json>( "environment.vars",
             [&]() -> nlohmann::json
             {
                 nlohmann::json ret = {};
@@ -216,6 +216,7 @@ COMMON_SETTINGS::COMMON_SETTINGS() :
                 }
             },
             {} ) );
+    envVarsParam->SetClearUnknownKeys();
 
     m_params.emplace_back( new PARAM<bool>( "input.focus_follow_sch_pcb",
             &m_Input.focus_follow_sch_pcb, false ) );
diff --git a/common/settings/json_settings.cpp b/common/settings/json_settings.cpp
index fffe948dec..459cda9d73 100644
--- a/common/settings/json_settings.cpp
+++ b/common/settings/json_settings.cpp
@@ -468,10 +468,12 @@ bool JSON_SETTINGS::SaveToFile( const wxString& aDirectory, bool aForce )
 
     for( PARAM_BASE* param : m_params )
     {
-        if( PARAM_WXSTRING_MAP* stringMap = dynamic_cast<PARAM_WXSTRING_MAP*>( param ) )
+        if( param->ClearUnknownKeys() )
         {
-            if( stringMap->ClearUnknownKeys() )
-                toSave[ stringMap->GetJsonPath() ] = nlohmann::json( {} );
+            nlohmann::json_pointer p
+                    = JSON_SETTINGS_INTERNALS::PointerFromString( param->GetJsonPath() );
+
+            toSave[p] = nlohmann::json( {} );
         }
     }
 
diff --git a/include/settings/parameters.h b/include/settings/parameters.h
index f920b1853c..ac6b52899b 100644
--- a/include/settings/parameters.h
+++ b/include/settings/parameters.h
@@ -77,6 +77,8 @@ public:
      */
     bool ClearUnknownKeys() const { return m_clearUnknownKeys; }
 
+    void SetClearUnknownKeys( bool aSet = true ) { m_clearUnknownKeys = aSet; }
+
 protected:
     std::string m_path;               ///< Address of the param in the json files
     bool        m_readOnly;           ///< Indicates param pointer should never be overwritten