in src/NuGet.Core/NuGet.CommandLine.XPlat/Program.cs [41:239]
public static int MainInternal(string[] args, CommandOutputLogger log, IEnvironmentVariableReader environmentVariableReader)
{
#if USEMSBUILDLOCATOR
try
{
// .NET JIT compiles one method at a time. If this method calls `MSBuildLocator` directly, the
// try block is never entered if Microsoft.Build.Locator.dll can't be found. So, run it in a
// lambda function to ensure we're in the try block. C# IIFE!
((Action)(() => Microsoft.Build.Locator.MSBuildLocator.RegisterDefaults()))();
}
catch
{
// MSBuildLocator is used only to enable Visual Studio debugging.
// It's not needed when using a patched dotnet sdk, so it doesn't matter if it fails.
}
#endif
#if DEBUG
var debugNuGetXPlat = environmentVariableReader.GetEnvironmentVariable("DEBUG_NUGET_XPLAT");
if (args.Contains(DebugOption) || string.Equals(bool.TrueString, debugNuGetXPlat, StringComparison.OrdinalIgnoreCase))
{
args = args.Where(arg => !StringComparer.OrdinalIgnoreCase.Equals(arg, DebugOption)).ToArray();
System.Diagnostics.Debugger.Launch();
}
#endif
// Optionally disable localization.
if (args.Any(arg => string.Equals(arg, CommandConstants.ForceEnglishOutputOption, StringComparison.OrdinalIgnoreCase)))
{
CultureUtility.DisableLocalization();
}
else
{
UILanguageOverride.Setup(log, environmentVariableReader);
}
log.LogDebug(string.Format(CultureInfo.CurrentCulture, Strings.Debug_CurrentUICulture, CultureInfo.DefaultThreadCurrentUICulture));
NuGet.Common.Migrations.MigrationRunner.Run();
// TODO: Migrating from Microsoft.Extensions.CommandLineUtils.CommandLineApplication to System.Commandline.Command
// If we are looking to add further commands here, we should also look to redesign this parsing logic at that time
// See related issues:
// - https://github.com/NuGet/Home/issues/11996
// - https://github.com/NuGet/Home/issues/11997
// - https://github.com/NuGet/Home/issues/13089
if (IsSystemCommandLineParsedCommand(args))
{
Func<ILoggerWithColor> getHidePrefixLogger = () =>
{
log.HidePrefixForInfoAndMinimal = true;
return log;
};
RootCommand rootCommand = new RootCommand();
// Commands called directly from the SDK CLI will use the SDK's common interactive option.
Option<bool> interactiveOption = new Option<bool>("--interactive");
interactiveOption.Description = Strings.AddPkg_InteractiveDescription;
interactiveOption.DefaultValueFactory = _ => Console.IsOutputRedirected;
if (args[0] == "package")
{
var packageCommand = new Command("package");
rootCommand.Subcommands.Add(packageCommand);
PackageSearchCommand.Register(packageCommand, getHidePrefixLogger);
#if DEBUG
PackageUpdateCommand.Register(packageCommand, interactiveOption);
PackageDownloadCommand.Register(packageCommand, interactiveOption);
#endif
}
else
{
var nugetCommand = new Command("nuget");
rootCommand.Subcommands.Add(nugetCommand);
ConfigCommand.Register(nugetCommand, getHidePrefixLogger);
ConfigCommand.Register(rootCommand, getHidePrefixLogger);
Commands.Why.WhyCommand.Register(nugetCommand, getHidePrefixLogger);
Commands.Why.WhyCommand.Register(rootCommand, getHidePrefixLogger);
}
CancellationTokenSource tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(TimeSpan.FromMinutes(DotnetPackageSearchTimeOut));
int exitCodeValue = 0;
ParseResult parseResult = rootCommand.Parse(args);
try
{
exitCodeValue = parseResult.Invoke();
}
catch (Exception ex)
{
LogException(ex, log);
exitCodeValue = ExitCodes.Error;
}
return exitCodeValue;
}
var app = InitializeApp(args, log);
// Remove the correct item in array for "package" commands. Only do this when "add package", "remove package", etc... are being run.
if (app.Name == DotnetPackageAppName)
{
// package add ...
args[0] = null;
args = args
.Where(e => e != null)
.ToArray();
}
NetworkProtocolUtility.SetConnectionLimit();
XPlatUtility.SetUserAgent();
app.OnExecute(() =>
{
app.ShowHelp();
return 0;
});
log.LogVerbose(string.Format(CultureInfo.CurrentCulture, Strings.OutputNuGetVersion, app.FullName, app.LongVersionGetter()));
int exitCode = 0;
try
{
exitCode = app.Execute(args);
}
catch (Exception e)
{
bool handled = false;
string verb = null;
if (args.Length > 1)
{
// Redirect users nicely if they do 'dotnet nuget sources add' or 'dotnet nuget add sources'
if (StringComparer.OrdinalIgnoreCase.Compare(args[0], "sources") == 0)
{
verb = args[1];
}
else if (StringComparer.OrdinalIgnoreCase.Compare(args[1], "sources") == 0)
{
verb = args[0];
}
if (verb != null)
{
switch (verb.ToLowerInvariant())
{
case "add":
case "remove":
case "update":
case "enable":
case "disable":
case "list":
log.LogMinimal(string.Format(CultureInfo.CurrentCulture,
Strings.Sources_Redirect, $"dotnet nuget {verb} source"));
handled = true;
break;
default:
break;
}
}
}
if (!handled)
{
// Log the error
if (ExceptionLogger.Instance.ShowStack)
{
log.LogError(e.ToString());
}
else
{
log.LogError(ExceptionUtilities.DisplayMessage(e));
}
// Log the stack trace as verbose output.
log.LogVerbose(e.ToString());
if (e is CommandParsingException)
{
ShowBestHelp(app, args);
}
exitCode = 1;
}
}
// Limit the exit code range to 0-255 to support POSIX
if (exitCode < 0 || exitCode > 255)
{
exitCode = 1;
}
return exitCode;
}