From f9be806ede887df3d7602c8e9f15423395387e57 Mon Sep 17 00:00:00 2001 From: Rain Sallow Date: Fri, 4 Oct 2024 12:03:19 -0400 Subject: [PATCH] (maint) Add command deprecation framework This allows us to maintain a simple list of deprecated aliases and the new command name, or commands that are being removed, and automatically warn when that command is called. --- .../Shared/ChocolateyCmdlet.cs | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/Chocolatey.PowerShell/Shared/ChocolateyCmdlet.cs b/src/Chocolatey.PowerShell/Shared/ChocolateyCmdlet.cs index 8e29e0add..23d677cf2 100644 --- a/src/Chocolatey.PowerShell/Shared/ChocolateyCmdlet.cs +++ b/src/Chocolatey.PowerShell/Shared/ChocolateyCmdlet.cs @@ -14,7 +14,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +using System; using System.Collections; +using System.Collections.Generic; using System.Management.Automation; using System.Text; using Chocolatey.PowerShell.Helpers; @@ -27,6 +29,16 @@ namespace Chocolatey.PowerShell.Shared /// public abstract class ChocolateyCmdlet : PSCmdlet { + // Place deprecated command names and their corresponding replacement in this dictionary to have those commands + // warn users about the deprecation when they are called by those names. + private readonly Dictionary _deprecatedCommandNames = new Dictionary(StringComparer.OrdinalIgnoreCase) + { + // Use the following format to provide a deprecation notice. If the new command name is an empty string, + // the warning will inform the user it is to be removed instead of renamed. + // + // { "Deprecated-CommandName", "New-CommandName" }, + }; + /// /// The canonical error ID for the command to assist with traceability. /// For more specific error IDs where needed, use "{ErrorId}.EventName". @@ -54,8 +66,20 @@ protected string ErrorId /// protected virtual bool Logging { get; } = true; + private void WriteWarningForDeprecatedCommands() + { + if (_deprecatedCommandNames.TryGetValue(MyInvocation.InvocationName, out var replacement)) + { + var message = string.IsNullOrEmpty(replacement) + ? $"The command '{MyInvocation.InvocationName}' is deprecated and will be removed in a future version" + : $"The '{MyInvocation.InvocationName}' alias is deprecated and will be removed in a future version. Use '{replacement}' to ensure compatibility with future versions of Chocolatey."; + WriteWarning(message); + } + } + protected sealed override void BeginProcessing() { + WriteWarningForDeprecatedCommands(); WriteCmdletCallDebugMessage(); Begin(); }