Skip to content

Commit 69c0cac

Browse files
committed
(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.
1 parent 02fdac5 commit 69c0cac

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

src/Chocolatey.PowerShell/Shared/ChocolateyCmdlet.cs

+24
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,9 @@
1414
// See the License for the specific language governing permissions and
1515
// limitations under the License.
1616

17+
using System;
1718
using System.Collections;
19+
using System.Collections.Generic;
1820
using System.Management.Automation;
1921
using System.Text;
2022
using Chocolatey.PowerShell.Helpers;
@@ -27,6 +29,16 @@ namespace Chocolatey.PowerShell.Shared
2729
/// </summary>
2830
public abstract class ChocolateyCmdlet : PSCmdlet
2931
{
32+
// Place deprecated command names and their corresponding replacement in this dictionary to have those commands
33+
// warn users about the deprecation when they are called by those names.
34+
private readonly Dictionary<string, string> _deprecatedCommandNames = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
35+
{
36+
// Use the following format to provide a deprecation notice. If the new command name is an empty string,
37+
// the warning will inform the user it is to be removed instead of renamed.
38+
//
39+
// { "Deprecated-CommandName", "New-CommandName" },
40+
};
41+
3042
/// <summary>
3143
/// The canonical error ID for the command to assist with traceability.
3244
/// For more specific error IDs where needed, use <c>"{ErrorId}.EventName"</c>.
@@ -54,8 +66,20 @@ protected string ErrorId
5466
/// </summary>
5567
protected virtual bool Logging { get; } = true;
5668

69+
private void WriteWarningForDeprecatedCommands()
70+
{
71+
if (_deprecatedCommandNames.TryGetValue(MyInvocation.InvocationName, out var replacement))
72+
{
73+
var message = string.IsNullOrEmpty(replacement)
74+
? $"The command '{MyInvocation.InvocationName}' is deprecated and will be removed in a future version"
75+
: $"The '{MyInvocation.InvocationName}' alias is deprecated and will be removed in a future version. Use '{replacement}' to ensure compatibility with future versions of Chocolatey.";
76+
WriteWarning(message);
77+
}
78+
}
79+
5780
protected sealed override void BeginProcessing()
5881
{
82+
WriteWarningForDeprecatedCommands();
5983
WriteCmdletCallDebugMessage();
6084
Begin();
6185
}

0 commit comments

Comments
 (0)