SetSettingCommandLineCommand.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.Reflection; 7 8 using Settings.UI.Library.Attributes; 9 10 namespace Microsoft.PowerToys.Settings.UI.Library; 11 12 /// <summary> 13 /// This user flow allows DSC resources to use PowerToys.Settings executable to set settings values by suppling them from command line using the following syntax: 14 /// PowerToys.Settings.exe set <module struct name>.<field name> <field_value> 15 /// 16 /// Example: PowerToys.Settings.exe set MeasureTool.MeasureCrossColor "#00FF00" 17 /// </summary> 18 public sealed class SetSettingCommandLineCommand 19 { 20 private static readonly char[] SettingNameSeparator = { '.' }; 21 22 private static (string ModuleName, string PropertyName) ParseSettingName(string settingName) 23 { 24 var parts = settingName.Split(SettingNameSeparator, 2, StringSplitOptions.RemoveEmptyEntries); 25 return (parts[0], parts[1]); 26 } 27 28 public static void Execute(string settingName, string settingValue, SettingsUtils settingsUtils) 29 { 30 Assembly settingsLibraryAssembly = CommandLineUtils.GetSettingsAssembly(); 31 32 var (moduleName, propertyName) = ParseSettingName(settingName); 33 34 var settingsConfig = CommandLineUtils.GetSettingsConfigFor(moduleName, settingsUtils, settingsLibraryAssembly); 35 36 var propertyInfo = CommandLineUtils.GetSettingPropertyInfo(propertyName, settingsConfig); 37 if (propertyInfo == null) 38 { 39 throw new ArgumentException($"Property '{propertyName}' wasn't found"); 40 } 41 42 if (propertyInfo.PropertyType.GetCustomAttribute<CmdConfigureIgnoreAttribute>() != null) 43 { 44 throw new ArgumentException($"Property '{propertyName}' is explicitly ignored"); 45 } 46 47 // Execute settingsConfig.Properties.<propertyName> = settingValue 48 var propertyValue = ICmdLineRepresentable.ParseFor(propertyInfo.PropertyType, settingValue); 49 var (settingInfo, properties) = CommandLineUtils.LocateSetting(propertyName, settingsConfig); 50 settingInfo.SetValue(properties, propertyValue); 51 52 settingsUtils.SaveSettings(settingsConfig.ToJsonString(), settingsConfig.GetModuleName()); 53 } 54 }