-
Notifications
You must be signed in to change notification settings - Fork 753
Expand file tree
/
Copy pathProgram.cs
More file actions
358 lines (310 loc) · 13.1 KB
/
Program.cs
File metadata and controls
358 lines (310 loc) · 13.1 KB
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
// 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.CommandLine;
using System.Globalization;
using System.Linq;
using System.Threading;
using Microsoft.Extensions.CommandLineUtils;
using NuGet.Commands;
using NuGet.Common;
#if DEBUG
using NuGet.CommandLine.XPlat.Commands.Package.Update;
#endif
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, EnvironmentVariableWrapper.Instance);
}
/// <summary>
/// Internal Main. This is used for testing.
/// </summary>
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);
#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;
}
private static bool IsSystemCommandLineParsedCommand(string[] args)
{
if (args.Length == 0)
{
return false;
}
string arg0 = args[0];
if (arg0 == "config" || arg0 == "why")
{
return true;
}
if (args.Length >= 2 && arg0 == "package")
{
string arg1 = args[1];
#if DEBUG
if (arg1 == "update")
{
return true;
}
#endif
if (arg1 == "search")
{
return true;
}
}
return false;
}
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());
// The commands below are implemented with System.CommandLine, and are here only for `dotnet nuget --help`
ConfigCommand.Register(app);
Commands.Why.WhyCommand.Register(app);
}
app.FullName = Strings.App_FullName;
app.HelpOption(XPlatUtility.HelpOption);
app.VersionOption("--version", typeof(Program).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();
}
}
}
}