/
Program.cs
295 lines (255 loc) · 11 KB
/
Program.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// 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.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Reflection;
using Microsoft.Extensions.CommandLineUtils;
using NuGet.Commands;
using NuGet.Common;
using System.CommandLine;
using System.Threading;
using System.CommandLine.Parsing;
namespace NuGet.CommandLine.XPlat
{
internal class Program
{
#if DEBUG
private const string DebugOption = "--debug";
#endif
private const string DotnetNuGetAppName = "dotnet nuget";
private const string DotnetPackageAppName = "NuGet.CommandLine.XPlat.dll package";
private const int DotnetPackageSearchTimeOut = 15;
public static int Main(string[] args)
{
var log = new CommandOutputLogger(LogLevel.Information);
return MainInternal(args, log);
}
/// <summary>
/// Internal Main. This is used for testing.
/// </summary>
public static int MainInternal(string[] args, CommandOutputLogger log)
{
#if DEBUG
// Uncomment the following when debugging. Also uncomment the PackageReference for Microsoft.Build.Locator.
/*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.
}*/
var debugNuGetXPlat = Environment.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();
Debugger.Launch();
}
#endif
// Optionally disable localization.
if (args.Any(arg => string.Equals(arg, CommandConstants.ForceEnglishOutputOption, StringComparison.OrdinalIgnoreCase)))
{
CultureUtility.DisableLocalization();
}
else
{
UILanguageOverride.Setup(log);
}
log.LogDebug(string.Format(CultureInfo.CurrentCulture, Strings.Debug_CurrentUICulture, CultureInfo.DefaultThreadCurrentUICulture));
NuGet.Common.Migrations.MigrationRunner.Run();
if ((args.Count() >= 2 && args[0] == "package" && args[1] == "search") || (args.Any() && args[0] == "config"))
{
// We are executing command `dotnet package search`
Func<ILoggerWithColor> getHidePrefixLogger = () =>
{
log.HidePrefixForInfoAndMinimal = true;
return log;
};
CliCommand rootCommand = new CliCommand("package");
PackageSearchCommand.Register(rootCommand, getHidePrefixLogger);
ConfigCommand.Register(rootCommand, getHidePrefixLogger);
CancellationTokenSource tokenSource = new CancellationTokenSource();
tokenSource.CancelAfter(TimeSpan.FromMinutes(DotnetPackageSearchTimeOut));
int exitCodeValue = 0;
CliConfiguration config = new(rootCommand);
ParseResult parseResult = rootCommand.Parse(args, config);
try
{
exitCodeValue = parseResult.Invoke();
}
catch (Exception ex)
{
LogException(ex, log);
var tokenList = parseResult.Tokens.TakeWhile(token => token.Type == CliTokenType.Argument || token.Type == CliTokenType.Command || token.Type == CliTokenType.Directive).Select(t => t.Value).ToList();
tokenList.Add("-h");
rootCommand.Parse(tokenList).Invoke();
exitCodeValue = 1;
}
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());
exitCode = 1;
ShowBestHelp(app, args);
}
}
// Limit the exit code range to 0-255 to support POSIX
if (exitCode < 0 || exitCode > 255)
{
exitCode = 1;
}
return exitCode;
}
internal static void LogException(Exception e, ILogger log)
{
// 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());
}
private static CommandLineApplication InitializeApp(string[] args, CommandOutputLogger log)
{
// Many commands don't want prefixes output. Use this func instead of () => log to set the HidePrefix property first.
Func<ILoggerWithColor> getHidePrefixLogger = () =>
{
log.HidePrefixForInfoAndMinimal = true;
return log;
};
// Allow commands to set the NuGet log level
Action<LogLevel> setLogLevel = (logLevel) => log.VerbosityLevel = logLevel;
var app = new CommandLineApplication();
if (args.Any() && args[0] == "package")
{
// "dotnet * package" commands
app.Name = DotnetPackageAppName;
AddPackageReferenceCommand.Register(app, () => log, () => new AddPackageReferenceCommandRunner());
RemovePackageReferenceCommand.Register(app, () => log, () => new RemovePackageReferenceCommandRunner());
ListPackageCommand.Register(app, getHidePrefixLogger, setLogLevel, () => new ListPackageCommandRunner());
}
else
{
// "dotnet nuget *" commands
app.Name = DotnetNuGetAppName;
CommandParsers.Register(app, getHidePrefixLogger);
DeleteCommand.Register(app, getHidePrefixLogger);
PushCommand.Register(app, getHidePrefixLogger);
LocalsCommand.Register(app, getHidePrefixLogger);
VerifyCommand.Register(app, getHidePrefixLogger, setLogLevel, () => new VerifyCommandRunner());
TrustedSignersCommand.Register(app, getHidePrefixLogger, setLogLevel);
SignCommand.Register(app, getHidePrefixLogger, setLogLevel, () => new SignCommandRunner());
}
app.FullName = Strings.App_FullName;
app.HelpOption(XPlatUtility.HelpOption);
app.VersionOption("--version", typeof(Program).GetTypeInfo().Assembly.GetName().Version.ToString());
return app;
}
private static void ShowBestHelp(CommandLineApplication app, string[] args)
{
CommandLineApplication lastCommand = null;
List<CommandLineApplication> commands = app.Commands;
// tunnel down into the args, and show the best help possible.
foreach (string arg in args)
{
foreach (CommandLineApplication command in commands)
{
if (arg == command.Name)
{
lastCommand = command;
commands = command.Commands;
break;
}
}
}
if (lastCommand != null)
{
lastCommand.ShowHelp();
}
else
{
app.ShowHelp();
}
}
}
}