diff --git a/Directory.Packages.props b/Directory.Packages.props
index eca68c8c53b..2761dc14cdd 100644
--- a/Directory.Packages.props
+++ b/Directory.Packages.props
@@ -53,7 +53,6 @@
-
@@ -179,7 +178,6 @@
<_allowBuildFromSourcePackage Include="Microsoft.CSharp" />
<_allowBuildFromSourcePackage Include="Microsoft.DotNet.Build.Tasks.Feed" />
<_allowBuildFromSourcePackage Include="Microsoft.DotNet.XliffTasks" />
- <_allowBuildFromSourcePackage Include="Microsoft.Extensions.CommandLineUtils.Sources" />
<_allowBuildFromSourcePackage Include="Microsoft.Extensions.FileProviders.Abstractions" />
<_allowBuildFromSourcePackage Include="Microsoft.Extensions.FileSystemGlobbing" />
<_allowBuildFromSourcePackage Include="Microsoft.Web.Xdt" />
diff --git a/NuGet.Config b/NuGet.Config
index 00d231892f6..4c7e64e6419 100644
--- a/NuGet.Config
+++ b/NuGet.Config
@@ -5,7 +5,6 @@
-
@@ -90,9 +89,6 @@
-
-
-
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/CommandConstants.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/CommandConstants.cs
index 836cd19be7f..af106877253 100644
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/CommandConstants.cs
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/CommandConstants.cs
@@ -3,7 +3,7 @@
#nullable enable
-namespace NuGet.CommandLine.XPlat
+namespace NuGet.CommandLine.XPlat.Commands
{
internal static class CommandConstants
{
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/CommandParsers.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/CommandParsers.cs
deleted file mode 100644
index cca3af72ba0..00000000000
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/CommandParsers.cs
+++ /dev/null
@@ -1,24 +0,0 @@
-// Copyright (c) .NET Foundation. All rights reserved.
-// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
-
-#nullable enable
-
-using System;
-using Microsoft.Extensions.CommandLineUtils;
-using NuGet.Common;
-
-namespace NuGet.CommandLine.XPlat
-{
- internal static class CommandParsers
- {
- public static void Register(CommandLineApplication app, Func getLogger)
- {
- AddVerbParser.Register(app, getLogger);
- DisableVerbParser.Register(app, getLogger);
- EnableVerbParser.Register(app, getLogger);
- ListVerbParser.Register(app, getLogger);
- RemoveVerbParser.Register(app, getLogger);
- UpdateVerbParser.Register(app, getLogger);
- }
- }
-}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/ConfigCommands/ConfigCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/ConfigCommands/ConfigCommand.cs
index 48e4afb32c4..58a7acbe8ae 100644
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/ConfigCommands/ConfigCommand.cs
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/ConfigCommands/ConfigCommand.cs
@@ -5,9 +5,7 @@
using System;
using System.CommandLine;
-using System.CommandLine.Help;
using System.Threading.Tasks;
-using Microsoft.Extensions.CommandLineUtils;
using NuGet.CommandLine.XPlat.Commands;
using NuGet.Common;
@@ -15,53 +13,6 @@ namespace NuGet.CommandLine.XPlat
{
internal class ConfigCommand
{
- private static HelpOption HelpOption = new HelpOption()
- {
- Arity = ArgumentArity.Zero
- };
-
- private static Argument SetConfigKeyArgument = new Argument(name: "config-key")
- {
- Arity = ArgumentArity.ExactlyOne,
- Description = Strings.ConfigSetConfigKeyDescription,
- };
-
- private static Argument UnsetConfigKeyArgument = new Argument(name: "config-key")
- {
- Arity = ArgumentArity.ExactlyOne,
- Description = Strings.ConfigUnsetConfigKeyDescription,
- };
-
- private static Argument ConfigValueArgument = new Argument(name: "config-value")
- {
- Arity = ArgumentArity.ExactlyOne,
- Description = Strings.ConfigSetConfigValueDescription,
- };
-
- private static Argument AllOrConfigKeyArgument = new Argument(name: "all-or-config-key")
- {
- Arity = ArgumentArity.ExactlyOne,
- Description = Strings.ConfigGetAllOrConfigKeyDescription
- };
-
- private static Option WorkingDirectory = new Option(name: "--working-directory")
- {
- Arity = ArgumentArity.ZeroOrOne,
- Description = Strings.ConfigPathsWorkingDirectoryDescription
- };
-
- private static Option ShowPathOption = new Option(name: "--show-path")
- {
- Arity = ArgumentArity.Zero,
- Description = Strings.ConfigGetShowPathDescription,
- };
-
- private static Option ConfigFileOption = new Option(name: "--configfile")
- {
- Arity = ArgumentArity.ZeroOrOne,
- Description = Strings.Option_ConfigFile,
- };
-
internal static void LogException(Exception e, ILogger log)
{
// Log the error
@@ -78,18 +29,9 @@ internal static void LogException(Exception e, ILogger log)
log.LogVerbose(e.ToString());
}
- internal static void Register(CommandLineApplication app)
- {
- app.Command("config", configCmd =>
- {
- configCmd.Description = Strings.Config_Description;
- });
- }
-
- internal static Command Register(Command app, Func getLogger)
+ internal static Command Register(Command app, Func getLogger)
{
var ConfigCmd = new DocumentedCommand(name: "config", description: Strings.Config_Description, "https://aka.ms/dotnet/nuget/config");
- ConfigCmd.Options.Add(HelpOption);
// Options directly under the verb 'config'
@@ -132,14 +74,19 @@ internal static Command Register(Command app, Func getLogger)
private static void RegisterOptionsForCommandConfigPaths(Command cmd, Func getLogger)
{
- cmd.Options.Add(WorkingDirectory);
- cmd.Options.Add(HelpOption);
+ var workingDirectory = new Option(name: "--working-directory")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.ConfigPathsWorkingDirectoryDescription
+ };
+
+ cmd.Options.Add(workingDirectory);
// Create handler delegate handler for cmd
cmd.SetAction((parseResult, cancellationToken) =>
{
var args = new ConfigPathsArgs()
{
- WorkingDirectory = parseResult.GetValue(WorkingDirectory),
+ WorkingDirectory = parseResult.GetValue(workingDirectory),
};
int exitCode = ConfigPathsRunner.Run(args, getLogger);
@@ -149,19 +96,36 @@ private static void RegisterOptionsForCommandConfigPaths(Command cmd, Func getLogger)
{
- cmd.Arguments.Add(AllOrConfigKeyArgument);
- cmd.Options.Add(WorkingDirectory);
- cmd.Options.Add(ShowPathOption);
- cmd.Options.Add(HelpOption);
+ var allOrConfigKeyArgument = new Argument(name: "all-or-config-key")
+ {
+ Arity = ArgumentArity.ExactlyOne,
+ Description = Strings.ConfigGetAllOrConfigKeyDescription
+ };
+
+ var workingDirectory = new Option(name: "--working-directory")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.ConfigPathsWorkingDirectoryDescription
+ };
+
+ var showPathOption = new Option(name: "--show-path")
+ {
+ Arity = ArgumentArity.Zero,
+ Description = Strings.ConfigGetShowPathDescription,
+ };
+
+ cmd.Arguments.Add(allOrConfigKeyArgument);
+ cmd.Options.Add(workingDirectory);
+ cmd.Options.Add(showPathOption);
// Create handler delegate handler for cmd
cmd.SetAction((parseResult, cancellationToken) =>
{
var args = new ConfigGetArgs()
{
- AllOrConfigKey = parseResult.GetValue(AllOrConfigKeyArgument),
- WorkingDirectory = parseResult.GetValue(WorkingDirectory),
- ShowPath = parseResult.GetValue(ShowPathOption),
+ AllOrConfigKey = parseResult.GetValue(allOrConfigKeyArgument),
+ WorkingDirectory = parseResult.GetValue(workingDirectory),
+ ShowPath = parseResult.GetValue(showPathOption),
};
int exitCode = ConfigGetRunner.Run(args, getLogger);
@@ -171,18 +135,35 @@ private static void RegisterOptionsForCommandConfigGet(Command cmd, Func getLogger)
{
- cmd.Arguments.Add(SetConfigKeyArgument);
- cmd.Arguments.Add(ConfigValueArgument);
- cmd.Options.Add(ConfigFileOption);
- cmd.Options.Add(HelpOption);
+ var setConfigKeyArgument = new Argument(name: "config-key")
+ {
+ Arity = ArgumentArity.ExactlyOne,
+ Description = Strings.ConfigSetConfigKeyDescription,
+ };
+
+ var configValueArgument = new Argument(name: "config-value")
+ {
+ Arity = ArgumentArity.ExactlyOne,
+ Description = Strings.ConfigSetConfigValueDescription,
+ };
+
+ var configFileOption = new Option(name: "--configfile")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.Option_ConfigFile,
+ };
+
+ cmd.Arguments.Add(setConfigKeyArgument);
+ cmd.Arguments.Add(configValueArgument);
+ cmd.Options.Add(configFileOption);
// Create handler delegate handler for cmd
cmd.SetAction((parseResult, cancellationToken) =>
{
var args = new ConfigSetArgs()
{
- ConfigKey = parseResult.GetValue(SetConfigKeyArgument),
- ConfigValue = parseResult.GetValue(ConfigValueArgument),
- ConfigFile = parseResult.GetValue(ConfigFileOption),
+ ConfigKey = parseResult.GetValue(setConfigKeyArgument),
+ ConfigValue = parseResult.GetValue(configValueArgument),
+ ConfigFile = parseResult.GetValue(configFileOption),
};
int exitCode = ConfigSetRunner.Run(args, getLogger);
@@ -192,16 +173,27 @@ private static void RegisterOptionsForCommandConfigSet(Command cmd, Func getLogger)
{
- cmd.Arguments.Add(UnsetConfigKeyArgument);
- cmd.Options.Add(ConfigFileOption);
- cmd.Options.Add(HelpOption);
+ var unsetConfigKeyArgument = new Argument(name: "config-key")
+ {
+ Arity = ArgumentArity.ExactlyOne,
+ Description = Strings.ConfigUnsetConfigKeyDescription,
+ };
+
+ var configFileOption = new Option(name: "--configfile")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.Option_ConfigFile,
+ };
+
+ cmd.Arguments.Add(unsetConfigKeyArgument);
+ cmd.Options.Add(configFileOption);
// Create handler delegate handler for cmd
cmd.SetAction((parseResult, cancellationToken) =>
{
var args = new ConfigUnsetArgs()
{
- ConfigKey = parseResult.GetValue(UnsetConfigKeyArgument),
- ConfigFile = parseResult.GetValue(ConfigFileOption),
+ ConfigKey = parseResult.GetValue(unsetConfigKeyArgument),
+ ConfigFile = parseResult.GetValue(configFileOption),
};
int exitCode = ConfigUnsetRunner.Run(args, getLogger);
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/DeleteCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/DeleteCommand.cs
index c7c2e765cc3..a279e83db8a 100644
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/DeleteCommand.cs
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/DeleteCommand.cs
@@ -4,10 +4,9 @@
#nullable disable
using System;
+using System.CommandLine;
using System.Globalization;
-using Microsoft.Extensions.CommandLineUtils;
using NuGet.Commands;
-using NuGet.Common;
using NuGet.Configuration;
using NuGet.Credentials;
@@ -15,83 +14,92 @@ namespace NuGet.CommandLine.XPlat
{
internal static class DeleteCommand
{
- public static void Register(CommandLineApplication app, Func getLogger)
+ internal static void Register(Command parent, Func getLogger)
{
- app.Command("delete", delete =>
+ var deleteCmd = new Command("delete", Strings.Delete_Description);
+
+ var sourceOption = new Option("--source", "-s")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.Source_Description,
+ };
+
+ var nonInteractiveOption = new Option("--non-interactive")
+ {
+ Arity = ArgumentArity.Zero,
+ Description = Strings.NonInteractive_Description,
+ };
+
+ var apiKeyOption = new Option("--api-key", "-k")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.ApiKey_Description,
+ };
+
+ var noServiceEndpointOption = new Option("--no-service-endpoint")
+ {
+ Arity = ArgumentArity.Zero,
+ Description = Strings.NoServiceEndpoint_Description,
+ };
+
+ var interactiveOption = new Option("--interactive")
+ {
+ Arity = ArgumentArity.Zero,
+ Description = Strings.NuGetXplatCommand_Interactive,
+ };
+
+ var packageIdArgument = new Argument("PackageId")
+ {
+ Arity = ArgumentArity.ExactlyOne,
+ Description = Strings.Delete_PackageIdAndVersion_Description,
+ };
+
+ var packageVersionArgument = new Argument("PackageVersion")
+ {
+ Arity = ArgumentArity.ExactlyOne,
+ Description = Strings.Delete_PackageIdAndVersion_Description,
+ };
+
+ deleteCmd.Options.Add(sourceOption);
+ deleteCmd.Options.Add(nonInteractiveOption);
+ deleteCmd.Options.Add(apiKeyOption);
+ deleteCmd.Options.Add(noServiceEndpointOption);
+ deleteCmd.Options.Add(interactiveOption);
+ deleteCmd.Arguments.Add(packageIdArgument);
+ deleteCmd.Arguments.Add(packageVersionArgument);
+
+ deleteCmd.SetAction(async (parseResult, cancellationToken) =>
{
- delete.Description = Strings.Delete_Description;
- delete.HelpOption(XPlatUtility.HelpOption);
-
- delete.Option(
- CommandConstants.ForceEnglishOutputOption,
- Strings.ForceEnglishOutput_Description,
- CommandOptionType.NoValue);
-
- var source = delete.Option(
- "-s|--source ",
- Strings.Source_Description,
- CommandOptionType.SingleValue);
-
- var nonInteractive = delete.Option(
- "--non-interactive",
- Strings.NonInteractive_Description,
- CommandOptionType.NoValue);
-
- var apikey = delete.Option(
- "-k|--api-key ",
- Strings.ApiKey_Description,
- CommandOptionType.SingleValue);
-
- var arguments = delete.Argument(
- "[root]",
- Strings.Delete_PackageIdAndVersion_Description,
- multipleValues: true);
-
- var noServiceEndpointDescription = delete.Option(
- "--no-service-endpoint",
- Strings.NoServiceEndpoint_Description,
- CommandOptionType.NoValue);
-
- var interactive = delete.Option(
- "--interactive",
- Strings.NuGetXplatCommand_Interactive,
- CommandOptionType.NoValue);
-
- delete.OnExecute(async () =>
- {
- if (arguments.Values.Count < 2)
- {
- throw new ArgumentException(Strings.Delete_MissingArguments);
- }
-
- string packageId = arguments.Values[0];
- string packageVersion = arguments.Values[1];
- string sourcePath = source.Value();
- string apiKeyValue = apikey.Value();
- bool nonInteractiveValue = nonInteractive.HasValue();
- bool noServiceEndpoint = noServiceEndpointDescription.HasValue();
-
- DefaultCredentialServiceUtility.SetupDefaultCredentialService(getLogger(), !interactive.HasValue());
+ string packageId = parseResult.GetValue(packageIdArgument);
+ string packageVersion = parseResult.GetValue(packageVersionArgument);
+ string sourcePath = parseResult.GetValue(sourceOption);
+ string apiKeyValue = parseResult.GetValue(apiKeyOption);
+ bool nonInteractiveValue = parseResult.GetValue(nonInteractiveOption);
+ bool noServiceEndpoint = parseResult.GetValue(noServiceEndpointOption);
+ bool interactiveValue = parseResult.GetValue(interactiveOption);
+
+ DefaultCredentialServiceUtility.SetupDefaultCredentialService(getLogger(), !interactiveValue);
#pragma warning disable CS0618 // Type or member is obsolete
- PackageSourceProvider sourceProvider = new PackageSourceProvider(XPlatUtility.GetSettingsForCurrentWorkingDirectory(), enablePackageSourcesChangedEvent: false);
+ PackageSourceProvider sourceProvider = new PackageSourceProvider(XPlatUtility.GetSettingsForCurrentWorkingDirectory(), enablePackageSourcesChangedEvent: false);
#pragma warning restore CS0618 // Type or member is obsolete
- await DeleteRunner.Run(
- sourceProvider.Settings,
- sourceProvider,
- packageId,
- packageVersion,
- sourcePath,
- apiKeyValue,
- nonInteractiveValue,
- noServiceEndpoint,
- Confirm,
- getLogger());
-
- return 0;
- });
+ await DeleteRunner.Run(
+ sourceProvider.Settings,
+ sourceProvider,
+ packageId,
+ packageVersion,
+ sourcePath,
+ apiKeyValue,
+ nonInteractiveValue,
+ noServiceEndpoint,
+ Confirm,
+ getLogger());
+
+ return 0;
});
+
+ parent.Subcommands.Add(deleteCmd);
}
private static bool Confirm(string description)
@@ -103,7 +111,7 @@ private static bool Confirm(string description)
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine(string.Format(CultureInfo.CurrentCulture, Strings.ConsoleConfirmMessage, description));
var result = Console.ReadLine();
- return result.StartsWith(Strings.ConsoleConfirmMessageAccept, StringComparison.OrdinalIgnoreCase);
+ return result != null && result.StartsWith(Strings.ConsoleConfirmMessageAccept, StringComparison.OrdinalIgnoreCase);
}
finally
{
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/LocalsCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/LocalsCommand.cs
index 4b54b532bee..1ee2cf961b7 100644
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/LocalsCommand.cs
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/LocalsCommand.cs
@@ -4,79 +4,84 @@
#nullable enable
using System;
+using System.CommandLine;
+using System.Collections.Generic;
using System.Globalization;
-using Microsoft.Extensions.CommandLineUtils;
+using System.Threading.Tasks;
using NuGet.Commands;
-using NuGet.Common;
namespace NuGet.CommandLine.XPlat
{
internal static class LocalsCommand
{
- public static void Register(CommandLineApplication app, Func getLogger)
+ internal static void Register(Command parent, Func getLogger)
{
- app.Command("locals", locals =>
+ var localsCmd = new Command("locals", Strings.LocalsCommand_Description);
+
+ var clearOption = new Option("--clear", "-c")
{
- locals.Description = Strings.LocalsCommand_Description;
- locals.HelpOption(XPlatUtility.HelpOption);
+ Arity = ArgumentArity.Zero,
+ Description = Strings.LocalsCommand_ClearDescription,
+ };
- locals.Option(
- CommandConstants.ForceEnglishOutputOption,
- Strings.ForceEnglishOutput_Description,
- CommandOptionType.NoValue);
+ var listOption = new Option("--list", "-l")
+ {
+ Arity = ArgumentArity.Zero,
+ Description = Strings.LocalsCommand_ListDescription,
+ };
- var clear = locals.Option(
- "-c|--clear",
- Strings.LocalsCommand_ClearDescription,
- CommandOptionType.NoValue);
+ var cacheLocationArgument = new Argument("Cache Location(s)")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.LocalsCommand_ArgumentDescription,
+ };
- var list = locals.Option(
- "-l|--list",
- Strings.LocalsCommand_ListDescription,
- CommandOptionType.NoValue);
+ localsCmd.Options.Add(clearOption);
+ localsCmd.Options.Add(listOption);
+ localsCmd.Arguments.Add(cacheLocationArgument);
- var arguments = locals.Argument(
- "Cache Location(s)",
- Strings.LocalsCommand_ArgumentDescription,
- multipleValues: false);
+ localsCmd.SetAction((parseResult, cancellationToken) =>
+ {
+ var logger = getLogger();
+ var setting = XPlatUtility.GetSettingsForCurrentWorkingDirectory();
- locals.OnExecute(() =>
- {
- var logger = getLogger();
- var setting = XPlatUtility.GetSettingsForCurrentWorkingDirectory();
+ string? cacheLocation = parseResult.GetValue(cacheLocationArgument);
+ bool clear = parseResult.GetValue(clearOption);
+ bool list = parseResult.GetValue(listOption);
- // Using both -clear and -list command options, or neither one of them, is not supported.
- // We use MinArgs = 0 even though the first argument is required,
- // to avoid throwing a command argument validation exception and
- // immediately show usage help for this command instead.
- if ((arguments.Values.Count < 1) || string.IsNullOrWhiteSpace(arguments.Values[0]))
- {
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_NoArguments));
- }
- else if (clear.HasValue() && list.HasValue())
- {
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_MultipleOperations));
- }
- else if (!clear.HasValue() && !list.HasValue())
- {
- throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_NoOperation));
- }
- else
- {
- var localsArgs = new LocalsArgs(arguments.Values,
- setting,
- logger.LogInformation,
- logger.LogError,
- clear.HasValue(),
- list.HasValue());
+ // Using both -clear and -list command options, or neither one of them, is not supported.
+ // We use MinArgs = 0 even though the first argument is required,
+ // to avoid throwing a command argument validation exception and
+ // immediately show usage help for this command instead.
+ if (string.IsNullOrWhiteSpace(cacheLocation))
+ {
+ throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_NoArguments));
+ }
+ else if (clear && list)
+ {
+ throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_MultipleOperations));
+ }
+ else if (!clear && !list)
+ {
+ throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.LocalsCommand_NoOperation));
+ }
+ else
+ {
+ var localsArgs = new LocalsArgs(new List { cacheLocation },
+ setting,
+ logger.LogInformation,
+ logger.LogError,
+ clear,
+ list);
- var localsCommandRunner = new LocalsCommandRunner();
- localsCommandRunner.ExecuteCommand(localsArgs);
- }
+ var localsCommandRunner = new LocalsCommandRunner();
+ localsCommandRunner.ExecuteCommand(localsArgs);
+ }
- return 0;
- });
+ return Task.FromResult(0);
});
+
+ parent.Subcommands.Add(localsCmd);
}
}
}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Add/DotnetNuGetAddCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Add/DotnetNuGetAddCommand.cs
new file mode 100644
index 00000000000..6a9e5207a05
--- /dev/null
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Add/DotnetNuGetAddCommand.cs
@@ -0,0 +1,118 @@
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System;
+using System.CommandLine;
+using System.Threading.Tasks;
+using NuGet.Commands;
+
+namespace NuGet.CommandLine.XPlat.Commands.NuGet.Add
+{
+ internal static class DotnetNuGetAddCommand
+ {
+ internal static void Register(Command parent, Func getLogger)
+ {
+ var addCmd = new Command("add", Strings.Add_Description);
+
+ RegisterAddSource(addCmd, getLogger);
+ RegisterAddClientCert(addCmd, getLogger);
+
+ parent.Subcommands.Add(addCmd);
+ }
+
+ private static void RegisterAddSource(Command parent, Func getLogger)
+ {
+ var sourceCmd = new Command("source", Strings.AddSourceCommandDescription);
+
+ var sourceArg = new Argument("PackageSourcePath") { Description = Strings.SourcesCommandSourceDescription };
+ var name = new Option("--name", "-n") { Description = Strings.SourcesCommandNameDescription };
+ var username = new Option("--username", "-u") { Description = Strings.SourcesCommandUsernameDescription };
+ var password = new Option("--password", "-p") { Description = Strings.SourcesCommandPasswordDescription };
+ var storePasswordInClearText = new Option("--store-password-in-clear-text") { Description = Strings.SourcesCommandStorePasswordInClearTextDescription };
+ var validAuthenticationTypes = new Option("--valid-authentication-types") { Description = Strings.SourcesCommandValidAuthenticationTypesDescription };
+ var protocolVersion = new Option("--protocol-version") { Description = Strings.SourcesCommandProtocolVersionDescription };
+ var configfile = new Option("--configfile") { Description = Strings.Option_ConfigFile };
+ var allowInsecureConnections = new Option("--allow-insecure-connections") { Description = Strings.SourcesCommandAllowInsecureConnectionsDescription };
+
+ sourceCmd.Arguments.Add(sourceArg);
+ sourceCmd.Options.Add(name);
+ sourceCmd.Options.Add(username);
+ sourceCmd.Options.Add(password);
+ sourceCmd.Options.Add(storePasswordInClearText);
+ sourceCmd.Options.Add(validAuthenticationTypes);
+ sourceCmd.Options.Add(protocolVersion);
+ sourceCmd.Options.Add(configfile);
+ sourceCmd.Options.Add(allowInsecureConnections);
+
+ sourceCmd.SetAction((parseResult, cancellationToken) =>
+ {
+ var args = new AddSourceArgs()
+ {
+ Source = parseResult.GetValue(sourceArg),
+ Name = parseResult.GetValue(name),
+ Username = parseResult.GetValue(username),
+ Password = parseResult.GetValue(password),
+ StorePasswordInClearText = parseResult.GetValue(storePasswordInClearText),
+ ValidAuthenticationTypes = parseResult.GetValue(validAuthenticationTypes),
+ ProtocolVersion = parseResult.GetValue(protocolVersion),
+ Configfile = parseResult.GetValue(configfile),
+ AllowInsecureConnections = parseResult.GetValue(allowInsecureConnections),
+ };
+
+ AddSourceRunner.Run(args, () => getLogger());
+ return Task.FromResult(0);
+ });
+
+ parent.Subcommands.Add(sourceCmd);
+ }
+
+ private static void RegisterAddClientCert(Command parent, Func getLogger)
+ {
+ var clientCertCmd = new Command("client-cert", Strings.AddClientCertCommandDescription);
+
+ var packagesource = new Option("--package-source", "-s") { Description = Strings.Option_PackageSource };
+ var path = new Option("--path") { Description = Strings.Option_Path };
+ var password = new Option("--password") { Description = Strings.Option_Password };
+ var storePasswordInClearText = new Option("--store-password-in-clear-text") { Description = Strings.Option_StorePasswordInClearText };
+ var storeLocation = new Option("--store-location") { Description = Strings.Option_StoreLocation };
+ var storeName = new Option("--store-name") { Description = Strings.Option_StoreName };
+ var findBy = new Option("--find-by") { Description = Strings.Option_FindBy };
+ var findValue = new Option("--find-value") { Description = Strings.Option_FindValue };
+ var force = new Option("--force", "-f") { Description = Strings.Option_Force };
+ var configfile = new Option("--configfile") { Description = Strings.Option_ConfigFile };
+
+ clientCertCmd.Options.Add(packagesource);
+ clientCertCmd.Options.Add(path);
+ clientCertCmd.Options.Add(password);
+ clientCertCmd.Options.Add(storePasswordInClearText);
+ clientCertCmd.Options.Add(storeLocation);
+ clientCertCmd.Options.Add(storeName);
+ clientCertCmd.Options.Add(findBy);
+ clientCertCmd.Options.Add(findValue);
+ clientCertCmd.Options.Add(force);
+ clientCertCmd.Options.Add(configfile);
+
+ clientCertCmd.SetAction((parseResult, cancellationToken) =>
+ {
+ var args = new AddClientCertArgs()
+ {
+ PackageSource = parseResult.GetValue(packagesource),
+ Path = parseResult.GetValue(path),
+ Password = parseResult.GetValue(password),
+ StorePasswordInClearText = parseResult.GetValue(storePasswordInClearText),
+ StoreLocation = parseResult.GetValue(storeLocation),
+ StoreName = parseResult.GetValue(storeName),
+ FindBy = parseResult.GetValue(findBy),
+ FindValue = parseResult.GetValue(findValue),
+ Force = parseResult.GetValue(force),
+ Configfile = parseResult.GetValue(configfile),
+ };
+
+ AddClientCertRunner.Run(args, () => getLogger());
+ return Task.FromResult(0);
+ });
+
+ parent.Subcommands.Add(clientCertCmd);
+ }
+ }
+}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Disable/DotnetNuGetDisableCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Disable/DotnetNuGetDisableCommand.cs
new file mode 100644
index 00000000000..72b76f240fc
--- /dev/null
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Disable/DotnetNuGetDisableCommand.cs
@@ -0,0 +1,41 @@
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System;
+using System.CommandLine;
+using System.Threading.Tasks;
+using NuGet.Commands;
+
+namespace NuGet.CommandLine.XPlat.Commands.NuGet.Disable
+{
+ internal static class DotnetNuGetDisableCommand
+ {
+ internal static void Register(Command parent, Func getLogger)
+ {
+ var disableCmd = new Command("disable", Strings.Disable_Description);
+
+ var sourceCmd = new Command("source", Strings.DisableSourceCommandDescription);
+
+ var nameArg = new Argument("name") { Description = Strings.SourcesCommandNameDescription };
+ var configfile = new Option("--configfile") { Description = Strings.Option_ConfigFile };
+
+ sourceCmd.Arguments.Add(nameArg);
+ sourceCmd.Options.Add(configfile);
+
+ sourceCmd.SetAction((parseResult, cancellationToken) =>
+ {
+ var args = new DisableSourceArgs()
+ {
+ Name = parseResult.GetValue(nameArg),
+ Configfile = parseResult.GetValue(configfile),
+ };
+
+ DisableSourceRunner.Run(args, () => getLogger());
+ return Task.FromResult(0);
+ });
+
+ disableCmd.Subcommands.Add(sourceCmd);
+ parent.Subcommands.Add(disableCmd);
+ }
+ }
+}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Enable/DotnetNuGetEnableCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Enable/DotnetNuGetEnableCommand.cs
new file mode 100644
index 00000000000..a785a3f53ad
--- /dev/null
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Enable/DotnetNuGetEnableCommand.cs
@@ -0,0 +1,41 @@
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System;
+using System.CommandLine;
+using System.Threading.Tasks;
+using NuGet.Commands;
+
+namespace NuGet.CommandLine.XPlat.Commands.NuGet.Enable
+{
+ internal static class DotnetNuGetEnableCommand
+ {
+ internal static void Register(Command parent, Func getLogger)
+ {
+ var enableCmd = new Command("enable", Strings.Enable_Description);
+
+ var sourceCmd = new Command("source", Strings.EnableSourceCommandDescription);
+
+ var nameArg = new Argument("name") { Description = Strings.SourcesCommandNameDescription };
+ var configfile = new Option("--configfile") { Description = Strings.Option_ConfigFile };
+
+ sourceCmd.Arguments.Add(nameArg);
+ sourceCmd.Options.Add(configfile);
+
+ sourceCmd.SetAction((parseResult, cancellationToken) =>
+ {
+ var args = new EnableSourceArgs()
+ {
+ Name = parseResult.GetValue(nameArg),
+ Configfile = parseResult.GetValue(configfile),
+ };
+
+ EnableSourceRunner.Run(args, () => getLogger());
+ return Task.FromResult(0);
+ });
+
+ enableCmd.Subcommands.Add(sourceCmd);
+ parent.Subcommands.Add(enableCmd);
+ }
+ }
+}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/List/DotnetNuGetListCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/List/DotnetNuGetListCommand.cs
new file mode 100644
index 00000000000..6972006ef04
--- /dev/null
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/List/DotnetNuGetListCommand.cs
@@ -0,0 +1,70 @@
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System;
+using System.CommandLine;
+using System.Threading.Tasks;
+using NuGet.Commands;
+
+namespace NuGet.CommandLine.XPlat.Commands.NuGet.List
+{
+ internal static class DotnetNuGetListCommand
+ {
+ internal static void Register(Command parent, Func getLogger)
+ {
+ var listCmd = new Command("list", Strings.List_Description);
+
+ RegisterListSource(listCmd, getLogger);
+ RegisterListClientCert(listCmd, getLogger);
+
+ parent.Subcommands.Add(listCmd);
+ }
+
+ private static void RegisterListSource(Command parent, Func getLogger)
+ {
+ var sourceCmd = new Command("source", Strings.ListSourceCommandDescription);
+
+ var format = new Option("--format") { Description = Strings.SourcesCommandFormatDescription };
+ var configfile = new Option("--configfile") { Description = Strings.Option_ConfigFile };
+
+ sourceCmd.Options.Add(format);
+ sourceCmd.Options.Add(configfile);
+
+ sourceCmd.SetAction((parseResult, cancellationToken) =>
+ {
+ var args = new ListSourceArgs()
+ {
+ Format = parseResult.GetValue(format),
+ Configfile = parseResult.GetValue(configfile),
+ };
+
+ ListSourceRunner.Run(args, () => getLogger());
+ return Task.FromResult(0);
+ });
+
+ parent.Subcommands.Add(sourceCmd);
+ }
+
+ private static void RegisterListClientCert(Command parent, Func getLogger)
+ {
+ var clientCertCmd = new Command("client-cert", Strings.ListClientCertCommandDescription);
+
+ var configfile = new Option("--configfile") { Description = Strings.Option_ConfigFile };
+
+ clientCertCmd.Options.Add(configfile);
+
+ clientCertCmd.SetAction((parseResult, cancellationToken) =>
+ {
+ var args = new ListClientCertArgs()
+ {
+ Configfile = parseResult.GetValue(configfile),
+ };
+
+ ListClientCertRunner.Run(args, () => getLogger());
+ return Task.FromResult(0);
+ });
+
+ parent.Subcommands.Add(clientCertCmd);
+ }
+ }
+}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Remove/DotnetNuGetRemoveCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Remove/DotnetNuGetRemoveCommand.cs
new file mode 100644
index 00000000000..7b299175775
--- /dev/null
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Remove/DotnetNuGetRemoveCommand.cs
@@ -0,0 +1,73 @@
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System;
+using System.CommandLine;
+using System.Threading.Tasks;
+using NuGet.Commands;
+
+namespace NuGet.CommandLine.XPlat.Commands.NuGet.Remove
+{
+ internal static class DotnetNuGetRemoveCommand
+ {
+ internal static void Register(Command parent, Func getLogger)
+ {
+ var removeCmd = new Command("remove", Strings.Remove_Description);
+
+ RegisterRemoveSource(removeCmd, getLogger);
+ RegisterRemoveClientCert(removeCmd, getLogger);
+
+ parent.Subcommands.Add(removeCmd);
+ }
+
+ private static void RegisterRemoveSource(Command parent, Func getLogger)
+ {
+ var sourceCmd = new Command("source", Strings.RemoveSourceCommandDescription);
+
+ var nameArg = new Argument("name") { Description = Strings.SourcesCommandNameDescription };
+ var configfile = new Option("--configfile") { Description = Strings.Option_ConfigFile };
+
+ sourceCmd.Arguments.Add(nameArg);
+ sourceCmd.Options.Add(configfile);
+
+ sourceCmd.SetAction((parseResult, cancellationToken) =>
+ {
+ var args = new RemoveSourceArgs()
+ {
+ Name = parseResult.GetValue(nameArg),
+ Configfile = parseResult.GetValue(configfile),
+ };
+
+ RemoveSourceRunner.Run(args, () => getLogger());
+ return Task.FromResult(0);
+ });
+
+ parent.Subcommands.Add(sourceCmd);
+ }
+
+ private static void RegisterRemoveClientCert(Command parent, Func getLogger)
+ {
+ var clientCertCmd = new Command("client-cert", Strings.RemoveClientCertCommandDescription);
+
+ var packagesource = new Option("--package-source", "-s") { Description = Strings.Option_PackageSource };
+ var configfile = new Option("--configfile") { Description = Strings.Option_ConfigFile };
+
+ clientCertCmd.Options.Add(packagesource);
+ clientCertCmd.Options.Add(configfile);
+
+ clientCertCmd.SetAction((parseResult, cancellationToken) =>
+ {
+ var args = new RemoveClientCertArgs()
+ {
+ PackageSource = parseResult.GetValue(packagesource),
+ Configfile = parseResult.GetValue(configfile),
+ };
+
+ RemoveClientCertRunner.Run(args, () => getLogger());
+ return Task.FromResult(0);
+ });
+
+ parent.Subcommands.Add(clientCertCmd);
+ }
+ }
+}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Update/DotnetNuGetUpdateCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Update/DotnetNuGetUpdateCommand.cs
new file mode 100644
index 00000000000..e30ea29eb87
--- /dev/null
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/NuGet/Update/DotnetNuGetUpdateCommand.cs
@@ -0,0 +1,118 @@
+// Copyright (c) .NET Foundation. All rights reserved.
+// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
+using System;
+using System.CommandLine;
+using System.Threading.Tasks;
+using NuGet.Commands;
+
+namespace NuGet.CommandLine.XPlat.Commands.NuGet.Update
+{
+ internal static class DotnetNuGetUpdateCommand
+ {
+ internal static void Register(Command parent, Func getLogger)
+ {
+ var updateCmd = new Command("update", Strings.Update_Description);
+
+ RegisterUpdateSource(updateCmd, getLogger);
+ RegisterUpdateClientCert(updateCmd, getLogger);
+
+ parent.Subcommands.Add(updateCmd);
+ }
+
+ private static void RegisterUpdateSource(Command parent, Func getLogger)
+ {
+ var sourceCmd = new Command("source", Strings.UpdateSourceCommandDescription);
+
+ var nameArg = new Argument("name") { Description = Strings.SourcesCommandNameDescription };
+ var source = new Option("--source", "-s") { Description = Strings.SourcesCommandSourceDescription };
+ var username = new Option("--username", "-u") { Description = Strings.SourcesCommandUsernameDescription };
+ var password = new Option("--password", "-p") { Description = Strings.SourcesCommandPasswordDescription };
+ var storePasswordInClearText = new Option("--store-password-in-clear-text") { Description = Strings.SourcesCommandStorePasswordInClearTextDescription };
+ var validAuthenticationTypes = new Option("--valid-authentication-types") { Description = Strings.SourcesCommandValidAuthenticationTypesDescription };
+ var protocolVersion = new Option("--protocol-version") { Description = Strings.SourcesCommandProtocolVersionDescription };
+ var configfile = new Option("--configfile") { Description = Strings.Option_ConfigFile };
+ var allowInsecureConnections = new Option("--allow-insecure-connections") { Description = Strings.SourcesCommandAllowInsecureConnectionsDescription };
+
+ sourceCmd.Arguments.Add(nameArg);
+ sourceCmd.Options.Add(source);
+ sourceCmd.Options.Add(username);
+ sourceCmd.Options.Add(password);
+ sourceCmd.Options.Add(storePasswordInClearText);
+ sourceCmd.Options.Add(validAuthenticationTypes);
+ sourceCmd.Options.Add(protocolVersion);
+ sourceCmd.Options.Add(configfile);
+ sourceCmd.Options.Add(allowInsecureConnections);
+
+ sourceCmd.SetAction((parseResult, cancellationToken) =>
+ {
+ var args = new UpdateSourceArgs()
+ {
+ Name = parseResult.GetValue(nameArg),
+ Source = parseResult.GetValue(source),
+ Username = parseResult.GetValue(username),
+ Password = parseResult.GetValue(password),
+ StorePasswordInClearText = parseResult.GetValue(storePasswordInClearText),
+ ValidAuthenticationTypes = parseResult.GetValue(validAuthenticationTypes),
+ ProtocolVersion = parseResult.GetValue(protocolVersion),
+ Configfile = parseResult.GetValue(configfile),
+ AllowInsecureConnections = parseResult.GetValue(allowInsecureConnections),
+ };
+
+ UpdateSourceRunner.Run(args, () => getLogger());
+ return Task.FromResult(0);
+ });
+
+ parent.Subcommands.Add(sourceCmd);
+ }
+
+ private static void RegisterUpdateClientCert(Command parent, Func getLogger)
+ {
+ var clientCertCmd = new Command("client-cert", Strings.UpdateClientCertCommandDescription);
+
+ var packagesource = new Option("--package-source", "-s") { Description = Strings.Option_PackageSource };
+ var path = new Option("--path") { Description = Strings.Option_Path };
+ var password = new Option("--password") { Description = Strings.Option_Password };
+ var storePasswordInClearText = new Option("--store-password-in-clear-text") { Description = Strings.Option_StorePasswordInClearText };
+ var storeLocation = new Option("--store-location") { Description = Strings.Option_StoreLocation };
+ var storeName = new Option("--store-name") { Description = Strings.Option_StoreName };
+ var findBy = new Option("--find-by") { Description = Strings.Option_FindBy };
+ var findValue = new Option("--find-value") { Description = Strings.Option_FindValue };
+ var force = new Option("--force", "-f") { Description = Strings.Option_Force };
+ var configfile = new Option("--configfile") { Description = Strings.Option_ConfigFile };
+
+ clientCertCmd.Options.Add(packagesource);
+ clientCertCmd.Options.Add(path);
+ clientCertCmd.Options.Add(password);
+ clientCertCmd.Options.Add(storePasswordInClearText);
+ clientCertCmd.Options.Add(storeLocation);
+ clientCertCmd.Options.Add(storeName);
+ clientCertCmd.Options.Add(findBy);
+ clientCertCmd.Options.Add(findValue);
+ clientCertCmd.Options.Add(force);
+ clientCertCmd.Options.Add(configfile);
+
+ clientCertCmd.SetAction((parseResult, cancellationToken) =>
+ {
+ var args = new UpdateClientCertArgs()
+ {
+ PackageSource = parseResult.GetValue(packagesource),
+ Path = parseResult.GetValue(path),
+ Password = parseResult.GetValue(password),
+ StorePasswordInClearText = parseResult.GetValue(storePasswordInClearText),
+ StoreLocation = parseResult.GetValue(storeLocation),
+ StoreName = parseResult.GetValue(storeName),
+ FindBy = parseResult.GetValue(findBy),
+ FindValue = parseResult.GetValue(findValue),
+ Force = parseResult.GetValue(force),
+ Configfile = parseResult.GetValue(configfile),
+ };
+
+ UpdateClientCertRunner.Run(args, () => getLogger());
+ return Task.FromResult(0);
+ });
+
+ parent.Subcommands.Add(clientCertCmd);
+ }
+ }
+}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/AddPackageReferenceCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/AddPackageReferenceCommand.cs
index 5824f320029..51d199b1e0f 100644
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/AddPackageReferenceCommand.cs
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/AddPackageReferenceCommand.cs
@@ -4,116 +4,141 @@
#nullable enable
using System;
+using System.CommandLine;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
-using Microsoft.Extensions.CommandLineUtils;
-using NuGet.Common;
using NuGet.Packaging.Signing;
namespace NuGet.CommandLine.XPlat
{
internal static class AddPackageReferenceCommand
{
- public static void Register(CommandLineApplication app, Func getLogger,
+ internal static void Register(Command parent, Func getLogger,
Func getCommandRunner,
Func? getVirtualProjectBuilder = null)
{
- app.Command("add", addpkg =>
+ var addCommand = new Command("add", Strings.AddPkg_Description);
+
+ var id = new Option("--package")
+ {
+ Description = Strings.AddPkg_PackageIdDescription,
+ Arity = ArgumentArity.ExactlyOne
+ };
+
+ var version = new Option("--version")
+ {
+ Description = Strings.AddPkg_PackageVersionDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var dgFilePath = new Option("--dg-file", "-d")
+ {
+ Description = Strings.AddPkg_DgFileDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var projectPath = new Option("--project", "-p")
+ {
+ Description = Strings.AddPkg_ProjectPathDescription,
+ Arity = ArgumentArity.ExactlyOne
+ };
+
+ var frameworks = new Option("--framework", "-f")
+ {
+ Description = Strings.AddPkg_FrameworksDescription,
+ Arity = ArgumentArity.OneOrMore
+ };
+
+ var noRestore = new Option("--no-restore", "-n")
+ {
+ Description = Strings.AddPkg_NoRestoreDescription,
+ Arity = ArgumentArity.Zero
+ };
+
+ var sources = new Option("--source", "-s")
+ {
+ Description = Strings.AddPkg_SourcesDescription,
+ Arity = ArgumentArity.OneOrMore
+ };
+
+ var packageDirectory = new Option("--package-directory")
+ {
+ Description = Strings.AddPkg_PackageDirectoryDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var interactive = new Option("--interactive")
+ {
+ Description = Strings.AddPkg_InteractiveDescription,
+ Arity = ArgumentArity.Zero
+ };
+
+ var prerelease = new Option("--prerelease")
+ {
+ Description = Strings.Prerelease_Description,
+ Arity = ArgumentArity.Zero
+ };
+
+ addCommand.Options.Add(id);
+ addCommand.Options.Add(version);
+ addCommand.Options.Add(dgFilePath);
+ addCommand.Options.Add(projectPath);
+ addCommand.Options.Add(frameworks);
+ addCommand.Options.Add(noRestore);
+ addCommand.Options.Add(sources);
+ addCommand.Options.Add(packageDirectory);
+ addCommand.Options.Add(interactive);
+ addCommand.Options.Add(prerelease);
+
+ addCommand.SetAction(async (parseResult, cancellationToken) =>
{
- addpkg.Description = Strings.AddPkg_Description;
- addpkg.HelpOption(XPlatUtility.HelpOption);
-
- addpkg.Option(
- CommandConstants.ForceEnglishOutputOption,
- Strings.ForceEnglishOutput_Description,
- CommandOptionType.NoValue);
-
- var id = addpkg.Option(
- "--package",
- Strings.AddPkg_PackageIdDescription,
- CommandOptionType.SingleValue);
-
- var version = addpkg.Option(
- "--version",
- Strings.AddPkg_PackageVersionDescription,
- CommandOptionType.SingleValue);
-
- var dgFilePath = addpkg.Option(
- "-d|--dg-file",
- Strings.AddPkg_DgFileDescription,
- CommandOptionType.SingleValue);
-
- var projectPath = addpkg.Option(
- "-p|--project",
- Strings.AddPkg_ProjectPathDescription,
- CommandOptionType.SingleValue);
-
- var frameworks = addpkg.Option(
- "-f|--framework",
- Strings.AddPkg_FrameworksDescription,
- CommandOptionType.MultipleValue);
-
- var noRestore = addpkg.Option(
- "-n|--no-restore",
- Strings.AddPkg_NoRestoreDescription,
- CommandOptionType.NoValue);
-
- var sources = addpkg.Option(
- "-s|--source",
- Strings.AddPkg_SourcesDescription,
- CommandOptionType.MultipleValue);
-
- var packageDirectory = addpkg.Option(
- "--package-directory",
- Strings.AddPkg_PackageDirectoryDescription,
- CommandOptionType.SingleValue);
-
- var interactive = addpkg.Option(
- "--interactive",
- Strings.AddPkg_InteractiveDescription,
- CommandOptionType.NoValue);
-
- var prerelease = addpkg.Option(
- "--prerelease",
- Strings.Prerelease_Description,
- CommandOptionType.NoValue);
-
- addpkg.OnExecute(() =>
+ var virtualProjectBuilder = getVirtualProjectBuilder?.Invoke();
+
+ var idValue = parseResult.GetValue(id);
+ var projectPathValue = parseResult.GetValue(projectPath);
+ var dgFilePathValue = parseResult.GetValue(dgFilePath);
+ var noRestoreValue = parseResult.GetValue(noRestore);
+ var prereleaseValue = parseResult.GetValue(prerelease);
+ var versionValue = parseResult.GetValue(version);
+
+ ValidateArgument(idValue, "--package", "add");
+ ValidateArgument(projectPathValue, "--project", "add");
+ ValidateProjectPath(projectPathValue, "add", virtualProjectBuilder);
+ if (!noRestoreValue)
+ {
+ ValidateArgument(dgFilePathValue, "--dg-file", "add");
+ }
+ var logger = getLogger();
+ var noVersion = string.IsNullOrEmpty(versionValue);
+ var packageVersion = !string.IsNullOrEmpty(versionValue) ? versionValue : null;
+ ValidatePrerelease(prereleaseValue, noVersion, "add");
+
+ var frameworkValues = parseResult.GetValue(frameworks) ?? Array.Empty();
+ var sourceValues = parseResult.GetValue(sources) ?? Array.Empty();
+
+ var packageRefArgs = new PackageReferenceArgs(projectPathValue, logger)
{
- var virtualProjectBuilder = getVirtualProjectBuilder?.Invoke();
-
- ValidateArgument(id, addpkg.Name);
- ValidateArgument(projectPath, addpkg.Name);
- ValidateProjectPath(projectPath, addpkg.Name, virtualProjectBuilder);
- if (!noRestore.HasValue())
- {
- ValidateArgument(dgFilePath, addpkg.Name);
- }
- var logger = getLogger();
- var noVersion = !version.HasValue();
- var packageVersion = version.HasValue() ? version.Value() : null;
- ValidatePrerelease(prerelease.HasValue(), noVersion, addpkg.Name);
- var packageRefArgs = new PackageReferenceArgs(projectPath.Value(), logger)
- {
- Frameworks = CommandLineUtility.SplitAndJoinAcrossMultipleValues(frameworks.Values),
- Sources = CommandLineUtility.SplitAndJoinAcrossMultipleValues(sources.Values),
- PackageDirectory = packageDirectory.Value(),
- NoRestore = noRestore.HasValue(),
- NoVersion = noVersion,
- DgFilePath = dgFilePath.Value(),
- Interactive = interactive.HasValue(),
- Prerelease = prerelease.HasValue(),
- PackageVersion = packageVersion,
- PackageId = id.Values[0]
- };
- var msBuild = new MSBuildAPIUtility(logger, virtualProjectBuilder);
-
- X509TrustStore.InitializeForDotNetSdk(logger);
-
- var addPackageRefCommandRunner = getCommandRunner();
- return addPackageRefCommandRunner.ExecuteCommand(packageRefArgs, msBuild);
- });
+ Frameworks = CommandLineUtility.SplitAndJoinAcrossMultipleValues(frameworkValues),
+ Sources = CommandLineUtility.SplitAndJoinAcrossMultipleValues(sourceValues),
+ PackageDirectory = parseResult.GetValue(packageDirectory) ?? string.Empty,
+ NoRestore = noRestoreValue,
+ NoVersion = noVersion,
+ DgFilePath = dgFilePathValue,
+ Interactive = parseResult.GetValue(interactive),
+ Prerelease = prereleaseValue,
+ PackageVersion = packageVersion!,
+ PackageId = idValue
+ };
+ var msBuild = new MSBuildAPIUtility(logger, virtualProjectBuilder!);
+
+ X509TrustStore.InitializeForDotNetSdk(logger);
+
+ var addPackageRefCommandRunner = getCommandRunner();
+ return await addPackageRefCommandRunner.ExecuteCommand(packageRefArgs, msBuild);
});
+
+ parent.Subcommands.Add(addCommand);
}
private static void ValidatePrerelease(bool prerelease, bool noVersion, string commandName)
@@ -125,26 +150,26 @@ private static void ValidatePrerelease(bool prerelease, bool noVersion, string c
}
}
- private static void ValidateArgument(CommandOption arg, string commandName)
+ private static void ValidateArgument([NotNull] string? value, string optionName, string commandName)
{
- if (arg.Values.Count < 1)
+ if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.Error_PkgMissingArgument,
commandName,
- arg.Template));
+ optionName));
}
}
- private static void ValidateProjectPath(CommandOption projectPath, string commandName, IVirtualProjectBuilder? virtualProjectBuilder)
+ private static void ValidateProjectPath(string projectPath, string commandName, IVirtualProjectBuilder? virtualProjectBuilder)
{
- if (!File.Exists(projectPath.Value())
- || (!projectPath.Value().EndsWith("proj", StringComparison.OrdinalIgnoreCase)
- && virtualProjectBuilder?.IsValidEntryPointPath(projectPath.Value()) != true))
+ if (!File.Exists(projectPath)
+ || (!projectPath.EndsWith("proj", StringComparison.OrdinalIgnoreCase)
+ && virtualProjectBuilder?.IsValidEntryPointPath(projectPath) != true))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
Strings.Error_PkgMissingOrInvalidProjectFile,
commandName,
- projectPath.Value()));
+ projectPath));
}
}
}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/ListPackage/ListPackageCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/ListPackage/ListPackageCommand.cs
index 3d37371dc42..1a5bab20e3e 100644
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/ListPackage/ListPackageCommand.cs
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/ListPackage/ListPackageCommand.cs
@@ -5,11 +5,11 @@
using System;
using System.Collections.Generic;
+using System.CommandLine;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Threading;
-using Microsoft.Extensions.CommandLineUtils;
using NuGet.CommandLine.XPlat.ListPackage;
using NuGet.Commands;
using NuGet.Common;
@@ -20,137 +20,169 @@ namespace NuGet.CommandLine.XPlat
{
internal static class ListPackageCommand
{
- public static void Register(
- CommandLineApplication app,
- Func getLogger,
+ internal static void Register(
+ Command parent,
+ Func getLogger,
Action setLogLevel,
- Func getCommandRunner)
+ Func getCommandRunner,
+ TextWriter? consoleOut = null,
+ TextWriter? consoleError = null)
{
- app.Command("list", listpkg =>
+ var listCommand = new Command("list", Strings.ListPkg_Description);
+
+ var path = new Argument("")
{
- listpkg.Description = Strings.ListPkg_Description;
- listpkg.HelpOption(XPlatUtility.HelpOption);
-
- listpkg.Option(
- CommandConstants.ForceEnglishOutputOption,
- Strings.ForceEnglishOutput_Description,
- CommandOptionType.NoValue);
-
- var path = listpkg.Argument(
- "",
- Strings.ListPkg_PathDescription,
- multipleValues: false);
-
- var framework = listpkg.Option(
- "--framework",
- Strings.ListPkg_FrameworkDescription,
- CommandOptionType.MultipleValue);
-
- var deprecatedReport = listpkg.Option(
- "--deprecated",
- Strings.ListPkg_DeprecatedDescription,
- CommandOptionType.NoValue);
-
- var outdatedReport = listpkg.Option(
- "--outdated",
- Strings.ListPkg_OutdatedDescription,
- CommandOptionType.NoValue);
-
- var vulnerableReport = listpkg.Option(
- "--vulnerable",
- Strings.ListPkg_VulnerableDescription,
- CommandOptionType.NoValue);
-
- var includeTransitive = listpkg.Option(
- "--include-transitive",
- Strings.ListPkg_TransitiveDescription,
- CommandOptionType.NoValue);
-
- var prerelease = listpkg.Option(
- "--include-prerelease",
- Strings.ListPkg_PrereleaseDescription,
- CommandOptionType.NoValue);
-
- var highestPatch = listpkg.Option(
- "--highest-patch",
- Strings.ListPkg_HighestPatchDescription,
- CommandOptionType.NoValue);
-
- var highestMinor = listpkg.Option(
- "--highest-minor",
- Strings.ListPkg_HighestMinorDescription,
- CommandOptionType.NoValue);
-
- var source = listpkg.Option(
- "--source",
- Strings.ListPkg_SourceDescription,
- CommandOptionType.MultipleValue);
-
- var config = listpkg.Option(
- "--config",
- Strings.ListPkg_ConfigDescription,
- CommandOptionType.SingleValue);
-
- var outputFormat = listpkg.Option(
- "--format",
- Strings.ListPkg_OutputFormatDescription,
- CommandOptionType.SingleValue);
-
- var outputVersion = listpkg.Option(
- "--output-version",
- Strings.ListPkg_OutputVersionDescription,
- CommandOptionType.SingleValue);
-
- var interactive = listpkg.Option(
- "--interactive",
- Strings.NuGetXplatCommand_Interactive,
- CommandOptionType.NoValue);
-
- var verbosity = listpkg.Option(
- "-v|--verbosity",
- Strings.Verbosity_Description,
- CommandOptionType.SingleValue);
-
- listpkg.OnExecute(async () =>
- {
- var logger = getLogger();
-
- setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value()));
-
- var settings = ProcessConfigFile(config.Value(), path.Value);
- var sources = source.Values;
-
- var packageSources = GetPackageSources(settings, sources, config);
-
- var reportType = GetReportType(
- isOutdated: outdatedReport.HasValue(),
- isDeprecated: deprecatedReport.HasValue(),
- isVulnerable: vulnerableReport.HasValue());
-
- IReportRenderer reportRenderer = GetOutputType(app.Out, app.Error, outputFormat.Value(), outputVersionOption: outputVersion.Value());
- var provider = new PackageSourceProvider(settings);
- var packageRefArgs = new ListPackageArgs(
- path.Value,
- packageSources,
- framework.Values,
- reportType,
- reportRenderer,
- includeTransitive.HasValue(),
- prerelease.HasValue(),
- highestPatch.HasValue(),
- highestMinor.HasValue(),
- provider.LoadAuditSources(),
- logger,
- CancellationToken.None);
-
- WarnAboutIncompatibleOptions(packageRefArgs, reportRenderer);
-
- DefaultCredentialServiceUtility.SetupDefaultCredentialService(getLogger(), !interactive.HasValue());
-
- var listPackageCommandRunner = getCommandRunner();
- return await listPackageCommandRunner.ExecuteCommandAsync(packageRefArgs);
- });
+ Description = Strings.ListPkg_PathDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var framework = new Option("--framework")
+ {
+ Description = Strings.ListPkg_FrameworkDescription,
+ Arity = ArgumentArity.OneOrMore
+ };
+
+ var deprecatedReport = new Option("--deprecated")
+ {
+ Description = Strings.ListPkg_DeprecatedDescription,
+ Arity = ArgumentArity.Zero
+ };
+
+ var outdatedReport = new Option("--outdated")
+ {
+ Description = Strings.ListPkg_OutdatedDescription,
+ Arity = ArgumentArity.Zero
+ };
+
+ var vulnerableReport = new Option("--vulnerable")
+ {
+ Description = Strings.ListPkg_VulnerableDescription,
+ Arity = ArgumentArity.Zero
+ };
+
+ var includeTransitive = new Option("--include-transitive")
+ {
+ Description = Strings.ListPkg_TransitiveDescription,
+ Arity = ArgumentArity.Zero
+ };
+
+ var prerelease = new Option("--include-prerelease")
+ {
+ Description = Strings.ListPkg_PrereleaseDescription,
+ Arity = ArgumentArity.Zero
+ };
+
+ var highestPatch = new Option("--highest-patch")
+ {
+ Description = Strings.ListPkg_HighestPatchDescription,
+ Arity = ArgumentArity.Zero
+ };
+
+ var highestMinor = new Option("--highest-minor")
+ {
+ Description = Strings.ListPkg_HighestMinorDescription,
+ Arity = ArgumentArity.Zero
+ };
+
+ var source = new Option("--source")
+ {
+ Description = Strings.ListPkg_SourceDescription,
+ Arity = ArgumentArity.OneOrMore
+ };
+
+ var config = new Option("--config")
+ {
+ Description = Strings.ListPkg_ConfigDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var outputFormat = new Option("--format")
+ {
+ Description = Strings.ListPkg_OutputFormatDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var outputVersion = new Option("--output-version")
+ {
+ Description = Strings.ListPkg_OutputVersionDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var interactive = new Option("--interactive")
+ {
+ Description = Strings.NuGetXplatCommand_Interactive,
+ Arity = ArgumentArity.Zero
+ };
+
+ var verbosity = new Option("--verbosity", "-v")
+ {
+ Description = Strings.Verbosity_Description,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ listCommand.Arguments.Add(path);
+ listCommand.Options.Add(framework);
+ listCommand.Options.Add(deprecatedReport);
+ listCommand.Options.Add(outdatedReport);
+ listCommand.Options.Add(vulnerableReport);
+ listCommand.Options.Add(includeTransitive);
+ listCommand.Options.Add(prerelease);
+ listCommand.Options.Add(highestPatch);
+ listCommand.Options.Add(highestMinor);
+ listCommand.Options.Add(source);
+ listCommand.Options.Add(config);
+ listCommand.Options.Add(outputFormat);
+ listCommand.Options.Add(outputVersion);
+ listCommand.Options.Add(interactive);
+ listCommand.Options.Add(verbosity);
+
+ listCommand.SetAction(async (parseResult, cancellationToken) =>
+ {
+ var logger = getLogger();
+
+ var verbosityValue = parseResult.GetValue(verbosity) ?? string.Empty;
+ setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosityValue));
+
+ var pathValue = parseResult.GetValue(path) ?? string.Empty;
+ var configValue = parseResult.GetValue(config);
+ var hasConfig = !string.IsNullOrEmpty(configValue);
+
+ var settings = ProcessConfigFile(configValue, pathValue);
+ var sourceValues = parseResult.GetValue(source) ?? Array.Empty();
+
+ var packageSources = GetPackageSources(settings, sourceValues, hasConfig);
+
+ var reportType = GetReportType(
+ isOutdated: parseResult.GetValue(outdatedReport),
+ isDeprecated: parseResult.GetValue(deprecatedReport),
+ isVulnerable: parseResult.GetValue(vulnerableReport));
+
+ IReportRenderer reportRenderer = GetOutputType(consoleOut ?? Console.Out, consoleError ?? Console.Error, parseResult.GetValue(outputFormat), outputVersionOption: parseResult.GetValue(outputVersion));
+ var provider = new PackageSourceProvider(settings);
+ var frameworkValues = parseResult.GetValue(framework) ?? Array.Empty();
+ var packageRefArgs = new ListPackageArgs(
+ pathValue,
+ packageSources,
+ frameworkValues.ToList(),
+ reportType,
+ reportRenderer,
+ parseResult.GetValue(includeTransitive),
+ parseResult.GetValue(prerelease),
+ parseResult.GetValue(highestPatch),
+ parseResult.GetValue(highestMinor),
+ provider.LoadAuditSources(),
+ logger,
+ CancellationToken.None);
+
+ WarnAboutIncompatibleOptions(packageRefArgs, reportRenderer);
+
+ DefaultCredentialServiceUtility.SetupDefaultCredentialService(getLogger(), !parseResult.GetValue(interactive));
+
+ var listPackageCommandRunner = getCommandRunner();
+ return await listPackageCommandRunner.ExecuteCommandAsync(packageRefArgs);
});
+
+ parent.Subcommands.Add(listCommand);
}
private static ReportType GetReportType(bool isDeprecated, bool isOutdated, bool isVulnerable)
@@ -171,7 +203,7 @@ private static ReportType GetReportType(bool isDeprecated, bool isOutdated, bool
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.ListPkg_InvalidOptions));
}
- private static IReportRenderer GetOutputType(TextWriter consoleOut, TextWriter consoleError, string outputFormatOption, string outputVersionOption)
+ private static IReportRenderer GetOutputType(TextWriter consoleOut, TextWriter consoleError, string? outputFormatOption, string? outputVersionOption)
{
ReportOutputFormat outputFormat = ReportOutputFormat.Console;
if (!string.IsNullOrEmpty(outputFormatOption) &&
@@ -193,7 +225,6 @@ private static IReportRenderer GetOutputType(TextWriter consoleOut, TextWriter c
IReportRenderer jsonReportRenderer;
var currentlySupportedReportVersions = new List { "1" };
- // If customer pass unsupported version then error out instead of defaulting to version probably unsupported by customer machine.
if (!string.IsNullOrEmpty(outputVersionOption) && !currentlySupportedReportVersions.Contains(outputVersionOption))
{
throw new ArgumentException(string.Format(Strings.ListPkg_InvalidOutputVersion, outputVersionOption, string.Join(" ,", currentlySupportedReportVersions)));
@@ -215,7 +246,7 @@ private static void WarnAboutIncompatibleOptions(ListPackageArgs packageRefArgs,
}
}
- private static ISettings ProcessConfigFile(string configFile, string projectOrSolution)
+ private static ISettings ProcessConfigFile(string? configFile, string? projectOrSolution)
{
if (string.IsNullOrEmpty(configFile))
{
@@ -229,10 +260,9 @@ private static ISettings ProcessConfigFile(string configFile, string projectOrSo
directory,
configFileName,
machineWideSettings: new XPlatMachineWideSetting());
-
}
- private static List GetPackageSources(ISettings settings, IEnumerable sources, CommandOption config)
+ private static List GetPackageSources(ISettings settings, IEnumerable sources, bool hasConfig)
{
var availableSources = PackageSourceProvider.LoadPackageSources(settings).Where(source => source.IsEnabled);
var uniqueSources = new HashSet();
@@ -247,7 +277,7 @@ private static List GetPackageSources(ISettings settings, IEnumer
}
}
- if (packageSources.Count == 0 || config.HasValue())
+ if (packageSources.Count == 0 || hasConfig)
{
packageSources.AddRange(availableSources);
}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/RemovePackageReferenceCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/RemovePackageReferenceCommand.cs
index 1d52ac7c25e..8752c1e38a3 100644
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/RemovePackageReferenceCommand.cs
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageReferenceCommands/RemovePackageReferenceCommand.cs
@@ -4,84 +4,87 @@
#nullable enable
using System;
+using System.CommandLine;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
-using Microsoft.Extensions.CommandLineUtils;
-using NuGet.Common;
namespace NuGet.CommandLine.XPlat
{
- internal class RemovePackageReferenceCommand
+ internal static class RemovePackageReferenceCommand
{
- public static void Register(CommandLineApplication app, Func getLogger,
+ internal static void Register(Command parent, Func getLogger,
Func getCommandRunner,
Func? getVirtualProjectBuilder = null)
{
- app.Command("remove", removePkg =>
+ var removeCommand = new Command("remove", Strings.RemovePkg_Description);
+
+ var id = new Option("--package")
{
- removePkg.Description = Strings.RemovePkg_Description;
- removePkg.HelpOption(XPlatUtility.HelpOption);
+ Description = Strings.RemovePkg_PackageIdDescription,
+ Arity = ArgumentArity.ExactlyOne
+ };
- removePkg.Option(
- CommandConstants.ForceEnglishOutputOption,
- Strings.ForceEnglishOutput_Description,
- CommandOptionType.NoValue);
+ var projectPath = new Option("--project", "-p")
+ {
+ Description = Strings.RemovePkg_ProjectPathDescription,
+ Arity = ArgumentArity.ExactlyOne
+ };
- var id = removePkg.Option(
- "--package",
- Strings.RemovePkg_PackageIdDescription,
- CommandOptionType.SingleValue);
+ var interactive = new Option("--interactive")
+ {
+ Description = Strings.AddPkg_InteractiveDescription,
+ Arity = ArgumentArity.Zero
+ };
- var projectPath = removePkg.Option(
- "-p|--project",
- Strings.RemovePkg_ProjectPathDescription,
- CommandOptionType.SingleValue);
+ removeCommand.Options.Add(id);
+ removeCommand.Options.Add(projectPath);
+ removeCommand.Options.Add(interactive);
- var interactive = removePkg.Option(
- "--interactive",
- Strings.AddPkg_InteractiveDescription,
- CommandOptionType.NoValue);
+ removeCommand.SetAction(async (parseResult, cancellationToken) =>
+ {
+ var virtualProjectBuilder = getVirtualProjectBuilder?.Invoke();
- removePkg.OnExecute(() =>
- {
- var virtualProjectBuilder = getVirtualProjectBuilder?.Invoke();
+ var idValue = parseResult.GetValue(id);
+ var projectPathValue = parseResult.GetValue(projectPath);
- ValidateArgument(id, removePkg.Name);
- ValidateArgument(projectPath, removePkg.Name);
- ValidateProjectPath(projectPath, removePkg.Name, virtualProjectBuilder);
- var logger = getLogger();
- var packageRefArgs = new PackageReferenceArgs(projectPath.Value(), logger)
- {
- Interactive = interactive.HasValue(),
- PackageId = id.Value()
- };
- var msBuild = new MSBuildAPIUtility(logger, virtualProjectBuilder);
- var removePackageRefCommandRunner = getCommandRunner();
- return removePackageRefCommandRunner.ExecuteCommand(packageRefArgs, msBuild);
- });
+ ValidateArgument(idValue, "--package", "remove");
+ ValidateArgument(projectPathValue, "--project", "remove");
+ ValidateProjectPath(projectPathValue, "remove", virtualProjectBuilder);
+ var logger = getLogger();
+ var packageRefArgs = new PackageReferenceArgs(projectPathValue, logger)
+ {
+ Interactive = parseResult.GetValue(interactive),
+ PackageId = idValue
+ };
+ var msBuild = new MSBuildAPIUtility(logger, virtualProjectBuilder!);
+ var removePackageRefCommandRunner = getCommandRunner();
+ return await removePackageRefCommandRunner.ExecuteCommand(packageRefArgs, msBuild);
});
+
+ parent.Subcommands.Add(removeCommand);
}
- private static void ValidateArgument(CommandOption arg, string commandName)
+ private static void ValidateArgument([NotNull] string? value, string optionName, string commandName)
{
- if (arg.Values.Count < 1)
+ if (string.IsNullOrEmpty(value))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.Error_PkgMissingArgument,
commandName,
- arg.Template));
+ optionName));
}
}
- private static void ValidateProjectPath(CommandOption projectPath, string commandName, IVirtualProjectBuilder? virtualProjectBuilder)
+ private static void ValidateProjectPath(string projectPath, string commandName, IVirtualProjectBuilder? virtualProjectBuilder)
{
- if (!File.Exists(projectPath.Value())
- || (!projectPath.Value().EndsWith("proj", StringComparison.OrdinalIgnoreCase)
- && virtualProjectBuilder?.IsValidEntryPointPath(projectPath.Value()) != true))
+ if (!File.Exists(projectPath)
+ || (!projectPath.EndsWith("proj", StringComparison.OrdinalIgnoreCase)
+ && virtualProjectBuilder?.IsValidEntryPointPath(projectPath) != true))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
Strings.Error_PkgMissingOrInvalidProjectFile,
commandName,
- projectPath.Value()));
+ projectPath));
}
}
}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageSearch/PackageSearchCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageSearch/PackageSearchCommand.cs
index 407f6d03163..c25f6f74f21 100644
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageSearch/PackageSearchCommand.cs
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PackageSearch/PackageSearchCommand.cs
@@ -6,7 +6,6 @@
using System;
using System.Collections.Generic;
using System.CommandLine;
-using System.CommandLine.Help;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
@@ -87,11 +86,6 @@ public static void Register(Command rootCommand, Func getLogge
Arity = ArgumentArity.ExactlyOne
};
- var help = new HelpOption()
- {
- Arity = ArgumentArity.Zero
- };
-
searchCommand.Arguments.Add(searchTerm);
searchCommand.Options.Add(sources);
searchCommand.Options.Add(exactMatch);
@@ -102,7 +96,6 @@ public static void Register(Command rootCommand, Func getLogge
searchCommand.Options.Add(format);
searchCommand.Options.Add(verbosity);
searchCommand.Options.Add(configFile);
- searchCommand.Options.Add(help);
searchCommand.SetAction(async (parserResult, cancelationToken) =>
{
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PushCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PushCommand.cs
index bc09a2f2578..3b55aeb92f4 100644
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PushCommand.cs
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/PushCommand.cs
@@ -4,11 +4,9 @@
#nullable enable
using System;
-using System.Collections.Generic;
+using System.CommandLine;
using System.Threading.Tasks;
-using Microsoft.Extensions.CommandLineUtils;
using NuGet.Commands;
-using NuGet.Common;
using NuGet.Configuration;
using NuGet.Credentials;
@@ -16,139 +14,162 @@ namespace NuGet.CommandLine.XPlat
{
internal static class PushCommand
{
- public static void Register(CommandLineApplication app, Func getLogger)
+ internal static void Register(Command parent, Func getLogger)
{
- app.Command("push", push =>
+ var pushCmd = new Command("push", Strings.Push_Description);
+
+ var sourceOption = new Option("--source", "-s")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.Source_Description,
+ };
+
+ var allowInsecureConnectionsOption = new Option("--allow-insecure-connections")
+ {
+ Arity = ArgumentArity.Zero,
+ Description = Strings.AllowInsecureConnections_Description,
+ };
+
+ var symbolSourceOption = new Option("--symbol-source", "-ss")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.SymbolSource_Description,
+ };
+
+ var timeoutOption = new Option("--timeout", "-t")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.Push_Timeout_Description,
+ };
+
+ var apiKeyOption = new Option("--api-key", "-k")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.ApiKey_Description,
+ };
+
+ var symbolApiKeyOption = new Option("--symbol-api-key", "-sk")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.SymbolApiKey_Description,
+ };
+
+ var disableBufferingOption = new Option("--disable-buffering", "-d")
+ {
+ Arity = ArgumentArity.Zero,
+ Description = Strings.DisableBuffering_Description,
+ };
+
+ var noSymbolsOption = new Option("--no-symbols", "-n")
{
- push.Description = Strings.Push_Description;
- push.HelpOption(XPlatUtility.HelpOption);
-
- push.Option(
- CommandConstants.ForceEnglishOutputOption,
- Strings.ForceEnglishOutput_Description,
- CommandOptionType.NoValue);
-
- var source = push.Option(
- "-s|--source ",
- Strings.Source_Description,
- CommandOptionType.SingleValue);
-
- var allowInsecureConnections = push.Option(
- "--allow-insecure-connections",
- Strings.AllowInsecureConnections_Description,
- CommandOptionType.NoValue);
-
- var symbolSource = push.Option(
- "-ss|--symbol-source ",
- Strings.SymbolSource_Description,
- CommandOptionType.SingleValue);
-
- var timeout = push.Option(
- "-t|--timeout ",
- Strings.Push_Timeout_Description,
- CommandOptionType.SingleValue);
-
- var apikey = push.Option(
- "-k|--api-key ",
- Strings.ApiKey_Description,
- CommandOptionType.SingleValue);
-
- var symbolApiKey = push.Option(
- "-sk|--symbol-api-key ",
- Strings.SymbolApiKey_Description,
- CommandOptionType.SingleValue);
-
- var disableBuffering = push.Option(
- "-d|--disable-buffering",
- Strings.DisableBuffering_Description,
- CommandOptionType.NoValue);
-
- var noSymbols = push.Option(
- "-n|--no-symbols",
- Strings.NoSymbols_Description,
- CommandOptionType.NoValue);
-
- var arguments = push.Argument(
- "[root]",
- Strings.Push_Package_ApiKey_Description,
- multipleValues: true);
-
- var noServiceEndpointDescription = push.Option(
- "--no-service-endpoint",
- Strings.NoServiceEndpoint_Description,
- CommandOptionType.NoValue);
-
- var interactive = push.Option(
- "--interactive",
- Strings.NuGetXplatCommand_Interactive,
- CommandOptionType.NoValue);
-
- var skipDuplicate = push.Option(
- "--skip-duplicate",
- Strings.PushCommandSkipDuplicateDescription,
- CommandOptionType.NoValue);
-
- var configurationFile = push.Option(
- "--configfile",
- Strings.Option_ConfigFile,
- CommandOptionType.SingleValue);
-
- push.OnExecute(async () =>
+ Arity = ArgumentArity.Zero,
+ Description = Strings.NoSymbols_Description,
+ };
+
+ var noServiceEndpointOption = new Option("--no-service-endpoint")
+ {
+ Arity = ArgumentArity.Zero,
+ Description = Strings.NoServiceEndpoint_Description,
+ };
+
+ var interactiveOption = new Option("--interactive")
+ {
+ Arity = ArgumentArity.Zero,
+ Description = Strings.NuGetXplatCommand_Interactive,
+ };
+
+ var skipDuplicateOption = new Option("--skip-duplicate")
+ {
+ Arity = ArgumentArity.Zero,
+ Description = Strings.PushCommandSkipDuplicateDescription,
+ };
+
+ var configFileOption = new Option("--configfile")
+ {
+ Arity = ArgumentArity.ZeroOrOne,
+ Description = Strings.Option_ConfigFile,
+ };
+
+ var packagePathsArgument = new Argument("package-paths")
+ {
+ Arity = ArgumentArity.OneOrMore,
+ Description = Strings.Push_Package_ApiKey_Description,
+ };
+
+ pushCmd.Options.Add(sourceOption);
+ pushCmd.Options.Add(allowInsecureConnectionsOption);
+ pushCmd.Options.Add(symbolSourceOption);
+ pushCmd.Options.Add(timeoutOption);
+ pushCmd.Options.Add(apiKeyOption);
+ pushCmd.Options.Add(symbolApiKeyOption);
+ pushCmd.Options.Add(disableBufferingOption);
+ pushCmd.Options.Add(noSymbolsOption);
+ pushCmd.Options.Add(noServiceEndpointOption);
+ pushCmd.Options.Add(interactiveOption);
+ pushCmd.Options.Add(skipDuplicateOption);
+ pushCmd.Options.Add(configFileOption);
+ pushCmd.Arguments.Add(packagePathsArgument);
+
+ pushCmd.SetAction(async (parseResult, cancellationToken) =>
+ {
+ string[]? packagePaths = parseResult.GetValue(packagePathsArgument);
+ if (packagePaths == null || packagePaths.Length < 1)
{
- if (arguments.Values.Count < 1)
- {
- throw new ArgumentException(Strings.Push_MissingArguments);
- }
-
- IList packagePaths = arguments.Values;
- string sourcePath = source.Value();
- string apiKeyValue = apikey.Value();
- string symbolSourcePath = symbolSource.Value();
- string symbolApiKeyValue = symbolApiKey.Value();
- bool disableBufferingValue = disableBuffering.HasValue();
- bool noSymbolsValue = noSymbols.HasValue();
- bool noServiceEndpoint = noServiceEndpointDescription.HasValue();
- bool skipDuplicateValue = skipDuplicate.HasValue();
- bool allowInsecureConnectionsValue = allowInsecureConnections.HasValue();
- int timeoutSeconds = 0;
-
- if (timeout.HasValue() && !int.TryParse(timeout.Value(), out timeoutSeconds))
- {
- throw new ArgumentException(Strings.Push_InvalidTimeout);
- }
+ throw new ArgumentException(Strings.Push_MissingArguments);
+ }
+
+ string? sourcePath = parseResult.GetValue(sourceOption);
+ string? apiKeyValue = parseResult.GetValue(apiKeyOption);
+ string? symbolSourcePath = parseResult.GetValue(symbolSourceOption);
+ string? symbolApiKeyValue = parseResult.GetValue(symbolApiKeyOption);
+ bool disableBufferingValue = parseResult.GetValue(disableBufferingOption);
+ bool noSymbolsValue = parseResult.GetValue(noSymbolsOption);
+ bool noServiceEndpoint = parseResult.GetValue(noServiceEndpointOption);
+ bool skipDuplicateValue = parseResult.GetValue(skipDuplicateOption);
+ bool allowInsecureConnectionsValue = parseResult.GetValue(allowInsecureConnectionsOption);
+ bool interactiveValue = parseResult.GetValue(interactiveOption);
+ string? timeoutValue = parseResult.GetValue(timeoutOption);
+ string? configFile = parseResult.GetValue(configFileOption);
+ int timeoutSeconds = 0;
+
+ if (!string.IsNullOrEmpty(timeoutValue) && !int.TryParse(timeoutValue, out timeoutSeconds))
+ {
+ throw new ArgumentException(Strings.Push_InvalidTimeout);
+ }
#pragma warning disable CS0618 // Type or member is obsolete
- var sourceProvider = new PackageSourceProvider(XPlatUtility.ProcessConfigFile(configurationFile.Value()), enablePackageSourcesChangedEvent: false);
+ var sourceProvider = new PackageSourceProvider(XPlatUtility.ProcessConfigFile(configFile), enablePackageSourcesChangedEvent: false);
#pragma warning restore CS0618 // Type or member is obsolete
- try
- {
- DefaultCredentialServiceUtility.SetupDefaultCredentialService(getLogger(), !interactive.HasValue());
-
- await PushRunner.Run(
- sourceProvider.Settings,
- sourceProvider,
- packagePaths,
- sourcePath,
- apiKeyValue,
- symbolSourcePath,
- symbolApiKeyValue,
- timeoutSeconds,
- disableBufferingValue,
- noSymbolsValue,
- noServiceEndpoint,
- skipDuplicateValue,
- allowInsecureConnectionsValue,
- getLogger());
- }
- catch (TaskCanceledException ex)
- {
- throw new AggregateException(ex, new Exception(Strings.Push_Timeout_Error));
- }
-
- return 0;
- });
+ try
+ {
+ DefaultCredentialServiceUtility.SetupDefaultCredentialService(getLogger(), !interactiveValue);
+
+ await PushRunner.Run(
+ sourceProvider.Settings,
+ sourceProvider,
+ packagePaths,
+ sourcePath,
+ apiKeyValue,
+ symbolSourcePath,
+ symbolApiKeyValue,
+ timeoutSeconds,
+ disableBufferingValue,
+ noSymbolsValue,
+ noServiceEndpoint,
+ skipDuplicateValue,
+ allowInsecureConnectionsValue,
+ getLogger());
+ }
+ catch (TaskCanceledException ex)
+ {
+ throw new AggregateException(ex, new Exception(Strings.Push_Timeout_Error));
+ }
+
+ return 0;
});
+
+ parent.Subcommands.Add(pushCmd);
}
}
}
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/Signing/SignCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/Signing/SignCommand.cs
index 4041a3ddbe2..0abdca7d8b2 100644
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/Signing/SignCommand.cs
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/Signing/SignCommand.cs
@@ -4,11 +4,13 @@
#nullable enable
using System;
+using System.Collections.Generic;
+using System.CommandLine;
+using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Security.Cryptography.X509Certificates;
-using Microsoft.Extensions.CommandLineUtils;
using NuGet.Commands;
using NuGet.Common;
using NuGet.Packaging.Signing;
@@ -19,177 +21,212 @@ internal static class SignCommand
{
private const string CommandName = "sign";
- internal static void Register(CommandLineApplication app,
- Func getLogger,
+ internal static void Register(Command parent,
+ Func getLogger,
Action setLogLevel,
Func getCommandRunner)
{
- app.Command(CommandName, signCmd =>
+ var signCmd = new Command(CommandName, Strings.SignCommandDescription);
+
+ var packagePaths = new Argument("package-paths")
+ {
+ Description = Strings.SignCommandPackagePathDescription,
+ Arity = ArgumentArity.OneOrMore
+ };
+
+ var outputDirectory = new Option("--output", "-o")
+ {
+ Description = Strings.SignCommandOutputDirectoryDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var path = new Option("--certificate-path")
+ {
+ Description = Strings.SignCommandCertificatePathDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var store = new Option("--certificate-store-name")
+ {
+ Description = Strings.SignCommandCertificateStoreNameDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var location = new Option("--certificate-store-location")
+ {
+ Description = Strings.SignCommandCertificateStoreLocationDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var subject = new Option("--certificate-subject-name")
+ {
+ Description = Strings.SignCommandCertificateSubjectNameDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var fingerprint = new Option("--certificate-fingerprint")
+ {
+ Description = Strings.SignCommandCertificateFingerprintDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var password = new Option("--certificate-password")
{
- CommandArgument packagePaths = signCmd.Argument(
- "",
- Strings.SignCommandPackagePathDescription,
- multipleValues: true);
-
- CommandOption outputDirectory = signCmd.Option(
- "-o|--output",
- Strings.SignCommandOutputDirectoryDescription,
- CommandOptionType.SingleValue);
-
- CommandOption path = signCmd.Option(
- "--certificate-path",
- Strings.SignCommandCertificatePathDescription,
- CommandOptionType.SingleValue);
-
- CommandOption store = signCmd.Option(
- "--certificate-store-name",
- Strings.SignCommandCertificateStoreNameDescription,
- CommandOptionType.SingleValue);
-
- CommandOption location = signCmd.Option(
- "--certificate-store-location",
- Strings.SignCommandCertificateStoreLocationDescription,
- CommandOptionType.SingleValue);
-
- CommandOption subject = signCmd.Option(
- "--certificate-subject-name",
- Strings.SignCommandCertificateSubjectNameDescription,
- CommandOptionType.SingleValue);
-
- CommandOption fingerprint = signCmd.Option(
- "--certificate-fingerprint",
- Strings.SignCommandCertificateFingerprintDescription,
- CommandOptionType.SingleValue);
-
- CommandOption password = signCmd.Option(
- "--certificate-password",
- Strings.SignCommandCertificatePasswordDescription,
- CommandOptionType.SingleValue);
-
- CommandOption algorithm = signCmd.Option(
- "--hash-algorithm",
- Strings.SignCommandHashAlgorithmDescription,
- CommandOptionType.SingleValue);
-
- CommandOption timestamper = signCmd.Option(
- "--timestamper",
- Strings.SignCommandTimestamperDescription,
- CommandOptionType.SingleValue);
-
- CommandOption timestamperAlgorithm = signCmd.Option(
- "--timestamp-hash-algorithm",
- Strings.SignCommandTimestampHashAlgorithmDescription,
- CommandOptionType.SingleValue);
-
- CommandOption overwrite = signCmd.Option(
- "--overwrite",
- Strings.SignCommandOverwriteDescription,
- CommandOptionType.NoValue);
-
- CommandOption allowUntrustedRoot = signCmd.Option(
- "--allow-untrusted-root",
- Strings.SignCommandAllowUntrustedRootDescription,
- CommandOptionType.NoValue);
-
- CommandOption verbosity = signCmd.Option(
- "-v|--verbosity",
- Strings.Verbosity_Description,
- CommandOptionType.SingleValue);
-
- signCmd.HelpOption(XPlatUtility.HelpOption);
-
- signCmd.Description = Strings.SignCommandDescription;
-
- signCmd.OnExecute(async () =>
+ Description = Strings.SignCommandCertificatePasswordDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var algorithm = new Option("--hash-algorithm")
+ {
+ Description = Strings.SignCommandHashAlgorithmDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var timestamper = new Option("--timestamper")
+ {
+ Description = Strings.SignCommandTimestamperDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var timestamperAlgorithm = new Option("--timestamp-hash-algorithm")
+ {
+ Description = Strings.SignCommandTimestampHashAlgorithmDescription,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ var overwrite = new Option("--overwrite")
+ {
+ Description = Strings.SignCommandOverwriteDescription,
+ Arity = ArgumentArity.Zero
+ };
+
+ var allowUntrustedRoot = new Option("--allow-untrusted-root")
+ {
+ Description = Strings.SignCommandAllowUntrustedRootDescription,
+ Arity = ArgumentArity.Zero
+ };
+
+ var verbosity = new Option("--verbosity", "-v")
+ {
+ Description = Strings.Verbosity_Description,
+ Arity = ArgumentArity.ZeroOrOne
+ };
+
+ signCmd.Arguments.Add(packagePaths);
+ signCmd.Options.Add(outputDirectory);
+ signCmd.Options.Add(path);
+ signCmd.Options.Add(store);
+ signCmd.Options.Add(location);
+ signCmd.Options.Add(subject);
+ signCmd.Options.Add(fingerprint);
+ signCmd.Options.Add(password);
+ signCmd.Options.Add(algorithm);
+ signCmd.Options.Add(timestamper);
+ signCmd.Options.Add(timestamperAlgorithm);
+ signCmd.Options.Add(overwrite);
+ signCmd.Options.Add(allowUntrustedRoot);
+ signCmd.Options.Add(verbosity);
+
+ signCmd.SetAction(async (parseResult, cancellationToken) =>
+ {
+ ILogger logger = getLogger();
+
+ string[]? packagePathValues = parseResult.GetValue(packagePaths);
+ string? pathValue = parseResult.GetValue(path);
+ string? fingerprintValue = parseResult.GetValue(fingerprint);
+ string? subjectValue = parseResult.GetValue(subject);
+ string? storeValue = parseResult.GetValue(store);
+ string? locationValue = parseResult.GetValue(location);
+ string? outputDirectoryValue = parseResult.GetValue(outputDirectory);
+ string? timestamperValue = parseResult.GetValue(timestamper);
+ string? algorithmValue = parseResult.GetValue(algorithm);
+ string? timestamperAlgorithmValue = parseResult.GetValue(timestamperAlgorithm);
+
+ ValidatePackagePaths(packagePathValues, "package-paths");
+ WarnIfNoTimestamper(logger, timestamperValue);
+ ValidateCertificateInputs(pathValue, fingerprintValue, subjectValue, storeValue, locationValue, logger);
+ ValidateAndCreateOutputDirectory(outputDirectoryValue);
+
+ SigningSpecificationsV1 signingSpec = SigningSpecifications.V1;
+ StoreLocation storeLocation = ValidateAndParseStoreLocation(locationValue);
+ StoreName storeName = ValidateAndParseStoreName(storeValue);
+ HashAlgorithmName hashAlgorithm = CommandLineUtility.ParseAndValidateHashAlgorithm(algorithmValue, "--hash-algorithm", signingSpec);
+ HashAlgorithmName timestampHashAlgorithm = CommandLineUtility.ParseAndValidateHashAlgorithm(timestamperAlgorithmValue, "--timestamp-hash-algorithm", signingSpec);
+
+ var args = new SignArgs()
{
- ILogger logger = getLogger();
-
- ValidatePackagePaths(packagePaths);
- WarnIfNoTimestamper(logger, timestamper);
- ValidateCertificateInputs(path, fingerprint, subject, store, location, logger);
- ValidateAndCreateOutputDirectory(outputDirectory);
-
- SigningSpecificationsV1 signingSpec = SigningSpecifications.V1;
- StoreLocation storeLocation = ValidateAndParseStoreLocation(location);
- StoreName storeName = ValidateAndParseStoreName(store);
- HashAlgorithmName hashAlgorithm = CommandLineUtility.ParseAndValidateHashAlgorithm(algorithm.Value(), algorithm.LongName, signingSpec);
- HashAlgorithmName timestampHashAlgorithm = CommandLineUtility.ParseAndValidateHashAlgorithm(timestamperAlgorithm.Value(), timestamperAlgorithm.LongName, signingSpec);
-
- var args = new SignArgs()
- {
- PackagePaths = packagePaths.Values,
- OutputDirectory = outputDirectory.Value(),
- CertificatePath = path.Value(),
- CertificateStoreName = storeName,
- CertificateStoreLocation = storeLocation,
- CertificateSubjectName = subject.Value(),
- CertificateFingerprint = fingerprint.Value(),
- CertificatePassword = password.Value(),
- SignatureHashAlgorithm = hashAlgorithm,
- Logger = logger,
- Overwrite = overwrite.HasValue(),
- AllowUntrustedRoot = allowUntrustedRoot.HasValue(),
- //The interactive option is not enabled at first, so the NonInteractive is always set to true. This is tracked by https://github.com/NuGet/Home/issues/10620
- NonInteractive = true,
- Timestamper = timestamper.Value(),
- TimestampHashAlgorithm = timestampHashAlgorithm
- };
-
- setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value()));
-
- X509TrustStore.InitializeForDotNetSdk(args.Logger);
-
- ISignCommandRunner runner = getCommandRunner();
- int result = await runner.ExecuteCommandAsync(args);
- return result;
- });
+ PackagePaths = new List(packagePathValues),
+ OutputDirectory = outputDirectoryValue,
+ CertificatePath = pathValue,
+ CertificateStoreName = storeName,
+ CertificateStoreLocation = storeLocation,
+ CertificateSubjectName = subjectValue,
+ CertificateFingerprint = fingerprintValue,
+ CertificatePassword = parseResult.GetValue(password),
+ SignatureHashAlgorithm = hashAlgorithm,
+ Logger = logger,
+ Overwrite = parseResult.GetValue(overwrite),
+ AllowUntrustedRoot = parseResult.GetValue(allowUntrustedRoot),
+ //The interactive option is not enabled at first, so the NonInteractive is always set to true. This is tracked by https://github.com/NuGet/Home/issues/10620
+ NonInteractive = true,
+ Timestamper = timestamperValue,
+ TimestampHashAlgorithm = timestampHashAlgorithm
+ };
+
+ setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(parseResult.GetValue(verbosity)));
+
+ X509TrustStore.InitializeForDotNetSdk(args.Logger);
+
+ ISignCommandRunner runner = getCommandRunner();
+ int result = await runner.ExecuteCommandAsync(args);
+ return result;
});
+
+ parent.Subcommands.Add(signCmd);
}
- private static void ValidatePackagePaths(CommandArgument argument)
+ private static void ValidatePackagePaths([NotNull] string[]? packagePaths, string argumentName)
{
- if (argument.Values.Count == 0 ||
- argument.Values.Any(packagePath => string.IsNullOrEmpty(packagePath)))
+ if (packagePaths == null ||
+ packagePaths.Length == 0 ||
+ packagePaths.Any(packagePath => string.IsNullOrEmpty(packagePath)))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Strings.Error_PkgMissingArgument,
CommandName,
- argument.Name));
+ argumentName));
}
}
- private static void WarnIfNoTimestamper(ILogger logger, CommandOption timeStamper)
+ private static void WarnIfNoTimestamper(ILogger logger, string? timestamper)
{
- if (!timeStamper.HasValue())
+ if (string.IsNullOrEmpty(timestamper))
{
logger.Log(LogMessage.CreateWarning(NuGetLogCode.NU3002, Strings.SignCommandNoTimestamperWarning));
}
}
- private static void ValidateAndCreateOutputDirectory(CommandOption output)
+ private static void ValidateAndCreateOutputDirectory(string? outputDirectory)
{
- if (output.HasValue())
+ if (!string.IsNullOrEmpty(outputDirectory))
{
- string outputDir = output.Value();
-
- if (!Directory.Exists(outputDir))
+ if (!Directory.Exists(outputDirectory))
{
- Directory.CreateDirectory(outputDir);
+ Directory.CreateDirectory(outputDirectory);
}
}
}
- private static StoreLocation ValidateAndParseStoreLocation(CommandOption location)
+ private static StoreLocation ValidateAndParseStoreLocation(string? locationValue)
{
StoreLocation storeLocation = StoreLocation.CurrentUser;
- if (location.HasValue())
+ if (!string.IsNullOrEmpty(locationValue))
{
- if (!string.IsNullOrEmpty(location.Value()) &&
- !Enum.TryParse(location.Value(), ignoreCase: true, result: out storeLocation))
+ if (!Enum.TryParse(locationValue, ignoreCase: true, result: out storeLocation))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
Strings.Err_InvalidValue,
- location.LongName,
+ "--certificate-store-location",
string.Join(",", Enum.GetValues().ToList())));
}
}
@@ -197,18 +234,17 @@ private static StoreLocation ValidateAndParseStoreLocation(CommandOption locatio
return storeLocation;
}
- private static StoreName ValidateAndParseStoreName(CommandOption store)
+ private static StoreName ValidateAndParseStoreName(string? storeValue)
{
StoreName storeName = StoreName.My;
- if (store.HasValue())
+ if (!string.IsNullOrEmpty(storeValue))
{
- if (!string.IsNullOrEmpty(store.Value()) &&
- !Enum.TryParse(store.Value(), ignoreCase: true, result: out storeName))
+ if (!Enum.TryParse(storeValue, ignoreCase: true, result: out storeName))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture,
Strings.Err_InvalidValue,
- store.LongName,
+ "--certificate-store-name",
string.Join(",", Enum.GetValues().ToList())));
}
}
@@ -216,33 +252,33 @@ private static StoreName ValidateAndParseStoreName(CommandOption store)
return storeName;
}
- private static void ValidateCertificateInputs(CommandOption path, CommandOption fingerprint,
- CommandOption subject, CommandOption store, CommandOption location, ILogger logger)
+ private static void ValidateCertificateInputs(string? path, string? fingerprint,
+ string? subject, string? store, string? location, ILogger logger)
{
- if (string.IsNullOrEmpty(path.Value()) &&
- string.IsNullOrEmpty(fingerprint.Value()) &&
- string.IsNullOrEmpty(subject.Value()))
+ if (string.IsNullOrEmpty(path) &&
+ string.IsNullOrEmpty(fingerprint) &&
+ string.IsNullOrEmpty(subject))
{
// Throw if user gave no certificate input
throw new ArgumentException(Strings.SignCommandNoCertificateException);
}
- else if (!string.IsNullOrEmpty(path.Value()) &&
- (!string.IsNullOrEmpty(fingerprint.Value()) ||
- !string.IsNullOrEmpty(subject.Value()) ||
- !string.IsNullOrEmpty(location.Value()) ||
- !string.IsNullOrEmpty(store.Value())))
+ else if (!string.IsNullOrEmpty(path) &&
+ (!string.IsNullOrEmpty(fingerprint) ||
+ !string.IsNullOrEmpty(subject) ||
+ !string.IsNullOrEmpty(location) ||
+ !string.IsNullOrEmpty(store)))
{
// Throw if the user provided a path and any one of the other options
throw new ArgumentException(Strings.SignCommandMultipleCertificateException);
}
- else if (!string.IsNullOrEmpty(fingerprint.Value()) && !string.IsNullOrEmpty(subject.Value()))
+ else if (!string.IsNullOrEmpty(fingerprint) && !string.IsNullOrEmpty(subject))
{
// Throw if the user provided a fingerprint and a subject
throw new ArgumentException(Strings.SignCommandMultipleCertificateException);
}
- else if (fingerprint.Value() != null)
+ else if (fingerprint != null)
{
- bool isValidFingerprint = CertificateUtility.TryDeduceHashAlgorithm(fingerprint.Value(), out HashAlgorithmName hashAlgorithmName);
+ bool isValidFingerprint = CertificateUtility.TryDeduceHashAlgorithm(fingerprint, out HashAlgorithmName hashAlgorithmName);
bool isSHA1 = hashAlgorithmName == HashAlgorithmName.SHA1;
string message = string.Format(CultureInfo.CurrentCulture, Strings.SignCommandInvalidCertificateFingerprint, NuGetLogCode.NU3043);
diff --git a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/Signing/TrustedSignersCommand.cs b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/Signing/TrustedSignersCommand.cs
index a94852d97f5..2b0a00f8e54 100644
--- a/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/Signing/TrustedSignersCommand.cs
+++ b/src/NuGet.Core/NuGet.CommandLine.XPlat/Commands/Signing/TrustedSignersCommand.cs
@@ -4,9 +4,9 @@
#nullable disable
using System;
+using System.CommandLine;
using System.Globalization;
using System.Threading.Tasks;
-using Microsoft.Extensions.CommandLineUtils;
using NuGet.Commands;
using NuGet.Common;
using NuGet.Configuration;
@@ -17,228 +17,179 @@ namespace NuGet.CommandLine.XPlat
{
internal static class TrustedSignersCommand
{
- internal static void Register(CommandLineApplication app,
- Func getLogger,
+ internal static void Register(Command parent,
+ Func getLogger,
Action setLogLevel)
{
- app.Command("trust", trustedSignersCmd =>
- {
- // sub-commands
- trustedSignersCmd.Command("list", (listCommand) =>
- {
- listCommand.Description = Strings.TrustListCommandDescription;
- CommandOption configFile = listCommand.Option(
- "--configfile",
- Strings.Option_ConfigFile,
- CommandOptionType.SingleValue);
+ var trustedSignersCmd = new Command("trust", Strings.TrustCommandDescription);
- listCommand.HelpOption(XPlatUtility.HelpOption);
+ // --- list subcommand ---
+ var listCommand = new Command("list", Strings.TrustListCommandDescription);
+ {
+ var configFile = new Option("--configfile") { Description = Strings.Option_ConfigFile, Arity = ArgumentArity.ZeroOrOne };
+ var verbosity = CreateVerbosityOption();
- CommandOption verbosity = listCommand.VerbosityOption();
+ listCommand.Options.Add(configFile);
+ listCommand.Options.Add(verbosity);
- listCommand.OnExecute(async () =>
- {
- return await ExecuteCommand(TrustCommand.List, algorithm: null, allowUntrustedRootOption: false, owners: null, verbosity, configFile, getLogger, setLogLevel);
- });
- });
-
- trustedSignersCmd.Command("sync", (syncCommand) =>
+ listCommand.SetAction(async (parseResult, cancellationToken) =>
{
- syncCommand.Description = Strings.TrustSyncCommandDescription;
- CommandOption configFile = syncCommand.Option(
- "--configfile",
- Strings.Option_ConfigFile,
- CommandOptionType.SingleValue);
-
- syncCommand.HelpOption(XPlatUtility.HelpOption);
-
- CommandOption verbosity = syncCommand.VerbosityOption(); ;
+ return await ExecuteCommand(TrustCommand.List, algorithm: null, allowUntrustedRootOption: false, owners: null, parseResult.GetValue(verbosity), parseResult.GetValue(configFile), getLogger, setLogLevel);
+ });
+ }
+ trustedSignersCmd.Subcommands.Add(listCommand);
- CommandArgument name = syncCommand.Argument("",
- Strings.TrustedSignerNameExists);
+ // --- sync subcommand ---
+ var syncCommand = new Command("sync", Strings.TrustSyncCommandDescription);
+ {
+ var name = new Argument("NAME") { Description = Strings.TrustedSignerNameExists };
+ var configFile = new Option("--configfile") { Description = Strings.Option_ConfigFile, Arity = ArgumentArity.ZeroOrOne };
+ var verbosity = CreateVerbosityOption();
- syncCommand.OnExecute(async () =>
- {
- return await ExecuteCommand(TrustCommand.Sync, algorithm: null, allowUntrustedRootOption: false, owners: null, verbosity, configFile, getLogger, setLogLevel, name: name.Value);
- });
- });
+ syncCommand.Arguments.Add(name);
+ syncCommand.Options.Add(configFile);
+ syncCommand.Options.Add(verbosity);
- trustedSignersCmd.Command("remove", (syncCommand) =>
+ syncCommand.SetAction(async (parseResult, cancellationToken) =>
{
- syncCommand.Description = Strings.TrustRemoveCommandDescription;
- CommandOption configFile = syncCommand.Option(
- "--configfile",
- Strings.Option_ConfigFile,
- CommandOptionType.SingleValue);
-
- syncCommand.HelpOption(XPlatUtility.HelpOption);
+ return await ExecuteCommand(TrustCommand.Sync, algorithm: null, allowUntrustedRootOption: false, owners: null, parseResult.GetValue(verbosity), parseResult.GetValue(configFile), getLogger, setLogLevel, name: parseResult.GetValue(name));
+ });
+ }
+ trustedSignersCmd.Subcommands.Add(syncCommand);
- CommandOption verbosity = syncCommand.VerbosityOption();
+ // --- remove subcommand ---
+ var removeCommand = new Command("remove", Strings.TrustRemoveCommandDescription);
+ {
+ var name = new Argument("NAME") { Description = Strings.TrustedSignerNameToRemove };
+ var configFile = new Option("--configfile") { Description = Strings.Option_ConfigFile, Arity = ArgumentArity.ZeroOrOne };
+ var verbosity = CreateVerbosityOption();
- CommandArgument name = syncCommand.Argument("",
- Strings.TrustedSignerNameToRemove);
+ removeCommand.Arguments.Add(name);
+ removeCommand.Options.Add(configFile);
+ removeCommand.Options.Add(verbosity);
- syncCommand.OnExecute(async () =>
- {
- return await ExecuteCommand(TrustCommand.Remove, algorithm: null, allowUntrustedRootOption: false, owners: null, verbosity, configFile, getLogger, setLogLevel, name: name.Value);
- });
+ removeCommand.SetAction(async (parseResult, cancellationToken) =>
+ {
+ return await ExecuteCommand(TrustCommand.Remove, algorithm: null, allowUntrustedRootOption: false, owners: null, parseResult.GetValue(verbosity), parseResult.GetValue(configFile), getLogger, setLogLevel, name: parseResult.GetValue(name));
});
+ }
+ trustedSignersCmd.Subcommands.Add(removeCommand);
- trustedSignersCmd.Command("author", (authorCommand) =>
+ // --- author subcommand ---
+ var authorCommand = new Command("author", Strings.TrustAuthorCommandDescription);
+ {
+ var name = new Argument("NAME") { Description = Strings.TrustedSignerNameToAdd };
+ var package = new Argument("PACKAGE") { Description = Strings.TrustLocalSignedNupkgPath };
+ var allowUntrustedRootOption = new Option("--allow-untrusted-root") { Description = Strings.TrustCommandAllowUntrustedRoot, Arity = ArgumentArity.Zero };
+ var configFile = new Option("--configfile") { Description = Strings.Option_ConfigFile, Arity = ArgumentArity.ZeroOrOne };
+ var verbosity = CreateVerbosityOption();
+
+ authorCommand.Arguments.Add(name);
+ authorCommand.Arguments.Add(package);
+ authorCommand.Options.Add(allowUntrustedRootOption);
+ authorCommand.Options.Add(configFile);
+ authorCommand.Options.Add(verbosity);
+
+ authorCommand.SetAction(async (parseResult, cancellationToken) =>
{
- authorCommand.Description = Strings.TrustAuthorCommandDescription;
-
- CommandOption allowUntrustedRootOption = authorCommand.Option(
- "--allow-untrusted-root",
- Strings.TrustCommandAllowUntrustedRoot,
- CommandOptionType.NoValue);
-
- CommandOption configFile = authorCommand.Option(
- "--configfile",
- Strings.Option_ConfigFile,
- CommandOptionType.SingleValue);
-
- authorCommand.HelpOption(XPlatUtility.HelpOption);
-
- CommandOption verbosity = authorCommand.VerbosityOption();
-
- CommandArgument name = authorCommand.Argument("",
- Strings.TrustedSignerNameToAdd);
- CommandArgument package = authorCommand.Argument("",
- Strings.TrustLocalSignedNupkgPath);
-
- authorCommand.OnExecute(async () =>
- {
- return await ExecuteCommand(TrustCommand.Author, algorithm: null, allowUntrustedRootOption.HasValue(), owners: null, verbosity, configFile, getLogger, setLogLevel, name: name.Value, sourceUrl: null, packagePath: package.Value);
- });
+ return await ExecuteCommand(TrustCommand.Author, algorithm: null, parseResult.GetValue(allowUntrustedRootOption), owners: null, parseResult.GetValue(verbosity), parseResult.GetValue(configFile), getLogger, setLogLevel, name: parseResult.GetValue(name), sourceUrl: null, packagePath: parseResult.GetValue(package));
});
+ }
+ trustedSignersCmd.Subcommands.Add(authorCommand);
- trustedSignersCmd.Command("repository", (repositoryCommand) =>
+ // --- repository subcommand ---
+ var repositoryCommand = new Command("repository", Strings.TrustRepositoryCommandDescription);
+ {
+ var name = new Argument("NAME") { Description = Strings.TrustedSignerNameToAdd };
+ var package = new Argument("PACKAGE") { Description = Strings.TrustLocalSignedNupkgPath };
+ var allowUntrustedRootOption = new Option("--allow-untrusted-root") { Description = Strings.TrustCommandAllowUntrustedRoot, Arity = ArgumentArity.Zero };
+ var owners = new Option("--owners") { Description = Strings.TrustCommandOwners, Arity = ArgumentArity.ZeroOrOne };
+ var configFile = new Option("--configfile") { Description = Strings.Option_ConfigFile, Arity = ArgumentArity.ZeroOrOne };
+ var verbosity = CreateVerbosityOption();
+
+ repositoryCommand.Arguments.Add(name);
+ repositoryCommand.Arguments.Add(package);
+ repositoryCommand.Options.Add(allowUntrustedRootOption);
+ repositoryCommand.Options.Add(owners);
+ repositoryCommand.Options.Add(configFile);
+ repositoryCommand.Options.Add(verbosity);
+
+ repositoryCommand.SetAction(async (parseResult, cancellationToken) =>
{
- repositoryCommand.Description = Strings.TrustRepositoryCommandDescription;
-
- CommandOption allowUntrustedRootOption = repositoryCommand.Option(
- "--allow-untrusted-root",
- Strings.TrustCommandAllowUntrustedRoot,
- CommandOptionType.NoValue);
-
- CommandOption configFile = repositoryCommand.Option(
- "--configfile",
- Strings.Option_ConfigFile,
- CommandOptionType.SingleValue);
-
- repositoryCommand.HelpOption(XPlatUtility.HelpOption);
-
- CommandOption owners = repositoryCommand.Option(
- "--owners",
- Strings.TrustCommandOwners,
- CommandOptionType.SingleValue);
-
- CommandOption verbosity = repositoryCommand.VerbosityOption();
-
- CommandArgument name = repositoryCommand.Argument("",
- Strings.TrustedSignerNameToAdd);
- CommandArgument package = repositoryCommand.Argument("",
- Strings.TrustLocalSignedNupkgPath);
-
- repositoryCommand.OnExecute(async () =>
- {
- return await ExecuteCommand(TrustCommand.Repository, algorithm: null, allowUntrustedRootOption.HasValue(), owners: owners, verbosity, configFile, getLogger, setLogLevel, name: name.Value, sourceUrl: null, packagePath: package.Value);
- });
+ return await ExecuteCommand(TrustCommand.Repository, algorithm: null, parseResult.GetValue(allowUntrustedRootOption), owners: parseResult.GetValue(owners), parseResult.GetValue(verbosity), parseResult.GetValue(configFile), getLogger, setLogLevel, name: parseResult.GetValue(name), sourceUrl: null, packagePath: parseResult.GetValue(package));
});
+ }
+ trustedSignersCmd.Subcommands.Add(repositoryCommand);
- trustedSignersCmd.Command("certificate", (certificateCommand) =>
+ // --- certificate subcommand ---
+ var certificateCommand = new Command("certificate", Strings.TrustRepositoryCommandDescription);
+ {
+ var name = new Argument("NAME") { Description = Strings.TrustedCertificateSignerNameToAdd };
+ var fingerprint = new Argument("FINGERPRINT") { Description = Strings.TrustCertificateFingerprint };
+ var algorithm = new Option("--algorithm") { Description = Strings.TrustCommandAlgorithm, Arity = ArgumentArity.ZeroOrOne };
+ var allowUntrustedRootOption = new Option("--allow-untrusted-root") { Description = Strings.TrustCommandAllowUntrustedRoot, Arity = ArgumentArity.Zero };
+ var configFile = new Option("--configfile") { Description = Strings.Option_ConfigFile, Arity = ArgumentArity.ZeroOrOne };
+ var verbosity = CreateVerbosityOption();
+
+ certificateCommand.Arguments.Add(name);
+ certificateCommand.Arguments.Add(fingerprint);
+ certificateCommand.Options.Add(algorithm);
+ certificateCommand.Options.Add(allowUntrustedRootOption);
+ certificateCommand.Options.Add(configFile);
+ certificateCommand.Options.Add(verbosity);
+
+ certificateCommand.SetAction(async (parseResult, cancellationToken) =>
{
- certificateCommand.Description = Strings.TrustRepositoryCommandDescription;
-
- CommandOption algorithm = certificateCommand.Option(
- "--algorithm",
- Strings.TrustCommandAlgorithm,
- CommandOptionType.SingleValue);
-
- CommandOption allowUntrustedRootOption = certificateCommand.Option(
- "--allow-untrusted-root",
- Strings.TrustCommandAllowUntrustedRoot,
- CommandOptionType.NoValue);
-
- CommandOption configFile = certificateCommand.Option(
- "--configfile",
- Strings.Option_ConfigFile,
- CommandOptionType.SingleValue);
-
- certificateCommand.HelpOption(XPlatUtility.HelpOption);
-
- CommandOption verbosity = certificateCommand.VerbosityOption();
-
- CommandArgument name = certificateCommand.Argument("",
- Strings.TrustedCertificateSignerNameToAdd);
- CommandArgument fingerprint = certificateCommand.Argument("",
- Strings.TrustCertificateFingerprint);
-
- certificateCommand.OnExecute(async () =>
- {
- return await ExecuteCommand(TrustCommand.Certificate, algorithm, allowUntrustedRootOption.HasValue(), owners: null, verbosity, configFile, getLogger, setLogLevel, name: name.Value, sourceUrl: null, packagePath: null, fingerprint: fingerprint.Value);
- });
+ return await ExecuteCommand(TrustCommand.Certificate, algorithm: parseResult.GetValue(algorithm), parseResult.GetValue(allowUntrustedRootOption), owners: null, parseResult.GetValue(verbosity), parseResult.GetValue(configFile), getLogger, setLogLevel, name: parseResult.GetValue(name), sourceUrl: null, packagePath: null, fingerprint: parseResult.GetValue(fingerprint));
});
+ }
+ trustedSignersCmd.Subcommands.Add(certificateCommand);
- trustedSignersCmd.Command("source", (sourceCommand) =>
+ // --- source subcommand ---
+ var sourceCommand = new Command("source", Strings.TrustSourceCommandDescription);
+ {
+ var name = new Argument("NAME") { Description = Strings.TrustSourceSignerName };
+ var sourceUrl = new Option("--source-url") { Description = Strings.TrustSourceUrl, Arity = ArgumentArity.ZeroOrOne };
+ var owners = new Option("--owners") { Description = Strings.TrustCommandOwners, Arity = ArgumentArity.ZeroOrOne };
+ var configFile = new Option("--configfile") { Description = Strings.Option_ConfigFile, Arity = ArgumentArity.ZeroOrOne };
+ var verbosity = CreateVerbosityOption();
+
+ sourceCommand.Arguments.Add(name);
+ sourceCommand.Options.Add(sourceUrl);
+ sourceCommand.Options.Add(owners);
+ sourceCommand.Options.Add(configFile);
+ sourceCommand.Options.Add(verbosity);
+
+ sourceCommand.SetAction(async (parseResult, cancellationToken) =>
{
- sourceCommand.Description = Strings.TrustSourceCommandDescription;
-
- CommandOption configFile = sourceCommand.Option(
- "--configfile",
- Strings.Option_ConfigFile,
- CommandOptionType.SingleValue);
-
- sourceCommand.HelpOption(XPlatUtility.HelpOption);
-
- CommandOption owners = sourceCommand.Option(
- "--owners",
- Strings.TrustCommandOwners,
- CommandOptionType.SingleValue);
-
- CommandOption sourceUrl = sourceCommand.Option(
- "--source-url",
- Strings.TrustSourceUrl,
- CommandOptionType.SingleValue);
-
- CommandOption verbosity = sourceCommand.VerbosityOption();
-
- CommandArgument name = sourceCommand.Argument("",
- Strings.TrustSourceSignerName);
-
- sourceCommand.OnExecute(async () =>
- {
- return await ExecuteCommand(TrustCommand.Source, algorithm: null, allowUntrustedRootOption: false, owners, verbosity, configFile, getLogger, setLogLevel, name: name.Value, sourceUrl: sourceUrl.Value());
- });
+ return await ExecuteCommand(TrustCommand.Source, algorithm: null, allowUntrustedRootOption: false, owners: parseResult.GetValue(owners), parseResult.GetValue(verbosity), parseResult.GetValue(configFile), getLogger, setLogLevel, name: parseResult.GetValue(name), sourceUrl: parseResult.GetValue(sourceUrl));
});
+ }
+ trustedSignersCmd.Subcommands.Add(sourceCommand);
- // Main command
- trustedSignersCmd.Description = Strings.TrustCommandDescription;
- CommandOption mainConfigFile = trustedSignersCmd.Option(
- "--configfile",
- Strings.Option_ConfigFile,
- CommandOptionType.SingleValue);
-
- trustedSignersCmd.HelpOption(XPlatUtility.HelpOption);
+ // --- Main command (defaults to list behavior) ---
+ var mainConfigFile = new Option("--configfile") { Description = Strings.Option_ConfigFile, Arity = ArgumentArity.ZeroOrOne };
+ var mainVerbosity = CreateVerbosityOption();
- CommandOption mainVerbosity = trustedSignersCmd.VerbosityOption();
+ trustedSignersCmd.Options.Add(mainConfigFile);
+ trustedSignersCmd.Options.Add(mainVerbosity);
- trustedSignersCmd.OnExecute(async () =>
- {
- // If no command specified then default to List command.
- return await ExecuteCommand(TrustCommand.List, algorithm: null, allowUntrustedRootOption: false, owners: null, mainVerbosity, mainConfigFile, getLogger, setLogLevel);
- });
+ trustedSignersCmd.SetAction(async (parseResult, cancellationToken) =>
+ {
+ // If no command specified then default to List command.
+ return await ExecuteCommand(TrustCommand.List, algorithm: null, allowUntrustedRootOption: false, owners: null, parseResult.GetValue(mainVerbosity), parseResult.GetValue(mainConfigFile), getLogger, setLogLevel);
});
+
+ parent.Subcommands.Add(trustedSignersCmd);
}
private static async Task ExecuteCommand(TrustCommand action,
- CommandOption algorithm,
+ string algorithm,
bool allowUntrustedRootOption,
- CommandOption owners,
- CommandOption verbosity,
- CommandOption configFile,
- Func getLogger,
+ string owners,
+ string verbosity,
+ string configFile,
+ Func getLogger,
Action setLogLevel,
string name = null,
string sourceUrl = null,
@@ -249,7 +200,7 @@ private static async Task ExecuteCommand(TrustCommand action,
try
{
- ISettings settings = XPlatUtility.ProcessConfigFile(configFile.Value());
+ ISettings settings = XPlatUtility.ProcessConfigFile(configFile);
var trustedSignersArgs = new TrustedSignersArgs()
{
@@ -258,15 +209,15 @@ private static async Task ExecuteCommand(TrustCommand action,
Name = name,
ServiceIndex = sourceUrl,
CertificateFingerprint = fingerprint,
- FingerprintAlgorithm = algorithm?.Value(),
+ FingerprintAlgorithm = algorithm,
AllowUntrustedRoot = allowUntrustedRootOption,
Author = action == TrustCommand.Author,
Repository = action == TrustCommand.Repository,
- Owners = CommandLineUtility.SplitAndJoinAcrossMultipleValues(owners?.Values),
+ Owners = CommandLineUtility.SplitAndJoinAcrossMultipleValues(owners != null ? new[] { owners } : null),
Logger = logger
};
- setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity.Value()));
+ setLogLevel(XPlatUtility.MSBuildVerbosityToNuGetLogLevel(verbosity));
// Add is the only action which does certificate chain building.
if (trustedSignersArgs.Action == TrustedSignersAction.Add)
@@ -322,12 +273,13 @@ private static async Task ExecuteCommand(TrustCommand action,
}
}
- private static CommandOption VerbosityOption(this CommandLineApplication command)
+ private static Option