GetSettingCommandLineCommand.cs
1 // Copyright (c) Microsoft Corporation 2 // The Microsoft Corporation licenses this file to you under the MIT license. 3 // See the LICENSE file in the project root for more information. 4 5 using System; 6 using System.Collections.Generic; 7 using System.Globalization; 8 using System.Text.Json; 9 using System.Xml; 10 11 using Microsoft.PowerToys.Settings.UI.Library.Interfaces; 12 using Settings.UI.Library.Attributes; 13 14 namespace Microsoft.PowerToys.Settings.UI.Library; 15 16 /// <summary> 17 /// This user flow allows DSC resources to use PowerToys.Settings executable to get settings values by querying them from command line using the following syntax: 18 /// PowerToys.Settings.exe get <path to a json file containing a list of modules and their corresponding properties> 19 /// 20 /// Example: PowerToys.Settings.exe get %TEMP%\properties.json 21 /// `properties.json` file contents: 22 /// { 23 /// "AlwaysOnTop": ["FrameEnabled", "FrameAccentColor"], 24 /// "FancyZones": ["FancyzonesShiftDrag", "FancyzonesShowOnAllMonitors"] 25 /// } 26 /// 27 /// Upon PowerToys.Settings.exe completion, it'll update `properties.json` file to contain something like this: 28 /// { 29 /// "AlwaysOnTop": { 30 /// "FrameEnabled": true, 31 /// "FrameAccentColor": "#0099cc" 32 /// }, 33 /// "FancyZones": { 34 /// "FancyzonesShiftDrag": true, 35 /// "FancyzonesShowOnAllMonitors": false 36 /// } 37 /// } 38 /// </summary> 39 public sealed class GetSettingCommandLineCommand 40 { 41 private static JsonSerializerOptions _serializerOptions = new JsonSerializerOptions 42 { 43 Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping, 44 }; 45 46 public static string Execute(Dictionary<string, List<string>> settingNamesForModules) 47 { 48 var modulesSettings = new Dictionary<string, Dictionary<string, object>>(); 49 50 var settingsAssembly = CommandLineUtils.GetSettingsAssembly(); 51 var settingsUtils = SettingsUtils.Default; 52 53 var enabledModules = SettingsRepository<GeneralSettings>.GetInstance(settingsUtils).SettingsConfig.Enabled; 54 55 foreach (var (moduleName, settings) in settingNamesForModules) 56 { 57 var moduleSettings = new Dictionary<string, object>(); 58 if (moduleName != nameof(GeneralSettings)) 59 { 60 moduleSettings.Add("Enabled", typeof(EnabledModules).GetProperty(moduleName).GetValue(enabledModules)); 61 } 62 63 var settingsConfig = CommandLineUtils.GetSettingsConfigFor(moduleName, settingsUtils, settingsAssembly); 64 foreach (var settingName in settings) 65 { 66 var value = CommandLineUtils.GetPropertyValue(settingName, settingsConfig); 67 if (value != null) 68 { 69 var cmdReprValue = ICmdLineRepresentable.ToCmdRepr(value.GetType(), value); 70 moduleSettings.Add(settingName, cmdReprValue); 71 } 72 } 73 74 modulesSettings.Add(moduleName, moduleSettings); 75 } 76 77 return JsonSerializer.Serialize(modulesSettings, _serializerOptions); 78 } 79 }